songs.js 33 KB

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