queueSongs.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. import config from "config";
  2. import async from "async";
  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 IOModule = moduleManager.modules.io;
  8. const YouTubeModule = moduleManager.modules.youtube;
  9. const CacheModule = moduleManager.modules.cache;
  10. CacheModule.runJob("SUB", {
  11. channel: "queue.newSong",
  12. cb: async songId => {
  13. const queueSongModel = await DBModule.runJob("GET_MODEL", {
  14. modelName: "queueSong"
  15. });
  16. queueSongModel.findOne({ _id: songId }, (err, song) => {
  17. IOModule.runJob("EMIT_TO_ROOM", {
  18. room: "admin.queue",
  19. args: ["event:admin.queueSong.added", song]
  20. });
  21. });
  22. }
  23. });
  24. CacheModule.runJob("SUB", {
  25. channel: "queue.removedSong",
  26. cb: songId => {
  27. IOModule.runJob("EMIT_TO_ROOM", {
  28. room: "admin.queue",
  29. args: ["event:admin.queueSong.removed", songId]
  30. });
  31. }
  32. });
  33. CacheModule.runJob("SUB", {
  34. channel: "queue.update",
  35. cb: async songId => {
  36. const queueSongModel = await DBModule.runJob("GET_MODEL", {
  37. modelName: "queueSong"
  38. });
  39. queueSongModel.findOne({ _id: songId }, (err, song) => {
  40. IOModule.runJob("EMIT_TO_ROOM", {
  41. room: "admin.queue",
  42. args: ["event:admin.queueSong.updated", song]
  43. });
  44. });
  45. }
  46. });
  47. export default {
  48. /**
  49. * Returns the length of the queue songs list
  50. *
  51. * @param session
  52. * @param cb
  53. */
  54. length: isAdminRequired(async function length(session, cb) {
  55. const queueSongModel = await DBModule.runJob(
  56. "GET_MODEL",
  57. {
  58. modelName: "queueSong"
  59. },
  60. this
  61. );
  62. async.waterfall(
  63. [
  64. next => {
  65. queueSongModel.countDocuments({}, next);
  66. }
  67. ],
  68. async (err, count) => {
  69. if (err) {
  70. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  71. this.log("ERROR", "QUEUE_SONGS_LENGTH", `Failed to get length from queue songs. "${err}"`);
  72. return cb({ status: "failure", message: err });
  73. }
  74. this.log("SUCCESS", "QUEUE_SONGS_LENGTH", `Got length from queue songs successfully.`);
  75. return cb(count);
  76. }
  77. );
  78. }),
  79. /**
  80. * Gets a set of queue songs
  81. *
  82. * @param session
  83. * @param set - the set number to return
  84. * @param cb
  85. */
  86. getSet: isAdminRequired(async function getSet(session, set, cb) {
  87. const queueSongModel = await DBModule.runJob(
  88. "GET_MODEL",
  89. {
  90. modelName: "queueSong"
  91. },
  92. this
  93. );
  94. async.waterfall(
  95. [
  96. next => {
  97. queueSongModel
  98. .find({})
  99. .skip(15 * (set - 1))
  100. .limit(15)
  101. .exec(next);
  102. }
  103. ],
  104. async (err, songs) => {
  105. if (err) {
  106. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  107. this.log("ERROR", "QUEUE_SONGS_GET_SET", `Failed to get set from queue songs. "${err}"`);
  108. return cb({ status: "failure", message: err });
  109. }
  110. this.log("SUCCESS", "QUEUE_SONGS_GET_SET", `Got set from queue songs successfully.`);
  111. return cb(songs);
  112. }
  113. );
  114. }),
  115. /**
  116. * Gets a song from the Musare song id
  117. *
  118. * @param {object} session - the session object automatically added by socket.io
  119. * @param {string} songId - the Musare song id
  120. * @param {Function} cb
  121. */
  122. getSongFromMusareId: isAdminRequired(async function getSong(session, songId, cb) {
  123. const queueSongModel = await DBModule.runJob(
  124. "GET_MODEL",
  125. {
  126. modelName: "queueSong"
  127. },
  128. this
  129. );
  130. async.waterfall(
  131. [
  132. next => {
  133. queueSongModel.findOne({ _id: songId }, next);
  134. }
  135. ],
  136. async (err, song) => {
  137. if (err) {
  138. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  139. this.log("ERROR", "QUEUE_SONGS_GET_SONG_FROM_MUSARE_ID", `Failed to get song ${songId}. "${err}"`);
  140. return cb({ status: "failure", message: err });
  141. }
  142. this.log("SUCCESS", "QUEUE_SONGS_GET_SONG_FROM_MUSARE_ID", `Got song ${songId} successfully.`);
  143. return cb({ status: "success", data: { song } });
  144. }
  145. );
  146. }),
  147. /**
  148. * Updates a queuesong
  149. *
  150. * @param {object} session - the session object automatically added by socket.io
  151. * @param {string} songId - the id of the queuesong that gets updated
  152. * @param {object} updatedSong - the object of the updated queueSong
  153. * @param {Function} cb - gets called with the result
  154. */
  155. update: isAdminRequired(async function update(session, songId, updatedSong, cb) {
  156. const queueSongModel = await DBModule.runJob(
  157. "GET_MODEL",
  158. {
  159. modelName: "queueSong"
  160. },
  161. this
  162. );
  163. async.waterfall(
  164. [
  165. next => {
  166. queueSongModel.findOne({ _id: songId }, next);
  167. },
  168. (song, next) => {
  169. if (!song) return next("Song not found");
  170. let updated = false;
  171. const $set = {};
  172. Object.keys(updatedSong).forEach(prop => {
  173. if (updatedSong[prop] !== song[prop]) $set[prop] = updatedSong[prop];
  174. });
  175. updated = true;
  176. if (!updated) return next("No properties changed");
  177. return queueSongModel.updateOne({ _id: songId }, { $set }, { runValidators: true }, next);
  178. }
  179. ],
  180. async err => {
  181. if (err) {
  182. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  183. this.log(
  184. "ERROR",
  185. "QUEUE_UPDATE",
  186. `Updating queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  187. );
  188. return cb({ status: "failure", message: err });
  189. }
  190. CacheModule.runJob("PUB", { channel: "queue.update", value: songId });
  191. this.log(
  192. "SUCCESS",
  193. "QUEUE_UPDATE",
  194. `User "${session.userId}" successfully update queuesong "${songId}".`
  195. );
  196. return cb({
  197. status: "success",
  198. message: "Successfully updated song."
  199. });
  200. }
  201. );
  202. }),
  203. /**
  204. * Removes a queuesong
  205. *
  206. * @param {object} session - the session object automatically added by socket.io
  207. * @param {string} songId - the id of the queuesong that gets removed
  208. * @param {Function} cb - gets called with the result
  209. */
  210. remove: isAdminRequired(async function remove(session, songId, cb) {
  211. const queueSongModel = await DBModule.runJob(
  212. "GET_MODEL",
  213. {
  214. modelName: "queueSong"
  215. },
  216. this
  217. );
  218. async.waterfall(
  219. [
  220. next => {
  221. queueSongModel.deleteOne({ _id: songId }, next);
  222. }
  223. ],
  224. async err => {
  225. if (err) {
  226. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  227. this.log(
  228. "ERROR",
  229. "QUEUE_REMOVE",
  230. `Removing queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  231. );
  232. return cb({ status: "failure", message: err });
  233. }
  234. CacheModule.runJob("PUB", {
  235. channel: "queue.removedSong",
  236. value: songId
  237. });
  238. this.log(
  239. "SUCCESS",
  240. "QUEUE_REMOVE",
  241. `User "${session.userId}" successfully removed queuesong "${songId}".`
  242. );
  243. return cb({
  244. status: "success",
  245. message: "Successfully updated song."
  246. });
  247. }
  248. );
  249. }),
  250. /**
  251. * Creates a queuesong
  252. *
  253. * @param {object} session - the session object automatically added by socket.io
  254. * @param {string} songId - the id of the song that gets added
  255. * @param {Function} cb - gets called with the result
  256. */
  257. add: isLoginRequired(async function add(session, songId, cb) {
  258. const requestedAt = Date.now();
  259. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  260. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  261. const QueueSongModel = await DBModule.runJob(
  262. "GET_MODEL",
  263. {
  264. modelName: "queueSong"
  265. },
  266. this
  267. );
  268. async.waterfall(
  269. [
  270. next => {
  271. QueueSongModel.findOne({ songId }, next);
  272. },
  273. (song, next) => {
  274. if (song) return next("This song is already in the queue.");
  275. return songModel.findOne({ songId }, next);
  276. },
  277. // Get YouTube data from id
  278. (song, next) => {
  279. if (song) return next("This song has already been added.");
  280. // TODO Add err object as first param of callback
  281. return YouTubeModule.runJob("GET_SONG", { songId }, this)
  282. .then(response => {
  283. const { song } = response;
  284. song.duration = -1;
  285. song.artists = [];
  286. song.genres = [];
  287. song.skipDuration = 0;
  288. song.thumbnail = `${config.get("domain")}/assets/notes.png`;
  289. song.explicit = false;
  290. song.requestedBy = session.userId;
  291. song.requestedAt = requestedAt;
  292. next(null, song);
  293. })
  294. .catch(next);
  295. },
  296. (newSong, next) => {
  297. const song = new QueueSongModel(newSong);
  298. song.save({ validateBeforeSave: false }, (err, song) => {
  299. if (err) return next(err);
  300. return next(null, song);
  301. });
  302. },
  303. (newSong, next) => {
  304. userModel.findOne({ _id: session.userId }, (err, user) => {
  305. if (err) return next(err, newSong);
  306. user.statistics.songsRequested += 1;
  307. return user.save(err => {
  308. if (err) return next(err, newSong);
  309. return next(null, newSong);
  310. });
  311. });
  312. }
  313. ],
  314. async (err, newSong) => {
  315. if (err) {
  316. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  317. this.log(
  318. "ERROR",
  319. "QUEUE_ADD",
  320. `Adding queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  321. );
  322. return cb({ status: "failure", message: err });
  323. }
  324. CacheModule.runJob("PUB", {
  325. channel: "queue.newSong",
  326. value: newSong._id
  327. });
  328. this.log("SUCCESS", "QUEUE_ADD", `User "${session.userId}" successfully added queuesong "${songId}".`);
  329. return cb({
  330. status: "success",
  331. message: "Successfully added that song to the queue"
  332. });
  333. }
  334. );
  335. }),
  336. /**
  337. * Adds a set of songs to the queue
  338. *
  339. * @param {object} session - the session object automatically added by socket.io
  340. * @param {string} url - the url of the the YouTube playlist
  341. * @param {boolean} musicOnly - whether to only get music from the playlist
  342. * @param {Function} cb - gets called with the result
  343. */
  344. addSetToQueue: isLoginRequired(function addSetToQueue(session, url, musicOnly, cb) {
  345. async.waterfall(
  346. [
  347. next => {
  348. YouTubeModule.runJob(
  349. "GET_PLAYLIST",
  350. {
  351. url,
  352. musicOnly
  353. },
  354. this
  355. )
  356. .then(res => {
  357. next(null, res.songs);
  358. })
  359. .catch(next);
  360. },
  361. (songIds, next) => {
  362. let successful = 0;
  363. let failed = 0;
  364. let alreadyInQueue = 0;
  365. let alreadyAdded = 0;
  366. if (songIds.length === 0) next();
  367. async.eachLimit(
  368. songIds,
  369. 1,
  370. (songId, next) => {
  371. IOModule.runJob(
  372. "RUN_ACTION2",
  373. {
  374. session,
  375. namespace: "queueSongs",
  376. action: "add",
  377. args: [songId]
  378. },
  379. this
  380. )
  381. .then(res => {
  382. if (res.status === "success") successful += 1;
  383. else failed += 1;
  384. if (res.message === "This song is already in the queue.") alreadyInQueue += 1;
  385. if (res.message === "This song has already been added.") alreadyAdded += 1;
  386. })
  387. .catch(() => {
  388. failed += 1;
  389. })
  390. .finally(() => {
  391. next();
  392. });
  393. },
  394. () => {
  395. next(null, { successful, failed, alreadyInQueue, alreadyAdded });
  396. }
  397. );
  398. }
  399. ],
  400. async (err, response) => {
  401. if (err) {
  402. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  403. this.log(
  404. "ERROR",
  405. "QUEUE_IMPORT",
  406. `Importing a YouTube playlist to the queue failed for user "${session.userId}". "${err}"`
  407. );
  408. return cb({ status: "failure", message: err });
  409. }
  410. this.log(
  411. "SUCCESS",
  412. "QUEUE_IMPORT",
  413. `Successfully imported a YouTube playlist to the queue for user "${session.userId}".`
  414. );
  415. return cb({
  416. status: "success",
  417. message: `Playlist is done importing. ${response.successful} were added succesfully, ${response.failed} failed (${response.alreadyInQueue} were already in queue, ${response.alreadyAdded} were already added)`
  418. });
  419. }
  420. );
  421. })
  422. };