playlists.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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(null, data.playlist._id);
  335. })
  336. .catch(err => {
  337. next(err);
  338. });
  339. },
  340. (playlistId, next) => {
  341. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  342. .then(response => {
  343. response.stationIds.forEach(stationId => {
  344. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId })
  345. .then()
  346. .catch();
  347. });
  348. })
  349. .catch();
  350. next();
  351. }
  352. ],
  353. err => {
  354. if (err && err !== true) return reject(new Error(err));
  355. return resolve({});
  356. }
  357. );
  358. });
  359. }
  360. /**
  361. * Gets a orphaned station playlists
  362. *
  363. * @returns {Promise} - returns promise (reject, resolve)
  364. */
  365. GET_ORPHANED_STATION_PLAYLISTS() {
  366. return new Promise((resolve, reject) => {
  367. PlaylistsModule.playlistModel.find({ type: "station" }, { songs: false }, (err, playlists) => {
  368. if (err) reject(new Error(err));
  369. else {
  370. const orphanedPlaylists = [];
  371. async.eachLimit(
  372. playlists,
  373. 1,
  374. (playlist, next) => {
  375. StationsModule.runJob("GET_STATION", { stationId: playlist.createdFor }, this)
  376. .then(() => {
  377. next();
  378. })
  379. .catch(err => {
  380. if (err.message === "Station not found") {
  381. orphanedPlaylists.push(playlist);
  382. next();
  383. } else next(err);
  384. });
  385. },
  386. err => {
  387. if (err) reject(new Error(err));
  388. else resolve({ playlists: orphanedPlaylists });
  389. }
  390. );
  391. }
  392. });
  393. });
  394. }
  395. /**
  396. * Deletes all orphaned station playlists
  397. *
  398. * @returns {Promise} - returns promise (reject, resolve)
  399. */
  400. DELETE_ORPHANED_STATION_PLAYLISTS() {
  401. return new Promise((resolve, reject) => {
  402. PlaylistsModule.runJob("GET_ORPHANED_STATION_PLAYLISTS", {}, this)
  403. .then(response => {
  404. async.eachLimit(
  405. response.playlists,
  406. 1,
  407. (playlist, next) => {
  408. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  409. .then(() => {
  410. this.log("INFO", "Deleting orphaned station playlist");
  411. next();
  412. })
  413. .catch(err => {
  414. next(err);
  415. });
  416. },
  417. err => {
  418. if (err) reject(new Error(err));
  419. else resolve({});
  420. }
  421. );
  422. })
  423. .catch(err => {
  424. reject(new Error(err));
  425. });
  426. });
  427. }
  428. /**
  429. * Fills a station playlist with songs
  430. *
  431. * @param {object} payload - object that contains the payload
  432. * @param {string} payload.stationId - the station id
  433. * @returns {Promise} - returns promise (reject, resolve)
  434. */
  435. AUTOFILL_STATION_PLAYLIST(payload) {
  436. return new Promise((resolve, reject) => {
  437. async.waterfall(
  438. [
  439. next => {
  440. if (!payload.stationId) next("Please specify a station id");
  441. else next();
  442. },
  443. next => {
  444. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  445. .then(station => {
  446. next(null, station);
  447. })
  448. .catch(next);
  449. },
  450. (station, next) => {
  451. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: station.playlist2 }, this)
  452. .then(() => {
  453. next(null, station);
  454. })
  455. .catch(err => {
  456. next(err);
  457. });
  458. },
  459. (station, next) => {
  460. const includedPlaylists = [];
  461. async.eachLimit(
  462. station.includedPlaylists,
  463. 1,
  464. (playlistId, next) => {
  465. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  466. .then(playlist => {
  467. includedPlaylists.push(playlist);
  468. next();
  469. })
  470. .catch(next);
  471. },
  472. err => {
  473. next(err, station, includedPlaylists);
  474. }
  475. );
  476. },
  477. (station, includedPlaylists, next) => {
  478. const excludedPlaylists = [];
  479. async.eachLimit(
  480. station.excludedPlaylists,
  481. 1,
  482. (playlistId, next) => {
  483. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  484. .then(playlist => {
  485. excludedPlaylists.push(playlist);
  486. next();
  487. })
  488. .catch(next);
  489. },
  490. err => {
  491. next(err, station, includedPlaylists, excludedPlaylists);
  492. }
  493. );
  494. },
  495. (station, includedPlaylists, excludedPlaylists, next) => {
  496. const excludedSongs = excludedPlaylists
  497. .flatMap(excludedPlaylist => excludedPlaylist.songs)
  498. .reduce(
  499. (items, item) =>
  500. items.find(x => x.songId === item.songId) ? [...items] : [...items, item],
  501. []
  502. );
  503. const includedSongs = includedPlaylists
  504. .flatMap(includedPlaylist => includedPlaylist.songs)
  505. .reduce(
  506. (songs, song) =>
  507. songs.find(x => x.songId === song.songId) ? [...songs] : [...songs, song],
  508. []
  509. )
  510. .filter(song => !excludedSongs.find(x => x.songId === song.songId));
  511. next(null, station, includedSongs);
  512. },
  513. (station, includedSongs, next) => {
  514. PlaylistsModule.playlistModel.updateOne(
  515. { _id: station.playlist2 },
  516. { $set: { songs: includedSongs } },
  517. next
  518. );
  519. }
  520. ],
  521. err => {
  522. if (err && err !== true) return reject(new Error(err));
  523. return resolve({});
  524. }
  525. );
  526. });
  527. }
  528. /**
  529. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  530. *
  531. * @param {object} payload - object that contains the payload
  532. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  533. * @returns {Promise} - returns promise (reject, resolve)
  534. */
  535. GET_PLAYLIST(payload) {
  536. return new Promise((resolve, reject) =>
  537. async.waterfall(
  538. [
  539. next => {
  540. CacheModule.runJob("HGETALL", { table: "playlists" }, this)
  541. .then(playlists => next(null, playlists))
  542. .catch(next);
  543. },
  544. (playlists, next) => {
  545. if (!playlists) return next();
  546. const playlistIds = Object.keys(playlists);
  547. return async.each(
  548. playlistIds,
  549. (playlistId, next) => {
  550. PlaylistsModule.playlistModel.findOne({ _id: playlistId }, (err, playlist) => {
  551. if (err) next(err);
  552. else if (!playlist) {
  553. CacheModule.runJob(
  554. "HDEL",
  555. {
  556. table: "playlists",
  557. key: playlistId
  558. },
  559. this
  560. )
  561. .then(() => next())
  562. .catch(next);
  563. } else next();
  564. });
  565. },
  566. next
  567. );
  568. },
  569. next => {
  570. CacheModule.runJob(
  571. "HGET",
  572. {
  573. table: "playlists",
  574. key: payload.playlistId
  575. },
  576. this
  577. )
  578. .then(playlist => next(null, playlist))
  579. .catch(next);
  580. },
  581. (playlist, next) => {
  582. if (playlist) return next(true, playlist);
  583. return PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  584. },
  585. (playlist, next) => {
  586. if (playlist) {
  587. CacheModule.runJob(
  588. "HSET",
  589. {
  590. table: "playlists",
  591. key: payload.playlistId,
  592. value: playlist
  593. },
  594. this
  595. )
  596. .then(playlist => {
  597. next(null, playlist);
  598. })
  599. .catch(next);
  600. } else next("Playlist not found");
  601. }
  602. ],
  603. (err, playlist) => {
  604. if (err && err !== true) return reject(new Error(err));
  605. return resolve(playlist);
  606. }
  607. )
  608. );
  609. }
  610. /**
  611. * Gets a playlist from id from Mongo and updates the cache with it
  612. *
  613. * @param {object} payload - object that contains the payload
  614. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  615. * @returns {Promise} - returns promise (reject, resolve)
  616. */
  617. UPDATE_PLAYLIST(payload) {
  618. // playlistId, cb
  619. return new Promise((resolve, reject) =>
  620. async.waterfall(
  621. [
  622. next => {
  623. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  624. },
  625. (playlist, next) => {
  626. if (!playlist) {
  627. CacheModule.runJob("HDEL", {
  628. table: "playlists",
  629. key: payload.playlistId
  630. });
  631. return next("Playlist not found");
  632. }
  633. return CacheModule.runJob(
  634. "HSET",
  635. {
  636. table: "playlists",
  637. key: payload.playlistId,
  638. value: playlist
  639. },
  640. this
  641. )
  642. .then(playlist => {
  643. next(null, playlist);
  644. })
  645. .catch(next);
  646. }
  647. ],
  648. (err, playlist) => {
  649. if (err && err !== true) return reject(new Error(err));
  650. return resolve(playlist);
  651. }
  652. )
  653. );
  654. }
  655. /**
  656. * Deletes playlist from id from Mongo and cache
  657. *
  658. * @param {object} payload - object that contains the payload
  659. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  660. * @returns {Promise} - returns promise (reject, resolve)
  661. */
  662. DELETE_PLAYLIST(payload) {
  663. // playlistId, cb
  664. return new Promise((resolve, reject) =>
  665. async.waterfall(
  666. [
  667. next => {
  668. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  669. },
  670. (res, next) => {
  671. CacheModule.runJob(
  672. "HDEL",
  673. {
  674. table: "playlists",
  675. key: payload.playlistId
  676. },
  677. this
  678. )
  679. .then(() => next())
  680. .catch(next);
  681. }
  682. ],
  683. err => {
  684. if (err && err !== true) return reject(new Error(err));
  685. return resolve();
  686. }
  687. )
  688. );
  689. }
  690. }
  691. export default new _PlaylistsModule();