queueSongs.js 9.6 KB

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