songs.js 34 KB

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