songs.js 41 KB

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