queueSongs.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. "use strict";
  2. const config = require("config");
  3. const async = require("async");
  4. const request = require("request");
  5. const hooks = require("./hooks");
  6. const db = require("../db");
  7. const utils = require("../utils");
  8. const cache = require("../cache");
  9. // const logger = moduleManager.modules["logger"];
  10. cache.runJob("SUB", {
  11. channel: "queue.newSong",
  12. cb: async (songId) => {
  13. const queueSongModel = await db.runJob("GET_MODEL", {
  14. modelName: "queueSong",
  15. });
  16. queueSongModel.findOne({ _id: songId }, (err, song) => {
  17. utils.runJob("EMIT_TO_ROOM", {
  18. room: "admin.queue",
  19. args: ["event:admin.queueSong.added", song],
  20. });
  21. });
  22. },
  23. });
  24. cache.runJob("SUB", {
  25. channel: "queue.removedSong",
  26. cb: (songId) => {
  27. utils.runJob("EMIT_TO_ROOM", {
  28. room: "admin.queue",
  29. args: ["event:admin.queueSong.removed", songId],
  30. });
  31. },
  32. });
  33. cache.runJob("SUB", {
  34. channel: "queue.update",
  35. cb: async (songId) => {
  36. const queueSongModel = await db.runJob("GET_MODEL", {
  37. modelName: "queueSong",
  38. });
  39. queueSongModel.findOne({ _id: songId }, (err, song) => {
  40. utils.runJob("EMIT_TO_ROOM", {
  41. room: "admin.queue",
  42. args: ["event:admin.queueSong.updated", song],
  43. });
  44. });
  45. },
  46. });
  47. let lib = {
  48. /**
  49. * Returns the length of the queue songs list
  50. *
  51. * @param session
  52. * @param cb
  53. */
  54. length: hooks.adminRequired(async (session, cb) => {
  55. const queueSongModel = await db.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 utils.runJob("GET_ERROR", { error: err });
  67. console.log(
  68. "ERROR",
  69. "QUEUE_SONGS_LENGTH",
  70. `Failed to get length from queue songs. "${err}"`
  71. );
  72. return cb({ status: "failure", message: err });
  73. }
  74. console.log(
  75. "SUCCESS",
  76. "QUEUE_SONGS_LENGTH",
  77. `Got length from queue songs successfully.`
  78. );
  79. cb(count);
  80. }
  81. );
  82. }),
  83. /**
  84. * Gets a set of queue songs
  85. *
  86. * @param session
  87. * @param set - the set number to return
  88. * @param cb
  89. */
  90. getSet: hooks.adminRequired(async (session, set, cb) => {
  91. const queueSongModel = await db.runJob("GET_MODEL", {
  92. modelName: "queueSong",
  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 utils.runJob("GET_ERROR", { error: err });
  107. console.log(
  108. "ERROR",
  109. "QUEUE_SONGS_GET_SET",
  110. `Failed to get set from queue songs. "${err}"`
  111. );
  112. return cb({ status: "failure", message: err });
  113. }
  114. console.log(
  115. "SUCCESS",
  116. "QUEUE_SONGS_GET_SET",
  117. `Got set from queue songs successfully.`
  118. );
  119. cb(songs);
  120. }
  121. );
  122. }),
  123. /**
  124. * Updates a queuesong
  125. *
  126. * @param {Object} session - the session object automatically added by socket.io
  127. * @param {String} songId - the id of the queuesong that gets updated
  128. * @param {Object} updatedSong - the object of the updated queueSong
  129. * @param {Function} cb - gets called with the result
  130. */
  131. update: hooks.adminRequired(async (session, songId, updatedSong, cb) => {
  132. const queueSongModel = await db.runJob("GET_MODEL", {
  133. modelName: "queueSong",
  134. });
  135. async.waterfall(
  136. [
  137. (next) => {
  138. queueSongModel.findOne({ _id: songId }, next);
  139. },
  140. (song, next) => {
  141. if (!song) return next("Song not found");
  142. let updated = false;
  143. let $set = {};
  144. for (let prop in updatedSong)
  145. if (updatedSong[prop] !== song[prop])
  146. $set[prop] = updatedSong[prop];
  147. updated = true;
  148. if (!updated) return next("No properties changed");
  149. queueSongModel.updateOne(
  150. { _id: songId },
  151. { $set },
  152. { runValidators: true },
  153. next
  154. );
  155. },
  156. ],
  157. async (err) => {
  158. if (err) {
  159. err = await utils.runJob("GET_ERROR", { error: err });
  160. console.log(
  161. "ERROR",
  162. "QUEUE_UPDATE",
  163. `Updating queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  164. );
  165. return cb({ status: "failure", message: err });
  166. }
  167. cache.runJob("PUB", { channel: "queue.update", value: songId });
  168. console.log(
  169. "SUCCESS",
  170. "QUEUE_UPDATE",
  171. `User "${session.userId}" successfully update queuesong "${songId}".`
  172. );
  173. return cb({
  174. status: "success",
  175. message: "Successfully updated song.",
  176. });
  177. }
  178. );
  179. }),
  180. /**
  181. * Removes a queuesong
  182. *
  183. * @param {Object} session - the session object automatically added by socket.io
  184. * @param {String} songId - the id of the queuesong that gets removed
  185. * @param {Function} cb - gets called with the result
  186. */
  187. remove: hooks.adminRequired(async (session, songId, cb, userId) => {
  188. const queueSongModel = await db.runJob("GET_MODEL", {
  189. modelName: "queueSong",
  190. });
  191. async.waterfall(
  192. [
  193. (next) => {
  194. queueSongModel.deleteOne({ _id: songId }, next);
  195. },
  196. ],
  197. async (err) => {
  198. if (err) {
  199. err = await utils.runJob("GET_ERROR", { error: err });
  200. console.log(
  201. "ERROR",
  202. "QUEUE_REMOVE",
  203. `Removing queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  204. );
  205. return cb({ status: "failure", message: err });
  206. }
  207. cache.runJob("PUB", {
  208. channel: "queue.removedSong",
  209. value: songId,
  210. });
  211. console.log(
  212. "SUCCESS",
  213. "QUEUE_REMOVE",
  214. `User "${session.userId}" successfully removed queuesong "${songId}".`
  215. );
  216. return cb({
  217. status: "success",
  218. message: "Successfully updated song.",
  219. });
  220. }
  221. );
  222. }),
  223. /**
  224. * Creates a queuesong
  225. *
  226. * @param {Object} session - the session object automatically added by socket.io
  227. * @param {String} songId - the id of the song that gets added
  228. * @param {Function} cb - gets called with the result
  229. */
  230. add: hooks.loginRequired(async (session, songId, cb) => {
  231. let requestedAt = Date.now();
  232. const songModel = await db.runJob("GET_MODEL", { modelName: "song" });
  233. const userModel = await db.runJob("GET_MODEL", { modelName: "user" });
  234. const queueSongModel = await db.runJob("GET_MODEL", {
  235. modelName: "queueSong",
  236. });
  237. async.waterfall(
  238. [
  239. (next) => {
  240. queueSongModel.findOne({ songId }, next);
  241. },
  242. (song, next) => {
  243. if (song) return next("This song is already in the queue.");
  244. songModel.findOne({ songId }, next);
  245. },
  246. // Get YouTube data from id
  247. (song, next) => {
  248. if (song) return next("This song has already been added.");
  249. //TODO Add err object as first param of callback
  250. utils
  251. .runJob("GET_SONG_FROM_YOUTUBE", { songId })
  252. .then((response) => {
  253. const song = response.song;
  254. song.duration = -1;
  255. song.artists = [];
  256. song.genres = [];
  257. song.skipDuration = 0;
  258. song.thumbnail = `${config.get(
  259. "domain"
  260. )}/assets/notes.png`;
  261. song.explicit = false;
  262. song.requestedBy = session.userId;
  263. song.requestedAt = requestedAt;
  264. next(null, song);
  265. })
  266. .catch(next);
  267. },
  268. /*(newSong, next) => {
  269. utils.getSongFromSpotify(newSong, (err, song) => {
  270. if (!song) next(null, newSong);
  271. else next(err, song);
  272. });
  273. },*/
  274. (newSong, next) => {
  275. const song = new queueSongModel(newSong);
  276. song.save({ validateBeforeSave: false }, (err, song) => {
  277. if (err) return next(err);
  278. next(null, song);
  279. });
  280. },
  281. (newSong, next) => {
  282. userModel.findOne({ _id: session.userId }, (err, user) => {
  283. if (err) next(err, newSong);
  284. else {
  285. user.statistics.songsRequested =
  286. user.statistics.songsRequested + 1;
  287. user.save((err) => {
  288. if (err) return next(err, newSong);
  289. else next(null, newSong);
  290. });
  291. }
  292. });
  293. },
  294. ],
  295. async (err, newSong) => {
  296. if (err) {
  297. err = await utils.runJob("GET_ERROR", { error: err });
  298. console.log(
  299. "ERROR",
  300. "QUEUE_ADD",
  301. `Adding queuesong "${songId}" failed for user ${session.userId}. "${err}"`
  302. );
  303. return cb({ status: "failure", message: err });
  304. }
  305. cache.runJob("PUB", {
  306. channel: "queue.newSong",
  307. value: newSong._id,
  308. });
  309. console.log(
  310. "SUCCESS",
  311. "QUEUE_ADD",
  312. `User "${session.userId}" successfully added queuesong "${songId}".`
  313. );
  314. return cb({
  315. status: "success",
  316. message: "Successfully added that song to the queue",
  317. });
  318. }
  319. );
  320. }),
  321. /**
  322. * Adds a set of songs to the queue
  323. *
  324. * @param {Object} session - the session object automatically added by socket.io
  325. * @param {String} url - the url of the the YouTube playlist
  326. * @param {Function} cb - gets called with the result
  327. */
  328. addSetToQueue: hooks.loginRequired((session, url, cb) => {
  329. async.waterfall(
  330. [
  331. (next) => {
  332. utils
  333. .runJob("GET_PLAYLIST_FROM_YOUTUBE", {
  334. url,
  335. musicOnly: false,
  336. })
  337. .then((songIds) => next(null, songIds))
  338. .catch(next);
  339. },
  340. (songIds, next) => {
  341. let processed = 0;
  342. function checkDone() {
  343. if (processed === songIds.length) next();
  344. }
  345. for (let s = 0; s < songIds.length; s++) {
  346. lib.add(session, songIds[s], () => {
  347. processed++;
  348. checkDone();
  349. });
  350. }
  351. },
  352. ],
  353. async (err) => {
  354. if (err) {
  355. err = await utils.runJob("GET_ERROR", { error: err });
  356. console.log(
  357. "ERROR",
  358. "QUEUE_IMPORT",
  359. `Importing a YouTube playlist to the queue failed for user "${session.userId}". "${err}"`
  360. );
  361. return cb({ status: "failure", message: err });
  362. } else {
  363. console.log(
  364. "SUCCESS",
  365. "QUEUE_IMPORT",
  366. `Successfully imported a YouTube playlist to the queue for user "${session.userId}".`
  367. );
  368. cb({
  369. status: "success",
  370. message: "Playlist has been successfully imported.",
  371. });
  372. }
  373. }
  374. );
  375. }),
  376. };
  377. module.exports = lib;