queueSongs.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. const lib = {
  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. * Updates a queuesong
  117. *
  118. * @param {object} session - the session object automatically added by socket.io
  119. * @param {string} songId - the id of the queuesong that gets updated
  120. * @param {object} updatedSong - the object of the updated queueSong
  121. * @param {Function} cb - gets called with the result
  122. */
  123. update: isAdminRequired(async function update(session, songId, updatedSong, cb) {
  124. const queueSongModel = await DBModule.runJob(
  125. "GET_MODEL",
  126. {
  127. modelName: "queueSong"
  128. },
  129. this
  130. );
  131. async.waterfall(
  132. [
  133. next => {
  134. queueSongModel.findOne({ _id: songId }, next);
  135. },
  136. (song, next) => {
  137. if (!song) return next("Song not found");
  138. let updated = false;
  139. const $set = {};
  140. Object.keys(updatedSong).forEach(prop => {
  141. if (updatedSong[prop] !== song[prop]) $set[prop] = updatedSong[prop];
  142. });
  143. updated = true;
  144. if (!updated) return next("No properties changed");
  145. return queueSongModel.updateOne({ _id: songId }, { $set }, { runValidators: true }, next);
  146. }
  147. ],
  148. async err => {
  149. if (err) {
  150. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  151. this.log(
  152. "ERROR",
  153. "QUEUE_UPDATE",
  154. `Updating queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  155. );
  156. return cb({ status: "failure", message: err });
  157. }
  158. CacheModule.runJob("PUB", { channel: "queue.update", value: songId });
  159. this.log(
  160. "SUCCESS",
  161. "QUEUE_UPDATE",
  162. `User "${session.userId}" successfully update queuesong "${songId}".`
  163. );
  164. return cb({
  165. status: "success",
  166. message: "Successfully updated song."
  167. });
  168. }
  169. );
  170. }),
  171. /**
  172. * Removes a queuesong
  173. *
  174. * @param {object} session - the session object automatically added by socket.io
  175. * @param {string} songId - the id of the queuesong that gets removed
  176. * @param {Function} cb - gets called with the result
  177. */
  178. remove: isAdminRequired(async function remove(session, songId, cb) {
  179. const queueSongModel = await DBModule.runJob(
  180. "GET_MODEL",
  181. {
  182. modelName: "queueSong"
  183. },
  184. this
  185. );
  186. async.waterfall(
  187. [
  188. next => {
  189. queueSongModel.deleteOne({ _id: songId }, next);
  190. }
  191. ],
  192. async err => {
  193. if (err) {
  194. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  195. this.log(
  196. "ERROR",
  197. "QUEUE_REMOVE",
  198. `Removing queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  199. );
  200. return cb({ status: "failure", message: err });
  201. }
  202. CacheModule.runJob("PUB", {
  203. channel: "queue.removedSong",
  204. value: songId
  205. });
  206. this.log(
  207. "SUCCESS",
  208. "QUEUE_REMOVE",
  209. `User "${session.userId}" successfully removed queuesong "${songId}".`
  210. );
  211. return cb({
  212. status: "success",
  213. message: "Successfully updated song."
  214. });
  215. }
  216. );
  217. }),
  218. /**
  219. * Creates a queuesong
  220. *
  221. * @param {object} session - the session object automatically added by socket.io
  222. * @param {string} songId - the id of the song that gets added
  223. * @param {Function} cb - gets called with the result
  224. */
  225. add: isLoginRequired(async function add(session, songId, cb) {
  226. const requestedAt = Date.now();
  227. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  228. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  229. const QueueSongModel = await DBModule.runJob(
  230. "GET_MODEL",
  231. {
  232. modelName: "queueSong"
  233. },
  234. this
  235. );
  236. async.waterfall(
  237. [
  238. next => {
  239. QueueSongModel.findOne({ songId }, next);
  240. },
  241. (song, next) => {
  242. if (song) return next("This song is already in the queue.");
  243. return songModel.findOne({ songId }, next);
  244. },
  245. // Get YouTube data from id
  246. (song, next) => {
  247. if (song) return next("This song has already been added.");
  248. // TODO Add err object as first param of callback
  249. return YouTubeModule.runJob("GET_SONG", { songId }, this)
  250. .then(response => {
  251. const { song } = response;
  252. song.duration = -1;
  253. song.artists = [];
  254. song.genres = [];
  255. song.skipDuration = 0;
  256. song.thumbnail = `${config.get("domain")}/assets/notes.png`;
  257. song.explicit = false;
  258. song.requestedBy = session.userId;
  259. song.requestedAt = requestedAt;
  260. next(null, song);
  261. })
  262. .catch(next);
  263. },
  264. (newSong, next) => {
  265. const song = new QueueSongModel(newSong);
  266. song.save({ validateBeforeSave: false }, (err, song) => {
  267. if (err) return next(err);
  268. return next(null, song);
  269. });
  270. },
  271. (newSong, next) => {
  272. userModel.findOne({ _id: session.userId }, (err, user) => {
  273. if (err) return next(err, newSong);
  274. user.statistics.songsRequested += 1;
  275. return user.save(err => {
  276. if (err) return next(err, newSong);
  277. return next(null, newSong);
  278. });
  279. });
  280. }
  281. ],
  282. async (err, newSong) => {
  283. if (err) {
  284. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  285. this.log(
  286. "ERROR",
  287. "QUEUE_ADD",
  288. `Adding queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  289. );
  290. return cb({ status: "failure", message: err });
  291. }
  292. CacheModule.runJob("PUB", {
  293. channel: "queue.newSong",
  294. value: newSong._id
  295. });
  296. this.log("SUCCESS", "QUEUE_ADD", `User "${session.userId}" successfully added queuesong "${songId}".`);
  297. return cb({
  298. status: "success",
  299. message: "Successfully added that song to the queue"
  300. });
  301. }
  302. );
  303. }),
  304. /**
  305. * Adds a set of songs to the queue
  306. *
  307. * @param {object} session - the session object automatically added by socket.io
  308. * @param {string} url - the url of the the YouTube playlist
  309. * @param {boolean} musicOnly - whether to only get music from the playlist
  310. * @param {Function} cb - gets called with the result
  311. */
  312. addSetToQueue: isLoginRequired(function addSetToQueue(session, url, musicOnly, cb) {
  313. async.waterfall(
  314. [
  315. next => {
  316. YouTubeModule.runJob(
  317. "GET_PLAYLIST",
  318. {
  319. url,
  320. musicOnly
  321. },
  322. this
  323. )
  324. .then(res => {
  325. next(null, res.songs);
  326. })
  327. .catch(next);
  328. },
  329. (songIds, next) => {
  330. let processed = 0;
  331. /**
  332. *
  333. */
  334. function checkDone() {
  335. if (processed === songIds.length) next();
  336. }
  337. songIds.forEach(songId => {
  338. lib.add(session, songId, () => {
  339. processed += 1;
  340. checkDone();
  341. });
  342. });
  343. }
  344. ],
  345. async err => {
  346. if (err) {
  347. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  348. this.log(
  349. "ERROR",
  350. "QUEUE_IMPORT",
  351. `Importing a YouTube playlist to the queue failed for user "${session.userId}". "${err}"`
  352. );
  353. return cb({ status: "failure", message: err });
  354. }
  355. this.log(
  356. "SUCCESS",
  357. "QUEUE_IMPORT",
  358. `Successfully imported a YouTube playlist to the queue for user "${session.userId}".`
  359. );
  360. return cb({
  361. status: "success",
  362. message: "Playlist has been successfully imported."
  363. });
  364. }
  365. );
  366. })
  367. };
  368. export default lib;