songs.js 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  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. YouTubeModule.runJob(
  1064. "GET_PLAYLIST",
  1065. {
  1066. url,
  1067. musicOnly
  1068. },
  1069. this
  1070. )
  1071. .then(res => {
  1072. next(null, res.songs);
  1073. })
  1074. .catch(next);
  1075. },
  1076. (youtubeIds, next) => {
  1077. let successful = 0;
  1078. let songs = {};
  1079. let failed = 0;
  1080. let alreadyInDatabase = 0;
  1081. if (youtubeIds.length === 0) next();
  1082. async.eachOfLimit(
  1083. youtubeIds,
  1084. 1,
  1085. (youtubeId, index, next) => {
  1086. WSModule.runJob(
  1087. "RUN_ACTION2",
  1088. {
  1089. session,
  1090. namespace: "songs",
  1091. action: "request",
  1092. args: [youtubeId, returnSongs]
  1093. },
  1094. this
  1095. )
  1096. .then(res => {
  1097. if (res.status === "success") successful += 1;
  1098. else failed += 1;
  1099. if (res.message === "This song is already in the database.") alreadyInDatabase += 1;
  1100. if (res.song) songs[index] = res.song;
  1101. })
  1102. .catch(() => {
  1103. failed += 1;
  1104. })
  1105. .finally(() => {
  1106. next();
  1107. });
  1108. },
  1109. () => {
  1110. if (returnSongs)
  1111. songs = Object.keys(songs)
  1112. .sort()
  1113. .map(key => songs[key]);
  1114. next(null, { successful, failed, alreadyInDatabase, songs });
  1115. }
  1116. );
  1117. }
  1118. ],
  1119. async (err, response) => {
  1120. if (err) {
  1121. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1122. this.log(
  1123. "ERROR",
  1124. "REQUEST_SET",
  1125. `Importing a YouTube playlist to be requested failed for user "${session.userId}". "${err}"`
  1126. );
  1127. return cb({ status: "error", message: err });
  1128. }
  1129. this.log(
  1130. "SUCCESS",
  1131. "REQUEST_SET",
  1132. `Successfully imported a YouTube playlist to be requested for user "${session.userId}".`
  1133. );
  1134. return cb({
  1135. status: "success",
  1136. message: `Playlist is done importing. ${response.successful} were added succesfully, ${response.failed} failed (${response.alreadyInDatabase} were already in database)`,
  1137. songs: returnSongs ? response.songs : null
  1138. });
  1139. }
  1140. );
  1141. }),
  1142. /**
  1143. * Likes a song
  1144. *
  1145. * @param session
  1146. * @param youtubeId - the youtube id
  1147. * @param cb
  1148. */
  1149. like: isLoginRequired(async function like(session, youtubeId, cb) {
  1150. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1151. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1152. async.waterfall(
  1153. [
  1154. next => songModel.findOne({ youtubeId }, next),
  1155. (song, next) => {
  1156. if (!song) return next("No song found with that id.");
  1157. return next(null, song);
  1158. },
  1159. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1160. (song, user, next) => {
  1161. if (!user) return next("User does not exist.");
  1162. return this.module
  1163. .runJob(
  1164. "RUN_ACTION2",
  1165. {
  1166. session,
  1167. namespace: "playlists",
  1168. action: "removeSongFromPlaylist",
  1169. args: [youtubeId, user.dislikedSongsPlaylist]
  1170. },
  1171. this
  1172. )
  1173. .then(res => {
  1174. if (res.status === "error" && res.message !== "Song wasn't in playlist.")
  1175. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1176. return next(null, song, user.likedSongsPlaylist);
  1177. })
  1178. .catch(err => next(err));
  1179. },
  1180. (song, likedSongsPlaylist, next) =>
  1181. this.module
  1182. .runJob(
  1183. "RUN_ACTION2",
  1184. {
  1185. session,
  1186. namespace: "playlists",
  1187. action: "addSongToPlaylist",
  1188. args: [false, youtubeId, likedSongsPlaylist]
  1189. },
  1190. this
  1191. )
  1192. .then(res => {
  1193. if (res.status === "error") {
  1194. if (res.message === "That song is already in the playlist")
  1195. return next("You have already liked this song.");
  1196. return next("Unable to add song to the 'Liked Songs' playlist.");
  1197. }
  1198. return next(null, song);
  1199. })
  1200. .catch(err => next(err)),
  1201. (song, next) => {
  1202. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1203. .then(ratings => next(null, song, ratings))
  1204. .catch(err => next(err));
  1205. }
  1206. ],
  1207. async (err, song, ratings) => {
  1208. if (err) {
  1209. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1210. this.log(
  1211. "ERROR",
  1212. "SONGS_LIKE",
  1213. `User "${session.userId}" failed to like song ${youtubeId}. "${err}"`
  1214. );
  1215. return cb({ status: "error", message: err });
  1216. }
  1217. const { likes, dislikes } = ratings;
  1218. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1219. CacheModule.runJob("PUB", {
  1220. channel: "song.like",
  1221. value: JSON.stringify({
  1222. youtubeId,
  1223. userId: session.userId,
  1224. likes,
  1225. dislikes
  1226. })
  1227. });
  1228. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1229. userId: session.userId,
  1230. type: "song__like",
  1231. payload: {
  1232. message: `Liked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  1233. youtubeId,
  1234. thumbnail: song.thumbnail
  1235. }
  1236. });
  1237. return cb({
  1238. status: "success",
  1239. message: "You have successfully liked this song."
  1240. });
  1241. }
  1242. );
  1243. }),
  1244. /**
  1245. * Dislikes a song
  1246. *
  1247. * @param session
  1248. * @param youtubeId - the youtube id
  1249. * @param cb
  1250. */
  1251. dislike: isLoginRequired(async function dislike(session, youtubeId, cb) {
  1252. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1253. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1254. async.waterfall(
  1255. [
  1256. next => {
  1257. songModel.findOne({ youtubeId }, next);
  1258. },
  1259. (song, next) => {
  1260. if (!song) return next("No song found with that id.");
  1261. return next(null, song);
  1262. },
  1263. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1264. (song, user, next) => {
  1265. if (!user) return next("User does not exist.");
  1266. return this.module
  1267. .runJob(
  1268. "RUN_ACTION2",
  1269. {
  1270. session,
  1271. namespace: "playlists",
  1272. action: "removeSongFromPlaylist",
  1273. args: [youtubeId, user.likedSongsPlaylist]
  1274. },
  1275. this
  1276. )
  1277. .then(res => {
  1278. if (res.status === "error" && res.message !== "Song wasn't in playlist.")
  1279. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1280. return next(null, song, user.dislikedSongsPlaylist);
  1281. })
  1282. .catch(err => next(err));
  1283. },
  1284. (song, dislikedSongsPlaylist, next) =>
  1285. this.module
  1286. .runJob(
  1287. "RUN_ACTION2",
  1288. {
  1289. session,
  1290. namespace: "playlists",
  1291. action: "addSongToPlaylist",
  1292. args: [false, youtubeId, dislikedSongsPlaylist]
  1293. },
  1294. this
  1295. )
  1296. .then(res => {
  1297. if (res.status === "error") {
  1298. if (res.message === "That song is already in the playlist")
  1299. return next("You have already disliked this song.");
  1300. return next("Unable to add song to the 'Disliked Songs' playlist.");
  1301. }
  1302. return next(null, song);
  1303. })
  1304. .catch(err => next(err)),
  1305. (song, next) => {
  1306. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1307. .then(ratings => next(null, song, ratings))
  1308. .catch(err => next(err));
  1309. }
  1310. ],
  1311. async (err, song, ratings) => {
  1312. if (err) {
  1313. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1314. this.log(
  1315. "ERROR",
  1316. "SONGS_DISLIKE",
  1317. `User "${session.userId}" failed to dislike song ${youtubeId}. "${err}"`
  1318. );
  1319. return cb({ status: "error", message: err });
  1320. }
  1321. const { likes, dislikes } = ratings;
  1322. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1323. CacheModule.runJob("PUB", {
  1324. channel: "song.dislike",
  1325. value: JSON.stringify({
  1326. youtubeId,
  1327. userId: session.userId,
  1328. likes,
  1329. dislikes
  1330. })
  1331. });
  1332. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1333. userId: session.userId,
  1334. type: "song__dislike",
  1335. payload: {
  1336. message: `Disliked song <youtubeId>${song.title} by ${song.artists.join(", ")}</youtubeId>`,
  1337. youtubeId,
  1338. thumbnail: song.thumbnail
  1339. }
  1340. });
  1341. return cb({
  1342. status: "success",
  1343. message: "You have successfully disliked this song."
  1344. });
  1345. }
  1346. );
  1347. }),
  1348. /**
  1349. * Undislikes a song
  1350. *
  1351. * @param session
  1352. * @param youtubeId - the youtube id
  1353. * @param cb
  1354. */
  1355. undislike: isLoginRequired(async function undislike(session, youtubeId, cb) {
  1356. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1357. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1358. async.waterfall(
  1359. [
  1360. next => {
  1361. songModel.findOne({ youtubeId }, next);
  1362. },
  1363. (song, next) => {
  1364. if (!song) return next("No song found with that id.");
  1365. return next(null, song);
  1366. },
  1367. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1368. (song, user, next) => {
  1369. if (!user) return next("User does not exist.");
  1370. return this.module
  1371. .runJob(
  1372. "RUN_ACTION2",
  1373. {
  1374. session,
  1375. namespace: "playlists",
  1376. action: "removeSongFromPlaylist",
  1377. args: [youtubeId, user.dislikedSongsPlaylist]
  1378. },
  1379. this
  1380. )
  1381. .then(res => {
  1382. if (res.status === "error")
  1383. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1384. return next(null, song, user.likedSongsPlaylist);
  1385. })
  1386. .catch(err => next(err));
  1387. },
  1388. (song, likedSongsPlaylist, next) => {
  1389. this.module
  1390. .runJob(
  1391. "RUN_ACTION2",
  1392. {
  1393. session,
  1394. namespace: "playlists",
  1395. action: "removeSongFromPlaylist",
  1396. args: [youtubeId, likedSongsPlaylist]
  1397. },
  1398. this
  1399. )
  1400. .then(res => {
  1401. if (res.status === "error" && res.message !== "Song wasn't in playlist.")
  1402. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1403. return next(null, song);
  1404. })
  1405. .catch(err => next(err));
  1406. },
  1407. (song, next) => {
  1408. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1409. .then(ratings => next(null, song, ratings))
  1410. .catch(err => next(err));
  1411. }
  1412. ],
  1413. async (err, song, ratings) => {
  1414. if (err) {
  1415. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1416. this.log(
  1417. "ERROR",
  1418. "SONGS_UNDISLIKE",
  1419. `User "${session.userId}" failed to undislike song ${youtubeId}. "${err}"`
  1420. );
  1421. return cb({ status: "error", message: err });
  1422. }
  1423. const { likes, dislikes } = ratings;
  1424. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1425. CacheModule.runJob("PUB", {
  1426. channel: "song.undislike",
  1427. value: JSON.stringify({
  1428. youtubeId,
  1429. userId: session.userId,
  1430. likes,
  1431. dislikes
  1432. })
  1433. });
  1434. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1435. userId: session.userId,
  1436. type: "song__undislike",
  1437. payload: {
  1438. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  1439. ", "
  1440. )}</youtubeId> from your Disliked Songs`,
  1441. youtubeId,
  1442. thumbnail: song.thumbnail
  1443. }
  1444. });
  1445. return cb({
  1446. status: "success",
  1447. message: "You have successfully undisliked this song."
  1448. });
  1449. }
  1450. );
  1451. }),
  1452. /**
  1453. * Unlikes a song
  1454. *
  1455. * @param session
  1456. * @param youtubeId - the youtube id
  1457. * @param cb
  1458. */
  1459. unlike: isLoginRequired(async function unlike(session, youtubeId, cb) {
  1460. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1461. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1462. async.waterfall(
  1463. [
  1464. next => {
  1465. songModel.findOne({ youtubeId }, next);
  1466. },
  1467. (song, next) => {
  1468. if (!song) return next("No song found with that id.");
  1469. return next(null, song);
  1470. },
  1471. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1472. (song, user, next) => {
  1473. if (!user) return next("User does not exist.");
  1474. return this.module
  1475. .runJob(
  1476. "RUN_ACTION2",
  1477. {
  1478. session,
  1479. namespace: "playlists",
  1480. action: "removeSongFromPlaylist",
  1481. args: [youtubeId, user.dislikedSongsPlaylist]
  1482. },
  1483. this
  1484. )
  1485. .then(res => {
  1486. if (res.status === "error" && res.message !== "Song wasn't in playlist.")
  1487. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1488. return next(null, song, user.likedSongsPlaylist);
  1489. })
  1490. .catch(err => next(err));
  1491. },
  1492. (song, likedSongsPlaylist, next) => {
  1493. this.module
  1494. .runJob(
  1495. "RUN_ACTION2",
  1496. {
  1497. session,
  1498. namespace: "playlists",
  1499. action: "removeSongFromPlaylist",
  1500. args: [youtubeId, likedSongsPlaylist]
  1501. },
  1502. this
  1503. )
  1504. .then(res => {
  1505. if (res.status === "error")
  1506. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1507. return next(null, song);
  1508. })
  1509. .catch(err => next(err));
  1510. },
  1511. (song, next) => {
  1512. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, youtubeId })
  1513. .then(ratings => next(null, song, ratings))
  1514. .catch(err => next(err));
  1515. }
  1516. ],
  1517. async (err, song, ratings) => {
  1518. if (err) {
  1519. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1520. this.log(
  1521. "ERROR",
  1522. "SONGS_UNLIKE",
  1523. `User "${session.userId}" failed to unlike song ${youtubeId}. "${err}"`
  1524. );
  1525. return cb({ status: "error", message: err });
  1526. }
  1527. const { likes, dislikes } = ratings;
  1528. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1529. CacheModule.runJob("PUB", {
  1530. channel: "song.unlike",
  1531. value: JSON.stringify({
  1532. youtubeId,
  1533. userId: session.userId,
  1534. likes,
  1535. dislikes
  1536. })
  1537. });
  1538. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1539. userId: session.userId,
  1540. type: "song__unlike",
  1541. payload: {
  1542. message: `Removed <youtubeId>${song.title} by ${song.artists.join(
  1543. ", "
  1544. )}</youtubeId> from your Liked Songs`,
  1545. youtubeId,
  1546. thumbnail: song.thumbnail
  1547. }
  1548. });
  1549. return cb({
  1550. status: "success",
  1551. message: "You have successfully unliked this song."
  1552. });
  1553. }
  1554. );
  1555. }),
  1556. /**
  1557. * Gets song ratings
  1558. *
  1559. * @param session
  1560. * @param songId - the Musare song id
  1561. * @param cb
  1562. */
  1563. getSongRatings: isLoginRequired(async function getSongRatings(session, songId, cb) {
  1564. async.waterfall(
  1565. [
  1566. next => {
  1567. SongsModule.runJob("GET_SONG", { songId }, this)
  1568. .then(res => next(null, res.song))
  1569. .catch(next);
  1570. },
  1571. (song, next) => {
  1572. next(null, {
  1573. likes: song.likes,
  1574. dislikes: song.dislikes
  1575. });
  1576. }
  1577. ],
  1578. async (err, ratings) => {
  1579. if (err) {
  1580. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1581. this.log(
  1582. "ERROR",
  1583. "SONGS_GET_RATINGS",
  1584. `User "${session.userId}" failed to get ratings for ${songId}. "${err}"`
  1585. );
  1586. return cb({ status: "error", message: err });
  1587. }
  1588. const { likes, dislikes } = ratings;
  1589. return cb({
  1590. status: "success",
  1591. data: {
  1592. likes,
  1593. dislikes
  1594. }
  1595. });
  1596. }
  1597. );
  1598. }),
  1599. /**
  1600. * Gets user's own song ratings
  1601. *
  1602. * @param session
  1603. * @param youtubeId - the youtube id
  1604. * @param cb
  1605. */
  1606. getOwnSongRatings: isLoginRequired(async function getOwnSongRatings(session, youtubeId, cb) {
  1607. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1608. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1609. async.waterfall(
  1610. [
  1611. next => songModel.findOne({ youtubeId }, next),
  1612. (song, next) => {
  1613. if (!song) return next("No song found with that id.");
  1614. return next(null);
  1615. },
  1616. next =>
  1617. playlistModel.findOne(
  1618. { createdBy: session.userId, displayName: "Liked Songs" },
  1619. (err, playlist) => {
  1620. if (err) return next(err);
  1621. if (!playlist) return next("'Liked Songs' playlist does not exist.");
  1622. let isLiked = false;
  1623. Object.values(playlist.songs).forEach(song => {
  1624. // song is found in 'liked songs' playlist
  1625. if (song.youtubeId === youtubeId) isLiked = true;
  1626. });
  1627. return next(null, isLiked);
  1628. }
  1629. ),
  1630. (isLiked, next) =>
  1631. playlistModel.findOne(
  1632. { createdBy: session.userId, displayName: "Disliked Songs" },
  1633. (err, playlist) => {
  1634. if (err) return next(err);
  1635. if (!playlist) return next("'Disliked Songs' playlist does not exist.");
  1636. const ratings = { isLiked, isDisliked: false };
  1637. Object.values(playlist.songs).forEach(song => {
  1638. // song is found in 'disliked songs' playlist
  1639. if (song.youtubeId === youtubeId) ratings.isDisliked = true;
  1640. });
  1641. return next(null, ratings);
  1642. }
  1643. )
  1644. ],
  1645. async (err, ratings) => {
  1646. if (err) {
  1647. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1648. this.log(
  1649. "ERROR",
  1650. "SONGS_GET_OWN_RATINGS",
  1651. `User "${session.userId}" failed to get ratings for ${youtubeId}. "${err}"`
  1652. );
  1653. return cb({ status: "error", message: err });
  1654. }
  1655. const { isLiked, isDisliked } = ratings;
  1656. return cb({
  1657. status: "success",
  1658. data: {
  1659. youtubeId,
  1660. liked: isLiked,
  1661. disliked: isDisliked
  1662. }
  1663. });
  1664. }
  1665. );
  1666. }),
  1667. /**
  1668. * Gets a list of all genres
  1669. *
  1670. * @param session
  1671. * @param cb
  1672. */
  1673. getGenres: isAdminRequired(function getGenres(session, cb) {
  1674. async.waterfall(
  1675. [
  1676. next => {
  1677. SongsModule.runJob("GET_GENRES", this)
  1678. .then(res => {
  1679. next(null, res.genres);
  1680. })
  1681. .catch(next);
  1682. }
  1683. ],
  1684. async (err, genres) => {
  1685. if (err && err !== true) {
  1686. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1687. this.log("ERROR", "GET_GENRES", `User ${session.userId} failed to get genres. '${err}'`);
  1688. cb({ status: "error", message: err });
  1689. } else {
  1690. this.log("SUCCESS", "GET_GENRES", `User ${session.userId} has successfully got the genres.`);
  1691. cb({
  1692. status: "success",
  1693. message: "Successfully got genres.",
  1694. data: {
  1695. items: genres
  1696. }
  1697. });
  1698. }
  1699. }
  1700. );
  1701. }),
  1702. /**
  1703. * Bulk update genres for selected songs
  1704. *
  1705. * @param session
  1706. * @param method Whether to add, remove or replace genres
  1707. * @param genres Array of genres to apply
  1708. * @param songIds Array of songIds to apply genres to
  1709. * @param cb
  1710. */
  1711. editGenres: isAdminRequired(async function editGenres(session, method, genres, songIds, cb) {
  1712. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1713. async.waterfall(
  1714. [
  1715. next => {
  1716. songModel.find({ _id: { $in: songIds } }, next);
  1717. },
  1718. (songs, next) => {
  1719. const songsFound = songs.map(song => song._id);
  1720. if (songsFound.length > 0) next(null, songsFound);
  1721. else next("None of the specified songs were found.");
  1722. },
  1723. (songsFound, next) => {
  1724. const query = {};
  1725. if (method === "add") {
  1726. query.$addToSet = { genres: { $each: genres } };
  1727. } else if (method === "remove") {
  1728. query.$pullAll = { genres };
  1729. } else if (method === "replace") {
  1730. query.$set = { genres };
  1731. } else {
  1732. next("Invalid method.");
  1733. return;
  1734. }
  1735. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1736. if (err) {
  1737. next(err);
  1738. return;
  1739. }
  1740. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1741. next();
  1742. });
  1743. }
  1744. ],
  1745. async err => {
  1746. if (err && err !== true) {
  1747. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1748. this.log("ERROR", "EDIT_GENRES", `User ${session.userId} failed to edit genres. '${err}'`);
  1749. cb({ status: "error", message: err });
  1750. } else {
  1751. this.log("SUCCESS", "EDIT_GENRES", `User ${session.userId} has successfully edited genres.`);
  1752. cb({
  1753. status: "success",
  1754. message: "Successfully edited genres."
  1755. });
  1756. }
  1757. }
  1758. );
  1759. }),
  1760. /**
  1761. * Gets a list of all artists
  1762. *
  1763. * @param session
  1764. * @param cb
  1765. */
  1766. getArtists: isAdminRequired(function getArtists(session, cb) {
  1767. async.waterfall(
  1768. [
  1769. next => {
  1770. SongsModule.runJob("GET_ARTISTS", this)
  1771. .then(res => {
  1772. next(null, res.artists);
  1773. })
  1774. .catch(next);
  1775. }
  1776. ],
  1777. async (err, artists) => {
  1778. if (err && err !== true) {
  1779. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1780. this.log("ERROR", "GET_ARTISTS", `User ${session.userId} failed to get artists. '${err}'`);
  1781. cb({ status: "error", message: err });
  1782. } else {
  1783. this.log("SUCCESS", "GET_ARTISTS", `User ${session.userId} has successfully got the artists.`);
  1784. cb({
  1785. status: "success",
  1786. message: "Successfully got artists.",
  1787. data: {
  1788. items: artists
  1789. }
  1790. });
  1791. }
  1792. }
  1793. );
  1794. }),
  1795. /**
  1796. * Bulk update artists for selected songs
  1797. *
  1798. * @param session
  1799. * @param method Whether to add, remove or replace artists
  1800. * @param artists Array of artists to apply
  1801. * @param songIds Array of songIds to apply artists to
  1802. * @param cb
  1803. */
  1804. editArtists: isAdminRequired(async function editArtists(session, method, artists, songIds, cb) {
  1805. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1806. async.waterfall(
  1807. [
  1808. next => {
  1809. songModel.find({ _id: { $in: songIds } }, next);
  1810. },
  1811. (songs, next) => {
  1812. const songsFound = songs.map(song => song._id);
  1813. if (songsFound.length > 0) next(null, songsFound);
  1814. else next("None of the specified songs were found.");
  1815. },
  1816. (songsFound, next) => {
  1817. const query = {};
  1818. if (method === "add") {
  1819. query.$addToSet = { artists: { $each: artists } };
  1820. } else if (method === "remove") {
  1821. query.$pullAll = { artists };
  1822. } else if (method === "replace") {
  1823. query.$set = { artists };
  1824. } else {
  1825. next("Invalid method.");
  1826. return;
  1827. }
  1828. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1829. if (err) {
  1830. next(err);
  1831. return;
  1832. }
  1833. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1834. next();
  1835. });
  1836. }
  1837. ],
  1838. async err => {
  1839. if (err && err !== true) {
  1840. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1841. this.log("ERROR", "EDIT_ARTISTS", `User ${session.userId} failed to edit artists. '${err}'`);
  1842. cb({ status: "error", message: err });
  1843. } else {
  1844. this.log("SUCCESS", "EDIT_ARTISTS", `User ${session.userId} has successfully edited artists.`);
  1845. cb({
  1846. status: "success",
  1847. message: "Successfully edited artists."
  1848. });
  1849. }
  1850. }
  1851. );
  1852. }),
  1853. /**
  1854. * Gets a list of all tags
  1855. *
  1856. * @param session
  1857. * @param cb
  1858. */
  1859. getTags: isAdminRequired(function getTags(session, cb) {
  1860. async.waterfall(
  1861. [
  1862. next => {
  1863. SongsModule.runJob("GET_TAGS", this)
  1864. .then(res => {
  1865. next(null, res.tags);
  1866. })
  1867. .catch(next);
  1868. }
  1869. ],
  1870. async (err, tags) => {
  1871. if (err && err !== true) {
  1872. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1873. this.log("ERROR", "GET_TAGS", `User ${session.userId} failed to get tags. '${err}'`);
  1874. cb({ status: "error", message: err });
  1875. } else {
  1876. this.log("SUCCESS", "GET_TAGS", `User ${session.userId} has successfully got the tags.`);
  1877. cb({
  1878. status: "success",
  1879. message: "Successfully got tags.",
  1880. data: {
  1881. items: tags
  1882. }
  1883. });
  1884. }
  1885. }
  1886. );
  1887. }),
  1888. /**
  1889. * Bulk update tags for selected songs
  1890. *
  1891. * @param session
  1892. * @param method Whether to add, remove or replace tags
  1893. * @param tags Array of tags to apply
  1894. * @param songIds Array of songIds to apply tags to
  1895. * @param cb
  1896. */
  1897. editTags: isAdminRequired(async function editTags(session, method, tags, songIds, cb) {
  1898. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1899. async.waterfall(
  1900. [
  1901. next => {
  1902. songModel.find({ _id: { $in: songIds } }, next);
  1903. },
  1904. (songs, next) => {
  1905. const songsFound = songs.map(song => song._id);
  1906. if (songsFound.length > 0) next(null, songsFound);
  1907. else next("None of the specified songs were found.");
  1908. },
  1909. (songsFound, next) => {
  1910. const query = {};
  1911. if (method === "add") {
  1912. query.$addToSet = { tags: { $each: tags } };
  1913. } else if (method === "remove") {
  1914. query.$pullAll = { tags };
  1915. } else if (method === "replace") {
  1916. query.$set = { tags };
  1917. } else {
  1918. next("Invalid method.");
  1919. return;
  1920. }
  1921. songModel.updateMany({ _id: { $in: songsFound } }, query, { runValidators: true }, err => {
  1922. if (err) {
  1923. next(err);
  1924. return;
  1925. }
  1926. SongsModule.runJob("UPDATE_SONGS", { songIds: songsFound });
  1927. next();
  1928. });
  1929. }
  1930. ],
  1931. async err => {
  1932. if (err && err !== true) {
  1933. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1934. this.log("ERROR", "EDIT_TAGS", `User ${session.userId} failed to edit tags. '${err}'`);
  1935. cb({ status: "error", message: err });
  1936. } else {
  1937. this.log("SUCCESS", "EDIT_TAGS", `User ${session.userId} has successfully edited tags.`);
  1938. cb({
  1939. status: "success",
  1940. message: "Successfully edited tags."
  1941. });
  1942. }
  1943. }
  1944. );
  1945. })
  1946. };