playlists.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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 {
  91. resolve();
  92. // PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", {})
  93. // .then()
  94. // .catch()
  95. // .finally(() => {
  96. // SongsModule.runJob("GET_ALL_GENRES", {})
  97. // .then(response => {
  98. // const { genres } = response;
  99. // genres.forEach(genre => {
  100. // PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }).then().catch();
  101. // });
  102. // })
  103. // .catch();
  104. // });
  105. }
  106. }
  107. )
  108. );
  109. }
  110. /**
  111. * Creates a playlist that is not generated or editable by a user e.g. liked songs playlist
  112. *
  113. * @param {object} payload - object that contains the payload
  114. * @param {string} payload.userId - the id of the user to create the playlist for
  115. * @param {string} payload.displayName - the display name of the playlist
  116. * @returns {Promise} - returns promise (reject, resolve)
  117. */
  118. CREATE_READ_ONLY_PLAYLIST(payload) {
  119. return new Promise((resolve, reject) => {
  120. PlaylistsModule.playlistModel.create(
  121. {
  122. isUserModifiable: false,
  123. displayName: payload.displayName,
  124. songs: [],
  125. createdBy: payload.userId,
  126. createdAt: Date.now(),
  127. createdFor: null,
  128. type: payload.type
  129. },
  130. (err, playlist) => {
  131. if (err) return reject(new Error(err));
  132. return resolve(playlist._id);
  133. }
  134. );
  135. });
  136. }
  137. /**
  138. * Creates a playlist that contains all songs of a specific genre
  139. *
  140. * @param {object} payload - object that contains the payload
  141. * @param {string} payload.genre - the genre
  142. * @returns {Promise} - returns promise (reject, resolve)
  143. */
  144. CREATE_GENRE_PLAYLIST(payload) {
  145. return new Promise((resolve, reject) => {
  146. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre: payload.genre.toLowerCase() }, this)
  147. .then(() => {
  148. reject(new Error("Playlist already exists"));
  149. })
  150. .catch(err => {
  151. if (err.message === "Playlist not found") {
  152. PlaylistsModule.playlistModel.create(
  153. {
  154. isUserModifiable: false,
  155. displayName: `Genre - ${payload.genre}`,
  156. songs: [],
  157. createdBy: "Musare",
  158. createdFor: `${payload.genre.toLowerCase()}`,
  159. createdAt: Date.now(),
  160. type: "genre"
  161. },
  162. (err, playlist) => {
  163. if (err) return reject(new Error(err));
  164. return resolve(playlist._id);
  165. }
  166. );
  167. } else reject(new Error(err));
  168. });
  169. });
  170. }
  171. /**
  172. * Gets all genre playlists
  173. *
  174. * @param {object} payload - object that contains the payload
  175. * @param {string} payload.includeSongs - include the songs
  176. * @returns {Promise} - returns promise (reject, resolve)
  177. */
  178. GET_ALL_GENRE_PLAYLISTS(payload) {
  179. return new Promise((resolve, reject) => {
  180. const includeObject = payload.includeSongs ? null : { songs: false };
  181. PlaylistsModule.playlistModel.find({ type: "genre" }, includeObject, (err, playlists) => {
  182. if (err) reject(new Error(err));
  183. else resolve({ playlists });
  184. });
  185. });
  186. }
  187. /**
  188. * Gets a genre playlist
  189. *
  190. * @param {object} payload - object that contains the payload
  191. * @param {string} payload.genre - the genre
  192. * @param {string} payload.includeSongs - include the songs
  193. * @returns {Promise} - returns promise (reject, resolve)
  194. */
  195. GET_GENRE_PLAYLIST(payload) {
  196. return new Promise((resolve, reject) => {
  197. const includeObject = payload.includeSongs ? null : { songs: false };
  198. PlaylistsModule.playlistModel.findOne(
  199. { type: "genre", createdFor: payload.genre },
  200. includeObject,
  201. (err, playlist) => {
  202. if (err) reject(new Error(err));
  203. else if (!playlist) reject(new Error("Playlist not found"));
  204. else resolve({ playlist });
  205. }
  206. );
  207. });
  208. }
  209. /**
  210. * Gets all missing genre playlists
  211. *
  212. * @returns {Promise} - returns promise (reject, resolve)
  213. */
  214. GET_MISSING_GENRE_PLAYLISTS() {
  215. return new Promise((resolve, reject) => {
  216. SongsModule.runJob("GET_ALL_GENRES", {}, this)
  217. .then(response => {
  218. const { genres } = response;
  219. const missingGenres = [];
  220. async.eachLimit(
  221. genres,
  222. 1,
  223. (genre, next) => {
  224. PlaylistsModule.runJob(
  225. "GET_GENRE_PLAYLIST",
  226. { genre: genre.toLowerCase(), includeSongs: false },
  227. this
  228. )
  229. .then(() => {
  230. next();
  231. })
  232. .catch(err => {
  233. if (err.message === "Playlist not found") {
  234. missingGenres.push(genre);
  235. next();
  236. } else next(err);
  237. });
  238. },
  239. err => {
  240. if (err) reject(err);
  241. else resolve({ genres: missingGenres });
  242. }
  243. );
  244. })
  245. .catch(err => {
  246. reject(err);
  247. });
  248. });
  249. }
  250. /**
  251. * Creates all missing genre playlists
  252. *
  253. * @returns {Promise} - returns promise (reject, resolve)
  254. */
  255. CREATE_MISSING_GENRE_PLAYLISTS() {
  256. return new Promise((resolve, reject) => {
  257. PlaylistsModule.runJob("GET_MISSING_GENRE_PLAYLISTS", {}, this)
  258. .then(response => {
  259. const { genres } = response;
  260. async.eachLimit(
  261. genres,
  262. 1,
  263. (genre, next) => {
  264. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre }, this)
  265. .then(() => {
  266. next();
  267. })
  268. .catch(err => {
  269. next(err);
  270. });
  271. },
  272. err => {
  273. if (err) reject(err);
  274. else resolve();
  275. }
  276. );
  277. })
  278. .catch(err => {
  279. reject(err);
  280. });
  281. });
  282. }
  283. /**
  284. * Gets a station playlist
  285. *
  286. * @param {object} payload - object that contains the payload
  287. * @param {string} payload.staationId - the station id
  288. * @param {string} payload.includeSongs - include the songs
  289. * @returns {Promise} - returns promise (reject, resolve)
  290. */
  291. GET_STATION_PLAYLIST(payload) {
  292. return new Promise((resolve, reject) => {
  293. const includeObject = payload.includeSongs ? null : { songs: false };
  294. PlaylistsModule.playlistModel.findOne(
  295. { type: "station", createdFor: payload.stationId },
  296. includeObject,
  297. (err, playlist) => {
  298. if (err) reject(new Error(err));
  299. else if (!playlist) reject(new Error("Playlist not found"));
  300. else resolve({ playlist });
  301. }
  302. );
  303. });
  304. }
  305. /**
  306. * Adds a song to a playlist
  307. *
  308. * @param {object} payload - object that contains the payload
  309. * @param {string} payload.playlistId - the playlist id
  310. * @param {string} payload.song - the song
  311. * @returns {Promise} - returns promise (reject, resolve)
  312. */
  313. ADD_SONG_TO_PLAYLIST(payload) {
  314. return new Promise((resolve, reject) => {
  315. const { _id, songId, title, artists, thumbnail, duration, status } = payload.song;
  316. const trimmedSong = {
  317. _id,
  318. songId,
  319. title,
  320. artists,
  321. thumbnail,
  322. duration,
  323. status
  324. };
  325. PlaylistsModule.playlistModel.updateOne(
  326. { _id: payload.playlistId },
  327. { $push: { songs: trimmedSong } },
  328. { runValidators: true },
  329. err => {
  330. if (err) reject(new Error(err));
  331. else {
  332. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  333. .then(() => resolve())
  334. .catch(err => {
  335. reject(new Error(err));
  336. });
  337. }
  338. }
  339. );
  340. });
  341. }
  342. /**
  343. * Deletes a song from a playlist based on the songId
  344. *
  345. * @param {object} payload - object that contains the payload
  346. * @param {string} payload.playlistId - the playlist id
  347. * @param {string} payload.songId - the songId
  348. * @returns {Promise} - returns promise (reject, resolve)
  349. */
  350. DELETE_SONG_FROM_PLAYLIST_BY_SONGID(payload) {
  351. return new Promise((resolve, reject) => {
  352. PlaylistsModule.playlistModel.updateOne(
  353. { _id: payload.playlistId },
  354. { $pull: { songs: { songId: payload.songId } } },
  355. err => {
  356. if (err) reject(new Error(err));
  357. else {
  358. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  359. .then(() => resolve())
  360. .catch(err => {
  361. reject(new Error(err));
  362. });
  363. }
  364. }
  365. );
  366. });
  367. }
  368. /**
  369. * Fills a genre playlist with songs
  370. *
  371. * @param {object} payload - object that contains the payload
  372. * @param {string} payload.genre - the genre
  373. * @returns {Promise} - returns promise (reject, resolve)
  374. */
  375. AUTOFILL_GENRE_PLAYLIST(payload) {
  376. return new Promise((resolve, reject) => {
  377. async.waterfall(
  378. [
  379. next => {
  380. PlaylistsModule.runJob(
  381. "GET_GENRE_PLAYLIST",
  382. { genre: payload.genre.toLowerCase(), includeSongs: true },
  383. this
  384. )
  385. .then(response => {
  386. next(null, { playlist: response.playlist });
  387. })
  388. .catch(err => {
  389. if (err.message === "Playlist not found") {
  390. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)
  391. .then(playlistId => {
  392. next(null, { playlist: { _id: playlistId, songs: [] } });
  393. })
  394. .catch(err => {
  395. next(err);
  396. });
  397. } else next(err);
  398. });
  399. },
  400. (data, next) => {
  401. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)
  402. .then(response => {
  403. data.songs = response.songs;
  404. next(null, data);
  405. })
  406. .catch(err => {
  407. console.log(err);
  408. next(err);
  409. });
  410. },
  411. (data, next) => {
  412. data.songsToDelete = [];
  413. data.songsToAdd = [];
  414. data.playlist.songs.forEach(playlistSong => {
  415. const found = data.songs.find(song => playlistSong.songId === song.songId);
  416. if (!found) data.songsToDelete.push(playlistSong);
  417. });
  418. data.songs.forEach(song => {
  419. const found = data.playlist.songs.find(playlistSong => song.songId === playlistSong.songId);
  420. if (!found) data.songsToAdd.push(song);
  421. });
  422. next(null, data);
  423. },
  424. (data, next) => {
  425. const promises = [];
  426. data.songsToAdd.forEach(song => {
  427. promises.push(
  428. PlaylistsModule.runJob(
  429. "ADD_SONG_TO_PLAYLIST",
  430. { playlistId: data.playlist._id, song },
  431. this
  432. )
  433. );
  434. });
  435. data.songsToDelete.forEach(song => {
  436. promises.push(
  437. PlaylistsModule.runJob(
  438. "DELETE_SONG_FROM_PLAYLIST_BY_SONGID",
  439. {
  440. playlistId: data.playlist._id,
  441. songId: song.songId
  442. },
  443. this
  444. )
  445. );
  446. });
  447. Promise.allSettled(promises)
  448. .then(() => {
  449. next(null, data.playlist._id);
  450. })
  451. .catch(err => {
  452. next(err);
  453. });
  454. },
  455. (playlistId, next) => {
  456. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  457. .then(response => {
  458. response.stationIds.forEach(stationId => {
  459. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  460. });
  461. })
  462. .catch();
  463. next();
  464. }
  465. ],
  466. err => {
  467. if (err && err !== true) return reject(new Error(err));
  468. return resolve({});
  469. }
  470. );
  471. });
  472. }
  473. /**
  474. * Gets orphaned genre playlists
  475. *
  476. * @returns {Promise} - returns promise (reject, resolve)
  477. */
  478. GET_ORPHANED_GENRE_PLAYLISTS() {
  479. return new Promise((resolve, reject) => {
  480. PlaylistsModule.playlistModel.find({ type: "genre" }, { songs: false }, (err, playlists) => {
  481. if (err) reject(new Error(err));
  482. else {
  483. const orphanedPlaylists = [];
  484. async.eachLimit(
  485. playlists,
  486. 1,
  487. (playlist, next) => {
  488. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: playlist.createdFor }, this)
  489. .then(response => {
  490. if (response.songs.length === 0) {
  491. StationsModule.runJob(
  492. "GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST",
  493. { playlistId: playlist._id },
  494. this
  495. )
  496. .then(response => {
  497. if (response.stationIds.length === 0) orphanedPlaylists.push(playlist);
  498. next();
  499. })
  500. .catch(next);
  501. } else next();
  502. })
  503. .catch(next);
  504. },
  505. err => {
  506. if (err) reject(new Error(err));
  507. else resolve({ playlists: orphanedPlaylists });
  508. }
  509. );
  510. }
  511. });
  512. });
  513. }
  514. /**
  515. * Deletes all orphaned genre playlists
  516. *
  517. * @returns {Promise} - returns promise (reject, resolve)
  518. */
  519. DELETE_ORPHANED_GENRE_PLAYLISTS() {
  520. return new Promise((resolve, reject) => {
  521. PlaylistsModule.runJob("GET_ORPHANED_GENRE_PLAYLISTS", {}, this)
  522. .then(response => {
  523. async.eachLimit(
  524. response.playlists,
  525. 1,
  526. (playlist, next) => {
  527. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  528. .then(() => {
  529. this.log("INFO", "Deleting orphaned genre playlist");
  530. next();
  531. })
  532. .catch(err => {
  533. next(err);
  534. });
  535. },
  536. err => {
  537. if (err) reject(new Error(err));
  538. else resolve({});
  539. }
  540. );
  541. })
  542. .catch(err => {
  543. reject(new Error(err));
  544. });
  545. });
  546. }
  547. /**
  548. * Gets a orphaned station playlists
  549. *
  550. * @returns {Promise} - returns promise (reject, resolve)
  551. */
  552. GET_ORPHANED_STATION_PLAYLISTS() {
  553. return new Promise((resolve, reject) => {
  554. PlaylistsModule.playlistModel.find({ type: "station" }, { songs: false }, (err, playlists) => {
  555. if (err) reject(new Error(err));
  556. else {
  557. const orphanedPlaylists = [];
  558. async.eachLimit(
  559. playlists,
  560. 1,
  561. (playlist, next) => {
  562. StationsModule.runJob("GET_STATION", { stationId: playlist.createdFor }, this)
  563. .then(station => {
  564. if (station.playlist !== playlist._id.toString()) {
  565. orphanedPlaylists.push(playlist);
  566. }
  567. next();
  568. })
  569. .catch(err => {
  570. if (err.message === "Station not found") {
  571. orphanedPlaylists.push(playlist);
  572. next();
  573. } else next(err);
  574. });
  575. },
  576. err => {
  577. if (err) reject(new Error(err));
  578. else resolve({ playlists: orphanedPlaylists });
  579. }
  580. );
  581. }
  582. });
  583. });
  584. }
  585. /**
  586. * Deletes all orphaned station playlists
  587. *
  588. * @returns {Promise} - returns promise (reject, resolve)
  589. */
  590. DELETE_ORPHANED_STATION_PLAYLISTS() {
  591. return new Promise((resolve, reject) => {
  592. PlaylistsModule.runJob("GET_ORPHANED_STATION_PLAYLISTS", {}, this)
  593. .then(response => {
  594. async.eachLimit(
  595. response.playlists,
  596. 1,
  597. (playlist, next) => {
  598. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  599. .then(() => {
  600. this.log("INFO", "Deleting orphaned station playlist");
  601. next();
  602. })
  603. .catch(err => {
  604. next(err);
  605. });
  606. },
  607. err => {
  608. if (err) reject(new Error(err));
  609. else resolve({});
  610. }
  611. );
  612. })
  613. .catch(err => {
  614. reject(new Error(err));
  615. });
  616. });
  617. }
  618. /**
  619. * Fills a station playlist with songs
  620. *
  621. * @param {object} payload - object that contains the payload
  622. * @param {string} payload.stationId - the station id
  623. * @returns {Promise} - returns promise (reject, resolve)
  624. */
  625. AUTOFILL_STATION_PLAYLIST(payload) {
  626. return new Promise((resolve, reject) => {
  627. let originalPlaylist = null;
  628. async.waterfall(
  629. [
  630. next => {
  631. if (!payload.stationId) next("Please specify a station id");
  632. else next();
  633. },
  634. next => {
  635. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  636. .then(station => {
  637. next(null, station);
  638. })
  639. .catch(next);
  640. },
  641. (station, next) => {
  642. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: station.playlist }, this)
  643. .then(playlist => {
  644. originalPlaylist = playlist;
  645. next(null, station);
  646. })
  647. .catch(err => {
  648. next(err);
  649. });
  650. },
  651. (station, next) => {
  652. const includedPlaylists = [];
  653. async.eachLimit(
  654. station.includedPlaylists,
  655. 1,
  656. (playlistId, next) => {
  657. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  658. .then(playlist => {
  659. includedPlaylists.push(playlist);
  660. next();
  661. })
  662. .catch(next);
  663. },
  664. err => {
  665. next(err, station, includedPlaylists);
  666. }
  667. );
  668. },
  669. (station, includedPlaylists, next) => {
  670. const excludedPlaylists = [];
  671. async.eachLimit(
  672. station.excludedPlaylists,
  673. 1,
  674. (playlistId, next) => {
  675. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  676. .then(playlist => {
  677. excludedPlaylists.push(playlist);
  678. next();
  679. })
  680. .catch(next);
  681. },
  682. err => {
  683. next(err, station, includedPlaylists, excludedPlaylists);
  684. }
  685. );
  686. },
  687. (station, includedPlaylists, excludedPlaylists, next) => {
  688. const excludedSongs = excludedPlaylists
  689. .flatMap(excludedPlaylist => excludedPlaylist.songs)
  690. .reduce(
  691. (items, item) =>
  692. items.find(x => x.songId === item.songId) ? [...items] : [...items, item],
  693. []
  694. );
  695. const includedSongs = includedPlaylists
  696. .flatMap(includedPlaylist => includedPlaylist.songs)
  697. .reduce(
  698. (songs, song) =>
  699. songs.find(x => x.songId === song.songId) ? [...songs] : [...songs, song],
  700. []
  701. )
  702. .filter(song => !excludedSongs.find(x => x.songId === song.songId));
  703. next(null, station, includedSongs);
  704. },
  705. (station, includedSongs, next) => {
  706. PlaylistsModule.playlistModel.updateOne(
  707. { _id: station.playlist },
  708. { $set: { songs: includedSongs } },
  709. err => {
  710. next(err, includedSongs);
  711. }
  712. );
  713. },
  714. (includedSongs, next) => {
  715. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: originalPlaylist._id }, this)
  716. .then(() => {
  717. next(null, includedSongs);
  718. })
  719. .catch(next);
  720. },
  721. (includedSongs, next) => {
  722. if (originalPlaylist.songs.length === 0 && includedSongs.length > 0)
  723. StationsModule.runJob("SKIP_STATION", { stationId: payload.stationId });
  724. next();
  725. }
  726. ],
  727. err => {
  728. if (err && err !== true) return reject(new Error(err));
  729. return resolve({});
  730. }
  731. );
  732. });
  733. }
  734. /**
  735. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  736. *
  737. * @param {object} payload - object that contains the payload
  738. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  739. * @returns {Promise} - returns promise (reject, resolve)
  740. */
  741. GET_PLAYLIST(payload) {
  742. return new Promise((resolve, reject) =>
  743. async.waterfall(
  744. [
  745. next => {
  746. CacheModule.runJob(
  747. "HGET",
  748. {
  749. table: "playlists",
  750. key: payload.playlistId
  751. },
  752. this
  753. )
  754. .then(playlist => next(null, playlist))
  755. .catch(next);
  756. },
  757. (playlist, next) => {
  758. if (playlist)
  759. PlaylistsModule.playlistModel.exists({ _id: payload.playlistId }, (err, exists) => {
  760. if (err) next(err);
  761. else if (exists) next(null, playlist);
  762. else {
  763. CacheModule.runJob(
  764. "HDEL",
  765. {
  766. table: "playlists",
  767. key: payload.playlistId
  768. },
  769. this
  770. )
  771. .then(() => next())
  772. .catch(next);
  773. }
  774. });
  775. else PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  776. },
  777. (playlist, next) => {
  778. if (playlist) {
  779. CacheModule.runJob(
  780. "HSET",
  781. {
  782. table: "playlists",
  783. key: payload.playlistId,
  784. value: playlist
  785. },
  786. this
  787. )
  788. .then(playlist => {
  789. next(null, playlist);
  790. })
  791. .catch(next);
  792. } else next("Playlist not found");
  793. }
  794. ],
  795. (err, playlist) => {
  796. if (err && err !== true) return reject(new Error(err));
  797. return resolve(playlist);
  798. }
  799. )
  800. );
  801. }
  802. /**
  803. * Gets a playlist from id from Mongo and updates the cache with it
  804. *
  805. * @param {object} payload - object that contains the payload
  806. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  807. * @returns {Promise} - returns promise (reject, resolve)
  808. */
  809. UPDATE_PLAYLIST(payload) {
  810. return new Promise((resolve, reject) =>
  811. async.waterfall(
  812. [
  813. next => {
  814. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  815. },
  816. (playlist, next) => {
  817. if (!playlist) {
  818. CacheModule.runJob("HDEL", {
  819. table: "playlists",
  820. key: payload.playlistId
  821. });
  822. return next("Playlist not found");
  823. }
  824. return CacheModule.runJob(
  825. "HSET",
  826. {
  827. table: "playlists",
  828. key: payload.playlistId,
  829. value: playlist
  830. },
  831. this
  832. )
  833. .then(playlist => {
  834. next(null, playlist);
  835. })
  836. .catch(next);
  837. }
  838. ],
  839. (err, playlist) => {
  840. if (err && err !== true) return reject(new Error(err));
  841. return resolve(playlist);
  842. }
  843. )
  844. );
  845. }
  846. /**
  847. * Deletes playlist from id from Mongo and cache
  848. *
  849. * @param {object} payload - object that contains the payload
  850. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  851. * @returns {Promise} - returns promise (reject, resolve)
  852. */
  853. DELETE_PLAYLIST(payload) {
  854. return new Promise((resolve, reject) =>
  855. async.waterfall(
  856. [
  857. next => {
  858. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  859. },
  860. (res, next) => {
  861. CacheModule.runJob(
  862. "HDEL",
  863. {
  864. table: "playlists",
  865. key: payload.playlistId
  866. },
  867. this
  868. )
  869. .then(() => next())
  870. .catch(next);
  871. }
  872. ],
  873. err => {
  874. if (err && err !== true) return reject(new Error(err));
  875. return resolve();
  876. }
  877. )
  878. );
  879. }
  880. }
  881. export default new _PlaylistsModule();