1
0

songs.js 35 KB

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