playlists.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  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 or property exists for totalLength, add totalLength property to all documents
  834. (pipeline, next) => {
  835. const { queries, properties } = payload;
  836. // Check if a filter with the totalLength property exists
  837. const totalLengthFilterExists =
  838. queries.map(query => query.filter.property).indexOf("totalLength") !== -1;
  839. // Check if a property with the totalLength property exists
  840. const totalLengthPropertyExists = properties.indexOf("totalLength") !== -1;
  841. // If no such filter or property exists, skip this function
  842. if (!totalLengthFilterExists && !totalLengthPropertyExists) return next(null, pipeline);
  843. // Adds totalLength field which is the sum of all durations of all songs in the songs array
  844. pipeline.push({
  845. $addFields: {
  846. totalLength: { $sum: "$songs.duration" }
  847. }
  848. });
  849. return next(null, pipeline);
  850. },
  851. // If a filter or property exists for songsCount, add songsCount property to all documents
  852. (pipeline, next) => {
  853. const { queries, properties } = payload;
  854. // Check if a filter with the songsCount property exists
  855. const songsCountFilterExists =
  856. queries.map(query => query.filter.property).indexOf("songsCount") !== -1;
  857. // Check if a property with the songsCount property exists
  858. const songsCountPropertyExists = properties.indexOf("songsCount") !== -1;
  859. // If no such filter or property exists, skip this function
  860. if (!songsCountFilterExists && !songsCountPropertyExists) return next(null, pipeline);
  861. // Adds songsCount field which is the length of the songs array
  862. pipeline.push({
  863. $addFields: {
  864. songsCount: { $size: "$songs" }
  865. }
  866. });
  867. return next(null, pipeline);
  868. },
  869. // If a filter exists for createdBy, add createdByUsername property to all documents
  870. (pipeline, next) => {
  871. const { queries } = payload;
  872. // Check if a filter with the createdBy property exists
  873. const createdByFilterExists =
  874. queries.map(query => query.filter.property).indexOf("createdBy") !== -1;
  875. // If no such filter exists, skip this function
  876. if (!createdByFilterExists) return next(null, pipeline);
  877. // Adds createdByOID field, which is an ObjectId version of createdBy
  878. pipeline.push({
  879. $addFields: {
  880. createdByOID: {
  881. $convert: {
  882. input: "$createdBy",
  883. to: "objectId",
  884. onError: "unknown",
  885. onNull: "unknown"
  886. }
  887. }
  888. }
  889. });
  890. // Looks up user(s) with the same _id as the createdByOID and puts the result in the createdByUser field
  891. pipeline.push({
  892. $lookup: {
  893. from: "users",
  894. localField: "createdByOID",
  895. foreignField: "_id",
  896. as: "createdByUser"
  897. }
  898. });
  899. // Unwinds the createdByUser array field into an object
  900. pipeline.push({
  901. $unwind: {
  902. path: "$createdByUser",
  903. preserveNullAndEmptyArrays: true
  904. }
  905. });
  906. // Adds createdByUsername field from the createdByUser username, or unknown if it doesn't exist, or Musare if it's set to Musare
  907. pipeline.push({
  908. $addFields: {
  909. createdByUsername: {
  910. $cond: [
  911. { $eq: ["$createdBy", "Musare"] },
  912. "Musare",
  913. { $ifNull: ["$createdByUser.username", "unknown"] }
  914. ]
  915. }
  916. }
  917. });
  918. // Removes the createdByOID and createdByUser property, just in case it doesn't get removed at a later stage
  919. pipeline.push({
  920. $project: {
  921. createdByOID: 0,
  922. createdByUser: 0
  923. }
  924. });
  925. return next(null, pipeline);
  926. },
  927. // Adds the match stage to aggregation pipeline, which is responsible for filtering
  928. (pipeline, next) => {
  929. const { queries, operator } = payload;
  930. let queryError;
  931. const newQueries = queries.flatMap(query => {
  932. const { data, filter, filterType } = query;
  933. const newQuery = {};
  934. if (filterType === "regex") {
  935. newQuery[filter.property] = new RegExp(`${data.slice(1, data.length - 1)}`, "i");
  936. } else if (filterType === "contains") {
  937. newQuery[filter.property] = new RegExp(
  938. `${data.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
  939. "i"
  940. );
  941. } else if (filterType === "exact") {
  942. newQuery[filter.property] = data.toString();
  943. } else if (filterType === "datetimeBefore") {
  944. newQuery[filter.property] = { $lte: new Date(data) };
  945. } else if (filterType === "datetimeAfter") {
  946. newQuery[filter.property] = { $gte: new Date(data) };
  947. } else if (filterType === "numberLesserEqual") {
  948. newQuery[filter.property] = { $lte: data };
  949. } else if (filterType === "numberLesser") {
  950. newQuery[filter.property] = { $lt: data };
  951. } else if (filterType === "numberGreater") {
  952. newQuery[filter.property] = { $gt: data };
  953. } else if (filterType === "numberGreaterEqual") {
  954. newQuery[filter.property] = { $gte: data };
  955. } else if (filterType === "numberEquals" || filterType === "boolean") {
  956. newQuery[filter.property] = { $eq: data };
  957. }
  958. if (filter.property === "createdBy")
  959. return { $or: [newQuery, { createdByUsername: newQuery.createdBy }] };
  960. return newQuery;
  961. });
  962. if (queryError) next(queryError);
  963. const queryObject = {};
  964. if (newQueries.length > 0) {
  965. if (operator === "and") queryObject.$and = newQueries;
  966. else if (operator === "or") queryObject.$or = newQueries;
  967. else if (operator === "nor") queryObject.$nor = newQueries;
  968. }
  969. pipeline.push({ $match: queryObject });
  970. next(null, pipeline);
  971. },
  972. // Adds sort stage to aggregation pipeline if there is at least one column being sorted, responsible for sorting data
  973. (pipeline, next) => {
  974. const { sort } = payload;
  975. const newSort = Object.fromEntries(
  976. Object.entries(sort).map(([property, direction]) => [
  977. property,
  978. direction === "ascending" ? 1 : -1
  979. ])
  980. );
  981. if (Object.keys(newSort).length > 0) pipeline.push({ $sort: newSort });
  982. next(null, pipeline);
  983. },
  984. // Adds first project stage to aggregation pipeline, responsible for including only the requested properties
  985. (pipeline, next) => {
  986. const { properties } = payload;
  987. pipeline.push({ $project: Object.fromEntries(properties.map(property => [property, 1])) });
  988. next(null, pipeline);
  989. },
  990. // Adds the facet stage to aggregation pipeline, responsible for returning a total document count, skipping and limitting the documents that will be returned
  991. (pipeline, next) => {
  992. const { page, pageSize } = payload;
  993. pipeline.push({
  994. $facet: {
  995. count: [{ $count: "count" }],
  996. documents: [{ $skip: pageSize * (page - 1) }, { $limit: pageSize }]
  997. }
  998. });
  999. // console.dir(pipeline, { depth: 6 });
  1000. next(null, pipeline);
  1001. },
  1002. // Executes the aggregation pipeline
  1003. (pipeline, next) => {
  1004. PlaylistsModule.playlistModel.aggregate(pipeline).exec((err, result) => {
  1005. // console.dir(err);
  1006. // console.dir(result, { depth: 6 });
  1007. if (err) return next(err);
  1008. if (result[0].count.length === 0) return next(null, 0, []);
  1009. const { count } = result[0].count[0];
  1010. const { documents } = result[0];
  1011. // console.log(111, err, result, count, documents[0]);
  1012. return next(null, count, documents);
  1013. });
  1014. }
  1015. ],
  1016. (err, count, playlists) => {
  1017. if (err && err !== true) return reject(new Error(err));
  1018. return resolve({ data: playlists, count });
  1019. }
  1020. );
  1021. });
  1022. }
  1023. /**
  1024. * Gets a playlist from id from Mongo and updates the cache with it
  1025. *
  1026. * @param {object} payload - object that contains the payload
  1027. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  1028. * @returns {Promise} - returns promise (reject, resolve)
  1029. */
  1030. UPDATE_PLAYLIST(payload) {
  1031. return new Promise((resolve, reject) =>
  1032. async.waterfall(
  1033. [
  1034. next => {
  1035. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  1036. },
  1037. (playlist, next) => {
  1038. if (!playlist) {
  1039. CacheModule.runJob("HDEL", {
  1040. table: "playlists",
  1041. key: payload.playlistId
  1042. });
  1043. return next("Playlist not found");
  1044. }
  1045. return CacheModule.runJob(
  1046. "HSET",
  1047. {
  1048. table: "playlists",
  1049. key: payload.playlistId,
  1050. value: playlist
  1051. },
  1052. this
  1053. )
  1054. .then(playlist => {
  1055. next(null, playlist);
  1056. })
  1057. .catch(next);
  1058. }
  1059. ],
  1060. (err, playlist) => {
  1061. if (err && err !== true) return reject(new Error(err));
  1062. return resolve(playlist);
  1063. }
  1064. )
  1065. );
  1066. }
  1067. /**
  1068. * Deletes playlist from id from Mongo and cache
  1069. *
  1070. * @param {object} payload - object that contains the payload
  1071. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  1072. * @returns {Promise} - returns promise (reject, resolve)
  1073. */
  1074. DELETE_PLAYLIST(payload) {
  1075. return new Promise((resolve, reject) =>
  1076. async.waterfall(
  1077. [
  1078. next => {
  1079. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  1080. },
  1081. (res, next) => {
  1082. CacheModule.runJob(
  1083. "HDEL",
  1084. {
  1085. table: "playlists",
  1086. key: payload.playlistId
  1087. },
  1088. this
  1089. )
  1090. .then(() => next())
  1091. .catch(next);
  1092. },
  1093. next => {
  1094. StationsModule.runJob(
  1095. "REMOVE_INCLUDED_OR_EXCLUDED_PLAYLIST_FROM_STATIONS",
  1096. { playlistId: payload.playlistId },
  1097. this
  1098. )
  1099. .then(() => {
  1100. next();
  1101. })
  1102. .catch(err => next(err));
  1103. }
  1104. ],
  1105. err => {
  1106. if (err && err !== true) return reject(new Error(err));
  1107. return resolve();
  1108. }
  1109. )
  1110. );
  1111. }
  1112. /**
  1113. * Searches through playlists
  1114. *
  1115. * @param {object} payload - object that contains the payload
  1116. * @param {string} payload.query - the query
  1117. * @param {string} payload.includePrivate - include private playlists
  1118. * @param {string} payload.includeStation - include station playlists
  1119. * @param {string} payload.includeUser - include user playlists
  1120. * @param {string} payload.includeGenre - include genre playlists
  1121. * @param {string} payload.includeOwn - include own user playlists
  1122. * @param {string} payload.userId - the user id of the person requesting
  1123. * @param {string} payload.includeSongs - include songs
  1124. * @param {string} payload.page - page (default 1)
  1125. * @returns {Promise} - returns promise (reject, resolve)
  1126. */
  1127. SEARCH(payload) {
  1128. return new Promise((resolve, reject) =>
  1129. async.waterfall(
  1130. [
  1131. next => {
  1132. const types = [];
  1133. if (payload.includeStation) types.push("station");
  1134. if (payload.includeUser) types.push("user");
  1135. if (payload.includeGenre) types.push("genre");
  1136. if (types.length === 0 && !payload.includeOwn) return next("No types have been included.");
  1137. const privacies = ["public"];
  1138. if (payload.includePrivate) privacies.push("private");
  1139. const includeObject = payload.includeSongs ? null : { songs: false };
  1140. const filterArray = [
  1141. {
  1142. displayName: new RegExp(`${payload.query}`, "i"),
  1143. privacy: { $in: privacies },
  1144. type: { $in: types }
  1145. }
  1146. ];
  1147. if (payload.includeOwn && payload.userId)
  1148. filterArray.push({
  1149. displayName: new RegExp(`${payload.query}`, "i"),
  1150. type: "user",
  1151. createdBy: payload.userId
  1152. });
  1153. return next(null, filterArray, includeObject);
  1154. },
  1155. (filterArray, includeObject, next) => {
  1156. const page = payload.page ? payload.page : 1;
  1157. const pageSize = 15;
  1158. const skipAmount = pageSize * (page - 1);
  1159. PlaylistsModule.playlistModel.find({ $or: filterArray }).count((err, count) => {
  1160. if (err) next(err);
  1161. else {
  1162. PlaylistsModule.playlistModel
  1163. .find({ $or: filterArray }, includeObject)
  1164. .skip(skipAmount)
  1165. .limit(pageSize)
  1166. .exec((err, playlists) => {
  1167. if (err) next(err);
  1168. else {
  1169. next(null, {
  1170. playlists,
  1171. page,
  1172. pageSize,
  1173. skipAmount,
  1174. count
  1175. });
  1176. }
  1177. });
  1178. }
  1179. });
  1180. },
  1181. (data, next) => {
  1182. if (data.playlists.length > 0) next(null, data);
  1183. else next("No playlists found");
  1184. }
  1185. ],
  1186. (err, data) => {
  1187. if (err && err !== true) return reject(new Error(err));
  1188. return resolve(data);
  1189. }
  1190. )
  1191. );
  1192. }
  1193. /**
  1194. * Clears and refills a station playlist
  1195. *
  1196. * @param {object} payload - object that contains the payload
  1197. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1198. * @returns {Promise} - returns promise (reject, resolve)
  1199. */
  1200. CLEAR_AND_REFILL_STATION_PLAYLIST(payload) {
  1201. return new Promise((resolve, reject) => {
  1202. const { playlistId } = payload;
  1203. async.waterfall(
  1204. [
  1205. next => {
  1206. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1207. .then(playlist => {
  1208. next(null, playlist);
  1209. })
  1210. .catch(err => {
  1211. next(err);
  1212. });
  1213. },
  1214. (playlist, next) => {
  1215. if (playlist.type !== "station") next("This playlist is not a station playlist.");
  1216. else next(null, playlist.createdFor);
  1217. },
  1218. (stationId, next) => {
  1219. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)
  1220. .then(() => {
  1221. next();
  1222. })
  1223. .catch(err => {
  1224. next(err);
  1225. });
  1226. }
  1227. ],
  1228. err => {
  1229. if (err && err !== true) return reject(new Error(err));
  1230. return resolve();
  1231. }
  1232. );
  1233. });
  1234. }
  1235. /**
  1236. * Clears and refills a genre playlist
  1237. *
  1238. * @param {object} payload - object that contains the payload
  1239. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1240. * @returns {Promise} - returns promise (reject, resolve)
  1241. */
  1242. CLEAR_AND_REFILL_GENRE_PLAYLIST(payload) {
  1243. return new Promise((resolve, reject) => {
  1244. const { playlistId } = payload;
  1245. async.waterfall(
  1246. [
  1247. next => {
  1248. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1249. .then(playlist => {
  1250. next(null, playlist);
  1251. })
  1252. .catch(err => {
  1253. next(err);
  1254. });
  1255. },
  1256. (playlist, next) => {
  1257. if (playlist.type !== "genre") next("This playlist is not a genre playlist.");
  1258. else next(null, playlist.createdFor);
  1259. },
  1260. (genre, next) => {
  1261. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }, this)
  1262. .then(() => {
  1263. next();
  1264. })
  1265. .catch(err => {
  1266. next(err);
  1267. });
  1268. }
  1269. ],
  1270. err => {
  1271. if (err && err !== true) return reject(new Error(err));
  1272. return resolve();
  1273. }
  1274. );
  1275. });
  1276. }
  1277. }
  1278. export default new _PlaylistsModule();