playlists.js 36 KB

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