playlists.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import async from "async";
  2. import CoreClass from "../core";
  3. let PlaylistsModule;
  4. let SongsModule;
  5. let CacheModule;
  6. let DBModule;
  7. let UtilsModule;
  8. class _PlaylistsModule extends CoreClass {
  9. // eslint-disable-next-line require-jsdoc
  10. constructor() {
  11. super("playlists");
  12. PlaylistsModule = this;
  13. }
  14. /**
  15. * Initialises the playlists module
  16. *
  17. * @returns {Promise} - returns promise (reject, resolve)
  18. */
  19. async initialize() {
  20. this.setStage(1);
  21. CacheModule = this.moduleManager.modules.cache;
  22. DBModule = this.moduleManager.modules.db;
  23. UtilsModule = this.moduleManager.modules.utils;
  24. SongsModule = this.moduleManager.modules.songs;
  25. this.playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" });
  26. this.playlistSchemaCache = await CacheModule.runJob("GET_SCHEMA", { schemaName: "playlist" });
  27. this.setStage(2);
  28. return new Promise((resolve, reject) =>
  29. async.waterfall(
  30. [
  31. next => {
  32. this.setStage(3);
  33. CacheModule.runJob("HGETALL", { table: "playlists" })
  34. .then(playlists => {
  35. next(null, playlists);
  36. })
  37. .catch(next);
  38. },
  39. (playlists, next) => {
  40. this.setStage(4);
  41. if (!playlists) return next();
  42. const playlistIds = Object.keys(playlists);
  43. return async.each(
  44. playlistIds,
  45. (playlistId, next) => {
  46. PlaylistsModule.playlistModel.findOne({ _id: playlistId }, (err, playlist) => {
  47. if (err) next(err);
  48. else if (!playlist) {
  49. CacheModule.runJob("HDEL", {
  50. table: "playlists",
  51. key: playlistId
  52. })
  53. .then(() => next())
  54. .catch(next);
  55. } else next();
  56. });
  57. },
  58. next
  59. );
  60. },
  61. next => {
  62. this.setStage(5);
  63. PlaylistsModule.playlistModel.find({}, next);
  64. },
  65. (playlists, next) => {
  66. this.setStage(6);
  67. async.each(
  68. playlists,
  69. (playlist, cb) => {
  70. CacheModule.runJob("HSET", {
  71. table: "playlists",
  72. key: playlist._id,
  73. value: PlaylistsModule.playlistSchemaCache(playlist)
  74. })
  75. .then(() => cb())
  76. .catch(next);
  77. },
  78. next
  79. );
  80. }
  81. ],
  82. async err => {
  83. if (err) {
  84. const formattedErr = await UtilsModule.runJob("GET_ERROR", {
  85. error: err
  86. });
  87. reject(new Error(formattedErr));
  88. } else resolve();
  89. }
  90. )
  91. );
  92. }
  93. /**
  94. * Creates a playlist that is not generated or editable by a user e.g. liked songs playlist
  95. *
  96. * @param {object} payload - object that contains the payload
  97. * @param {string} payload.userId - the id of the user to create the playlist for
  98. * @param {string} payload.displayName - the display name of the playlist
  99. * @returns {Promise} - returns promise (reject, resolve)
  100. */
  101. CREATE_READ_ONLY_PLAYLIST(payload) {
  102. return new Promise((resolve, reject) => {
  103. PlaylistsModule.playlistModel.create(
  104. {
  105. isUserModifiable: false,
  106. displayName: payload.displayName,
  107. songs: [],
  108. createdBy: payload.userId,
  109. createdAt: Date.now(),
  110. createdFor: null,
  111. type: payload.type
  112. },
  113. (err, playlist) => {
  114. if (err) return reject(new Error(err));
  115. return resolve(playlist._id);
  116. }
  117. );
  118. });
  119. }
  120. /**
  121. * Creates a playlist that contains all songs of a specific genre
  122. *
  123. * @param {object} payload - object that contains the payload
  124. * @param {string} payload.genre - the genre
  125. * @returns {Promise} - returns promise (reject, resolve)
  126. */
  127. CREATE_GENRE_PLAYLIST(payload) {
  128. return new Promise((resolve, reject) => {
  129. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre: payload.genre.toLowerCase() }, this)
  130. .then(() => {
  131. reject(new Error("Playlist already exists"));
  132. })
  133. .catch(err => {
  134. if (err.message === "Playlist not found") {
  135. PlaylistsModule.playlistModel.create(
  136. {
  137. isUserModifiable: false,
  138. displayName: `Genre - ${payload.genre}`,
  139. songs: [],
  140. createdBy: "Musare",
  141. createdFor: `${payload.genre.toLowerCase()}`,
  142. createdAt: Date.now(),
  143. type: "genre"
  144. },
  145. (err, playlist) => {
  146. if (err) return reject(new Error(err));
  147. return resolve(playlist._id);
  148. }
  149. );
  150. } else reject(new Error(err));
  151. });
  152. });
  153. }
  154. /**
  155. * Gets all genre playlists
  156. *
  157. * @param {object} payload - object that contains the payload
  158. * @param {string} payload.includeSongs - include the songs
  159. * @returns {Promise} - returns promise (reject, resolve)
  160. */
  161. GET_ALL_GENRE_PLAYLISTS(payload) {
  162. return new Promise((resolve, reject) => {
  163. const includeObject = payload.includeSongs ? null : { songs: false };
  164. PlaylistsModule.playlistModel.find({ type: "genre" }, includeObject, (err, playlists) => {
  165. if (err) reject(new Error(err));
  166. else resolve({ playlists });
  167. });
  168. });
  169. }
  170. /**
  171. * Gets a genre playlist
  172. *
  173. * @param {object} payload - object that contains the payload
  174. * @param {string} payload.genre - the genre
  175. * @param {string} payload.includeSongs - include the songs
  176. * @returns {Promise} - returns promise (reject, resolve)
  177. */
  178. GET_GENRE_PLAYLIST(payload) {
  179. return new Promise((resolve, reject) => {
  180. const includeObject = payload.includeSongs ? null : { songs: false };
  181. PlaylistsModule.playlistModel.findOne(
  182. { type: "genre", createdFor: payload.genre },
  183. includeObject,
  184. (err, playlist) => {
  185. if (err) reject(new Error(err));
  186. else if (!playlist) reject(new Error("Playlist not found"));
  187. else resolve({ playlist });
  188. }
  189. );
  190. });
  191. }
  192. /**
  193. * Adds a song to a playlist
  194. *
  195. * @param {object} payload - object that contains the payload
  196. * @param {string} payload.playlistId - the playlist id
  197. * @param {string} payload.song - the song
  198. * @returns {Promise} - returns promise (reject, resolve)
  199. */
  200. ADD_SONG_TO_PLAYLIST(payload) {
  201. return new Promise((resolve, reject) => {
  202. const song = {
  203. _id: payload.song._id,
  204. songId: payload.song.songId,
  205. title: payload.song.title,
  206. duration: payload.song.duration
  207. };
  208. PlaylistsModule.playlistModel.updateOne(
  209. { _id: payload.playlistId },
  210. { $push: { songs: song } },
  211. { runValidators: true },
  212. err => {
  213. if (err) reject(new Error(err));
  214. else {
  215. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  216. .then(() => resolve())
  217. .catch(err => {
  218. reject(new Error(err));
  219. });
  220. }
  221. }
  222. );
  223. });
  224. }
  225. /**
  226. * Deletes a song from a playlist based on the songId
  227. *
  228. * @param {object} payload - object that contains the payload
  229. * @param {string} payload.playlistId - the playlist id
  230. * @param {string} payload.songId - the songId
  231. * @returns {Promise} - returns promise (reject, resolve)
  232. */
  233. DELETE_SONG_FROM_PLAYLIST_BY_SONGID(payload) {
  234. return new Promise((resolve, reject) => {
  235. PlaylistsModule.playlistModel.updateOne(
  236. { _id: payload.playlistId },
  237. { $pull: { songs: { songId: payload.songId } } },
  238. err => {
  239. if (err) reject(new Error(err));
  240. else {
  241. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  242. .then(() => resolve())
  243. .catch(err => {
  244. reject(new Error(err));
  245. });
  246. }
  247. }
  248. );
  249. });
  250. }
  251. /**
  252. * Fills a genre playlist with songs
  253. *
  254. * @param {object} payload - object that contains the payload
  255. * @param {string} payload.genre - the genre
  256. * @returns {Promise} - returns promise (reject, resolve)
  257. */
  258. AUTOFILL_GENRE_PLAYLIST(payload) {
  259. return new Promise((resolve, reject) => {
  260. async.waterfall(
  261. [
  262. next => {
  263. PlaylistsModule.runJob(
  264. "GET_GENRE_PLAYLIST",
  265. { genre: payload.genre.toLowerCase(), includeSongs: true },
  266. this
  267. )
  268. .then(response => {
  269. next(null, { playlist: response.playlist });
  270. })
  271. .catch(err => {
  272. if (err.message === "Playlist not found") {
  273. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)
  274. .then(playlistId => {
  275. next(null, { playlist: { _id: playlistId, songs: [] } });
  276. })
  277. .catch(err => {
  278. next(err);
  279. });
  280. } else next(err);
  281. });
  282. },
  283. (data, next) => {
  284. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)
  285. .then(response => {
  286. data.songs = response.songs;
  287. next(null, data);
  288. })
  289. .catch(err => {
  290. console.log(err);
  291. next(err);
  292. });
  293. },
  294. (data, next) => {
  295. data.songsToDelete = [];
  296. data.songsToAdd = [];
  297. data.playlist.songs.forEach(playlistSong => {
  298. const found = data.songs.find(song => playlistSong.songId === song.songId);
  299. if (!found) data.songsToDelete.push(playlistSong);
  300. });
  301. data.songs.forEach(song => {
  302. const found = data.playlist.songs.find(playlistSong => song.songId === playlistSong.songId);
  303. if (!found) data.songsToAdd.push(song);
  304. });
  305. next(null, data);
  306. },
  307. (data, next) => {
  308. const promises = [];
  309. data.songsToAdd.forEach(song => {
  310. promises.push(
  311. PlaylistsModule.runJob(
  312. "ADD_SONG_TO_PLAYLIST",
  313. { playlistId: data.playlist._id, song },
  314. this
  315. )
  316. );
  317. });
  318. data.songsToDelete.forEach(song => {
  319. promises.push(
  320. PlaylistsModule.runJob(
  321. "DELETE_SONG_FROM_PLAYLIST_BY_SONGID",
  322. {
  323. playlistId: data.playlist._id,
  324. songId: song.songId
  325. },
  326. this
  327. )
  328. );
  329. });
  330. Promise.allSettled(promises)
  331. .then(() => {
  332. next();
  333. })
  334. .catch(err => {
  335. next(err);
  336. });
  337. }
  338. ],
  339. err => {
  340. if (err && err !== true) return reject(new Error(err));
  341. return resolve({});
  342. }
  343. );
  344. });
  345. }
  346. /**
  347. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  348. *
  349. * @param {object} payload - object that contains the payload
  350. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  351. * @returns {Promise} - returns promise (reject, resolve)
  352. */
  353. GET_PLAYLIST(payload) {
  354. return new Promise((resolve, reject) =>
  355. async.waterfall(
  356. [
  357. next => {
  358. CacheModule.runJob("HGETALL", { table: "playlists" }, this)
  359. .then(playlists => {
  360. next(null, playlists);
  361. })
  362. .catch(next);
  363. },
  364. (playlists, next) => {
  365. if (!playlists) return next();
  366. const playlistIds = Object.keys(playlists);
  367. return async.each(
  368. playlistIds,
  369. (playlistId, next) => {
  370. PlaylistsModule.playlistModel.findOne({ _id: playlistId }, (err, playlist) => {
  371. if (err) next(err);
  372. else if (!playlist) {
  373. CacheModule.runJob(
  374. "HDEL",
  375. {
  376. table: "playlists",
  377. key: playlistId
  378. },
  379. this
  380. )
  381. .then(() => next())
  382. .catch(next);
  383. } else next();
  384. });
  385. },
  386. next
  387. );
  388. },
  389. next => {
  390. CacheModule.runJob(
  391. "HGET",
  392. {
  393. table: "playlists",
  394. key: payload.playlistId
  395. },
  396. this
  397. )
  398. .then(playlist => next(null, playlist))
  399. .catch(next);
  400. },
  401. (playlist, next) => {
  402. if (playlist) return next(true, playlist);
  403. return PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  404. },
  405. (playlist, next) => {
  406. if (playlist) {
  407. CacheModule.runJob(
  408. "HSET",
  409. {
  410. table: "playlists",
  411. key: payload.playlistId,
  412. value: playlist
  413. },
  414. this
  415. )
  416. .then(playlist => {
  417. next(null, playlist);
  418. })
  419. .catch(next);
  420. } else next("Playlist not found");
  421. }
  422. ],
  423. (err, playlist) => {
  424. if (err && err !== true) return reject(new Error(err));
  425. return resolve(playlist);
  426. }
  427. )
  428. );
  429. }
  430. /**
  431. * Gets a playlist from id from Mongo and updates the cache with it
  432. *
  433. * @param {object} payload - object that contains the payload
  434. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  435. * @returns {Promise} - returns promise (reject, resolve)
  436. */
  437. UPDATE_PLAYLIST(payload) {
  438. // playlistId, cb
  439. return new Promise((resolve, reject) =>
  440. async.waterfall(
  441. [
  442. next => {
  443. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  444. },
  445. (playlist, next) => {
  446. if (!playlist) {
  447. CacheModule.runJob("HDEL", {
  448. table: "playlists",
  449. key: payload.playlistId
  450. });
  451. return next("Playlist not found");
  452. }
  453. return CacheModule.runJob(
  454. "HSET",
  455. {
  456. table: "playlists",
  457. key: payload.playlistId,
  458. value: playlist
  459. },
  460. this
  461. )
  462. .then(playlist => {
  463. next(null, playlist);
  464. })
  465. .catch(next);
  466. }
  467. ],
  468. (err, playlist) => {
  469. if (err && err !== true) return reject(new Error(err));
  470. return resolve(playlist);
  471. }
  472. )
  473. );
  474. }
  475. /**
  476. * Deletes playlist from id from Mongo and cache
  477. *
  478. * @param {object} payload - object that contains the payload
  479. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  480. * @returns {Promise} - returns promise (reject, resolve)
  481. */
  482. DELETE_PLAYLIST(payload) {
  483. // playlistId, cb
  484. return new Promise((resolve, reject) =>
  485. async.waterfall(
  486. [
  487. next => {
  488. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  489. },
  490. (res, next) => {
  491. CacheModule.runJob(
  492. "HDEL",
  493. {
  494. table: "playlists",
  495. key: payload.playlistId
  496. },
  497. this
  498. )
  499. .then(() => next())
  500. .catch(next);
  501. }
  502. ],
  503. err => {
  504. if (err && err !== true) return reject(new Error(err));
  505. return resolve();
  506. }
  507. )
  508. );
  509. }
  510. }
  511. export default new _PlaylistsModule();