playlists.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  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. let RatingsModule;
  10. let WSModule;
  11. class _PlaylistsModule extends CoreClass {
  12. // eslint-disable-next-line require-jsdoc
  13. constructor() {
  14. super("playlists");
  15. PlaylistsModule = this;
  16. }
  17. /**
  18. * Initialises the playlists module
  19. *
  20. * @returns {Promise} - returns promise (reject, resolve)
  21. */
  22. async initialize() {
  23. this.setStage(1);
  24. StationsModule = this.moduleManager.modules.stations;
  25. CacheModule = this.moduleManager.modules.cache;
  26. DBModule = this.moduleManager.modules.db;
  27. UtilsModule = this.moduleManager.modules.utils;
  28. SongsModule = this.moduleManager.modules.songs;
  29. RatingsModule = this.moduleManager.modules.ratings;
  30. WSModule = this.moduleManager.modules.ws;
  31. this.playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" });
  32. this.playlistSchemaCache = await CacheModule.runJob("GET_SCHEMA", { schemaName: "playlist" });
  33. CacheModule.runJob("SUB", {
  34. channel: "playlist.updated",
  35. cb: async data => {
  36. PlaylistsModule.playlistModel.findOne(
  37. { _id: data.playlistId },
  38. ["_id", "displayName", "type", "privacy", "songs", "createdBy", "createdAt", "createdFor"],
  39. (err, playlist) => {
  40. const newPlaylist = {
  41. ...playlist._doc,
  42. songsCount: playlist.songs.length,
  43. songsLength: playlist.songs.reduce(
  44. (previous, current) => ({
  45. duration: previous.duration + current.duration
  46. }),
  47. { duration: 0 }
  48. ).duration
  49. };
  50. delete newPlaylist.songs;
  51. WSModule.runJob("EMIT_TO_ROOM", {
  52. room: "admin.playlists",
  53. args: ["event:admin.playlist.updated", { data: { playlist: newPlaylist } }]
  54. });
  55. }
  56. );
  57. }
  58. });
  59. this.setStage(2);
  60. return new Promise((resolve, reject) => {
  61. async.waterfall(
  62. [
  63. next => {
  64. this.setStage(3);
  65. CacheModule.runJob("HGETALL", { table: "playlists" })
  66. .then(playlists => {
  67. next(null, playlists);
  68. })
  69. .catch(next);
  70. },
  71. (playlists, next) => {
  72. this.setStage(4);
  73. if (!playlists) return next();
  74. const playlistIds = Object.keys(playlists);
  75. return async.each(
  76. playlistIds,
  77. (playlistId, next) => {
  78. PlaylistsModule.playlistModel.findOne({ _id: playlistId }, (err, playlist) => {
  79. if (err) next(err);
  80. else if (!playlist) {
  81. CacheModule.runJob("HDEL", {
  82. table: "playlists",
  83. key: playlistId
  84. })
  85. .then(() => next())
  86. .catch(next);
  87. } else next();
  88. });
  89. },
  90. next
  91. );
  92. },
  93. next => {
  94. this.setStage(5);
  95. PlaylistsModule.playlistModel.find({}, next);
  96. },
  97. (playlists, next) => {
  98. this.setStage(6);
  99. async.each(
  100. playlists,
  101. (playlist, cb) => {
  102. CacheModule.runJob("HSET", {
  103. table: "playlists",
  104. key: playlist._id,
  105. value: PlaylistsModule.playlistSchemaCache(playlist)
  106. })
  107. .then(() => cb())
  108. .catch(next);
  109. },
  110. next
  111. );
  112. }
  113. ],
  114. async err => {
  115. if (err) {
  116. const formattedErr = await UtilsModule.runJob("GET_ERROR", {
  117. error: err
  118. });
  119. reject(new Error(formattedErr));
  120. } else {
  121. resolve();
  122. }
  123. }
  124. );
  125. });
  126. }
  127. /**
  128. * Returns a list of playlists that include a specific song
  129. *
  130. * @param {object} payload - object that contains the payload
  131. * @param {string} payload.songId - the song id
  132. * @param {string} payload.includeSongs - include the songs
  133. * @returns {Promise} - returns promise (reject, resolve)
  134. */
  135. GET_PLAYLISTS_WITH_SONG(payload) {
  136. return new Promise((resolve, reject) => {
  137. const includeObject = payload.includeSongs ? null : { songs: false };
  138. PlaylistsModule.playlistModel.find({ "songs._id": payload.songId }, includeObject, (err, playlists) => {
  139. if (err) reject(err);
  140. else resolve({ playlists });
  141. });
  142. });
  143. }
  144. /**
  145. * Creates a playlist owned by a user
  146. *
  147. * @param {object} payload - object that contains the payload
  148. * @param {string} payload.userId - the id of the user to create the playlist for
  149. * @param {string} payload.displayName - the display name of the playlist
  150. * @param {string} payload.type - the type of the playlist
  151. * @returns {Promise} - returns promise (reject, resolve)
  152. */
  153. CREATE_USER_PLAYLIST(payload) {
  154. return new Promise((resolve, reject) => {
  155. PlaylistsModule.playlistModel.create(
  156. {
  157. displayName: payload.displayName,
  158. songs: [],
  159. createdBy: payload.userId,
  160. createdAt: Date.now(),
  161. createdFor: null,
  162. type: payload.type
  163. },
  164. (err, playlist) => {
  165. if (err) return reject(new Error(err));
  166. return resolve(playlist._id);
  167. }
  168. );
  169. });
  170. }
  171. /**
  172. * Creates a playlist that contains all songs of a specific genre
  173. *
  174. * @param {object} payload - object that contains the payload
  175. * @param {string} payload.genre - the genre
  176. * @returns {Promise} - returns promise (reject, resolve)
  177. */
  178. CREATE_GENRE_PLAYLIST(payload) {
  179. return new Promise((resolve, reject) => {
  180. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre: payload.genre.toLowerCase() }, this)
  181. .then(() => {
  182. reject(new Error("Playlist already exists"));
  183. })
  184. .catch(err => {
  185. if (err.message === "Playlist not found") {
  186. PlaylistsModule.playlistModel.create(
  187. {
  188. displayName: `Genre - ${payload.genre}`,
  189. songs: [],
  190. createdBy: "Musare",
  191. createdFor: `${payload.genre.toLowerCase()}`,
  192. createdAt: Date.now(),
  193. type: "genre"
  194. },
  195. (err, playlist) => {
  196. if (err) return reject(new Error(err));
  197. return resolve(playlist._id);
  198. }
  199. );
  200. } else reject(new Error(err));
  201. });
  202. });
  203. }
  204. /**
  205. * Gets all genre playlists
  206. *
  207. * @param {object} payload - object that contains the payload
  208. * @param {string} payload.includeSongs - include the songs
  209. * @returns {Promise} - returns promise (reject, resolve)
  210. */
  211. GET_ALL_GENRE_PLAYLISTS(payload) {
  212. return new Promise((resolve, reject) => {
  213. const includeObject = payload.includeSongs ? null : { songs: false };
  214. PlaylistsModule.playlistModel.find({ type: "genre" }, includeObject, (err, playlists) => {
  215. if (err) reject(new Error(err));
  216. else resolve({ playlists });
  217. });
  218. });
  219. }
  220. /**
  221. * Gets all station playlists
  222. *
  223. * @param {object} payload - object that contains the payload
  224. * @param {string} payload.includeSongs - include the songs
  225. * @returns {Promise} - returns promise (reject, resolve)
  226. */
  227. GET_ALL_STATION_PLAYLISTS(payload) {
  228. return new Promise((resolve, reject) => {
  229. const includeObject = payload.includeSongs ? null : { songs: false };
  230. PlaylistsModule.playlistModel.find({ type: "station" }, includeObject, (err, playlists) => {
  231. if (err) reject(new Error(err));
  232. else resolve({ playlists });
  233. });
  234. });
  235. }
  236. /**
  237. * Gets a genre playlist
  238. *
  239. * @param {object} payload - object that contains the payload
  240. * @param {string} payload.genre - the genre
  241. * @param {string} payload.includeSongs - include the songs
  242. * @returns {Promise} - returns promise (reject, resolve)
  243. */
  244. GET_GENRE_PLAYLIST(payload) {
  245. return new Promise((resolve, reject) => {
  246. const includeObject = payload.includeSongs ? null : { songs: false };
  247. PlaylistsModule.playlistModel.findOne(
  248. { type: "genre", createdFor: payload.genre },
  249. includeObject,
  250. (err, playlist) => {
  251. if (err) reject(new Error(err));
  252. else if (!playlist) reject(new Error("Playlist not found"));
  253. else resolve({ playlist });
  254. }
  255. );
  256. });
  257. }
  258. /**
  259. * Gets all missing genre playlists
  260. *
  261. * @returns {Promise} - returns promise (reject, resolve)
  262. */
  263. GET_MISSING_GENRE_PLAYLISTS() {
  264. return new Promise((resolve, reject) => {
  265. SongsModule.runJob("GET_ALL_GENRES", {}, this)
  266. .then(response => {
  267. const { genres } = response;
  268. const missingGenres = [];
  269. async.eachLimit(
  270. genres,
  271. 1,
  272. (genre, next) => {
  273. PlaylistsModule.runJob(
  274. "GET_GENRE_PLAYLIST",
  275. { genre: genre.toLowerCase(), includeSongs: false },
  276. this
  277. )
  278. .then(() => {
  279. next();
  280. })
  281. .catch(err => {
  282. if (err.message === "Playlist not found") {
  283. missingGenres.push(genre);
  284. next();
  285. } else next(err);
  286. });
  287. },
  288. err => {
  289. if (err) reject(err);
  290. else resolve({ genres: missingGenres });
  291. }
  292. );
  293. })
  294. .catch(err => {
  295. reject(err);
  296. });
  297. });
  298. }
  299. /**
  300. * Creates all missing genre playlists
  301. *
  302. * @returns {Promise} - returns promise (reject, resolve)
  303. */
  304. CREATE_MISSING_GENRE_PLAYLISTS() {
  305. return new Promise((resolve, reject) => {
  306. PlaylistsModule.runJob("GET_MISSING_GENRE_PLAYLISTS", {}, this)
  307. .then(response => {
  308. const { genres } = response;
  309. async.eachLimit(
  310. genres,
  311. 1,
  312. (genre, next) => {
  313. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre }, this)
  314. .then(() => {
  315. next();
  316. })
  317. .catch(err => {
  318. next(err);
  319. });
  320. },
  321. err => {
  322. if (err) reject(err);
  323. else resolve();
  324. }
  325. );
  326. })
  327. .catch(err => {
  328. reject(err);
  329. });
  330. });
  331. }
  332. /**
  333. * Gets a station playlist
  334. *
  335. * @param {object} payload - object that contains the payload
  336. * @param {string} payload.staationId - the station id
  337. * @param {string} payload.includeSongs - include the songs
  338. * @returns {Promise} - returns promise (reject, resolve)
  339. */
  340. GET_STATION_PLAYLIST(payload) {
  341. return new Promise((resolve, reject) => {
  342. const includeObject = payload.includeSongs ? null : { songs: false };
  343. PlaylistsModule.playlistModel.findOne(
  344. { type: "station", createdFor: payload.stationId },
  345. includeObject,
  346. (err, playlist) => {
  347. if (err) reject(new Error(err));
  348. else if (!playlist) reject(new Error("Playlist not found"));
  349. else resolve({ playlist });
  350. }
  351. );
  352. });
  353. }
  354. /**
  355. * Adds a song to a playlist
  356. *
  357. * @param {object} payload - object that contains the payload
  358. * @param {string} payload.playlistId - the playlist id
  359. * @param {string} payload.youtubeId - the youtube id
  360. * @returns {Promise} - returns promise (reject, resolve)
  361. */
  362. ADD_SONG_TO_PLAYLIST(payload) {
  363. return new Promise((resolve, reject) => {
  364. const { playlistId, youtubeId } = payload;
  365. async.waterfall(
  366. [
  367. next => {
  368. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  369. .then(playlist => {
  370. next(null, playlist);
  371. })
  372. .catch(next);
  373. },
  374. (playlist, next) => {
  375. if (!playlist) return next("Playlist not found.");
  376. if (playlist.songs.find(song => song.youtubeId === youtubeId))
  377. return next("That song is already in the playlist.");
  378. return next();
  379. },
  380. next => {
  381. SongsModule.runJob("ENSURE_SONG_EXISTS_BY_YOUTUBE_ID", { youtubeId }, this)
  382. .then(response => {
  383. const { song } = response;
  384. const { _id, title, artists, thumbnail, duration, verified } = song;
  385. next(null, {
  386. _id,
  387. youtubeId,
  388. title,
  389. artists,
  390. thumbnail,
  391. duration,
  392. verified
  393. });
  394. })
  395. .catch(next);
  396. },
  397. (newSong, next) => {
  398. PlaylistsModule.playlistModel.updateOne(
  399. { _id: playlistId },
  400. { $push: { songs: newSong } },
  401. { runValidators: true },
  402. err => {
  403. if (err) return next(err);
  404. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  405. .then(playlist => next(null, playlist, newSong))
  406. .catch(next);
  407. }
  408. );
  409. },
  410. (playlist, newSong, next) => {
  411. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId })
  412. .then(response => {
  413. async.each(
  414. response.stationIds,
  415. (stationId, next) => {
  416. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId })
  417. .then()
  418. .catch();
  419. next();
  420. },
  421. err => {
  422. if (err) next(err);
  423. else next(null, playlist, newSong);
  424. }
  425. );
  426. })
  427. .catch(next);
  428. },
  429. (playlist, newSong, next) => {
  430. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  431. RatingsModule.runJob("RECALCULATE_RATINGS", {
  432. youtubeId: newSong.youtubeId
  433. })
  434. .then(ratings => next(null, playlist, newSong, ratings))
  435. .catch(next);
  436. } else {
  437. next(null, playlist, newSong, null);
  438. }
  439. }
  440. ],
  441. (err, playlist, song, ratings) => {
  442. if (err) reject(err);
  443. else resolve({ playlist, song, ratings });
  444. }
  445. );
  446. });
  447. }
  448. /**
  449. * Remove from playlist
  450. *
  451. * @param {object} payload - object that contains the payload
  452. * @param {string} payload.playlistId - the playlist id
  453. * @param {string} payload.youtubeId - the youtube id
  454. * @returns {Promise} - returns a promise (resolve, reject)
  455. */
  456. REMOVE_FROM_PLAYLIST(payload) {
  457. return new Promise((resolve, reject) => {
  458. const { playlistId, youtubeId } = payload;
  459. async.waterfall(
  460. [
  461. next => {
  462. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  463. .then(playlist => {
  464. next(null, playlist);
  465. })
  466. .catch(next);
  467. },
  468. (playlist, next) => {
  469. if (!playlist) return next("Playlist not found.");
  470. if (!playlist.songs.find(song => song.youtubeId === youtubeId))
  471. return next("That song is not currently in the playlist.");
  472. return PlaylistsModule.playlistModel.updateOne(
  473. { _id: playlistId },
  474. { $pull: { songs: { youtubeId } } },
  475. next
  476. );
  477. },
  478. (res, next) => {
  479. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  480. .then(playlist => next(null, playlist))
  481. .catch(next);
  482. },
  483. (playlist, next) => {
  484. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId })
  485. .then(response => {
  486. async.each(
  487. response.stationIds,
  488. (stationId, next) => {
  489. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId })
  490. .then()
  491. .catch();
  492. next();
  493. },
  494. err => {
  495. if (err) next(err);
  496. else next(null, playlist);
  497. }
  498. );
  499. })
  500. .catch(next);
  501. },
  502. (playlist, next) => {
  503. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  504. RatingsModule.runJob("RECALCULATE_RATINGS", { youtubeId })
  505. .then(ratings => next(null, playlist, ratings))
  506. .catch(next);
  507. } else next(null, playlist, null);
  508. },
  509. (playlist, ratings, next) =>
  510. CacheModule.runJob(
  511. "PUB",
  512. {
  513. channel: "playlist.updated",
  514. value: { playlistId }
  515. },
  516. this
  517. )
  518. .then(() => next(null, playlist, ratings))
  519. .catch(next)
  520. ],
  521. (err, playlist, ratings) => {
  522. if (err) reject(err);
  523. else resolve({ playlist, ratings });
  524. }
  525. );
  526. });
  527. }
  528. /**
  529. * Deletes a song from a playlist based on the youtube id
  530. *
  531. * @param {object} payload - object that contains the payload
  532. * @param {string} payload.playlistId - the playlist id
  533. * @param {string} payload.youtubeId - the youtube id
  534. * @returns {Promise} - returns promise (reject, resolve)
  535. */
  536. DELETE_SONG_FROM_PLAYLIST_BY_YOUTUBE_ID(payload) {
  537. return new Promise((resolve, reject) => {
  538. PlaylistsModule.playlistModel.updateOne(
  539. { _id: payload.playlistId },
  540. { $pull: { songs: { youtubeId: payload.youtubeId } } },
  541. err => {
  542. if (err) reject(new Error(err));
  543. else {
  544. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  545. .then(() => resolve())
  546. .catch(err => {
  547. reject(new Error(err));
  548. });
  549. }
  550. }
  551. );
  552. });
  553. }
  554. /**
  555. * Fills a genre playlist with songs
  556. *
  557. * @param {object} payload - object that contains the payload
  558. * @param {string} payload.genre - the genre
  559. * @param {string} payload.createPlaylist - create playlist if it doesn't exist, default false
  560. * @returns {Promise} - returns promise (reject, resolve)
  561. */
  562. AUTOFILL_GENRE_PLAYLIST(payload) {
  563. return new Promise((resolve, reject) => {
  564. async.waterfall(
  565. [
  566. next => {
  567. PlaylistsModule.runJob(
  568. "GET_GENRE_PLAYLIST",
  569. { genre: payload.genre.toLowerCase(), includeSongs: true },
  570. this
  571. )
  572. .then(response => {
  573. next(null, response.playlist._id);
  574. })
  575. .catch(err => {
  576. if (err.message === "Playlist not found") {
  577. if (payload.createPlaylist)
  578. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)
  579. .then(playlistId => {
  580. next(null, playlistId);
  581. })
  582. .catch(err => {
  583. next(err);
  584. });
  585. } else next(err);
  586. });
  587. },
  588. (playlistId, next) => {
  589. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)
  590. .then(response => {
  591. next(null, playlistId, response.songs);
  592. })
  593. .catch(err => {
  594. console.log(err);
  595. next(err);
  596. });
  597. },
  598. (playlistId, _songs, next) => {
  599. const songs = _songs.map(song => {
  600. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  601. return {
  602. _id,
  603. youtubeId,
  604. title,
  605. artists,
  606. thumbnail,
  607. duration,
  608. verified
  609. };
  610. });
  611. PlaylistsModule.playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, err => {
  612. next(err, playlistId);
  613. });
  614. },
  615. (playlistId, next) => {
  616. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  617. .then(() => {
  618. next(null, playlistId);
  619. })
  620. .catch(next);
  621. },
  622. (playlistId, next) => {
  623. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId }, this)
  624. .then(response => {
  625. async.eachLimit(
  626. response.stationIds,
  627. 1,
  628. (stationId, next) => {
  629. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)
  630. .then(() => {
  631. next();
  632. })
  633. .catch(err => {
  634. next(err);
  635. });
  636. },
  637. err => {
  638. if (err) next(err);
  639. else next();
  640. }
  641. );
  642. })
  643. .catch(err => {
  644. next(err);
  645. });
  646. }
  647. ],
  648. err => {
  649. if (err && err !== true) return reject(new Error(err));
  650. return resolve({});
  651. }
  652. );
  653. });
  654. }
  655. /**
  656. * Gets orphaned genre playlists
  657. *
  658. * @returns {Promise} - returns promise (reject, resolve)
  659. */
  660. GET_ORPHANED_GENRE_PLAYLISTS() {
  661. return new Promise((resolve, reject) => {
  662. PlaylistsModule.playlistModel.find({ type: "genre" }, { songs: false }, (err, playlists) => {
  663. if (err) reject(new Error(err));
  664. else {
  665. const orphanedPlaylists = [];
  666. async.eachLimit(
  667. playlists,
  668. 1,
  669. (playlist, next) => {
  670. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: playlist.createdFor }, this)
  671. .then(response => {
  672. if (response.songs.length === 0) {
  673. StationsModule.runJob(
  674. "GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST",
  675. { playlistId: playlist._id },
  676. this
  677. )
  678. .then(response => {
  679. if (response.stationIds.length === 0) orphanedPlaylists.push(playlist);
  680. next();
  681. })
  682. .catch(next);
  683. } else next();
  684. })
  685. .catch(next);
  686. },
  687. err => {
  688. if (err) reject(new Error(err));
  689. else resolve({ playlists: orphanedPlaylists });
  690. }
  691. );
  692. }
  693. });
  694. });
  695. }
  696. /**
  697. * Deletes all orphaned genre playlists
  698. *
  699. * @returns {Promise} - returns promise (reject, resolve)
  700. */
  701. DELETE_ORPHANED_GENRE_PLAYLISTS() {
  702. return new Promise((resolve, reject) => {
  703. PlaylistsModule.runJob("GET_ORPHANED_GENRE_PLAYLISTS", {}, this)
  704. .then(response => {
  705. async.eachLimit(
  706. response.playlists,
  707. 1,
  708. (playlist, next) => {
  709. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  710. .then(() => {
  711. this.log("INFO", "Deleting orphaned genre playlist");
  712. next();
  713. })
  714. .catch(err => {
  715. next(err);
  716. });
  717. },
  718. err => {
  719. if (err) reject(new Error(err));
  720. else resolve({});
  721. }
  722. );
  723. })
  724. .catch(err => {
  725. reject(new Error(err));
  726. });
  727. });
  728. }
  729. /**
  730. * Gets a orphaned station playlists
  731. *
  732. * @returns {Promise} - returns promise (reject, resolve)
  733. */
  734. GET_ORPHANED_STATION_PLAYLISTS() {
  735. return new Promise((resolve, reject) => {
  736. PlaylistsModule.playlistModel.find({ type: "station" }, { songs: false }, (err, playlists) => {
  737. if (err) reject(new Error(err));
  738. else {
  739. const orphanedPlaylists = [];
  740. async.eachLimit(
  741. playlists,
  742. 1,
  743. (playlist, next) => {
  744. StationsModule.runJob("GET_STATION", { stationId: playlist.createdFor }, this)
  745. .then(station => {
  746. if (station.playlist !== playlist._id.toString()) {
  747. orphanedPlaylists.push(playlist);
  748. }
  749. next();
  750. })
  751. .catch(err => {
  752. if (err.message === "Station not found") {
  753. orphanedPlaylists.push(playlist);
  754. next();
  755. } else next(err);
  756. });
  757. },
  758. err => {
  759. if (err) reject(new Error(err));
  760. else resolve({ playlists: orphanedPlaylists });
  761. }
  762. );
  763. }
  764. });
  765. });
  766. }
  767. /**
  768. * Deletes all orphaned station playlists
  769. *
  770. * @returns {Promise} - returns promise (reject, resolve)
  771. */
  772. DELETE_ORPHANED_STATION_PLAYLISTS() {
  773. return new Promise((resolve, reject) => {
  774. PlaylistsModule.runJob("GET_ORPHANED_STATION_PLAYLISTS", {}, this)
  775. .then(response => {
  776. async.eachLimit(
  777. response.playlists,
  778. 1,
  779. (playlist, next) => {
  780. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  781. .then(() => {
  782. this.log("INFO", "Deleting orphaned station playlist");
  783. next();
  784. })
  785. .catch(err => {
  786. next(err);
  787. });
  788. },
  789. err => {
  790. if (err) reject(new Error(err));
  791. else resolve({});
  792. }
  793. );
  794. })
  795. .catch(err => {
  796. reject(new Error(err));
  797. });
  798. });
  799. }
  800. /**
  801. * Fills a station playlist with songs
  802. *
  803. * @param {object} payload - object that contains the payload
  804. * @param {string} payload.stationId - the station id
  805. * @returns {Promise} - returns promise (reject, resolve)
  806. */
  807. AUTOFILL_STATION_PLAYLIST(payload) {
  808. return new Promise((resolve, reject) => {
  809. let originalPlaylist = null;
  810. async.waterfall(
  811. [
  812. next => {
  813. if (!payload.stationId) next("Please specify a station id");
  814. else next();
  815. },
  816. next => {
  817. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  818. .then(station => {
  819. next(null, station);
  820. })
  821. .catch(next);
  822. },
  823. (station, next) => {
  824. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: station.playlist }, this)
  825. .then(playlist => {
  826. originalPlaylist = playlist;
  827. next(null, station);
  828. })
  829. .catch(err => {
  830. next(err);
  831. });
  832. },
  833. (station, next) => {
  834. const playlists = [];
  835. async.eachLimit(
  836. station.autofill.playlists,
  837. 1,
  838. (playlistId, next) => {
  839. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  840. .then(playlist => {
  841. playlists.push(playlist);
  842. next();
  843. })
  844. .catch(next);
  845. },
  846. err => {
  847. next(err, station, playlists);
  848. }
  849. );
  850. },
  851. (station, playlists, next) => {
  852. const blacklist = [];
  853. async.eachLimit(
  854. station.blacklist,
  855. 1,
  856. (playlistId, next) => {
  857. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  858. .then(playlist => {
  859. blacklist.push(playlist);
  860. next();
  861. })
  862. .catch(next);
  863. },
  864. err => {
  865. next(err, station, playlists, blacklist);
  866. }
  867. );
  868. },
  869. (station, playlists, blacklist, next) => {
  870. const blacklistedSongs = blacklist
  871. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  872. .reduce(
  873. (items, item) =>
  874. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  875. []
  876. );
  877. const includedSongs = playlists
  878. .flatMap(playlist => playlist.songs)
  879. .reduce(
  880. (songs, song) =>
  881. songs.find(x => x.youtubeId === song.youtubeId) ? [...songs] : [...songs, song],
  882. []
  883. )
  884. .filter(song => !blacklistedSongs.find(x => x.youtubeId === song.youtubeId));
  885. next(null, station, includedSongs);
  886. },
  887. (station, includedSongs, next) => {
  888. PlaylistsModule.playlistModel.updateOne(
  889. { _id: station.playlist },
  890. { $set: { songs: includedSongs } },
  891. err => {
  892. next(err, includedSongs);
  893. }
  894. );
  895. },
  896. (includedSongs, next) => {
  897. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: originalPlaylist._id }, this)
  898. .then(() => {
  899. next(null, includedSongs);
  900. })
  901. .catch(next);
  902. },
  903. (includedSongs, next) => {
  904. if (originalPlaylist.songs.length === 0 && includedSongs.length > 0)
  905. StationsModule.runJob("SKIP_STATION", { stationId: payload.stationId, natural: false });
  906. next();
  907. }
  908. ],
  909. err => {
  910. if (err && err !== true) return reject(new Error(err));
  911. return resolve({});
  912. }
  913. );
  914. });
  915. }
  916. /**
  917. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  918. *
  919. * @param {object} payload - object that contains the payload
  920. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  921. * @returns {Promise} - returns promise (reject, resolve)
  922. */
  923. GET_PLAYLIST(payload) {
  924. return new Promise((resolve, reject) => {
  925. async.waterfall(
  926. [
  927. next => {
  928. CacheModule.runJob(
  929. "HGET",
  930. {
  931. table: "playlists",
  932. key: payload.playlistId
  933. },
  934. this
  935. )
  936. .then(playlist => next(null, playlist))
  937. .catch(next);
  938. },
  939. (playlist, next) => {
  940. if (playlist)
  941. PlaylistsModule.playlistModel.exists({ _id: payload.playlistId }, (err, exists) => {
  942. if (err) next(err);
  943. else if (exists) next(null, playlist);
  944. else {
  945. CacheModule.runJob(
  946. "HDEL",
  947. {
  948. table: "playlists",
  949. key: payload.playlistId
  950. },
  951. this
  952. )
  953. .then(() => next())
  954. .catch(next);
  955. }
  956. });
  957. else PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  958. },
  959. (playlist, next) => {
  960. if (playlist) {
  961. CacheModule.runJob(
  962. "HSET",
  963. {
  964. table: "playlists",
  965. key: payload.playlistId,
  966. value: playlist
  967. },
  968. this
  969. )
  970. .then(playlist => {
  971. next(null, playlist);
  972. })
  973. .catch(next);
  974. } else next("Playlist not found");
  975. }
  976. ],
  977. (err, playlist) => {
  978. if (err && err !== true) return reject(new Error(err));
  979. return resolve(playlist);
  980. }
  981. );
  982. });
  983. }
  984. /**
  985. * Gets a playlist from id from Mongo and updates the cache with it
  986. *
  987. * @param {object} payload - object that contains the payload
  988. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  989. * @returns {Promise} - returns promise (reject, resolve)
  990. */
  991. UPDATE_PLAYLIST(payload) {
  992. return new Promise((resolve, reject) => {
  993. async.waterfall(
  994. [
  995. next => {
  996. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  997. },
  998. (playlist, next) => {
  999. if (!playlist) {
  1000. CacheModule.runJob("HDEL", {
  1001. table: "playlists",
  1002. key: payload.playlistId
  1003. });
  1004. return next("Playlist not found");
  1005. }
  1006. return CacheModule.runJob(
  1007. "HSET",
  1008. {
  1009. table: "playlists",
  1010. key: payload.playlistId,
  1011. value: playlist
  1012. },
  1013. this
  1014. )
  1015. .then(playlist => {
  1016. next(null, playlist);
  1017. })
  1018. .catch(next);
  1019. }
  1020. ],
  1021. (err, playlist) => {
  1022. if (err && err !== true) return reject(new Error(err));
  1023. return resolve(playlist);
  1024. }
  1025. );
  1026. });
  1027. }
  1028. /**
  1029. * Deletes playlist from id from Mongo and cache
  1030. *
  1031. * @param {object} payload - object that contains the payload
  1032. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  1033. * @returns {Promise} - returns promise (reject, resolve)
  1034. */
  1035. DELETE_PLAYLIST(payload) {
  1036. return new Promise((resolve, reject) => {
  1037. async.waterfall(
  1038. [
  1039. next => {
  1040. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  1041. },
  1042. (res, next) => {
  1043. CacheModule.runJob(
  1044. "HDEL",
  1045. {
  1046. table: "playlists",
  1047. key: payload.playlistId
  1048. },
  1049. this
  1050. )
  1051. .then(() => next())
  1052. .catch(next);
  1053. },
  1054. next => {
  1055. StationsModule.runJob(
  1056. "REMOVE_AUTOFILLED_OR_BLACKLISTED_PLAYLIST_FROM_STATIONS",
  1057. { playlistId: payload.playlistId },
  1058. this
  1059. )
  1060. .then(() => {
  1061. next();
  1062. })
  1063. .catch(err => next(err));
  1064. }
  1065. ],
  1066. err => {
  1067. if (err && err !== true) return reject(new Error(err));
  1068. return resolve();
  1069. }
  1070. );
  1071. });
  1072. }
  1073. /**
  1074. * Searches through playlists
  1075. *
  1076. * @param {object} payload - object that contains the payload
  1077. * @param {string} payload.query - the query
  1078. * @param {string} payload.includePrivate - include private playlists
  1079. * @param {string} payload.includeStation - include station playlists
  1080. * @param {string} payload.includeUser - include user playlists
  1081. * @param {string} payload.includeGenre - include genre playlists
  1082. * @param {string} payload.includeOwn - include own user playlists
  1083. * @param {string} payload.userId - the user id of the person requesting
  1084. * @param {string} payload.includeSongs - include songs
  1085. * @param {string} payload.page - page (default 1)
  1086. * @returns {Promise} - returns promise (reject, resolve)
  1087. */
  1088. SEARCH(payload) {
  1089. return new Promise((resolve, reject) => {
  1090. async.waterfall(
  1091. [
  1092. next => {
  1093. const types = [];
  1094. if (payload.includeStation) types.push("station");
  1095. if (payload.includeUser) types.push("user");
  1096. if (payload.includeGenre) types.push("genre");
  1097. if (types.length === 0 && !payload.includeOwn) return next("No types have been included.");
  1098. const privacies = ["public"];
  1099. if (payload.includePrivate) privacies.push("private");
  1100. const includeObject = payload.includeSongs ? null : { songs: false };
  1101. const filterArray = [
  1102. {
  1103. displayName: new RegExp(`${payload.query}`, "i"),
  1104. privacy: { $in: privacies },
  1105. type: { $in: types }
  1106. }
  1107. ];
  1108. if (payload.includeOwn && payload.userId)
  1109. filterArray.push({
  1110. displayName: new RegExp(`${payload.query}`, "i"),
  1111. type: "user",
  1112. createdBy: payload.userId
  1113. });
  1114. return next(null, filterArray, includeObject);
  1115. },
  1116. (filterArray, includeObject, next) => {
  1117. const page = payload.page ? payload.page : 1;
  1118. const pageSize = 15;
  1119. const skipAmount = pageSize * (page - 1);
  1120. PlaylistsModule.playlistModel.find({ $or: filterArray }).count((err, count) => {
  1121. if (err) next(err);
  1122. else {
  1123. PlaylistsModule.playlistModel
  1124. .find({ $or: filterArray }, includeObject)
  1125. .skip(skipAmount)
  1126. .limit(pageSize)
  1127. .exec((err, playlists) => {
  1128. if (err) next(err);
  1129. else {
  1130. next(null, {
  1131. playlists,
  1132. page,
  1133. pageSize,
  1134. skipAmount,
  1135. count
  1136. });
  1137. }
  1138. });
  1139. }
  1140. });
  1141. },
  1142. (data, next) => {
  1143. if (data.playlists.length > 0) next(null, data);
  1144. else next("No playlists found");
  1145. }
  1146. ],
  1147. (err, data) => {
  1148. if (err && err !== true) return reject(new Error(err));
  1149. return resolve(data);
  1150. }
  1151. );
  1152. });
  1153. }
  1154. /**
  1155. * Clears and refills a station playlist
  1156. *
  1157. * @param {object} payload - object that contains the payload
  1158. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1159. * @returns {Promise} - returns promise (reject, resolve)
  1160. */
  1161. CLEAR_AND_REFILL_STATION_PLAYLIST(payload) {
  1162. return new Promise((resolve, reject) => {
  1163. const { playlistId } = payload;
  1164. async.waterfall(
  1165. [
  1166. next => {
  1167. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1168. .then(playlist => {
  1169. next(null, playlist);
  1170. })
  1171. .catch(err => {
  1172. next(err);
  1173. });
  1174. },
  1175. (playlist, next) => {
  1176. if (playlist.type !== "station") next("This playlist is not a station playlist.");
  1177. else next(null, playlist.createdFor);
  1178. },
  1179. (stationId, next) => {
  1180. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)
  1181. .then(() => {
  1182. next();
  1183. })
  1184. .catch(err => {
  1185. next(err);
  1186. });
  1187. }
  1188. ],
  1189. err => {
  1190. if (err && err !== true) return reject(new Error(err));
  1191. return resolve();
  1192. }
  1193. );
  1194. });
  1195. }
  1196. /**
  1197. * Clears and refills a genre playlist
  1198. *
  1199. * @param {object} payload - object that contains the payload
  1200. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1201. * @returns {Promise} - returns promise (reject, resolve)
  1202. */
  1203. CLEAR_AND_REFILL_GENRE_PLAYLIST(payload) {
  1204. return new Promise((resolve, reject) => {
  1205. const { playlistId } = payload;
  1206. async.waterfall(
  1207. [
  1208. next => {
  1209. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1210. .then(playlist => {
  1211. next(null, playlist);
  1212. })
  1213. .catch(err => {
  1214. next(err);
  1215. });
  1216. },
  1217. (playlist, next) => {
  1218. if (playlist.type !== "genre") next("This playlist is not a genre playlist.");
  1219. else next(null, playlist.createdFor);
  1220. },
  1221. (genre, next) => {
  1222. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: true }, this)
  1223. .then(() => {
  1224. next();
  1225. })
  1226. .catch(err => {
  1227. next(err);
  1228. });
  1229. }
  1230. ],
  1231. err => {
  1232. if (err && err !== true) return reject(new Error(err));
  1233. return resolve();
  1234. }
  1235. );
  1236. });
  1237. }
  1238. }
  1239. export default new _PlaylistsModule();