playlists.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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. // PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", {})
  93. // .then()
  94. // .catch()
  95. // .finally(() => {
  96. // SongsModule.runJob("GET_ALL_GENRES", {})
  97. // .then(response => {
  98. // const { genres } = response;
  99. // genres.forEach(genre => {
  100. // PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }).then().catch();
  101. // });
  102. // })
  103. // .catch();
  104. // });
  105. }
  106. }
  107. )
  108. );
  109. }
  110. /**
  111. * Creates a playlist that is not generated or editable by a user e.g. liked songs playlist
  112. *
  113. * @param {object} payload - object that contains the payload
  114. * @param {string} payload.userId - the id of the user to create the playlist for
  115. * @param {string} payload.displayName - the display name of the playlist
  116. * @returns {Promise} - returns promise (reject, resolve)
  117. */
  118. CREATE_READ_ONLY_PLAYLIST(payload) {
  119. return new Promise((resolve, reject) => {
  120. PlaylistsModule.playlistModel.create(
  121. {
  122. isUserModifiable: false,
  123. displayName: payload.displayName,
  124. songs: [],
  125. createdBy: payload.userId,
  126. createdAt: Date.now(),
  127. createdFor: null,
  128. type: payload.type
  129. },
  130. (err, playlist) => {
  131. if (err) return reject(new Error(err));
  132. return resolve(playlist._id);
  133. }
  134. );
  135. });
  136. }
  137. /**
  138. * Creates a playlist that contains all songs of a specific genre
  139. *
  140. * @param {object} payload - object that contains the payload
  141. * @param {string} payload.genre - the genre
  142. * @returns {Promise} - returns promise (reject, resolve)
  143. */
  144. CREATE_GENRE_PLAYLIST(payload) {
  145. return new Promise((resolve, reject) => {
  146. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre: payload.genre.toLowerCase() }, this)
  147. .then(() => {
  148. reject(new Error("Playlist already exists"));
  149. })
  150. .catch(err => {
  151. if (err.message === "Playlist not found") {
  152. PlaylistsModule.playlistModel.create(
  153. {
  154. isUserModifiable: false,
  155. displayName: `Genre - ${payload.genre}`,
  156. songs: [],
  157. createdBy: "Musare",
  158. createdFor: `${payload.genre.toLowerCase()}`,
  159. createdAt: Date.now(),
  160. type: "genre"
  161. },
  162. (err, playlist) => {
  163. if (err) return reject(new Error(err));
  164. return resolve(playlist._id);
  165. }
  166. );
  167. } else reject(new Error(err));
  168. });
  169. });
  170. }
  171. /**
  172. * Gets all genre playlists
  173. *
  174. * @param {object} payload - object that contains the payload
  175. * @param {string} payload.includeSongs - include the songs
  176. * @returns {Promise} - returns promise (reject, resolve)
  177. */
  178. GET_ALL_GENRE_PLAYLISTS(payload) {
  179. return new Promise((resolve, reject) => {
  180. const includeObject = payload.includeSongs ? null : { songs: false };
  181. PlaylistsModule.playlistModel.find({ type: "genre" }, includeObject, (err, playlists) => {
  182. if (err) reject(new Error(err));
  183. else resolve({ playlists });
  184. });
  185. });
  186. }
  187. /**
  188. * Gets all station playlists
  189. *
  190. * @param {object} payload - object that contains the payload
  191. * @param {string} payload.includeSongs - include the songs
  192. * @returns {Promise} - returns promise (reject, resolve)
  193. */
  194. GET_ALL_STATION_PLAYLISTS(payload) {
  195. return new Promise((resolve, reject) => {
  196. const includeObject = payload.includeSongs ? null : { songs: false };
  197. PlaylistsModule.playlistModel.find({ type: "station" }, includeObject, (err, playlists) => {
  198. if (err) reject(new Error(err));
  199. else resolve({ playlists });
  200. });
  201. });
  202. }
  203. /**
  204. * Gets a genre playlist
  205. *
  206. * @param {object} payload - object that contains the payload
  207. * @param {string} payload.genre - the genre
  208. * @param {string} payload.includeSongs - include the songs
  209. * @returns {Promise} - returns promise (reject, resolve)
  210. */
  211. GET_GENRE_PLAYLIST(payload) {
  212. return new Promise((resolve, reject) => {
  213. const includeObject = payload.includeSongs ? null : { songs: false };
  214. PlaylistsModule.playlistModel.findOne(
  215. { type: "genre", createdFor: payload.genre },
  216. includeObject,
  217. (err, playlist) => {
  218. if (err) reject(new Error(err));
  219. else if (!playlist) reject(new Error("Playlist not found"));
  220. else resolve({ playlist });
  221. }
  222. );
  223. });
  224. }
  225. /**
  226. * Gets all missing genre playlists
  227. *
  228. * @returns {Promise} - returns promise (reject, resolve)
  229. */
  230. GET_MISSING_GENRE_PLAYLISTS() {
  231. return new Promise((resolve, reject) => {
  232. SongsModule.runJob("GET_ALL_GENRES", {}, this)
  233. .then(response => {
  234. const { genres } = response;
  235. const missingGenres = [];
  236. async.eachLimit(
  237. genres,
  238. 1,
  239. (genre, next) => {
  240. PlaylistsModule.runJob(
  241. "GET_GENRE_PLAYLIST",
  242. { genre: genre.toLowerCase(), includeSongs: false },
  243. this
  244. )
  245. .then(() => {
  246. next();
  247. })
  248. .catch(err => {
  249. if (err.message === "Playlist not found") {
  250. missingGenres.push(genre);
  251. next();
  252. } else next(err);
  253. });
  254. },
  255. err => {
  256. if (err) reject(err);
  257. else resolve({ genres: missingGenres });
  258. }
  259. );
  260. })
  261. .catch(err => {
  262. reject(err);
  263. });
  264. });
  265. }
  266. /**
  267. * Creates all missing genre playlists
  268. *
  269. * @returns {Promise} - returns promise (reject, resolve)
  270. */
  271. CREATE_MISSING_GENRE_PLAYLISTS() {
  272. return new Promise((resolve, reject) => {
  273. PlaylistsModule.runJob("GET_MISSING_GENRE_PLAYLISTS", {}, this)
  274. .then(response => {
  275. const { genres } = response;
  276. async.eachLimit(
  277. genres,
  278. 1,
  279. (genre, next) => {
  280. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre }, this)
  281. .then(() => {
  282. next();
  283. })
  284. .catch(err => {
  285. next(err);
  286. });
  287. },
  288. err => {
  289. if (err) reject(err);
  290. else resolve();
  291. }
  292. );
  293. })
  294. .catch(err => {
  295. reject(err);
  296. });
  297. });
  298. }
  299. /**
  300. * Gets a station playlist
  301. *
  302. * @param {object} payload - object that contains the payload
  303. * @param {string} payload.staationId - the station id
  304. * @param {string} payload.includeSongs - include the songs
  305. * @returns {Promise} - returns promise (reject, resolve)
  306. */
  307. GET_STATION_PLAYLIST(payload) {
  308. return new Promise((resolve, reject) => {
  309. const includeObject = payload.includeSongs ? null : { songs: false };
  310. PlaylistsModule.playlistModel.findOne(
  311. { type: "station", createdFor: payload.stationId },
  312. includeObject,
  313. (err, playlist) => {
  314. if (err) reject(new Error(err));
  315. else if (!playlist) reject(new Error("Playlist not found"));
  316. else resolve({ playlist });
  317. }
  318. );
  319. });
  320. }
  321. /**
  322. * Adds a song to a playlist
  323. *
  324. * @param {object} payload - object that contains the payload
  325. * @param {string} payload.playlistId - the playlist id
  326. * @param {string} payload.song - the song
  327. * @returns {Promise} - returns promise (reject, resolve)
  328. */
  329. ADD_SONG_TO_PLAYLIST(payload) {
  330. return new Promise((resolve, reject) => {
  331. const { _id, youtubeId, title, artists, thumbnail, duration, status } = payload.song;
  332. const trimmedSong = {
  333. _id,
  334. youtubeId,
  335. title,
  336. artists,
  337. thumbnail,
  338. duration,
  339. status
  340. };
  341. PlaylistsModule.playlistModel.updateOne(
  342. { _id: payload.playlistId },
  343. { $push: { songs: trimmedSong } },
  344. { runValidators: true },
  345. err => {
  346. if (err) reject(new Error(err));
  347. else {
  348. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  349. .then(() => resolve())
  350. .catch(err => {
  351. reject(new Error(err));
  352. });
  353. }
  354. }
  355. );
  356. });
  357. }
  358. /**
  359. * Deletes a song from a playlist based on the youtube id
  360. *
  361. * @param {object} payload - object that contains the payload
  362. * @param {string} payload.playlistId - the playlist id
  363. * @param {string} payload.youtubeId - the youtube id
  364. * @returns {Promise} - returns promise (reject, resolve)
  365. */
  366. DELETE_SONG_FROM_PLAYLIST_BY_YOUTUBE_ID(payload) {
  367. return new Promise((resolve, reject) => {
  368. PlaylistsModule.playlistModel.updateOne(
  369. { _id: payload.playlistId },
  370. { $pull: { songs: { youtubeId: payload.youtubeId } } },
  371. err => {
  372. if (err) reject(new Error(err));
  373. else {
  374. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)
  375. .then(() => resolve())
  376. .catch(err => {
  377. reject(new Error(err));
  378. });
  379. }
  380. }
  381. );
  382. });
  383. }
  384. /**
  385. * Fills a genre playlist with songs
  386. *
  387. * @param {object} payload - object that contains the payload
  388. * @param {string} payload.genre - the genre
  389. * @returns {Promise} - returns promise (reject, resolve)
  390. */
  391. AUTOFILL_GENRE_PLAYLIST(payload) {
  392. return new Promise((resolve, reject) => {
  393. async.waterfall(
  394. [
  395. next => {
  396. PlaylistsModule.runJob(
  397. "GET_GENRE_PLAYLIST",
  398. { genre: payload.genre.toLowerCase(), includeSongs: true },
  399. this
  400. )
  401. .then(response => {
  402. next(null, response.playlist._id);
  403. })
  404. .catch(err => {
  405. if (err.message === "Playlist not found") {
  406. PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)
  407. .then(playlistId => {
  408. next(null, playlistId);
  409. })
  410. .catch(err => {
  411. next(err);
  412. });
  413. } else next(err);
  414. });
  415. },
  416. (playlistId, next) => {
  417. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)
  418. .then(response => {
  419. next(null, playlistId, response.songs);
  420. })
  421. .catch(err => {
  422. console.log(err);
  423. next(err);
  424. });
  425. },
  426. (playlistId, _songs, next) => {
  427. const songs = _songs.map(song => {
  428. const { _id, youtubeId, title, artists, thumbnail, duration, status } = song;
  429. return {
  430. _id,
  431. youtubeId,
  432. title,
  433. artists,
  434. thumbnail,
  435. duration,
  436. status
  437. };
  438. });
  439. PlaylistsModule.playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, err => {
  440. next(err, playlistId);
  441. });
  442. },
  443. (playlistId, next) => {
  444. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  445. .then(() => {
  446. next(null, playlistId);
  447. })
  448. .catch(next);
  449. },
  450. // (data, next) => {
  451. // data.songsToDelete = [];
  452. // data.songsToAdd = [];
  453. // data.playlist.songs.forEach(playlistSong => {
  454. // const found = data.songs.find(song => playlistSong.youtubeId === song.youtubeId);
  455. // if (!found) data.songsToDelete.push(playlistSong);
  456. // });
  457. // data.songs.forEach(song => {
  458. // const found = data.playlist.songs.find(playlistSong => song.youtubeId === playlistSong.youtubeId);
  459. // if (!found) data.songsToAdd.push(song);
  460. // });
  461. // next(null, data);
  462. // },
  463. // (data, next) => {
  464. // const promises = [];
  465. // data.songsToAdd.forEach(song => {
  466. // promises.push(
  467. // PlaylistsModule.runJob(
  468. // "ADD_SONG_TO_PLAYLIST",
  469. // { playlistId: data.playlist._id, song },
  470. // this
  471. // )
  472. // );
  473. // });
  474. // data.songsToDelete.forEach(song => {
  475. // promises.push(
  476. // PlaylistsModule.runJob(
  477. // "DELETE_SONG_FROM_PLAYLIST_BY_YOUTUBE_ID",
  478. // {
  479. // playlistId: data.playlist._id,
  480. // youtubeId: song.youtubeId
  481. // },
  482. // this
  483. // )
  484. // );
  485. // });
  486. // Promise.allSettled(promises)
  487. // .then(() => {
  488. // next(null, data.playlist._id);
  489. // })
  490. // .catch(err => {
  491. // next(err);
  492. // });
  493. // },
  494. (playlistId, next) => {
  495. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  496. .then(response => {
  497. response.stationIds.forEach(stationId => {
  498. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  499. });
  500. })
  501. .catch();
  502. next();
  503. }
  504. ],
  505. err => {
  506. if (err && err !== true) return reject(new Error(err));
  507. return resolve({});
  508. }
  509. );
  510. });
  511. }
  512. /**
  513. * Gets orphaned genre playlists
  514. *
  515. * @returns {Promise} - returns promise (reject, resolve)
  516. */
  517. GET_ORPHANED_GENRE_PLAYLISTS() {
  518. return new Promise((resolve, reject) => {
  519. PlaylistsModule.playlistModel.find({ type: "genre" }, { songs: false }, (err, playlists) => {
  520. if (err) reject(new Error(err));
  521. else {
  522. const orphanedPlaylists = [];
  523. async.eachLimit(
  524. playlists,
  525. 1,
  526. (playlist, next) => {
  527. SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: playlist.createdFor }, this)
  528. .then(response => {
  529. if (response.songs.length === 0) {
  530. StationsModule.runJob(
  531. "GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST",
  532. { playlistId: playlist._id },
  533. this
  534. )
  535. .then(response => {
  536. if (response.stationIds.length === 0) orphanedPlaylists.push(playlist);
  537. next();
  538. })
  539. .catch(next);
  540. } else next();
  541. })
  542. .catch(next);
  543. },
  544. err => {
  545. if (err) reject(new Error(err));
  546. else resolve({ playlists: orphanedPlaylists });
  547. }
  548. );
  549. }
  550. });
  551. });
  552. }
  553. /**
  554. * Deletes all orphaned genre playlists
  555. *
  556. * @returns {Promise} - returns promise (reject, resolve)
  557. */
  558. DELETE_ORPHANED_GENRE_PLAYLISTS() {
  559. return new Promise((resolve, reject) => {
  560. PlaylistsModule.runJob("GET_ORPHANED_GENRE_PLAYLISTS", {}, this)
  561. .then(response => {
  562. async.eachLimit(
  563. response.playlists,
  564. 1,
  565. (playlist, next) => {
  566. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  567. .then(() => {
  568. this.log("INFO", "Deleting orphaned genre playlist");
  569. next();
  570. })
  571. .catch(err => {
  572. next(err);
  573. });
  574. },
  575. err => {
  576. if (err) reject(new Error(err));
  577. else resolve({});
  578. }
  579. );
  580. })
  581. .catch(err => {
  582. reject(new Error(err));
  583. });
  584. });
  585. }
  586. /**
  587. * Gets a orphaned station playlists
  588. *
  589. * @returns {Promise} - returns promise (reject, resolve)
  590. */
  591. GET_ORPHANED_STATION_PLAYLISTS() {
  592. return new Promise((resolve, reject) => {
  593. PlaylistsModule.playlistModel.find({ type: "station" }, { songs: false }, (err, playlists) => {
  594. if (err) reject(new Error(err));
  595. else {
  596. const orphanedPlaylists = [];
  597. async.eachLimit(
  598. playlists,
  599. 1,
  600. (playlist, next) => {
  601. StationsModule.runJob("GET_STATION", { stationId: playlist.createdFor }, this)
  602. .then(station => {
  603. if (station.playlist !== playlist._id.toString()) {
  604. orphanedPlaylists.push(playlist);
  605. }
  606. next();
  607. })
  608. .catch(err => {
  609. if (err.message === "Station not found") {
  610. orphanedPlaylists.push(playlist);
  611. next();
  612. } else next(err);
  613. });
  614. },
  615. err => {
  616. if (err) reject(new Error(err));
  617. else resolve({ playlists: orphanedPlaylists });
  618. }
  619. );
  620. }
  621. });
  622. });
  623. }
  624. /**
  625. * Deletes all orphaned station playlists
  626. *
  627. * @returns {Promise} - returns promise (reject, resolve)
  628. */
  629. DELETE_ORPHANED_STATION_PLAYLISTS() {
  630. return new Promise((resolve, reject) => {
  631. PlaylistsModule.runJob("GET_ORPHANED_STATION_PLAYLISTS", {}, this)
  632. .then(response => {
  633. async.eachLimit(
  634. response.playlists,
  635. 1,
  636. (playlist, next) => {
  637. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)
  638. .then(() => {
  639. this.log("INFO", "Deleting orphaned station playlist");
  640. next();
  641. })
  642. .catch(err => {
  643. next(err);
  644. });
  645. },
  646. err => {
  647. if (err) reject(new Error(err));
  648. else resolve({});
  649. }
  650. );
  651. })
  652. .catch(err => {
  653. reject(new Error(err));
  654. });
  655. });
  656. }
  657. /**
  658. * Fills a station playlist with songs
  659. *
  660. * @param {object} payload - object that contains the payload
  661. * @param {string} payload.stationId - the station id
  662. * @returns {Promise} - returns promise (reject, resolve)
  663. */
  664. AUTOFILL_STATION_PLAYLIST(payload) {
  665. return new Promise((resolve, reject) => {
  666. let originalPlaylist = null;
  667. async.waterfall(
  668. [
  669. next => {
  670. if (!payload.stationId) next("Please specify a station id");
  671. else next();
  672. },
  673. next => {
  674. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  675. .then(station => {
  676. next(null, station);
  677. })
  678. .catch(next);
  679. },
  680. (station, next) => {
  681. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: station.playlist }, this)
  682. .then(playlist => {
  683. originalPlaylist = playlist;
  684. next(null, station);
  685. })
  686. .catch(err => {
  687. next(err);
  688. });
  689. },
  690. (station, next) => {
  691. const includedPlaylists = [];
  692. async.eachLimit(
  693. station.includedPlaylists,
  694. 1,
  695. (playlistId, next) => {
  696. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  697. .then(playlist => {
  698. includedPlaylists.push(playlist);
  699. next();
  700. })
  701. .catch(next);
  702. },
  703. err => {
  704. next(err, station, includedPlaylists);
  705. }
  706. );
  707. },
  708. (station, includedPlaylists, next) => {
  709. const excludedPlaylists = [];
  710. async.eachLimit(
  711. station.excludedPlaylists,
  712. 1,
  713. (playlistId, next) => {
  714. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  715. .then(playlist => {
  716. excludedPlaylists.push(playlist);
  717. next();
  718. })
  719. .catch(next);
  720. },
  721. err => {
  722. next(err, station, includedPlaylists, excludedPlaylists);
  723. }
  724. );
  725. },
  726. (station, includedPlaylists, excludedPlaylists, next) => {
  727. const excludedSongs = excludedPlaylists
  728. .flatMap(excludedPlaylist => excludedPlaylist.songs)
  729. .reduce(
  730. (items, item) =>
  731. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  732. []
  733. );
  734. const includedSongs = includedPlaylists
  735. .flatMap(includedPlaylist => includedPlaylist.songs)
  736. .reduce(
  737. (songs, song) =>
  738. songs.find(x => x.youtubeId === song.youtubeId) ? [...songs] : [...songs, song],
  739. []
  740. )
  741. .filter(song => !excludedSongs.find(x => x.youtubeId === song.youtubeId));
  742. next(null, station, includedSongs);
  743. },
  744. (station, includedSongs, next) => {
  745. PlaylistsModule.playlistModel.updateOne(
  746. { _id: station.playlist },
  747. { $set: { songs: includedSongs } },
  748. err => {
  749. next(err, includedSongs);
  750. }
  751. );
  752. },
  753. (includedSongs, next) => {
  754. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: originalPlaylist._id }, this)
  755. .then(() => {
  756. next(null, includedSongs);
  757. })
  758. .catch(next);
  759. },
  760. (includedSongs, next) => {
  761. if (originalPlaylist.songs.length === 0 && includedSongs.length > 0)
  762. StationsModule.runJob("SKIP_STATION", { stationId: payload.stationId });
  763. next();
  764. }
  765. ],
  766. err => {
  767. if (err && err !== true) return reject(new Error(err));
  768. return resolve({});
  769. }
  770. );
  771. });
  772. }
  773. /**
  774. * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  775. *
  776. * @param {object} payload - object that contains the payload
  777. * @param {string} payload.playlistId - the id of the playlist we are trying to get
  778. * @returns {Promise} - returns promise (reject, resolve)
  779. */
  780. GET_PLAYLIST(payload) {
  781. return new Promise((resolve, reject) =>
  782. async.waterfall(
  783. [
  784. next => {
  785. CacheModule.runJob(
  786. "HGET",
  787. {
  788. table: "playlists",
  789. key: payload.playlistId
  790. },
  791. this
  792. )
  793. .then(playlist => next(null, playlist))
  794. .catch(next);
  795. },
  796. (playlist, next) => {
  797. if (playlist)
  798. PlaylistsModule.playlistModel.exists({ _id: payload.playlistId }, (err, exists) => {
  799. if (err) next(err);
  800. else if (exists) next(null, playlist);
  801. else {
  802. CacheModule.runJob(
  803. "HDEL",
  804. {
  805. table: "playlists",
  806. key: payload.playlistId
  807. },
  808. this
  809. )
  810. .then(() => next())
  811. .catch(next);
  812. }
  813. });
  814. else PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  815. },
  816. (playlist, next) => {
  817. if (playlist) {
  818. CacheModule.runJob(
  819. "HSET",
  820. {
  821. table: "playlists",
  822. key: payload.playlistId,
  823. value: playlist
  824. },
  825. this
  826. )
  827. .then(playlist => {
  828. next(null, playlist);
  829. })
  830. .catch(next);
  831. } else next("Playlist not found");
  832. }
  833. ],
  834. (err, playlist) => {
  835. if (err && err !== true) return reject(new Error(err));
  836. return resolve(playlist);
  837. }
  838. )
  839. );
  840. }
  841. /**
  842. * Gets a playlist from id from Mongo and updates the cache with it
  843. *
  844. * @param {object} payload - object that contains the payload
  845. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  846. * @returns {Promise} - returns promise (reject, resolve)
  847. */
  848. UPDATE_PLAYLIST(payload) {
  849. return new Promise((resolve, reject) =>
  850. async.waterfall(
  851. [
  852. next => {
  853. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  854. },
  855. (playlist, next) => {
  856. if (!playlist) {
  857. CacheModule.runJob("HDEL", {
  858. table: "playlists",
  859. key: payload.playlistId
  860. });
  861. return next("Playlist not found");
  862. }
  863. return CacheModule.runJob(
  864. "HSET",
  865. {
  866. table: "playlists",
  867. key: payload.playlistId,
  868. value: playlist
  869. },
  870. this
  871. )
  872. .then(playlist => {
  873. next(null, playlist);
  874. })
  875. .catch(next);
  876. }
  877. ],
  878. (err, playlist) => {
  879. if (err && err !== true) return reject(new Error(err));
  880. return resolve(playlist);
  881. }
  882. )
  883. );
  884. }
  885. /**
  886. * Deletes playlist from id from Mongo and cache
  887. *
  888. * @param {object} payload - object that contains the payload
  889. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  890. * @returns {Promise} - returns promise (reject, resolve)
  891. */
  892. DELETE_PLAYLIST(payload) {
  893. return new Promise((resolve, reject) =>
  894. async.waterfall(
  895. [
  896. next => {
  897. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  898. },
  899. (res, next) => {
  900. CacheModule.runJob(
  901. "HDEL",
  902. {
  903. table: "playlists",
  904. key: payload.playlistId
  905. },
  906. this
  907. )
  908. .then(() => next())
  909. .catch(next);
  910. }
  911. ],
  912. err => {
  913. if (err && err !== true) return reject(new Error(err));
  914. return resolve();
  915. }
  916. )
  917. );
  918. }
  919. /**
  920. * Searches through playlists
  921. *
  922. * @param {object} payload - object that contains the payload
  923. * @param {string} payload.query - the query
  924. * @param {string} payload.includePrivate - include private playlists
  925. * @param {string} payload.includeStation - include station playlists
  926. * @param {string} payload.includeUser - include user playlists
  927. * @param {string} payload.includeGenre - include genre playlists
  928. * @param {string} payload.includeOwn - include own user playlists
  929. * @param {string} payload.userId - the user id of the person requesting
  930. * @param {string} payload.includeSongs - include songs
  931. * @param {string} payload.page - page (default 1)
  932. * @returns {Promise} - returns promise (reject, resolve)
  933. */
  934. SEARCH(payload) {
  935. return new Promise((resolve, reject) =>
  936. async.waterfall(
  937. [
  938. next => {
  939. const types = [];
  940. if (payload.includeStation) types.push("station");
  941. if (payload.includeUser) types.push("user");
  942. if (payload.includeGenre) types.push("genre");
  943. if (types.length === 0 && !payload.includeOwn) return next("No types have been included.");
  944. const privacies = ["public"];
  945. if (payload.includePrivate) privacies.push("private");
  946. const includeObject = payload.includeSongs ? null : { songs: false };
  947. const filterArray = [
  948. {
  949. displayName: new RegExp(`${payload.query}`, "i"),
  950. privacy: { $in: privacies },
  951. type: { $in: types }
  952. }
  953. ];
  954. if (payload.includeOwn && payload.userId)
  955. filterArray.push({
  956. displayName: new RegExp(`${payload.query}`, "i"),
  957. type: "user",
  958. createdBy: payload.userId
  959. });
  960. return next(null, filterArray, includeObject);
  961. },
  962. (filterArray, includeObject, next) => {
  963. const page = payload.page ? payload.page : 1;
  964. PlaylistsModule.playlistModel
  965. .find({ $or: filterArray }, includeObject)
  966. .skip(15 * (page - 1))
  967. .limit(15)
  968. .exec(next);
  969. },
  970. (playlists, next) => {
  971. if (playlists.length > 0) next(null, playlists);
  972. else next("No playlists found");
  973. }
  974. ],
  975. (err, playlists) => {
  976. if (err && err !== true) return reject(new Error(err));
  977. return resolve({ playlists });
  978. }
  979. )
  980. );
  981. }
  982. /**
  983. * Clears and refills a station playlist
  984. *
  985. * @param {object} payload - object that contains the payload
  986. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  987. * @returns {Promise} - returns promise (reject, resolve)
  988. */
  989. CLEAR_AND_REFILL_STATION_PLAYLIST(payload) {
  990. return new Promise((resolve, reject) => {
  991. const { playlistId } = payload;
  992. async.waterfall(
  993. [
  994. next => {
  995. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  996. .then(playlist => {
  997. next(null, playlist);
  998. })
  999. .catch(err => {
  1000. next(err);
  1001. });
  1002. },
  1003. (playlist, next) => {
  1004. if (playlist.type !== "station") next("This playlist is not a station playlist.");
  1005. else next(null, playlist.createdFor);
  1006. },
  1007. (stationId, next) => {
  1008. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)
  1009. .then(() => {
  1010. next();
  1011. })
  1012. .catch(err => {
  1013. next(err);
  1014. });
  1015. }
  1016. ],
  1017. err => {
  1018. if (err && err !== true) return reject(new Error(err));
  1019. return resolve();
  1020. }
  1021. );
  1022. });
  1023. }
  1024. /**
  1025. * Clears and refills a genre playlist
  1026. *
  1027. * @param {object} payload - object that contains the payload
  1028. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1029. * @returns {Promise} - returns promise (reject, resolve)
  1030. */
  1031. CLEAR_AND_REFILL_GENRE_PLAYLIST(payload) {
  1032. return new Promise((resolve, reject) => {
  1033. const { playlistId } = payload;
  1034. async.waterfall(
  1035. [
  1036. next => {
  1037. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1038. .then(playlist => {
  1039. next(null, playlist);
  1040. })
  1041. .catch(err => {
  1042. next(err);
  1043. });
  1044. },
  1045. (playlist, next) => {
  1046. if (playlist.type !== "genre") next("This playlist is not a genre playlist.");
  1047. else next(null, playlist.createdFor);
  1048. },
  1049. (genre, next) => {
  1050. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }, this)
  1051. .then(() => {
  1052. next();
  1053. })
  1054. .catch(err => {
  1055. next(err);
  1056. });
  1057. }
  1058. ],
  1059. err => {
  1060. if (err && err !== true) return reject(new Error(err));
  1061. return resolve();
  1062. }
  1063. );
  1064. });
  1065. }
  1066. }
  1067. export default new _PlaylistsModule();