playlists.js 20 KB

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