playlists.js 34 KB

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