playlists.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  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 all station playlists
  189. *
  190. * @param {object} payload - object that contains the payload
  191. * @param {string} payload.includeSongs - include the songs
  192. * @returns {Promise} - returns promise (reject, resolve)
  193. */
  194. GET_ALL_STATION_PLAYLISTS(payload) {
  195. return new Promise((resolve, reject) => {
  196. const includeObject = payload.includeSongs ? null : { songs: false };
  197. PlaylistsModule.playlistModel.find({ type: "station" }, includeObject, (err, playlists) => {
  198. if (err) reject(new Error(err));
  199. else resolve({ playlists });
  200. });
  201. });
  202. }
  203. /**
  204. * Gets a genre playlist
  205. *
  206. * @param {object} payload - object that contains the payload
  207. * @param {string} payload.genre - the genre
  208. * @param {string} payload.includeSongs - include the songs
  209. * @returns {Promise} - returns promise (reject, resolve)
  210. */
  211. GET_GENRE_PLAYLIST(payload) {
  212. return new Promise((resolve, reject) => {
  213. const includeObject = payload.includeSongs ? null : { songs: false };
  214. PlaylistsModule.playlistModel.findOne(
  215. { type: "genre", createdFor: payload.genre },
  216. includeObject,
  217. (err, playlist) => {
  218. if (err) reject(new Error(err));
  219. else if (!playlist) reject(new Error("Playlist not found"));
  220. else resolve({ playlist });
  221. }
  222. );
  223. });
  224. }
  225. /**
  226. * Gets all missing genre playlists
  227. *
  228. * @returns {Promise} - returns promise (reject, resolve)
  229. */
  230. GET_MISSING_GENRE_PLAYLISTS() {
  231. return new Promise((resolve, reject) => {
  232. SongsModule.runJob("GET_ALL_GENRES", {}, this)
  233. .then(response => {
  234. const { genres } = response;
  235. const missingGenres = [];
  236. async.eachLimit(
  237. genres,
  238. 1,
  239. (genre, next) => {
  240. PlaylistsModule.runJob(
  241. "GET_GENRE_PLAYLIST",
  242. { genre: genre.toLowerCase(), includeSongs: false },
  243. this
  244. )
  245. .then(() => {
  246. next();
  247. })
  248. .catch(err => {
  249. if (err.message === "Playlist not found") {
  250. missingGenres.push(genre);
  251. next();
  252. } else next(err);
  253. });
  254. },
  255. err => {
  256. if (err) reject(err);
  257. else resolve({ genres: missingGenres });
  258. }
  259. );
  260. })
  261. .catch(err => {
  262. reject(err);
  263. });
  264. });
  265. }
  266. /**
  267. * Creates all missing genre playlists
  268. *
  269. * @returns {Promise} - returns promise (reject, resolve)
  270. */
  271. CREATE_MISSING_GENRE_PLAYLISTS() {
  272. return new Promise((resolve, reject) => {
  273. PlaylistsModule.runJob("GET_MISSING_GENRE_PLAYLISTS", {}, this)
  274. .then(response => {
  275. const { genres } = response;
  276. async.eachLimit(
  277. genres,
  278. 1,
  279. (genre, next) => {
  280. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre }, this)
  281. .then(() => {
  282. next();
  283. })
  284. .catch(err => {
  285. next(err);
  286. });
  287. },
  288. err => {
  289. if (err) reject(err);
  290. else resolve();
  291. }
  292. );
  293. })
  294. .catch(err => {
  295. reject(err);
  296. });
  297. });
  298. }
  299. /**
  300. * Gets a station playlist
  301. *
  302. * @param {object} payload - object that contains the payload
  303. * @param {string} payload.staationId - the station id
  304. * @param {string} payload.includeSongs - include the songs
  305. * @returns {Promise} - returns promise (reject, resolve)
  306. */
  307. GET_STATION_PLAYLIST(payload) {
  308. return new Promise((resolve, reject) => {
  309. const includeObject = payload.includeSongs ? null : { songs: false };
  310. PlaylistsModule.playlistModel.findOne(
  311. { type: "station", createdFor: payload.stationId },
  312. includeObject,
  313. (err, playlist) => {
  314. if (err) reject(new Error(err));
  315. else if (!playlist) reject(new Error("Playlist not found"));
  316. else resolve({ playlist });
  317. }
  318. );
  319. });
  320. }
  321. /**
  322. * Adds a song to a playlist
  323. *
  324. * @param {object} payload - object that contains the payload
  325. * @param {string} payload.playlistId - the playlist id
  326. * @param {string} payload.song - the song
  327. * @returns {Promise} - returns promise (reject, resolve)
  328. */
  329. ADD_SONG_TO_PLAYLIST(payload) {
  330. return new Promise((resolve, reject) => {
  331. const { _id, youtubeId, title, artists, thumbnail, duration, status } = payload.song;
  332. const trimmedSong = {
  333. _id,
  334. youtubeId,
  335. title,
  336. artists,
  337. thumbnail,
  338. duration,
  339. status
  340. };
  341. PlaylistsModule.playlistModel.updateOne(
  342. { _id: payload.playlistId },
  343. { $push: { songs: trimmedSong } },
  344. { runValidators: true },
  345. err => {
  346. if (err) reject(new Error(err));
  347. else {
  348. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  349. .then(() => resolve())
  350. .catch(err => {
  351. reject(new Error(err));
  352. });
  353. }
  354. }
  355. );
  356. });
  357. }
  358. /**
  359. * Deletes a song from a playlist based on the youtube id
  360. *
  361. * @param {object} payload - object that contains the payload
  362. * @param {string} payload.playlistId - the playlist id
  363. * @param {string} payload.youtubeId - the youtube id
  364. * @returns {Promise} - returns promise (reject, resolve)
  365. */
  366. DELETE_SONG_FROM_PLAYLIST_BY_YOUTUBE_ID(payload) {
  367. return new Promise((resolve, reject) => {
  368. PlaylistsModule.playlistModel.updateOne(
  369. { _id: payload.playlistId },
  370. { $pull: { songs: { youtubeId: payload.youtubeId } } },
  371. err => {
  372. if (err) reject(new Error(err));
  373. else {
  374. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  375. .then(() => resolve())
  376. .catch(err => {
  377. reject(new Error(err));
  378. });
  379. }
  380. }
  381. );
  382. });
  383. }
  384. /**
  385. * Fills a genre playlist with songs
  386. *
  387. * @param {object} payload - object that contains the payload
  388. * @param {string} payload.genre - the genre
  389. * @returns {Promise} - returns promise (reject, resolve)
  390. */
  391. AUTOFILL_GENRE_PLAYLIST(payload) {
  392. return new Promise((resolve, reject) => {
  393. async.waterfall(
  394. [
  395. next => {
  396. PlaylistsModule.runJob(
  397. "GET_GENRE_PLAYLIST",
  398. { genre: payload.genre.toLowerCase(), includeSongs: true },
  399. this
  400. )
  401. .then(response => {
  402. next(null, response.playlist._id);
  403. })
  404. .catch(err => {
  405. if (err.message === "Playlist not found") {
  406. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)
  407. .then(playlistId => {
  408. next(null, playlistId);
  409. })
  410. .catch(err => {
  411. next(err);
  412. });
  413. } else next(err);
  414. });
  415. },
  416. (playlistId, next) => {
  417. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)
  418. .then(response => {
  419. next(null, playlistId, response.songs);
  420. })
  421. .catch(err => {
  422. console.log(err);
  423. next(err);
  424. });
  425. },
  426. (playlistId, _songs, next) => {
  427. const songs = _songs.map(song => {
  428. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  429. return {
  430. _id,
  431. youtubeId,
  432. title,
  433. artists,
  434. thumbnail,
  435. duration,
  436. status
  437. };
  438. });
  439. PlaylistsModule.playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, err => {
  440. next(err, playlistId);
  441. });
  442. },
  443. (playlistId, next) => {
  444. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  445. .then(() => {
  446. next(null, playlistId);
  447. })
  448. .catch(next);
  449. },
  450. // (data, next) => {
  451. // data.songsToDelete = [];
  452. // data.songsToAdd = [];
  453. // data.playlist.songs.forEach(playlistSong => {
  454. // const found = data.songs.find(song => playlistSong.youtubeId === song.youtubeId);
  455. // if (!found) data.songsToDelete.push(playlistSong);
  456. // });
  457. // data.songs.forEach(song => {
  458. // const found = data.playlist.songs.find(playlistSong => song.youtubeId === playlistSong.youtubeId);
  459. // if (!found) data.songsToAdd.push(song);
  460. // });
  461. // next(null, data);
  462. // },
  463. // (data, next) => {
  464. // const promises = [];
  465. // data.songsToAdd.forEach(song => {
  466. // promises.push(
  467. // PlaylistsModule.runJob(
  468. // "ADD_SONG_TO_PLAYLIST",
  469. // { playlistId: data.playlist._id, song },
  470. // this
  471. // )
  472. // );
  473. // });
  474. // data.songsToDelete.forEach(song => {
  475. // promises.push(
  476. // PlaylistsModule.runJob(
  477. // "DELETE_SONG_FROM_PLAYLIST_BY_YOUTUBE_ID",
  478. // {
  479. // playlistId: data.playlist._id,
  480. // youtubeId: song.youtubeId
  481. // },
  482. // this
  483. // )
  484. // );
  485. // });
  486. // Promise.allSettled(promises)
  487. // .then(() => {
  488. // next(null, data.playlist._id);
  489. // })
  490. // .catch(err => {
  491. // next(err);
  492. // });
  493. // },
  494. (playlistId, next) => {
  495. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  496. .then(response => {
  497. response.stationIds.forEach(stationId => {
  498. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  499. });
  500. })
  501. .catch();
  502. next();
  503. }
  504. ],
  505. err => {
  506. if (err && err !== true) return reject(new Error(err));
  507. return resolve({});
  508. }
  509. );
  510. });
  511. }
  512. /**
  513. * Gets orphaned genre playlists
  514. *
  515. * @returns {Promise} - returns promise (reject, resolve)
  516. */
  517. GET_ORPHANED_GENRE_PLAYLISTS() {
  518. return new Promise((resolve, reject) => {
  519. PlaylistsModule.playlistModel.find({ type: "genre" }, { songs: false }, (err, playlists) => {
  520. if (err) reject(new Error(err));
  521. else {
  522. const orphanedPlaylists = [];
  523. async.eachLimit(
  524. playlists,
  525. 1,
  526. (playlist, next) => {
  527. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: playlist.createdFor }, this)
  528. .then(response => {
  529. if (response.songs.length === 0) {
  530. StationsModule.runJob(
  531. "GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST",
  532. { playlistId: playlist._id },
  533. this
  534. )
  535. .then(response => {
  536. if (response.stationIds.length === 0) orphanedPlaylists.push(playlist);
  537. next();
  538. })
  539. .catch(next);
  540. } else next();
  541. })
  542. .catch(next);
  543. },
  544. err => {
  545. if (err) reject(new Error(err));
  546. else resolve({ playlists: orphanedPlaylists });
  547. }
  548. );
  549. }
  550. });
  551. });
  552. }
  553. /**
  554. * Deletes all orphaned genre playlists
  555. *
  556. * @returns {Promise} - returns promise (reject, resolve)
  557. */
  558. DELETE_ORPHANED_GENRE_PLAYLISTS() {
  559. return new Promise((resolve, reject) => {
  560. PlaylistsModule.runJob("GET_ORPHANED_GENRE_PLAYLISTS", {}, this)
  561. .then(response => {
  562. async.eachLimit(
  563. response.playlists,
  564. 1,
  565. (playlist, next) => {
  566. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  567. .then(() => {
  568. this.log("INFO", "Deleting orphaned genre playlist");
  569. next();
  570. })
  571. .catch(err => {
  572. next(err);
  573. });
  574. },
  575. err => {
  576. if (err) reject(new Error(err));
  577. else resolve({});
  578. }
  579. );
  580. })
  581. .catch(err => {
  582. reject(new Error(err));
  583. });
  584. });
  585. }
  586. /**
  587. * Gets a orphaned station playlists
  588. *
  589. * @returns {Promise} - returns promise (reject, resolve)
  590. */
  591. GET_ORPHANED_STATION_PLAYLISTS() {
  592. return new Promise((resolve, reject) => {
  593. PlaylistsModule.playlistModel.find({ type: "station" }, { songs: false }, (err, playlists) => {
  594. if (err) reject(new Error(err));
  595. else {
  596. const orphanedPlaylists = [];
  597. async.eachLimit(
  598. playlists,
  599. 1,
  600. (playlist, next) => {
  601. StationsModule.runJob("GET_STATION", { stationId: playlist.createdFor }, this)
  602. .then(station => {
  603. if (station.playlist !== playlist._id.toString()) {
  604. orphanedPlaylists.push(playlist);
  605. }
  606. next();
  607. })
  608. .catch(err => {
  609. if (err.message === "Station not found") {
  610. orphanedPlaylists.push(playlist);
  611. next();
  612. } else next(err);
  613. });
  614. },
  615. err => {
  616. if (err) reject(new Error(err));
  617. else resolve({ playlists: orphanedPlaylists });
  618. }
  619. );
  620. }
  621. });
  622. });
  623. }
  624. /**
  625. * Deletes all orphaned station playlists
  626. *
  627. * @returns {Promise} - returns promise (reject, resolve)
  628. */
  629. DELETE_ORPHANED_STATION_PLAYLISTS() {
  630. return new Promise((resolve, reject) => {
  631. PlaylistsModule.runJob("GET_ORPHANED_STATION_PLAYLISTS", {}, this)
  632. .then(response => {
  633. async.eachLimit(
  634. response.playlists,
  635. 1,
  636. (playlist, next) => {
  637. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  638. .then(() => {
  639. this.log("INFO", "Deleting orphaned station playlist");
  640. next();
  641. })
  642. .catch(err => {
  643. next(err);
  644. });
  645. },
  646. err => {
  647. if (err) reject(new Error(err));
  648. else resolve({});
  649. }
  650. );
  651. })
  652. .catch(err => {
  653. reject(new Error(err));
  654. });
  655. });
  656. }
  657. /**
  658. * Fills a station playlist with songs
  659. *
  660. * @param {object} payload - object that contains the payload
  661. * @param {string} payload.stationId - the station id
  662. * @returns {Promise} - returns promise (reject, resolve)
  663. */
  664. AUTOFILL_STATION_PLAYLIST(payload) {
  665. return new Promise((resolve, reject) => {
  666. let originalPlaylist = null;
  667. async.waterfall(
  668. [
  669. next => {
  670. if (!payload.stationId) next("Please specify a station id");
  671. else next();
  672. },
  673. next => {
  674. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  675. .then(station => {
  676. next(null, station);
  677. })
  678. .catch(next);
  679. },
  680. (station, next) => {
  681. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: station.playlist }, this)
  682. .then(playlist => {
  683. originalPlaylist = playlist;
  684. next(null, station);
  685. })
  686. .catch(err => {
  687. next(err);
  688. });
  689. },
  690. (station, next) => {
  691. const includedPlaylists = [];
  692. async.eachLimit(
  693. station.includedPlaylists,
  694. 1,
  695. (playlistId, next) => {
  696. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  697. .then(playlist => {
  698. includedPlaylists.push(playlist);
  699. next();
  700. })
  701. .catch(next);
  702. },
  703. err => {
  704. next(err, station, includedPlaylists);
  705. }
  706. );
  707. },
  708. (station, includedPlaylists, next) => {
  709. const excludedPlaylists = [];
  710. async.eachLimit(
  711. station.excludedPlaylists,
  712. 1,
  713. (playlistId, next) => {
  714. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  715. .then(playlist => {
  716. excludedPlaylists.push(playlist);
  717. next();
  718. })
  719. .catch(next);
  720. },
  721. err => {
  722. next(err, station, includedPlaylists, excludedPlaylists);
  723. }
  724. );
  725. },
  726. (station, includedPlaylists, excludedPlaylists, next) => {
  727. const excludedSongs = excludedPlaylists
  728. .flatMap(excludedPlaylist => excludedPlaylist.songs)
  729. .reduce(
  730. (items, item) =>
  731. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  732. []
  733. );
  734. const includedSongs = includedPlaylists
  735. .flatMap(includedPlaylist => includedPlaylist.songs)
  736. .reduce(
  737. (songs, song) =>
  738. songs.find(x => x.youtubeId === song.youtubeId) ? [...songs] : [...songs, song],
  739. []
  740. )
  741. .filter(song => !excludedSongs.find(x => x.youtubeId === song.youtubeId));
  742. next(null, station, includedSongs);
  743. },
  744. (station, includedSongs, next) => {
  745. PlaylistsModule.playlistModel.updateOne(
  746. { _id: station.playlist },
  747. { $set: { songs: includedSongs } },
  748. err => {
  749. next(err, includedSongs);
  750. }
  751. );
  752. },
  753. (includedSongs, next) => {
  754. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: originalPlaylist._id }, this)
  755. .then(() => {
  756. next(null, includedSongs);
  757. })
  758. .catch(next);
  759. },
  760. (includedSongs, next) => {
  761. if (originalPlaylist.songs.length === 0 && includedSongs.length > 0)
  762. StationsModule.runJob("SKIP_STATION", { stationId: payload.stationId, natural: false });
  763. next();
  764. }
  765. ],
  766. err => {
  767. if (err && err !== true) return reject(new Error(err));
  768. return resolve({});
  769. }
  770. );
  771. });
  772. }
  773. /**
  774. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  775. *
  776. * @param {object} payload - object that contains the payload
  777. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  778. * @returns {Promise} - returns promise (reject, resolve)
  779. */
  780. GET_PLAYLIST(payload) {
  781. return new Promise((resolve, reject) =>
  782. async.waterfall(
  783. [
  784. next => {
  785. CacheModule.runJob(
  786. "HGET",
  787. {
  788. table: "playlists",
  789. key: payload.playlistId
  790. },
  791. this
  792. )
  793. .then(playlist => next(null, playlist))
  794. .catch(next);
  795. },
  796. (playlist, next) => {
  797. if (playlist)
  798. PlaylistsModule.playlistModel.exists({ _id: payload.playlistId }, (err, exists) => {
  799. if (err) next(err);
  800. else if (exists) next(null, playlist);
  801. else {
  802. CacheModule.runJob(
  803. "HDEL",
  804. {
  805. table: "playlists",
  806. key: payload.playlistId
  807. },
  808. this
  809. )
  810. .then(() => next())
  811. .catch(next);
  812. }
  813. });
  814. else PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  815. },
  816. (playlist, next) => {
  817. if (playlist) {
  818. CacheModule.runJob(
  819. "HSET",
  820. {
  821. table: "playlists",
  822. key: payload.playlistId,
  823. value: playlist
  824. },
  825. this
  826. )
  827. .then(playlist => {
  828. next(null, playlist);
  829. })
  830. .catch(next);
  831. } else next("Playlist not found");
  832. }
  833. ],
  834. (err, playlist) => {
  835. if (err && err !== true) return reject(new Error(err));
  836. return resolve(playlist);
  837. }
  838. )
  839. );
  840. }
  841. /**
  842. * Gets a playlist from id from Mongo and updates the cache with it
  843. *
  844. * @param {object} payload - object that contains the payload
  845. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  846. * @returns {Promise} - returns promise (reject, resolve)
  847. */
  848. UPDATE_PLAYLIST(payload) {
  849. return new Promise((resolve, reject) =>
  850. async.waterfall(
  851. [
  852. next => {
  853. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  854. },
  855. (playlist, next) => {
  856. if (!playlist) {
  857. CacheModule.runJob("HDEL", {
  858. table: "playlists",
  859. key: payload.playlistId
  860. });
  861. return next("Playlist not found");
  862. }
  863. return CacheModule.runJob(
  864. "HSET",
  865. {
  866. table: "playlists",
  867. key: payload.playlistId,
  868. value: playlist
  869. },
  870. this
  871. )
  872. .then(playlist => {
  873. next(null, playlist);
  874. })
  875. .catch(next);
  876. }
  877. ],
  878. (err, playlist) => {
  879. if (err && err !== true) return reject(new Error(err));
  880. return resolve(playlist);
  881. }
  882. )
  883. );
  884. }
  885. /**
  886. * Deletes playlist from id from Mongo and cache
  887. *
  888. * @param {object} payload - object that contains the payload
  889. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  890. * @returns {Promise} - returns promise (reject, resolve)
  891. */
  892. DELETE_PLAYLIST(payload) {
  893. return new Promise((resolve, reject) =>
  894. async.waterfall(
  895. [
  896. next => {
  897. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  898. },
  899. (res, next) => {
  900. CacheModule.runJob(
  901. "HDEL",
  902. {
  903. table: "playlists",
  904. key: payload.playlistId
  905. },
  906. this
  907. )
  908. .then(() => next())
  909. .catch(next);
  910. }
  911. ],
  912. err => {
  913. if (err && err !== true) return reject(new Error(err));
  914. return resolve();
  915. }
  916. )
  917. );
  918. }
  919. /**
  920. * Searches through playlists
  921. *
  922. * @param {object} payload - object that contains the payload
  923. * @param {string} payload.query - the query
  924. * @param {string} payload.includePrivate - include private playlists
  925. * @param {string} payload.includeStation - include station playlists
  926. * @param {string} payload.includeUser - include user playlists
  927. * @param {string} payload.includeGenre - include genre playlists
  928. * @param {string} payload.includeOwn - include own user playlists
  929. * @param {string} payload.userId - the user id of the person requesting
  930. * @param {string} payload.includeSongs - include songs
  931. * @param {string} payload.page - page (default 1)
  932. * @returns {Promise} - returns promise (reject, resolve)
  933. */
  934. SEARCH(payload) {
  935. return new Promise((resolve, reject) =>
  936. async.waterfall(
  937. [
  938. next => {
  939. const types = [];
  940. if (payload.includeStation) types.push("station");
  941. if (payload.includeUser) types.push("user");
  942. if (payload.includeGenre) types.push("genre");
  943. if (types.length === 0 && !payload.includeOwn) return next("No types have been included.");
  944. const privacies = ["public"];
  945. if (payload.includePrivate) privacies.push("private");
  946. const includeObject = payload.includeSongs ? null : { songs: false };
  947. const filterArray = [
  948. {
  949. displayName: new RegExp(`${payload.query}`, "i"),
  950. privacy: { $in: privacies },
  951. type: { $in: types }
  952. }
  953. ];
  954. if (payload.includeOwn && payload.userId)
  955. filterArray.push({
  956. displayName: new RegExp(`${payload.query}`, "i"),
  957. type: "user",
  958. createdBy: payload.userId
  959. });
  960. return next(null, filterArray, includeObject);
  961. },
  962. (filterArray, includeObject, next) => {
  963. const page = payload.page ? payload.page : 1;
  964. const pageSize = 15;
  965. const skipAmount = pageSize * (page - 1);
  966. PlaylistsModule.playlistModel.find({ $or: filterArray }).count((err, count) => {
  967. if (err) next(err);
  968. else {
  969. PlaylistsModule.playlistModel
  970. .find({ $or: filterArray }, includeObject)
  971. .skip(skipAmount)
  972. .limit(pageSize)
  973. .exec((err, playlists) => {
  974. if (err) next(err);
  975. else {
  976. next(null, {
  977. playlists,
  978. page,
  979. pageSize,
  980. skipAmount,
  981. count
  982. });
  983. }
  984. });
  985. }
  986. });
  987. },
  988. (data, next) => {
  989. if (data.playlists.length > 0) next(null, data);
  990. else next("No playlists found");
  991. }
  992. ],
  993. (err, data) => {
  994. if (err && err !== true) return reject(new Error(err));
  995. return resolve(data);
  996. }
  997. )
  998. );
  999. }
  1000. /**
  1001. * Clears and refills a station playlist
  1002. *
  1003. * @param {object} payload - object that contains the payload
  1004. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1005. * @returns {Promise} - returns promise (reject, resolve)
  1006. */
  1007. CLEAR_AND_REFILL_STATION_PLAYLIST(payload) {
  1008. return new Promise((resolve, reject) => {
  1009. const { playlistId } = payload;
  1010. async.waterfall(
  1011. [
  1012. next => {
  1013. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1014. .then(playlist => {
  1015. next(null, playlist);
  1016. })
  1017. .catch(err => {
  1018. next(err);
  1019. });
  1020. },
  1021. (playlist, next) => {
  1022. if (playlist.type !== "station") next("This playlist is not a station playlist.");
  1023. else next(null, playlist.createdFor);
  1024. },
  1025. (stationId, next) => {
  1026. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)
  1027. .then(() => {
  1028. next();
  1029. })
  1030. .catch(err => {
  1031. next(err);
  1032. });
  1033. }
  1034. ],
  1035. err => {
  1036. if (err && err !== true) return reject(new Error(err));
  1037. return resolve();
  1038. }
  1039. );
  1040. });
  1041. }
  1042. /**
  1043. * Clears and refills a genre playlist
  1044. *
  1045. * @param {object} payload - object that contains the payload
  1046. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1047. * @returns {Promise} - returns promise (reject, resolve)
  1048. */
  1049. CLEAR_AND_REFILL_GENRE_PLAYLIST(payload) {
  1050. return new Promise((resolve, reject) => {
  1051. const { playlistId } = payload;
  1052. async.waterfall(
  1053. [
  1054. next => {
  1055. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1056. .then(playlist => {
  1057. next(null, playlist);
  1058. })
  1059. .catch(err => {
  1060. next(err);
  1061. });
  1062. },
  1063. (playlist, next) => {
  1064. if (playlist.type !== "genre") next("This playlist is not a genre playlist.");
  1065. else next(null, playlist.createdFor);
  1066. },
  1067. (genre, next) => {
  1068. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }, this)
  1069. .then(() => {
  1070. next();
  1071. })
  1072. .catch(err => {
  1073. next(err);
  1074. });
  1075. }
  1076. ],
  1077. err => {
  1078. if (err && err !== true) return reject(new Error(err));
  1079. return resolve();
  1080. }
  1081. );
  1082. });
  1083. }
  1084. }
  1085. export default new _PlaylistsModule();