songs.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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. next(null, song);
  289. })
  290. .catch(next);
  291. }
  292. ],
  293. async (err, song) => {
  294. if (err) {
  295. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  296. this.log("ERROR", "SONGS_UPDATE", `Failed to update song "${songId}". "${err}"`);
  297. return cb({ status: "error", message: err });
  298. }
  299. this.log("SUCCESS", "SONGS_UPDATE", `Successfully updated song "${songId}".`);
  300. return cb({
  301. status: "success",
  302. message: "Song has been successfully updated",
  303. data: { song }
  304. });
  305. }
  306. );
  307. }),
  308. // /**
  309. // * Removes a song
  310. // *
  311. // * @param session
  312. // * @param songId - the song id
  313. // * @param cb
  314. // */
  315. // remove: isAdminRequired(async function remove(session, songId, cb) {
  316. // const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  317. // let song = null;
  318. // async.waterfall(
  319. // [
  320. // next => {
  321. // songModel.findOne({ _id: songId }, next);
  322. // },
  323. // (_song, next) => {
  324. // song = _song;
  325. // songModel.deleteOne({ _id: songId }, next);
  326. // },
  327. // (res, next) => {
  328. // CacheModule.runJob("HDEL", { table: "songs", key: songId }, this)
  329. // .then(() => {
  330. // next();
  331. // })
  332. // .catch(next)
  333. // .finally(() => {
  334. // song.genres.forEach(genre => {
  335. // PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  336. // .then(() => {})
  337. // .catch(() => {});
  338. // });
  339. // });
  340. // }
  341. // ],
  342. // async err => {
  343. // if (err) {
  344. // err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  345. // this.log("ERROR", "SONGS_REMOVE", `Failed to remove song "${songId}". "${err}"`);
  346. // return cb({ status: "error", message: err });
  347. // }
  348. // this.log("SUCCESS", "SONGS_REMOVE", `Successfully removed song "${songId}".`);
  349. // if (song.status === "verified") {
  350. // CacheModule.runJob("PUB", {
  351. // channel: "song.removedVerifiedSong",
  352. // value: songId
  353. // });
  354. // }
  355. // if (song.status === "unverified") {
  356. // CacheModule.runJob("PUB", {
  357. // channel: "song.removedUnverifiedSong",
  358. // value: songId
  359. // });
  360. // }
  361. // if (song.status === "hidden") {
  362. // CacheModule.runJob("PUB", {
  363. // channel: "song.removedHiddenSong",
  364. // value: songId
  365. // });
  366. // }
  367. // return cb({
  368. // status: "success",
  369. // message: "Song has been successfully removed"
  370. // });
  371. // }
  372. // );
  373. // }),
  374. /**
  375. * Searches through official songs
  376. *
  377. * @param {object} session - the session object automatically added by the websocket
  378. * @param {string} query - the query
  379. * @param {string} page - the page
  380. * @param {Function} cb - gets called with the result
  381. */
  382. searchOfficial: isLoginRequired(async function searchOfficial(session, query, page, cb) {
  383. async.waterfall(
  384. [
  385. next => {
  386. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  387. else next();
  388. },
  389. next => {
  390. SongsModule.runJob("SEARCH", {
  391. query,
  392. includeVerified: true,
  393. trimmed: true,
  394. page
  395. })
  396. .then(response => {
  397. next(null, response);
  398. })
  399. .catch(err => {
  400. next(err);
  401. });
  402. }
  403. ],
  404. async (err, data) => {
  405. if (err) {
  406. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  407. this.log("ERROR", "SONGS_SEARCH_OFFICIAL", `Searching songs failed. "${err}"`);
  408. return cb({ status: "error", message: err });
  409. }
  410. this.log("SUCCESS", "SONGS_SEARCH_OFFICIAL", "Searching songs successful.");
  411. return cb({ status: "success", data });
  412. }
  413. );
  414. }),
  415. /**
  416. * Requests a song
  417. *
  418. * @param {object} session - the session object automatically added by the websocket
  419. * @param {string} youtubeId - the youtube id of the song that gets requested
  420. * @param {string} returnSong - returns the simple song
  421. * @param {Function} cb - gets called with the result
  422. */
  423. request: isLoginRequired(async function add(session, youtubeId, returnSong, cb) {
  424. SongsModule.runJob("REQUEST_SONG", { youtubeId, userId: session.userId }, this)
  425. .then(response => {
  426. this.log(
  427. "SUCCESS",
  428. "SONGS_REQUEST",
  429. `User "${session.userId}" successfully requested song "${youtubeId}".`
  430. );
  431. return cb({
  432. status: "success",
  433. message: "Successfully requested that song",
  434. song: returnSong ? response.song : null
  435. });
  436. })
  437. .catch(async _err => {
  438. const err = await UtilsModule.runJob("GET_ERROR", { error: _err }, this);
  439. this.log(
  440. "ERROR",
  441. "SONGS_REQUEST",
  442. `Requesting song "${youtubeId}" failed for user ${session.userId}. "${err}"`
  443. );
  444. return cb({ status: "error", message: err, song: returnSong && _err.data ? _err.data.song : null });
  445. });
  446. }),
  447. /**
  448. * Hides a song
  449. *
  450. * @param {object} session - the session object automatically added by the websocket
  451. * @param {string} songId - the song id of the song that gets hidden
  452. * @param {Function} cb - gets called with the result
  453. */
  454. hide: isLoginRequired(async function add(session, songId, cb) {
  455. SongsModule.runJob("HIDE_SONG", { songId }, this)
  456. .then(() => {
  457. this.log("SUCCESS", "SONGS_HIDE", `User "${session.userId}" successfully hid song "${songId}".`);
  458. return cb({
  459. status: "success",
  460. message: "Successfully hid that song"
  461. });
  462. })
  463. .catch(async err => {
  464. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  465. this.log("ERROR", "SONGS_HIDE", `Hiding song "${songId}" failed for user ${session.userId}. "${err}"`);
  466. return cb({ status: "error", message: err });
  467. });
  468. }),
  469. /**
  470. * Unhides a song
  471. *
  472. * @param {object} session - the session object automatically added by the websocket
  473. * @param {string} songId - the song id of the song that gets hidden
  474. * @param {Function} cb - gets called with the result
  475. */
  476. unhide: isLoginRequired(async function add(session, songId, cb) {
  477. SongsModule.runJob("UNHIDE_SONG", { songId }, this)
  478. .then(() => {
  479. this.log("SUCCESS", "SONGS_UNHIDE", `User "${session.userId}" successfully unhid song "${songId}".`);
  480. return cb({
  481. status: "success",
  482. message: "Successfully unhid that song"
  483. });
  484. })
  485. .catch(async err => {
  486. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  487. this.log(
  488. "ERROR",
  489. "SONGS_UNHIDE",
  490. `Unhiding song "${songId}" failed for user ${session.userId}. "${err}"`
  491. );
  492. return cb({ status: "error", message: err });
  493. });
  494. }),
  495. /**
  496. * Verifies a song
  497. *
  498. * @param session
  499. * @param songId - the song id
  500. * @param cb
  501. */
  502. verify: isAdminRequired(async function add(session, songId, cb) {
  503. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  504. async.waterfall(
  505. [
  506. next => {
  507. SongModel.findOne({ _id: songId }, next);
  508. },
  509. (song, next) => {
  510. if (!song) return next("This song is not in the database.");
  511. return next(null, song);
  512. },
  513. (song, next) => {
  514. const oldStatus = song.status;
  515. song.verifiedBy = session.userId;
  516. song.verifiedAt = Date.now();
  517. song.status = "verified";
  518. song.save(err => next(err, song, oldStatus));
  519. },
  520. (song, oldStatus, next) => {
  521. song.genres.forEach(genre => {
  522. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  523. .then(() => {})
  524. .catch(() => {});
  525. });
  526. song.artists.forEach(artist => {
  527. PlaylistsModule.runJob("AUTOFILL_ARTIST_PLAYLIST", { artist })
  528. .then(() => {})
  529. .catch(() => {});
  530. });
  531. SongsModule.runJob("UPDATE_SONG", { songId: song._id, oldStatus });
  532. next(null, song, oldStatus);
  533. }
  534. ],
  535. async err => {
  536. if (err) {
  537. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  538. this.log("ERROR", "SONGS_VERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  539. return cb({ status: "error", message: err });
  540. }
  541. this.log("SUCCESS", "SONGS_VERIFY", `User "${session.userId}" successfully verified song "${songId}".`);
  542. return cb({
  543. status: "success",
  544. message: "Song has been verified successfully."
  545. });
  546. }
  547. );
  548. // TODO Check if video is in queue and Add the song to the appropriate stations
  549. }),
  550. /**
  551. * Un-verifies a song
  552. *
  553. * @param session
  554. * @param songId - the song id
  555. * @param cb
  556. */
  557. unverify: isAdminRequired(async function add(session, songId, cb) {
  558. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  559. async.waterfall(
  560. [
  561. next => {
  562. SongModel.findOne({ _id: songId }, next);
  563. },
  564. (song, next) => {
  565. if (!song) return next("This song is not in the database.");
  566. return next(null, song);
  567. },
  568. (song, next) => {
  569. song.status = "unverified";
  570. song.save(err => {
  571. next(err, song);
  572. });
  573. },
  574. (song, next) => {
  575. song.genres.forEach(genre => {
  576. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  577. .then(() => {})
  578. .catch(() => {});
  579. });
  580. song.artists.forEach(artist => {
  581. PlaylistsModule.runJob("AUTOFILL_ARTIST_PLAYLIST", { artist })
  582. .then(() => {})
  583. .catch(() => {});
  584. });
  585. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: "verified" });
  586. next(null);
  587. }
  588. ],
  589. async err => {
  590. if (err) {
  591. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  592. this.log("ERROR", "SONGS_UNVERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  593. return cb({ status: "error", message: err });
  594. }
  595. this.log(
  596. "SUCCESS",
  597. "SONGS_UNVERIFY",
  598. `User "${session.userId}" successfully unverified song "${songId}".`
  599. );
  600. return cb({
  601. status: "success",
  602. message: "Song has been unverified successfully."
  603. });
  604. }
  605. );
  606. // TODO Check if video is in queue and Add the song to the appropriate stations
  607. }),
  608. /**
  609. * Requests a set of songs
  610. *
  611. * @param {object} session - the session object automatically added by the websocket
  612. * @param {string} url - the url of the the YouTube playlist
  613. * @param {boolean} musicOnly - whether to only get music from the playlist
  614. * @param {Function} cb - gets called with the result
  615. */
  616. requestSet: isLoginRequired(function requestSet(session, url, musicOnly, returnSongs, cb) {
  617. async.waterfall(
  618. [
  619. next => {
  620. YouTubeModule.runJob(
  621. "GET_PLAYLIST",
  622. {
  623. url,
  624. musicOnly
  625. },
  626. this
  627. )
  628. .then(res => {
  629. next(null, res.songs);
  630. })
  631. .catch(next);
  632. },
  633. (youtubeIds, next) => {
  634. let successful = 0;
  635. let songs = {};
  636. let failed = 0;
  637. let alreadyInDatabase = 0;
  638. if (youtubeIds.length === 0) next();
  639. async.eachOfLimit(
  640. youtubeIds,
  641. 1,
  642. (youtubeId, index, next) => {
  643. WSModule.runJob(
  644. "RUN_ACTION2",
  645. {
  646. session,
  647. namespace: "songs",
  648. action: "request",
  649. args: [youtubeId, returnSongs]
  650. },
  651. this
  652. )
  653. .then(res => {
  654. if (res.status === "success") successful += 1;
  655. else failed += 1;
  656. if (res.message === "This song is already in the database.") alreadyInDatabase += 1;
  657. if (res.song) songs[index] = res.song;
  658. else songs[index] = null;
  659. })
  660. .catch(() => {
  661. failed += 1;
  662. })
  663. .finally(() => {
  664. next();
  665. });
  666. },
  667. () => {
  668. if (returnSongs)
  669. songs = Object.keys(songs)
  670. .sort()
  671. .map(key => songs[key]);
  672. next(null, { successful, failed, alreadyInDatabase, songs });
  673. }
  674. );
  675. }
  676. ],
  677. async (err, response) => {
  678. if (err) {
  679. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  680. this.log(
  681. "ERROR",
  682. "REQUEST_SET",
  683. `Importing a YouTube playlist to be requested failed for user "${session.userId}". "${err}"`
  684. );
  685. return cb({ status: "error", message: err });
  686. }
  687. this.log(
  688. "SUCCESS",
  689. "REQUEST_SET",
  690. `Successfully imported a YouTube playlist to be requested for user "${session.userId}".`
  691. );
  692. return cb({
  693. status: "success",
  694. message: `Playlist is done importing. ${response.successful} were added succesfully, ${response.failed} failed (${response.alreadyInDatabase} were already in database)`,
  695. songs: returnSongs ? response.songs : null
  696. });
  697. }
  698. );
  699. }),
  700. /**
  701. * Likes a song
  702. *
  703. * @param session
  704. * @param youtubeId - the youtube id
  705. * @param cb
  706. */
  707. like: isLoginRequired(async function like(session, youtubeId, cb) {
  708. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  709. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  710. async.waterfall(
  711. [
  712. next => songModel.findOne({ youtubeId }, next),
  713. (song, next) => {
  714. if (!song) return next("No song found with that id.");
  715. return next(null, song);
  716. },
  717. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  718. (song, user, next) => {
  719. if (!user) return next("User does not exist.");
  720. return this.module
  721. .runJob(
  722. "RUN_ACTION2",
  723. {
  724. session,
  725. namespace: "playlists",
  726. action: "addSongToPlaylist",
  727. args: [false, youtubeId, user.likedSongsPlaylist]
  728. },
  729. this
  730. )
  731. .then(res => {
  732. if (res.status === "error") {
  733. if (res.message === "That song is already in the playlist")
  734. return next("You have already liked this song.");
  735. return next("Unable to add song to the 'Liked Songs' playlist.");
  736. }
  737. return next(null, song, user.dislikedSongsPlaylist);
  738. })
  739. .catch(err => next(err));
  740. },
  741. (song, dislikedSongsPlaylist, next) => {
  742. this.module
  743. .runJob(
  744. "RUN_ACTION2",
  745. {
  746. session,
  747. namespace: "playlists",
  748. action: "removeSongFromPlaylist",
  749. args: [youtubeId, dislikedSongsPlaylist]
  750. },
  751. this
  752. )
  753. .then(res => {
  754. if (res.status === "error")
  755. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  756. return next(null, song);
  757. })
  758. .catch(err => next(err));
  759. },
  760. (song, next) => {
  761. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  762. .then(ratings => next(null, song, ratings))
  763. .catch(err => next(err));
  764. }
  765. ],
  766. async (err, song, { likes, dislikes }) => {
  767. if (err) {
  768. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  769. this.log(
  770. "ERROR",
  771. "SONGS_LIKE",
  772. `User "${session.userId}" failed to like song ${youtubeId}. "${err}"`
  773. );
  774. return cb({ status: "error", message: err });
  775. }
  776. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  777. CacheModule.runJob("PUB", {
  778. channel: "song.like",
  779. value: JSON.stringify({
  780. youtubeId,
  781. userId: session.userId,
  782. likes,
  783. dislikes
  784. })
  785. });
  786. ActivitiesModule.runJob("ADD_ACTIVITY", {
  787. userId: session.userId,
  788. type: "song__like",
  789. payload: {
  790. message: `Liked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  791. youtubeId,
  792. thumbnail: song.thumbnail
  793. }
  794. });
  795. return cb({
  796. status: "success",
  797. message: "You have successfully liked this song."
  798. });
  799. }
  800. );
  801. }),
  802. /**
  803. * Dislikes a song
  804. *
  805. * @param session
  806. * @param youtubeId - the youtube id
  807. * @param cb
  808. */
  809. dislike: isLoginRequired(async function dislike(session, youtubeId, cb) {
  810. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  811. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  812. async.waterfall(
  813. [
  814. next => {
  815. songModel.findOne({ youtubeId }, next);
  816. },
  817. (song, next) => {
  818. if (!song) return next("No song found with that id.");
  819. return next(null, song);
  820. },
  821. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  822. (song, user, next) => {
  823. if (!user) return next("User does not exist.");
  824. return this.module
  825. .runJob(
  826. "RUN_ACTION2",
  827. {
  828. session,
  829. namespace: "playlists",
  830. action: "addSongToPlaylist",
  831. args: [false, youtubeId, user.dislikedSongsPlaylist]
  832. },
  833. this
  834. )
  835. .then(res => {
  836. if (res.status === "error") {
  837. if (res.message === "That song is already in the playlist")
  838. return next("You have already disliked this song.");
  839. return next("Unable to add song to the 'Disliked Songs' playlist.");
  840. }
  841. return next(null, song, user.likedSongsPlaylist);
  842. })
  843. .catch(err => next(err));
  844. },
  845. (song, likedSongsPlaylist, next) => {
  846. this.module
  847. .runJob(
  848. "RUN_ACTION2",
  849. {
  850. session,
  851. namespace: "playlists",
  852. action: "removeSongFromPlaylist",
  853. args: [youtubeId, likedSongsPlaylist]
  854. },
  855. this
  856. )
  857. .then(res => {
  858. if (res.status === "error")
  859. return next("Unable to remove song from the 'Liked Songs' playlist.");
  860. return next(null, song);
  861. })
  862. .catch(err => next(err));
  863. },
  864. (song, next) => {
  865. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  866. .then(ratings => next(null, song, ratings))
  867. .catch(err => next(err));
  868. }
  869. ],
  870. async (err, song, { likes, dislikes }) => {
  871. if (err) {
  872. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  873. this.log(
  874. "ERROR",
  875. "SONGS_DISLIKE",
  876. `User "${session.userId}" failed to dislike song ${youtubeId}. "${err}"`
  877. );
  878. return cb({ status: "error", message: err });
  879. }
  880. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  881. CacheModule.runJob("PUB", {
  882. channel: "song.dislike",
  883. value: JSON.stringify({
  884. youtubeId,
  885. userId: session.userId,
  886. likes,
  887. dislikes
  888. })
  889. });
  890. ActivitiesModule.runJob("ADD_ACTIVITY", {
  891. userId: session.userId,
  892. type: "song__dislike",
  893. payload: {
  894. message: `Disliked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  895. youtubeId,
  896. thumbnail: song.thumbnail
  897. }
  898. });
  899. return cb({
  900. status: "success",
  901. message: "You have successfully disliked this song."
  902. });
  903. }
  904. );
  905. }),
  906. /**
  907. * Undislikes a song
  908. *
  909. * @param session
  910. * @param youtubeId - the youtube id
  911. * @param cb
  912. */
  913. undislike: isLoginRequired(async function undislike(session, youtubeId, cb) {
  914. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  915. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  916. async.waterfall(
  917. [
  918. next => {
  919. songModel.findOne({ youtubeId }, next);
  920. },
  921. (song, next) => {
  922. if (!song) return next("No song found with that id.");
  923. return next(null, song);
  924. },
  925. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  926. (song, user, next) => {
  927. if (!user) return next("User does not exist.");
  928. return this.module
  929. .runJob(
  930. "RUN_ACTION2",
  931. {
  932. session,
  933. namespace: "playlists",
  934. action: "removeSongFromPlaylist",
  935. args: [youtubeId, user.dislikedSongsPlaylist]
  936. },
  937. this
  938. )
  939. .then(res => {
  940. if (res.status === "error")
  941. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  942. return next(null, song, user.likedSongsPlaylist);
  943. })
  944. .catch(err => next(err));
  945. },
  946. (song, likedSongsPlaylist, next) => {
  947. this.module
  948. .runJob(
  949. "RUN_ACTION2",
  950. {
  951. session,
  952. namespace: "playlists",
  953. action: "removeSongFromPlaylist",
  954. args: [youtubeId, likedSongsPlaylist]
  955. },
  956. this
  957. )
  958. .then(res => {
  959. if (res.status === "error")
  960. return next("Unable to remove song from the 'Liked Songs' playlist.");
  961. return next(null, song);
  962. })
  963. .catch(err => next(err));
  964. },
  965. (song, next) => {
  966. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  967. .then(ratings => next(null, song, ratings))
  968. .catch(err => next(err));
  969. }
  970. ],
  971. async (err, song, { likes, dislikes }) => {
  972. if (err) {
  973. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  974. this.log(
  975. "ERROR",
  976. "SONGS_UNDISLIKE",
  977. `User "${session.userId}" failed to undislike song ${youtubeId}. "${err}"`
  978. );
  979. return cb({ status: "error", message: err });
  980. }
  981. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  982. CacheModule.runJob("PUB", {
  983. channel: "song.undislike",
  984. value: JSON.stringify({
  985. youtubeId,
  986. userId: session.userId,
  987. likes,
  988. dislikes
  989. })
  990. });
  991. ActivitiesModule.runJob("ADD_ACTIVITY", {
  992. userId: session.userId,
  993. type: "song__undislike",
  994. payload: {
  995. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  996. ", "
  997. )}</youtubeId> from your Disliked Songs`,
  998. youtubeId,
  999. thumbnail: song.thumbnail
  1000. }
  1001. });
  1002. return cb({
  1003. status: "success",
  1004. message: "You have successfully undisliked this song."
  1005. });
  1006. }
  1007. );
  1008. }),
  1009. /**
  1010. * Unlikes a song
  1011. *
  1012. * @param session
  1013. * @param youtubeId - the youtube id
  1014. * @param cb
  1015. */
  1016. unlike: isLoginRequired(async function unlike(session, youtubeId, cb) {
  1017. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1018. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1019. async.waterfall(
  1020. [
  1021. next => {
  1022. songModel.findOne({ youtubeId }, next);
  1023. },
  1024. (song, next) => {
  1025. if (!song) return next("No song found with that id.");
  1026. return next(null, song);
  1027. },
  1028. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1029. (song, user, next) => {
  1030. if (!user) return next("User does not exist.");
  1031. return this.module
  1032. .runJob(
  1033. "RUN_ACTION2",
  1034. {
  1035. session,
  1036. namespace: "playlists",
  1037. action: "removeSongFromPlaylist",
  1038. args: [youtubeId, user.dislikedSongsPlaylist]
  1039. },
  1040. this
  1041. )
  1042. .then(res => {
  1043. if (res.status === "error")
  1044. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1045. return next(null, song, user.likedSongsPlaylist);
  1046. })
  1047. .catch(err => next(err));
  1048. },
  1049. (song, likedSongsPlaylist, next) => {
  1050. this.module
  1051. .runJob(
  1052. "RUN_ACTION2",
  1053. {
  1054. session,
  1055. namespace: "playlists",
  1056. action: "removeSongFromPlaylist",
  1057. args: [youtubeId, likedSongsPlaylist]
  1058. },
  1059. this
  1060. )
  1061. .then(res => {
  1062. if (res.status === "error")
  1063. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1064. return next(null, song);
  1065. })
  1066. .catch(err => next(err));
  1067. },
  1068. (song, next) => {
  1069. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1070. .then(ratings => next(null, song, ratings))
  1071. .catch(err => next(err));
  1072. }
  1073. ],
  1074. async (err, song, { likes, dislikes }) => {
  1075. if (err) {
  1076. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1077. this.log(
  1078. "ERROR",
  1079. "SONGS_UNLIKE",
  1080. `User "${session.userId}" failed to unlike song ${youtubeId}. "${err}"`
  1081. );
  1082. return cb({ status: "error", message: err });
  1083. }
  1084. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1085. CacheModule.runJob("PUB", {
  1086. channel: "song.unlike",
  1087. value: JSON.stringify({
  1088. youtubeId,
  1089. userId: session.userId,
  1090. likes,
  1091. dislikes
  1092. })
  1093. });
  1094. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1095. userId: session.userId,
  1096. type: "song__unlike",
  1097. payload: {
  1098. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  1099. ", "
  1100. )}</youtubeId> from your Liked Songs`,
  1101. youtubeId,
  1102. thumbnail: song.thumbnail
  1103. }
  1104. });
  1105. return cb({
  1106. status: "success",
  1107. message: "You have successfully unliked this song."
  1108. });
  1109. }
  1110. );
  1111. }),
  1112. /**
  1113. * Gets song ratings
  1114. *
  1115. * @param session
  1116. * @param songId - the Musare song id
  1117. * @param cb
  1118. */
  1119. getSongRatings: isLoginRequired(async function getSongRatings(session, songId, cb) {
  1120. async.waterfall(
  1121. [
  1122. next => {
  1123. SongsModule.runJob("GET_SONG", { songId }, this)
  1124. .then(res => next(null, res.song))
  1125. .catch(next);
  1126. },
  1127. (song, next) => {
  1128. next(null, {
  1129. likes: song.likes,
  1130. dislikes: song.dislikes
  1131. });
  1132. }
  1133. ],
  1134. async (err, ratings) => {
  1135. if (err) {
  1136. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1137. this.log(
  1138. "ERROR",
  1139. "SONGS_GET_RATINGS",
  1140. `User "${session.userId}" failed to get ratings for ${songId}. "${err}"`
  1141. );
  1142. return cb({ status: "error", message: err });
  1143. }
  1144. const { likes, dislikes } = ratings;
  1145. return cb({
  1146. status: "success",
  1147. data: {
  1148. likes,
  1149. dislikes
  1150. }
  1151. });
  1152. }
  1153. );
  1154. }),
  1155. /**
  1156. * Gets user's own song ratings
  1157. *
  1158. * @param session
  1159. * @param youtubeId - the youtube id
  1160. * @param cb
  1161. */
  1162. getOwnSongRatings: isLoginRequired(async function getOwnSongRatings(session, youtubeId, cb) {
  1163. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1164. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1165. async.waterfall(
  1166. [
  1167. next => songModel.findOne({ youtubeId }, next),
  1168. (song, next) => {
  1169. if (!song) return next("No song found with that id.");
  1170. return next(null);
  1171. },
  1172. next =>
  1173. playlistModel.findOne(
  1174. { createdBy: session.userId, displayName: "Liked Songs" },
  1175. (err, playlist) => {
  1176. if (err) return next(err);
  1177. if (!playlist) return next("'Liked Songs' playlist does not exist.");
  1178. let isLiked = false;
  1179. Object.values(playlist.songs).forEach(song => {
  1180. // song is found in 'liked songs' playlist
  1181. if (song.youtubeId === youtubeId) isLiked = true;
  1182. });
  1183. return next(null, isLiked);
  1184. }
  1185. ),
  1186. (isLiked, next) =>
  1187. playlistModel.findOne(
  1188. { createdBy: session.userId, displayName: "Disliked Songs" },
  1189. (err, playlist) => {
  1190. if (err) return next(err);
  1191. if (!playlist) return next("'Disliked Songs' playlist does not exist.");
  1192. const ratings = { isLiked, isDisliked: false };
  1193. Object.values(playlist.songs).forEach(song => {
  1194. // song is found in 'disliked songs' playlist
  1195. if (song.youtubeId === youtubeId) ratings.isDisliked = true;
  1196. });
  1197. return next(null, ratings);
  1198. }
  1199. )
  1200. ],
  1201. async (err, ratings) => {
  1202. if (err) {
  1203. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1204. this.log(
  1205. "ERROR",
  1206. "SONGS_GET_OWN_RATINGS",
  1207. `User "${session.userId}" failed to get ratings for ${youtubeId}. "${err}"`
  1208. );
  1209. return cb({ status: "error", message: err });
  1210. }
  1211. const { isLiked, isDisliked } = ratings;
  1212. return cb({
  1213. status: "success",
  1214. data: {
  1215. youtubeId,
  1216. liked: isLiked,
  1217. disliked: isDisliked
  1218. }
  1219. });
  1220. }
  1221. );
  1222. })
  1223. };