songs.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  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. SongsModule.runJob("UPDATE_SONG", { songId: song._id, oldStatus });
  527. next(null, song, oldStatus);
  528. }
  529. ],
  530. async err => {
  531. if (err) {
  532. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  533. this.log("ERROR", "SONGS_VERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  534. return cb({ status: "error", message: err });
  535. }
  536. this.log("SUCCESS", "SONGS_VERIFY", `User "${session.userId}" successfully verified song "${songId}".`);
  537. return cb({
  538. status: "success",
  539. message: "Song has been verified successfully."
  540. });
  541. }
  542. );
  543. // TODO Check if video is in queue and Add the song to the appropriate stations
  544. }),
  545. /**
  546. * Un-verifies a song
  547. *
  548. * @param session
  549. * @param songId - the song id
  550. * @param cb
  551. */
  552. unverify: isAdminRequired(async function add(session, songId, cb) {
  553. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  554. async.waterfall(
  555. [
  556. next => {
  557. SongModel.findOne({ _id: songId }, next);
  558. },
  559. (song, next) => {
  560. if (!song) return next("This song is not in the database.");
  561. return next(null, song);
  562. },
  563. (song, next) => {
  564. song.status = "unverified";
  565. song.save(err => {
  566. next(err, song);
  567. });
  568. },
  569. (song, next) => {
  570. song.genres.forEach(genre => {
  571. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  572. .then(() => {})
  573. .catch(() => {});
  574. });
  575. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: "verified" });
  576. next(null);
  577. }
  578. ],
  579. async err => {
  580. if (err) {
  581. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  582. this.log("ERROR", "SONGS_UNVERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  583. return cb({ status: "error", message: err });
  584. }
  585. this.log(
  586. "SUCCESS",
  587. "SONGS_UNVERIFY",
  588. `User "${session.userId}" successfully unverified song "${songId}".`
  589. );
  590. return cb({
  591. status: "success",
  592. message: "Song has been unverified successfully."
  593. });
  594. }
  595. );
  596. // TODO Check if video is in queue and Add the song to the appropriate stations
  597. }),
  598. /**
  599. * Requests a set of songs
  600. *
  601. * @param {object} session - the session object automatically added by the websocket
  602. * @param {string} url - the url of the the YouTube playlist
  603. * @param {boolean} musicOnly - whether to only get music from the playlist
  604. * @param {Function} cb - gets called with the result
  605. */
  606. requestSet: isLoginRequired(function requestSet(session, url, musicOnly, returnSongs, cb) {
  607. async.waterfall(
  608. [
  609. next => {
  610. YouTubeModule.runJob(
  611. "GET_PLAYLIST",
  612. {
  613. url,
  614. musicOnly
  615. },
  616. this
  617. )
  618. .then(res => {
  619. next(null, res.songs);
  620. })
  621. .catch(next);
  622. },
  623. (youtubeIds, next) => {
  624. let successful = 0;
  625. let songs = {};
  626. let failed = 0;
  627. let alreadyInDatabase = 0;
  628. if (youtubeIds.length === 0) next();
  629. async.eachOfLimit(
  630. youtubeIds,
  631. 1,
  632. (youtubeId, index, next) => {
  633. WSModule.runJob(
  634. "RUN_ACTION2",
  635. {
  636. session,
  637. namespace: "songs",
  638. action: "request",
  639. args: [youtubeId, returnSongs]
  640. },
  641. this
  642. )
  643. .then(res => {
  644. if (res.status === "success") successful += 1;
  645. else failed += 1;
  646. if (res.message === "This song is already in the database.") alreadyInDatabase += 1;
  647. if (res.song) songs[index] = res.song;
  648. else songs[index] = null;
  649. })
  650. .catch(() => {
  651. failed += 1;
  652. })
  653. .finally(() => {
  654. next();
  655. });
  656. },
  657. () => {
  658. if (returnSongs)
  659. songs = Object.keys(songs)
  660. .sort()
  661. .map(key => songs[key]);
  662. next(null, { successful, failed, alreadyInDatabase, songs });
  663. }
  664. );
  665. }
  666. ],
  667. async (err, response) => {
  668. if (err) {
  669. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  670. this.log(
  671. "ERROR",
  672. "REQUEST_SET",
  673. `Importing a YouTube playlist to be requested failed for user "${session.userId}". "${err}"`
  674. );
  675. return cb({ status: "error", message: err });
  676. }
  677. this.log(
  678. "SUCCESS",
  679. "REQUEST_SET",
  680. `Successfully imported a YouTube playlist to be requested for user "${session.userId}".`
  681. );
  682. return cb({
  683. status: "success",
  684. message: `Playlist is done importing. ${response.successful} were added succesfully, ${response.failed} failed (${response.alreadyInDatabase} were already in database)`,
  685. songs: returnSongs ? response.songs : null
  686. });
  687. }
  688. );
  689. }),
  690. /**
  691. * Likes a song
  692. *
  693. * @param session
  694. * @param youtubeId - the youtube id
  695. * @param cb
  696. */
  697. like: isLoginRequired(async function like(session, youtubeId, cb) {
  698. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  699. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  700. async.waterfall(
  701. [
  702. next => songModel.findOne({ youtubeId }, next),
  703. (song, next) => {
  704. if (!song) return next("No song found with that id.");
  705. return next(null, song);
  706. },
  707. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  708. (song, user, next) => {
  709. if (!user) return next("User does not exist.");
  710. return this.module
  711. .runJob(
  712. "RUN_ACTION2",
  713. {
  714. session,
  715. namespace: "playlists",
  716. action: "addSongToPlaylist",
  717. args: [false, youtubeId, user.likedSongsPlaylist]
  718. },
  719. this
  720. )
  721. .then(res => {
  722. if (res.status === "error") {
  723. if (res.message === "That song is already in the playlist")
  724. return next("You have already liked this song.");
  725. return next("Unable to add song to the 'Liked Songs' playlist.");
  726. }
  727. return next(null, song, user.dislikedSongsPlaylist);
  728. })
  729. .catch(err => next(err));
  730. },
  731. (song, dislikedSongsPlaylist, next) => {
  732. this.module
  733. .runJob(
  734. "RUN_ACTION2",
  735. {
  736. session,
  737. namespace: "playlists",
  738. action: "removeSongFromPlaylist",
  739. args: [youtubeId, dislikedSongsPlaylist]
  740. },
  741. this
  742. )
  743. .then(res => {
  744. if (res.status === "error")
  745. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  746. return next(null, song);
  747. })
  748. .catch(err => next(err));
  749. },
  750. (song, next) => {
  751. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  752. .then(ratings => next(null, song, ratings))
  753. .catch(err => next(err));
  754. }
  755. ],
  756. async (err, song, { likes, dislikes }) => {
  757. if (err) {
  758. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  759. this.log(
  760. "ERROR",
  761. "SONGS_LIKE",
  762. `User "${session.userId}" failed to like song ${youtubeId}. "${err}"`
  763. );
  764. return cb({ status: "error", message: err });
  765. }
  766. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  767. CacheModule.runJob("PUB", {
  768. channel: "song.like",
  769. value: JSON.stringify({
  770. youtubeId,
  771. userId: session.userId,
  772. likes,
  773. dislikes
  774. })
  775. });
  776. ActivitiesModule.runJob("ADD_ACTIVITY", {
  777. userId: session.userId,
  778. type: "song__like",
  779. payload: {
  780. message: `Liked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  781. youtubeId,
  782. thumbnail: song.thumbnail
  783. }
  784. });
  785. return cb({
  786. status: "success",
  787. message: "You have successfully liked this song."
  788. });
  789. }
  790. );
  791. }),
  792. /**
  793. * Dislikes a song
  794. *
  795. * @param session
  796. * @param youtubeId - the youtube id
  797. * @param cb
  798. */
  799. dislike: isLoginRequired(async function dislike(session, youtubeId, cb) {
  800. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  801. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  802. async.waterfall(
  803. [
  804. next => {
  805. songModel.findOne({ youtubeId }, next);
  806. },
  807. (song, next) => {
  808. if (!song) return next("No song found with that id.");
  809. return next(null, song);
  810. },
  811. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  812. (song, user, next) => {
  813. if (!user) return next("User does not exist.");
  814. return this.module
  815. .runJob(
  816. "RUN_ACTION2",
  817. {
  818. session,
  819. namespace: "playlists",
  820. action: "addSongToPlaylist",
  821. args: [false, youtubeId, user.dislikedSongsPlaylist]
  822. },
  823. this
  824. )
  825. .then(res => {
  826. if (res.status === "error") {
  827. if (res.message === "That song is already in the playlist")
  828. return next("You have already disliked this song.");
  829. return next("Unable to add song to the 'Disliked Songs' playlist.");
  830. }
  831. return next(null, song, user.likedSongsPlaylist);
  832. })
  833. .catch(err => next(err));
  834. },
  835. (song, likedSongsPlaylist, next) => {
  836. this.module
  837. .runJob(
  838. "RUN_ACTION2",
  839. {
  840. session,
  841. namespace: "playlists",
  842. action: "removeSongFromPlaylist",
  843. args: [youtubeId, likedSongsPlaylist]
  844. },
  845. this
  846. )
  847. .then(res => {
  848. if (res.status === "error")
  849. return next("Unable to remove song from the 'Liked Songs' playlist.");
  850. return next(null, song);
  851. })
  852. .catch(err => next(err));
  853. },
  854. (song, next) => {
  855. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  856. .then(ratings => next(null, song, ratings))
  857. .catch(err => next(err));
  858. }
  859. ],
  860. async (err, song, { likes, dislikes }) => {
  861. if (err) {
  862. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  863. this.log(
  864. "ERROR",
  865. "SONGS_DISLIKE",
  866. `User "${session.userId}" failed to dislike song ${youtubeId}. "${err}"`
  867. );
  868. return cb({ status: "error", message: err });
  869. }
  870. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  871. CacheModule.runJob("PUB", {
  872. channel: "song.dislike",
  873. value: JSON.stringify({
  874. youtubeId,
  875. userId: session.userId,
  876. likes,
  877. dislikes
  878. })
  879. });
  880. ActivitiesModule.runJob("ADD_ACTIVITY", {
  881. userId: session.userId,
  882. type: "song__dislike",
  883. payload: {
  884. message: `Disliked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  885. youtubeId,
  886. thumbnail: song.thumbnail
  887. }
  888. });
  889. return cb({
  890. status: "success",
  891. message: "You have successfully disliked this song."
  892. });
  893. }
  894. );
  895. }),
  896. /**
  897. * Undislikes a song
  898. *
  899. * @param session
  900. * @param youtubeId - the youtube id
  901. * @param cb
  902. */
  903. undislike: isLoginRequired(async function undislike(session, youtubeId, cb) {
  904. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  905. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  906. async.waterfall(
  907. [
  908. next => {
  909. songModel.findOne({ youtubeId }, next);
  910. },
  911. (song, next) => {
  912. if (!song) return next("No song found with that id.");
  913. return next(null, song);
  914. },
  915. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  916. (song, user, next) => {
  917. if (!user) return next("User does not exist.");
  918. return this.module
  919. .runJob(
  920. "RUN_ACTION2",
  921. {
  922. session,
  923. namespace: "playlists",
  924. action: "removeSongFromPlaylist",
  925. args: [youtubeId, user.dislikedSongsPlaylist]
  926. },
  927. this
  928. )
  929. .then(res => {
  930. if (res.status === "error")
  931. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  932. return next(null, song, user.likedSongsPlaylist);
  933. })
  934. .catch(err => next(err));
  935. },
  936. (song, likedSongsPlaylist, next) => {
  937. this.module
  938. .runJob(
  939. "RUN_ACTION2",
  940. {
  941. session,
  942. namespace: "playlists",
  943. action: "removeSongFromPlaylist",
  944. args: [youtubeId, likedSongsPlaylist]
  945. },
  946. this
  947. )
  948. .then(res => {
  949. if (res.status === "error")
  950. return next("Unable to remove song from the 'Liked Songs' playlist.");
  951. return next(null, song);
  952. })
  953. .catch(err => next(err));
  954. },
  955. (song, next) => {
  956. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  957. .then(ratings => next(null, song, ratings))
  958. .catch(err => next(err));
  959. }
  960. ],
  961. async (err, song, { likes, dislikes }) => {
  962. if (err) {
  963. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  964. this.log(
  965. "ERROR",
  966. "SONGS_UNDISLIKE",
  967. `User "${session.userId}" failed to undislike song ${youtubeId}. "${err}"`
  968. );
  969. return cb({ status: "error", message: err });
  970. }
  971. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  972. CacheModule.runJob("PUB", {
  973. channel: "song.undislike",
  974. value: JSON.stringify({
  975. youtubeId,
  976. userId: session.userId,
  977. likes,
  978. dislikes
  979. })
  980. });
  981. ActivitiesModule.runJob("ADD_ACTIVITY", {
  982. userId: session.userId,
  983. type: "song__undislike",
  984. payload: {
  985. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  986. ", "
  987. )}</youtubeId> from your Disliked Songs`,
  988. youtubeId,
  989. thumbnail: song.thumbnail
  990. }
  991. });
  992. return cb({
  993. status: "success",
  994. message: "You have successfully undisliked this song."
  995. });
  996. }
  997. );
  998. }),
  999. /**
  1000. * Unlikes a song
  1001. *
  1002. * @param session
  1003. * @param youtubeId - the youtube id
  1004. * @param cb
  1005. */
  1006. unlike: isLoginRequired(async function unlike(session, youtubeId, cb) {
  1007. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1008. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1009. async.waterfall(
  1010. [
  1011. next => {
  1012. songModel.findOne({ youtubeId }, next);
  1013. },
  1014. (song, next) => {
  1015. if (!song) return next("No song found with that id.");
  1016. return next(null, song);
  1017. },
  1018. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1019. (song, user, next) => {
  1020. if (!user) return next("User does not exist.");
  1021. return this.module
  1022. .runJob(
  1023. "RUN_ACTION2",
  1024. {
  1025. session,
  1026. namespace: "playlists",
  1027. action: "removeSongFromPlaylist",
  1028. args: [youtubeId, user.dislikedSongsPlaylist]
  1029. },
  1030. this
  1031. )
  1032. .then(res => {
  1033. if (res.status === "error")
  1034. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1035. return next(null, song, user.likedSongsPlaylist);
  1036. })
  1037. .catch(err => next(err));
  1038. },
  1039. (song, likedSongsPlaylist, next) => {
  1040. this.module
  1041. .runJob(
  1042. "RUN_ACTION2",
  1043. {
  1044. session,
  1045. namespace: "playlists",
  1046. action: "removeSongFromPlaylist",
  1047. args: [youtubeId, likedSongsPlaylist]
  1048. },
  1049. this
  1050. )
  1051. .then(res => {
  1052. if (res.status === "error")
  1053. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1054. return next(null, song);
  1055. })
  1056. .catch(err => next(err));
  1057. },
  1058. (song, next) => {
  1059. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1060. .then(ratings => next(null, song, ratings))
  1061. .catch(err => next(err));
  1062. }
  1063. ],
  1064. async (err, song, { likes, dislikes }) => {
  1065. if (err) {
  1066. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1067. this.log(
  1068. "ERROR",
  1069. "SONGS_UNLIKE",
  1070. `User "${session.userId}" failed to unlike song ${youtubeId}. "${err}"`
  1071. );
  1072. return cb({ status: "error", message: err });
  1073. }
  1074. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1075. CacheModule.runJob("PUB", {
  1076. channel: "song.unlike",
  1077. value: JSON.stringify({
  1078. youtubeId,
  1079. userId: session.userId,
  1080. likes,
  1081. dislikes
  1082. })
  1083. });
  1084. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1085. userId: session.userId,
  1086. type: "song__unlike",
  1087. payload: {
  1088. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  1089. ", "
  1090. )}</youtubeId> from your Liked Songs`,
  1091. youtubeId,
  1092. thumbnail: song.thumbnail
  1093. }
  1094. });
  1095. return cb({
  1096. status: "success",
  1097. message: "You have successfully unliked this song."
  1098. });
  1099. }
  1100. );
  1101. }),
  1102. /**
  1103. * Gets song ratings
  1104. *
  1105. * @param session
  1106. * @param songId - the Musare song id
  1107. * @param cb
  1108. */
  1109. getSongRatings: isLoginRequired(async function getSongRatings(session, songId, cb) {
  1110. async.waterfall(
  1111. [
  1112. next => {
  1113. SongsModule.runJob("GET_SONG", { songId }, this)
  1114. .then(res => next(null, res.song))
  1115. .catch(next);
  1116. },
  1117. (song, next) => {
  1118. next(null, {
  1119. likes: song.likes,
  1120. dislikes: song.dislikes
  1121. });
  1122. }
  1123. ],
  1124. async (err, ratings) => {
  1125. if (err) {
  1126. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1127. this.log(
  1128. "ERROR",
  1129. "SONGS_GET_RATINGS",
  1130. `User "${session.userId}" failed to get ratings for ${songId}. "${err}"`
  1131. );
  1132. return cb({ status: "error", message: err });
  1133. }
  1134. const { likes, dislikes } = ratings;
  1135. return cb({
  1136. status: "success",
  1137. data: {
  1138. likes,
  1139. dislikes
  1140. }
  1141. });
  1142. }
  1143. );
  1144. }),
  1145. /**
  1146. * Gets user's own song ratings
  1147. *
  1148. * @param session
  1149. * @param youtubeId - the youtube id
  1150. * @param cb
  1151. */
  1152. getOwnSongRatings: isLoginRequired(async function getOwnSongRatings(session, youtubeId, cb) {
  1153. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1154. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1155. async.waterfall(
  1156. [
  1157. next => songModel.findOne({ youtubeId }, next),
  1158. (song, next) => {
  1159. if (!song) return next("No song found with that id.");
  1160. return next(null);
  1161. },
  1162. next =>
  1163. playlistModel.findOne(
  1164. { createdBy: session.userId, displayName: "Liked Songs" },
  1165. (err, playlist) => {
  1166. if (err) return next(err);
  1167. if (!playlist) return next("'Liked Songs' playlist does not exist.");
  1168. let isLiked = false;
  1169. Object.values(playlist.songs).forEach(song => {
  1170. // song is found in 'liked songs' playlist
  1171. if (song.youtubeId === youtubeId) isLiked = true;
  1172. });
  1173. return next(null, isLiked);
  1174. }
  1175. ),
  1176. (isLiked, next) =>
  1177. playlistModel.findOne(
  1178. { createdBy: session.userId, displayName: "Disliked Songs" },
  1179. (err, playlist) => {
  1180. if (err) return next(err);
  1181. if (!playlist) return next("'Disliked Songs' playlist does not exist.");
  1182. const ratings = { isLiked, isDisliked: false };
  1183. Object.values(playlist.songs).forEach(song => {
  1184. // song is found in 'disliked songs' playlist
  1185. if (song.youtubeId === youtubeId) ratings.isDisliked = true;
  1186. });
  1187. return next(null, ratings);
  1188. }
  1189. )
  1190. ],
  1191. async (err, ratings) => {
  1192. if (err) {
  1193. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1194. this.log(
  1195. "ERROR",
  1196. "SONGS_GET_OWN_RATINGS",
  1197. `User "${session.userId}" failed to get ratings for ${youtubeId}. "${err}"`
  1198. );
  1199. return cb({ status: "error", message: err });
  1200. }
  1201. const { isLiked, isDisliked } = ratings;
  1202. return cb({
  1203. status: "success",
  1204. data: {
  1205. youtubeId,
  1206. liked: isLiked,
  1207. disliked: isDisliked
  1208. }
  1209. });
  1210. }
  1211. );
  1212. })
  1213. };