playlists.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. displayName: payload.displayName,
  106. songs: [],
  107. createdBy: payload.userId,
  108. createdAt: Date.now(),
  109. createdFor: null,
  110. type: payload.type
  111. },
  112. (err, playlist) => {
  113. if (err) return reject(new Error(err));
  114. return resolve(playlist._id);
  115. }
  116. );
  117. });
  118. }
  119. /**
  120. * Creates a playlist that contains all songs of a specific genre
  121. *
  122. * @param {object} payload - object that contains the payload
  123. * @param {string} payload.genre - the genre
  124. * @returns {Promise} - returns promise (reject, resolve)
  125. */
  126. CREATE_GENRE_PLAYLIST(payload) {
  127. return new Promise((resolve, reject) => {
  128. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre: payload.genre.toLowerCase() }, this)
  129. .then(() => {
  130. reject(new Error("Playlist already exists"));
  131. })
  132. .catch(err => {
  133. if (err.message === "Playlist not found") {
  134. PlaylistsModule.playlistModel.create(
  135. {
  136. displayName: `Genre - ${payload.genre}`,
  137. songs: [],
  138. createdBy: "Musare",
  139. createdFor: `${payload.genre.toLowerCase()}`,
  140. createdAt: Date.now(),
  141. type: "genre"
  142. },
  143. (err, playlist) => {
  144. if (err) return reject(new Error(err));
  145. return resolve(playlist._id);
  146. }
  147. );
  148. } else reject(new Error(err));
  149. });
  150. });
  151. }
  152. /**
  153. * Gets all genre playlists
  154. *
  155. * @param {object} payload - object that contains the payload
  156. * @param {string} payload.includeSongs - include the songs
  157. * @returns {Promise} - returns promise (reject, resolve)
  158. */
  159. GET_ALL_GENRE_PLAYLISTS(payload) {
  160. return new Promise((resolve, reject) => {
  161. const includeObject = payload.includeSongs ? null : { songs: false };
  162. PlaylistsModule.playlistModel.find({ type: "genre" }, includeObject, (err, playlists) => {
  163. if (err) reject(new Error(err));
  164. else resolve({ playlists });
  165. });
  166. });
  167. }
  168. /**
  169. * Gets a genre playlist
  170. *
  171. * @param {object} payload - object that contains the payload
  172. * @param {string} payload.genre - the genre
  173. * @param {string} payload.includeSongs - include the songs
  174. * @returns {Promise} - returns promise (reject, resolve)
  175. */
  176. GET_GENRE_PLAYLIST(payload) {
  177. return new Promise((resolve, reject) => {
  178. const includeObject = payload.includeSongs ? null : { songs: false };
  179. PlaylistsModule.playlistModel.findOne(
  180. { type: "genre", createdFor: payload.genre },
  181. includeObject,
  182. (err, playlist) => {
  183. if (err) reject(new Error(err));
  184. else if (!playlist) reject(new Error("Playlist not found"));
  185. else resolve({ playlist });
  186. }
  187. );
  188. });
  189. }
  190. /**
  191. * Adds a song to a playlist
  192. *
  193. * @param {object} payload - object that contains the payload
  194. * @param {string} payload.playlistId - the playlist id
  195. * @param {string} payload.song - the song
  196. * @returns {Promise} - returns promise (reject, resolve)
  197. */
  198. ADD_SONG_TO_PLAYLIST(payload) {
  199. return new Promise((resolve, reject) => {
  200. const song = {
  201. _id: payload.song._id,
  202. songId: payload.song.songId,
  203. title: payload.song.title,
  204. duration: payload.song.duration
  205. };
  206. PlaylistsModule.playlistModel.updateOne(
  207. { _id: payload.playlistId },
  208. { $push: { songs: song } },
  209. { runValidators: true },
  210. err => {
  211. if (err) reject(new Error(err));
  212. else {
  213. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  214. .then(() => resolve())
  215. .catch(err => {
  216. reject(new Error(err));
  217. });
  218. }
  219. }
  220. );
  221. });
  222. }
  223. /**
  224. * Deletes a song from a playlist based on the songId
  225. *
  226. * @param {object} payload - object that contains the payload
  227. * @param {string} payload.playlistId - the playlist id
  228. * @param {string} payload.songId - the songId
  229. * @returns {Promise} - returns promise (reject, resolve)
  230. */
  231. DELETE_SONG_FROM_PLAYLIST_BY_SONGID(payload) {
  232. return new Promise((resolve, reject) => {
  233. PlaylistsModule.playlistModel.updateOne(
  234. { _id: payload.playlistId },
  235. { $pull: { songs: { songId: payload.songId } } },
  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. * Fills a genre playlist with songs
  251. *
  252. * @param {object} payload - object that contains the payload
  253. * @param {string} payload.genre - the genre
  254. * @returns {Promise} - returns promise (reject, resolve)
  255. */
  256. AUTOFILL_GENRE_PLAYLIST(payload) {
  257. return new Promise((resolve, reject) => {
  258. async.waterfall(
  259. [
  260. next => {
  261. PlaylistsModule.runJob(
  262. "GET_GENRE_PLAYLIST",
  263. { genre: payload.genre.toLowerCase(), includeSongs: true },
  264. this
  265. )
  266. .then(response => {
  267. next(null, { playlist: response.playlist });
  268. })
  269. .catch(err => {
  270. if (err.message === "Playlist not found") {
  271. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)
  272. .then(playlistId => {
  273. next(null, { playlist: { _id: playlistId, songs: [] } });
  274. })
  275. .catch(err => {
  276. next(err);
  277. });
  278. } else next(err);
  279. });
  280. },
  281. (data, next) => {
  282. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)
  283. .then(response => {
  284. data.songs = response.songs;
  285. next(null, data);
  286. })
  287. .catch(err => {
  288. console.log(err);
  289. next(err);
  290. });
  291. },
  292. (data, next) => {
  293. data.songsToDelete = [];
  294. data.songsToAdd = [];
  295. data.playlist.songs.forEach(playlistSong => {
  296. const found = data.songs.find(song => playlistSong.songId === song.songId);
  297. if (!found) data.songsToDelete.push(playlistSong);
  298. });
  299. data.songs.forEach(song => {
  300. const found = data.playlist.songs.find(playlistSong => song.songId === playlistSong.songId);
  301. if (!found) data.songsToAdd.push(song);
  302. });
  303. next(null, data);
  304. },
  305. (data, next) => {
  306. const promises = [];
  307. data.songsToAdd.forEach(song => {
  308. promises.push(
  309. PlaylistsModule.runJob(
  310. "ADD_SONG_TO_PLAYLIST",
  311. { playlistId: data.playlist._id, song },
  312. this
  313. )
  314. );
  315. });
  316. data.songsToDelete.forEach(song => {
  317. promises.push(
  318. PlaylistsModule.runJob(
  319. "DELETE_SONG_FROM_PLAYLIST_BY_SONGID",
  320. {
  321. playlistId: data.playlist._id,
  322. songId: song.songId
  323. },
  324. this
  325. )
  326. );
  327. });
  328. Promise.allSettled(promises)
  329. .then(() => {
  330. next();
  331. })
  332. .catch(err => {
  333. next(err);
  334. });
  335. }
  336. ],
  337. err => {
  338. if (err && err !== true) return reject(new Error(err));
  339. return resolve({});
  340. }
  341. );
  342. });
  343. }
  344. /**
  345. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  346. *
  347. * @param {object} payload - object that contains the payload
  348. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  349. * @returns {Promise} - returns promise (reject, resolve)
  350. */
  351. GET_PLAYLIST(payload) {
  352. return new Promise((resolve, reject) =>
  353. async.waterfall(
  354. [
  355. next => {
  356. CacheModule.runJob("HGETALL", { table: "playlists" }, this)
  357. .then(playlists => {
  358. next(null, playlists);
  359. })
  360. .catch(next);
  361. },
  362. (playlists, next) => {
  363. if (!playlists) return next();
  364. const playlistIds = Object.keys(playlists);
  365. return async.each(
  366. playlistIds,
  367. (playlistId, next) => {
  368. PlaylistsModule.playlistModel.findOne({ _id: playlistId }, (err, playlist) => {
  369. if (err) next(err);
  370. else if (!playlist) {
  371. CacheModule.runJob(
  372. "HDEL",
  373. {
  374. table: "playlists",
  375. key: playlistId
  376. },
  377. this
  378. )
  379. .then(() => next())
  380. .catch(next);
  381. } else next();
  382. });
  383. },
  384. next
  385. );
  386. },
  387. next => {
  388. CacheModule.runJob(
  389. "HGET",
  390. {
  391. table: "playlists",
  392. key: payload.playlistId
  393. },
  394. this
  395. )
  396. .then(playlist => next(null, playlist))
  397. .catch(next);
  398. },
  399. (playlist, next) => {
  400. if (playlist) return next(true, playlist);
  401. return PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  402. },
  403. (playlist, next) => {
  404. if (playlist) {
  405. CacheModule.runJob(
  406. "HSET",
  407. {
  408. table: "playlists",
  409. key: payload.playlistId,
  410. value: playlist
  411. },
  412. this
  413. )
  414. .then(playlist => {
  415. next(null, playlist);
  416. })
  417. .catch(next);
  418. } else next("Playlist not found");
  419. }
  420. ],
  421. (err, playlist) => {
  422. if (err && err !== true) return reject(new Error(err));
  423. return resolve(playlist);
  424. }
  425. )
  426. );
  427. }
  428. /**
  429. * Gets a playlist from id from Mongo and updates the cache with it
  430. *
  431. * @param {object} payload - object that contains the payload
  432. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  433. * @returns {Promise} - returns promise (reject, resolve)
  434. */
  435. UPDATE_PLAYLIST(payload) {
  436. // playlistId, cb
  437. return new Promise((resolve, reject) =>
  438. async.waterfall(
  439. [
  440. next => {
  441. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  442. },
  443. (playlist, next) => {
  444. if (!playlist) {
  445. CacheModule.runJob("HDEL", {
  446. table: "playlists",
  447. key: payload.playlistId
  448. });
  449. return next("Playlist not found");
  450. }
  451. return CacheModule.runJob(
  452. "HSET",
  453. {
  454. table: "playlists",
  455. key: payload.playlistId,
  456. value: playlist
  457. },
  458. this
  459. )
  460. .then(playlist => {
  461. next(null, playlist);
  462. })
  463. .catch(next);
  464. }
  465. ],
  466. (err, playlist) => {
  467. if (err && err !== true) return reject(new Error(err));
  468. return resolve(playlist);
  469. }
  470. )
  471. );
  472. }
  473. /**
  474. * Deletes playlist from id from Mongo and cache
  475. *
  476. * @param {object} payload - object that contains the payload
  477. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  478. * @returns {Promise} - returns promise (reject, resolve)
  479. */
  480. DELETE_PLAYLIST(payload) {
  481. // playlistId, cb
  482. return new Promise((resolve, reject) =>
  483. async.waterfall(
  484. [
  485. next => {
  486. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  487. },
  488. (res, next) => {
  489. CacheModule.runJob(
  490. "HDEL",
  491. {
  492. table: "playlists",
  493. key: payload.playlistId
  494. },
  495. this
  496. )
  497. .then(() => next())
  498. .catch(next);
  499. }
  500. ],
  501. err => {
  502. if (err && err !== true) return reject(new Error(err));
  503. return resolve();
  504. }
  505. )
  506. );
  507. }
  508. }
  509. export default new _PlaylistsModule();