songs.js 54 KB

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