songs.js 52 KB

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