songs.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  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. // * Adds a song
  710. // *
  711. // * @param session
  712. // * @param song - the song object
  713. // * @param cb
  714. // */
  715. // add: isAdminRequired(async function add(session, song, cb) {
  716. // const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  717. // async.waterfall(
  718. // [
  719. // next => {
  720. // SongModel.findOne({ youtubeId: song.youtubeId }, next);
  721. // },
  722. // (existingSong, next) => {
  723. // if (existingSong) return next("Song is already in rotation.");
  724. // return next();
  725. // },
  726. // next => {
  727. // const newSong = new SongModel(song);
  728. // newSong.verifiedBy = session.userId;
  729. // newSong.verifiedAt = Date.now();
  730. // newSong.save(next);
  731. // },
  732. // (res, next) => {
  733. // this.module
  734. // .runJob(
  735. // "RUN_ACTION2",
  736. // {
  737. // session,
  738. // namespace: "queueSongs",
  739. // action: "remove",
  740. // args: [song._id]
  741. // },
  742. // this
  743. // )
  744. // .finally(() => {
  745. // song.genres.forEach(genre => {
  746. // PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  747. // .then(() => {})
  748. // .catch(() => {});
  749. // });
  750. // next();
  751. // });
  752. // }
  753. // ],
  754. // async err => {
  755. // if (err) {
  756. // err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  757. // this.log("ERROR", "SONGS_ADD", `User "${session.userId}" failed to add song. "${err}"`);
  758. // return cb({ status: "error", message: err });
  759. // }
  760. // this.log("SUCCESS", "SONGS_ADD", `User "${session.userId}" successfully added song "${song.youtubeId}".`);
  761. // CacheModule.runJob("PUB", {
  762. // channel: "song.added",
  763. // value: song.youtubeId
  764. // });
  765. // return cb({
  766. // status: "success",
  767. // message: "Song has been moved from the queue successfully."
  768. // });
  769. // }
  770. // );
  771. // // TODO Check if video is in queue and Add the song to the appropriate stations
  772. // }),
  773. /**
  774. * Likes a song
  775. *
  776. * @param session
  777. * @param youtubeId - the youtube id
  778. * @param cb
  779. */
  780. like: isLoginRequired(async function like(session, youtubeId, cb) {
  781. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  782. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  783. async.waterfall(
  784. [
  785. next => songModel.findOne({ youtubeId }, next),
  786. (song, next) => {
  787. if (!song) return next("No song found with that id.");
  788. return next(null, song);
  789. },
  790. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  791. (song, user, next) => {
  792. if (!user) return next("User does not exist.");
  793. return this.module
  794. .runJob(
  795. "RUN_ACTION2",
  796. {
  797. session,
  798. namespace: "playlists",
  799. action: "addSongToPlaylist",
  800. args: [false, youtubeId, user.likedSongsPlaylist]
  801. },
  802. this
  803. )
  804. .then(res => {
  805. if (res.status === "error") {
  806. if (res.message === "That song is already in the playlist")
  807. return next("You have already liked this song.");
  808. return next("Unable to add song to the 'Liked Songs' playlist.");
  809. }
  810. return next(null, song, user.dislikedSongsPlaylist);
  811. })
  812. .catch(err => next(err));
  813. },
  814. (song, dislikedSongsPlaylist, next) => {
  815. this.module
  816. .runJob(
  817. "RUN_ACTION2",
  818. {
  819. session,
  820. namespace: "playlists",
  821. action: "removeSongFromPlaylist",
  822. args: [youtubeId, dislikedSongsPlaylist]
  823. },
  824. this
  825. )
  826. .then(res => {
  827. if (res.status === "error")
  828. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  829. return next(null, song);
  830. })
  831. .catch(err => next(err));
  832. },
  833. (song, next) => {
  834. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  835. .then(ratings => next(null, song, ratings))
  836. .catch(err => next(err));
  837. }
  838. ],
  839. async (err, song, { likes, dislikes }) => {
  840. if (err) {
  841. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  842. this.log(
  843. "ERROR",
  844. "SONGS_LIKE",
  845. `User "${session.userId}" failed to like song ${youtubeId}. "${err}"`
  846. );
  847. return cb({ status: "error", message: err });
  848. }
  849. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  850. CacheModule.runJob("PUB", {
  851. channel: "song.like",
  852. value: JSON.stringify({
  853. youtubeId,
  854. userId: session.userId,
  855. likes,
  856. dislikes
  857. })
  858. });
  859. ActivitiesModule.runJob("ADD_ACTIVITY", {
  860. userId: session.userId,
  861. type: "song__like",
  862. payload: {
  863. message: `Liked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  864. youtubeId,
  865. thumbnail: song.thumbnail
  866. }
  867. });
  868. return cb({
  869. status: "success",
  870. message: "You have successfully liked this song."
  871. });
  872. }
  873. );
  874. }),
  875. /**
  876. * Dislikes a song
  877. *
  878. * @param session
  879. * @param youtubeId - the youtube id
  880. * @param cb
  881. */
  882. dislike: isLoginRequired(async function dislike(session, youtubeId, cb) {
  883. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  884. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  885. async.waterfall(
  886. [
  887. next => {
  888. songModel.findOne({ youtubeId }, next);
  889. },
  890. (song, next) => {
  891. if (!song) return next("No song found with that id.");
  892. return next(null, song);
  893. },
  894. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  895. (song, user, next) => {
  896. if (!user) return next("User does not exist.");
  897. return this.module
  898. .runJob(
  899. "RUN_ACTION2",
  900. {
  901. session,
  902. namespace: "playlists",
  903. action: "addSongToPlaylist",
  904. args: [false, youtubeId, user.dislikedSongsPlaylist]
  905. },
  906. this
  907. )
  908. .then(res => {
  909. if (res.status === "error") {
  910. if (res.message === "That song is already in the playlist")
  911. return next("You have already disliked this song.");
  912. return next("Unable to add song to the 'Disliked Songs' playlist.");
  913. }
  914. return next(null, song, user.likedSongsPlaylist);
  915. })
  916. .catch(err => next(err));
  917. },
  918. (song, likedSongsPlaylist, next) => {
  919. this.module
  920. .runJob(
  921. "RUN_ACTION2",
  922. {
  923. session,
  924. namespace: "playlists",
  925. action: "removeSongFromPlaylist",
  926. args: [youtubeId, likedSongsPlaylist]
  927. },
  928. this
  929. )
  930. .then(res => {
  931. if (res.status === "error")
  932. return next("Unable to remove song from the 'Liked Songs' playlist.");
  933. return next(null, song);
  934. })
  935. .catch(err => next(err));
  936. },
  937. (song, next) => {
  938. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  939. .then(ratings => next(null, song, ratings))
  940. .catch(err => next(err));
  941. }
  942. ],
  943. async (err, song, { likes, dislikes }) => {
  944. if (err) {
  945. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  946. this.log(
  947. "ERROR",
  948. "SONGS_DISLIKE",
  949. `User "${session.userId}" failed to dislike song ${youtubeId}. "${err}"`
  950. );
  951. return cb({ status: "error", message: err });
  952. }
  953. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  954. CacheModule.runJob("PUB", {
  955. channel: "song.dislike",
  956. value: JSON.stringify({
  957. youtubeId,
  958. userId: session.userId,
  959. likes,
  960. dislikes
  961. })
  962. });
  963. ActivitiesModule.runJob("ADD_ACTIVITY", {
  964. userId: session.userId,
  965. type: "song__dislike",
  966. payload: {
  967. message: `Disliked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  968. youtubeId,
  969. thumbnail: song.thumbnail
  970. }
  971. });
  972. return cb({
  973. status: "success",
  974. message: "You have successfully disliked this song."
  975. });
  976. }
  977. );
  978. }),
  979. /**
  980. * Undislikes a song
  981. *
  982. * @param session
  983. * @param youtubeId - the youtube id
  984. * @param cb
  985. */
  986. undislike: isLoginRequired(async function undislike(session, youtubeId, cb) {
  987. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  988. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  989. async.waterfall(
  990. [
  991. next => {
  992. songModel.findOne({ youtubeId }, next);
  993. },
  994. (song, next) => {
  995. if (!song) return next("No song found with that id.");
  996. return next(null, song);
  997. },
  998. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  999. (song, user, next) => {
  1000. if (!user) return next("User does not exist.");
  1001. return this.module
  1002. .runJob(
  1003. "RUN_ACTION2",
  1004. {
  1005. session,
  1006. namespace: "playlists",
  1007. action: "removeSongFromPlaylist",
  1008. args: [youtubeId, user.dislikedSongsPlaylist]
  1009. },
  1010. this
  1011. )
  1012. .then(res => {
  1013. if (res.status === "error")
  1014. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1015. return next(null, song, user.likedSongsPlaylist);
  1016. })
  1017. .catch(err => next(err));
  1018. },
  1019. (song, likedSongsPlaylist, next) => {
  1020. this.module
  1021. .runJob(
  1022. "RUN_ACTION2",
  1023. {
  1024. session,
  1025. namespace: "playlists",
  1026. action: "removeSongFromPlaylist",
  1027. args: [youtubeId, likedSongsPlaylist]
  1028. },
  1029. this
  1030. )
  1031. .then(res => {
  1032. if (res.status === "error")
  1033. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1034. return next(null, song);
  1035. })
  1036. .catch(err => next(err));
  1037. },
  1038. (song, next) => {
  1039. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1040. .then(ratings => next(null, song, ratings))
  1041. .catch(err => next(err));
  1042. }
  1043. ],
  1044. async (err, song, { likes, dislikes }) => {
  1045. if (err) {
  1046. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1047. this.log(
  1048. "ERROR",
  1049. "SONGS_UNDISLIKE",
  1050. `User "${session.userId}" failed to undislike song ${youtubeId}. "${err}"`
  1051. );
  1052. return cb({ status: "error", message: err });
  1053. }
  1054. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1055. CacheModule.runJob("PUB", {
  1056. channel: "song.undislike",
  1057. value: JSON.stringify({
  1058. youtubeId,
  1059. userId: session.userId,
  1060. likes,
  1061. dislikes
  1062. })
  1063. });
  1064. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1065. userId: session.userId,
  1066. type: "song__undislike",
  1067. payload: {
  1068. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  1069. ", "
  1070. )}</youtubeId> from your Disliked Songs`,
  1071. youtubeId,
  1072. thumbnail: song.thumbnail
  1073. }
  1074. });
  1075. return cb({
  1076. status: "success",
  1077. message: "You have successfully undisliked this song."
  1078. });
  1079. }
  1080. );
  1081. }),
  1082. /**
  1083. * Unlikes a song
  1084. *
  1085. * @param session
  1086. * @param youtubeId - the youtube id
  1087. * @param cb
  1088. */
  1089. unlike: isLoginRequired(async function unlike(session, youtubeId, cb) {
  1090. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1091. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1092. async.waterfall(
  1093. [
  1094. next => {
  1095. songModel.findOne({ youtubeId }, next);
  1096. },
  1097. (song, next) => {
  1098. if (!song) return next("No song found with that id.");
  1099. return next(null, song);
  1100. },
  1101. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1102. (song, user, next) => {
  1103. if (!user) return next("User does not exist.");
  1104. return this.module
  1105. .runJob(
  1106. "RUN_ACTION2",
  1107. {
  1108. session,
  1109. namespace: "playlists",
  1110. action: "removeSongFromPlaylist",
  1111. args: [youtubeId, user.dislikedSongsPlaylist]
  1112. },
  1113. this
  1114. )
  1115. .then(res => {
  1116. if (res.status === "error")
  1117. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1118. return next(null, song, user.likedSongsPlaylist);
  1119. })
  1120. .catch(err => next(err));
  1121. },
  1122. (song, likedSongsPlaylist, next) => {
  1123. this.module
  1124. .runJob(
  1125. "RUN_ACTION2",
  1126. {
  1127. session,
  1128. namespace: "playlists",
  1129. action: "removeSongFromPlaylist",
  1130. args: [youtubeId, likedSongsPlaylist]
  1131. },
  1132. this
  1133. )
  1134. .then(res => {
  1135. if (res.status === "error")
  1136. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1137. return next(null, song);
  1138. })
  1139. .catch(err => next(err));
  1140. },
  1141. (song, next) => {
  1142. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1143. .then(ratings => next(null, song, ratings))
  1144. .catch(err => next(err));
  1145. }
  1146. ],
  1147. async (err, song, { likes, dislikes }) => {
  1148. if (err) {
  1149. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1150. this.log(
  1151. "ERROR",
  1152. "SONGS_UNLIKE",
  1153. `User "${session.userId}" failed to unlike song ${youtubeId}. "${err}"`
  1154. );
  1155. return cb({ status: "error", message: err });
  1156. }
  1157. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1158. CacheModule.runJob("PUB", {
  1159. channel: "song.unlike",
  1160. value: JSON.stringify({
  1161. youtubeId,
  1162. userId: session.userId,
  1163. likes,
  1164. dislikes
  1165. })
  1166. });
  1167. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1168. userId: session.userId,
  1169. type: "song__unlike",
  1170. payload: {
  1171. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  1172. ", "
  1173. )}</youtubeId> from your Liked Songs`,
  1174. youtubeId,
  1175. thumbnail: song.thumbnail
  1176. }
  1177. });
  1178. return cb({
  1179. status: "success",
  1180. message: "You have successfully unliked this song."
  1181. });
  1182. }
  1183. );
  1184. }),
  1185. /**
  1186. * Gets song ratings
  1187. *
  1188. * @param session
  1189. * @param songId - the Musare song id
  1190. * @param cb
  1191. */
  1192. getSongRatings: isLoginRequired(async function getSongRatings(session, songId, cb) {
  1193. async.waterfall(
  1194. [
  1195. next => {
  1196. SongsModule.runJob("GET_SONG", { songId }, this)
  1197. .then(res => next(null, res.song))
  1198. .catch(next);
  1199. },
  1200. (song, next) => {
  1201. next(null, {
  1202. likes: song.likes,
  1203. dislikes: song.dislikes
  1204. });
  1205. }
  1206. ],
  1207. async (err, ratings) => {
  1208. if (err) {
  1209. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1210. this.log(
  1211. "ERROR",
  1212. "SONGS_GET_RATINGS",
  1213. `User "${session.userId}" failed to get ratings for ${songId}. "${err}"`
  1214. );
  1215. return cb({ status: "error", message: err });
  1216. }
  1217. const { likes, dislikes } = ratings;
  1218. return cb({
  1219. status: "success",
  1220. data: {
  1221. likes,
  1222. dislikes
  1223. }
  1224. });
  1225. }
  1226. );
  1227. }),
  1228. /**
  1229. * Gets user's own song ratings
  1230. *
  1231. * @param session
  1232. * @param youtubeId - the youtube id
  1233. * @param cb
  1234. */
  1235. getOwnSongRatings: isLoginRequired(async function getOwnSongRatings(session, youtubeId, cb) {
  1236. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1237. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1238. async.waterfall(
  1239. [
  1240. next => songModel.findOne({ youtubeId }, next),
  1241. (song, next) => {
  1242. if (!song) return next("No song found with that id.");
  1243. return next(null);
  1244. },
  1245. next =>
  1246. playlistModel.findOne(
  1247. { createdBy: session.userId, displayName: "Liked Songs" },
  1248. (err, playlist) => {
  1249. if (err) return next(err);
  1250. if (!playlist) return next("'Liked Songs' playlist does not exist.");
  1251. let isLiked = false;
  1252. Object.values(playlist.songs).forEach(song => {
  1253. // song is found in 'liked songs' playlist
  1254. if (song.youtubeId === youtubeId) isLiked = true;
  1255. });
  1256. return next(null, isLiked);
  1257. }
  1258. ),
  1259. (isLiked, next) =>
  1260. playlistModel.findOne(
  1261. { createdBy: session.userId, displayName: "Disliked Songs" },
  1262. (err, playlist) => {
  1263. if (err) return next(err);
  1264. if (!playlist) return next("'Disliked Songs' playlist does not exist.");
  1265. const ratings = { isLiked, isDisliked: false };
  1266. Object.values(playlist.songs).forEach(song => {
  1267. // song is found in 'disliked songs' playlist
  1268. if (song.youtubeId === youtubeId) ratings.isDisliked = true;
  1269. });
  1270. return next(null, ratings);
  1271. }
  1272. )
  1273. ],
  1274. async (err, ratings) => {
  1275. if (err) {
  1276. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1277. this.log(
  1278. "ERROR",
  1279. "SONGS_GET_OWN_RATINGS",
  1280. `User "${session.userId}" failed to get ratings for ${youtubeId}. "${err}"`
  1281. );
  1282. return cb({ status: "error", message: err });
  1283. }
  1284. const { isLiked, isDisliked } = ratings;
  1285. return cb({
  1286. status: "success",
  1287. data: {
  1288. youtubeId,
  1289. liked: isLiked,
  1290. disliked: isDisliked
  1291. }
  1292. });
  1293. }
  1294. );
  1295. })
  1296. };