songs.js 54 KB

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