songs.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  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. const requestedAt = Date.now();
  493. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  494. const UserModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  495. async.waterfall(
  496. [
  497. next => {
  498. SongModel.findOne({ songId }, next);
  499. },
  500. // Get YouTube data from id
  501. (song, next) => {
  502. if (song) return next("This song is already in the database.");
  503. // TODO Add err object as first param of callback
  504. return YouTubeModule.runJob("GET_SONG", { songId }, this)
  505. .then(response => {
  506. const { song } = response;
  507. song.duration = -1;
  508. song.artists = [];
  509. song.genres = [];
  510. song.skipDuration = 0;
  511. song.thumbnail = `${config.get("domain")}/assets/notes.png`;
  512. song.explicit = false;
  513. song.requestedBy = session.userId;
  514. song.requestedAt = requestedAt;
  515. song.verified = false;
  516. next(null, song);
  517. })
  518. .catch(next);
  519. },
  520. (newSong, next) => {
  521. const song = new SongModel(newSong);
  522. song.save({ validateBeforeSave: false }, err => {
  523. if (err) return next(err, song);
  524. return next(null, song);
  525. });
  526. },
  527. (song, next) => {
  528. UserModel.findOne({ _id: session.userId }, (err, user) => {
  529. if (err) return next(err);
  530. user.statistics.songsRequested += 1;
  531. return user.save(err => {
  532. if (err) return next(err);
  533. return next(null, song);
  534. });
  535. });
  536. }
  537. ],
  538. async (err, song) => {
  539. if (err) {
  540. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  541. this.log(
  542. "ERROR",
  543. "SONGS_REQUEST",
  544. `Requesting song "${songId}" failed for user ${session.userId}. "${err}"`
  545. );
  546. return cb({ status: "failure", message: err });
  547. }
  548. CacheModule.runJob("PUB", {
  549. channel: "song.newUnverifiedSong",
  550. value: song._id
  551. });
  552. this.log(
  553. "SUCCESS",
  554. "SONGS_REQUEST",
  555. `User "${session.userId}" successfully requested song "${songId}".`
  556. );
  557. return cb({
  558. status: "success",
  559. message: "Successfully requested that song"
  560. });
  561. }
  562. );
  563. }),
  564. /**
  565. * Verifies a song
  566. *
  567. * @param session
  568. * @param song - the song object
  569. * @param cb
  570. */
  571. verify: isAdminRequired(async function add(session, songId, cb) {
  572. const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  573. async.waterfall(
  574. [
  575. next => {
  576. SongModel.findOne({ songId }, next);
  577. },
  578. (song, next) => {
  579. if (!song) return next("This song is not in the database.");
  580. return next(null, song);
  581. },
  582. (song, next) => {
  583. song.acceptedBy = session.userId;
  584. song.acceptedAt = Date.now();
  585. song.verified = true;
  586. song.save(err => {
  587. next(err, song);
  588. });
  589. },
  590. (song, next) => {
  591. song.genres.forEach(genre => {
  592. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  593. .then(() => {})
  594. .catch(() => {});
  595. });
  596. next(null, song);
  597. }
  598. ],
  599. async (err, song) => {
  600. if (err) {
  601. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  602. this.log("ERROR", "SONGS_VERIFY", `User "${session.userId}" failed to verify song. "${err}"`);
  603. return cb({ status: "failure", message: err });
  604. }
  605. this.log("SUCCESS", "SONGS_VERIFY", `User "${session.userId}" successfully verified song "${songId}".`);
  606. CacheModule.runJob("PUB", {
  607. channel: "song.newVerifiedSong",
  608. value: song._id
  609. });
  610. return cb({
  611. status: "success",
  612. message: "Song has been verified successfully."
  613. });
  614. }
  615. );
  616. // TODO Check if video is in queue and Add the song to the appropriate stations
  617. }),
  618. /**
  619. * Requests a set of songs
  620. *
  621. * @param {object} session - the session object automatically added by the websocket
  622. * @param {string} url - the url of the the YouTube playlist
  623. * @param {boolean} musicOnly - whether to only get music from the playlist
  624. * @param {Function} cb - gets called with the result
  625. */
  626. requestSet: isLoginRequired(function requestSet(session, url, musicOnly, cb) {
  627. async.waterfall(
  628. [
  629. next => {
  630. YouTubeModule.runJob(
  631. "GET_PLAYLIST",
  632. {
  633. url,
  634. musicOnly
  635. },
  636. this
  637. )
  638. .then(res => {
  639. next(null, res.songs);
  640. })
  641. .catch(next);
  642. },
  643. (songIds, next) => {
  644. let successful = 0;
  645. let failed = 0;
  646. let alreadyInDatabase = 0;
  647. if (songIds.length === 0) next();
  648. async.eachLimit(
  649. songIds,
  650. 1,
  651. (songId, next) => {
  652. WSModule.runJob(
  653. "RUN_ACTION2",
  654. {
  655. session,
  656. namespace: "songs",
  657. action: "request",
  658. args: [songId]
  659. },
  660. this
  661. )
  662. .then(res => {
  663. if (res.status === "success") successful += 1;
  664. else failed += 1;
  665. if (res.message === "This song is already in the database.") alreadyInDatabase += 1;
  666. })
  667. .catch(() => {
  668. failed += 1;
  669. })
  670. .finally(() => {
  671. next();
  672. });
  673. },
  674. () => {
  675. next(null, { successful, failed, alreadyInDatabase });
  676. }
  677. );
  678. }
  679. ],
  680. async (err, response) => {
  681. if (err) {
  682. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  683. this.log(
  684. "ERROR",
  685. "REQUEST_SET",
  686. `Importing a YouTube playlist to be requested failed for user "${session.userId}". "${err}"`
  687. );
  688. return cb({ status: "failure", message: err });
  689. }
  690. this.log(
  691. "SUCCESS",
  692. "REQUEST_SET",
  693. `Successfully imported a YouTube playlist to be requested for user "${session.userId}".`
  694. );
  695. return cb({
  696. status: "success",
  697. message: `Playlist is done importing. ${response.successful} were added succesfully, ${response.failed} failed (${response.alreadyInDatabase} were already in database)`
  698. });
  699. }
  700. );
  701. }),
  702. // /**
  703. // * Adds a song
  704. // *
  705. // * @param session
  706. // * @param song - the song object
  707. // * @param cb
  708. // */
  709. // add: isAdminRequired(async function add(session, song, cb) {
  710. // const SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  711. // async.waterfall(
  712. // [
  713. // next => {
  714. // SongModel.findOne({ songId: song.songId }, next);
  715. // },
  716. // (existingSong, next) => {
  717. // if (existingSong) return next("Song is already in rotation.");
  718. // return next();
  719. // },
  720. // next => {
  721. // const newSong = new SongModel(song);
  722. // newSong.acceptedBy = session.userId;
  723. // newSong.acceptedAt = Date.now();
  724. // newSong.save(next);
  725. // },
  726. // (res, next) => {
  727. // this.module
  728. // .runJob(
  729. // "RUN_ACTION2",
  730. // {
  731. // session,
  732. // namespace: "queueSongs",
  733. // action: "remove",
  734. // args: [song._id]
  735. // },
  736. // this
  737. // )
  738. // .finally(() => {
  739. // song.genres.forEach(genre => {
  740. // PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre })
  741. // .then(() => {})
  742. // .catch(() => {});
  743. // });
  744. // next();
  745. // });
  746. // }
  747. // ],
  748. // async err => {
  749. // if (err) {
  750. // err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  751. // this.log("ERROR", "SONGS_ADD", `User "${session.userId}" failed to add song. "${err}"`);
  752. // return cb({ status: "failure", message: err });
  753. // }
  754. // this.log("SUCCESS", "SONGS_ADD", `User "${session.userId}" successfully added song "${song.songId}".`);
  755. // CacheModule.runJob("PUB", {
  756. // channel: "song.added",
  757. // value: song.songId
  758. // });
  759. // return cb({
  760. // status: "success",
  761. // message: "Song has been moved from the queue successfully."
  762. // });
  763. // }
  764. // );
  765. // // TODO Check if video is in queue and Add the song to the appropriate stations
  766. // }),
  767. /**
  768. * Likes a song
  769. *
  770. * @param session
  771. * @param musareSongId - the song id
  772. * @param cb
  773. */
  774. like: isLoginRequired(async function like(session, musareSongId, cb) {
  775. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  776. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  777. async.waterfall(
  778. [
  779. next => songModel.findOne({ songId: musareSongId }, next),
  780. (song, next) => {
  781. if (!song) return next("No song found with that id.");
  782. return next(null, song);
  783. },
  784. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  785. (song, user, next) => {
  786. if (!user) return next("User does not exist.");
  787. return this.module
  788. .runJob(
  789. "RUN_ACTION2",
  790. {
  791. session,
  792. namespace: "playlists",
  793. action: "addSongToPlaylist",
  794. args: [false, musareSongId, user.likedSongsPlaylist]
  795. },
  796. this
  797. )
  798. .then(res => {
  799. if (res.status === "failure")
  800. return next("Unable to add song to the 'Liked Songs' playlist.");
  801. return next(null, song, user.dislikedSongsPlaylist);
  802. })
  803. .catch(err => next(err));
  804. },
  805. (song, dislikedSongsPlaylist, next) => {
  806. this.module
  807. .runJob(
  808. "RUN_ACTION2",
  809. {
  810. session,
  811. namespace: "playlists",
  812. action: "removeSongFromPlaylist",
  813. args: [musareSongId, dislikedSongsPlaylist]
  814. },
  815. this
  816. )
  817. .then(res => {
  818. if (res.status === "failure")
  819. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  820. return next(null, song);
  821. })
  822. .catch(err => next(err));
  823. },
  824. (song, next) => {
  825. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, musareSongId })
  826. .then(ratings => next(null, song, ratings))
  827. .catch(err => next(err));
  828. }
  829. ],
  830. async (err, song, { likes, dislikes }) => {
  831. if (err) {
  832. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  833. this.log(
  834. "ERROR",
  835. "SONGS_LIKE",
  836. `User "${session.userId}" failed to like song ${musareSongId}. "${err}"`
  837. );
  838. return cb({ status: "failure", message: err });
  839. }
  840. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  841. CacheModule.runJob("PUB", {
  842. channel: "song.like",
  843. value: JSON.stringify({
  844. songId: musareSongId,
  845. userId: session.userId,
  846. likes,
  847. dislikes
  848. })
  849. });
  850. ActivitiesModule.runJob("ADD_ACTIVITY", {
  851. userId: session.userId,
  852. type: "song__like",
  853. payload: {
  854. message: `Liked song <songId>${song.title} by ${song.artists.join(", ")}</songId>`,
  855. songId: song._id,
  856. thumbnail: song.thumbnail
  857. }
  858. });
  859. return cb({
  860. status: "success",
  861. message: "You have successfully liked this song."
  862. });
  863. }
  864. );
  865. }),
  866. // TODO: ALready liked/disliked etc.
  867. /**
  868. * Dislikes a song
  869. *
  870. * @param session
  871. * @param musareSongId - the song id
  872. * @param cb
  873. */
  874. dislike: isLoginRequired(async function dislike(session, musareSongId, cb) {
  875. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  876. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  877. async.waterfall(
  878. [
  879. next => {
  880. songModel.findOne({ songId: musareSongId }, next);
  881. },
  882. (song, next) => {
  883. if (!song) return next("No song found with that id.");
  884. return next(null, song);
  885. },
  886. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  887. (song, user, next) => {
  888. if (!user) return next("User does not exist.");
  889. return this.module
  890. .runJob(
  891. "RUN_ACTION2",
  892. {
  893. session,
  894. namespace: "playlists",
  895. action: "addSongToPlaylist",
  896. args: [false, musareSongId, user.dislikedSongsPlaylist]
  897. },
  898. this
  899. )
  900. .then(res => {
  901. if (res.status === "failure")
  902. return next("Unable to add song to the 'Disliked Songs' playlist.");
  903. return next(null, song, user.likedSongsPlaylist);
  904. })
  905. .catch(err => next(err));
  906. },
  907. (song, likedSongsPlaylist, next) => {
  908. this.module
  909. .runJob(
  910. "RUN_ACTION2",
  911. {
  912. session,
  913. namespace: "playlists",
  914. action: "removeSongFromPlaylist",
  915. args: [musareSongId, likedSongsPlaylist]
  916. },
  917. this
  918. )
  919. .then(res => {
  920. if (res.status === "failure")
  921. return next("Unable to remove song from the 'Liked Songs' playlist.");
  922. return next(null, song);
  923. })
  924. .catch(err => next(err));
  925. },
  926. (song, next) => {
  927. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, musareSongId })
  928. .then(ratings => next(null, song, ratings))
  929. .catch(err => next(err));
  930. }
  931. ],
  932. async (err, song, { likes, dislikes }) => {
  933. if (err) {
  934. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  935. this.log(
  936. "ERROR",
  937. "SONGS_DISLIKE",
  938. `User "${session.userId}" failed to dislike song ${musareSongId}. "${err}"`
  939. );
  940. return cb({ status: "failure", message: err });
  941. }
  942. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  943. CacheModule.runJob("PUB", {
  944. channel: "song.dislike",
  945. value: JSON.stringify({
  946. songId: musareSongId,
  947. userId: session.userId,
  948. likes,
  949. dislikes
  950. })
  951. });
  952. ActivitiesModule.runJob("ADD_ACTIVITY", {
  953. userId: session.userId,
  954. type: "song__dislike",
  955. payload: {
  956. message: `Disliked song <songId>${song.title} by ${song.artists.join(", ")}</songId>`,
  957. songId: song._id,
  958. thumbnail: song.thumbnail
  959. }
  960. });
  961. return cb({
  962. status: "success",
  963. message: "You have successfully disliked this song."
  964. });
  965. }
  966. );
  967. }),
  968. /**
  969. * Undislikes a song
  970. *
  971. * @param session
  972. * @param musareSongId - the song id
  973. * @param cb
  974. */
  975. undislike: isLoginRequired(async function undislike(session, musareSongId, cb) {
  976. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  977. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  978. async.waterfall(
  979. [
  980. next => {
  981. songModel.findOne({ songId: musareSongId }, next);
  982. },
  983. (song, next) => {
  984. if (!song) return next("No song found with that id.");
  985. return next(null, song);
  986. },
  987. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  988. (song, user, next) => {
  989. if (!user) return next("User does not exist.");
  990. return this.module
  991. .runJob(
  992. "RUN_ACTION2",
  993. {
  994. session,
  995. namespace: "playlists",
  996. action: "removeSongFromPlaylist",
  997. args: [musareSongId, user.dislikedSongsPlaylist]
  998. },
  999. this
  1000. )
  1001. .then(res => {
  1002. if (res.status === "failure")
  1003. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1004. return next(null, song, user.likedSongsPlaylist);
  1005. })
  1006. .catch(err => next(err));
  1007. },
  1008. (song, likedSongsPlaylist, next) => {
  1009. this.module
  1010. .runJob(
  1011. "RUN_ACTION2",
  1012. {
  1013. session,
  1014. namespace: "playlists",
  1015. action: "removeSongFromPlaylist",
  1016. args: [musareSongId, likedSongsPlaylist]
  1017. },
  1018. this
  1019. )
  1020. .then(res => {
  1021. if (res.status === "failure")
  1022. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1023. return next(null, song);
  1024. })
  1025. .catch(err => next(err));
  1026. },
  1027. (song, next) => {
  1028. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, musareSongId })
  1029. .then(ratings => next(null, song, ratings))
  1030. .catch(err => next(err));
  1031. }
  1032. ],
  1033. async (err, song, { likes, dislikes }) => {
  1034. if (err) {
  1035. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1036. this.log(
  1037. "ERROR",
  1038. "SONGS_UNDISLIKE",
  1039. `User "${session.userId}" failed to undislike song ${musareSongId}. "${err}"`
  1040. );
  1041. return cb({ status: "failure", message: err });
  1042. }
  1043. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1044. CacheModule.runJob("PUB", {
  1045. channel: "song.undislike",
  1046. value: JSON.stringify({
  1047. songId: musareSongId,
  1048. userId: session.userId,
  1049. likes,
  1050. dislikes
  1051. })
  1052. });
  1053. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1054. userId: session.userId,
  1055. type: "song__undislike",
  1056. payload: {
  1057. message: `Removed <songId>${song.title} by ${song.artists.join(
  1058. ", "
  1059. )}</songId> from your Disliked Songs`,
  1060. songId: song._id,
  1061. thumbnail: song.thumbnail
  1062. }
  1063. });
  1064. return cb({
  1065. status: "success",
  1066. message: "You have successfully undisliked this song."
  1067. });
  1068. }
  1069. );
  1070. }),
  1071. /**
  1072. * Unlikes a song
  1073. *
  1074. * @param session
  1075. * @param musareSongId - the song id
  1076. * @param cb
  1077. */
  1078. unlike: isLoginRequired(async function unlike(session, musareSongId, cb) {
  1079. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1080. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1081. async.waterfall(
  1082. [
  1083. next => {
  1084. songModel.findOne({ songId: musareSongId }, next);
  1085. },
  1086. (song, next) => {
  1087. if (!song) return next("No song found with that id.");
  1088. return next(null, song);
  1089. },
  1090. (song, next) => userModel.findOne({ _id: session.userId }, (err, user) => next(err, song, user)),
  1091. (song, user, next) => {
  1092. if (!user) return next("User does not exist.");
  1093. return this.module
  1094. .runJob(
  1095. "RUN_ACTION2",
  1096. {
  1097. session,
  1098. namespace: "playlists",
  1099. action: "removeSongFromPlaylist",
  1100. args: [musareSongId, user.dislikedSongsPlaylist]
  1101. },
  1102. this
  1103. )
  1104. .then(res => {
  1105. if (res.status === "failure")
  1106. return next("Unable to remove song from the 'Disliked Songs' playlist.");
  1107. return next(null, song, user.likedSongsPlaylist);
  1108. })
  1109. .catch(err => next(err));
  1110. },
  1111. (song, likedSongsPlaylist, next) => {
  1112. this.module
  1113. .runJob(
  1114. "RUN_ACTION2",
  1115. {
  1116. session,
  1117. namespace: "playlists",
  1118. action: "removeSongFromPlaylist",
  1119. args: [musareSongId, likedSongsPlaylist]
  1120. },
  1121. this
  1122. )
  1123. .then(res => {
  1124. if (res.status === "failure")
  1125. return next("Unable to remove song from the 'Liked Songs' playlist.");
  1126. return next(null, song);
  1127. })
  1128. .catch(err => next(err));
  1129. },
  1130. (song, next) => {
  1131. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId: song._id, musareSongId })
  1132. .then(ratings => next(null, song, ratings))
  1133. .catch(err => next(err));
  1134. }
  1135. ],
  1136. async (err, song, { likes, dislikes }) => {
  1137. if (err) {
  1138. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1139. this.log(
  1140. "ERROR",
  1141. "SONGS_UNLIKE",
  1142. `User "${session.userId}" failed to unlike song ${musareSongId}. "${err}"`
  1143. );
  1144. return cb({ status: "failure", message: err });
  1145. }
  1146. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  1147. CacheModule.runJob("PUB", {
  1148. channel: "song.unlike",
  1149. value: JSON.stringify({
  1150. songId: musareSongId,
  1151. userId: session.userId,
  1152. likes,
  1153. dislikes
  1154. })
  1155. });
  1156. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1157. userId: session.userId,
  1158. type: "song__unlike",
  1159. payload: {
  1160. message: `Removed <songId>${song.title} by ${song.artists.join(
  1161. ", "
  1162. )}</songId> from your Liked Songs`,
  1163. songId: song._id,
  1164. thumbnail: song.thumbnail
  1165. }
  1166. });
  1167. return cb({
  1168. status: "success",
  1169. message: "You have successfully unliked this song."
  1170. });
  1171. }
  1172. );
  1173. }),
  1174. /**
  1175. * Gets user's own song ratings
  1176. *
  1177. * @param session
  1178. * @param musareSongId - the song id
  1179. * @param cb
  1180. */
  1181. getOwnSongRatings: isLoginRequired(async function getOwnSongRatings(session, musareSongId, cb) {
  1182. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1183. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  1184. async.waterfall(
  1185. [
  1186. next => {
  1187. songModel.findOne({ songId: musareSongId }, next);
  1188. },
  1189. (song, next) => {
  1190. if (!song) return next("No song found with that id.");
  1191. return next(null);
  1192. },
  1193. next =>
  1194. playlistModel.findOne(
  1195. { createdBy: session.userId, displayName: "Liked Songs" },
  1196. (err, playlist) => {
  1197. if (err) return next(err);
  1198. if (!playlist) return next("'Liked Songs' playlist does not exist.");
  1199. let isLiked = false;
  1200. Object.values(playlist.songs).forEach(song => {
  1201. // song is found in 'liked songs' playlist
  1202. if (song.songId === musareSongId) isLiked = true;
  1203. });
  1204. return next(null, isLiked);
  1205. }
  1206. ),
  1207. (isLiked, next) =>
  1208. playlistModel.findOne(
  1209. { createdBy: session.userId, displayName: "Disliked Songs" },
  1210. (err, playlist) => {
  1211. if (err) return next(err);
  1212. if (!playlist) return next("'Disliked Songs' playlist does not exist.");
  1213. const ratings = { isLiked, isDisliked: false };
  1214. Object.values(playlist.songs).forEach(song => {
  1215. // song is found in 'disliked songs' playlist
  1216. if (song.songId === musareSongId) ratings.isDisliked = true;
  1217. });
  1218. return next(null, ratings);
  1219. }
  1220. )
  1221. ],
  1222. async (err, ratings) => {
  1223. if (err) {
  1224. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1225. this.log(
  1226. "ERROR",
  1227. "SONGS_GET_OWN_RATINGS",
  1228. `User "${session.userId}" failed to get ratings for ${musareSongId}. "${err}"`
  1229. );
  1230. return cb({ status: "failure", message: err });
  1231. }
  1232. const { isLiked, isDisliked } = ratings;
  1233. return cb({
  1234. status: "success",
  1235. songId: musareSongId,
  1236. liked: isLiked,
  1237. disliked: isDisliked
  1238. });
  1239. }
  1240. );
  1241. })
  1242. };