songs.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. import async from "async";
  2. import { isAdminRequired, isLoginRequired } from "./hooks";
  3. import moduleManager from "../../index";
  4. const DBModule = moduleManager.modules.db;
  5. const UtilsModule = moduleManager.modules.utils;
  6. const WSModule = moduleManager.modules.ws;
  7. const CacheModule = moduleManager.modules.cache;
  8. const SongsModule = moduleManager.modules.songs;
  9. const ActivitiesModule = moduleManager.modules.activities;
  10. const YouTubeModule = moduleManager.modules.youtube;
  11. const PlaylistsModule = moduleManager.modules.playlists;
  12. CacheModule.runJob("SUB", {
  13. channel: "song.updated",
  14. cb: async data => {
  15. const songModel = await DBModule.runJob("GET_MODEL", {
  16. modelName: "song"
  17. });
  18. songModel.findOne({ _id: data.songId }, (err, song) => {
  19. WSModule.runJob("EMIT_TO_ROOMS", {
  20. rooms: ["import-album", "admin.songs", `edit-song.${data.songId}`],
  21. args: ["event:admin.song.updated", { data: { song, oldStatus: data.oldStatus } }]
  22. });
  23. });
  24. }
  25. });
  26. CacheModule.runJob("SUB", {
  27. channel: "song.like",
  28. cb: data => {
  29. WSModule.runJob("EMIT_TO_ROOM", {
  30. room: `song.${data.youtubeId}`,
  31. args: [
  32. "event:song.liked",
  33. {
  34. data: { youtubeId: data.youtubeId, likes: data.likes, dislikes: data.dislikes }
  35. }
  36. ]
  37. });
  38. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  39. sockets.forEach(socket => {
  40. socket.dispatch("event:song.ratings.updated", {
  41. data: {
  42. youtubeId: data.youtubeId,
  43. liked: true,
  44. disliked: false
  45. }
  46. });
  47. });
  48. });
  49. }
  50. });
  51. CacheModule.runJob("SUB", {
  52. channel: "song.dislike",
  53. cb: data => {
  54. WSModule.runJob("EMIT_TO_ROOM", {
  55. room: `song.${data.youtubeId}`,
  56. args: [
  57. "event:song.disliked",
  58. {
  59. data: { youtubeId: data.youtubeId, likes: data.likes, dislikes: data.dislikes }
  60. }
  61. ]
  62. });
  63. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  64. sockets.forEach(socket => {
  65. socket.dispatch("event:song.ratings.updated", {
  66. data: {
  67. youtubeId: data.youtubeId,
  68. liked: false,
  69. disliked: true
  70. }
  71. });
  72. });
  73. });
  74. }
  75. });
  76. CacheModule.runJob("SUB", {
  77. channel: "song.unlike",
  78. cb: data => {
  79. WSModule.runJob("EMIT_TO_ROOM", {
  80. room: `song.${data.youtubeId}`,
  81. args: [
  82. "event:song.unliked",
  83. {
  84. data: { youtubeId: data.youtubeId, likes: data.likes, dislikes: data.dislikes }
  85. }
  86. ]
  87. });
  88. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  89. sockets.forEach(socket => {
  90. socket.dispatch("event:song.ratings.updated", {
  91. data: {
  92. youtubeId: data.youtubeId,
  93. liked: false,
  94. disliked: false
  95. }
  96. });
  97. });
  98. });
  99. }
  100. });
  101. CacheModule.runJob("SUB", {
  102. channel: "song.undislike",
  103. cb: data => {
  104. WSModule.runJob("EMIT_TO_ROOM", {
  105. room: `song.${data.youtubeId}`,
  106. args: [
  107. "event:song.undisliked",
  108. {
  109. data: { youtubeId: data.youtubeId, likes: data.likes, dislikes: data.dislikes }
  110. }
  111. ]
  112. });
  113. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  114. sockets.forEach(socket => {
  115. socket.dispatch("event:song.ratings.updated", {
  116. data: {
  117. youtubeId: data.youtubeId,
  118. liked: false,
  119. disliked: false
  120. }
  121. });
  122. });
  123. });
  124. }
  125. });
  126. export default {
  127. /**
  128. * Returns the length of the songs list
  129. *
  130. * @param {object} session - the session object automatically added by the websocket
  131. * @param cb
  132. */
  133. length: isAdminRequired(async function length(session, cb) {
  134. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  135. async.waterfall(
  136. [
  137. next => {
  138. songModel.countDocuments({}, next);
  139. }
  140. ],
  141. async (err, count) => {
  142. if (err) {
  143. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  144. this.log("ERROR", "SONGS_LENGTH", `Failed to get length from songs. "${err}"`);
  145. return cb({ status: "error", message: err });
  146. }
  147. this.log("SUCCESS", "SONGS_LENGTH", `Got length from songs successfully.`);
  148. return cb({ status: "success", message: "Successfully got length of songs.", data: { length: count } });
  149. }
  150. );
  151. }),
  152. /**
  153. * Gets a set of songs
  154. *
  155. * @param {object} session - the session object automatically added by the websocket
  156. * @param set - the set number to return
  157. * @param cb
  158. */
  159. getSet: isAdminRequired(async function getSet(session, set, cb) {
  160. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  161. async.waterfall(
  162. [
  163. next => {
  164. songModel
  165. .find({})
  166. .skip(15 * (set - 1))
  167. .limit(15)
  168. .exec(next);
  169. }
  170. ],
  171. async (err, songs) => {
  172. if (err) {
  173. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  174. this.log("ERROR", "SONGS_GET_SET", `Failed to get set from songs. "${err}"`);
  175. return cb({ status: "error", message: err });
  176. }
  177. this.log("SUCCESS", "SONGS_GET_SET", `Got set from songs successfully.`);
  178. return cb({ status: "success", message: "Successfully got set of songs.", data: { songs } });
  179. }
  180. );
  181. }),
  182. /**
  183. * Gets songs, used in the admin songs page by the AdvancedTable component
  184. *
  185. * @param {object} session - the session object automatically added by the websocket
  186. * @param page - the page
  187. * @param pageSize - the size per page
  188. * @param properties - the properties to return for each song
  189. * @param sort - the sort object
  190. * @param queries - the queries array
  191. * @param operator - the operator for queries
  192. * @param cb
  193. */
  194. getData: isAdminRequired(async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  195. async.waterfall(
  196. [
  197. next => {
  198. SongsModule.runJob(
  199. "GET_DATA",
  200. {
  201. page,
  202. pageSize,
  203. properties,
  204. sort,
  205. queries,
  206. operator
  207. },
  208. this
  209. )
  210. .then(response => {
  211. next(null, response);
  212. })
  213. .catch(err => {
  214. next(err);
  215. });
  216. }
  217. ],
  218. async (err, response) => {
  219. if (err) {
  220. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  221. this.log("ERROR", "SONGS_GET_DATA", `Failed to get data from songs. "${err}"`);
  222. return cb({ status: "error", message: err });
  223. }
  224. this.log("SUCCESS", "SONGS_GET_DATA", `Got data from songs successfully.`);
  225. return cb({ status: "success", message: "Successfully got data from songs.", data: response });
  226. }
  227. );
  228. }),
  229. /**
  230. * Updates all songs
  231. *
  232. * @param {object} session - the session object automatically added by the websocket
  233. * @param cb
  234. */
  235. updateAll: isAdminRequired(async function updateAll(session, cb) {
  236. async.waterfall(
  237. [
  238. next => {
  239. SongsModule.runJob("UPDATE_ALL_SONGS", {}, this)
  240. .then(() => {
  241. next();
  242. })
  243. .catch(err => {
  244. next(err);
  245. });
  246. }
  247. ],
  248. async err => {
  249. if (err) {
  250. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  251. this.log("ERROR", "SONGS_UPDATE_ALL", `Failed to update all songs. "${err}"`);
  252. return cb({ status: "error", message: err });
  253. }
  254. this.log("SUCCESS", "SONGS_UPDATE_ALL", `Updated all songs successfully.`);
  255. return cb({ status: "success", message: "Successfully updated all songs." });
  256. }
  257. );
  258. }),
  259. /**
  260. * Recalculates all song ratings
  261. *
  262. * @param {object} session - the session object automatically added by the websocket
  263. * @param cb
  264. */
  265. recalculateAllRatings: isAdminRequired(async function recalculateAllRatings(session, cb) {
  266. async.waterfall(
  267. [
  268. next => {
  269. SongsModule.runJob("RECALCULATE_ALL_SONG_RATINGS", {}, this)
  270. .then(() => {
  271. next();
  272. })
  273. .catch(err => {
  274. next(err);
  275. });
  276. }
  277. ],
  278. async err => {
  279. if (err) {
  280. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  281. this.log(
  282. "ERROR",
  283. "SONGS_RECALCULATE_ALL_RATINGS",
  284. `Failed to recalculate all song ratings. "${err}"`
  285. );
  286. return cb({ status: "error", message: err });
  287. }
  288. this.log("SUCCESS", "SONGS_RECALCULATE_ALL_RATINGS", `Recalculated all song ratings successfully.`);
  289. return cb({ status: "success", message: "Successfully recalculated all song ratings." });
  290. }
  291. );
  292. }),
  293. /**
  294. * Gets a song from the Musare song id
  295. *
  296. * @param {object} session - the session object automatically added by the websocket
  297. * @param {string} songId - the song id
  298. * @param {Function} cb
  299. */
  300. getSongFromSongId: isAdminRequired(function getSongFromSongId(session, songId, cb) {
  301. async.waterfall(
  302. [
  303. next => {
  304. SongsModule.runJob("GET_SONG", { songId }, this)
  305. .then(response => next(null, response.song))
  306. .catch(err => next(err));
  307. }
  308. ],
  309. async (err, song) => {
  310. if (err) {
  311. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  312. this.log("ERROR", "SONGS_GET_SONG_FROM_MUSARE_ID", `Failed to get song ${songId}. "${err}"`);
  313. return cb({ status: "error", message: err });
  314. }
  315. this.log("SUCCESS", "SONGS_GET_SONG_FROM_MUSARE_ID", `Got song ${songId} successfully.`);
  316. return cb({ status: "success", data: { song } });
  317. }
  318. );
  319. }),
  320. /**
  321. * Updates a song
  322. *
  323. * @param {object} session - the session object automatically added by the websocket
  324. * @param {string} songId - the song id
  325. * @param {object} song - the updated song object
  326. * @param {Function} cb
  327. */
  328. update: isAdminRequired(async function update(session, songId, song, cb) {
  329. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  330. let existingSong = null;
  331. async.waterfall(
  332. [
  333. next => {
  334. songModel.findOne({ _id: songId }, next);
  335. },
  336. (_existingSong, next) => {
  337. existingSong = _existingSong;
  338. songModel.updateOne({ _id: songId }, song, { runValidators: true }, next);
  339. },
  340. (res, next) => {
  341. SongsModule.runJob("UPDATE_SONG", { songId }, this)
  342. .then(song => {
  343. existingSong.genres
  344. .concat(song.genres)
  345. .filter((value, index, self) => self.indexOf(value) === index)
  346. .forEach(genre => {
  347. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  348. .then(() => {})
  349. .catch(() => {});
  350. });
  351. next(null, song);
  352. })
  353. .catch(next);
  354. }
  355. ],
  356. async (err, song) => {
  357. if (err) {
  358. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  359. this.log("ERROR", "SONGS_UPDATE", `Failed to update song "${songId}". "${err}"`);
  360. return cb({ status: "error", message: err });
  361. }
  362. this.log("SUCCESS", "SONGS_UPDATE", `Successfully updated song "${songId}".`);
  363. return cb({
  364. status: "success",
  365. message: "Song has been successfully updated",
  366. data: { song }
  367. });
  368. }
  369. );
  370. }),
  371. // /**
  372. // * Removes a song
  373. // *
  374. // * @param session
  375. // * @param songId - the song id
  376. // * @param cb
  377. // */
  378. // remove: isAdminRequired(async function remove(session, songId, cb) {
  379. // const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  380. // let song = null;
  381. // async.waterfall(
  382. // [
  383. // next => {
  384. // songModel.findOne({ _id: songId }, next);
  385. // },
  386. // (_song, next) => {
  387. // song = _song;
  388. // songModel.deleteOne({ _id: songId }, next);
  389. // },
  390. // (res, next) => {
  391. // CacheModule.runJob("HDEL", { table: "songs", key: songId }, this)
  392. // .then(() => {
  393. // next();
  394. // })
  395. // .catch(next)
  396. // .finally(() => {
  397. // song.genres.forEach(genre => {
  398. // PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  399. // .then(() => {})
  400. // .catch(() => {});
  401. // });
  402. // });
  403. // }
  404. // ],
  405. // async err => {
  406. // if (err) {
  407. // err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  408. // this.log("ERROR", "SONGS_REMOVE", `Failed to remove song "${songId}". "${err}"`);
  409. // return cb({ status: "error", message: err });
  410. // }
  411. // this.log("SUCCESS", "SONGS_REMOVE", `Successfully removed song "${songId}".`);
  412. // if (song.status === "verified") {
  413. // CacheModule.runJob("PUB", {
  414. // channel: "song.removedVerifiedSong",
  415. // value: songId
  416. // });
  417. // }
  418. // if (song.status === "unverified") {
  419. // CacheModule.runJob("PUB", {
  420. // channel: "song.removedUnverifiedSong",
  421. // value: songId
  422. // });
  423. // }
  424. // if (song.status === "hidden") {
  425. // CacheModule.runJob("PUB", {
  426. // channel: "song.removedHiddenSong",
  427. // value: songId
  428. // });
  429. // }
  430. // return cb({
  431. // status: "success",
  432. // message: "Song has been successfully removed"
  433. // });
  434. // }
  435. // );
  436. // }),
  437. /**
  438. * Searches through official songs
  439. *
  440. * @param {object} session - the session object automatically added by the websocket
  441. * @param {string} query - the query
  442. * @param {string} page - the page
  443. * @param {Function} cb - gets called with the result
  444. */
  445. searchOfficial: isLoginRequired(async function searchOfficial(session, query, page, cb) {
  446. async.waterfall(
  447. [
  448. next => {
  449. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  450. else next();
  451. },
  452. next => {
  453. SongsModule.runJob("SEARCH", {
  454. query,
  455. includeVerified: true,
  456. trimmed: true,
  457. page
  458. })
  459. .then(response => {
  460. next(null, response);
  461. })
  462. .catch(err => {
  463. next(err);
  464. });
  465. }
  466. ],
  467. async (err, data) => {
  468. if (err) {
  469. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  470. this.log("ERROR", "SONGS_SEARCH_OFFICIAL", `Searching songs failed. "${err}"`);
  471. return cb({ status: "error", message: err });
  472. }
  473. this.log("SUCCESS", "SONGS_SEARCH_OFFICIAL", "Searching songs successful.");
  474. return cb({ status: "success", data });
  475. }
  476. );
  477. }),
  478. /**
  479. * Requests a song
  480. *
  481. * @param {object} session - the session object automatically added by the websocket
  482. * @param {string} youtubeId - the youtube id of the song that gets requested
  483. * @param {string} returnSong - returns the simple song
  484. * @param {Function} cb - gets called with the result
  485. */
  486. request: isLoginRequired(async function add(session, youtubeId, returnSong, cb) {
  487. SongsModule.runJob("REQUEST_SONG", { youtubeId, userId: session.userId }, this)
  488. .then(response => {
  489. this.log(
  490. "SUCCESS",
  491. "SONGS_REQUEST",
  492. `User "${session.userId}" successfully requested song "${youtubeId}".`
  493. );
  494. return cb({
  495. status: "success",
  496. message: "Successfully requested that song",
  497. song: returnSong ? response.song : null
  498. });
  499. })
  500. .catch(async _err => {
  501. const err = await UtilsModule.runJob("GET_ERROR", { error: _err }, this);
  502. this.log(
  503. "ERROR",
  504. "SONGS_REQUEST",
  505. `Requesting song "${youtubeId}" failed for user ${session.userId}. "${err}"`
  506. );
  507. return cb({ status: "error", message: err, song: returnSong && _err.data ? _err.data.song : null });
  508. });
  509. }),
  510. /**
  511. * Verifies a song
  512. *
  513. * @param session
  514. * @param songId - the song id
  515. * @param cb
  516. */
  517. verify: isAdminRequired(async function add(session, songId, cb) {
  518. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  519. async.waterfall(
  520. [
  521. next => {
  522. SongModel.findOne({ _id: songId }, next);
  523. },
  524. (song, next) => {
  525. if (!song) return next("This song is not in the database.");
  526. return next(null, song);
  527. },
  528. (song, next) => {
  529. const oldStatus = false;
  530. song.verifiedBy = session.userId;
  531. song.verifiedAt = Date.now();
  532. song.verified = true;
  533. song.save(err => next(err, song, oldStatus));
  534. },
  535. (song, oldStatus, next) => {
  536. song.genres.forEach(genre => {
  537. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  538. .then(() => {})
  539. .catch(() => {});
  540. });
  541. SongsModule.runJob("UPDATE_SONG", { songId: song._id, oldStatus });
  542. next(null, song, oldStatus);
  543. }
  544. ],
  545. async err => {
  546. if (err) {
  547. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  548. this.log("ERROR", "SONGS_VERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  549. return cb({ status: "error", message: err });
  550. }
  551. this.log("SUCCESS", "SONGS_VERIFY", `User "${session.userId}" successfully verified song "${songId}".`);
  552. return cb({
  553. status: "success",
  554. message: "Song has been verified successfully."
  555. });
  556. }
  557. );
  558. // TODO Check if video is in queue and Add the song to the appropriate stations
  559. }),
  560. /**
  561. * Un-verifies a song
  562. *
  563. * @param session
  564. * @param songId - the song id
  565. * @param cb
  566. */
  567. unverify: isAdminRequired(async function add(session, songId, cb) {
  568. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  569. async.waterfall(
  570. [
  571. next => {
  572. SongModel.findOne({ _id: songId }, next);
  573. },
  574. (song, next) => {
  575. if (!song) return next("This song is not in the database.");
  576. return next(null, song);
  577. },
  578. (song, next) => {
  579. song.verified = false;
  580. song.save(err => {
  581. next(err, song);
  582. });
  583. },
  584. (song, next) => {
  585. song.genres.forEach(genre => {
  586. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  587. .then(() => {})
  588. .catch(() => {});
  589. });
  590. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: true });
  591. next(null);
  592. }
  593. ],
  594. async err => {
  595. if (err) {
  596. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  597. this.log("ERROR", "SONGS_UNVERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  598. return cb({ status: "error", message: err });
  599. }
  600. this.log(
  601. "SUCCESS",
  602. "SONGS_UNVERIFY",
  603. `User "${session.userId}" successfully unverified song "${songId}".`
  604. );
  605. return cb({
  606. status: "success",
  607. message: "Song has been unverified successfully."
  608. });
  609. }
  610. );
  611. // TODO Check if video is in queue and Add the song to the appropriate stations
  612. }),
  613. /**
  614. * Requests a set of songs
  615. *
  616. * @param {object} session - the session object automatically added by the websocket
  617. * @param {string} url - the url of the the YouTube playlist
  618. * @param {boolean} musicOnly - whether to only get music from the playlist
  619. * @param {Function} cb - gets called with the result
  620. */
  621. requestSet: isLoginRequired(function requestSet(session, url, musicOnly, returnSongs, cb) {
  622. async.waterfall(
  623. [
  624. next => {
  625. YouTubeModule.runJob(
  626. "GET_PLAYLIST",
  627. {
  628. url,
  629. musicOnly
  630. },
  631. this
  632. )
  633. .then(res => {
  634. next(null, res.songs);
  635. })
  636. .catch(next);
  637. },
  638. (youtubeIds, next) => {
  639. let successful = 0;
  640. let songs = {};
  641. let failed = 0;
  642. let alreadyInDatabase = 0;
  643. if (youtubeIds.length === 0) next();
  644. async.eachOfLimit(
  645. youtubeIds,
  646. 1,
  647. (youtubeId, index, next) => {
  648. WSModule.runJob(
  649. "RUN_ACTION2",
  650. {
  651. session,
  652. namespace: "songs",
  653. action: "request",
  654. args: [youtubeId, returnSongs]
  655. },
  656. this
  657. )
  658. .then(res => {
  659. if (res.status === "success") successful += 1;
  660. else failed += 1;
  661. if (res.message === "This song is already in the database.") alreadyInDatabase += 1;
  662. if (res.song) songs[index] = res.song;
  663. else songs[index] = null;
  664. })
  665. .catch(() => {
  666. failed += 1;
  667. })
  668. .finally(() => {
  669. next();
  670. });
  671. },
  672. () => {
  673. if (returnSongs)
  674. songs = Object.keys(songs)
  675. .sort()
  676. .map(key => songs[key]);
  677. next(null, { successful, failed, alreadyInDatabase, songs });
  678. }
  679. );
  680. }
  681. ],
  682. async (err, response) => {
  683. if (err) {
  684. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  685. this.log(
  686. "ERROR",
  687. "REQUEST_SET",
  688. `Importing a YouTube playlist to be requested failed for user "${session.userId}". "${err}"`
  689. );
  690. return cb({ status: "error", message: err });
  691. }
  692. this.log(
  693. "SUCCESS",
  694. "REQUEST_SET",
  695. `Successfully imported a YouTube playlist to be requested for user "${session.userId}".`
  696. );
  697. return cb({
  698. status: "success",
  699. message: `Playlist is done importing. ${response.successful} were added succesfully, ${response.failed} failed (${response.alreadyInDatabase} were already in database)`,
  700. songs: returnSongs ? response.songs : null
  701. });
  702. }
  703. );
  704. }),
  705. /**
  706. * Likes a song
  707. *
  708. * @param session
  709. * @param youtubeId - the youtube id
  710. * @param cb
  711. */
  712. like: isLoginRequired(async function like(session, youtubeId, cb) {
  713. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  714. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  715. async.waterfall(
  716. [
  717. next => songModel.findOne({ youtubeId }, next),
  718. (song, next) => {
  719. if (!song) return next("No song found with that id.");
  720. return next(null, song);
  721. },
  722. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  723. (song, user, next) => {
  724. if (!user) return next("User does not exist.");
  725. return this.module
  726. .runJob(
  727. "RUN_ACTION2",
  728. {
  729. session,
  730. namespace: "playlists",
  731. action: "addSongToPlaylist",
  732. args: [false, youtubeId, user.likedSongsPlaylist]
  733. },
  734. this
  735. )
  736. .then(res => {
  737. if (res.status === "error") {
  738. if (res.message === "That song is already in the playlist")
  739. return next("You have already liked this song.");
  740. return next("Unable to add song to the 'Liked Songs' playlist.");
  741. }
  742. return next(null, song, user.dislikedSongsPlaylist);
  743. })
  744. .catch(err => next(err));
  745. },
  746. (song, dislikedSongsPlaylist, next) => {
  747. this.module
  748. .runJob(
  749. "RUN_ACTION2",
  750. {
  751. session,
  752. namespace: "playlists",
  753. action: "removeSongFromPlaylist",
  754. args: [youtubeId, dislikedSongsPlaylist]
  755. },
  756. this
  757. )
  758. .then(res => {
  759. if (res.status === "error")
  760. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  761. return next(null, song);
  762. })
  763. .catch(err => next(err));
  764. },
  765. (song, next) => {
  766. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  767. .then(ratings => next(null, song, ratings))
  768. .catch(err => next(err));
  769. }
  770. ],
  771. async (err, song, { likes, dislikes }) => {
  772. if (err) {
  773. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  774. this.log(
  775. "ERROR",
  776. "SONGS_LIKE",
  777. `User "${session.userId}" failed to like song ${youtubeId}. "${err}"`
  778. );
  779. return cb({ status: "error", message: err });
  780. }
  781. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  782. CacheModule.runJob("PUB", {
  783. channel: "song.like",
  784. value: JSON.stringify({
  785. youtubeId,
  786. userId: session.userId,
  787. likes,
  788. dislikes
  789. })
  790. });
  791. ActivitiesModule.runJob("ADD_ACTIVITY", {
  792. userId: session.userId,
  793. type: "song__like",
  794. payload: {
  795. message: `Liked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  796. youtubeId,
  797. thumbnail: song.thumbnail
  798. }
  799. });
  800. return cb({
  801. status: "success",
  802. message: "You have successfully liked this song."
  803. });
  804. }
  805. );
  806. }),
  807. /**
  808. * Dislikes a song
  809. *
  810. * @param session
  811. * @param youtubeId - the youtube id
  812. * @param cb
  813. */
  814. dislike: isLoginRequired(async function dislike(session, youtubeId, cb) {
  815. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  816. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  817. async.waterfall(
  818. [
  819. next => {
  820. songModel.findOne({ youtubeId }, next);
  821. },
  822. (song, next) => {
  823. if (!song) return next("No song found with that id.");
  824. return next(null, song);
  825. },
  826. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  827. (song, user, next) => {
  828. if (!user) return next("User does not exist.");
  829. return this.module
  830. .runJob(
  831. "RUN_ACTION2",
  832. {
  833. session,
  834. namespace: "playlists",
  835. action: "addSongToPlaylist",
  836. args: [false, youtubeId, user.dislikedSongsPlaylist]
  837. },
  838. this
  839. )
  840. .then(res => {
  841. if (res.status === "error") {
  842. if (res.message === "That song is already in the playlist")
  843. return next("You have already disliked this song.");
  844. return next("Unable to add song to the 'Disliked Songs' playlist.");
  845. }
  846. return next(null, song, user.likedSongsPlaylist);
  847. })
  848. .catch(err => next(err));
  849. },
  850. (song, likedSongsPlaylist, next) => {
  851. this.module
  852. .runJob(
  853. "RUN_ACTION2",
  854. {
  855. session,
  856. namespace: "playlists",
  857. action: "removeSongFromPlaylist",
  858. args: [youtubeId, likedSongsPlaylist]
  859. },
  860. this
  861. )
  862. .then(res => {
  863. if (res.status === "error")
  864. return next("Unable to remove song from the 'Liked Songs' playlist.");
  865. return next(null, song);
  866. })
  867. .catch(err => next(err));
  868. },
  869. (song, next) => {
  870. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  871. .then(ratings => next(null, song, ratings))
  872. .catch(err => next(err));
  873. }
  874. ],
  875. async (err, song, { likes, dislikes }) => {
  876. if (err) {
  877. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  878. this.log(
  879. "ERROR",
  880. "SONGS_DISLIKE",
  881. `User "${session.userId}" failed to dislike song ${youtubeId}. "${err}"`
  882. );
  883. return cb({ status: "error", message: err });
  884. }
  885. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  886. CacheModule.runJob("PUB", {
  887. channel: "song.dislike",
  888. value: JSON.stringify({
  889. youtubeId,
  890. userId: session.userId,
  891. likes,
  892. dislikes
  893. })
  894. });
  895. ActivitiesModule.runJob("ADD_ACTIVITY", {
  896. userId: session.userId,
  897. type: "song__dislike",
  898. payload: {
  899. message: `Disliked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  900. youtubeId,
  901. thumbnail: song.thumbnail
  902. }
  903. });
  904. return cb({
  905. status: "success",
  906. message: "You have successfully disliked this song."
  907. });
  908. }
  909. );
  910. }),
  911. /**
  912. * Undislikes a song
  913. *
  914. * @param session
  915. * @param youtubeId - the youtube id
  916. * @param cb
  917. */
  918. undislike: isLoginRequired(async function undislike(session, youtubeId, cb) {
  919. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  920. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  921. async.waterfall(
  922. [
  923. next => {
  924. songModel.findOne({ youtubeId }, next);
  925. },
  926. (song, next) => {
  927. if (!song) return next("No song found with that id.");
  928. return next(null, song);
  929. },
  930. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  931. (song, user, next) => {
  932. if (!user) return next("User does not exist.");
  933. return this.module
  934. .runJob(
  935. "RUN_ACTION2",
  936. {
  937. session,
  938. namespace: "playlists",
  939. action: "removeSongFromPlaylist",
  940. args: [youtubeId, user.dislikedSongsPlaylist]
  941. },
  942. this
  943. )
  944. .then(res => {
  945. if (res.status === "error")
  946. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  947. return next(null, song, user.likedSongsPlaylist);
  948. })
  949. .catch(err => next(err));
  950. },
  951. (song, likedSongsPlaylist, next) => {
  952. this.module
  953. .runJob(
  954. "RUN_ACTION2",
  955. {
  956. session,
  957. namespace: "playlists",
  958. action: "removeSongFromPlaylist",
  959. args: [youtubeId, likedSongsPlaylist]
  960. },
  961. this
  962. )
  963. .then(res => {
  964. if (res.status === "error")
  965. return next("Unable to remove song from the 'Liked Songs' playlist.");
  966. return next(null, song);
  967. })
  968. .catch(err => next(err));
  969. },
  970. (song, next) => {
  971. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  972. .then(ratings => next(null, song, ratings))
  973. .catch(err => next(err));
  974. }
  975. ],
  976. async (err, song, { likes, dislikes }) => {
  977. if (err) {
  978. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  979. this.log(
  980. "ERROR",
  981. "SONGS_UNDISLIKE",
  982. `User "${session.userId}" failed to undislike song ${youtubeId}. "${err}"`
  983. );
  984. return cb({ status: "error", message: err });
  985. }
  986. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  987. CacheModule.runJob("PUB", {
  988. channel: "song.undislike",
  989. value: JSON.stringify({
  990. youtubeId,
  991. userId: session.userId,
  992. likes,
  993. dislikes
  994. })
  995. });
  996. ActivitiesModule.runJob("ADD_ACTIVITY", {
  997. userId: session.userId,
  998. type: "song__undislike",
  999. payload: {
  1000. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  1001. ", "
  1002. )}</youtubeId> from your Disliked Songs`,
  1003. youtubeId,
  1004. thumbnail: song.thumbnail
  1005. }
  1006. });
  1007. return cb({
  1008. status: "success",
  1009. message: "You have successfully undisliked this song."
  1010. });
  1011. }
  1012. );
  1013. }),
  1014. /**
  1015. * Unlikes a song
  1016. *
  1017. * @param session
  1018. * @param youtubeId - the youtube id
  1019. * @param cb
  1020. */
  1021. unlike: isLoginRequired(async function unlike(session, youtubeId, cb) {
  1022. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1023. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1024. async.waterfall(
  1025. [
  1026. next => {
  1027. songModel.findOne({ youtubeId }, next);
  1028. },
  1029. (song, next) => {
  1030. if (!song) return next("No song found with that id.");
  1031. return next(null, song);
  1032. },
  1033. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1034. (song, user, next) => {
  1035. if (!user) return next("User does not exist.");
  1036. return this.module
  1037. .runJob(
  1038. "RUN_ACTION2",
  1039. {
  1040. session,
  1041. namespace: "playlists",
  1042. action: "removeSongFromPlaylist",
  1043. args: [youtubeId, user.dislikedSongsPlaylist]
  1044. },
  1045. this
  1046. )
  1047. .then(res => {
  1048. if (res.status === "error")
  1049. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1050. return next(null, song, user.likedSongsPlaylist);
  1051. })
  1052. .catch(err => next(err));
  1053. },
  1054. (song, likedSongsPlaylist, next) => {
  1055. this.module
  1056. .runJob(
  1057. "RUN_ACTION2",
  1058. {
  1059. session,
  1060. namespace: "playlists",
  1061. action: "removeSongFromPlaylist",
  1062. args: [youtubeId, likedSongsPlaylist]
  1063. },
  1064. this
  1065. )
  1066. .then(res => {
  1067. if (res.status === "error")
  1068. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1069. return next(null, song);
  1070. })
  1071. .catch(err => next(err));
  1072. },
  1073. (song, next) => {
  1074. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1075. .then(ratings => next(null, song, ratings))
  1076. .catch(err => next(err));
  1077. }
  1078. ],
  1079. async (err, song, { likes, dislikes }) => {
  1080. if (err) {
  1081. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1082. this.log(
  1083. "ERROR",
  1084. "SONGS_UNLIKE",
  1085. `User "${session.userId}" failed to unlike song ${youtubeId}. "${err}"`
  1086. );
  1087. return cb({ status: "error", message: err });
  1088. }
  1089. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1090. CacheModule.runJob("PUB", {
  1091. channel: "song.unlike",
  1092. value: JSON.stringify({
  1093. youtubeId,
  1094. userId: session.userId,
  1095. likes,
  1096. dislikes
  1097. })
  1098. });
  1099. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1100. userId: session.userId,
  1101. type: "song__unlike",
  1102. payload: {
  1103. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  1104. ", "
  1105. )}</youtubeId> from your Liked Songs`,
  1106. youtubeId,
  1107. thumbnail: song.thumbnail
  1108. }
  1109. });
  1110. return cb({
  1111. status: "success",
  1112. message: "You have successfully unliked this song."
  1113. });
  1114. }
  1115. );
  1116. }),
  1117. /**
  1118. * Gets song ratings
  1119. *
  1120. * @param session
  1121. * @param songId - the Musare song id
  1122. * @param cb
  1123. */
  1124. getSongRatings: isLoginRequired(async function getSongRatings(session, songId, cb) {
  1125. async.waterfall(
  1126. [
  1127. next => {
  1128. SongsModule.runJob("GET_SONG", { songId }, this)
  1129. .then(res => next(null, res.song))
  1130. .catch(next);
  1131. },
  1132. (song, next) => {
  1133. next(null, {
  1134. likes: song.likes,
  1135. dislikes: song.dislikes
  1136. });
  1137. }
  1138. ],
  1139. async (err, ratings) => {
  1140. if (err) {
  1141. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1142. this.log(
  1143. "ERROR",
  1144. "SONGS_GET_RATINGS",
  1145. `User "${session.userId}" failed to get ratings for ${songId}. "${err}"`
  1146. );
  1147. return cb({ status: "error", message: err });
  1148. }
  1149. const { likes, dislikes } = ratings;
  1150. return cb({
  1151. status: "success",
  1152. data: {
  1153. likes,
  1154. dislikes
  1155. }
  1156. });
  1157. }
  1158. );
  1159. }),
  1160. /**
  1161. * Gets user's own song ratings
  1162. *
  1163. * @param session
  1164. * @param youtubeId - the youtube id
  1165. * @param cb
  1166. */
  1167. getOwnSongRatings: isLoginRequired(async function getOwnSongRatings(session, youtubeId, cb) {
  1168. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1169. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1170. async.waterfall(
  1171. [
  1172. next => songModel.findOne({ youtubeId }, next),
  1173. (song, next) => {
  1174. if (!song) return next("No song found with that id.");
  1175. return next(null);
  1176. },
  1177. next =>
  1178. playlistModel.findOne(
  1179. { createdBy: session.userId, displayName: "Liked Songs" },
  1180. (err, playlist) => {
  1181. if (err) return next(err);
  1182. if (!playlist) return next("'Liked Songs' playlist does not exist.");
  1183. let isLiked = false;
  1184. Object.values(playlist.songs).forEach(song => {
  1185. // song is found in 'liked songs' playlist
  1186. if (song.youtubeId === youtubeId) isLiked = true;
  1187. });
  1188. return next(null, isLiked);
  1189. }
  1190. ),
  1191. (isLiked, next) =>
  1192. playlistModel.findOne(
  1193. { createdBy: session.userId, displayName: "Disliked Songs" },
  1194. (err, playlist) => {
  1195. if (err) return next(err);
  1196. if (!playlist) return next("'Disliked Songs' playlist does not exist.");
  1197. const ratings = { isLiked, isDisliked: false };
  1198. Object.values(playlist.songs).forEach(song => {
  1199. // song is found in 'disliked songs' playlist
  1200. if (song.youtubeId === youtubeId) ratings.isDisliked = true;
  1201. });
  1202. return next(null, ratings);
  1203. }
  1204. )
  1205. ],
  1206. async (err, ratings) => {
  1207. if (err) {
  1208. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1209. this.log(
  1210. "ERROR",
  1211. "SONGS_GET_OWN_RATINGS",
  1212. `User "${session.userId}" failed to get ratings for ${youtubeId}. "${err}"`
  1213. );
  1214. return cb({ status: "error", message: err });
  1215. }
  1216. const { isLiked, isDisliked } = ratings;
  1217. return cb({
  1218. status: "success",
  1219. data: {
  1220. youtubeId,
  1221. liked: isLiked,
  1222. disliked: isDisliked
  1223. }
  1224. });
  1225. }
  1226. );
  1227. })
  1228. };