queueSongs.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import config from "config";
  2. import async from "async";
  3. import { isAdminRequired, isLoginRequired } from "./hooks";
  4. import db from "../db";
  5. import utils from "../utils";
  6. import cache from "../cache";
  7. // const logger = moduleManager.modules["logger"];
  8. cache.runJob("SUB", {
  9. channel: "queue.newSong",
  10. cb: async songId => {
  11. const queueSongModel = await db.runJob("GET_MODEL", {
  12. modelName: "queueSong"
  13. });
  14. queueSongModel.findOne({ _id: songId }, (err, song) => {
  15. utils.runJob("EMIT_TO_ROOM", {
  16. room: "admin.queue",
  17. args: ["event:admin.queueSong.added", song]
  18. });
  19. });
  20. }
  21. });
  22. cache.runJob("SUB", {
  23. channel: "queue.removedSong",
  24. cb: songId => {
  25. utils.runJob("EMIT_TO_ROOM", {
  26. room: "admin.queue",
  27. args: ["event:admin.queueSong.removed", songId]
  28. });
  29. }
  30. });
  31. cache.runJob("SUB", {
  32. channel: "queue.update",
  33. cb: async songId => {
  34. const queueSongModel = await db.runJob("GET_MODEL", {
  35. modelName: "queueSong"
  36. });
  37. queueSongModel.findOne({ _id: songId }, (err, song) => {
  38. utils.runJob("EMIT_TO_ROOM", {
  39. room: "admin.queue",
  40. args: ["event:admin.queueSong.updated", song]
  41. });
  42. });
  43. }
  44. });
  45. const lib = {
  46. /**
  47. * Returns the length of the queue songs list
  48. *
  49. * @param session
  50. * @param cb
  51. */
  52. length: isAdminRequired(async (session, cb) => {
  53. const queueSongModel = await db.runJob("GET_MODEL", {
  54. modelName: "queueSong"
  55. });
  56. async.waterfall(
  57. [
  58. next => {
  59. queueSongModel.countDocuments({}, next);
  60. }
  61. ],
  62. async (err, count) => {
  63. if (err) {
  64. err = await utils.runJob("GET_ERROR", { error: err });
  65. console.log("ERROR", "QUEUE_SONGS_LENGTH", `Failed to get length from queue songs. "${err}"`);
  66. return cb({ status: "failure", message: err });
  67. }
  68. console.log("SUCCESS", "QUEUE_SONGS_LENGTH", `Got length from queue songs successfully.`);
  69. return cb(count);
  70. }
  71. );
  72. }),
  73. /**
  74. * Gets a set of queue songs
  75. *
  76. * @param session
  77. * @param set - the set number to return
  78. * @param cb
  79. */
  80. getSet: isAdminRequired(async (session, set, cb) => {
  81. const queueSongModel = await db.runJob("GET_MODEL", {
  82. modelName: "queueSong"
  83. });
  84. async.waterfall(
  85. [
  86. next => {
  87. queueSongModel
  88. .find({})
  89. .skip(15 * (set - 1))
  90. .limit(15)
  91. .exec(next);
  92. }
  93. ],
  94. async (err, songs) => {
  95. if (err) {
  96. err = await utils.runJob("GET_ERROR", { error: err });
  97. console.log("ERROR", "QUEUE_SONGS_GET_SET", `Failed to get set from queue songs. "${err}"`);
  98. return cb({ status: "failure", message: err });
  99. }
  100. console.log("SUCCESS", "QUEUE_SONGS_GET_SET", `Got set from queue songs successfully.`);
  101. return cb(songs);
  102. }
  103. );
  104. }),
  105. /**
  106. * Updates a queuesong
  107. *
  108. * @param {object} session - the session object automatically added by socket.io
  109. * @param {string} songId - the id of the queuesong that gets updated
  110. * @param {object} updatedSong - the object of the updated queueSong
  111. * @param {Function} cb - gets called with the result
  112. */
  113. update: isAdminRequired(async (session, songId, updatedSong, cb) => {
  114. const queueSongModel = await db.runJob("GET_MODEL", {
  115. modelName: "queueSong"
  116. });
  117. async.waterfall(
  118. [
  119. next => {
  120. queueSongModel.findOne({ _id: songId }, next);
  121. },
  122. (song, next) => {
  123. if (!song) return next("Song not found");
  124. let updated = false;
  125. const $set = {};
  126. Object.keys(updatedSong).forEach(prop => {
  127. if (updatedSong[prop] !== song[prop]) $set[prop] = updatedSong[prop];
  128. });
  129. updated = true;
  130. if (!updated) return next("No properties changed");
  131. return queueSongModel.updateOne({ _id: songId }, { $set }, { runValidators: true }, next);
  132. }
  133. ],
  134. async err => {
  135. if (err) {
  136. err = await utils.runJob("GET_ERROR", { error: err });
  137. console.log(
  138. "ERROR",
  139. "QUEUE_UPDATE",
  140. `Updating queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  141. );
  142. return cb({ status: "failure", message: err });
  143. }
  144. cache.runJob("PUB", { channel: "queue.update", value: songId });
  145. console.log(
  146. "SUCCESS",
  147. "QUEUE_UPDATE",
  148. `User "${session.userId}" successfully update queuesong "${songId}".`
  149. );
  150. return cb({
  151. status: "success",
  152. message: "Successfully updated song."
  153. });
  154. }
  155. );
  156. }),
  157. /**
  158. * Removes a queuesong
  159. *
  160. * @param {object} session - the session object automatically added by socket.io
  161. * @param {string} songId - the id of the queuesong that gets removed
  162. * @param {Function} cb - gets called with the result
  163. */
  164. remove: isAdminRequired(async (session, songId, cb) => {
  165. const queueSongModel = await db.runJob("GET_MODEL", {
  166. modelName: "queueSong"
  167. });
  168. async.waterfall(
  169. [
  170. next => {
  171. queueSongModel.deleteOne({ _id: songId }, next);
  172. }
  173. ],
  174. async err => {
  175. if (err) {
  176. err = await utils.runJob("GET_ERROR", { error: err });
  177. console.log(
  178. "ERROR",
  179. "QUEUE_REMOVE",
  180. `Removing queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  181. );
  182. return cb({ status: "failure", message: err });
  183. }
  184. cache.runJob("PUB", {
  185. channel: "queue.removedSong",
  186. value: songId
  187. });
  188. console.log(
  189. "SUCCESS",
  190. "QUEUE_REMOVE",
  191. `User "${session.userId}" successfully removed queuesong "${songId}".`
  192. );
  193. return cb({
  194. status: "success",
  195. message: "Successfully updated song."
  196. });
  197. }
  198. );
  199. }),
  200. /**
  201. * Creates a queuesong
  202. *
  203. * @param {object} session - the session object automatically added by socket.io
  204. * @param {string} songId - the id of the song that gets added
  205. * @param {Function} cb - gets called with the result
  206. */
  207. add: isLoginRequired(async (session, songId, cb) => {
  208. const requestedAt = Date.now();
  209. const songModel = await db.runJob("GET_MODEL", { modelName: "song" });
  210. const userModel = await db.runJob("GET_MODEL", { modelName: "user" });
  211. const QueueSongModel = await db.runJob("GET_MODEL", {
  212. modelName: "queueSong"
  213. });
  214. async.waterfall(
  215. [
  216. next => {
  217. QueueSongModel.findOne({ songId }, next);
  218. },
  219. (song, next) => {
  220. if (song) return next("This song is already in the queue.");
  221. return songModel.findOne({ songId }, next);
  222. },
  223. // Get YouTube data from id
  224. (song, next) => {
  225. if (song) return next("This song has already been added.");
  226. // TODO Add err object as first param of callback
  227. return utils
  228. .runJob("GET_SONG_FROM_YOUTUBE", { songId })
  229. .then(response => {
  230. const { song } = response;
  231. song.duration = -1;
  232. song.artists = [];
  233. song.genres = [];
  234. song.skipDuration = 0;
  235. song.thumbnail = `${config.get("domain")}/assets/notes.png`;
  236. song.explicit = false;
  237. song.requestedBy = session.userId;
  238. song.requestedAt = requestedAt;
  239. next(null, song);
  240. })
  241. .catch(next);
  242. },
  243. (newSong, next) => {
  244. const song = new QueueSongModel(newSong);
  245. song.save({ validateBeforeSave: false }, (err, song) => {
  246. if (err) return next(err);
  247. return next(null, song);
  248. });
  249. },
  250. (newSong, next) => {
  251. userModel.findOne({ _id: session.userId }, (err, user) => {
  252. if (err) return next(err, newSong);
  253. user.statistics.songsRequested += 1;
  254. return user.save(err => {
  255. if (err) return next(err, newSong);
  256. return next(null, newSong);
  257. });
  258. });
  259. }
  260. ],
  261. async (err, newSong) => {
  262. if (err) {
  263. err = await utils.runJob("GET_ERROR", { error: err });
  264. console.log(
  265. "ERROR",
  266. "QUEUE_ADD",
  267. `Adding queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  268. );
  269. return cb({ status: "failure", message: err });
  270. }
  271. cache.runJob("PUB", {
  272. channel: "queue.newSong",
  273. value: newSong._id
  274. });
  275. console.log(
  276. "SUCCESS",
  277. "QUEUE_ADD",
  278. `User "${session.userId}" successfully added queuesong "${songId}".`
  279. );
  280. return cb({
  281. status: "success",
  282. message: "Successfully added that song to the queue"
  283. });
  284. }
  285. );
  286. }),
  287. /**
  288. * Adds a set of songs to the queue
  289. *
  290. * @param {object} session - the session object automatically added by socket.io
  291. * @param {string} url - the url of the the YouTube playlist
  292. * @param {boolean} musicOnly - whether to only get music from the playlist
  293. * @param {Function} cb - gets called with the result
  294. */
  295. addSetToQueue: isLoginRequired((session, url, musicOnly, cb) => {
  296. async.waterfall(
  297. [
  298. next => {
  299. utils
  300. .runJob("GET_PLAYLIST_FROM_YOUTUBE", {
  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 utils.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;