songs.js 52 KB

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