songs.js 43 KB

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