queueSongs.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 YouTubeModule from "../youtube";
  7. import cache from "../cache";
  8. // const logger = moduleManager.modules["logger"];
  9. cache.runJob("SUB", {
  10. channel: "queue.newSong",
  11. cb: async songId => {
  12. const queueSongModel = await db.runJob("GET_MODEL", {
  13. modelName: "queueSong"
  14. });
  15. queueSongModel.findOne({ _id: songId }, (err, song) => {
  16. utils.runJob("EMIT_TO_ROOM", {
  17. room: "admin.queue",
  18. args: ["event:admin.queueSong.added", song]
  19. });
  20. });
  21. }
  22. });
  23. cache.runJob("SUB", {
  24. channel: "queue.removedSong",
  25. cb: songId => {
  26. utils.runJob("EMIT_TO_ROOM", {
  27. room: "admin.queue",
  28. args: ["event:admin.queueSong.removed", songId]
  29. });
  30. }
  31. });
  32. cache.runJob("SUB", {
  33. channel: "queue.update",
  34. cb: async songId => {
  35. const queueSongModel = await db.runJob("GET_MODEL", {
  36. modelName: "queueSong"
  37. });
  38. queueSongModel.findOne({ _id: songId }, (err, song) => {
  39. utils.runJob("EMIT_TO_ROOM", {
  40. room: "admin.queue",
  41. args: ["event:admin.queueSong.updated", song]
  42. });
  43. });
  44. }
  45. });
  46. const lib = {
  47. /**
  48. * Returns the length of the queue songs list
  49. *
  50. * @param session
  51. * @param cb
  52. */
  53. length: isAdminRequired(async (session, cb) => {
  54. const queueSongModel = await db.runJob("GET_MODEL", {
  55. modelName: "queueSong"
  56. });
  57. async.waterfall(
  58. [
  59. next => {
  60. queueSongModel.countDocuments({}, next);
  61. }
  62. ],
  63. async (err, count) => {
  64. if (err) {
  65. err = await utils.runJob("GET_ERROR", { error: err });
  66. console.log("ERROR", "QUEUE_SONGS_LENGTH", `Failed to get length from queue songs. "${err}"`);
  67. return cb({ status: "failure", message: err });
  68. }
  69. console.log("SUCCESS", "QUEUE_SONGS_LENGTH", `Got length from queue songs successfully.`);
  70. return cb(count);
  71. }
  72. );
  73. }),
  74. /**
  75. * Gets a set of queue songs
  76. *
  77. * @param session
  78. * @param set - the set number to return
  79. * @param cb
  80. */
  81. getSet: isAdminRequired(async (session, set, cb) => {
  82. const queueSongModel = await db.runJob("GET_MODEL", {
  83. modelName: "queueSong"
  84. });
  85. async.waterfall(
  86. [
  87. next => {
  88. queueSongModel
  89. .find({})
  90. .skip(15 * (set - 1))
  91. .limit(15)
  92. .exec(next);
  93. }
  94. ],
  95. async (err, songs) => {
  96. if (err) {
  97. err = await utils.runJob("GET_ERROR", { error: err });
  98. console.log("ERROR", "QUEUE_SONGS_GET_SET", `Failed to get set from queue songs. "${err}"`);
  99. return cb({ status: "failure", message: err });
  100. }
  101. console.log("SUCCESS", "QUEUE_SONGS_GET_SET", `Got set from queue songs successfully.`);
  102. return cb(songs);
  103. }
  104. );
  105. }),
  106. /**
  107. * Updates a queuesong
  108. *
  109. * @param {object} session - the session object automatically added by socket.io
  110. * @param {string} songId - the id of the queuesong that gets updated
  111. * @param {object} updatedSong - the object of the updated queueSong
  112. * @param {Function} cb - gets called with the result
  113. */
  114. update: isAdminRequired(async (session, songId, updatedSong, cb) => {
  115. const queueSongModel = await db.runJob("GET_MODEL", {
  116. modelName: "queueSong"
  117. });
  118. async.waterfall(
  119. [
  120. next => {
  121. queueSongModel.findOne({ _id: songId }, next);
  122. },
  123. (song, next) => {
  124. if (!song) return next("Song not found");
  125. let updated = false;
  126. const $set = {};
  127. Object.keys(updatedSong).forEach(prop => {
  128. if (updatedSong[prop] !== song[prop]) $set[prop] = updatedSong[prop];
  129. });
  130. updated = true;
  131. if (!updated) return next("No properties changed");
  132. return queueSongModel.updateOne({ _id: songId }, { $set }, { runValidators: true }, next);
  133. }
  134. ],
  135. async err => {
  136. if (err) {
  137. err = await utils.runJob("GET_ERROR", { error: err });
  138. console.log(
  139. "ERROR",
  140. "QUEUE_UPDATE",
  141. `Updating queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  142. );
  143. return cb({ status: "failure", message: err });
  144. }
  145. cache.runJob("PUB", { channel: "queue.update", value: songId });
  146. console.log(
  147. "SUCCESS",
  148. "QUEUE_UPDATE",
  149. `User "${session.userId}" successfully update queuesong "${songId}".`
  150. );
  151. return cb({
  152. status: "success",
  153. message: "Successfully updated song."
  154. });
  155. }
  156. );
  157. }),
  158. /**
  159. * Removes a queuesong
  160. *
  161. * @param {object} session - the session object automatically added by socket.io
  162. * @param {string} songId - the id of the queuesong that gets removed
  163. * @param {Function} cb - gets called with the result
  164. */
  165. remove: isAdminRequired(async (session, songId, cb) => {
  166. const queueSongModel = await db.runJob("GET_MODEL", {
  167. modelName: "queueSong"
  168. });
  169. async.waterfall(
  170. [
  171. next => {
  172. queueSongModel.deleteOne({ _id: songId }, next);
  173. }
  174. ],
  175. async err => {
  176. if (err) {
  177. err = await utils.runJob("GET_ERROR", { error: err });
  178. console.log(
  179. "ERROR",
  180. "QUEUE_REMOVE",
  181. `Removing queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  182. );
  183. return cb({ status: "failure", message: err });
  184. }
  185. cache.runJob("PUB", {
  186. channel: "queue.removedSong",
  187. value: songId
  188. });
  189. console.log(
  190. "SUCCESS",
  191. "QUEUE_REMOVE",
  192. `User "${session.userId}" successfully removed queuesong "${songId}".`
  193. );
  194. return cb({
  195. status: "success",
  196. message: "Successfully updated song."
  197. });
  198. }
  199. );
  200. }),
  201. /**
  202. * Creates a queuesong
  203. *
  204. * @param {object} session - the session object automatically added by socket.io
  205. * @param {string} songId - the id of the song that gets added
  206. * @param {Function} cb - gets called with the result
  207. */
  208. add: isLoginRequired(async (session, songId, cb) => {
  209. const requestedAt = Date.now();
  210. const songModel = await db.runJob("GET_MODEL", { modelName: "song" });
  211. const userModel = await db.runJob("GET_MODEL", { modelName: "user" });
  212. const QueueSongModel = await db.runJob("GET_MODEL", {
  213. modelName: "queueSong"
  214. });
  215. async.waterfall(
  216. [
  217. next => {
  218. QueueSongModel.findOne({ songId }, next);
  219. },
  220. (song, next) => {
  221. if (song) return next("This song is already in the queue.");
  222. return songModel.findOne({ songId }, next);
  223. },
  224. // Get YouTube data from id
  225. (song, next) => {
  226. if (song) return next("This song has already been added.");
  227. // TODO Add err object as first param of callback
  228. return YouTubeModule.runJob("GET_SONG", { 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. YouTubeModule.runJob("GET_PLAYLIST", {
  300. url,
  301. musicOnly
  302. })
  303. .then(res => {
  304. next(null, res.songs);
  305. })
  306. .catch(next);
  307. },
  308. (songIds, next) => {
  309. let processed = 0;
  310. /**
  311. *
  312. */
  313. function checkDone() {
  314. if (processed === songIds.length) next();
  315. }
  316. songIds.forEach(songId => {
  317. lib.add(session, songId, () => {
  318. processed += 1;
  319. checkDone();
  320. });
  321. });
  322. }
  323. ],
  324. async err => {
  325. if (err) {
  326. err = await utils.runJob("GET_ERROR", { error: err });
  327. console.log(
  328. "ERROR",
  329. "QUEUE_IMPORT",
  330. `Importing a YouTube playlist to the queue failed for user "${session.userId}". "${err}"`
  331. );
  332. return cb({ status: "failure", message: err });
  333. }
  334. console.log(
  335. "SUCCESS",
  336. "QUEUE_IMPORT",
  337. `Successfully imported a YouTube playlist to the queue for user "${session.userId}".`
  338. );
  339. return cb({
  340. status: "success",
  341. message: "Playlist has been successfully imported."
  342. });
  343. }
  344. );
  345. })
  346. };
  347. export default lib;