playlists.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  418. *
  419. * @param {object} payload - object that contains the payload
  420. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  421. * @returns {Promise} - returns promise (reject, resolve)
  422. */
  423. GET_PLAYLIST(payload) {
  424. return new Promise((resolve, reject) =>
  425. async.waterfall(
  426. [
  427. next => {
  428. CacheModule.runJob("HGETALL", { table: "playlists" }, this)
  429. .then(playlists => {
  430. next(null, playlists);
  431. })
  432. .catch(next);
  433. },
  434. (playlists, next) => {
  435. if (!playlists) return next();
  436. const playlistIds = Object.keys(playlists);
  437. return async.each(
  438. playlistIds,
  439. (playlistId, next) => {
  440. PlaylistsModule.playlistModel.findOne({ _id: playlistId }, (err, playlist) => {
  441. if (err) next(err);
  442. else if (!playlist) {
  443. CacheModule.runJob(
  444. "HDEL",
  445. {
  446. table: "playlists",
  447. key: playlistId
  448. },
  449. this
  450. )
  451. .then(() => next())
  452. .catch(next);
  453. } else next();
  454. });
  455. },
  456. next
  457. );
  458. },
  459. next => {
  460. CacheModule.runJob(
  461. "HGET",
  462. {
  463. table: "playlists",
  464. key: payload.playlistId
  465. },
  466. this
  467. )
  468. .then(playlist => next(null, playlist))
  469. .catch(next);
  470. },
  471. (playlist, next) => {
  472. if (playlist) return next(true, playlist);
  473. return PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  474. },
  475. (playlist, next) => {
  476. if (playlist) {
  477. CacheModule.runJob(
  478. "HSET",
  479. {
  480. table: "playlists",
  481. key: payload.playlistId,
  482. value: playlist
  483. },
  484. this
  485. )
  486. .then(playlist => {
  487. next(null, playlist);
  488. })
  489. .catch(next);
  490. } else next("Playlist not found");
  491. }
  492. ],
  493. (err, playlist) => {
  494. if (err && err !== true) return reject(new Error(err));
  495. return resolve(playlist);
  496. }
  497. )
  498. );
  499. }
  500. /**
  501. * Gets a playlist from id from Mongo and updates the cache with it
  502. *
  503. * @param {object} payload - object that contains the payload
  504. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  505. * @returns {Promise} - returns promise (reject, resolve)
  506. */
  507. UPDATE_PLAYLIST(payload) {
  508. // playlistId, cb
  509. return new Promise((resolve, reject) =>
  510. async.waterfall(
  511. [
  512. next => {
  513. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  514. },
  515. (playlist, next) => {
  516. if (!playlist) {
  517. CacheModule.runJob("HDEL", {
  518. table: "playlists",
  519. key: payload.playlistId
  520. });
  521. return next("Playlist not found");
  522. }
  523. return CacheModule.runJob(
  524. "HSET",
  525. {
  526. table: "playlists",
  527. key: payload.playlistId,
  528. value: playlist
  529. },
  530. this
  531. )
  532. .then(playlist => {
  533. next(null, playlist);
  534. })
  535. .catch(next);
  536. }
  537. ],
  538. (err, playlist) => {
  539. if (err && err !== true) return reject(new Error(err));
  540. return resolve(playlist);
  541. }
  542. )
  543. );
  544. }
  545. /**
  546. * Deletes playlist from id from Mongo and cache
  547. *
  548. * @param {object} payload - object that contains the payload
  549. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  550. * @returns {Promise} - returns promise (reject, resolve)
  551. */
  552. DELETE_PLAYLIST(payload) {
  553. // playlistId, cb
  554. return new Promise((resolve, reject) =>
  555. async.waterfall(
  556. [
  557. next => {
  558. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  559. },
  560. (res, next) => {
  561. CacheModule.runJob(
  562. "HDEL",
  563. {
  564. table: "playlists",
  565. key: payload.playlistId
  566. },
  567. this
  568. )
  569. .then(() => next())
  570. .catch(next);
  571. }
  572. ],
  573. err => {
  574. if (err && err !== true) return reject(new Error(err));
  575. return resolve();
  576. }
  577. )
  578. );
  579. }
  580. }
  581. export default new _PlaylistsModule();