utils.js 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. import config from "config";
  2. import async from "async";
  3. import crypto from "crypto";
  4. import request from "request";
  5. import CoreClass from "../core";
  6. let UtilsModule;
  7. let IOModule;
  8. let SpotifyModule;
  9. let CacheModule;
  10. class _UtilsModule extends CoreClass {
  11. // eslint-disable-next-line require-jsdoc
  12. constructor() {
  13. super("utils");
  14. this.youtubeRequestCallbacks = [];
  15. this.youtubeRequestsPending = 0;
  16. this.youtubeRequestsActive = false;
  17. UtilsModule = this;
  18. }
  19. /**
  20. * Initialises the utils module
  21. *
  22. * @returns {Promise} - returns promise (reject, resolve)
  23. */
  24. initialize() {
  25. return new Promise(resolve => {
  26. IOModule = this.moduleManager.modules.io;
  27. SpotifyModule = this.moduleManager.modules.spotify;
  28. CacheModule = this.moduleManager.modules.cache;
  29. resolve();
  30. });
  31. }
  32. /**
  33. * Parses the cookie into a readable object
  34. *
  35. * @param {object} payload - object that contains the payload
  36. * @param {string} payload.cookieString - the cookie string
  37. * @returns {Promise} - returns promise (reject, resolve)
  38. */
  39. PARSE_COOKIES(payload) {
  40. return new Promise((resolve, reject) => {
  41. const cookies = {};
  42. if (typeof payload.cookieString !== "string") return reject(new Error("Cookie string is not a string"));
  43. // eslint-disable-next-line array-callback-return
  44. payload.cookieString.split("; ").map(cookie => {
  45. cookies[cookie.substring(0, cookie.indexOf("="))] = cookie.substring(
  46. cookie.indexOf("=") + 1,
  47. cookie.length
  48. );
  49. });
  50. return resolve(cookies);
  51. });
  52. }
  53. // COOKIES_TO_STRING() {//cookies
  54. // return new Promise((resolve, reject) => {
  55. // let newCookie = [];
  56. // for (let prop in cookie) {
  57. // newCookie.push(prop + "=" + cookie[prop]);
  58. // }
  59. // return newCookie.join("; ");
  60. // });
  61. // }
  62. /**
  63. * Removes a cookie by name
  64. *
  65. * @param {object} payload - object that contains the payload
  66. * @param {object} payload.cookieString - the cookie string
  67. * @param {string} payload.cookieName - the unique name of the cookie
  68. * @returns {Promise} - returns promise (reject, resolve)
  69. */
  70. REMOVE_COOKIE(payload) {
  71. return new Promise((resolve, reject) => {
  72. let cookies;
  73. try {
  74. cookies = UtilsModule.runJob(
  75. "PARSE_COOKIES",
  76. {
  77. cookieString: payload.cookieString
  78. },
  79. this
  80. );
  81. } catch (err) {
  82. return reject(err);
  83. }
  84. delete cookies[payload.cookieName];
  85. return resolve(this.toString(cookies));
  86. });
  87. }
  88. /**
  89. * Replaces any html reserved characters in a string with html entities
  90. *
  91. * @param {object} payload - object that contains the payload
  92. * @param {string} payload.str - the string to replace characters with html entities
  93. * @returns {Promise} - returns promise (reject, resolve)
  94. */
  95. HTML_ENTITIES(payload) {
  96. return new Promise(resolve => {
  97. resolve(
  98. String(payload.str)
  99. .replace(/&/g, "&")
  100. .replace(/</g, "&lt;")
  101. .replace(/>/g, "&gt;")
  102. .replace(/"/g, "&quot;")
  103. );
  104. });
  105. }
  106. /**
  107. * Generates a random string of a specified length
  108. *
  109. * @param {object} payload - object that contains the payload
  110. * @param {number} payload.length - the length the random string should be
  111. * @returns {Promise} - returns promise (reject, resolve)
  112. */
  113. async GENERATE_RANDOM_STRING(payload) {
  114. const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
  115. const promises = [];
  116. for (let i = 0; i < payload.length; i += 1) {
  117. promises.push(
  118. UtilsModule.runJob(
  119. "GET_RANDOM_NUMBER",
  120. {
  121. min: 0,
  122. max: chars.length - 1
  123. },
  124. this
  125. )
  126. );
  127. }
  128. const randomNums = await Promise.all(promises);
  129. const randomChars = [];
  130. for (let i = 0; i < payload.length; i += 1) {
  131. randomChars.push(chars[randomNums[i]]);
  132. }
  133. return new Promise(resolve => resolve(randomChars.join("")));
  134. }
  135. /**
  136. * Returns a socket object from a socket identifier
  137. *
  138. * @param {object} payload - object that contains the payload
  139. * @param {string} payload.socketId - the socket id
  140. * @returns {Promise} - returns promise (reject, resolve)
  141. */
  142. async GET_SOCKET_FROM_ID(payload) {
  143. // socketId
  144. const io = await IOModule.runJob("IO", {}, this);
  145. return new Promise(resolve => resolve(io.sockets.sockets[payload.socketId]));
  146. }
  147. /**
  148. * Creates a random number within a range
  149. *
  150. * @param {object} payload - object that contains the payload
  151. * @param {number} payload.min - the minimum number the result should be
  152. * @param {number} payload.max - the maximum number the result should be
  153. * @returns {Promise} - returns promise (reject, resolve)
  154. */
  155. GET_RANDOM_NUMBER(payload) {
  156. // min, max
  157. return new Promise(resolve =>
  158. resolve(Math.floor(Math.random() * (payload.max - payload.min + 1)) + payload.min)
  159. );
  160. }
  161. /**
  162. * Converts ISO8601 time format (YouTube API) to HH:MM:SS
  163. *
  164. * @param {object} payload - object contaiing the payload
  165. * @param {string} payload.duration - string in the format of ISO8601
  166. * @returns {Promise} - returns a promise (resolve, reject)
  167. */
  168. CONVERT_TIME(payload) {
  169. // duration
  170. return new Promise(resolve => {
  171. let { duration } = payload;
  172. let a = duration.match(/\d+/g);
  173. if (duration.indexOf("M") >= 0 && duration.indexOf("H") === -1 && duration.indexOf("S") === -1) {
  174. a = [0, a[0], 0];
  175. }
  176. if (duration.indexOf("H") >= 0 && duration.indexOf("M") === -1) {
  177. a = [a[0], 0, a[1]];
  178. }
  179. if (duration.indexOf("H") >= 0 && duration.indexOf("M") === -1 && duration.indexOf("S") === -1) {
  180. a = [a[0], 0, 0];
  181. }
  182. duration = 0;
  183. if (a.length === 3) {
  184. duration += parseInt(a[0]) * 3600;
  185. duration += parseInt(a[1]) * 60;
  186. duration += parseInt(a[2]);
  187. }
  188. if (a.length === 2) {
  189. duration += parseInt(a[0]) * 60;
  190. duration += parseInt(a[1]);
  191. }
  192. if (a.length === 1) {
  193. duration += parseInt(a[0]);
  194. }
  195. const hours = Math.floor(duration / 3600);
  196. const minutes = Math.floor((duration % 3600) / 60);
  197. const seconds = Math.floor((duration % 3600) % 60);
  198. resolve(
  199. (hours < 10 ? `0${hours}:` : `${hours}:`) +
  200. (minutes < 10 ? `0${minutes}:` : `${minutes}:`) +
  201. (seconds < 10 ? `0${seconds}` : seconds)
  202. );
  203. });
  204. }
  205. /**
  206. * Creates a random identifier for e.g. sessionId
  207. *
  208. * @returns {Promise} - returns promise (reject, resolve)
  209. */
  210. GUID() {
  211. return new Promise(resolve => {
  212. resolve(
  213. [1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1]
  214. .map(b =>
  215. b
  216. ? Math.floor((1 + Math.random()) * 0x10000)
  217. .toString(16)
  218. .substring(1)
  219. : "-"
  220. )
  221. .join("")
  222. );
  223. });
  224. }
  225. // UNKNOWN
  226. // eslint-disable-next-line require-jsdoc
  227. async SOCKET_FROM_SESSION(payload) {
  228. // socketId
  229. const io = await IOModule.runJob("IO", {}, this);
  230. return new Promise((resolve, reject) => {
  231. const ns = io.of("/");
  232. if (ns) {
  233. return resolve(ns.connected[payload.socketId]);
  234. }
  235. return reject();
  236. });
  237. }
  238. /**
  239. * Gets all sockets for a specified session id
  240. *
  241. * @param {object} payload - object containing the payload
  242. * @param {string} payload.sessionId - user session id
  243. * @returns {Promise} - returns promise (reject, resolve)
  244. */
  245. async SOCKETS_FROM_SESSION_ID(payload) {
  246. const io = await IOModule.runJob("IO", {}, this);
  247. return new Promise(resolve => {
  248. const ns = io.of("/");
  249. const sockets = [];
  250. if (ns) {
  251. return async.each(
  252. Object.keys(ns.connected),
  253. (id, next) => {
  254. const { session } = ns.connected[id];
  255. if (session.sessionId === payload.sessionId) sockets.push(session.sessionId);
  256. next();
  257. },
  258. () => {
  259. resolve({ sockets });
  260. }
  261. );
  262. }
  263. return resolve();
  264. });
  265. }
  266. /**
  267. * Returns any sockets for a specific user
  268. *
  269. * @param {object} payload - object that contains the payload
  270. * @param {string} payload.userId - the user id
  271. * @returns {Promise} - returns promise (reject, resolve)
  272. */
  273. async SOCKETS_FROM_USER(payload) {
  274. const io = await IOModule.runJob("IO", {}, this);
  275. return new Promise((resolve, reject) => {
  276. const ns = io.of("/");
  277. const sockets = [];
  278. if (ns) {
  279. return async.each(
  280. Object.keys(ns.connected),
  281. (id, next) => {
  282. const { session } = ns.connected[id];
  283. CacheModule.runJob(
  284. "HGET",
  285. {
  286. table: "sessions",
  287. key: session.sessionId
  288. },
  289. this
  290. )
  291. .then(session => {
  292. if (session && session.userId === payload.userId) sockets.push(ns.connected[id]);
  293. next();
  294. })
  295. .catch(err => {
  296. next(err);
  297. });
  298. },
  299. err => {
  300. if (err) return reject(err);
  301. return resolve({ sockets });
  302. }
  303. );
  304. }
  305. return resolve();
  306. });
  307. }
  308. /**
  309. * Returns any sockets from a specific ip address
  310. *
  311. * @param {object} payload - object that contains the payload
  312. * @param {string} payload.ip - the ip address in question
  313. * @returns {Promise} - returns promise (reject, resolve)
  314. */
  315. async SOCKETS_FROM_IP(payload) {
  316. const io = await IOModule.runJob("IO", {}, this);
  317. return new Promise(resolve => {
  318. const ns = io.of("/");
  319. const sockets = [];
  320. if (ns) {
  321. return async.each(
  322. Object.keys(ns.connected),
  323. (id, next) => {
  324. const { session } = ns.connected[id];
  325. CacheModule.runJob(
  326. "HGET",
  327. {
  328. table: "sessions",
  329. key: session.sessionId
  330. },
  331. this
  332. )
  333. .then(session => {
  334. if (session && ns.connected[id].ip === payload.ip) sockets.push(ns.connected[id]);
  335. next();
  336. })
  337. .catch(() => next());
  338. },
  339. () => {
  340. resolve({ sockets });
  341. }
  342. );
  343. }
  344. return resolve();
  345. });
  346. }
  347. /**
  348. * Returns any sockets from a specific user without using redis/cache
  349. *
  350. * @param {object} payload - object that contains the payload
  351. * @param {string} payload.userId - the id of the user in question
  352. * @returns {Promise} - returns promise (reject, resolve)
  353. */
  354. async SOCKETS_FROM_USER_WITHOUT_CACHE(payload) {
  355. const io = await IOModule.runJob("IO", {}, this);
  356. return new Promise(resolve => {
  357. const ns = io.of("/");
  358. const sockets = [];
  359. if (ns) {
  360. return async.each(
  361. Object.keys(ns.connected),
  362. (id, next) => {
  363. const { session } = ns.connected[id];
  364. if (session.userId === payload.userId) sockets.push(ns.connected[id]);
  365. next();
  366. },
  367. () => {
  368. resolve({ sockets });
  369. }
  370. );
  371. }
  372. return resolve();
  373. });
  374. }
  375. /**
  376. * Allows a socket to leave any rooms they are connected to
  377. *
  378. * @param {object} payload - object that contains the payload
  379. * @param {string} payload.socketId - the id of the socket which should leave all their rooms
  380. * @returns {Promise} - returns promise (reject, resolve)
  381. */
  382. async SOCKET_LEAVE_ROOMS(payload) {
  383. const socket = await UtilsModule.runJob(
  384. "SOCKET_FROM_SESSION",
  385. {
  386. socketId: payload.socketId
  387. },
  388. this
  389. );
  390. return new Promise(resolve => {
  391. const { rooms } = socket;
  392. Object.keys(rooms).forEach(roomKey => {
  393. const room = rooms[roomKey];
  394. socket.leave(room);
  395. });
  396. return resolve();
  397. });
  398. }
  399. /**
  400. * Allows a socket to join a specified room
  401. *
  402. * @param {object} payload - object that contains the payload
  403. * @param {string} payload.socketId - the id of the socket which should join the room
  404. * @param {object} payload.room - the object representing the room the socket should join
  405. * @returns {Promise} - returns promise (reject, resolve)
  406. */
  407. async SOCKET_JOIN_ROOM(payload) {
  408. const socket = await UtilsModule.runJob(
  409. "SOCKET_FROM_SESSION",
  410. {
  411. socketId: payload.socketId
  412. },
  413. this
  414. );
  415. return new Promise(resolve => {
  416. const { rooms } = socket;
  417. Object.keys(rooms).forEach(roomKey => {
  418. const room = rooms[roomKey];
  419. socket.leave(room);
  420. });
  421. socket.join(payload.room);
  422. return resolve();
  423. });
  424. }
  425. // UNKNOWN
  426. // eslint-disable-next-line require-jsdoc
  427. async SOCKET_JOIN_SONG_ROOM(payload) {
  428. // socketId, room
  429. const socket = await UtilsModule.runJob(
  430. "SOCKET_FROM_SESSION",
  431. {
  432. socketId: payload.socketId
  433. },
  434. this
  435. );
  436. return new Promise(resolve => {
  437. const { rooms } = socket;
  438. Object.keys(rooms).forEach(roomKey => {
  439. const room = rooms[roomKey];
  440. if (room.indexOf("song.") !== -1) socket.leave(room);
  441. });
  442. socket.join(payload.room);
  443. return resolve();
  444. });
  445. }
  446. // UNKNOWN
  447. // eslint-disable-next-line require-jsdoc
  448. SOCKETS_JOIN_SONG_ROOM(payload) {
  449. // sockets, room
  450. return new Promise(resolve => {
  451. Object.keys(payload.sockets).forEach(socketKey => {
  452. const socket = payload.sockets[socketKey];
  453. const { rooms } = socket;
  454. Object.keys(rooms).forEach(roomKey => {
  455. const room = rooms[roomKey];
  456. if (room.indexOf("song.") !== -1) socket.leave(room);
  457. });
  458. socket.join(payload.room);
  459. });
  460. return resolve();
  461. });
  462. }
  463. // UNKNOWN
  464. // eslint-disable-next-line require-jsdoc
  465. SOCKETS_LEAVE_SONG_ROOMS(payload) {
  466. // sockets
  467. return new Promise(resolve => {
  468. Object.keys(payload.sockets).forEach(socketKey => {
  469. const socket = payload.sockets[socketKey];
  470. const { rooms } = socket;
  471. Object.keys(rooms).forEach(roomKey => {
  472. const room = rooms[roomKey];
  473. if (room.indexOf("song.") !== -1) socket.leave(room);
  474. });
  475. });
  476. resolve();
  477. });
  478. }
  479. /**
  480. * Emits arguments to any sockets that are in a specified a room
  481. *
  482. * @param {object} payload - object that contains the payload
  483. * @param {string} payload.room - the name of the room to emit arguments
  484. * @param {object} payload.args - any arguments to be emitted to the sockets in the specific room
  485. * @returns {Promise} - returns promise (reject, resolve)
  486. */
  487. async EMIT_TO_ROOM(payload) {
  488. const io = await IOModule.runJob("IO", {}, this);
  489. return new Promise(resolve => {
  490. const { sockets } = io.sockets;
  491. Object.keys(sockets).forEach(socketKey => {
  492. const socket = sockets[socketKey];
  493. if (socket.rooms[payload.room]) {
  494. socket.emit(...payload.args);
  495. }
  496. });
  497. return resolve();
  498. });
  499. }
  500. /**
  501. * Gets any sockets connected to a room
  502. *
  503. * @param {object} payload - object that contains the payload
  504. * @param {string} payload.room - the name of the room
  505. * @returns {Promise} - returns promise (reject, resolve)
  506. */
  507. async GET_ROOM_SOCKETS(payload) {
  508. const io = await IOModule.runJob("IO", {}, this);
  509. return new Promise(resolve => {
  510. const { sockets } = io.sockets;
  511. const roomSockets = [];
  512. Object.keys(sockets).forEach(socketKey => {
  513. const socket = sockets[socketKey];
  514. if (socket.rooms[payload.room]) roomSockets.push(socket);
  515. });
  516. return resolve(roomSockets);
  517. });
  518. }
  519. /**
  520. * Gets the details of a song using the YouTube API
  521. *
  522. * @param {object} payload - object that contains the payload
  523. * @param {string} payload.songId - the YouTube API id of the song
  524. * @returns {Promise} - returns promise (reject, resolve)
  525. */
  526. GET_SONG_FROM_YOUTUBE(payload) {
  527. // songId, cb
  528. return new Promise((resolve, reject) => {
  529. this.youtubeRequestCallbacks.push({
  530. cb: () => {
  531. this.youtubeRequestsActive = true;
  532. const youtubeParams = [
  533. "part=snippet,contentDetails,statistics,status",
  534. `id=${encodeURIComponent(payload.songId)}`,
  535. `key=${config.get("apis.youtube.key")}`
  536. ].join("&");
  537. request(`https://www.googleapis.com/youtube/v3/videos?${youtubeParams}`, (err, res, body) => {
  538. this.youtubeRequestCallbacks.splice(0, 1);
  539. if (this.youtubeRequestCallbacks.length > 0) {
  540. this.youtubeRequestCallbacks[0].cb(this.youtubeRequestCallbacks[0].songId);
  541. } else this.youtubeRequestsActive = false;
  542. if (err) {
  543. console.error(err);
  544. return null;
  545. }
  546. body = JSON.parse(body);
  547. if (body.error) {
  548. console.log("ERROR", "GET_SONG_FROM_YOUTUBE", `${body.error.message}`);
  549. return reject(new Error("An error has occured. Please try again later."));
  550. }
  551. if (body.items[0] === undefined)
  552. return reject(
  553. new Error("The specified video does not exist or cannot be publicly accessed.")
  554. );
  555. // TODO Clean up duration converter
  556. let dur = body.items[0].contentDetails.duration;
  557. dur = dur.replace("PT", "");
  558. let duration = 0;
  559. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  560. v2 = Number(v2);
  561. duration = v2 * 60 * 60;
  562. return "";
  563. });
  564. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  565. v2 = Number(v2);
  566. duration += v2 * 60;
  567. return "";
  568. });
  569. // eslint-disable-next-line no-unused-vars
  570. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  571. v2 = Number(v2);
  572. duration += v2;
  573. return "";
  574. });
  575. const song = {
  576. songId: body.items[0].id,
  577. title: body.items[0].snippet.title,
  578. duration
  579. };
  580. return resolve({ song });
  581. });
  582. },
  583. songId: payload.songId
  584. });
  585. if (!this.youtubeRequestsActive) {
  586. this.youtubeRequestCallbacks[0].cb(this.youtubeRequestCallbacks[0].songId);
  587. }
  588. });
  589. }
  590. /**
  591. * Filters a list of YouTube videos so that they only contains videos with music
  592. *
  593. * @param {object} payload - object that contains the payload
  594. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  595. * @returns {Promise} - returns promise (reject, resolve)
  596. */
  597. FILTER_MUSIC_VIDEOS_YOUTUBE(payload) {
  598. // videoIds, cb
  599. return new Promise((resolve, reject) => {
  600. /**
  601. * @param {Function} cb2 - callback
  602. */
  603. function getNextPage(cb2) {
  604. const localVideoIds = payload.videoIds.splice(0, 50);
  605. const youtubeParams = [
  606. "part=topicDetails",
  607. `id=${encodeURIComponent(localVideoIds.join(","))}`,
  608. `maxResults=50`,
  609. `key=${config.get("apis.youtube.key")}`
  610. ].join("&");
  611. request(`https://www.googleapis.com/youtube/v3/videos?${youtubeParams}`, (err, res, body) => {
  612. if (err) {
  613. console.error(err);
  614. return reject(new Error("Failed to find playlist from YouTube"));
  615. }
  616. body = JSON.parse(body);
  617. if (body.error) {
  618. console.log("ERROR", "FILTER_MUSIC_VIDEOS_YOUTUBE", `${body.error.message}`);
  619. return reject(new Error("An error has occured. Please try again later."));
  620. }
  621. const songIds = [];
  622. body.items.forEach(item => {
  623. const songId = item.id;
  624. if (!item.topicDetails) return;
  625. if (item.topicDetails.relevantTopicIds.indexOf("/m/04rlf") !== -1) {
  626. songIds.push(songId);
  627. }
  628. });
  629. if (payload.videoIds.length > 0) {
  630. return getNextPage(newSongIds => {
  631. cb2(songIds.concat(newSongIds));
  632. });
  633. }
  634. return cb2(songIds);
  635. });
  636. }
  637. if (payload.videoIds.length === 0) resolve({ songIds: [] });
  638. else getNextPage(songIds => resolve({ songIds }));
  639. });
  640. }
  641. /**
  642. * Returns an array of songs taken from a YouTube playlist
  643. *
  644. * @param {object} payload - object that contains the payload
  645. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the playlist
  646. * @param {string} payload.url - the url of the YouTube playlist
  647. * @returns {Promise} - returns promise (reject, resolve)
  648. */
  649. GET_PLAYLIST_FROM_YOUTUBE(payload) {
  650. // payload includes: url, musicOnly
  651. return new Promise((resolve, reject) => {
  652. const local = this;
  653. const name = "list".replace(/[\\[]/, "\\[").replace(/[\]]/, "\\]");
  654. const regex = new RegExp(`[\\?&]${name}=([^&#]*)`);
  655. const splitQuery = regex.exec(payload.url);
  656. if (!splitQuery) {
  657. console.log("ERROR", "GET_PLAYLIST_FROM_YOUTUBE", "Invalid YouTube playlist URL query.");
  658. return reject(new Error("An error has occured. Please try again later."));
  659. }
  660. const playlistId = splitQuery[1];
  661. /**
  662. * @param {string} pageToken - page token for YouTube API
  663. * @param {Array} songs - array of songs
  664. */
  665. function getPage(pageToken, songs) {
  666. const nextPageToken = pageToken ? `pageToken=${pageToken}` : "";
  667. const youtubeParams = [
  668. "part=contentDetails",
  669. `playlistId=${encodeURIComponent(playlistId)}`,
  670. `maxResults=50`,
  671. `key=${config.get("apis.youtube.key")}`,
  672. nextPageToken
  673. ].join("&");
  674. request(
  675. `https://www.googleapis.com/youtube/v3/playlistItems?${youtubeParams}`,
  676. async (err, res, body) => {
  677. if (err) {
  678. console.error(err);
  679. return reject(new Error("Failed to find playlist from YouTube"));
  680. }
  681. body = JSON.parse(body);
  682. if (body.error) {
  683. console.log("ERROR", "GET_PLAYLIST_FROM_YOUTUBE", `${body.error.message}`);
  684. return reject(new Error("An error has occured. Please try again later."));
  685. }
  686. songs = songs.concat(body.items);
  687. if (body.nextPageToken) return getPage(body.nextPageToken, songs);
  688. songs = songs.map(song => song.contentDetails.videoId);
  689. if (!payload.musicOnly) return resolve({ songs });
  690. return local
  691. .runJob(
  692. "FILTER_MUSIC_VIDEOS_YOUTUBE",
  693. {
  694. videoIds: songs.slice()
  695. },
  696. this
  697. )
  698. .then(filteredSongs => {
  699. resolve({ filteredSongs, songs });
  700. });
  701. }
  702. );
  703. }
  704. return getPage(null, []);
  705. });
  706. }
  707. /**
  708. * Gets the details of a song from the Spotify API
  709. *
  710. * @param {object} payload - object that contains the payload
  711. * @param {object} payload.song - the song object (song.title etc.)
  712. * @returns {Promise} - returns promise (reject, resolve)
  713. */
  714. async GET_SONG_FROM_SPOTIFY(payload) {
  715. // song
  716. const token = await SpotifyModule.runJob("GET_TOKEN", {}, this);
  717. return new Promise((resolve, reject) => {
  718. if (!config.get("apis.spotify.enabled")) return reject(new Error("Spotify is not enabled."));
  719. const song = { ...payload.song };
  720. const spotifyParams = [`q=${encodeURIComponent(payload.song.title)}`, `type=track`].join("&");
  721. const options = {
  722. url: `https://api.spotify.com/v1/search?${spotifyParams}`,
  723. headers: {
  724. Authorization: `Bearer ${token}`
  725. }
  726. };
  727. return request(options, (err, res, body) => {
  728. if (err) console.error(err);
  729. body = JSON.parse(body);
  730. if (body.error) console.error(body.error);
  731. Object.keys(body).forEach(bodyKey => {
  732. const { items } = body[bodyKey];
  733. Object.keys(items).every(itemsKey => {
  734. const item = items[itemsKey];
  735. let hasArtist = false;
  736. for (let k = 0; k < item.artists.length; k += 1) {
  737. const artist = item.artists[k];
  738. if (song.title.indexOf(artist.name) !== -1) hasArtist = true;
  739. }
  740. if (hasArtist && song.title.indexOf(item.name) !== -1) {
  741. song.duration = item.duration_ms / 1000;
  742. song.artists = item.artists.map(artist => artist.name);
  743. song.title = item.name;
  744. song.explicit = item.explicit;
  745. song.thumbnail = item.album.images[1].url;
  746. return false;
  747. }
  748. return true;
  749. });
  750. });
  751. resolve({ song });
  752. });
  753. });
  754. }
  755. /**
  756. * Returns the details of multiple songs from the Spotify API
  757. *
  758. * @param {object} payload - object that contains the payload
  759. * @param {object} payload.title - the query/title of a song to search the API with
  760. * @returns {Promise} - returns promise (reject, resolve)
  761. */
  762. async GET_SONGS_FROM_SPOTIFY(payload) {
  763. // title, artist
  764. const token = await SpotifyModule.runJob("GET_TOKEN", {}, this);
  765. return new Promise((resolve, reject) => {
  766. if (!config.get("apis.spotify.enabled")) return reject(new Error("Spotify is not enabled."));
  767. const spotifyParams = [`q=${encodeURIComponent(payload.title)}`, `type=track`].join("&");
  768. const options = {
  769. url: `https://api.spotify.com/v1/search?${spotifyParams}`,
  770. headers: {
  771. Authorization: `Bearer ${token}`
  772. }
  773. };
  774. return request(options, (err, res, body) => {
  775. if (err) return console.error(err);
  776. body = JSON.parse(body);
  777. if (body.error) return console.error(body.error);
  778. const songs = [];
  779. Object.keys(body).forEach(bodyKey => {
  780. const { items } = body[bodyKey];
  781. Object.keys(items).forEach(itemsKey => {
  782. const item = items[itemsKey];
  783. let hasArtist = false;
  784. for (let k = 0; k < item.artists.length; k += 1) {
  785. const localArtist = item.artists[k];
  786. if (payload.artist.toLowerCase() === localArtist.name.toLowerCase()) hasArtist = true;
  787. }
  788. if (
  789. hasArtist &&
  790. (payload.title.indexOf(item.name) !== -1 || item.name.indexOf(payload.title) !== -1)
  791. ) {
  792. const song = {};
  793. song.duration = item.duration_ms / 1000;
  794. song.artists = item.artists.map(artist => artist.name);
  795. song.title = item.name;
  796. song.explicit = item.explicit;
  797. song.thumbnail = item.album.images[1].url;
  798. songs.push(song);
  799. }
  800. });
  801. });
  802. return resolve({ songs });
  803. });
  804. });
  805. }
  806. /**
  807. * Shuffles an array of songs
  808. *
  809. * @param {object} payload - object that contains the payload
  810. * @param {object} payload.array - an array of songs that should be shuffled
  811. * @returns {Promise} - returns promise (reject, resolve)
  812. */
  813. SHUFFLE(payload) {
  814. // array
  815. return new Promise(resolve => {
  816. const array = payload.array.slice();
  817. let currentIndex = payload.array.length;
  818. let temporaryValue;
  819. let randomIndex;
  820. // While there remain elements to shuffle...
  821. while (currentIndex !== 0) {
  822. // Pick a remaining element...
  823. randomIndex = Math.floor(Math.random() * currentIndex);
  824. currentIndex -= 1;
  825. // And swap it with the current element.
  826. temporaryValue = array[currentIndex];
  827. array[currentIndex] = array[randomIndex];
  828. array[randomIndex] = temporaryValue;
  829. }
  830. resolve({ array });
  831. });
  832. }
  833. /**
  834. * Creates an error
  835. *
  836. * @param {object} payload - object that contains the payload
  837. * @param {object} payload.error - object that contains the error
  838. * @param {string} payload.message - possible error message
  839. * @param {object} payload.errors - possible object that contains multiple errors
  840. * @returns {Promise} - returns promise (reject, resolve)
  841. */
  842. GET_ERROR(payload) {
  843. return new Promise(resolve => {
  844. let error = "An error occurred.";
  845. if (typeof payload.error === "string") error = payload.error;
  846. else if (payload.error.message) {
  847. if (payload.error.message !== "Validation failed") error = payload.error.message;
  848. else error = payload.error.errors[Object.keys(payload.error.errors)].message;
  849. }
  850. resolve(error);
  851. });
  852. }
  853. /**
  854. * Creates the gravatar url for a specified email address
  855. *
  856. * @param {object} payload - object that contains the payload
  857. * @param {string} payload.email - the email address
  858. * @returns {Promise} - returns promise (reject, resolve)
  859. */
  860. CREATE_GRAVATAR(payload) {
  861. return new Promise(resolve => {
  862. const hash = crypto.createHash("md5").update(payload.email).digest("hex");
  863. resolve(`https://www.gravatar.com/avatar/${hash}`);
  864. });
  865. }
  866. /**
  867. * @returns {Promise} - returns promise (reject, resolve)
  868. */
  869. DEBUG() {
  870. return new Promise(resolve => resolve());
  871. }
  872. }
  873. export default new _UtilsModule();