playlists.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. import async from "async";
  2. import CoreClass from "../core";
  3. let PlaylistsModule;
  4. let StationsModule;
  5. let SongsModule;
  6. let CacheModule;
  7. let DBModule;
  8. let UtilsModule;
  9. class _PlaylistsModule extends CoreClass {
  10. // eslint-disable-next-line require-jsdoc
  11. constructor() {
  12. super("playlists");
  13. PlaylistsModule = this;
  14. }
  15. /**
  16. * Initialises the playlists module
  17. *
  18. * @returns {Promise} - returns promise (reject, resolve)
  19. */
  20. async initialize() {
  21. this.setStage(1);
  22. StationsModule = this.moduleManager.modules.stations;
  23. CacheModule = this.moduleManager.modules.cache;
  24. DBModule = this.moduleManager.modules.db;
  25. UtilsModule = this.moduleManager.modules.utils;
  26. SongsModule = this.moduleManager.modules.songs;
  27. this.playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" });
  28. this.playlistSchemaCache = await CacheModule.runJob("GET_SCHEMA", { schemaName: "playlist" });
  29. this.setStage(2);
  30. return new Promise((resolve, reject) =>
  31. async.waterfall(
  32. [
  33. next => {
  34. this.setStage(3);
  35. CacheModule.runJob("HGETALL", { table: "playlists" })
  36. .then(playlists => {
  37. next(null, playlists);
  38. })
  39. .catch(next);
  40. },
  41. (playlists, next) => {
  42. this.setStage(4);
  43. if (!playlists) return next();
  44. const playlistIds = Object.keys(playlists);
  45. return async.each(
  46. playlistIds,
  47. (playlistId, next) => {
  48. PlaylistsModule.playlistModel.findOne({ _id: playlistId }, (err, playlist) => {
  49. if (err) next(err);
  50. else if (!playlist) {
  51. CacheModule.runJob("HDEL", {
  52. table: "playlists",
  53. key: playlistId
  54. })
  55. .then(() => next())
  56. .catch(next);
  57. } else next();
  58. });
  59. },
  60. next
  61. );
  62. },
  63. next => {
  64. this.setStage(5);
  65. PlaylistsModule.playlistModel.find({}, next);
  66. },
  67. (playlists, next) => {
  68. this.setStage(6);
  69. async.each(
  70. playlists,
  71. (playlist, cb) => {
  72. CacheModule.runJob("HSET", {
  73. table: "playlists",
  74. key: playlist._id,
  75. value: PlaylistsModule.playlistSchemaCache(playlist)
  76. })
  77. .then(() => cb())
  78. .catch(next);
  79. },
  80. next
  81. );
  82. }
  83. ],
  84. async err => {
  85. if (err) {
  86. const formattedErr = await UtilsModule.runJob("GET_ERROR", {
  87. error: err
  88. });
  89. reject(new Error(formattedErr));
  90. } else resolve();
  91. }
  92. )
  93. );
  94. }
  95. /**
  96. * Creates a playlist that is not generated or editable by a user e.g. liked songs playlist
  97. *
  98. * @param {object} payload - object that contains the payload
  99. * @param {string} payload.userId - the id of the user to create the playlist for
  100. * @param {string} payload.displayName - the display name of the playlist
  101. * @returns {Promise} - returns promise (reject, resolve)
  102. */
  103. CREATE_READ_ONLY_PLAYLIST(payload) {
  104. return new Promise((resolve, reject) => {
  105. PlaylistsModule.playlistModel.create(
  106. {
  107. isUserModifiable: false,
  108. displayName: payload.displayName,
  109. songs: [],
  110. createdBy: payload.userId,
  111. createdAt: Date.now(),
  112. createdFor: null,
  113. type: payload.type
  114. },
  115. (err, playlist) => {
  116. if (err) return reject(new Error(err));
  117. return resolve(playlist._id);
  118. }
  119. );
  120. });
  121. }
  122. /**
  123. * Creates a playlist that contains all songs of a specific genre
  124. *
  125. * @param {object} payload - object that contains the payload
  126. * @param {string} payload.genre - the genre
  127. * @returns {Promise} - returns promise (reject, resolve)
  128. */
  129. CREATE_GENRE_PLAYLIST(payload) {
  130. return new Promise((resolve, reject) => {
  131. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre: payload.genre.toLowerCase() }, this)
  132. .then(() => {
  133. reject(new Error("Playlist already exists"));
  134. })
  135. .catch(err => {
  136. if (err.message === "Playlist not found") {
  137. PlaylistsModule.playlistModel.create(
  138. {
  139. isUserModifiable: false,
  140. displayName: `Genre - ${payload.genre}`,
  141. songs: [],
  142. createdBy: "Musare",
  143. createdFor: `${payload.genre.toLowerCase()}`,
  144. createdAt: Date.now(),
  145. type: "genre"
  146. },
  147. (err, playlist) => {
  148. if (err) return reject(new Error(err));
  149. return resolve(playlist._id);
  150. }
  151. );
  152. } else reject(new Error(err));
  153. });
  154. });
  155. }
  156. /**
  157. * Gets all genre playlists
  158. *
  159. * @param {object} payload - object that contains the payload
  160. * @param {string} payload.includeSongs - include the songs
  161. * @returns {Promise} - returns promise (reject, resolve)
  162. */
  163. GET_ALL_GENRE_PLAYLISTS(payload) {
  164. return new Promise((resolve, reject) => {
  165. const includeObject = payload.includeSongs ? null : { songs: false };
  166. PlaylistsModule.playlistModel.find({ type: "genre" }, includeObject, (err, playlists) => {
  167. if (err) reject(new Error(err));
  168. else resolve({ playlists });
  169. });
  170. });
  171. }
  172. /**
  173. * Gets a genre playlist
  174. *
  175. * @param {object} payload - object that contains the payload
  176. * @param {string} payload.genre - the genre
  177. * @param {string} payload.includeSongs - include the songs
  178. * @returns {Promise} - returns promise (reject, resolve)
  179. */
  180. GET_GENRE_PLAYLIST(payload) {
  181. return new Promise((resolve, reject) => {
  182. const includeObject = payload.includeSongs ? null : { songs: false };
  183. PlaylistsModule.playlistModel.findOne(
  184. { type: "genre", createdFor: payload.genre },
  185. includeObject,
  186. (err, playlist) => {
  187. if (err) reject(new Error(err));
  188. else if (!playlist) reject(new Error("Playlist not found"));
  189. else resolve({ playlist });
  190. }
  191. );
  192. });
  193. }
  194. /**
  195. * Gets a station playlist
  196. *
  197. * @param {object} payload - object that contains the payload
  198. * @param {string} payload.staationId - the station id
  199. * @param {string} payload.includeSongs - include the songs
  200. * @returns {Promise} - returns promise (reject, resolve)
  201. */
  202. GET_STATION_PLAYLIST(payload) {
  203. return new Promise((resolve, reject) => {
  204. const includeObject = payload.includeSongs ? null : { songs: false };
  205. PlaylistsModule.playlistModel.findOne(
  206. { type: "station", createdFor: payload.stationId },
  207. includeObject,
  208. (err, playlist) => {
  209. if (err) reject(new Error(err));
  210. else if (!playlist) reject(new Error("Playlist not found"));
  211. else resolve({ playlist });
  212. }
  213. );
  214. });
  215. }
  216. /**
  217. * Adds a song to a playlist
  218. *
  219. * @param {object} payload - object that contains the payload
  220. * @param {string} payload.playlistId - the playlist id
  221. * @param {string} payload.song - the song
  222. * @returns {Promise} - returns promise (reject, resolve)
  223. */
  224. ADD_SONG_TO_PLAYLIST(payload) {
  225. return new Promise((resolve, reject) => {
  226. const song = {
  227. _id: payload.song._id,
  228. songId: payload.song.songId,
  229. title: payload.song.title,
  230. duration: payload.song.duration
  231. };
  232. PlaylistsModule.playlistModel.updateOne(
  233. { _id: payload.playlistId },
  234. { $push: { songs: song } },
  235. { runValidators: true },
  236. err => {
  237. if (err) reject(new Error(err));
  238. else {
  239. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  240. .then(() => resolve())
  241. .catch(err => {
  242. reject(new Error(err));
  243. });
  244. }
  245. }
  246. );
  247. });
  248. }
  249. /**
  250. * Deletes a song from a playlist based on the songId
  251. *
  252. * @param {object} payload - object that contains the payload
  253. * @param {string} payload.playlistId - the playlist id
  254. * @param {string} payload.songId - the songId
  255. * @returns {Promise} - returns promise (reject, resolve)
  256. */
  257. DELETE_SONG_FROM_PLAYLIST_BY_SONGID(payload) {
  258. return new Promise((resolve, reject) => {
  259. PlaylistsModule.playlistModel.updateOne(
  260. { _id: payload.playlistId },
  261. { $pull: { songs: { songId: payload.songId } } },
  262. err => {
  263. if (err) reject(new Error(err));
  264. else {
  265. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  266. .then(() => resolve())
  267. .catch(err => {
  268. reject(new Error(err));
  269. });
  270. }
  271. }
  272. );
  273. });
  274. }
  275. /**
  276. * Fills a genre playlist with songs
  277. *
  278. * @param {object} payload - object that contains the payload
  279. * @param {string} payload.genre - the genre
  280. * @returns {Promise} - returns promise (reject, resolve)
  281. */
  282. AUTOFILL_GENRE_PLAYLIST(payload) {
  283. return new Promise((resolve, reject) => {
  284. async.waterfall(
  285. [
  286. next => {
  287. PlaylistsModule.runJob(
  288. "GET_GENRE_PLAYLIST",
  289. { genre: payload.genre.toLowerCase(), includeSongs: true },
  290. this
  291. )
  292. .then(response => {
  293. next(null, { playlist: response.playlist });
  294. })
  295. .catch(err => {
  296. if (err.message === "Playlist not found") {
  297. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)
  298. .then(playlistId => {
  299. next(null, { playlist: { _id: playlistId, songs: [] } });
  300. })
  301. .catch(err => {
  302. next(err);
  303. });
  304. } else next(err);
  305. });
  306. },
  307. (data, next) => {
  308. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)
  309. .then(response => {
  310. data.songs = response.songs;
  311. next(null, data);
  312. })
  313. .catch(err => {
  314. console.log(err);
  315. next(err);
  316. });
  317. },
  318. (data, next) => {
  319. data.songsToDelete = [];
  320. data.songsToAdd = [];
  321. data.playlist.songs.forEach(playlistSong => {
  322. const found = data.songs.find(song => playlistSong.songId === song.songId);
  323. if (!found) data.songsToDelete.push(playlistSong);
  324. });
  325. data.songs.forEach(song => {
  326. const found = data.playlist.songs.find(playlistSong => song.songId === playlistSong.songId);
  327. if (!found) data.songsToAdd.push(song);
  328. });
  329. next(null, data);
  330. },
  331. (data, next) => {
  332. const promises = [];
  333. data.songsToAdd.forEach(song => {
  334. promises.push(
  335. PlaylistsModule.runJob(
  336. "ADD_SONG_TO_PLAYLIST",
  337. { playlistId: data.playlist._id, song },
  338. this
  339. )
  340. );
  341. });
  342. data.songsToDelete.forEach(song => {
  343. promises.push(
  344. PlaylistsModule.runJob(
  345. "DELETE_SONG_FROM_PLAYLIST_BY_SONGID",
  346. {
  347. playlistId: data.playlist._id,
  348. songId: song.songId
  349. },
  350. this
  351. )
  352. );
  353. });
  354. Promise.allSettled(promises)
  355. .then(() => {
  356. next(null, data.playlist._id);
  357. })
  358. .catch(err => {
  359. next(err);
  360. });
  361. },
  362. (playlistId, next) => {
  363. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  364. .then(response => {
  365. response.stationIds.forEach(stationId => {
  366. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  367. });
  368. })
  369. .catch();
  370. next();
  371. }
  372. ],
  373. err => {
  374. if (err && err !== true) return reject(new Error(err));
  375. return resolve({});
  376. }
  377. );
  378. });
  379. }
  380. /**
  381. * Gets a orphaned station playlists
  382. *
  383. * @returns {Promise} - returns promise (reject, resolve)
  384. */
  385. GET_ORPHANED_STATION_PLAYLISTS() {
  386. return new Promise((resolve, reject) => {
  387. PlaylistsModule.playlistModel.find({ type: "station" }, { songs: false }, (err, playlists) => {
  388. if (err) reject(new Error(err));
  389. else {
  390. const orphanedPlaylists = [];
  391. async.eachLimit(
  392. playlists,
  393. 1,
  394. (playlist, next) => {
  395. StationsModule.runJob("GET_STATION", { stationId: playlist.createdFor }, this)
  396. .then(station => {
  397. if (station.playlist2 !== playlist._id.toString()) {
  398. orphanedPlaylists.push(playlist);
  399. }
  400. next();
  401. })
  402. .catch(err => {
  403. if (err.message === "Station not found") {
  404. orphanedPlaylists.push(playlist);
  405. next();
  406. } else next(err);
  407. });
  408. },
  409. err => {
  410. if (err) reject(new Error(err));
  411. else resolve({ playlists: orphanedPlaylists });
  412. }
  413. );
  414. }
  415. });
  416. });
  417. }
  418. /**
  419. * Deletes all orphaned station playlists
  420. *
  421. * @returns {Promise} - returns promise (reject, resolve)
  422. */
  423. DELETE_ORPHANED_STATION_PLAYLISTS() {
  424. return new Promise((resolve, reject) => {
  425. PlaylistsModule.runJob("GET_ORPHANED_STATION_PLAYLISTS", {}, this)
  426. .then(response => {
  427. async.eachLimit(
  428. response.playlists,
  429. 1,
  430. (playlist, next) => {
  431. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  432. .then(() => {
  433. this.log("INFO", "Deleting orphaned station playlist");
  434. next();
  435. })
  436. .catch(err => {
  437. next(err);
  438. });
  439. },
  440. err => {
  441. if (err) reject(new Error(err));
  442. else resolve({});
  443. }
  444. );
  445. })
  446. .catch(err => {
  447. reject(new Error(err));
  448. });
  449. });
  450. }
  451. /**
  452. * Fills a station playlist with songs
  453. *
  454. * @param {object} payload - object that contains the payload
  455. * @param {string} payload.stationId - the station id
  456. * @returns {Promise} - returns promise (reject, resolve)
  457. */
  458. AUTOFILL_STATION_PLAYLIST(payload) {
  459. return new Promise((resolve, reject) => {
  460. async.waterfall(
  461. [
  462. next => {
  463. if (!payload.stationId) next("Please specify a station id");
  464. else next();
  465. },
  466. next => {
  467. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  468. .then(station => {
  469. next(null, station);
  470. })
  471. .catch(next);
  472. },
  473. (station, next) => {
  474. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: station.playlist2 }, this)
  475. .then(() => {
  476. next(null, station);
  477. })
  478. .catch(err => {
  479. next(err);
  480. });
  481. },
  482. (station, next) => {
  483. const includedPlaylists = [];
  484. async.eachLimit(
  485. station.includedPlaylists,
  486. 1,
  487. (playlistId, next) => {
  488. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  489. .then(playlist => {
  490. includedPlaylists.push(playlist);
  491. next();
  492. })
  493. .catch(next);
  494. },
  495. err => {
  496. next(err, station, includedPlaylists);
  497. }
  498. );
  499. },
  500. (station, includedPlaylists, next) => {
  501. const excludedPlaylists = [];
  502. async.eachLimit(
  503. station.excludedPlaylists,
  504. 1,
  505. (playlistId, next) => {
  506. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  507. .then(playlist => {
  508. excludedPlaylists.push(playlist);
  509. next();
  510. })
  511. .catch(next);
  512. },
  513. err => {
  514. next(err, station, includedPlaylists, excludedPlaylists);
  515. }
  516. );
  517. },
  518. (station, includedPlaylists, excludedPlaylists, next) => {
  519. const excludedSongs = excludedPlaylists
  520. .flatMap(excludedPlaylist => excludedPlaylist.songs)
  521. .reduce(
  522. (items, item) =>
  523. items.find(x => x.songId === item.songId) ? [...items] : [...items, item],
  524. []
  525. );
  526. const includedSongs = includedPlaylists
  527. .flatMap(includedPlaylist => includedPlaylist.songs)
  528. .reduce(
  529. (songs, song) =>
  530. songs.find(x => x.songId === song.songId) ? [...songs] : [...songs, song],
  531. []
  532. )
  533. .filter(song => !excludedSongs.find(x => x.songId === song.songId));
  534. next(null, station, includedSongs);
  535. },
  536. (station, includedSongs, next) => {
  537. PlaylistsModule.playlistModel.updateOne(
  538. { _id: station.playlist2 },
  539. { $set: { songs: includedSongs } },
  540. next
  541. );
  542. }
  543. ],
  544. err => {
  545. if (err && err !== true) return reject(new Error(err));
  546. return resolve({});
  547. }
  548. );
  549. });
  550. }
  551. /**
  552. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  553. *
  554. * @param {object} payload - object that contains the payload
  555. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  556. * @returns {Promise} - returns promise (reject, resolve)
  557. */
  558. GET_PLAYLIST(payload) {
  559. return new Promise((resolve, reject) =>
  560. async.waterfall(
  561. [
  562. next => {
  563. CacheModule.runJob("HGETALL", { table: "playlists" }, this)
  564. .then(playlists => next(null, playlists))
  565. .catch(next);
  566. },
  567. (playlists, next) => {
  568. if (!playlists) return next();
  569. const playlistIds = Object.keys(playlists);
  570. return async.each(
  571. playlistIds,
  572. (playlistId, next) => {
  573. PlaylistsModule.playlistModel.findOne({ _id: playlistId }, (err, playlist) => {
  574. if (err) next(err);
  575. else if (!playlist) {
  576. CacheModule.runJob(
  577. "HDEL",
  578. {
  579. table: "playlists",
  580. key: playlistId
  581. },
  582. this
  583. )
  584. .then(() => next())
  585. .catch(next);
  586. } else next();
  587. });
  588. },
  589. next
  590. );
  591. },
  592. next => {
  593. CacheModule.runJob(
  594. "HGET",
  595. {
  596. table: "playlists",
  597. key: payload.playlistId
  598. },
  599. this
  600. )
  601. .then(playlist => next(null, playlist))
  602. .catch(next);
  603. },
  604. (playlist, next) => {
  605. if (playlist) return next(true, playlist);
  606. return PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  607. },
  608. (playlist, next) => {
  609. if (playlist) {
  610. CacheModule.runJob(
  611. "HSET",
  612. {
  613. table: "playlists",
  614. key: payload.playlistId,
  615. value: playlist
  616. },
  617. this
  618. )
  619. .then(playlist => {
  620. next(null, playlist);
  621. })
  622. .catch(next);
  623. } else next("Playlist not found");
  624. }
  625. ],
  626. (err, playlist) => {
  627. if (err && err !== true) return reject(new Error(err));
  628. return resolve(playlist);
  629. }
  630. )
  631. );
  632. }
  633. /**
  634. * Gets a playlist from id from Mongo and updates the cache with it
  635. *
  636. * @param {object} payload - object that contains the payload
  637. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  638. * @returns {Promise} - returns promise (reject, resolve)
  639. */
  640. UPDATE_PLAYLIST(payload) {
  641. // playlistId, cb
  642. return new Promise((resolve, reject) =>
  643. async.waterfall(
  644. [
  645. next => {
  646. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  647. },
  648. (playlist, next) => {
  649. if (!playlist) {
  650. CacheModule.runJob("HDEL", {
  651. table: "playlists",
  652. key: payload.playlistId
  653. });
  654. return next("Playlist not found");
  655. }
  656. return CacheModule.runJob(
  657. "HSET",
  658. {
  659. table: "playlists",
  660. key: payload.playlistId,
  661. value: playlist
  662. },
  663. this
  664. )
  665. .then(playlist => {
  666. next(null, playlist);
  667. })
  668. .catch(next);
  669. }
  670. ],
  671. (err, playlist) => {
  672. if (err && err !== true) return reject(new Error(err));
  673. return resolve(playlist);
  674. }
  675. )
  676. );
  677. }
  678. /**
  679. * Deletes playlist from id from Mongo and cache
  680. *
  681. * @param {object} payload - object that contains the payload
  682. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  683. * @returns {Promise} - returns promise (reject, resolve)
  684. */
  685. DELETE_PLAYLIST(payload) {
  686. // playlistId, cb
  687. return new Promise((resolve, reject) =>
  688. async.waterfall(
  689. [
  690. next => {
  691. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  692. },
  693. (res, next) => {
  694. CacheModule.runJob(
  695. "HDEL",
  696. {
  697. table: "playlists",
  698. key: payload.playlistId
  699. },
  700. this
  701. )
  702. .then(() => next())
  703. .catch(next);
  704. }
  705. ],
  706. err => {
  707. if (err && err !== true) return reject(new Error(err));
  708. return resolve();
  709. }
  710. )
  711. );
  712. }
  713. }
  714. export default new _PlaylistsModule();