playlists.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  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 MediaModule;
  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. MediaModule = this.moduleManager.modules.media;
  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. // * Returns a list of youtube ids in all user playlists of the specified user
  146. // *
  147. // * @param {object} payload - object that contains the payload
  148. // * @param {string} payload.userId - the user id
  149. // * @returns {Promise} - returns promise (reject, resolve)
  150. // */
  151. // GET_SONG_YOUTUBE_IDS_FROM_PLAYLISTS(payload) {
  152. // return new Promise((resolve, reject) => {
  153. // PlaylistsModule.playlistModel.find({ createdBy: payload.userId }, (err, playlists) => {
  154. // const youtubeIds = new Set();
  155. // if (err) reject(err);
  156. // else {
  157. // playlists.forEach(playlist => {
  158. // playlist.songs.forEach(song => {
  159. // youtubeIds.add(song.youtubeId);
  160. // });
  161. // });
  162. // console.log(Array.from(youtubeIds));
  163. // resolve({ youtubeIds: Array.from(youtubeIds) });
  164. // }
  165. // });
  166. // });
  167. // }
  168. /**
  169. * Creates a playlist owned by a user
  170. *
  171. * @param {object} payload - object that contains the payload
  172. * @param {string} payload.userId - the id of the user to create the playlist for
  173. * @param {string} payload.displayName - the display name of the playlist
  174. * @param {string} payload.type - the type of the playlist
  175. * @returns {Promise} - returns promise (reject, resolve)
  176. */
  177. CREATE_USER_PLAYLIST(payload) {
  178. return new Promise((resolve, reject) => {
  179. PlaylistsModule.playlistModel.create(
  180. {
  181. displayName: payload.displayName,
  182. songs: [],
  183. createdBy: payload.userId,
  184. createdAt: Date.now(),
  185. createdFor: null,
  186. type: payload.type
  187. },
  188. (err, playlist) => {
  189. if (err) return reject(new Error(err));
  190. return resolve(playlist._id);
  191. }
  192. );
  193. });
  194. }
  195. /**
  196. * Creates a playlist that contains all songs of a specific genre
  197. *
  198. * @param {object} payload - object that contains the payload
  199. * @param {string} payload.genre - the genre
  200. * @returns {Promise} - returns promise (reject, resolve)
  201. */
  202. CREATE_GENRE_PLAYLIST(payload) {
  203. return new Promise((resolve, reject) => {
  204. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre: payload.genre.toLowerCase() }, this)
  205. .then(() => {
  206. reject(new Error("Playlist already exists"));
  207. })
  208. .catch(err => {
  209. if (err.message === "Playlist not found") {
  210. PlaylistsModule.playlistModel.create(
  211. {
  212. displayName: `Genre - ${payload.genre}`,
  213. songs: [],
  214. createdBy: "Musare",
  215. createdFor: `${payload.genre.toLowerCase()}`,
  216. createdAt: Date.now(),
  217. type: "genre"
  218. },
  219. (err, playlist) => {
  220. if (err) return reject(new Error(err));
  221. return resolve(playlist._id);
  222. }
  223. );
  224. } else reject(new Error(err));
  225. });
  226. });
  227. }
  228. /**
  229. * Gets all genre playlists
  230. *
  231. * @param {object} payload - object that contains the payload
  232. * @param {string} payload.includeSongs - include the songs
  233. * @returns {Promise} - returns promise (reject, resolve)
  234. */
  235. GET_ALL_GENRE_PLAYLISTS(payload) {
  236. return new Promise((resolve, reject) => {
  237. const includeObject = payload.includeSongs ? null : { songs: false };
  238. PlaylistsModule.playlistModel.find({ type: "genre" }, includeObject, (err, playlists) => {
  239. if (err) reject(new Error(err));
  240. else resolve({ playlists });
  241. });
  242. });
  243. }
  244. /**
  245. * Gets all station playlists
  246. *
  247. * @param {object} payload - object that contains the payload
  248. * @param {string} payload.includeSongs - include the songs
  249. * @returns {Promise} - returns promise (reject, resolve)
  250. */
  251. GET_ALL_STATION_PLAYLISTS(payload) {
  252. return new Promise((resolve, reject) => {
  253. const includeObject = payload.includeSongs ? null : { songs: false };
  254. PlaylistsModule.playlistModel.find({ type: "station" }, includeObject, (err, playlists) => {
  255. if (err) reject(new Error(err));
  256. else resolve({ playlists });
  257. });
  258. });
  259. }
  260. /**
  261. * Gets a genre playlist
  262. *
  263. * @param {object} payload - object that contains the payload
  264. * @param {string} payload.genre - the genre
  265. * @param {string} payload.includeSongs - include the songs
  266. * @returns {Promise} - returns promise (reject, resolve)
  267. */
  268. GET_GENRE_PLAYLIST(payload) {
  269. return new Promise((resolve, reject) => {
  270. const includeObject = payload.includeSongs ? null : { songs: false };
  271. PlaylistsModule.playlistModel.findOne(
  272. { type: "genre", createdFor: payload.genre },
  273. includeObject,
  274. (err, playlist) => {
  275. if (err) reject(new Error(err));
  276. else if (!playlist) reject(new Error("Playlist not found"));
  277. else resolve({ playlist });
  278. }
  279. );
  280. });
  281. }
  282. /**
  283. * Gets all missing genre playlists
  284. *
  285. * @returns {Promise} - returns promise (reject, resolve)
  286. */
  287. GET_MISSING_GENRE_PLAYLISTS() {
  288. return new Promise((resolve, reject) => {
  289. SongsModule.runJob("GET_ALL_GENRES", {}, this)
  290. .then(response => {
  291. const { genres } = response;
  292. const missingGenres = [];
  293. async.eachLimit(
  294. genres,
  295. 1,
  296. (genre, next) => {
  297. PlaylistsModule.runJob(
  298. "GET_GENRE_PLAYLIST",
  299. { genre: genre.toLowerCase(), includeSongs: false },
  300. this
  301. )
  302. .then(() => {
  303. next();
  304. })
  305. .catch(err => {
  306. if (err.message === "Playlist not found") {
  307. missingGenres.push(genre);
  308. next();
  309. } else next(err);
  310. });
  311. },
  312. err => {
  313. if (err) reject(err);
  314. else resolve({ genres: missingGenres });
  315. }
  316. );
  317. })
  318. .catch(err => {
  319. reject(err);
  320. });
  321. });
  322. }
  323. /**
  324. * Creates all missing genre playlists
  325. *
  326. * @returns {Promise} - returns promise (reject, resolve)
  327. */
  328. CREATE_MISSING_GENRE_PLAYLISTS() {
  329. return new Promise((resolve, reject) => {
  330. PlaylistsModule.runJob("GET_MISSING_GENRE_PLAYLISTS", {}, this)
  331. .then(response => {
  332. const { genres } = response;
  333. async.eachLimit(
  334. genres,
  335. 1,
  336. (genre, next) => {
  337. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre }, this)
  338. .then(() => {
  339. next();
  340. })
  341. .catch(err => {
  342. next(err);
  343. });
  344. },
  345. err => {
  346. if (err) reject(err);
  347. else resolve();
  348. }
  349. );
  350. })
  351. .catch(err => {
  352. reject(err);
  353. });
  354. });
  355. }
  356. /**
  357. * Gets a station playlist
  358. *
  359. * @param {object} payload - object that contains the payload
  360. * @param {string} payload.staationId - the station id
  361. * @param {string} payload.includeSongs - include the songs
  362. * @returns {Promise} - returns promise (reject, resolve)
  363. */
  364. GET_STATION_PLAYLIST(payload) {
  365. return new Promise((resolve, reject) => {
  366. const includeObject = payload.includeSongs ? null : { songs: false };
  367. PlaylistsModule.playlistModel.findOne(
  368. { type: "station", createdFor: payload.stationId },
  369. includeObject,
  370. (err, playlist) => {
  371. if (err) reject(new Error(err));
  372. else if (!playlist) reject(new Error("Playlist not found"));
  373. else resolve({ playlist });
  374. }
  375. );
  376. });
  377. }
  378. /**
  379. * Adds a song to a playlist
  380. *
  381. * @param {object} payload - object that contains the payload
  382. * @param {string} payload.playlistId - the playlist id
  383. * @param {string} payload.mediaSource - the media source
  384. * @returns {Promise} - returns promise (reject, resolve)
  385. */
  386. ADD_SONG_TO_PLAYLIST(payload) {
  387. return new Promise((resolve, reject) => {
  388. const { playlistId, mediaSource } = payload;
  389. async.waterfall(
  390. [
  391. next => {
  392. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  393. .then(playlist => {
  394. next(null, playlist);
  395. })
  396. .catch(next);
  397. },
  398. (playlist, next) => {
  399. if (!playlist) return next("Playlist not found.");
  400. if (playlist.songs.find(song => song.mediaSource === mediaSource))
  401. return next("That song is already in the playlist.");
  402. return next();
  403. },
  404. next => {
  405. MediaModule.runJob("GET_MEDIA", { mediaSource }, this)
  406. .then(response => {
  407. const { song } = response;
  408. const { _id, title, artists, thumbnail, duration, verified } = song;
  409. next(null, {
  410. _id,
  411. mediaSource,
  412. title,
  413. artists,
  414. thumbnail,
  415. duration,
  416. verified
  417. });
  418. })
  419. .catch(next);
  420. },
  421. (newSong, next) => {
  422. PlaylistsModule.playlistModel.updateOne(
  423. { _id: playlistId },
  424. { $push: { songs: newSong } },
  425. { runValidators: true },
  426. err => {
  427. if (err) return next(err);
  428. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  429. .then(playlist => next(null, playlist, newSong))
  430. .catch(next);
  431. }
  432. );
  433. },
  434. (playlist, newSong, next) => {
  435. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId })
  436. .then(response => {
  437. async.each(
  438. response.stationIds,
  439. (stationId, next) => {
  440. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId })
  441. .then()
  442. .catch();
  443. next();
  444. },
  445. err => {
  446. if (err) next(err);
  447. else next(null, playlist, newSong);
  448. }
  449. );
  450. })
  451. .catch(next);
  452. },
  453. (playlist, newSong, next) => {
  454. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  455. MediaModule.runJob("RECALCULATE_RATINGS", {
  456. mediaSource: newSong.mediaSource
  457. })
  458. .then(ratings => next(null, playlist, newSong, ratings))
  459. .catch(next);
  460. } else {
  461. next(null, playlist, newSong, null);
  462. }
  463. }
  464. ],
  465. (err, playlist, song, ratings) => {
  466. if (err) reject(err);
  467. else resolve({ playlist, song, ratings });
  468. }
  469. );
  470. });
  471. }
  472. /**
  473. * Replaces a song in a playlist
  474. *
  475. * @param {object} payload - object that contains the payload
  476. * @param {string} payload.playlistId - the playlist id
  477. * @param {string} payload.newMediaSource - the new media source
  478. * @param {string} payload.oldMediaSource - the old media source
  479. * @returns {Promise} - returns promise (reject, resolve)
  480. */
  481. REPLACE_SONG_IN_PLAYLIST(payload) {
  482. return new Promise((resolve, reject) => {
  483. const { playlistId, newMediaSource, oldMediaSource } = payload;
  484. async.waterfall(
  485. [
  486. next => {
  487. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  488. .then(playlist => {
  489. next(null, playlist);
  490. })
  491. .catch(next);
  492. },
  493. (playlist, next) => {
  494. if (!playlist) return next("Playlist not found.");
  495. if (playlist.songs.find(song => song.mediaSource === newMediaSource))
  496. return next("The new song is already in the playlist.");
  497. return next();
  498. },
  499. next => {
  500. MediaModule.runJob("GET_MEDIA", { mediaSource: newMediaSource }, this)
  501. .then(response => {
  502. const { song } = response;
  503. const { _id, title, artists, thumbnail, duration, verified } = song;
  504. next(null, {
  505. _id,
  506. mediaSource: newMediaSource,
  507. title,
  508. artists,
  509. thumbnail,
  510. duration,
  511. verified
  512. });
  513. })
  514. .catch(next);
  515. },
  516. (newSong, next) => {
  517. PlaylistsModule.playlistModel.updateOne(
  518. { _id: playlistId, "songs.mediaSource": oldMediaSource },
  519. { $set: { "songs.$": newSong } },
  520. { runValidators: true },
  521. err => {
  522. if (err) return next(err);
  523. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  524. .then(playlist => next(null, playlist, newSong))
  525. .catch(next);
  526. }
  527. );
  528. },
  529. (playlist, newSong, next) => {
  530. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId })
  531. .then(response => {
  532. async.each(
  533. response.stationIds,
  534. (stationId, next) => {
  535. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId })
  536. .then()
  537. .catch();
  538. next();
  539. },
  540. err => {
  541. if (err) next(err);
  542. else next(null, playlist, newSong);
  543. }
  544. );
  545. })
  546. .catch(next);
  547. },
  548. (playlist, newSong, next) => {
  549. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  550. MediaModule.runJob("RECALCULATE_RATINGS", {
  551. mediaSource: newSong.mediaSource
  552. })
  553. .then(ratings => next(null, playlist, newSong, ratings))
  554. .catch(next);
  555. } else {
  556. next(null, playlist, newSong, null);
  557. }
  558. },
  559. (playlist, newSong, newRatings, next) => {
  560. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  561. MediaModule.runJob("RECALCULATE_RATINGS", {
  562. mediaSource: oldMediaSource
  563. })
  564. .then(ratings => next(null, playlist, newSong, newRatings, oldRatings))
  565. .catch(next);
  566. } else {
  567. next(null, playlist, newSong, null, null);
  568. }
  569. }
  570. ],
  571. (err, playlist, song, newRatings, oldRatings) => {
  572. if (err) reject(err);
  573. else resolve({ playlist, song, newRatings, oldRatings });
  574. }
  575. );
  576. });
  577. }
  578. /**
  579. * Remove from playlist
  580. *
  581. * @param {object} payload - object that contains the payload
  582. * @param {string} payload.playlistId - the playlist id
  583. * @param {string} payload.mediaSource - the media source
  584. * @returns {Promise} - returns a promise (resolve, reject)
  585. */
  586. REMOVE_FROM_PLAYLIST(payload) {
  587. return new Promise((resolve, reject) => {
  588. const { playlistId, mediaSource } = payload;
  589. async.waterfall(
  590. [
  591. next => {
  592. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  593. .then(playlist => {
  594. next(null, playlist);
  595. })
  596. .catch(next);
  597. },
  598. (playlist, next) => {
  599. if (!playlist) return next("Playlist not found.");
  600. if (!playlist.songs.find(song => song.mediaSource === mediaSource))
  601. return next("That song is not currently in the playlist.");
  602. return PlaylistsModule.playlistModel.updateOne(
  603. { _id: playlistId },
  604. { $pull: { songs: { mediaSource } } },
  605. next
  606. );
  607. },
  608. (res, next) => {
  609. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  610. .then(playlist => next(null, playlist))
  611. .catch(next);
  612. },
  613. (playlist, next) => {
  614. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId })
  615. .then(response => {
  616. async.each(
  617. response.stationIds,
  618. (stationId, next) => {
  619. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId })
  620. .then()
  621. .catch();
  622. next();
  623. },
  624. err => {
  625. if (err) next(err);
  626. else next(null, playlist);
  627. }
  628. );
  629. })
  630. .catch(next);
  631. },
  632. (playlist, next) => {
  633. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  634. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource })
  635. .then(ratings => next(null, playlist, ratings))
  636. .catch(next);
  637. } else next(null, playlist, null);
  638. },
  639. (playlist, ratings, next) =>
  640. CacheModule.runJob(
  641. "PUB",
  642. {
  643. channel: "playlist.updated",
  644. value: { playlistId }
  645. },
  646. this
  647. )
  648. .then(() => next(null, playlist, ratings))
  649. .catch(next)
  650. ],
  651. (err, playlist, ratings) => {
  652. if (err) reject(err);
  653. else resolve({ playlist, ratings });
  654. }
  655. );
  656. });
  657. }
  658. /**
  659. * Deletes a song from a playlist based on the media source
  660. *
  661. * @param {object} payload - object that contains the payload
  662. * @param {string} payload.playlistId - the playlist id
  663. * @param {string} payload.mediaSource - the media source
  664. * @returns {Promise} - returns promise (reject, resolve)
  665. */
  666. DELETE_SONG_FROM_PLAYLIST_BY_MEDIA_SOURCE_ID(payload) {
  667. return new Promise((resolve, reject) => {
  668. PlaylistsModule.playlistModel.updateOne(
  669. { _id: payload.playlistId },
  670. { $pull: { songs: { mediaSource: payload.mediaSource } } },
  671. err => {
  672. if (err) reject(new Error(err));
  673. else {
  674. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  675. .then(() => resolve())
  676. .catch(err => {
  677. reject(new Error(err));
  678. });
  679. }
  680. }
  681. );
  682. });
  683. }
  684. /**
  685. * Fills a genre playlist with songs
  686. *
  687. * @param {object} payload - object that contains the payload
  688. * @param {string} payload.genre - the genre
  689. * @param {string} payload.createPlaylist - create playlist if it doesn't exist, default false
  690. * @returns {Promise} - returns promise (reject, resolve)
  691. */
  692. AUTOFILL_GENRE_PLAYLIST(payload) {
  693. return new Promise((resolve, reject) => {
  694. async.waterfall(
  695. [
  696. next => {
  697. PlaylistsModule.runJob(
  698. "GET_GENRE_PLAYLIST",
  699. { genre: payload.genre.toLowerCase(), includeSongs: true },
  700. this
  701. )
  702. .then(response => {
  703. next(null, response.playlist._id);
  704. })
  705. .catch(err => {
  706. if (err.message === "Playlist not found") {
  707. if (payload.createPlaylist)
  708. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)
  709. .then(playlistId => {
  710. next(null, playlistId);
  711. })
  712. .catch(err => {
  713. next(err);
  714. });
  715. } else next(err);
  716. });
  717. },
  718. (playlistId, next) => {
  719. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)
  720. .then(response => {
  721. next(null, playlistId, response.songs);
  722. })
  723. .catch(err => {
  724. console.log(err);
  725. next(err);
  726. });
  727. },
  728. (playlistId, _songs, next) => {
  729. const songs = _songs.map(song => {
  730. const { _id, mediaSource, title, artists, thumbnail, duration, verified } = song;
  731. return {
  732. _id,
  733. mediaSource,
  734. title,
  735. artists,
  736. thumbnail,
  737. duration,
  738. verified
  739. };
  740. });
  741. PlaylistsModule.playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, err => {
  742. next(err, playlistId);
  743. });
  744. },
  745. (playlistId, next) => {
  746. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  747. .then(() => {
  748. next(null, playlistId);
  749. })
  750. .catch(next);
  751. },
  752. (playlistId, next) => {
  753. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId }, this)
  754. .then(response => {
  755. async.eachLimit(
  756. response.stationIds,
  757. 1,
  758. (stationId, next) => {
  759. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)
  760. .then(() => {
  761. next();
  762. })
  763. .catch(err => {
  764. next(err);
  765. });
  766. },
  767. err => {
  768. if (err) next(err);
  769. else next();
  770. }
  771. );
  772. })
  773. .catch(err => {
  774. next(err);
  775. });
  776. }
  777. ],
  778. err => {
  779. if (err && err !== true) return reject(new Error(err));
  780. return resolve({});
  781. }
  782. );
  783. });
  784. }
  785. /**
  786. * Gets orphaned genre playlists
  787. *
  788. * @returns {Promise} - returns promise (reject, resolve)
  789. */
  790. GET_ORPHANED_GENRE_PLAYLISTS() {
  791. return new Promise((resolve, reject) => {
  792. PlaylistsModule.playlistModel.find({ type: "genre" }, { songs: false }, (err, playlists) => {
  793. if (err) reject(new Error(err));
  794. else {
  795. const orphanedPlaylists = [];
  796. async.eachLimit(
  797. playlists,
  798. 1,
  799. (playlist, next) => {
  800. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: playlist.createdFor }, this)
  801. .then(response => {
  802. if (response.songs.length === 0) {
  803. StationsModule.runJob(
  804. "GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST",
  805. { playlistId: playlist._id },
  806. this
  807. )
  808. .then(response => {
  809. if (response.stationIds.length === 0) orphanedPlaylists.push(playlist);
  810. next();
  811. })
  812. .catch(next);
  813. } else next();
  814. })
  815. .catch(next);
  816. },
  817. err => {
  818. if (err) reject(new Error(err));
  819. else resolve({ playlists: orphanedPlaylists });
  820. }
  821. );
  822. }
  823. });
  824. });
  825. }
  826. /**
  827. * Deletes all orphaned genre playlists
  828. *
  829. * @returns {Promise} - returns promise (reject, resolve)
  830. */
  831. DELETE_ORPHANED_GENRE_PLAYLISTS() {
  832. return new Promise((resolve, reject) => {
  833. PlaylistsModule.runJob("GET_ORPHANED_GENRE_PLAYLISTS", {}, this)
  834. .then(response => {
  835. async.eachLimit(
  836. response.playlists,
  837. 1,
  838. (playlist, next) => {
  839. this.publishProgress({ status: "update", message: `Deleting "${playlist._id}"` });
  840. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  841. .then(() => {
  842. this.log("INFO", "Deleting orphaned genre playlist");
  843. next();
  844. })
  845. .catch(err => {
  846. next(err);
  847. });
  848. },
  849. err => {
  850. if (err) reject(new Error(err));
  851. else resolve({});
  852. }
  853. );
  854. })
  855. .catch(err => {
  856. reject(new Error(err));
  857. });
  858. });
  859. }
  860. /**
  861. * Gets a orphaned station playlists
  862. *
  863. * @returns {Promise} - returns promise (reject, resolve)
  864. */
  865. GET_ORPHANED_STATION_PLAYLISTS() {
  866. return new Promise((resolve, reject) => {
  867. PlaylistsModule.playlistModel.find({ type: "station" }, { songs: false }, (err, playlists) => {
  868. if (err) reject(new Error(err));
  869. else {
  870. const orphanedPlaylists = [];
  871. async.eachLimit(
  872. playlists,
  873. 1,
  874. (playlist, next) => {
  875. StationsModule.runJob("GET_STATION", { stationId: playlist.createdFor }, this)
  876. .then(station => {
  877. if (station.playlist !== playlist._id.toString()) {
  878. orphanedPlaylists.push(playlist);
  879. }
  880. next();
  881. })
  882. .catch(err => {
  883. if (err.message === "Station not found") {
  884. orphanedPlaylists.push(playlist);
  885. next();
  886. } else next(err);
  887. });
  888. },
  889. err => {
  890. if (err) reject(new Error(err));
  891. else resolve({ playlists: orphanedPlaylists });
  892. }
  893. );
  894. }
  895. });
  896. });
  897. }
  898. /**
  899. * Deletes all orphaned station playlists
  900. *
  901. * @returns {Promise} - returns promise (reject, resolve)
  902. */
  903. DELETE_ORPHANED_STATION_PLAYLISTS() {
  904. return new Promise((resolve, reject) => {
  905. PlaylistsModule.runJob("GET_ORPHANED_STATION_PLAYLISTS", {}, this)
  906. .then(response => {
  907. async.eachLimit(
  908. response.playlists,
  909. 1,
  910. (playlist, next) => {
  911. this.publishProgress({ status: "update", message: `Deleting "${playlist._id}"` });
  912. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  913. .then(() => {
  914. this.log("INFO", "Deleting orphaned station playlist");
  915. next();
  916. })
  917. .catch(err => {
  918. next(err);
  919. });
  920. },
  921. err => {
  922. if (err) reject(new Error(err));
  923. else resolve({});
  924. }
  925. );
  926. })
  927. .catch(err => {
  928. reject(new Error(err));
  929. });
  930. });
  931. }
  932. /**
  933. * Fills a station playlist with songs
  934. *
  935. * @param {object} payload - object that contains the payload
  936. * @param {string} payload.stationId - the station id
  937. * @returns {Promise} - returns promise (reject, resolve)
  938. */
  939. AUTOFILL_STATION_PLAYLIST(payload) {
  940. return new Promise((resolve, reject) => {
  941. let originalPlaylist = null;
  942. async.waterfall(
  943. [
  944. next => {
  945. if (!payload.stationId) next("Please specify a station id");
  946. else next();
  947. },
  948. next => {
  949. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  950. .then(station => {
  951. next(null, station);
  952. })
  953. .catch(next);
  954. },
  955. (station, next) => {
  956. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: station.playlist }, this)
  957. .then(playlist => {
  958. originalPlaylist = playlist;
  959. next(null, station);
  960. })
  961. .catch(err => {
  962. next(err);
  963. });
  964. },
  965. (station, next) => {
  966. const playlists = [];
  967. async.eachLimit(
  968. station.autofill.playlists,
  969. 1,
  970. (playlistId, next) => {
  971. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  972. .then(playlist => {
  973. playlists.push(playlist);
  974. next();
  975. })
  976. .catch(next);
  977. },
  978. err => {
  979. next(err, station, playlists);
  980. }
  981. );
  982. },
  983. (station, playlists, next) => {
  984. const blacklist = [];
  985. async.eachLimit(
  986. station.blacklist,
  987. 1,
  988. (playlistId, next) => {
  989. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  990. .then(playlist => {
  991. blacklist.push(playlist);
  992. next();
  993. })
  994. .catch(next);
  995. },
  996. err => {
  997. next(err, station, playlists, blacklist);
  998. }
  999. );
  1000. },
  1001. (station, playlists, blacklist, next) => {
  1002. const blacklistedSongs = blacklist
  1003. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  1004. .reduce(
  1005. (items, item) =>
  1006. items.find(x => x.mediaSource === item.mediaSource) ? [...items] : [...items, item],
  1007. []
  1008. );
  1009. const includedSongs = playlists
  1010. .flatMap(playlist => playlist.songs)
  1011. .reduce(
  1012. (songs, song) =>
  1013. songs.find(x => x.mediaSource === song.mediaSource) ? [...songs] : [...songs, song],
  1014. []
  1015. )
  1016. .filter(song => !blacklistedSongs.find(x => x.mediaSource === song.mediaSource));
  1017. next(null, station, includedSongs);
  1018. },
  1019. (station, includedSongs, next) => {
  1020. PlaylistsModule.playlistModel.updateOne(
  1021. { _id: station.playlist },
  1022. { $set: { songs: includedSongs } },
  1023. err => {
  1024. next(err, includedSongs);
  1025. }
  1026. );
  1027. },
  1028. (includedSongs, next) => {
  1029. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: originalPlaylist._id }, this)
  1030. .then(() => {
  1031. next(null, includedSongs);
  1032. })
  1033. .catch(next);
  1034. },
  1035. (includedSongs, next) => {
  1036. if (originalPlaylist.songs.length === 0 && includedSongs.length > 0)
  1037. StationsModule.runJob("SKIP_STATION", {
  1038. stationId: payload.stationId,
  1039. natural: false,
  1040. skipReason: "other"
  1041. });
  1042. next();
  1043. }
  1044. ],
  1045. err => {
  1046. if (err && err !== true) return reject(new Error(err));
  1047. return resolve({});
  1048. }
  1049. );
  1050. });
  1051. }
  1052. /**
  1053. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  1054. *
  1055. * @param {object} payload - object that contains the payload
  1056. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  1057. * @returns {Promise} - returns promise (reject, resolve)
  1058. */
  1059. GET_PLAYLIST(payload) {
  1060. return new Promise((resolve, reject) => {
  1061. async.waterfall(
  1062. [
  1063. next => {
  1064. CacheModule.runJob(
  1065. "HGET",
  1066. {
  1067. table: "playlists",
  1068. key: payload.playlistId
  1069. },
  1070. this
  1071. )
  1072. .then(playlist => next(null, playlist))
  1073. .catch(next);
  1074. },
  1075. (playlist, next) => {
  1076. if (playlist)
  1077. PlaylistsModule.playlistModel.exists({ _id: payload.playlistId }, (err, exists) => {
  1078. if (err) next(err);
  1079. else if (exists) next(null, playlist);
  1080. else {
  1081. CacheModule.runJob(
  1082. "HDEL",
  1083. {
  1084. table: "playlists",
  1085. key: payload.playlistId
  1086. },
  1087. this
  1088. )
  1089. .then(() => next())
  1090. .catch(next);
  1091. }
  1092. });
  1093. else PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  1094. },
  1095. (playlist, next) => {
  1096. if (playlist) {
  1097. CacheModule.runJob(
  1098. "HSET",
  1099. {
  1100. table: "playlists",
  1101. key: payload.playlistId,
  1102. value: playlist
  1103. },
  1104. this
  1105. )
  1106. .then(playlist => {
  1107. next(null, playlist);
  1108. })
  1109. .catch(next);
  1110. } else next("Playlist not found");
  1111. }
  1112. ],
  1113. (err, playlist) => {
  1114. if (err && err !== true) return reject(new Error(err));
  1115. return resolve(playlist);
  1116. }
  1117. );
  1118. });
  1119. }
  1120. /**
  1121. * Gets a playlist from id from Mongo and updates the cache with it
  1122. *
  1123. * @param {object} payload - object that contains the payload
  1124. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  1125. * @returns {Promise} - returns promise (reject, resolve)
  1126. */
  1127. UPDATE_PLAYLIST(payload) {
  1128. return new Promise((resolve, reject) => {
  1129. async.waterfall(
  1130. [
  1131. next => {
  1132. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  1133. },
  1134. (playlist, next) => {
  1135. if (!playlist) {
  1136. CacheModule.runJob("HDEL", {
  1137. table: "playlists",
  1138. key: payload.playlistId
  1139. });
  1140. return next("Playlist not found");
  1141. }
  1142. return CacheModule.runJob(
  1143. "HSET",
  1144. {
  1145. table: "playlists",
  1146. key: payload.playlistId,
  1147. value: playlist
  1148. },
  1149. this
  1150. )
  1151. .then(playlist => {
  1152. next(null, playlist);
  1153. })
  1154. .catch(next);
  1155. }
  1156. ],
  1157. (err, playlist) => {
  1158. if (err && err !== true) return reject(new Error(err));
  1159. return resolve(playlist);
  1160. }
  1161. );
  1162. });
  1163. }
  1164. /**
  1165. * Deletes playlist from id from Mongo and cache
  1166. *
  1167. * @param {object} payload - object that contains the payload
  1168. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  1169. * @returns {Promise} - returns promise (reject, resolve)
  1170. */
  1171. DELETE_PLAYLIST(payload) {
  1172. return new Promise((resolve, reject) => {
  1173. async.waterfall(
  1174. [
  1175. next => {
  1176. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  1177. },
  1178. (res, next) => {
  1179. CacheModule.runJob(
  1180. "HDEL",
  1181. {
  1182. table: "playlists",
  1183. key: payload.playlistId
  1184. },
  1185. this
  1186. )
  1187. .then(() => next())
  1188. .catch(next);
  1189. },
  1190. next => {
  1191. StationsModule.runJob(
  1192. "REMOVE_AUTOFILLED_OR_BLACKLISTED_PLAYLIST_FROM_STATIONS",
  1193. { playlistId: payload.playlistId },
  1194. this
  1195. )
  1196. .then(() => {
  1197. next();
  1198. })
  1199. .catch(err => next(err));
  1200. }
  1201. ],
  1202. err => {
  1203. if (err && err !== true) return reject(new Error(err));
  1204. return resolve();
  1205. }
  1206. );
  1207. });
  1208. }
  1209. /**
  1210. * Searches through playlists
  1211. *
  1212. * @param {object} payload - object that contains the payload
  1213. * @param {string} payload.query - the query
  1214. * @param {string} payload.includePrivate - include private playlists
  1215. * @param {string} payload.includeStation - include station playlists
  1216. * @param {string} payload.includeUser - include user playlists
  1217. * @param {string} payload.includeGenre - include genre playlists
  1218. * @param {string} payload.includeAdmin - include admin playlists
  1219. * @param {string} payload.includeOwn - include own user playlists
  1220. * @param {string} payload.userId - the user id of the person requesting
  1221. * @param {string} payload.includeSongs - include songs
  1222. * @param {string} payload.page - page (default 1)
  1223. * @returns {Promise} - returns promise (reject, resolve)
  1224. */
  1225. SEARCH(payload) {
  1226. return new Promise((resolve, reject) => {
  1227. async.waterfall(
  1228. [
  1229. next => {
  1230. const types = [];
  1231. if (payload.includeStation) types.push("station");
  1232. if (payload.includeUser) types.push("user");
  1233. if (payload.includeGenre) types.push("genre");
  1234. if (payload.includeAdmin) types.push("admin");
  1235. if (types.length === 0 && !payload.includeOwn) return next("No types have been included.");
  1236. const privacies = ["public"];
  1237. if (payload.includePrivate) privacies.push("private");
  1238. const includeObject = payload.includeSongs ? null : { songs: false };
  1239. const filterArray = [
  1240. {
  1241. displayName: new RegExp(`${payload.query}`, "i"),
  1242. privacy: { $in: privacies },
  1243. type: { $in: types }
  1244. }
  1245. ];
  1246. if (payload.includeOwn && payload.userId)
  1247. filterArray.push({
  1248. displayName: new RegExp(`${payload.query}`, "i"),
  1249. type: "user",
  1250. createdBy: payload.userId
  1251. });
  1252. return next(null, filterArray, includeObject);
  1253. },
  1254. (filterArray, includeObject, next) => {
  1255. const page = payload.page ? payload.page : 1;
  1256. const pageSize = 15;
  1257. const skipAmount = pageSize * (page - 1);
  1258. PlaylistsModule.playlistModel.find({ $or: filterArray }).count((err, count) => {
  1259. if (err) next(err);
  1260. else {
  1261. PlaylistsModule.playlistModel
  1262. .find({ $or: filterArray }, includeObject)
  1263. .skip(skipAmount)
  1264. .limit(pageSize)
  1265. .exec((err, playlists) => {
  1266. if (err) next(err);
  1267. else {
  1268. next(null, {
  1269. playlists,
  1270. page,
  1271. pageSize,
  1272. skipAmount,
  1273. count
  1274. });
  1275. }
  1276. });
  1277. }
  1278. });
  1279. },
  1280. (data, next) => {
  1281. if (data.playlists.length > 0) next(null, data);
  1282. else next("No playlists found");
  1283. }
  1284. ],
  1285. (err, data) => {
  1286. if (err && err !== true) return reject(new Error(err));
  1287. return resolve(data);
  1288. }
  1289. );
  1290. });
  1291. }
  1292. /**
  1293. * Clears and refills a station playlist
  1294. *
  1295. * @param {object} payload - object that contains the payload
  1296. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1297. * @returns {Promise} - returns promise (reject, resolve)
  1298. */
  1299. CLEAR_AND_REFILL_STATION_PLAYLIST(payload) {
  1300. return new Promise((resolve, reject) => {
  1301. const { playlistId } = payload;
  1302. async.waterfall(
  1303. [
  1304. next => {
  1305. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1306. .then(playlist => {
  1307. next(null, playlist);
  1308. })
  1309. .catch(err => {
  1310. next(err);
  1311. });
  1312. },
  1313. (playlist, next) => {
  1314. if (playlist.type !== "station") next("This playlist is not a station playlist.");
  1315. else next(null, playlist.createdFor);
  1316. },
  1317. (stationId, next) => {
  1318. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)
  1319. .then(() => {
  1320. next();
  1321. })
  1322. .catch(err => {
  1323. next(err);
  1324. });
  1325. }
  1326. ],
  1327. err => {
  1328. if (err && err !== true) return reject(new Error(err));
  1329. return resolve();
  1330. }
  1331. );
  1332. });
  1333. }
  1334. /**
  1335. * Clears and refills a genre playlist
  1336. *
  1337. * @param {object} payload - object that contains the payload
  1338. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1339. * @returns {Promise} - returns promise (reject, resolve)
  1340. */
  1341. CLEAR_AND_REFILL_GENRE_PLAYLIST(payload) {
  1342. return new Promise((resolve, reject) => {
  1343. const { playlistId } = payload;
  1344. async.waterfall(
  1345. [
  1346. next => {
  1347. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1348. .then(playlist => {
  1349. next(null, playlist);
  1350. })
  1351. .catch(err => {
  1352. next(err);
  1353. });
  1354. },
  1355. (playlist, next) => {
  1356. if (playlist.type !== "genre") next("This playlist is not a genre playlist.");
  1357. else next(null, playlist.createdFor);
  1358. },
  1359. (genre, next) => {
  1360. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: true }, this)
  1361. .then(() => {
  1362. next();
  1363. })
  1364. .catch(err => {
  1365. next(err);
  1366. });
  1367. }
  1368. ],
  1369. err => {
  1370. if (err && err !== true) return reject(new Error(err));
  1371. return resolve();
  1372. }
  1373. );
  1374. });
  1375. }
  1376. }
  1377. export default new _PlaylistsModule();