playlists.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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: Number(data) };
  949. } else if (filterType === "numberLesser") {
  950. newQuery[filter.property] = { $lt: Number(data) };
  951. } else if (filterType === "numberGreater") {
  952. newQuery[filter.property] = { $gt: Number(data) };
  953. } else if (filterType === "numberGreaterEqual") {
  954. newQuery[filter.property] = { $gte: Number(data) };
  955. } else if (filterType === "numberEquals") {
  956. newQuery[filter.property] = { $eq: Number(data) };
  957. } else if (filterType === "boolean") {
  958. newQuery[filter.property] = { $eq: !!data };
  959. }
  960. if (filter.property === "createdBy")
  961. return { $or: [newQuery, { createdByUsername: newQuery.createdBy }] };
  962. return newQuery;
  963. });
  964. if (queryError) next(queryError);
  965. const queryObject = {};
  966. if (newQueries.length > 0) {
  967. if (operator === "and") queryObject.$and = newQueries;
  968. else if (operator === "or") queryObject.$or = newQueries;
  969. else if (operator === "nor") queryObject.$nor = newQueries;
  970. }
  971. pipeline.push({ $match: queryObject });
  972. next(null, pipeline);
  973. },
  974. // Adds sort stage to aggregation pipeline if there is at least one column being sorted, responsible for sorting data
  975. (pipeline, next) => {
  976. const { sort } = payload;
  977. const newSort = Object.fromEntries(
  978. Object.entries(sort).map(([property, direction]) => [
  979. property,
  980. direction === "ascending" ? 1 : -1
  981. ])
  982. );
  983. if (Object.keys(newSort).length > 0) pipeline.push({ $sort: newSort });
  984. next(null, pipeline);
  985. },
  986. // Adds first project stage to aggregation pipeline, responsible for including only the requested properties
  987. (pipeline, next) => {
  988. const { properties } = payload;
  989. pipeline.push({ $project: Object.fromEntries(properties.map(property => [property, 1])) });
  990. next(null, pipeline);
  991. },
  992. // Adds the facet stage to aggregation pipeline, responsible for returning a total document count, skipping and limitting the documents that will be returned
  993. (pipeline, next) => {
  994. const { page, pageSize } = payload;
  995. pipeline.push({
  996. $facet: {
  997. count: [{ $count: "count" }],
  998. documents: [{ $skip: pageSize * (page - 1) }, { $limit: pageSize }]
  999. }
  1000. });
  1001. // console.dir(pipeline, { depth: 6 });
  1002. next(null, pipeline);
  1003. },
  1004. // Executes the aggregation pipeline
  1005. (pipeline, next) => {
  1006. PlaylistsModule.playlistModel.aggregate(pipeline).exec((err, result) => {
  1007. // console.dir(err);
  1008. // console.dir(result, { depth: 6 });
  1009. if (err) return next(err);
  1010. if (result[0].count.length === 0) return next(null, 0, []);
  1011. const { count } = result[0].count[0];
  1012. const { documents } = result[0];
  1013. // console.log(111, err, result, count, documents[0]);
  1014. return next(null, count, documents);
  1015. });
  1016. }
  1017. ],
  1018. (err, count, playlists) => {
  1019. if (err && err !== true) return reject(new Error(err));
  1020. return resolve({ data: playlists, count });
  1021. }
  1022. );
  1023. });
  1024. }
  1025. /**
  1026. * Gets a playlist from id from Mongo and updates the cache with it
  1027. *
  1028. * @param {object} payload - object that contains the payload
  1029. * @param {string} payload.playlistId - the id of the playlist we are trying to update
  1030. * @returns {Promise} - returns promise (reject, resolve)
  1031. */
  1032. UPDATE_PLAYLIST(payload) {
  1033. return new Promise((resolve, reject) =>
  1034. async.waterfall(
  1035. [
  1036. next => {
  1037. PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);
  1038. },
  1039. (playlist, next) => {
  1040. if (!playlist) {
  1041. CacheModule.runJob("HDEL", {
  1042. table: "playlists",
  1043. key: payload.playlistId
  1044. });
  1045. return next("Playlist not found");
  1046. }
  1047. return CacheModule.runJob(
  1048. "HSET",
  1049. {
  1050. table: "playlists",
  1051. key: payload.playlistId,
  1052. value: playlist
  1053. },
  1054. this
  1055. )
  1056. .then(playlist => {
  1057. next(null, playlist);
  1058. })
  1059. .catch(next);
  1060. }
  1061. ],
  1062. (err, playlist) => {
  1063. if (err && err !== true) return reject(new Error(err));
  1064. return resolve(playlist);
  1065. }
  1066. )
  1067. );
  1068. }
  1069. /**
  1070. * Deletes playlist from id from Mongo and cache
  1071. *
  1072. * @param {object} payload - object that contains the payload
  1073. * @param {string} payload.playlistId - the id of the playlist we are trying to delete
  1074. * @returns {Promise} - returns promise (reject, resolve)
  1075. */
  1076. DELETE_PLAYLIST(payload) {
  1077. return new Promise((resolve, reject) =>
  1078. async.waterfall(
  1079. [
  1080. next => {
  1081. PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);
  1082. },
  1083. (res, next) => {
  1084. CacheModule.runJob(
  1085. "HDEL",
  1086. {
  1087. table: "playlists",
  1088. key: payload.playlistId
  1089. },
  1090. this
  1091. )
  1092. .then(() => next())
  1093. .catch(next);
  1094. },
  1095. next => {
  1096. StationsModule.runJob(
  1097. "REMOVE_INCLUDED_OR_EXCLUDED_PLAYLIST_FROM_STATIONS",
  1098. { playlistId: payload.playlistId },
  1099. this
  1100. )
  1101. .then(() => {
  1102. next();
  1103. })
  1104. .catch(err => next(err));
  1105. }
  1106. ],
  1107. err => {
  1108. if (err && err !== true) return reject(new Error(err));
  1109. return resolve();
  1110. }
  1111. )
  1112. );
  1113. }
  1114. /**
  1115. * Searches through playlists
  1116. *
  1117. * @param {object} payload - object that contains the payload
  1118. * @param {string} payload.query - the query
  1119. * @param {string} payload.includePrivate - include private playlists
  1120. * @param {string} payload.includeStation - include station playlists
  1121. * @param {string} payload.includeUser - include user playlists
  1122. * @param {string} payload.includeGenre - include genre playlists
  1123. * @param {string} payload.includeOwn - include own user playlists
  1124. * @param {string} payload.userId - the user id of the person requesting
  1125. * @param {string} payload.includeSongs - include songs
  1126. * @param {string} payload.page - page (default 1)
  1127. * @returns {Promise} - returns promise (reject, resolve)
  1128. */
  1129. SEARCH(payload) {
  1130. return new Promise((resolve, reject) =>
  1131. async.waterfall(
  1132. [
  1133. next => {
  1134. const types = [];
  1135. if (payload.includeStation) types.push("station");
  1136. if (payload.includeUser) types.push("user");
  1137. if (payload.includeGenre) types.push("genre");
  1138. if (types.length === 0 && !payload.includeOwn) return next("No types have been included.");
  1139. const privacies = ["public"];
  1140. if (payload.includePrivate) privacies.push("private");
  1141. const includeObject = payload.includeSongs ? null : { songs: false };
  1142. const filterArray = [
  1143. {
  1144. displayName: new RegExp(`${payload.query}`, "i"),
  1145. privacy: { $in: privacies },
  1146. type: { $in: types }
  1147. }
  1148. ];
  1149. if (payload.includeOwn && payload.userId)
  1150. filterArray.push({
  1151. displayName: new RegExp(`${payload.query}`, "i"),
  1152. type: "user",
  1153. createdBy: payload.userId
  1154. });
  1155. return next(null, filterArray, includeObject);
  1156. },
  1157. (filterArray, includeObject, next) => {
  1158. const page = payload.page ? payload.page : 1;
  1159. const pageSize = 15;
  1160. const skipAmount = pageSize * (page - 1);
  1161. PlaylistsModule.playlistModel.find({ $or: filterArray }).count((err, count) => {
  1162. if (err) next(err);
  1163. else {
  1164. PlaylistsModule.playlistModel
  1165. .find({ $or: filterArray }, includeObject)
  1166. .skip(skipAmount)
  1167. .limit(pageSize)
  1168. .exec((err, playlists) => {
  1169. if (err) next(err);
  1170. else {
  1171. next(null, {
  1172. playlists,
  1173. page,
  1174. pageSize,
  1175. skipAmount,
  1176. count
  1177. });
  1178. }
  1179. });
  1180. }
  1181. });
  1182. },
  1183. (data, next) => {
  1184. if (data.playlists.length > 0) next(null, data);
  1185. else next("No playlists found");
  1186. }
  1187. ],
  1188. (err, data) => {
  1189. if (err && err !== true) return reject(new Error(err));
  1190. return resolve(data);
  1191. }
  1192. )
  1193. );
  1194. }
  1195. /**
  1196. * Clears and refills a station playlist
  1197. *
  1198. * @param {object} payload - object that contains the payload
  1199. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1200. * @returns {Promise} - returns promise (reject, resolve)
  1201. */
  1202. CLEAR_AND_REFILL_STATION_PLAYLIST(payload) {
  1203. return new Promise((resolve, reject) => {
  1204. const { playlistId } = payload;
  1205. async.waterfall(
  1206. [
  1207. next => {
  1208. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1209. .then(playlist => {
  1210. next(null, playlist);
  1211. })
  1212. .catch(err => {
  1213. next(err);
  1214. });
  1215. },
  1216. (playlist, next) => {
  1217. if (playlist.type !== "station") next("This playlist is not a station playlist.");
  1218. else next(null, playlist.createdFor);
  1219. },
  1220. (stationId, next) => {
  1221. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)
  1222. .then(() => {
  1223. next();
  1224. })
  1225. .catch(err => {
  1226. next(err);
  1227. });
  1228. }
  1229. ],
  1230. err => {
  1231. if (err && err !== true) return reject(new Error(err));
  1232. return resolve();
  1233. }
  1234. );
  1235. });
  1236. }
  1237. /**
  1238. * Clears and refills a genre playlist
  1239. *
  1240. * @param {object} payload - object that contains the payload
  1241. * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill
  1242. * @returns {Promise} - returns promise (reject, resolve)
  1243. */
  1244. CLEAR_AND_REFILL_GENRE_PLAYLIST(payload) {
  1245. return new Promise((resolve, reject) => {
  1246. const { playlistId } = payload;
  1247. async.waterfall(
  1248. [
  1249. next => {
  1250. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1251. .then(playlist => {
  1252. next(null, playlist);
  1253. })
  1254. .catch(err => {
  1255. next(err);
  1256. });
  1257. },
  1258. (playlist, next) => {
  1259. if (playlist.type !== "genre") next("This playlist is not a genre playlist.");
  1260. else next(null, playlist.createdFor);
  1261. },
  1262. (genre, next) => {
  1263. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }, this)
  1264. .then(() => {
  1265. next();
  1266. })
  1267. .catch(err => {
  1268. next(err);
  1269. });
  1270. }
  1271. ],
  1272. err => {
  1273. if (err && err !== true) return reject(new Error(err));
  1274. return resolve();
  1275. }
  1276. );
  1277. });
  1278. }
  1279. }
  1280. export default new _PlaylistsModule();