playlists.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 => next(null, playlists))
  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. return new Promise((resolve, reject) =>
  437. async.waterfall(
  438. [
  439. next => {
  440. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  441. },
  442. (playlist, next) => {
  443. if (!playlist) {
  444. CacheModule.runJob("HDEL", {
  445. table: "playlists",
  446. key: payload.playlistId
  447. });
  448. return next("Playlist not found");
  449. }
  450. return CacheModule.runJob(
  451. "HSET",
  452. {
  453. table: "playlists",
  454. key: payload.playlistId,
  455. value: playlist
  456. },
  457. this
  458. )
  459. .then(playlist => {
  460. next(null, playlist);
  461. })
  462. .catch(next);
  463. }
  464. ],
  465. (err, playlist) => {
  466. if (err && err !== true) return reject(new Error(err));
  467. return resolve(playlist);
  468. }
  469. )
  470. );
  471. }
  472. /**
  473. * Deletes playlist from id from Mongo and cache
  474. *
  475. * @param {object} payload - object that contains the payload
  476. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  477. * @returns {Promise} - returns promise (reject, resolve)
  478. */
  479. DELETE_PLAYLIST(payload) {
  480. return new Promise((resolve, reject) =>
  481. async.waterfall(
  482. [
  483. next => {
  484. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  485. },
  486. (res, next) => {
  487. CacheModule.runJob(
  488. "HDEL",
  489. {
  490. table: "playlists",
  491. key: payload.playlistId
  492. },
  493. this
  494. )
  495. .then(() => next())
  496. .catch(next);
  497. }
  498. ],
  499. err => {
  500. if (err && err !== true) return reject(new Error(err));
  501. return resolve();
  502. }
  503. )
  504. );
  505. }
  506. }
  507. export default new _PlaylistsModule();