songs.js 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126
  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}`, "edit-songs"],
  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}`, "edit-songs"],
  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. DBModule.runJob(
  179. "GET_DATA",
  180. {
  181. page,
  182. pageSize,
  183. properties,
  184. sort,
  185. queries,
  186. operator,
  187. modelName: "song",
  188. blacklistedProperties: [],
  189. specialProperties: {
  190. requestedBy: [
  191. {
  192. $addFields: {
  193. requestedByOID: {
  194. $convert: {
  195. input: "$requestedBy",
  196. to: "objectId",
  197. onError: "unknown",
  198. onNull: "unknown"
  199. }
  200. }
  201. }
  202. },
  203. {
  204. $lookup: {
  205. from: "users",
  206. localField: "requestedByOID",
  207. foreignField: "_id",
  208. as: "requestedByUser"
  209. }
  210. },
  211. {
  212. $addFields: {
  213. requestedByUsername: {
  214. $ifNull: ["$requestedByUser.username", "unknown"]
  215. }
  216. }
  217. },
  218. {
  219. $project: {
  220. requestedByOID: 0,
  221. requestedByUser: 0
  222. }
  223. }
  224. ],
  225. verifiedBy: [
  226. {
  227. $addFields: {
  228. verifiedByOID: {
  229. $convert: {
  230. input: "$verifiedBy",
  231. to: "objectId",
  232. onError: "unknown",
  233. onNull: "unknown"
  234. }
  235. }
  236. }
  237. },
  238. {
  239. $lookup: {
  240. from: "users",
  241. localField: "verifiedByOID",
  242. foreignField: "_id",
  243. as: "verifiedByUser"
  244. }
  245. },
  246. {
  247. $unwind: {
  248. path: "$verifiedByUser",
  249. preserveNullAndEmptyArrays: true
  250. }
  251. },
  252. {
  253. $addFields: {
  254. verifiedByUsername: {
  255. $ifNull: ["$verifiedByUser.username", "unknown"]
  256. }
  257. }
  258. },
  259. {
  260. $project: {
  261. verifiedByOID: 0,
  262. verifiedByUser: 0
  263. }
  264. }
  265. ]
  266. },
  267. specialQueries: {
  268. requestedBy: newQuery => ({
  269. $or: [newQuery, { requestedByUsername: newQuery.requestedBy }]
  270. }),
  271. verifiedBy: newQuery => ({
  272. $or: [newQuery, { verifiedByUsername: newQuery.verifiedBy }]
  273. })
  274. }
  275. },
  276. this
  277. )
  278. .then(response => {
  279. next(null, response);
  280. })
  281. .catch(err => {
  282. next(err);
  283. });
  284. }
  285. ],
  286. async (err, response) => {
  287. if (err) {
  288. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  289. this.log("ERROR", "SONGS_GET_DATA", `Failed to get data from songs. "${err}"`);
  290. return cb({ status: "error", message: err });
  291. }
  292. this.log("SUCCESS", "SONGS_GET_DATA", `Got data from songs successfully.`);
  293. return cb({ status: "success", message: "Successfully got data from songs.", data: response });
  294. }
  295. );
  296. }),
  297. /**
  298. * Updates all songs
  299. *
  300. * @param {object} session - the session object automatically added by the websocket
  301. * @param cb
  302. */
  303. updateAll: isAdminRequired(async function updateAll(session, cb) {
  304. async.waterfall(
  305. [
  306. next => {
  307. SongsModule.runJob("UPDATE_ALL_SONGS", {}, this)
  308. .then(() => {
  309. next();
  310. })
  311. .catch(err => {
  312. next(err);
  313. });
  314. }
  315. ],
  316. async err => {
  317. if (err) {
  318. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  319. this.log("ERROR", "SONGS_UPDATE_ALL", `Failed to update all songs. "${err}"`);
  320. return cb({ status: "error", message: err });
  321. }
  322. this.log("SUCCESS", "SONGS_UPDATE_ALL", `Updated all songs successfully.`);
  323. return cb({ status: "success", message: "Successfully updated all songs." });
  324. }
  325. );
  326. }),
  327. /**
  328. * Recalculates all song ratings
  329. *
  330. * @param {object} session - the session object automatically added by the websocket
  331. * @param cb
  332. */
  333. recalculateAllRatings: isAdminRequired(async function recalculateAllRatings(session, cb) {
  334. async.waterfall(
  335. [
  336. next => {
  337. SongsModule.runJob("RECALCULATE_ALL_SONG_RATINGS", {}, this)
  338. .then(() => {
  339. next();
  340. })
  341. .catch(err => {
  342. next(err);
  343. });
  344. }
  345. ],
  346. async err => {
  347. if (err) {
  348. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  349. this.log(
  350. "ERROR",
  351. "SONGS_RECALCULATE_ALL_RATINGS",
  352. `Failed to recalculate all song ratings. "${err}"`
  353. );
  354. return cb({ status: "error", message: err });
  355. }
  356. this.log("SUCCESS", "SONGS_RECALCULATE_ALL_RATINGS", `Recalculated all song ratings successfully.`);
  357. return cb({ status: "success", message: "Successfully recalculated all song ratings." });
  358. }
  359. );
  360. }),
  361. /**
  362. * Gets a song from the Musare song id
  363. *
  364. * @param {object} session - the session object automatically added by the websocket
  365. * @param {string} songId - the song id
  366. * @param {Function} cb
  367. */
  368. getSongFromSongId: isAdminRequired(function getSongFromSongId(session, songId, cb) {
  369. async.waterfall(
  370. [
  371. next => {
  372. SongsModule.runJob("GET_SONG", { songId }, this)
  373. .then(response => next(null, response.song))
  374. .catch(err => next(err));
  375. }
  376. ],
  377. async (err, song) => {
  378. if (err) {
  379. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  380. this.log("ERROR", "SONGS_GET_SONG_FROM_MUSARE_ID", `Failed to get song ${songId}. "${err}"`);
  381. return cb({ status: "error", message: err });
  382. }
  383. this.log("SUCCESS", "SONGS_GET_SONG_FROM_MUSARE_ID", `Got song ${songId} successfully.`);
  384. return cb({ status: "success", data: { song } });
  385. }
  386. );
  387. }),
  388. /**
  389. * Gets multiple songs from the Musare song ids
  390. * At this time only used in EditSongs
  391. *
  392. * @param {object} session - the session object automatically added by the websocket
  393. * @param {Array} songIds - the song ids
  394. * @param {Function} cb
  395. */
  396. getSongsFromSongIds: isAdminRequired(function getSongFromSongId(session, songIds, cb) {
  397. async.waterfall(
  398. [
  399. next => {
  400. SongsModule.runJob(
  401. "GET_SONGS",
  402. {
  403. songIds,
  404. properties: ["youtubeId", "title", "artists", "thumbnail", "duration", "verified", "_id"]
  405. },
  406. this
  407. )
  408. .then(response => next(null, response.songs))
  409. .catch(err => next(err));
  410. }
  411. ],
  412. async (err, songs) => {
  413. if (err) {
  414. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  415. this.log("ERROR", "SONGS_GET_SONGS_FROM_MUSARE_IDS", `Failed to get songs. "${err}"`);
  416. return cb({ status: "error", message: err });
  417. }
  418. this.log("SUCCESS", "SONGS_GET_SONGS_FROM_MUSARE_IDS", `Got songs successfully.`);
  419. return cb({ status: "success", data: { songs } });
  420. }
  421. );
  422. }),
  423. /**
  424. * Creates a song
  425. *
  426. * @param {object} session - the session object automatically added by the websocket
  427. * @param {object} newSong - the song object
  428. * @param {Function} cb
  429. */
  430. create: isAdminRequired(async function create(session, newSong, cb) {
  431. async.waterfall(
  432. [
  433. next => {
  434. SongsModule.runJob("CREATE_SONG", { song: newSong, userId: session.userId }, this)
  435. .then(song => next(null, song))
  436. .catch(next);
  437. }
  438. ],
  439. async (err, song) => {
  440. if (err) {
  441. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  442. this.log("ERROR", "SONGS_CREATE", `Failed to create song "${JSON.stringify(newSong)}". "${err}"`);
  443. return cb({ status: "error", message: err });
  444. }
  445. this.log("SUCCESS", "SONGS_CREATE", `Successfully created song "${song._id}".`);
  446. return cb({
  447. status: "success",
  448. message: "Song has been successfully created",
  449. data: { song }
  450. });
  451. }
  452. );
  453. }),
  454. /**
  455. * Updates a song
  456. *
  457. * @param {object} session - the session object automatically added by the websocket
  458. * @param {string} songId - the song id
  459. * @param {object} song - the updated song object
  460. * @param {Function} cb
  461. */
  462. update: isAdminRequired(async function update(session, songId, song, cb) {
  463. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  464. let existingSong = null;
  465. async.waterfall(
  466. [
  467. next => {
  468. songModel.findOne({ _id: songId }, next);
  469. },
  470. (_existingSong, next) => {
  471. existingSong = _existingSong;
  472. // Verify the song
  473. if (existingSong.verified === false && song.verified === true) {
  474. song.verifiedBy = session.userId;
  475. song.verifiedAt = Date.now();
  476. }
  477. // Unverify the song
  478. else if (existingSong.verified === true && song.verified === false) {
  479. song.verifiedBy = null;
  480. song.verifiedAt = null;
  481. }
  482. next();
  483. },
  484. next => {
  485. songModel.updateOne({ _id: songId }, song, { runValidators: true }, next);
  486. },
  487. (res, next) => {
  488. SongsModule.runJob("UPDATE_SONG", { songId }, this)
  489. .then(song => {
  490. existingSong.genres
  491. .concat(song.genres)
  492. .filter((value, index, self) => self.indexOf(value) === index)
  493. .forEach(genre => {
  494. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", {
  495. genre,
  496. createPlaylist: song.verified
  497. })
  498. .then(() => {})
  499. .catch(() => {});
  500. });
  501. next(null, song);
  502. })
  503. .catch(next);
  504. }
  505. ],
  506. async (err, song) => {
  507. if (err) {
  508. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  509. this.log("ERROR", "SONGS_UPDATE", `Failed to update song "${songId}". "${err}"`);
  510. return cb({ status: "error", message: err });
  511. }
  512. this.log("SUCCESS", "SONGS_UPDATE", `Successfully updated song "${songId}".`);
  513. return cb({
  514. status: "success",
  515. message: "Song has been successfully updated",
  516. data: { song }
  517. });
  518. }
  519. );
  520. }),
  521. /**
  522. * Removes a song
  523. *
  524. * @param session
  525. * @param songId - the song id
  526. * @param cb
  527. */
  528. remove: isAdminRequired(async function remove(session, songId, cb) {
  529. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  530. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  531. async.waterfall(
  532. [
  533. next => {
  534. songModel.findOne({ _id: songId }, next);
  535. },
  536. (song, next) => {
  537. PlaylistsModule.runJob("GET_PLAYLISTS_WITH_SONG", { songId }, this)
  538. .then(res => {
  539. async.eachLimit(
  540. res.playlists,
  541. 1,
  542. (playlist, next) => {
  543. WSModule.runJob(
  544. "RUN_ACTION2",
  545. {
  546. session,
  547. namespace: "playlists",
  548. action: "removeSongFromPlaylist",
  549. args: [song.youtubeId, playlist._id]
  550. },
  551. this
  552. )
  553. .then(res => {
  554. if (res.status === "error") next(res.message);
  555. else next();
  556. })
  557. .catch(err => {
  558. next(err);
  559. });
  560. },
  561. err => {
  562. if (err) next(err);
  563. else next(null, song);
  564. }
  565. );
  566. })
  567. .catch(err => next(err));
  568. },
  569. (song, next) => {
  570. stationModel.find({ "queue._id": songId }, (err, stations) => {
  571. if (err) next(err);
  572. else {
  573. async.eachLimit(
  574. stations,
  575. 1,
  576. (station, next) => {
  577. WSModule.runJob(
  578. "RUN_ACTION2",
  579. {
  580. session,
  581. namespace: "stations",
  582. action: "removeFromQueue",
  583. args: [station._id, song.youtubeId]
  584. },
  585. this
  586. )
  587. .then(res => {
  588. if (
  589. res.status === "error" &&
  590. res.message !== "Station not found" &&
  591. res.message !== "Song is not currently in the queue."
  592. )
  593. next(res.message);
  594. else next();
  595. })
  596. .catch(err => {
  597. next(err);
  598. });
  599. },
  600. err => {
  601. if (err) next(err);
  602. else next();
  603. }
  604. );
  605. }
  606. });
  607. },
  608. next => {
  609. stationModel.find({ "currentSong._id": songId }, (err, stations) => {
  610. if (err) next(err);
  611. else {
  612. async.eachLimit(
  613. stations,
  614. 1,
  615. (station, next) => {
  616. StationsModule.runJob(
  617. "SKIP_STATION",
  618. { stationId: station._id, natural: false },
  619. this
  620. )
  621. .then(() => {
  622. next();
  623. })
  624. .catch(err => {
  625. if (err.message === "Station not found.") next();
  626. else next(err);
  627. });
  628. },
  629. err => {
  630. if (err) next(err);
  631. else next();
  632. }
  633. );
  634. }
  635. });
  636. },
  637. next => {
  638. songModel.deleteOne({ _id: songId }, err => {
  639. if (err) next(err);
  640. else next();
  641. });
  642. },
  643. next => {
  644. CacheModule.runJob("HDEL", { table: "songs", key: songId }, this)
  645. .then(() => {
  646. next();
  647. })
  648. .catch(next);
  649. }
  650. ],
  651. async err => {
  652. if (err) {
  653. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  654. this.log("ERROR", "SONGS_REMOVE", `Failed to remove song "${songId}". "${err}"`);
  655. return cb({ status: "error", message: err });
  656. }
  657. this.log("SUCCESS", "SONGS_REMOVE", `Successfully removed song "${songId}".`);
  658. CacheModule.runJob("PUB", {
  659. channel: "song.removed",
  660. value: { songId }
  661. });
  662. return cb({
  663. status: "success",
  664. message: "Song has been successfully removed"
  665. });
  666. }
  667. );
  668. }),
  669. /**
  670. * Removes many songs
  671. *
  672. * @param session
  673. * @param songIds - array of song ids
  674. * @param cb
  675. */
  676. removeMany: isAdminRequired(async function remove(session, songIds, cb) {
  677. const successful = [];
  678. const failed = [];
  679. async.waterfall(
  680. [
  681. next => {
  682. async.eachLimit(
  683. songIds,
  684. 1,
  685. (songId, next) => {
  686. WSModule.runJob(
  687. "RUN_ACTION2",
  688. {
  689. session,
  690. namespace: "songs",
  691. action: "remove",
  692. args: [songId]
  693. },
  694. this
  695. )
  696. .then(res => {
  697. if (res.status === "error") failed.push(songId);
  698. else successful.push(songId);
  699. next();
  700. })
  701. .catch(err => {
  702. next(err);
  703. });
  704. },
  705. err => {
  706. if (err) next(err);
  707. else next();
  708. }
  709. );
  710. }
  711. ],
  712. async err => {
  713. if (err) {
  714. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  715. this.log("ERROR", "SONGS_REMOVE_MANY", `Failed to remove songs "${failed.join(", ")}". "${err}"`);
  716. return cb({ status: "error", message: err });
  717. }
  718. let message = "";
  719. if (successful.length === 1) message += `1 song has been successfully removed`;
  720. else message += `${successful.length} songs have been successfully removed`;
  721. if (failed.length > 0) {
  722. this.log("ERROR", "SONGS_REMOVE_MANY", `Failed to remove songs "${failed.join(", ")}". "${err}"`);
  723. if (failed.length === 1) message += `, failed to remove 1 song`;
  724. else message += `, failed to remove ${failed.length} songs`;
  725. }
  726. this.log("SUCCESS", "SONGS_REMOVE_MANY", `${message} "${successful.join(", ")}"`);
  727. return cb({
  728. status: "success",
  729. message
  730. });
  731. }
  732. );
  733. }),
  734. /**
  735. * Searches through official songs
  736. *
  737. * @param {object} session - the session object automatically added by the websocket
  738. * @param {string} query - the query
  739. * @param {string} page - the page
  740. * @param {Function} cb - gets called with the result
  741. */
  742. searchOfficial: isLoginRequired(async function searchOfficial(session, query, page, cb) {
  743. async.waterfall(
  744. [
  745. next => {
  746. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  747. else next();
  748. },
  749. next => {
  750. SongsModule.runJob("SEARCH", {
  751. query,
  752. includeVerified: true,
  753. trimmed: true,
  754. page
  755. })
  756. .then(response => {
  757. next(null, response);
  758. })
  759. .catch(err => {
  760. next(err);
  761. });
  762. }
  763. ],
  764. async (err, data) => {
  765. if (err) {
  766. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  767. this.log("ERROR", "SONGS_SEARCH_OFFICIAL", `Searching songs failed. "${err}"`);
  768. return cb({ status: "error", message: err });
  769. }
  770. this.log("SUCCESS", "SONGS_SEARCH_OFFICIAL", "Searching songs successful.");
  771. return cb({ status: "success", data });
  772. }
  773. );
  774. }),
  775. /**
  776. * Requests a song
  777. *
  778. * @param {object} session - the session object automatically added by the websocket
  779. * @param {string} youtubeId - the youtube id of the song that gets requested
  780. * @param {string} returnSong - returns the simple song
  781. * @param {Function} cb - gets called with the result
  782. */
  783. request: isLoginRequired(async function add(session, youtubeId, returnSong, cb) {
  784. SongsModule.runJob("REQUEST_SONG", { youtubeId, userId: session.userId }, this)
  785. .then(response => {
  786. this.log(
  787. "SUCCESS",
  788. "SONGS_REQUEST",
  789. `User "${session.userId}" successfully requested song "${youtubeId}".`
  790. );
  791. return cb({
  792. status: "success",
  793. message: "Successfully requested that song",
  794. song: returnSong ? response.song : null
  795. });
  796. })
  797. .catch(async _err => {
  798. const err = await UtilsModule.runJob("GET_ERROR", { error: _err }, this);
  799. this.log(
  800. "ERROR",
  801. "SONGS_REQUEST",
  802. `Requesting song "${youtubeId}" failed for user ${session.userId}. "${err}"`
  803. );
  804. return cb({ status: "error", message: err, song: returnSong && _err.data ? _err.data.song : null });
  805. });
  806. }),
  807. /**
  808. * Verifies a song
  809. *
  810. * @param session
  811. * @param songId - the song id
  812. * @param cb
  813. */
  814. verify: isAdminRequired(async function add(session, songId, cb) {
  815. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  816. async.waterfall(
  817. [
  818. next => {
  819. SongModel.findOne({ _id: songId }, next);
  820. },
  821. (song, next) => {
  822. if (!song) return next("This song is not in the database.");
  823. return next(null, song);
  824. },
  825. (song, next) => {
  826. const oldStatus = false;
  827. song.verifiedBy = session.userId;
  828. song.verifiedAt = Date.now();
  829. song.verified = true;
  830. song.save(err => next(err, song, oldStatus));
  831. },
  832. (song, oldStatus, next) => {
  833. song.genres.forEach(genre => {
  834. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: true })
  835. .then(() => {})
  836. .catch(() => {});
  837. });
  838. SongsModule.runJob("UPDATE_SONG", { songId: song._id, oldStatus });
  839. next(null, song, oldStatus);
  840. }
  841. ],
  842. async err => {
  843. if (err) {
  844. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  845. this.log("ERROR", "SONGS_VERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  846. return cb({ status: "error", message: err });
  847. }
  848. this.log("SUCCESS", "SONGS_VERIFY", `User "${session.userId}" successfully verified song "${songId}".`);
  849. return cb({
  850. status: "success",
  851. message: "Song has been verified successfully."
  852. });
  853. }
  854. );
  855. // TODO Check if video is in queue and Add the song to the appropriate stations
  856. }),
  857. /**
  858. * Verify many songs
  859. *
  860. * @param session
  861. * @param songIds - array of song ids
  862. * @param cb
  863. */
  864. verifyMany: isAdminRequired(async function verifyMany(session, songIds, cb) {
  865. const successful = [];
  866. const failed = [];
  867. async.waterfall(
  868. [
  869. next => {
  870. async.eachLimit(
  871. songIds,
  872. 1,
  873. (songId, next) => {
  874. WSModule.runJob(
  875. "RUN_ACTION2",
  876. {
  877. session,
  878. namespace: "songs",
  879. action: "verify",
  880. args: [songId]
  881. },
  882. this
  883. )
  884. .then(res => {
  885. if (res.status === "error") failed.push(songId);
  886. else successful.push(songId);
  887. next();
  888. })
  889. .catch(err => {
  890. next(err);
  891. });
  892. },
  893. err => {
  894. if (err) next(err);
  895. else next();
  896. }
  897. );
  898. }
  899. ],
  900. async err => {
  901. if (err) {
  902. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  903. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  904. return cb({ status: "error", message: err });
  905. }
  906. let message = "";
  907. if (successful.length === 1) message += `1 song has been successfully verified`;
  908. else message += `${successful.length} songs have been successfully verified`;
  909. if (failed.length > 0) {
  910. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  911. if (failed.length === 1) message += `, failed to verify 1 song`;
  912. else message += `, failed to verify ${failed.length} songs`;
  913. }
  914. this.log("SUCCESS", "SONGS_VERIFY_MANY", `${message} "${successful.join(", ")}"`);
  915. return cb({
  916. status: "success",
  917. message
  918. });
  919. }
  920. );
  921. }),
  922. /**
  923. * Un-verifies a song
  924. *
  925. * @param session
  926. * @param songId - the song id
  927. * @param cb
  928. */
  929. unverify: isAdminRequired(async function add(session, songId, cb) {
  930. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  931. async.waterfall(
  932. [
  933. next => {
  934. SongModel.findOne({ _id: songId }, next);
  935. },
  936. (song, next) => {
  937. if (!song) return next("This song is not in the database.");
  938. return next(null, song);
  939. },
  940. (song, next) => {
  941. song.verified = false;
  942. song.verifiedBy = null;
  943. song.verifiedAt = null;
  944. song.save(err => {
  945. next(err, song);
  946. });
  947. },
  948. (song, next) => {
  949. song.genres.forEach(genre => {
  950. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: false })
  951. .then(() => {})
  952. .catch(() => {});
  953. });
  954. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: true });
  955. next(null);
  956. }
  957. ],
  958. async err => {
  959. if (err) {
  960. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  961. this.log("ERROR", "SONGS_UNVERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  962. return cb({ status: "error", message: err });
  963. }
  964. this.log(
  965. "SUCCESS",
  966. "SONGS_UNVERIFY",
  967. `User "${session.userId}" successfully unverified song "${songId}".`
  968. );
  969. return cb({
  970. status: "success",
  971. message: "Song has been unverified successfully."
  972. });
  973. }
  974. );
  975. // TODO Check if video is in queue and Add the song to the appropriate stations
  976. }),
  977. /**
  978. * Unverify many songs
  979. *
  980. * @param session
  981. * @param songIds - array of song ids
  982. * @param cb
  983. */
  984. unverifyMany: isAdminRequired(async function unverifyMany(session, songIds, cb) {
  985. const successful = [];
  986. const failed = [];
  987. async.waterfall(
  988. [
  989. next => {
  990. async.eachLimit(
  991. songIds,
  992. 1,
  993. (songId, next) => {
  994. WSModule.runJob(
  995. "RUN_ACTION2",
  996. {
  997. session,
  998. namespace: "songs",
  999. action: "unverify",
  1000. args: [songId]
  1001. },
  1002. this
  1003. )
  1004. .then(res => {
  1005. if (res.status === "error") failed.push(songId);
  1006. else successful.push(songId);
  1007. next();
  1008. })
  1009. .catch(err => {
  1010. next(err);
  1011. });
  1012. },
  1013. err => {
  1014. if (err) next(err);
  1015. else next();
  1016. }
  1017. );
  1018. }
  1019. ],
  1020. async err => {
  1021. if (err) {
  1022. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1023. this.log(
  1024. "ERROR",
  1025. "SONGS_UNVERIFY_MANY",
  1026. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  1027. );
  1028. return cb({ status: "error", message: err });
  1029. }
  1030. let message = "";
  1031. if (successful.length === 1) message += `1 song has been successfully unverified`;
  1032. else message += `${successful.length} songs have been successfully unverified`;
  1033. if (failed.length > 0) {
  1034. this.log(
  1035. "ERROR",
  1036. "SONGS_UNVERIFY_MANY",
  1037. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  1038. );
  1039. if (failed.length === 1) message += `, failed to unverify 1 song`;
  1040. else message += `, failed to unverify ${failed.length} songs`;
  1041. }
  1042. this.log("SUCCESS", "SONGS_UNVERIFY_MANY", `${message} "${successful.join(", ")}"`);
  1043. return cb({
  1044. status: "success",
  1045. message
  1046. });
  1047. }
  1048. );
  1049. }),
  1050. /**
  1051. * Requests a set of songs
  1052. *
  1053. * @param {object} session - the session object automatically added by the websocket
  1054. * @param {string} url - the url of the the YouTube playlist
  1055. * @param {boolean} musicOnly - whether to only get music from the playlist
  1056. * @param {Function} cb - gets called with the result
  1057. */
  1058. requestSet: isLoginRequired(function requestSet(session, url, musicOnly, returnSongs, cb) {
  1059. async.waterfall(
  1060. [
  1061. next => {
  1062. YouTubeModule.runJob(
  1063. "GET_PLAYLIST",
  1064. {
  1065. url,
  1066. musicOnly
  1067. },
  1068. this
  1069. )
  1070. .then(res => {
  1071. next(null, res.songs);
  1072. })
  1073. .catch(next);
  1074. },
  1075. (youtubeIds, next) => {
  1076. let successful = 0;
  1077. let songs = {};
  1078. let failed = 0;
  1079. let alreadyInDatabase = 0;
  1080. if (youtubeIds.length === 0) next();
  1081. async.eachOfLimit(
  1082. youtubeIds,
  1083. 1,
  1084. (youtubeId, index, next) => {
  1085. WSModule.runJob(
  1086. "RUN_ACTION2",
  1087. {
  1088. session,
  1089. namespace: "songs",
  1090. action: "request",
  1091. args: [youtubeId, returnSongs]
  1092. },
  1093. this
  1094. )
  1095. .then(res => {
  1096. if (res.status === "success") successful += 1;
  1097. else failed += 1;
  1098. if (res.message === "This song is already in the database.") alreadyInDatabase += 1;
  1099. if (res.song) songs[index] = res.song;
  1100. })
  1101. .catch(() => {
  1102. failed += 1;
  1103. })
  1104. .finally(() => {
  1105. next();
  1106. });
  1107. },
  1108. () => {
  1109. if (returnSongs)
  1110. songs = Object.keys(songs)
  1111. .sort()
  1112. .map(key => songs[key]);
  1113. next(null, { successful, failed, alreadyInDatabase, songs });
  1114. }
  1115. );
  1116. }
  1117. ],
  1118. async (err, response) => {
  1119. if (err) {
  1120. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1121. this.log(
  1122. "ERROR",
  1123. "REQUEST_SET",
  1124. `Importing a YouTube playlist to be requested failed for user "${session.userId}". "${err}"`
  1125. );
  1126. return cb({ status: "error", message: err });
  1127. }
  1128. this.log(
  1129. "SUCCESS",
  1130. "REQUEST_SET",
  1131. `Successfully imported a YouTube playlist to be requested for user "${session.userId}".`
  1132. );
  1133. return cb({
  1134. status: "success",
  1135. message: `Playlist is done importing. ${response.successful} were added succesfully, ${response.failed} failed (${response.alreadyInDatabase} were already in database)`,
  1136. songs: returnSongs ? response.songs : null
  1137. });
  1138. }
  1139. );
  1140. }),
  1141. /**
  1142. * Likes a song
  1143. *
  1144. * @param session
  1145. * @param youtubeId - the youtube id
  1146. * @param cb
  1147. */
  1148. like: isLoginRequired(async function like(session, youtubeId, cb) {
  1149. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1150. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1151. async.waterfall(
  1152. [
  1153. next => songModel.findOne({ youtubeId }, next),
  1154. (song, next) => {
  1155. if (!song) return next("No song found with that id.");
  1156. return next(null, song);
  1157. },
  1158. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1159. (song, user, next) => {
  1160. if (!user) return next("User does not exist.");
  1161. return this.module
  1162. .runJob(
  1163. "RUN_ACTION2",
  1164. {
  1165. session,
  1166. namespace: "playlists",
  1167. action: "removeSongFromPlaylist",
  1168. args: [youtubeId, user.dislikedSongsPlaylist]
  1169. },
  1170. this
  1171. )
  1172. .then(res => {
  1173. if (res.status === "error" && res.message !== "Song wasn't in playlist.")
  1174. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1175. return next(null, song, user.likedSongsPlaylist);
  1176. })
  1177. .catch(err => next(err));
  1178. },
  1179. (song, likedSongsPlaylist, next) =>
  1180. this.module
  1181. .runJob(
  1182. "RUN_ACTION2",
  1183. {
  1184. session,
  1185. namespace: "playlists",
  1186. action: "addSongToPlaylist",
  1187. args: [false, youtubeId, likedSongsPlaylist]
  1188. },
  1189. this
  1190. )
  1191. .then(res => {
  1192. if (res.status === "error") {
  1193. if (res.message === "That song is already in the playlist")
  1194. return next("You have already liked this song.");
  1195. return next("Unable to add song to the 'Liked Songs' playlist.");
  1196. }
  1197. return next(null, song);
  1198. })
  1199. .catch(err => next(err)),
  1200. (song, next) => {
  1201. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1202. .then(ratings => next(null, song, ratings))
  1203. .catch(err => next(err));
  1204. }
  1205. ],
  1206. async (err, song, ratings) => {
  1207. if (err) {
  1208. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1209. this.log(
  1210. "ERROR",
  1211. "SONGS_LIKE",
  1212. `User "${session.userId}" failed to like song ${youtubeId}. "${err}"`
  1213. );
  1214. return cb({ status: "error", message: err });
  1215. }
  1216. const { likes, dislikes } = ratings;
  1217. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1218. CacheModule.runJob("PUB", {
  1219. channel: "song.like",
  1220. value: JSON.stringify({
  1221. youtubeId,
  1222. userId: session.userId,
  1223. likes,
  1224. dislikes
  1225. })
  1226. });
  1227. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1228. userId: session.userId,
  1229. type: "song__like",
  1230. payload: {
  1231. message: `Liked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  1232. youtubeId,
  1233. thumbnail: song.thumbnail
  1234. }
  1235. });
  1236. return cb({
  1237. status: "success",
  1238. message: "You have successfully liked this song."
  1239. });
  1240. }
  1241. );
  1242. }),
  1243. /**
  1244. * Dislikes a song
  1245. *
  1246. * @param session
  1247. * @param youtubeId - the youtube id
  1248. * @param cb
  1249. */
  1250. dislike: isLoginRequired(async function dislike(session, youtubeId, cb) {
  1251. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1252. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1253. async.waterfall(
  1254. [
  1255. next => {
  1256. songModel.findOne({ youtubeId }, next);
  1257. },
  1258. (song, next) => {
  1259. if (!song) return next("No song found with that id.");
  1260. return next(null, song);
  1261. },
  1262. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1263. (song, user, next) => {
  1264. if (!user) return next("User does not exist.");
  1265. return this.module
  1266. .runJob(
  1267. "RUN_ACTION2",
  1268. {
  1269. session,
  1270. namespace: "playlists",
  1271. action: "removeSongFromPlaylist",
  1272. args: [youtubeId, user.likedSongsPlaylist]
  1273. },
  1274. this
  1275. )
  1276. .then(res => {
  1277. if (res.status === "error" && res.message !== "Song wasn't in playlist.")
  1278. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1279. return next(null, song, user.dislikedSongsPlaylist);
  1280. })
  1281. .catch(err => next(err));
  1282. },
  1283. (song, dislikedSongsPlaylist, next) =>
  1284. this.module
  1285. .runJob(
  1286. "RUN_ACTION2",
  1287. {
  1288. session,
  1289. namespace: "playlists",
  1290. action: "addSongToPlaylist",
  1291. args: [false, youtubeId, dislikedSongsPlaylist]
  1292. },
  1293. this
  1294. )
  1295. .then(res => {
  1296. if (res.status === "error") {
  1297. if (res.message === "That song is already in the playlist")
  1298. return next("You have already disliked this song.");
  1299. return next("Unable to add song to the 'Disliked Songs' playlist.");
  1300. }
  1301. return next(null, song);
  1302. })
  1303. .catch(err => next(err)),
  1304. (song, next) => {
  1305. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1306. .then(ratings => next(null, song, ratings))
  1307. .catch(err => next(err));
  1308. }
  1309. ],
  1310. async (err, song, ratings) => {
  1311. if (err) {
  1312. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1313. this.log(
  1314. "ERROR",
  1315. "SONGS_DISLIKE",
  1316. `User "${session.userId}" failed to dislike song ${youtubeId}. "${err}"`
  1317. );
  1318. return cb({ status: "error", message: err });
  1319. }
  1320. const { likes, dislikes } = ratings;
  1321. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1322. CacheModule.runJob("PUB", {
  1323. channel: "song.dislike",
  1324. value: JSON.stringify({
  1325. youtubeId,
  1326. userId: session.userId,
  1327. likes,
  1328. dislikes
  1329. })
  1330. });
  1331. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1332. userId: session.userId,
  1333. type: "song__dislike",
  1334. payload: {
  1335. message: `Disliked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  1336. youtubeId,
  1337. thumbnail: song.thumbnail
  1338. }
  1339. });
  1340. return cb({
  1341. status: "success",
  1342. message: "You have successfully disliked this song."
  1343. });
  1344. }
  1345. );
  1346. }),
  1347. /**
  1348. * Undislikes a song
  1349. *
  1350. * @param session
  1351. * @param youtubeId - the youtube id
  1352. * @param cb
  1353. */
  1354. undislike: isLoginRequired(async function undislike(session, youtubeId, cb) {
  1355. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1356. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1357. async.waterfall(
  1358. [
  1359. next => {
  1360. songModel.findOne({ youtubeId }, next);
  1361. },
  1362. (song, next) => {
  1363. if (!song) return next("No song found with that id.");
  1364. return next(null, song);
  1365. },
  1366. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1367. (song, user, next) => {
  1368. if (!user) return next("User does not exist.");
  1369. return this.module
  1370. .runJob(
  1371. "RUN_ACTION2",
  1372. {
  1373. session,
  1374. namespace: "playlists",
  1375. action: "removeSongFromPlaylist",
  1376. args: [youtubeId, user.dislikedSongsPlaylist]
  1377. },
  1378. this
  1379. )
  1380. .then(res => {
  1381. if (res.status === "error")
  1382. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1383. return next(null, song, user.likedSongsPlaylist);
  1384. })
  1385. .catch(err => next(err));
  1386. },
  1387. (song, likedSongsPlaylist, next) => {
  1388. this.module
  1389. .runJob(
  1390. "RUN_ACTION2",
  1391. {
  1392. session,
  1393. namespace: "playlists",
  1394. action: "removeSongFromPlaylist",
  1395. args: [youtubeId, likedSongsPlaylist]
  1396. },
  1397. this
  1398. )
  1399. .then(res => {
  1400. if (res.status === "error" && res.message !== "Song wasn't in playlist.")
  1401. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1402. return next(null, song);
  1403. })
  1404. .catch(err => next(err));
  1405. },
  1406. (song, next) => {
  1407. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1408. .then(ratings => next(null, song, ratings))
  1409. .catch(err => next(err));
  1410. }
  1411. ],
  1412. async (err, song, ratings) => {
  1413. if (err) {
  1414. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1415. this.log(
  1416. "ERROR",
  1417. "SONGS_UNDISLIKE",
  1418. `User "${session.userId}" failed to undislike song ${youtubeId}. "${err}"`
  1419. );
  1420. return cb({ status: "error", message: err });
  1421. }
  1422. const { likes, dislikes } = ratings;
  1423. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1424. CacheModule.runJob("PUB", {
  1425. channel: "song.undislike",
  1426. value: JSON.stringify({
  1427. youtubeId,
  1428. userId: session.userId,
  1429. likes,
  1430. dislikes
  1431. })
  1432. });
  1433. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1434. userId: session.userId,
  1435. type: "song__undislike",
  1436. payload: {
  1437. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  1438. ", "
  1439. )}</youtubeId> from your Disliked Songs`,
  1440. youtubeId,
  1441. thumbnail: song.thumbnail
  1442. }
  1443. });
  1444. return cb({
  1445. status: "success",
  1446. message: "You have successfully undisliked this song."
  1447. });
  1448. }
  1449. );
  1450. }),
  1451. /**
  1452. * Unlikes a song
  1453. *
  1454. * @param session
  1455. * @param youtubeId - the youtube id
  1456. * @param cb
  1457. */
  1458. unlike: isLoginRequired(async function unlike(session, youtubeId, cb) {
  1459. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1460. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1461. async.waterfall(
  1462. [
  1463. next => {
  1464. songModel.findOne({ youtubeId }, next);
  1465. },
  1466. (song, next) => {
  1467. if (!song) return next("No song found with that id.");
  1468. return next(null, song);
  1469. },
  1470. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1471. (song, user, next) => {
  1472. if (!user) return next("User does not exist.");
  1473. return this.module
  1474. .runJob(
  1475. "RUN_ACTION2",
  1476. {
  1477. session,
  1478. namespace: "playlists",
  1479. action: "removeSongFromPlaylist",
  1480. args: [youtubeId, user.dislikedSongsPlaylist]
  1481. },
  1482. this
  1483. )
  1484. .then(res => {
  1485. if (res.status === "error" && res.message !== "Song wasn't in playlist.")
  1486. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1487. return next(null, song, user.likedSongsPlaylist);
  1488. })
  1489. .catch(err => next(err));
  1490. },
  1491. (song, likedSongsPlaylist, next) => {
  1492. this.module
  1493. .runJob(
  1494. "RUN_ACTION2",
  1495. {
  1496. session,
  1497. namespace: "playlists",
  1498. action: "removeSongFromPlaylist",
  1499. args: [youtubeId, likedSongsPlaylist]
  1500. },
  1501. this
  1502. )
  1503. .then(res => {
  1504. if (res.status === "error")
  1505. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1506. return next(null, song);
  1507. })
  1508. .catch(err => next(err));
  1509. },
  1510. (song, next) => {
  1511. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1512. .then(ratings => next(null, song, ratings))
  1513. .catch(err => next(err));
  1514. }
  1515. ],
  1516. async (err, song, ratings) => {
  1517. if (err) {
  1518. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1519. this.log(
  1520. "ERROR",
  1521. "SONGS_UNLIKE",
  1522. `User "${session.userId}" failed to unlike song ${youtubeId}. "${err}"`
  1523. );
  1524. return cb({ status: "error", message: err });
  1525. }
  1526. const { likes, dislikes } = ratings;
  1527. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1528. CacheModule.runJob("PUB", {
  1529. channel: "song.unlike",
  1530. value: JSON.stringify({
  1531. youtubeId,
  1532. userId: session.userId,
  1533. likes,
  1534. dislikes
  1535. })
  1536. });
  1537. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1538. userId: session.userId,
  1539. type: "song__unlike",
  1540. payload: {
  1541. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  1542. ", "
  1543. )}</youtubeId> from your Liked Songs`,
  1544. youtubeId,
  1545. thumbnail: song.thumbnail
  1546. }
  1547. });
  1548. return cb({
  1549. status: "success",
  1550. message: "You have successfully unliked this song."
  1551. });
  1552. }
  1553. );
  1554. }),
  1555. /**
  1556. * Gets song ratings
  1557. *
  1558. * @param session
  1559. * @param songId - the Musare song id
  1560. * @param cb
  1561. */
  1562. getSongRatings: isLoginRequired(async function getSongRatings(session, songId, cb) {
  1563. async.waterfall(
  1564. [
  1565. next => {
  1566. SongsModule.runJob("GET_SONG", { songId }, this)
  1567. .then(res => next(null, res.song))
  1568. .catch(next);
  1569. },
  1570. (song, next) => {
  1571. next(null, {
  1572. likes: song.likes,
  1573. dislikes: song.dislikes
  1574. });
  1575. }
  1576. ],
  1577. async (err, ratings) => {
  1578. if (err) {
  1579. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1580. this.log(
  1581. "ERROR",
  1582. "SONGS_GET_RATINGS",
  1583. `User "${session.userId}" failed to get ratings for ${songId}. "${err}"`
  1584. );
  1585. return cb({ status: "error", message: err });
  1586. }
  1587. const { likes, dislikes } = ratings;
  1588. return cb({
  1589. status: "success",
  1590. data: {
  1591. likes,
  1592. dislikes
  1593. }
  1594. });
  1595. }
  1596. );
  1597. }),
  1598. /**
  1599. * Gets user's own song ratings
  1600. *
  1601. * @param session
  1602. * @param youtubeId - the youtube id
  1603. * @param cb
  1604. */
  1605. getOwnSongRatings: isLoginRequired(async function getOwnSongRatings(session, youtubeId, cb) {
  1606. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1607. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1608. async.waterfall(
  1609. [
  1610. next => songModel.findOne({ youtubeId }, next),
  1611. (song, next) => {
  1612. if (!song) return next("No song found with that id.");
  1613. return next(null);
  1614. },
  1615. next =>
  1616. playlistModel.findOne(
  1617. { createdBy: session.userId, displayName: "Liked Songs" },
  1618. (err, playlist) => {
  1619. if (err) return next(err);
  1620. if (!playlist) return next("'Liked Songs' playlist does not exist.");
  1621. let isLiked = false;
  1622. Object.values(playlist.songs).forEach(song => {
  1623. // song is found in 'liked songs' playlist
  1624. if (song.youtubeId === youtubeId) isLiked = true;
  1625. });
  1626. return next(null, isLiked);
  1627. }
  1628. ),
  1629. (isLiked, next) =>
  1630. playlistModel.findOne(
  1631. { createdBy: session.userId, displayName: "Disliked Songs" },
  1632. (err, playlist) => {
  1633. if (err) return next(err);
  1634. if (!playlist) return next("'Disliked Songs' playlist does not exist.");
  1635. const ratings = { isLiked, isDisliked: false };
  1636. Object.values(playlist.songs).forEach(song => {
  1637. // song is found in 'disliked songs' playlist
  1638. if (song.youtubeId === youtubeId) ratings.isDisliked = true;
  1639. });
  1640. return next(null, ratings);
  1641. }
  1642. )
  1643. ],
  1644. async (err, ratings) => {
  1645. if (err) {
  1646. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1647. this.log(
  1648. "ERROR",
  1649. "SONGS_GET_OWN_RATINGS",
  1650. `User "${session.userId}" failed to get ratings for ${youtubeId}. "${err}"`
  1651. );
  1652. return cb({ status: "error", message: err });
  1653. }
  1654. const { isLiked, isDisliked } = ratings;
  1655. return cb({
  1656. status: "success",
  1657. data: {
  1658. youtubeId,
  1659. liked: isLiked,
  1660. disliked: isDisliked
  1661. }
  1662. });
  1663. }
  1664. );
  1665. }),
  1666. /**
  1667. * Gets a list of all genres
  1668. *
  1669. * @param session
  1670. * @param cb
  1671. */
  1672. getGenres: isAdminRequired(function getGenres(session, cb) {
  1673. async.waterfall(
  1674. [
  1675. next => {
  1676. SongsModule.runJob("GET_GENRES", this)
  1677. .then(res => {
  1678. next(null, res.genres);
  1679. })
  1680. .catch(next);
  1681. }
  1682. ],
  1683. async (err, genres) => {
  1684. if (err && err !== true) {
  1685. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1686. this.log("ERROR", "GET_GENRES", `User ${session.userId} failed to get genres. '${err}'`);
  1687. cb({ status: "error", message: err });
  1688. } else {
  1689. this.log("SUCCESS", "GET_GENRES", `User ${session.userId} has successfully got the genres.`);
  1690. cb({
  1691. status: "success",
  1692. message: "Successfully got genres.",
  1693. data: {
  1694. items: genres
  1695. }
  1696. });
  1697. }
  1698. }
  1699. );
  1700. }),
  1701. /**
  1702. * Bulk update genres for selected songs
  1703. *
  1704. * @param session
  1705. * @param method Whether to add, remove or replace genres
  1706. * @param genres Array of genres to apply
  1707. * @param songIds Array of songIds to apply genres to
  1708. * @param cb
  1709. */
  1710. editGenres: isAdminRequired(async function editGenres(session, method, genres, songIds, cb) {
  1711. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1712. async.waterfall(
  1713. [
  1714. next => {
  1715. songModel.find({ _id: { $in: songIds } }, next);
  1716. },
  1717. (songs, next) => {
  1718. const songsFound = songs.map(song => song._id);
  1719. if (songsFound.length > 0) next(null, songsFound);
  1720. else next("None of the specified songs were found.");
  1721. },
  1722. (songsFound, next) => {
  1723. const query = {};
  1724. if (method === "add") {
  1725. query.$addToSet = { genres: { $each: genres } };
  1726. } else if (method === "remove") {
  1727. query.$pullAll = { genres };
  1728. } else if (method === "replace") {
  1729. query.$set = { genres };
  1730. } else {
  1731. next("Invalid method.");
  1732. return;
  1733. }
  1734. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1735. if (err) {
  1736. next(err);
  1737. return;
  1738. }
  1739. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1740. next();
  1741. });
  1742. }
  1743. ],
  1744. async err => {
  1745. if (err && err !== true) {
  1746. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1747. this.log("ERROR", "EDIT_GENRES", `User ${session.userId} failed to edit genres. '${err}'`);
  1748. cb({ status: "error", message: err });
  1749. } else {
  1750. this.log("SUCCESS", "EDIT_GENRES", `User ${session.userId} has successfully edited genres.`);
  1751. cb({
  1752. status: "success",
  1753. message: "Successfully edited genres."
  1754. });
  1755. }
  1756. }
  1757. );
  1758. }),
  1759. /**
  1760. * Gets a list of all artists
  1761. *
  1762. * @param session
  1763. * @param cb
  1764. */
  1765. getArtists: isAdminRequired(function getArtists(session, cb) {
  1766. async.waterfall(
  1767. [
  1768. next => {
  1769. SongsModule.runJob("GET_ARTISTS", this)
  1770. .then(res => {
  1771. next(null, res.artists);
  1772. })
  1773. .catch(next);
  1774. }
  1775. ],
  1776. async (err, artists) => {
  1777. if (err && err !== true) {
  1778. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1779. this.log("ERROR", "GET_ARTISTS", `User ${session.userId} failed to get artists. '${err}'`);
  1780. cb({ status: "error", message: err });
  1781. } else {
  1782. this.log("SUCCESS", "GET_ARTISTS", `User ${session.userId} has successfully got the artists.`);
  1783. cb({
  1784. status: "success",
  1785. message: "Successfully got artists.",
  1786. data: {
  1787. items: artists
  1788. }
  1789. });
  1790. }
  1791. }
  1792. );
  1793. }),
  1794. /**
  1795. * Bulk update artists for selected songs
  1796. *
  1797. * @param session
  1798. * @param method Whether to add, remove or replace artists
  1799. * @param artists Array of artists to apply
  1800. * @param songIds Array of songIds to apply artists to
  1801. * @param cb
  1802. */
  1803. editArtists: isAdminRequired(async function editArtists(session, method, artists, songIds, cb) {
  1804. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1805. async.waterfall(
  1806. [
  1807. next => {
  1808. songModel.find({ _id: { $in: songIds } }, next);
  1809. },
  1810. (songs, next) => {
  1811. const songsFound = songs.map(song => song._id);
  1812. if (songsFound.length > 0) next(null, songsFound);
  1813. else next("None of the specified songs were found.");
  1814. },
  1815. (songsFound, next) => {
  1816. const query = {};
  1817. if (method === "add") {
  1818. query.$addToSet = { artists: { $each: artists } };
  1819. } else if (method === "remove") {
  1820. query.$pullAll = { artists };
  1821. } else if (method === "replace") {
  1822. query.$set = { artists };
  1823. } else {
  1824. next("Invalid method.");
  1825. return;
  1826. }
  1827. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1828. if (err) {
  1829. next(err);
  1830. return;
  1831. }
  1832. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1833. next();
  1834. });
  1835. }
  1836. ],
  1837. async err => {
  1838. if (err && err !== true) {
  1839. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1840. this.log("ERROR", "EDIT_ARTISTS", `User ${session.userId} failed to edit artists. '${err}'`);
  1841. cb({ status: "error", message: err });
  1842. } else {
  1843. this.log("SUCCESS", "EDIT_ARTISTS", `User ${session.userId} has successfully edited artists.`);
  1844. cb({
  1845. status: "success",
  1846. message: "Successfully edited artists."
  1847. });
  1848. }
  1849. }
  1850. );
  1851. }),
  1852. /**
  1853. * Gets a list of all tags
  1854. *
  1855. * @param session
  1856. * @param cb
  1857. */
  1858. getTags: isAdminRequired(function getTags(session, cb) {
  1859. async.waterfall(
  1860. [
  1861. next => {
  1862. SongsModule.runJob("GET_TAGS", this)
  1863. .then(res => {
  1864. next(null, res.tags);
  1865. })
  1866. .catch(next);
  1867. }
  1868. ],
  1869. async (err, tags) => {
  1870. if (err && err !== true) {
  1871. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1872. this.log("ERROR", "GET_TAGS", `User ${session.userId} failed to get tags. '${err}'`);
  1873. cb({ status: "error", message: err });
  1874. } else {
  1875. this.log("SUCCESS", "GET_TAGS", `User ${session.userId} has successfully got the tags.`);
  1876. cb({
  1877. status: "success",
  1878. message: "Successfully got tags.",
  1879. data: {
  1880. items: tags
  1881. }
  1882. });
  1883. }
  1884. }
  1885. );
  1886. }),
  1887. /**
  1888. * Bulk update tags for selected songs
  1889. *
  1890. * @param session
  1891. * @param method Whether to add, remove or replace tags
  1892. * @param tags Array of tags to apply
  1893. * @param songIds Array of songIds to apply tags to
  1894. * @param cb
  1895. */
  1896. editTags: isAdminRequired(async function editTags(session, method, tags, songIds, cb) {
  1897. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1898. async.waterfall(
  1899. [
  1900. next => {
  1901. songModel.find({ _id: { $in: songIds } }, next);
  1902. },
  1903. (songs, next) => {
  1904. const songsFound = songs.map(song => song._id);
  1905. if (songsFound.length > 0) next(null, songsFound);
  1906. else next("None of the specified songs were found.");
  1907. },
  1908. (songsFound, next) => {
  1909. const query = {};
  1910. if (method === "add") {
  1911. query.$addToSet = { tags: { $each: tags } };
  1912. } else if (method === "remove") {
  1913. query.$pullAll = { tags };
  1914. } else if (method === "replace") {
  1915. query.$set = { tags };
  1916. } else {
  1917. next("Invalid method.");
  1918. return;
  1919. }
  1920. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1921. if (err) {
  1922. next(err);
  1923. return;
  1924. }
  1925. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1926. next();
  1927. });
  1928. }
  1929. ],
  1930. async err => {
  1931. if (err && err !== true) {
  1932. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1933. this.log("ERROR", "EDIT_TAGS", `User ${session.userId} failed to edit tags. '${err}'`);
  1934. cb({ status: "error", message: err });
  1935. } else {
  1936. this.log("SUCCESS", "EDIT_TAGS", `User ${session.userId} has successfully edited tags.`);
  1937. cb({
  1938. status: "success",
  1939. message: "Successfully edited tags."
  1940. });
  1941. }
  1942. }
  1943. );
  1944. })
  1945. };