playlists.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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.youtubeId - the youtube id
  384. * @returns {Promise} - returns promise (reject, resolve)
  385. */
  386. ADD_SONG_TO_PLAYLIST(payload) {
  387. return new Promise((resolve, reject) => {
  388. const { playlistId, youtubeId } = 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.youtubeId === youtubeId))
  401. return next("That song is already in the playlist.");
  402. return next();
  403. },
  404. next => {
  405. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  406. .then(response => {
  407. const { song } = response;
  408. const { _id, title, artists, thumbnail, duration, verified } = song;
  409. next(null, {
  410. _id,
  411. youtubeId,
  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. youtubeId: newSong.youtubeId
  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. * Remove from playlist
  474. *
  475. * @param {object} payload - object that contains the payload
  476. * @param {string} payload.playlistId - the playlist id
  477. * @param {string} payload.youtubeId - the youtube id
  478. * @returns {Promise} - returns a promise (resolve, reject)
  479. */
  480. REMOVE_FROM_PLAYLIST(payload) {
  481. return new Promise((resolve, reject) => {
  482. const { playlistId, youtubeId } = payload;
  483. async.waterfall(
  484. [
  485. next => {
  486. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  487. .then(playlist => {
  488. next(null, playlist);
  489. })
  490. .catch(next);
  491. },
  492. (playlist, next) => {
  493. if (!playlist) return next("Playlist not found.");
  494. if (!playlist.songs.find(song => song.youtubeId === youtubeId))
  495. return next("That song is not currently in the playlist.");
  496. return PlaylistsModule.playlistModel.updateOne(
  497. { _id: playlistId },
  498. { $pull: { songs: { youtubeId } } },
  499. next
  500. );
  501. },
  502. (res, next) => {
  503. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  504. .then(playlist => next(null, playlist))
  505. .catch(next);
  506. },
  507. (playlist, next) => {
  508. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId })
  509. .then(response => {
  510. async.each(
  511. response.stationIds,
  512. (stationId, next) => {
  513. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId })
  514. .then()
  515. .catch();
  516. next();
  517. },
  518. err => {
  519. if (err) next(err);
  520. else next(null, playlist);
  521. }
  522. );
  523. })
  524. .catch(next);
  525. },
  526. (playlist, next) => {
  527. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  528. MediaModule.runJob("RECALCULATE_RATINGS", { youtubeId })
  529. .then(ratings => next(null, playlist, ratings))
  530. .catch(next);
  531. } else next(null, playlist, null);
  532. },
  533. (playlist, ratings, next) =>
  534. CacheModule.runJob(
  535. "PUB",
  536. {
  537. channel: "playlist.updated",
  538. value: { playlistId }
  539. },
  540. this
  541. )
  542. .then(() => next(null, playlist, ratings))
  543. .catch(next)
  544. ],
  545. (err, playlist, ratings) => {
  546. if (err) reject(err);
  547. else resolve({ playlist, ratings });
  548. }
  549. );
  550. });
  551. }
  552. /**
  553. * Deletes a song from a playlist based on the youtube id
  554. *
  555. * @param {object} payload - object that contains the payload
  556. * @param {string} payload.playlistId - the playlist id
  557. * @param {string} payload.youtubeId - the youtube id
  558. * @returns {Promise} - returns promise (reject, resolve)
  559. */
  560. DELETE_SONG_FROM_PLAYLIST_BY_YOUTUBE_ID(payload) {
  561. return new Promise((resolve, reject) => {
  562. PlaylistsModule.playlistModel.updateOne(
  563. { _id: payload.playlistId },
  564. { $pull: { songs: { youtubeId: payload.youtubeId } } },
  565. err => {
  566. if (err) reject(new Error(err));
  567. else {
  568. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  569. .then(() => resolve())
  570. .catch(err => {
  571. reject(new Error(err));
  572. });
  573. }
  574. }
  575. );
  576. });
  577. }
  578. /**
  579. * Fills a genre playlist with songs
  580. *
  581. * @param {object} payload - object that contains the payload
  582. * @param {string} payload.genre - the genre
  583. * @param {string} payload.createPlaylist - create playlist if it doesn't exist, default false
  584. * @returns {Promise} - returns promise (reject, resolve)
  585. */
  586. AUTOFILL_GENRE_PLAYLIST(payload) {
  587. return new Promise((resolve, reject) => {
  588. async.waterfall(
  589. [
  590. next => {
  591. PlaylistsModule.runJob(
  592. "GET_GENRE_PLAYLIST",
  593. { genre: payload.genre.toLowerCase(), includeSongs: true },
  594. this
  595. )
  596. .then(response => {
  597. next(null, response.playlist._id);
  598. })
  599. .catch(err => {
  600. if (err.message === "Playlist not found") {
  601. if (payload.createPlaylist)
  602. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)
  603. .then(playlistId => {
  604. next(null, playlistId);
  605. })
  606. .catch(err => {
  607. next(err);
  608. });
  609. } else next(err);
  610. });
  611. },
  612. (playlistId, next) => {
  613. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)
  614. .then(response => {
  615. next(null, playlistId, response.songs);
  616. })
  617. .catch(err => {
  618. console.log(err);
  619. next(err);
  620. });
  621. },
  622. (playlistId, _songs, next) => {
  623. const songs = _songs.map(song => {
  624. const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;
  625. return {
  626. _id,
  627. youtubeId,
  628. title,
  629. artists,
  630. thumbnail,
  631. duration,
  632. verified
  633. };
  634. });
  635. PlaylistsModule.playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, err => {
  636. next(err, playlistId);
  637. });
  638. },
  639. (playlistId, next) => {
  640. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  641. .then(() => {
  642. next(null, playlistId);
  643. })
  644. .catch(next);
  645. },
  646. (playlistId, next) => {
  647. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId }, this)
  648. .then(response => {
  649. async.eachLimit(
  650. response.stationIds,
  651. 1,
  652. (stationId, next) => {
  653. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)
  654. .then(() => {
  655. next();
  656. })
  657. .catch(err => {
  658. next(err);
  659. });
  660. },
  661. err => {
  662. if (err) next(err);
  663. else next();
  664. }
  665. );
  666. })
  667. .catch(err => {
  668. next(err);
  669. });
  670. }
  671. ],
  672. err => {
  673. if (err && err !== true) return reject(new Error(err));
  674. return resolve({});
  675. }
  676. );
  677. });
  678. }
  679. /**
  680. * Gets orphaned genre playlists
  681. *
  682. * @returns {Promise} - returns promise (reject, resolve)
  683. */
  684. GET_ORPHANED_GENRE_PLAYLISTS() {
  685. return new Promise((resolve, reject) => {
  686. PlaylistsModule.playlistModel.find({ type: "genre" }, { songs: false }, (err, playlists) => {
  687. if (err) reject(new Error(err));
  688. else {
  689. const orphanedPlaylists = [];
  690. async.eachLimit(
  691. playlists,
  692. 1,
  693. (playlist, next) => {
  694. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: playlist.createdFor }, this)
  695. .then(response => {
  696. if (response.songs.length === 0) {
  697. StationsModule.runJob(
  698. "GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST",
  699. { playlistId: playlist._id },
  700. this
  701. )
  702. .then(response => {
  703. if (response.stationIds.length === 0) orphanedPlaylists.push(playlist);
  704. next();
  705. })
  706. .catch(next);
  707. } else next();
  708. })
  709. .catch(next);
  710. },
  711. err => {
  712. if (err) reject(new Error(err));
  713. else resolve({ playlists: orphanedPlaylists });
  714. }
  715. );
  716. }
  717. });
  718. });
  719. }
  720. /**
  721. * Deletes all orphaned genre playlists
  722. *
  723. * @returns {Promise} - returns promise (reject, resolve)
  724. */
  725. DELETE_ORPHANED_GENRE_PLAYLISTS() {
  726. return new Promise((resolve, reject) => {
  727. PlaylistsModule.runJob("GET_ORPHANED_GENRE_PLAYLISTS", {}, this)
  728. .then(response => {
  729. async.eachLimit(
  730. response.playlists,
  731. 1,
  732. (playlist, next) => {
  733. this.publishProgress({ status: "update", message: `Deleting "${playlist._id}"` });
  734. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  735. .then(() => {
  736. this.log("INFO", "Deleting orphaned genre playlist");
  737. next();
  738. })
  739. .catch(err => {
  740. next(err);
  741. });
  742. },
  743. err => {
  744. if (err) reject(new Error(err));
  745. else resolve({});
  746. }
  747. );
  748. })
  749. .catch(err => {
  750. reject(new Error(err));
  751. });
  752. });
  753. }
  754. /**
  755. * Gets a orphaned station playlists
  756. *
  757. * @returns {Promise} - returns promise (reject, resolve)
  758. */
  759. GET_ORPHANED_STATION_PLAYLISTS() {
  760. return new Promise((resolve, reject) => {
  761. PlaylistsModule.playlistModel.find({ type: "station" }, { songs: false }, (err, playlists) => {
  762. if (err) reject(new Error(err));
  763. else {
  764. const orphanedPlaylists = [];
  765. async.eachLimit(
  766. playlists,
  767. 1,
  768. (playlist, next) => {
  769. StationsModule.runJob("GET_STATION", { stationId: playlist.createdFor }, this)
  770. .then(station => {
  771. if (station.playlist !== playlist._id.toString()) {
  772. orphanedPlaylists.push(playlist);
  773. }
  774. next();
  775. })
  776. .catch(err => {
  777. if (err.message === "Station not found") {
  778. orphanedPlaylists.push(playlist);
  779. next();
  780. } else next(err);
  781. });
  782. },
  783. err => {
  784. if (err) reject(new Error(err));
  785. else resolve({ playlists: orphanedPlaylists });
  786. }
  787. );
  788. }
  789. });
  790. });
  791. }
  792. /**
  793. * Deletes all orphaned station playlists
  794. *
  795. * @returns {Promise} - returns promise (reject, resolve)
  796. */
  797. DELETE_ORPHANED_STATION_PLAYLISTS() {
  798. return new Promise((resolve, reject) => {
  799. PlaylistsModule.runJob("GET_ORPHANED_STATION_PLAYLISTS", {}, this)
  800. .then(response => {
  801. async.eachLimit(
  802. response.playlists,
  803. 1,
  804. (playlist, next) => {
  805. this.publishProgress({ status: "update", message: `Deleting "${playlist._id}"` });
  806. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  807. .then(() => {
  808. this.log("INFO", "Deleting orphaned station playlist");
  809. next();
  810. })
  811. .catch(err => {
  812. next(err);
  813. });
  814. },
  815. err => {
  816. if (err) reject(new Error(err));
  817. else resolve({});
  818. }
  819. );
  820. })
  821. .catch(err => {
  822. reject(new Error(err));
  823. });
  824. });
  825. }
  826. /**
  827. * Fills a station playlist with songs
  828. *
  829. * @param {object} payload - object that contains the payload
  830. * @param {string} payload.stationId - the station id
  831. * @returns {Promise} - returns promise (reject, resolve)
  832. */
  833. AUTOFILL_STATION_PLAYLIST(payload) {
  834. return new Promise((resolve, reject) => {
  835. let originalPlaylist = null;
  836. async.waterfall(
  837. [
  838. next => {
  839. if (!payload.stationId) next("Please specify a station id");
  840. else next();
  841. },
  842. next => {
  843. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  844. .then(station => {
  845. next(null, station);
  846. })
  847. .catch(next);
  848. },
  849. (station, next) => {
  850. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: station.playlist }, this)
  851. .then(playlist => {
  852. originalPlaylist = playlist;
  853. next(null, station);
  854. })
  855. .catch(err => {
  856. next(err);
  857. });
  858. },
  859. (station, next) => {
  860. const playlists = [];
  861. async.eachLimit(
  862. station.autofill.playlists,
  863. 1,
  864. (playlistId, next) => {
  865. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  866. .then(playlist => {
  867. playlists.push(playlist);
  868. next();
  869. })
  870. .catch(next);
  871. },
  872. err => {
  873. next(err, station, playlists);
  874. }
  875. );
  876. },
  877. (station, playlists, next) => {
  878. const blacklist = [];
  879. async.eachLimit(
  880. station.blacklist,
  881. 1,
  882. (playlistId, next) => {
  883. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  884. .then(playlist => {
  885. blacklist.push(playlist);
  886. next();
  887. })
  888. .catch(next);
  889. },
  890. err => {
  891. next(err, station, playlists, blacklist);
  892. }
  893. );
  894. },
  895. (station, playlists, blacklist, next) => {
  896. const blacklistedSongs = blacklist
  897. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  898. .reduce(
  899. (items, item) =>
  900. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  901. []
  902. );
  903. const includedSongs = playlists
  904. .flatMap(playlist => playlist.songs)
  905. .reduce(
  906. (songs, song) =>
  907. songs.find(x => x.youtubeId === song.youtubeId) ? [...songs] : [...songs, song],
  908. []
  909. )
  910. .filter(song => !blacklistedSongs.find(x => x.youtubeId === song.youtubeId));
  911. next(null, station, includedSongs);
  912. },
  913. (station, includedSongs, next) => {
  914. PlaylistsModule.playlistModel.updateOne(
  915. { _id: station.playlist },
  916. { $set: { songs: includedSongs } },
  917. err => {
  918. next(err, includedSongs);
  919. }
  920. );
  921. },
  922. (includedSongs, next) => {
  923. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: originalPlaylist._id }, this)
  924. .then(() => {
  925. next(null, includedSongs);
  926. })
  927. .catch(next);
  928. },
  929. (includedSongs, next) => {
  930. if (originalPlaylist.songs.length === 0 && includedSongs.length > 0)
  931. StationsModule.runJob("SKIP_STATION", {
  932. stationId: payload.stationId,
  933. natural: false,
  934. skipReason: "other"
  935. });
  936. next();
  937. }
  938. ],
  939. err => {
  940. if (err && err !== true) return reject(new Error(err));
  941. return resolve({});
  942. }
  943. );
  944. });
  945. }
  946. /**
  947. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  948. *
  949. * @param {object} payload - object that contains the payload
  950. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  951. * @returns {Promise} - returns promise (reject, resolve)
  952. */
  953. GET_PLAYLIST(payload) {
  954. return new Promise((resolve, reject) => {
  955. async.waterfall(
  956. [
  957. next => {
  958. CacheModule.runJob(
  959. "HGET",
  960. {
  961. table: "playlists",
  962. key: payload.playlistId
  963. },
  964. this
  965. )
  966. .then(playlist => next(null, playlist))
  967. .catch(next);
  968. },
  969. (playlist, next) => {
  970. if (playlist)
  971. PlaylistsModule.playlistModel.exists({ _id: payload.playlistId }, (err, exists) => {
  972. if (err) next(err);
  973. else if (exists) next(null, playlist);
  974. else {
  975. CacheModule.runJob(
  976. "HDEL",
  977. {
  978. table: "playlists",
  979. key: payload.playlistId
  980. },
  981. this
  982. )
  983. .then(() => next())
  984. .catch(next);
  985. }
  986. });
  987. else PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  988. },
  989. (playlist, next) => {
  990. if (playlist) {
  991. CacheModule.runJob(
  992. "HSET",
  993. {
  994. table: "playlists",
  995. key: payload.playlistId,
  996. value: playlist
  997. },
  998. this
  999. )
  1000. .then(playlist => {
  1001. next(null, playlist);
  1002. })
  1003. .catch(next);
  1004. } else next("Playlist not found");
  1005. }
  1006. ],
  1007. (err, playlist) => {
  1008. if (err && err !== true) return reject(new Error(err));
  1009. return resolve(playlist);
  1010. }
  1011. );
  1012. });
  1013. }
  1014. /**
  1015. * Gets a playlist from id from Mongo and updates the cache with it
  1016. *
  1017. * @param {object} payload - object that contains the payload
  1018. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  1019. * @returns {Promise} - returns promise (reject, resolve)
  1020. */
  1021. UPDATE_PLAYLIST(payload) {
  1022. return new Promise((resolve, reject) => {
  1023. async.waterfall(
  1024. [
  1025. next => {
  1026. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  1027. },
  1028. (playlist, next) => {
  1029. if (!playlist) {
  1030. CacheModule.runJob("HDEL", {
  1031. table: "playlists",
  1032. key: payload.playlistId
  1033. });
  1034. return next("Playlist not found");
  1035. }
  1036. return CacheModule.runJob(
  1037. "HSET",
  1038. {
  1039. table: "playlists",
  1040. key: payload.playlistId,
  1041. value: playlist
  1042. },
  1043. this
  1044. )
  1045. .then(playlist => {
  1046. next(null, playlist);
  1047. })
  1048. .catch(next);
  1049. }
  1050. ],
  1051. (err, playlist) => {
  1052. if (err && err !== true) return reject(new Error(err));
  1053. return resolve(playlist);
  1054. }
  1055. );
  1056. });
  1057. }
  1058. /**
  1059. * Deletes playlist from id from Mongo and cache
  1060. *
  1061. * @param {object} payload - object that contains the payload
  1062. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  1063. * @returns {Promise} - returns promise (reject, resolve)
  1064. */
  1065. DELETE_PLAYLIST(payload) {
  1066. return new Promise((resolve, reject) => {
  1067. async.waterfall(
  1068. [
  1069. next => {
  1070. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  1071. },
  1072. (res, next) => {
  1073. CacheModule.runJob(
  1074. "HDEL",
  1075. {
  1076. table: "playlists",
  1077. key: payload.playlistId
  1078. },
  1079. this
  1080. )
  1081. .then(() => next())
  1082. .catch(next);
  1083. },
  1084. next => {
  1085. StationsModule.runJob(
  1086. "REMOVE_AUTOFILLED_OR_BLACKLISTED_PLAYLIST_FROM_STATIONS",
  1087. { playlistId: payload.playlistId },
  1088. this
  1089. )
  1090. .then(() => {
  1091. next();
  1092. })
  1093. .catch(err => next(err));
  1094. }
  1095. ],
  1096. err => {
  1097. if (err && err !== true) return reject(new Error(err));
  1098. return resolve();
  1099. }
  1100. );
  1101. });
  1102. }
  1103. /**
  1104. * Searches through playlists
  1105. *
  1106. * @param {object} payload - object that contains the payload
  1107. * @param {string} payload.query - the query
  1108. * @param {string} payload.includePrivate - include private playlists
  1109. * @param {string} payload.includeStation - include station playlists
  1110. * @param {string} payload.includeUser - include user playlists
  1111. * @param {string} payload.includeGenre - include genre playlists
  1112. * @param {string} payload.includeAdmin - include admin playlists
  1113. * @param {string} payload.includeOwn - include own user playlists
  1114. * @param {string} payload.userId - the user id of the person requesting
  1115. * @param {string} payload.includeSongs - include songs
  1116. * @param {string} payload.page - page (default 1)
  1117. * @returns {Promise} - returns promise (reject, resolve)
  1118. */
  1119. SEARCH(payload) {
  1120. return new Promise((resolve, reject) => {
  1121. async.waterfall(
  1122. [
  1123. next => {
  1124. const types = [];
  1125. if (payload.includeStation) types.push("station");
  1126. if (payload.includeUser) types.push("user");
  1127. if (payload.includeGenre) types.push("genre");
  1128. if (payload.includeAdmin) types.push("admin");
  1129. if (types.length === 0 && !payload.includeOwn) return next("No types have been included.");
  1130. const privacies = ["public"];
  1131. if (payload.includePrivate) privacies.push("private");
  1132. const includeObject = payload.includeSongs ? null : { songs: false };
  1133. const filterArray = [
  1134. {
  1135. displayName: new RegExp(`${payload.query}`, "i"),
  1136. privacy: { $in: privacies },
  1137. type: { $in: types }
  1138. }
  1139. ];
  1140. if (payload.includeOwn && payload.userId)
  1141. filterArray.push({
  1142. displayName: new RegExp(`${payload.query}`, "i"),
  1143. type: "user",
  1144. createdBy: payload.userId
  1145. });
  1146. return next(null, filterArray, includeObject);
  1147. },
  1148. (filterArray, includeObject, next) => {
  1149. const page = payload.page ? payload.page : 1;
  1150. const pageSize = 15;
  1151. const skipAmount = pageSize * (page - 1);
  1152. PlaylistsModule.playlistModel.find({ $or: filterArray }).count((err, count) => {
  1153. if (err) next(err);
  1154. else {
  1155. PlaylistsModule.playlistModel
  1156. .find({ $or: filterArray }, includeObject)
  1157. .skip(skipAmount)
  1158. .limit(pageSize)
  1159. .exec((err, playlists) => {
  1160. if (err) next(err);
  1161. else {
  1162. next(null, {
  1163. playlists,
  1164. page,
  1165. pageSize,
  1166. skipAmount,
  1167. count
  1168. });
  1169. }
  1170. });
  1171. }
  1172. });
  1173. },
  1174. (data, next) => {
  1175. if (data.playlists.length > 0) next(null, data);
  1176. else next("No playlists found");
  1177. }
  1178. ],
  1179. (err, data) => {
  1180. if (err && err !== true) return reject(new Error(err));
  1181. return resolve(data);
  1182. }
  1183. );
  1184. });
  1185. }
  1186. /**
  1187. * Clears and refills a station playlist
  1188. *
  1189. * @param {object} payload - object that contains the payload
  1190. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1191. * @returns {Promise} - returns promise (reject, resolve)
  1192. */
  1193. CLEAR_AND_REFILL_STATION_PLAYLIST(payload) {
  1194. return new Promise((resolve, reject) => {
  1195. const { playlistId } = payload;
  1196. async.waterfall(
  1197. [
  1198. next => {
  1199. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1200. .then(playlist => {
  1201. next(null, playlist);
  1202. })
  1203. .catch(err => {
  1204. next(err);
  1205. });
  1206. },
  1207. (playlist, next) => {
  1208. if (playlist.type !== "station") next("This playlist is not a station playlist.");
  1209. else next(null, playlist.createdFor);
  1210. },
  1211. (stationId, next) => {
  1212. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)
  1213. .then(() => {
  1214. next();
  1215. })
  1216. .catch(err => {
  1217. next(err);
  1218. });
  1219. }
  1220. ],
  1221. err => {
  1222. if (err && err !== true) return reject(new Error(err));
  1223. return resolve();
  1224. }
  1225. );
  1226. });
  1227. }
  1228. /**
  1229. * Clears and refills a genre playlist
  1230. *
  1231. * @param {object} payload - object that contains the payload
  1232. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1233. * @returns {Promise} - returns promise (reject, resolve)
  1234. */
  1235. CLEAR_AND_REFILL_GENRE_PLAYLIST(payload) {
  1236. return new Promise((resolve, reject) => {
  1237. const { playlistId } = payload;
  1238. async.waterfall(
  1239. [
  1240. next => {
  1241. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1242. .then(playlist => {
  1243. next(null, playlist);
  1244. })
  1245. .catch(err => {
  1246. next(err);
  1247. });
  1248. },
  1249. (playlist, next) => {
  1250. if (playlist.type !== "genre") next("This playlist is not a genre playlist.");
  1251. else next(null, playlist.createdFor);
  1252. },
  1253. (genre, next) => {
  1254. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: true }, this)
  1255. .then(() => {
  1256. next();
  1257. })
  1258. .catch(err => {
  1259. next(err);
  1260. });
  1261. }
  1262. ],
  1263. err => {
  1264. if (err && err !== true) return reject(new Error(err));
  1265. return resolve();
  1266. }
  1267. );
  1268. });
  1269. }
  1270. }
  1271. export default new _PlaylistsModule();