songs.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  1. import async from "async";
  2. import { isAdminRequired, isLoginRequired } from "./hooks";
  3. import moduleManager from "../../index";
  4. const DBModule = moduleManager.modules.db;
  5. const UtilsModule = moduleManager.modules.utils;
  6. const WSModule = moduleManager.modules.ws;
  7. const CacheModule = moduleManager.modules.cache;
  8. const SongsModule = moduleManager.modules.songs;
  9. const ActivitiesModule = moduleManager.modules.activities;
  10. const YouTubeModule = moduleManager.modules.youtube;
  11. const PlaylistsModule = moduleManager.modules.playlists;
  12. const StationsModule = moduleManager.modules.stations;
  13. CacheModule.runJob("SUB", {
  14. channel: "song.updated",
  15. cb: async data => {
  16. const songModel = await DBModule.runJob("GET_MODEL", {
  17. modelName: "song"
  18. });
  19. songModel.findOne({ _id: data.songId }, (err, song) => {
  20. WSModule.runJob("EMIT_TO_ROOMS", {
  21. rooms: ["import-album", "admin.songs", `edit-song.${data.songId}`, "edit-songs"],
  22. args: ["event:admin.song.updated", { data: { song, oldStatus: data.oldStatus } }]
  23. });
  24. });
  25. }
  26. });
  27. CacheModule.runJob("SUB", {
  28. channel: "song.removed",
  29. cb: async data => {
  30. WSModule.runJob("EMIT_TO_ROOMS", {
  31. rooms: ["import-album", "admin.songs", `edit-song.${data.songId}`, "edit-songs"],
  32. args: ["event:admin.song.removed", { data }]
  33. });
  34. }
  35. });
  36. CacheModule.runJob("SUB", {
  37. channel: "song.like",
  38. cb: data => {
  39. WSModule.runJob("EMIT_TO_ROOM", {
  40. room: `song.${data.youtubeId}`,
  41. args: [
  42. "event:song.liked",
  43. {
  44. data: { youtubeId: data.youtubeId, likes: data.likes, dislikes: data.dislikes }
  45. }
  46. ]
  47. });
  48. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  49. sockets.forEach(socket => {
  50. socket.dispatch("event:song.ratings.updated", {
  51. data: {
  52. youtubeId: data.youtubeId,
  53. liked: true,
  54. disliked: false
  55. }
  56. });
  57. });
  58. });
  59. }
  60. });
  61. CacheModule.runJob("SUB", {
  62. channel: "song.dislike",
  63. cb: data => {
  64. WSModule.runJob("EMIT_TO_ROOM", {
  65. room: `song.${data.youtubeId}`,
  66. args: [
  67. "event:song.disliked",
  68. {
  69. data: { youtubeId: data.youtubeId, likes: data.likes, dislikes: data.dislikes }
  70. }
  71. ]
  72. });
  73. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  74. sockets.forEach(socket => {
  75. socket.dispatch("event:song.ratings.updated", {
  76. data: {
  77. youtubeId: data.youtubeId,
  78. liked: false,
  79. disliked: true
  80. }
  81. });
  82. });
  83. });
  84. }
  85. });
  86. CacheModule.runJob("SUB", {
  87. channel: "song.unlike",
  88. cb: data => {
  89. WSModule.runJob("EMIT_TO_ROOM", {
  90. room: `song.${data.youtubeId}`,
  91. args: [
  92. "event:song.unliked",
  93. {
  94. data: { youtubeId: data.youtubeId, likes: data.likes, dislikes: data.dislikes }
  95. }
  96. ]
  97. });
  98. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  99. sockets.forEach(socket => {
  100. socket.dispatch("event:song.ratings.updated", {
  101. data: {
  102. youtubeId: data.youtubeId,
  103. liked: false,
  104. disliked: false
  105. }
  106. });
  107. });
  108. });
  109. }
  110. });
  111. CacheModule.runJob("SUB", {
  112. channel: "song.undislike",
  113. cb: data => {
  114. WSModule.runJob("EMIT_TO_ROOM", {
  115. room: `song.${data.youtubeId}`,
  116. args: [
  117. "event:song.undisliked",
  118. {
  119. data: { youtubeId: data.youtubeId, likes: data.likes, dislikes: data.dislikes }
  120. }
  121. ]
  122. });
  123. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  124. sockets.forEach(socket => {
  125. socket.dispatch("event:song.ratings.updated", {
  126. data: {
  127. youtubeId: data.youtubeId,
  128. liked: false,
  129. disliked: false
  130. }
  131. });
  132. });
  133. });
  134. }
  135. });
  136. export default {
  137. /**
  138. * Returns the length of the songs list
  139. *
  140. * @param {object} session - the session object automatically added by the websocket
  141. * @param cb
  142. */
  143. length: isAdminRequired(async function length(session, cb) {
  144. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  145. async.waterfall(
  146. [
  147. next => {
  148. songModel.countDocuments({}, next);
  149. }
  150. ],
  151. async (err, count) => {
  152. if (err) {
  153. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  154. this.log("ERROR", "SONGS_LENGTH", `Failed to get length from songs. "${err}"`);
  155. return cb({ status: "error", message: err });
  156. }
  157. this.log("SUCCESS", "SONGS_LENGTH", `Got length from songs successfully.`);
  158. return cb({ status: "success", message: "Successfully got length of songs.", data: { length: count } });
  159. }
  160. );
  161. }),
  162. /**
  163. * Gets songs, used in the admin songs page by the AdvancedTable component
  164. *
  165. * @param {object} session - the session object automatically added by the websocket
  166. * @param page - the page
  167. * @param pageSize - the size per page
  168. * @param properties - the properties to return for each song
  169. * @param sort - the sort object
  170. * @param queries - the queries array
  171. * @param operator - the operator for queries
  172. * @param cb
  173. */
  174. getData: isAdminRequired(async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  175. async.waterfall(
  176. [
  177. next => {
  178. DBModule.runJob(
  179. "GET_DATA",
  180. {
  181. page,
  182. pageSize,
  183. properties,
  184. sort,
  185. queries,
  186. operator,
  187. modelName: "song",
  188. blacklistedProperties: [],
  189. specialProperties: {
  190. requestedBy: [
  191. {
  192. $addFields: {
  193. requestedByOID: {
  194. $convert: {
  195. input: "$requestedBy",
  196. to: "objectId",
  197. onError: "unknown",
  198. onNull: "unknown"
  199. }
  200. }
  201. }
  202. },
  203. {
  204. $lookup: {
  205. from: "users",
  206. localField: "requestedByOID",
  207. foreignField: "_id",
  208. as: "requestedByUser"
  209. }
  210. },
  211. {
  212. $addFields: {
  213. requestedByUsername: {
  214. $ifNull: ["$requestedByUser.username", "unknown"]
  215. }
  216. }
  217. },
  218. {
  219. $project: {
  220. requestedByOID: 0,
  221. requestedByUser: 0
  222. }
  223. }
  224. ],
  225. verifiedBy: [
  226. {
  227. $addFields: {
  228. verifiedByOID: {
  229. $convert: {
  230. input: "$verifiedBy",
  231. to: "objectId",
  232. onError: "unknown",
  233. onNull: "unknown"
  234. }
  235. }
  236. }
  237. },
  238. {
  239. $lookup: {
  240. from: "users",
  241. localField: "verifiedByOID",
  242. foreignField: "_id",
  243. as: "verifiedByUser"
  244. }
  245. },
  246. {
  247. $unwind: {
  248. path: "$verifiedByUser",
  249. preserveNullAndEmptyArrays: true
  250. }
  251. },
  252. {
  253. $addFields: {
  254. verifiedByUsername: {
  255. $ifNull: ["$verifiedByUser.username", "unknown"]
  256. }
  257. }
  258. },
  259. {
  260. $project: {
  261. verifiedByOID: 0,
  262. verifiedByUser: 0
  263. }
  264. }
  265. ]
  266. },
  267. specialQueries: {
  268. requestedBy: newQuery => ({
  269. $or: [newQuery, { requestedByUsername: newQuery.requestedBy }]
  270. }),
  271. verifiedBy: newQuery => ({
  272. $or: [newQuery, { verifiedByUsername: newQuery.verifiedBy }]
  273. })
  274. }
  275. },
  276. this
  277. )
  278. .then(response => {
  279. next(null, response);
  280. })
  281. .catch(err => {
  282. next(err);
  283. });
  284. }
  285. ],
  286. async (err, response) => {
  287. if (err) {
  288. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  289. this.log("ERROR", "SONGS_GET_DATA", `Failed to get data from songs. "${err}"`);
  290. return cb({ status: "error", message: err });
  291. }
  292. this.log("SUCCESS", "SONGS_GET_DATA", `Got data from songs successfully.`);
  293. return cb({ status: "success", message: "Successfully got data from songs.", data: response });
  294. }
  295. );
  296. }),
  297. /**
  298. * Updates all songs
  299. *
  300. * @param {object} session - the session object automatically added by the websocket
  301. * @param cb
  302. */
  303. updateAll: isAdminRequired(async function updateAll(session, cb) {
  304. async.waterfall(
  305. [
  306. next => {
  307. SongsModule.runJob("UPDATE_ALL_SONGS", {}, this)
  308. .then(() => {
  309. next();
  310. })
  311. .catch(err => {
  312. next(err);
  313. });
  314. }
  315. ],
  316. async err => {
  317. if (err) {
  318. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  319. this.log("ERROR", "SONGS_UPDATE_ALL", `Failed to update all songs. "${err}"`);
  320. return cb({ status: "error", message: err });
  321. }
  322. this.log("SUCCESS", "SONGS_UPDATE_ALL", `Updated all songs successfully.`);
  323. return cb({ status: "success", message: "Successfully updated all songs." });
  324. }
  325. );
  326. }),
  327. /**
  328. * Recalculates all song ratings
  329. *
  330. * @param {object} session - the session object automatically added by the websocket
  331. * @param cb
  332. */
  333. recalculateAllRatings: isAdminRequired(async function recalculateAllRatings(session, cb) {
  334. async.waterfall(
  335. [
  336. next => {
  337. SongsModule.runJob("RECALCULATE_ALL_SONG_RATINGS", {}, this)
  338. .then(() => {
  339. next();
  340. })
  341. .catch(err => {
  342. next(err);
  343. });
  344. }
  345. ],
  346. async err => {
  347. if (err) {
  348. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  349. this.log(
  350. "ERROR",
  351. "SONGS_RECALCULATE_ALL_RATINGS",
  352. `Failed to recalculate all song ratings. "${err}"`
  353. );
  354. return cb({ status: "error", message: err });
  355. }
  356. this.log("SUCCESS", "SONGS_RECALCULATE_ALL_RATINGS", `Recalculated all song ratings successfully.`);
  357. return cb({ status: "success", message: "Successfully recalculated all song ratings." });
  358. }
  359. );
  360. }),
  361. /**
  362. * Gets a song from the Musare song id
  363. *
  364. * @param {object} session - the session object automatically added by the websocket
  365. * @param {string} songId - the song id
  366. * @param {Function} cb
  367. */
  368. getSongFromSongId: isAdminRequired(function getSongFromSongId(session, songId, cb) {
  369. async.waterfall(
  370. [
  371. next => {
  372. SongsModule.runJob("GET_SONG", { songId }, this)
  373. .then(response => next(null, response.song))
  374. .catch(err => next(err));
  375. }
  376. ],
  377. async (err, song) => {
  378. if (err) {
  379. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  380. this.log("ERROR", "SONGS_GET_SONG_FROM_MUSARE_ID", `Failed to get song ${songId}. "${err}"`);
  381. return cb({ status: "error", message: err });
  382. }
  383. this.log("SUCCESS", "SONGS_GET_SONG_FROM_MUSARE_ID", `Got song ${songId} successfully.`);
  384. return cb({ status: "success", data: { song } });
  385. }
  386. );
  387. }),
  388. /**
  389. * Gets multiple songs from the Musare song ids
  390. * At this time only used in EditSongs
  391. *
  392. * @param {object} session - the session object automatically added by the websocket
  393. * @param {Array} songIds - the song ids
  394. * @param {Function} cb
  395. */
  396. getSongsFromSongIds: isAdminRequired(function getSongFromSongId(session, songIds, cb) {
  397. async.waterfall(
  398. [
  399. next => {
  400. SongsModule.runJob(
  401. "GET_SONGS",
  402. {
  403. songIds,
  404. properties: ["youtubeId", "title", "artists", "thumbnail", "duration", "verified", "_id"]
  405. },
  406. this
  407. )
  408. .then(response => next(null, response.songs))
  409. .catch(err => next(err));
  410. }
  411. ],
  412. async (err, songs) => {
  413. if (err) {
  414. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  415. this.log("ERROR", "SONGS_GET_SONGS_FROM_MUSARE_IDS", `Failed to get songs. "${err}"`);
  416. return cb({ status: "error", message: err });
  417. }
  418. this.log("SUCCESS", "SONGS_GET_SONGS_FROM_MUSARE_IDS", `Got songs successfully.`);
  419. return cb({ status: "success", data: { songs } });
  420. }
  421. );
  422. }),
  423. /**
  424. * Creates a song
  425. *
  426. * @param {object} session - the session object automatically added by the websocket
  427. * @param {object} newSong - the song object
  428. * @param {Function} cb
  429. */
  430. create: isAdminRequired(async function create(session, newSong, cb) {
  431. async.waterfall(
  432. [
  433. next => {
  434. SongsModule.runJob("CREATE_SONG", { song: newSong, userId: session.userId }, this)
  435. .then(song => next(null, song))
  436. .catch(next);
  437. }
  438. ],
  439. async (err, song) => {
  440. if (err) {
  441. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  442. this.log("ERROR", "SONGS_CREATE", `Failed to create song "${JSON.stringify(newSong)}". "${err}"`);
  443. return cb({ status: "error", message: err });
  444. }
  445. this.log("SUCCESS", "SONGS_CREATE", `Successfully created song "${song._id}".`);
  446. return cb({
  447. status: "success",
  448. message: "Song has been successfully created",
  449. data: { song }
  450. });
  451. }
  452. );
  453. }),
  454. /**
  455. * Updates a song
  456. *
  457. * @param {object} session - the session object automatically added by the websocket
  458. * @param {string} songId - the song id
  459. * @param {object} song - the updated song object
  460. * @param {Function} cb
  461. */
  462. update: isAdminRequired(async function update(session, songId, song, cb) {
  463. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  464. let existingSong = null;
  465. async.waterfall(
  466. [
  467. next => {
  468. songModel.findOne({ _id: songId }, next);
  469. },
  470. (_existingSong, next) => {
  471. existingSong = _existingSong;
  472. // Verify the song
  473. if (existingSong.verified === false && song.verified === true) {
  474. song.verifiedBy = session.userId;
  475. song.verifiedAt = Date.now();
  476. }
  477. // Unverify the song
  478. else if (existingSong.verified === true && song.verified === false) {
  479. song.verifiedBy = null;
  480. song.verifiedAt = null;
  481. }
  482. next();
  483. },
  484. next => {
  485. songModel.updateOne({ _id: songId }, song, { runValidators: true }, next);
  486. },
  487. (res, next) => {
  488. SongsModule.runJob("UPDATE_SONG", { songId }, this)
  489. .then(song => {
  490. existingSong.genres
  491. .concat(song.genres)
  492. .filter((value, index, self) => self.indexOf(value) === index)
  493. .forEach(genre => {
  494. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", {
  495. genre,
  496. createPlaylist: song.verified
  497. })
  498. .then(() => {})
  499. .catch(() => {});
  500. });
  501. next(null, song);
  502. })
  503. .catch(next);
  504. }
  505. ],
  506. async (err, song) => {
  507. if (err) {
  508. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  509. this.log("ERROR", "SONGS_UPDATE", `Failed to update song "${songId}". "${err}"`);
  510. return cb({ status: "error", message: err });
  511. }
  512. this.log("SUCCESS", "SONGS_UPDATE", `Successfully updated song "${songId}".`);
  513. return cb({
  514. status: "success",
  515. message: "Song has been successfully updated",
  516. data: { song }
  517. });
  518. }
  519. );
  520. }),
  521. /**
  522. * Removes a song
  523. *
  524. * @param session
  525. * @param songId - the song id
  526. * @param cb
  527. */
  528. remove: isAdminRequired(async function remove(session, songId, cb) {
  529. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  530. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  531. async.waterfall(
  532. [
  533. next => {
  534. songModel.findOne({ _id: songId }, next);
  535. },
  536. (song, next) => {
  537. PlaylistsModule.runJob("GET_PLAYLISTS_WITH_SONG", { songId }, this)
  538. .then(res => {
  539. async.eachLimit(
  540. res.playlists,
  541. 1,
  542. (playlist, next) => {
  543. WSModule.runJob(
  544. "RUN_ACTION2",
  545. {
  546. session,
  547. namespace: "playlists",
  548. action: "removeSongFromPlaylist",
  549. args: [song.youtubeId, playlist._id]
  550. },
  551. this
  552. )
  553. .then(res => {
  554. if (res.status === "error") next(res.message);
  555. else next();
  556. })
  557. .catch(err => {
  558. next(err);
  559. });
  560. },
  561. err => {
  562. if (err) next(err);
  563. else next(null, song);
  564. }
  565. );
  566. })
  567. .catch(err => next(err));
  568. },
  569. (song, next) => {
  570. stationModel.find({ "queue._id": songId }, (err, stations) => {
  571. if (err) next(err);
  572. else {
  573. async.eachLimit(
  574. stations,
  575. 1,
  576. (station, next) => {
  577. WSModule.runJob(
  578. "RUN_ACTION2",
  579. {
  580. session,
  581. namespace: "stations",
  582. action: "removeFromQueue",
  583. args: [station._id, song.youtubeId]
  584. },
  585. this
  586. )
  587. .then(res => {
  588. if (
  589. res.status === "error" &&
  590. res.message !== "Station not found" &&
  591. res.message !== "Song is not currently in the queue."
  592. )
  593. next(res.message);
  594. else next();
  595. })
  596. .catch(err => {
  597. next(err);
  598. });
  599. },
  600. err => {
  601. if (err) next(err);
  602. else next();
  603. }
  604. );
  605. }
  606. });
  607. },
  608. next => {
  609. stationModel.find({ "currentSong._id": songId }, (err, stations) => {
  610. if (err) next(err);
  611. else {
  612. async.eachLimit(
  613. stations,
  614. 1,
  615. (station, next) => {
  616. StationsModule.runJob(
  617. "SKIP_STATION",
  618. { stationId: station._id, natural: false },
  619. this
  620. )
  621. .then(() => {
  622. next();
  623. })
  624. .catch(err => {
  625. if (err.message === "Station not found.") next();
  626. else next(err);
  627. });
  628. },
  629. err => {
  630. if (err) next(err);
  631. else next();
  632. }
  633. );
  634. }
  635. });
  636. },
  637. next => {
  638. songModel.deleteOne({ _id: songId }, err => {
  639. if (err) next(err);
  640. else next();
  641. });
  642. },
  643. next => {
  644. CacheModule.runJob("HDEL", { table: "songs", key: songId }, this)
  645. .then(() => {
  646. next();
  647. })
  648. .catch(next);
  649. }
  650. ],
  651. async err => {
  652. if (err) {
  653. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  654. this.log("ERROR", "SONGS_REMOVE", `Failed to remove song "${songId}". "${err}"`);
  655. return cb({ status: "error", message: err });
  656. }
  657. this.log("SUCCESS", "SONGS_REMOVE", `Successfully removed song "${songId}".`);
  658. CacheModule.runJob("PUB", {
  659. channel: "song.removed",
  660. value: { songId }
  661. });
  662. return cb({
  663. status: "success",
  664. message: "Song has been successfully removed"
  665. });
  666. }
  667. );
  668. }),
  669. /**
  670. * Removes many songs
  671. *
  672. * @param session
  673. * @param songIds - array of song ids
  674. * @param cb
  675. */
  676. removeMany: isAdminRequired(async function remove(session, songIds, cb) {
  677. const successful = [];
  678. const failed = [];
  679. async.waterfall(
  680. [
  681. next => {
  682. async.eachLimit(
  683. songIds,
  684. 1,
  685. (songId, next) => {
  686. WSModule.runJob(
  687. "RUN_ACTION2",
  688. {
  689. session,
  690. namespace: "songs",
  691. action: "remove",
  692. args: [songId]
  693. },
  694. this
  695. )
  696. .then(res => {
  697. if (res.status === "error") failed.push(songId);
  698. else successful.push(songId);
  699. next();
  700. })
  701. .catch(err => {
  702. next(err);
  703. });
  704. },
  705. err => {
  706. if (err) next(err);
  707. else next();
  708. }
  709. );
  710. }
  711. ],
  712. async err => {
  713. if (err) {
  714. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  715. this.log("ERROR", "SONGS_REMOVE_MANY", `Failed to remove songs "${failed.join(", ")}". "${err}"`);
  716. return cb({ status: "error", message: err });
  717. }
  718. let message = "";
  719. if (successful.length === 1) message += `1 song has been successfully removed`;
  720. else message += `${successful.length} songs have been successfully removed`;
  721. if (failed.length > 0) {
  722. this.log("ERROR", "SONGS_REMOVE_MANY", `Failed to remove songs "${failed.join(", ")}". "${err}"`);
  723. if (failed.length === 1) message += `, failed to remove 1 song`;
  724. else message += `, failed to remove ${failed.length} songs`;
  725. }
  726. this.log("SUCCESS", "SONGS_REMOVE_MANY", `${message} "${successful.join(", ")}"`);
  727. return cb({
  728. status: "success",
  729. message
  730. });
  731. }
  732. );
  733. }),
  734. /**
  735. * Searches through official songs
  736. *
  737. * @param {object} session - the session object automatically added by the websocket
  738. * @param {string} query - the query
  739. * @param {string} page - the page
  740. * @param {Function} cb - gets called with the result
  741. */
  742. searchOfficial: isLoginRequired(async function searchOfficial(session, query, page, cb) {
  743. async.waterfall(
  744. [
  745. next => {
  746. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  747. else next();
  748. },
  749. next => {
  750. SongsModule.runJob("SEARCH", {
  751. query,
  752. includeVerified: true,
  753. trimmed: true,
  754. page
  755. })
  756. .then(response => {
  757. next(null, response);
  758. })
  759. .catch(err => {
  760. next(err);
  761. });
  762. }
  763. ],
  764. async (err, data) => {
  765. if (err) {
  766. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  767. this.log("ERROR", "SONGS_SEARCH_OFFICIAL", `Searching songs failed. "${err}"`);
  768. return cb({ status: "error", message: err });
  769. }
  770. this.log("SUCCESS", "SONGS_SEARCH_OFFICIAL", "Searching songs successful.");
  771. return cb({ status: "success", data });
  772. }
  773. );
  774. }),
  775. /**
  776. * Requests a song
  777. *
  778. * @param {object} session - the session object automatically added by the websocket
  779. * @param {string} youtubeId - the youtube id of the song that gets requested
  780. * @param {string} returnSong - returns the simple song
  781. * @param {Function} cb - gets called with the result
  782. */
  783. request: isLoginRequired(async function add(session, youtubeId, returnSong, cb) {
  784. SongsModule.runJob("REQUEST_SONG", { youtubeId, userId: session.userId }, this)
  785. .then(response => {
  786. this.log(
  787. "SUCCESS",
  788. "SONGS_REQUEST",
  789. `User "${session.userId}" successfully requested song "${youtubeId}".`
  790. );
  791. return cb({
  792. status: "success",
  793. message: "Successfully requested that song",
  794. song: returnSong ? response.song : null
  795. });
  796. })
  797. .catch(async _err => {
  798. const err = await UtilsModule.runJob("GET_ERROR", { error: _err }, this);
  799. this.log(
  800. "ERROR",
  801. "SONGS_REQUEST",
  802. `Requesting song "${youtubeId}" failed for user ${session.userId}. "${err}"`
  803. );
  804. return cb({ status: "error", message: err, song: returnSong && _err.data ? _err.data.song : null });
  805. });
  806. }),
  807. /**
  808. * Verifies a song
  809. *
  810. * @param session
  811. * @param songId - the song id
  812. * @param cb
  813. */
  814. verify: isAdminRequired(async function add(session, songId, cb) {
  815. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  816. async.waterfall(
  817. [
  818. next => {
  819. SongModel.findOne({ _id: songId }, next);
  820. },
  821. (song, next) => {
  822. if (!song) return next("This song is not in the database.");
  823. return next(null, song);
  824. },
  825. (song, next) => {
  826. const oldStatus = false;
  827. song.verifiedBy = session.userId;
  828. song.verifiedAt = Date.now();
  829. song.verified = true;
  830. song.save(err => next(err, song, oldStatus));
  831. },
  832. (song, oldStatus, next) => {
  833. song.genres.forEach(genre => {
  834. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: true })
  835. .then(() => {})
  836. .catch(() => {});
  837. });
  838. SongsModule.runJob("UPDATE_SONG", { songId: song._id, oldStatus });
  839. next(null, song, oldStatus);
  840. }
  841. ],
  842. async err => {
  843. if (err) {
  844. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  845. this.log("ERROR", "SONGS_VERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  846. return cb({ status: "error", message: err });
  847. }
  848. this.log("SUCCESS", "SONGS_VERIFY", `User "${session.userId}" successfully verified song "${songId}".`);
  849. return cb({
  850. status: "success",
  851. message: "Song has been verified successfully."
  852. });
  853. }
  854. );
  855. // TODO Check if video is in queue and Add the song to the appropriate stations
  856. }),
  857. /**
  858. * Verify many songs
  859. *
  860. * @param session
  861. * @param songIds - array of song ids
  862. * @param cb
  863. */
  864. verifyMany: isAdminRequired(async function verifyMany(session, songIds, cb) {
  865. const successful = [];
  866. const failed = [];
  867. async.waterfall(
  868. [
  869. next => {
  870. async.eachLimit(
  871. songIds,
  872. 1,
  873. (songId, next) => {
  874. WSModule.runJob(
  875. "RUN_ACTION2",
  876. {
  877. session,
  878. namespace: "songs",
  879. action: "verify",
  880. args: [songId]
  881. },
  882. this
  883. )
  884. .then(res => {
  885. if (res.status === "error") failed.push(songId);
  886. else successful.push(songId);
  887. next();
  888. })
  889. .catch(err => {
  890. next(err);
  891. });
  892. },
  893. err => {
  894. if (err) next(err);
  895. else next();
  896. }
  897. );
  898. }
  899. ],
  900. async err => {
  901. if (err) {
  902. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  903. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  904. return cb({ status: "error", message: err });
  905. }
  906. let message = "";
  907. if (successful.length === 1) message += `1 song has been successfully verified`;
  908. else message += `${successful.length} songs have been successfully verified`;
  909. if (failed.length > 0) {
  910. this.log("ERROR", "SONGS_VERIFY_MANY", `Failed to verify songs "${failed.join(", ")}". "${err}"`);
  911. if (failed.length === 1) message += `, failed to verify 1 song`;
  912. else message += `, failed to verify ${failed.length} songs`;
  913. }
  914. this.log("SUCCESS", "SONGS_VERIFY_MANY", `${message} "${successful.join(", ")}"`);
  915. return cb({
  916. status: "success",
  917. message
  918. });
  919. }
  920. );
  921. }),
  922. /**
  923. * Un-verifies a song
  924. *
  925. * @param session
  926. * @param songId - the song id
  927. * @param cb
  928. */
  929. unverify: isAdminRequired(async function add(session, songId, cb) {
  930. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  931. async.waterfall(
  932. [
  933. next => {
  934. SongModel.findOne({ _id: songId }, next);
  935. },
  936. (song, next) => {
  937. if (!song) return next("This song is not in the database.");
  938. return next(null, song);
  939. },
  940. (song, next) => {
  941. song.verified = false;
  942. song.verifiedBy = null;
  943. song.verifiedAt = null;
  944. song.save(err => {
  945. next(err, song);
  946. });
  947. },
  948. (song, next) => {
  949. song.genres.forEach(genre => {
  950. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre, createPlaylist: false })
  951. .then(() => {})
  952. .catch(() => {});
  953. });
  954. SongsModule.runJob("UPDATE_SONG", { songId, oldStatus: true });
  955. next(null);
  956. }
  957. ],
  958. async err => {
  959. if (err) {
  960. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  961. this.log("ERROR", "SONGS_UNVERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  962. return cb({ status: "error", message: err });
  963. }
  964. this.log(
  965. "SUCCESS",
  966. "SONGS_UNVERIFY",
  967. `User "${session.userId}" successfully unverified song "${songId}".`
  968. );
  969. return cb({
  970. status: "success",
  971. message: "Song has been unverified successfully."
  972. });
  973. }
  974. );
  975. // TODO Check if video is in queue and Add the song to the appropriate stations
  976. }),
  977. /**
  978. * Unverify many songs
  979. *
  980. * @param session
  981. * @param songIds - array of song ids
  982. * @param cb
  983. */
  984. unverifyMany: isAdminRequired(async function unverifyMany(session, songIds, cb) {
  985. const successful = [];
  986. const failed = [];
  987. async.waterfall(
  988. [
  989. next => {
  990. async.eachLimit(
  991. songIds,
  992. 1,
  993. (songId, next) => {
  994. WSModule.runJob(
  995. "RUN_ACTION2",
  996. {
  997. session,
  998. namespace: "songs",
  999. action: "unverify",
  1000. args: [songId]
  1001. },
  1002. this
  1003. )
  1004. .then(res => {
  1005. if (res.status === "error") failed.push(songId);
  1006. else successful.push(songId);
  1007. next();
  1008. })
  1009. .catch(err => {
  1010. next(err);
  1011. });
  1012. },
  1013. err => {
  1014. if (err) next(err);
  1015. else next();
  1016. }
  1017. );
  1018. }
  1019. ],
  1020. async err => {
  1021. if (err) {
  1022. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1023. this.log(
  1024. "ERROR",
  1025. "SONGS_UNVERIFY_MANY",
  1026. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  1027. );
  1028. return cb({ status: "error", message: err });
  1029. }
  1030. let message = "";
  1031. if (successful.length === 1) message += `1 song has been successfully unverified`;
  1032. else message += `${successful.length} songs have been successfully unverified`;
  1033. if (failed.length > 0) {
  1034. this.log(
  1035. "ERROR",
  1036. "SONGS_UNVERIFY_MANY",
  1037. `Failed to unverify songs "${failed.join(", ")}". "${err}"`
  1038. );
  1039. if (failed.length === 1) message += `, failed to unverify 1 song`;
  1040. else message += `, failed to unverify ${failed.length} songs`;
  1041. }
  1042. this.log("SUCCESS", "SONGS_UNVERIFY_MANY", `${message} "${successful.join(", ")}"`);
  1043. return cb({
  1044. status: "success",
  1045. message
  1046. });
  1047. }
  1048. );
  1049. }),
  1050. /**
  1051. * Requests a set of songs
  1052. *
  1053. * @param {object} session - the session object automatically added by the websocket
  1054. * @param {string} url - the url of the the YouTube playlist
  1055. * @param {boolean} musicOnly - whether to only get music from the playlist
  1056. * @param {Function} cb - gets called with the result
  1057. */
  1058. requestSet: isLoginRequired(function requestSet(session, url, musicOnly, returnSongs, cb) {
  1059. async.waterfall(
  1060. [
  1061. next => {
  1062. YouTubeModule.runJob(
  1063. "GET_PLAYLIST",
  1064. {
  1065. url,
  1066. musicOnly
  1067. },
  1068. this
  1069. )
  1070. .then(res => {
  1071. next(null, res.songs);
  1072. })
  1073. .catch(next);
  1074. },
  1075. (youtubeIds, next) => {
  1076. let successful = 0;
  1077. let songs = {};
  1078. let failed = 0;
  1079. let alreadyInDatabase = 0;
  1080. if (youtubeIds.length === 0) next();
  1081. async.eachOfLimit(
  1082. youtubeIds,
  1083. 1,
  1084. (youtubeId, index, next) => {
  1085. WSModule.runJob(
  1086. "RUN_ACTION2",
  1087. {
  1088. session,
  1089. namespace: "songs",
  1090. action: "request",
  1091. args: [youtubeId, returnSongs]
  1092. },
  1093. this
  1094. )
  1095. .then(res => {
  1096. if (res.status === "success") successful += 1;
  1097. else failed += 1;
  1098. if (res.message === "This song is already in the database.") alreadyInDatabase += 1;
  1099. if (res.song) songs[index] = res.song;
  1100. else songs[index] = null;
  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")
  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")
  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")
  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")
  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.$push = { 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.$push = { 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.$push = { 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. };