songs.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. 'use strict';
  2. const async = require('async');
  3. const hooks = require('./hooks');
  4. const queueSongs = require('./queueSongs');
  5. const moduleManager = require("../../index");
  6. const db = moduleManager.modules["db"];
  7. const songs = moduleManager.modules["songs"];
  8. const cache = moduleManager.modules["cache"];
  9. const utils = moduleManager.modules["utils"];
  10. const logger = moduleManager.modules["logger"];
  11. cache.sub('song.removed', songId => {
  12. utils.emitToRoom('admin.songs', 'event:admin.song.removed', songId);
  13. });
  14. cache.sub('song.added', songId => {
  15. db.models.song.findOne({_id: songId}, (err, song) => {
  16. utils.emitToRoom('admin.songs', 'event:admin.song.added', song);
  17. });
  18. });
  19. cache.sub('song.updated', songId => {
  20. db.models.song.findOne({_id: songId}, (err, song) => {
  21. utils.emitToRoom('admin.songs', 'event:admin.song.updated', song);
  22. });
  23. });
  24. cache.sub('song.like', (data) => {
  25. utils.emitToRoom(`song.${data.songId}`, 'event:song.like', {songId: data.songId, likes: data.likes, dislikes: data.dislikes});
  26. utils.socketsFromUser(data.userId, (sockets) => {
  27. sockets.forEach((socket) => {
  28. socket.emit('event:song.newRatings', {songId: data.songId, liked: true, disliked: false});
  29. });
  30. });
  31. });
  32. cache.sub('song.dislike', (data) => {
  33. utils.emitToRoom(`song.${data.songId}`, 'event:song.dislike', {songId: data.songId, likes: data.likes, dislikes: data.dislikes});
  34. utils.socketsFromUser(data.userId, (sockets) => {
  35. sockets.forEach((socket) => {
  36. socket.emit('event:song.newRatings', {songId: data.songId, liked: false, disliked: true});
  37. });
  38. });
  39. });
  40. cache.sub('song.unlike', (data) => {
  41. utils.emitToRoom(`song.${data.songId}`, 'event:song.unlike', {songId: data.songId, likes: data.likes, dislikes: data.dislikes});
  42. utils.socketsFromUser(data.userId, (sockets) => {
  43. sockets.forEach((socket) => {
  44. socket.emit('event:song.newRatings', {songId: data.songId, liked: false, disliked: false});
  45. });
  46. });
  47. });
  48. cache.sub('song.undislike', (data) => {
  49. utils.emitToRoom(`song.${data.songId}`, 'event:song.undislike', {songId: data.songId, likes: data.likes, dislikes: data.dislikes});
  50. utils.socketsFromUser(data.userId, (sockets) => {
  51. sockets.forEach((socket) => {
  52. socket.emit('event:song.newRatings', {songId: data.songId, liked: false, disliked: false});
  53. });
  54. });
  55. });
  56. module.exports = {
  57. /**
  58. * Returns the length of the songs list
  59. *
  60. * @param session
  61. * @param cb
  62. */
  63. length: hooks.adminRequired((session, cb) => {
  64. async.waterfall([
  65. (next) => {
  66. db.models.song.countDocuments({}, next);
  67. }
  68. ], async (err, count) => {
  69. if (err) {
  70. err = await utils.getError(err);
  71. logger.error("SONGS_LENGTH", `Failed to get length from songs. "${err}"`);
  72. return cb({'status': 'failure', 'message': err});
  73. }
  74. logger.success("SONGS_LENGTH", `Got length from songs successfully.`);
  75. cb(count);
  76. });
  77. }),
  78. /**
  79. * Gets a set of songs
  80. *
  81. * @param session
  82. * @param set - the set number to return
  83. * @param cb
  84. */
  85. getSet: hooks.adminRequired((session, set, cb) => {
  86. async.waterfall([
  87. (next) => {
  88. db.models.song.find({}).limit(15 * set).exec(next);
  89. }
  90. ], async (err, songs) => {
  91. if (err) {
  92. err = await utils.getError(err);
  93. logger.error("SONGS_GET_SET", `Failed to get set from songs. "${err}"`);
  94. return cb({'status': 'failure', 'message': err});
  95. }
  96. logger.success("SONGS_GET_SET", `Got set from songs successfully.`);
  97. logger.stationIssue(songs.length, true);
  98. logger.stationIssue(Math.max(songs.length - 15, 0), true);
  99. cb(songs.splice(Math.max(songs.length - 15, 0)));
  100. });
  101. }),
  102. /**
  103. * Gets a song
  104. *
  105. * @param session
  106. * @param songId - the song id
  107. * @param cb
  108. */
  109. getSong: hooks.adminRequired((session, songId, cb) => {
  110. console.log(songId);
  111. async.waterfall([
  112. (next) => {
  113. db.models.song.findOne({ songId }).exec(next);
  114. }
  115. ], async (err, song) => {
  116. if (err) {
  117. err = await utils.getError(err);
  118. logger.error("SONGS_GET_SONG", `Failed to get song ${songId}. "${err}"`);
  119. return cb({ status: 'failure', message: err });
  120. } else {
  121. logger.success("SONGS_GET_SONG", `Got song ${songId} successfully.`);
  122. cb({ status: "success", data: song });
  123. }
  124. });
  125. }),
  126. /**
  127. * Updates a song
  128. *
  129. * @param session
  130. * @param songId - the song id
  131. * @param song - the updated song object
  132. * @param cb
  133. */
  134. update: hooks.adminRequired((session, songId, song, cb) => {
  135. async.waterfall([
  136. (next) => {
  137. db.models.song.updateOne({_id: songId}, song, {runValidators: true}, next);
  138. },
  139. (res, next) => {
  140. songs.updateSong(songId, next);
  141. }
  142. ], async (err, song) => {
  143. if (err) {
  144. err = await utils.getError(err);
  145. logger.error("SONGS_UPDATE", `Failed to update song "${songId}". "${err}"`);
  146. return cb({'status': 'failure', 'message': err});
  147. }
  148. logger.success("SONGS_UPDATE", `Successfully updated song "${songId}".`);
  149. cache.pub('song.updated', song.songId);
  150. cb({ status: 'success', message: 'Song has been successfully updated', data: song });
  151. });
  152. }),
  153. /**
  154. * Removes a song
  155. *
  156. * @param session
  157. * @param songId - the song id
  158. * @param cb
  159. */
  160. remove: hooks.adminRequired((session, songId, cb) => {
  161. async.waterfall([
  162. (next) => {
  163. db.models.song.deleteOne({_id: songId}, next);
  164. },
  165. (res, next) => {//TODO Check if res gets returned from above
  166. cache.hdel('songs', songId, next);
  167. }
  168. ], async (err) => {
  169. if (err) {
  170. err = await utils.getError(err);
  171. logger.error("SONGS_UPDATE", `Failed to remove song "${songId}". "${err}"`);
  172. return cb({'status': 'failure', 'message': err});
  173. }
  174. logger.success("SONGS_UPDATE", `Successfully remove song "${songId}".`);
  175. cache.pub('song.removed', songId);
  176. cb({status: 'success', message: 'Song has been successfully updated'});
  177. });
  178. }),
  179. /**
  180. * Adds a song
  181. *
  182. * @param session
  183. * @param song - the song object
  184. * @param cb
  185. */
  186. add: hooks.adminRequired((session, song, cb) => {
  187. async.waterfall([
  188. (next) => {
  189. db.models.song.findOne({songId: song.songId}, next);
  190. },
  191. (existingSong, next) => {
  192. if (existingSong) return next('Song is already in rotation.');
  193. next();
  194. },
  195. (next) => {
  196. const newSong = new db.models.song(song);
  197. newSong.acceptedBy = session.userId;
  198. newSong.acceptedAt = Date.now();
  199. newSong.save(next);
  200. },
  201. (res, next) => {
  202. queueSongs.remove(session, song._id, () => {
  203. next();
  204. });
  205. },
  206. ], async (err) => {
  207. if (err) {
  208. err = await utils.getError(err);
  209. logger.error("SONGS_ADD", `User "${session.userId}" failed to add song. "${err}"`);
  210. return cb({'status': 'failure', 'message': err});
  211. }
  212. logger.success("SONGS_ADD", `User "${session.userId}" successfully added song "${song.songId}".`);
  213. cache.pub('song.added', song.songId);
  214. cb({status: 'success', message: 'Song has been moved from the queue successfully.'});
  215. });
  216. //TODO Check if video is in queue and Add the song to the appropriate stations
  217. }),
  218. /**
  219. * Likes a song
  220. *
  221. * @param session
  222. * @param songId - the song id
  223. * @param cb
  224. */
  225. like: hooks.loginRequired((session, songId, cb) => {
  226. async.waterfall([
  227. (next) => {
  228. db.models.song.findOne({songId}, next);
  229. },
  230. (song, next) => {
  231. if (!song) return next('No song found with that id.');
  232. next(null, song);
  233. }
  234. ], async (err, song) => {
  235. if (err) {
  236. err = await utils.getError(err);
  237. logger.error("SONGS_LIKE", `User "${session.userId}" failed to like song ${songId}. "${err}"`);
  238. return cb({'status': 'failure', 'message': err});
  239. }
  240. let oldSongId = songId;
  241. songId = song._id;
  242. db.models.user.findOne({ _id: session.userId }, (err, user) => {
  243. if (user.liked.indexOf(songId) !== -1) return cb({ status: 'failure', message: 'You have already liked this song.' });
  244. db.models.user.updateOne({_id: session.userId}, {$push: {liked: songId}, $pull: {disliked: songId}}, err => {
  245. if (!err) {
  246. db.models.user.countDocuments({"liked": songId}, (err, likes) => {
  247. if (err) return cb({ status: 'failure', message: 'Something went wrong while liking this song.' });
  248. db.models.user.countDocuments({"disliked": songId}, (err, dislikes) => {
  249. if (err) return cb({ status: 'failure', message: 'Something went wrong while liking this song.' });
  250. db.models.song.update({_id: songId}, {$set: {likes: likes, dislikes: dislikes}}, (err) => {
  251. if (err) return cb({ status: 'failure', message: 'Something went wrong while liking this song.' });
  252. songs.updateSong(songId, (err, song) => {});
  253. cache.pub('song.like', JSON.stringify({ songId: oldSongId, userId: session.userId, likes: likes, dislikes: dislikes }));
  254. return cb({ status: 'success', message: 'You have successfully liked this song.' });
  255. });
  256. });
  257. });
  258. } else return cb({ status: 'failure', message: 'Something went wrong while liking this song.' });
  259. });
  260. });
  261. });
  262. }),
  263. /**
  264. * Dislikes a song
  265. *
  266. * @param session
  267. * @param songId - the song id
  268. * @param cb
  269. */
  270. dislike: hooks.loginRequired((session, songId, cb) => {
  271. async.waterfall([
  272. (next) => {
  273. db.models.song.findOne({songId}, next);
  274. },
  275. (song, next) => {
  276. if (!song) return next('No song found with that id.');
  277. next(null, song);
  278. }
  279. ], async (err, song) => {
  280. if (err) {
  281. err = await utils.getError(err);
  282. logger.error("SONGS_DISLIKE", `User "${session.userId}" failed to like song ${songId}. "${err}"`);
  283. return cb({'status': 'failure', 'message': err});
  284. }
  285. let oldSongId = songId;
  286. songId = song._id;
  287. db.models.user.findOne({ _id: session.userId }, (err, user) => {
  288. if (user.disliked.indexOf(songId) !== -1) return cb({ status: 'failure', message: 'You have already disliked this song.' });
  289. db.models.user.updateOne({_id: session.userId}, {$push: {disliked: songId}, $pull: {liked: songId}}, err => {
  290. if (!err) {
  291. db.models.user.countDocuments({"liked": songId}, (err, likes) => {
  292. if (err) return cb({ status: 'failure', message: 'Something went wrong while disliking this song.' });
  293. db.models.user.countDocuments({"disliked": songId}, (err, dislikes) => {
  294. if (err) return cb({ status: 'failure', message: 'Something went wrong while disliking this song.' });
  295. db.models.song.update({_id: songId}, {$set: {likes: likes, dislikes: dislikes}}, (err, res) => {
  296. if (err) return cb({ status: 'failure', message: 'Something went wrong while disliking this song.' });
  297. songs.updateSong(songId, (err, song) => {});
  298. cache.pub('song.dislike', JSON.stringify({ songId: oldSongId, userId: session.userId, likes: likes, dislikes: dislikes }));
  299. return cb({ status: 'success', message: 'You have successfully disliked this song.' });
  300. });
  301. });
  302. });
  303. } else return cb({ status: 'failure', message: 'Something went wrong while disliking this song.' });
  304. });
  305. });
  306. });
  307. }),
  308. /**
  309. * Undislikes a song
  310. *
  311. * @param session
  312. * @param songId - the song id
  313. * @param cb
  314. */
  315. undislike: hooks.loginRequired((session, songId, cb) => {
  316. async.waterfall([
  317. (next) => {
  318. db.models.song.findOne({songId}, next);
  319. },
  320. (song, next) => {
  321. if (!song) return next('No song found with that id.');
  322. next(null, song);
  323. }
  324. ], async (err, song) => {
  325. if (err) {
  326. err = await utils.getError(err);
  327. logger.error("SONGS_UNDISLIKE", `User "${session.userId}" failed to like song ${songId}. "${err}"`);
  328. return cb({'status': 'failure', 'message': err});
  329. }
  330. let oldSongId = songId;
  331. songId = song._id;
  332. db.models.user.findOne({_id: session.userId}, (err, user) => {
  333. if (user.disliked.indexOf(songId) === -1) return cb({
  334. status: 'failure',
  335. message: 'You have not disliked this song.'
  336. });
  337. db.models.user.updateOne({_id: session.userId}, {$pull: {liked: songId, disliked: songId}}, err => {
  338. if (!err) {
  339. db.models.user.countDocuments({"liked": songId}, (err, likes) => {
  340. if (err) return cb({
  341. status: 'failure',
  342. message: 'Something went wrong while undisliking this song.'
  343. });
  344. db.models.user.countDocuments({"disliked": songId}, (err, dislikes) => {
  345. if (err) return cb({
  346. status: 'failure',
  347. message: 'Something went wrong while undisliking this song.'
  348. });
  349. db.models.song.update({_id: songId}, {$set: {likes: likes, dislikes: dislikes}}, (err) => {
  350. if (err) return cb({
  351. status: 'failure',
  352. message: 'Something went wrong while undisliking this song.'
  353. });
  354. songs.updateSong(songId, (err, song) => {
  355. });
  356. cache.pub('song.undislike', JSON.stringify({
  357. songId: oldSongId,
  358. userId: session.userId,
  359. likes: likes,
  360. dislikes: dislikes
  361. }));
  362. return cb({
  363. status: 'success',
  364. message: 'You have successfully undisliked this song.'
  365. });
  366. });
  367. });
  368. });
  369. } else return cb({status: 'failure', message: 'Something went wrong while undisliking this song.'});
  370. });
  371. });
  372. });
  373. }),
  374. /**
  375. * Unlikes a song
  376. *
  377. * @param session
  378. * @param songId - the song id
  379. * @param cb
  380. */
  381. unlike: hooks.loginRequired((session, songId, cb) => {
  382. async.waterfall([
  383. (next) => {
  384. db.models.song.findOne({songId}, next);
  385. },
  386. (song, next) => {
  387. if (!song) return next('No song found with that id.');
  388. next(null, song);
  389. }
  390. ], async (err, song) => {
  391. if (err) {
  392. err = await utils.getError(err);
  393. logger.error("SONGS_UNLIKE", `User "${session.userId}" failed to like song ${songId}. "${err}"`);
  394. return cb({'status': 'failure', 'message': err});
  395. }
  396. let oldSongId = songId;
  397. songId = song._id;
  398. db.models.user.findOne({ _id: session.userId }, (err, user) => {
  399. if (user.liked.indexOf(songId) === -1) return cb({ status: 'failure', message: 'You have not liked this song.' });
  400. db.models.user.updateOne({_id: session.userId}, {$pull: {liked: songId, disliked: songId}}, err => {
  401. if (!err) {
  402. db.models.user.countDocuments({"liked": songId}, (err, likes) => {
  403. if (err) return cb({ status: 'failure', message: 'Something went wrong while unliking this song.' });
  404. db.models.user.countDocuments({"disliked": songId}, (err, dislikes) => {
  405. if (err) return cb({ status: 'failure', message: 'Something went wrong while undiking this song.' });
  406. db.models.song.updateOne({_id: songId}, {$set: {likes: likes, dislikes: dislikes}}, (err) => {
  407. if (err) return cb({ status: 'failure', message: 'Something went wrong while unliking this song.' });
  408. songs.updateSong(songId, (err, song) => {});
  409. cache.pub('song.unlike', JSON.stringify({ songId: oldSongId, userId: session.userId, likes: likes, dislikes: dislikes }));
  410. return cb({ status: 'success', message: 'You have successfully unliked this song.' });
  411. });
  412. });
  413. });
  414. } else return cb({ status: 'failure', message: 'Something went wrong while unliking this song.' });
  415. });
  416. });
  417. });
  418. }),
  419. /**
  420. * Gets user's own song ratings
  421. *
  422. * @param session
  423. * @param songId - the song id
  424. * @param cb
  425. */
  426. getOwnSongRatings: hooks.loginRequired((session, songId, cb) => {
  427. async.waterfall([
  428. (next) => {
  429. db.models.song.findOne({songId}, next);
  430. },
  431. (song, next) => {
  432. if (!song) return next('No song found with that id.');
  433. next(null, song);
  434. }
  435. ], async (err, song) => {
  436. if (err) {
  437. err = await utils.getError(err);
  438. logger.error("SONGS_GET_OWN_RATINGS", `User "${session.userId}" failed to get ratings for ${songId}. "${err}"`);
  439. return cb({'status': 'failure', 'message': err});
  440. }
  441. let newSongId = song._id;
  442. db.models.user.findOne({_id: session.userId}, (err, user) => {
  443. if (!err && user) {
  444. return cb({
  445. status: 'success',
  446. songId: songId,
  447. liked: (user.liked.indexOf(newSongId) !== -1),
  448. disliked: (user.disliked.indexOf(newSongId) !== -1)
  449. });
  450. } else {
  451. return cb({
  452. status: 'failure',
  453. message: utils.getError(err)
  454. });
  455. }
  456. });
  457. });
  458. })
  459. };