queueSongs.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. import config from "config";
  2. import async from "async";
  3. import { isAdminRequired, isLoginRequired, isOwnerRequired } 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. for (let prop = 0, songKeys = Object.keys(updatedSong); prop < songKeys.length; prop += 1) {
  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. utils.getSongFromSpotify(newSong, (err, song) => {
  245. if (!song) next(null, newSong);
  246. else next(err, song);
  247. });
  248. }, */
  249. (newSong, next) => {
  250. const song = new QueueSongModel(newSong);
  251. song.save({ validateBeforeSave: false }, (err, song) => {
  252. if (err) return next(err);
  253. return next(null, song);
  254. });
  255. },
  256. (newSong, next) => {
  257. userModel.findOne({ _id: session.userId }, (err, user) => {
  258. if (err) return next(err, newSong);
  259. user.statistics.songsRequested += 1;
  260. return user.save(err => {
  261. if (err) return next(err, newSong);
  262. return next(null, newSong);
  263. });
  264. });
  265. }
  266. ],
  267. async (err, newSong) => {
  268. if (err) {
  269. err = await utils.runJob("GET_ERROR", { error: err });
  270. console.log(
  271. "ERROR",
  272. "QUEUE_ADD",
  273. `Adding queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  274. );
  275. return cb({ status: "failure", message: err });
  276. }
  277. cache.runJob("PUB", {
  278. channel: "queue.newSong",
  279. value: newSong._id
  280. });
  281. console.log(
  282. "SUCCESS",
  283. "QUEUE_ADD",
  284. `User "${session.userId}" successfully added queuesong "${songId}".`
  285. );
  286. return cb({
  287. status: "success",
  288. message: "Successfully added that song to the queue"
  289. });
  290. }
  291. );
  292. }),
  293. /**
  294. * Adds a set of songs to the queue
  295. *
  296. * @param {object} session - the session object automatically added by socket.io
  297. * @param {string} url - the url of the the YouTube playlist
  298. * @param {boolean} musicOnly - whether to only get music from the playlist
  299. * @param {Function} cb - gets called with the result
  300. */
  301. addSetToQueue: isLoginRequired((session, url, musicOnly, cb) => {
  302. async.waterfall(
  303. [
  304. next => {
  305. utils
  306. .runJob("GET_PLAYLIST_FROM_YOUTUBE", {
  307. url,
  308. musicOnly
  309. })
  310. .then(res => {
  311. next(null, res.songs);
  312. })
  313. .catch(next);
  314. },
  315. (songIds, next) => {
  316. let processed = 0;
  317. /**
  318. *
  319. */
  320. function checkDone() {
  321. if (processed === songIds.length) next();
  322. }
  323. songIds.forEach(songId => {
  324. lib.add(session, songId, () => {
  325. processed += 1;
  326. checkDone();
  327. });
  328. });
  329. }
  330. ],
  331. async err => {
  332. if (err) {
  333. err = await utils.runJob("GET_ERROR", { error: err });
  334. console.log(
  335. "ERROR",
  336. "QUEUE_IMPORT",
  337. `Importing a YouTube playlist to the queue failed for user "${session.userId}". "${err}"`
  338. );
  339. return cb({ status: "failure", message: err });
  340. }
  341. console.log(
  342. "SUCCESS",
  343. "QUEUE_IMPORT",
  344. `Successfully imported a YouTube playlist to the queue for user "${session.userId}".`
  345. );
  346. return cb({
  347. status: "success",
  348. message: "Playlist has been successfully imported."
  349. });
  350. }
  351. );
  352. })
  353. };
  354. export default lib;