playlists.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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. * Adds a song to a playlist
  196. *
  197. * @param {object} payload - object that contains the payload
  198. * @param {string} payload.playlistId - the playlist id
  199. * @param {string} payload.song - the song
  200. * @returns {Promise} - returns promise (reject, resolve)
  201. */
  202. ADD_SONG_TO_PLAYLIST(payload) {
  203. return new Promise((resolve, reject) => {
  204. const song = {
  205. _id: payload.song._id,
  206. songId: payload.song.songId,
  207. title: payload.song.title,
  208. duration: payload.song.duration
  209. };
  210. PlaylistsModule.playlistModel.updateOne(
  211. { _id: payload.playlistId },
  212. { $push: { songs: song } },
  213. { runValidators: true },
  214. err => {
  215. if (err) reject(new Error(err));
  216. else {
  217. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  218. .then(() => resolve())
  219. .catch(err => {
  220. reject(new Error(err));
  221. });
  222. }
  223. }
  224. );
  225. });
  226. }
  227. /**
  228. * Deletes a song from a playlist based on the songId
  229. *
  230. * @param {object} payload - object that contains the payload
  231. * @param {string} payload.playlistId - the playlist id
  232. * @param {string} payload.songId - the songId
  233. * @returns {Promise} - returns promise (reject, resolve)
  234. */
  235. DELETE_SONG_FROM_PLAYLIST_BY_SONGID(payload) {
  236. return new Promise((resolve, reject) => {
  237. PlaylistsModule.playlistModel.updateOne(
  238. { _id: payload.playlistId },
  239. { $pull: { songs: { songId: payload.songId } } },
  240. err => {
  241. if (err) reject(new Error(err));
  242. else {
  243. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  244. .then(() => resolve())
  245. .catch(err => {
  246. reject(new Error(err));
  247. });
  248. }
  249. }
  250. );
  251. });
  252. }
  253. /**
  254. * Fills a genre playlist with songs
  255. *
  256. * @param {object} payload - object that contains the payload
  257. * @param {string} payload.genre - the genre
  258. * @returns {Promise} - returns promise (reject, resolve)
  259. */
  260. AUTOFILL_GENRE_PLAYLIST(payload) {
  261. return new Promise((resolve, reject) => {
  262. async.waterfall(
  263. [
  264. next => {
  265. PlaylistsModule.runJob(
  266. "GET_GENRE_PLAYLIST",
  267. { genre: payload.genre.toLowerCase(), includeSongs: true },
  268. this
  269. )
  270. .then(response => {
  271. next(null, { playlist: response.playlist });
  272. })
  273. .catch(err => {
  274. if (err.message === "Playlist not found") {
  275. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)
  276. .then(playlistId => {
  277. next(null, { playlist: { _id: playlistId, songs: [] } });
  278. })
  279. .catch(err => {
  280. next(err);
  281. });
  282. } else next(err);
  283. });
  284. },
  285. (data, next) => {
  286. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)
  287. .then(response => {
  288. data.songs = response.songs;
  289. next(null, data);
  290. })
  291. .catch(err => {
  292. console.log(err);
  293. next(err);
  294. });
  295. },
  296. (data, next) => {
  297. data.songsToDelete = [];
  298. data.songsToAdd = [];
  299. data.playlist.songs.forEach(playlistSong => {
  300. const found = data.songs.find(song => playlistSong.songId === song.songId);
  301. if (!found) data.songsToDelete.push(playlistSong);
  302. });
  303. data.songs.forEach(song => {
  304. const found = data.playlist.songs.find(playlistSong => song.songId === playlistSong.songId);
  305. if (!found) data.songsToAdd.push(song);
  306. });
  307. next(null, data);
  308. },
  309. (data, next) => {
  310. const promises = [];
  311. data.songsToAdd.forEach(song => {
  312. promises.push(
  313. PlaylistsModule.runJob(
  314. "ADD_SONG_TO_PLAYLIST",
  315. { playlistId: data.playlist._id, song },
  316. this
  317. )
  318. );
  319. });
  320. data.songsToDelete.forEach(song => {
  321. promises.push(
  322. PlaylistsModule.runJob(
  323. "DELETE_SONG_FROM_PLAYLIST_BY_SONGID",
  324. {
  325. playlistId: data.playlist._id,
  326. songId: song.songId
  327. },
  328. this
  329. )
  330. );
  331. });
  332. Promise.allSettled(promises)
  333. .then(() => {
  334. next();
  335. })
  336. .catch(err => {
  337. next(err);
  338. });
  339. }
  340. ],
  341. err => {
  342. if (err && err !== true) return reject(new Error(err));
  343. return resolve({});
  344. }
  345. );
  346. });
  347. }
  348. /**
  349. * Gets a orphaned station playlists
  350. *
  351. * @returns {Promise} - returns promise (reject, resolve)
  352. */
  353. GET_ORPHANED_STATION_PLAYLISTS() {
  354. return new Promise((resolve, reject) => {
  355. PlaylistsModule.playlistModel.find({ type: "station" }, { songs: false }, (err, playlists) => {
  356. if (err) reject(new Error(err));
  357. else {
  358. const orphanedPlaylists = [];
  359. async.eachLimit(
  360. playlists,
  361. 1,
  362. (playlist, next) => {
  363. StationsModule.runJob("GET_STATION", { stationId: playlist.createdFor }, this)
  364. .then(() => {
  365. next();
  366. })
  367. .catch(err => {
  368. if (err.message === "Station not found") {
  369. orphanedPlaylists.push(playlist);
  370. next();
  371. } else next(err);
  372. });
  373. },
  374. err => {
  375. if (err) reject(new Error(err));
  376. else resolve({ playlists: orphanedPlaylists });
  377. }
  378. );
  379. }
  380. });
  381. });
  382. }
  383. /**
  384. * Deletes all orphaned station playlists
  385. *
  386. * @returns {Promise} - returns promise (reject, resolve)
  387. */
  388. DELETE_ORPHANED_STATION_PLAYLISTS() {
  389. return new Promise((resolve, reject) => {
  390. PlaylistsModule.runJob("GET_ORPHANED_STATION_PLAYLISTS", {}, this)
  391. .then(response => {
  392. async.eachLimit(
  393. response.playlists,
  394. 1,
  395. (playlist, next) => {
  396. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  397. .then(() => {
  398. this.log("INFO", "Deleting orphaned station playlist");
  399. next();
  400. })
  401. .catch(err => {
  402. next(err);
  403. });
  404. },
  405. err => {
  406. if (err) reject(new Error(err));
  407. else resolve({});
  408. }
  409. );
  410. })
  411. .catch(err => {
  412. reject(new Error(err));
  413. });
  414. });
  415. }
  416. /**
  417. * Fills a station playlist with songs
  418. *
  419. * @param {object} payload - object that contains the payload
  420. * @param {string} payload.stationId - the station id
  421. * @returns {Promise} - returns promise (reject, resolve)
  422. */
  423. AUTOFILL_STATION_PLAYLIST(payload) {
  424. return new Promise((resolve, reject) => {
  425. async.waterfall(
  426. [
  427. next => {
  428. if (!payload.stationId) next("Please specify a station id");
  429. else next();
  430. },
  431. next => {
  432. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  433. .then(station => {
  434. next(null, station);
  435. })
  436. .catch(next);
  437. },
  438. (station, next) => {
  439. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: station.playlist2 }, this)
  440. .then(() => {
  441. next(null, station);
  442. })
  443. .catch(err => {
  444. next(err);
  445. });
  446. },
  447. (station, next) => {
  448. const includedPlaylists = [];
  449. async.eachLimit(
  450. station.includedPlaylists,
  451. 1,
  452. (playlistId, next) => {
  453. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  454. .then(playlist => {
  455. includedPlaylists.push(playlist);
  456. next();
  457. })
  458. .catch(next);
  459. },
  460. err => {
  461. next(err, station, includedPlaylists);
  462. }
  463. );
  464. },
  465. (station, includedPlaylists, next) => {
  466. const excludedPlaylists = [];
  467. async.eachLimit(
  468. station.excludedPlaylists,
  469. 1,
  470. (playlistId, next) => {
  471. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  472. .then(playlist => {
  473. excludedPlaylists.push(playlist);
  474. next();
  475. })
  476. .catch(next);
  477. },
  478. err => {
  479. next(err, station, includedPlaylists, excludedPlaylists);
  480. }
  481. );
  482. },
  483. (station, includedPlaylists, excludedPlaylists, next) => {
  484. const excludedSongs = excludedPlaylists
  485. .flatMap(excludedPlaylist => excludedPlaylist.songs)
  486. .reduce(
  487. (items, item) =>
  488. items.find(x => x.songId === item.songId) ? [...items] : [...items, item],
  489. []
  490. );
  491. const includedSongs = includedPlaylists
  492. .flatMap(includedPlaylist => includedPlaylist.songs)
  493. .reduce(
  494. (songs, song) =>
  495. songs.find(x => x.songId === song.songId) ? [...songs] : [...songs, song],
  496. []
  497. )
  498. .filter(song => !excludedSongs.find(x => x.songId === song.songId));
  499. next(null, station, includedSongs);
  500. },
  501. (station, includedSongs, next) => {
  502. PlaylistsModule.playlistModel.updateOne(
  503. { _id: station.playlist2 },
  504. { $set: { songs: includedSongs } },
  505. next
  506. );
  507. }
  508. ],
  509. err => {
  510. if (err && err !== true) return reject(new Error(err));
  511. return resolve({});
  512. }
  513. );
  514. });
  515. }
  516. /**
  517. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  518. *
  519. * @param {object} payload - object that contains the payload
  520. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  521. * @returns {Promise} - returns promise (reject, resolve)
  522. */
  523. GET_PLAYLIST(payload) {
  524. return new Promise((resolve, reject) =>
  525. async.waterfall(
  526. [
  527. next => {
  528. CacheModule.runJob("HGETALL", { table: "playlists" }, this)
  529. .then(playlists => next(null, playlists))
  530. .catch(next);
  531. },
  532. (playlists, next) => {
  533. if (!playlists) return next();
  534. const playlistIds = Object.keys(playlists);
  535. return async.each(
  536. playlistIds,
  537. (playlistId, next) => {
  538. PlaylistsModule.playlistModel.findOne({ _id: playlistId }, (err, playlist) => {
  539. if (err) next(err);
  540. else if (!playlist) {
  541. CacheModule.runJob(
  542. "HDEL",
  543. {
  544. table: "playlists",
  545. key: playlistId
  546. },
  547. this
  548. )
  549. .then(() => next())
  550. .catch(next);
  551. } else next();
  552. });
  553. },
  554. next
  555. );
  556. },
  557. next => {
  558. CacheModule.runJob(
  559. "HGET",
  560. {
  561. table: "playlists",
  562. key: payload.playlistId
  563. },
  564. this
  565. )
  566. .then(playlist => next(null, playlist))
  567. .catch(next);
  568. },
  569. (playlist, next) => {
  570. if (playlist) return next(true, playlist);
  571. return PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  572. },
  573. (playlist, next) => {
  574. if (playlist) {
  575. CacheModule.runJob(
  576. "HSET",
  577. {
  578. table: "playlists",
  579. key: payload.playlistId,
  580. value: playlist
  581. },
  582. this
  583. )
  584. .then(playlist => {
  585. next(null, playlist);
  586. })
  587. .catch(next);
  588. } else next("Playlist not found");
  589. }
  590. ],
  591. (err, playlist) => {
  592. if (err && err !== true) return reject(new Error(err));
  593. return resolve(playlist);
  594. }
  595. )
  596. );
  597. }
  598. /**
  599. * Gets a playlist from id from Mongo and updates the cache with it
  600. *
  601. * @param {object} payload - object that contains the payload
  602. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  603. * @returns {Promise} - returns promise (reject, resolve)
  604. */
  605. UPDATE_PLAYLIST(payload) {
  606. // playlistId, cb
  607. return new Promise((resolve, reject) =>
  608. async.waterfall(
  609. [
  610. next => {
  611. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  612. },
  613. (playlist, next) => {
  614. if (!playlist) {
  615. CacheModule.runJob("HDEL", {
  616. table: "playlists",
  617. key: payload.playlistId
  618. });
  619. return next("Playlist not found");
  620. }
  621. return CacheModule.runJob(
  622. "HSET",
  623. {
  624. table: "playlists",
  625. key: payload.playlistId,
  626. value: playlist
  627. },
  628. this
  629. )
  630. .then(playlist => {
  631. next(null, playlist);
  632. })
  633. .catch(next);
  634. }
  635. ],
  636. (err, playlist) => {
  637. if (err && err !== true) return reject(new Error(err));
  638. return resolve(playlist);
  639. }
  640. )
  641. );
  642. }
  643. /**
  644. * Deletes playlist from id from Mongo and cache
  645. *
  646. * @param {object} payload - object that contains the payload
  647. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  648. * @returns {Promise} - returns promise (reject, resolve)
  649. */
  650. DELETE_PLAYLIST(payload) {
  651. // playlistId, cb
  652. return new Promise((resolve, reject) =>
  653. async.waterfall(
  654. [
  655. next => {
  656. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  657. },
  658. (res, next) => {
  659. CacheModule.runJob(
  660. "HDEL",
  661. {
  662. table: "playlists",
  663. key: payload.playlistId
  664. },
  665. this
  666. )
  667. .then(() => next())
  668. .catch(next);
  669. }
  670. ],
  671. err => {
  672. if (err && err !== true) return reject(new Error(err));
  673. return resolve();
  674. }
  675. )
  676. );
  677. }
  678. }
  679. export default new _PlaylistsModule();