utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. 'use strict';
  2. const coreClass = require("../core");
  3. const config = require('config'),
  4. async = require('async'),
  5. request = require('request');
  6. class Timer {
  7. constructor(callback, delay, paused) {
  8. this.callback = callback;
  9. this.timerId = undefined;
  10. this.start = undefined;
  11. this.paused = paused;
  12. this.remaining = delay;
  13. this.timeWhenPaused = 0;
  14. this.timePaused = Date.now();
  15. if (!paused) {
  16. this.resume();
  17. }
  18. }
  19. pause() {
  20. clearTimeout(this.timerId);
  21. this.remaining -= Date.now() - this.start;
  22. this.timePaused = Date.now();
  23. this.paused = true;
  24. }
  25. ifNotPaused() {
  26. if (!this.paused) {
  27. this.resume();
  28. }
  29. }
  30. resume() {
  31. this.start = Date.now();
  32. clearTimeout(this.timerId);
  33. this.timerId = setTimeout(this.callback, this.remaining);
  34. this.timeWhenPaused = Date.now() - this.timePaused;
  35. this.paused = false;
  36. }
  37. resetTimeWhenPaused() {
  38. this.timeWhenPaused = 0;
  39. }
  40. getTimePaused() {
  41. if (!this.paused) {
  42. return this.timeWhenPaused;
  43. } else {
  44. return Date.now() - this.timePaused;
  45. }
  46. }
  47. }
  48. let youtubeRequestCallbacks = [];
  49. let youtubeRequestsPending = 0;
  50. let youtubeRequestsActive = false;
  51. module.exports = class extends coreClass {
  52. initialize() {
  53. return new Promise((resolve, reject) => {
  54. this.setStage(1);
  55. this.io = this.moduleManager.modules["io"];
  56. this.db = this.moduleManager.modules["db"];
  57. this.spotify = this.moduleManager.modules["spotify"];
  58. this.cache = this.moduleManager.modules["cache"];
  59. this.Timer = Timer;
  60. resolve();
  61. });
  62. }
  63. async parseCookies(cookieString) {
  64. try { await this._validateHook(); } catch { return; }
  65. let cookies = {};
  66. if (cookieString) cookieString.split("; ").map((cookie) => {
  67. (cookies[cookie.substring(0, cookie.indexOf("="))] = cookie.substring(cookie.indexOf("=") + 1, cookie.length));
  68. });
  69. return cookies;
  70. }
  71. async cookiesToString(cookies) {
  72. try { await this._validateHook(); } catch { return; }
  73. let newCookie = [];
  74. for (let prop in cookie) {
  75. newCookie.push(prop + "=" + cookie[prop]);
  76. }
  77. return newCookie.join("; ");
  78. }
  79. async removeCookie(cookieString, cookieName) {
  80. try { await this._validateHook(); } catch { return; }
  81. var cookies = this.parseCookies(cookieString);
  82. delete cookies[cookieName];
  83. return this.toString(cookies);
  84. }
  85. async htmlEntities(str) {
  86. try { await this._validateHook(); } catch { return; }
  87. return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
  88. }
  89. async generateRandomString(len) {
  90. try { await this._validateHook(); } catch { return; }
  91. let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
  92. let result = [];
  93. for (let i = 0; i < len; i++) {
  94. result.push(chars[await this.getRandomNumber(0, chars.length - 1)]);
  95. }
  96. return result.join("");
  97. }
  98. async getSocketFromId(socketId) {
  99. try { await this._validateHook(); } catch { return; }
  100. return globals.io.sockets.sockets[socketId];
  101. }
  102. async getRandomNumber(min, max) {
  103. try { await this._validateHook(); } catch { return; }
  104. return Math.floor(Math.random() * (max - min + 1)) + min
  105. }
  106. async convertTime(duration) {
  107. try { await this._validateHook(); } catch { return; }
  108. let a = duration.match(/\d+/g);
  109. if (duration.indexOf('M') >= 0 && duration.indexOf('H') == -1 && duration.indexOf('S') == -1) {
  110. a = [0, a[0], 0];
  111. }
  112. if (duration.indexOf('H') >= 0 && duration.indexOf('M') == -1) {
  113. a = [a[0], 0, a[1]];
  114. }
  115. if (duration.indexOf('H') >= 0 && duration.indexOf('M') == -1 && duration.indexOf('S') == -1) {
  116. a = [a[0], 0, 0];
  117. }
  118. duration = 0;
  119. if (a.length == 3) {
  120. duration = duration + parseInt(a[0]) * 3600;
  121. duration = duration + parseInt(a[1]) * 60;
  122. duration = duration + parseInt(a[2]);
  123. }
  124. if (a.length == 2) {
  125. duration = duration + parseInt(a[0]) * 60;
  126. duration = duration + parseInt(a[1]);
  127. }
  128. if (a.length == 1) {
  129. duration = duration + parseInt(a[0]);
  130. }
  131. let hours = Math.floor(duration / 3600);
  132. let minutes = Math.floor(duration % 3600 / 60);
  133. let seconds = Math.floor(duration % 3600 % 60);
  134. return (hours < 10 ? ("0" + hours + ":") : (hours + ":")) + (minutes < 10 ? ("0" + minutes + ":") : (minutes + ":")) + (seconds < 10 ? ("0" + seconds) : seconds);
  135. }
  136. async guid () {
  137. try { await this._validateHook(); } catch { return; }
  138. return [1,1,0,1,0,1,0,1,0,1,1,1].map(b => b ? Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) : '-').join('');
  139. }
  140. async socketFromSession(socketId) {
  141. try { await this._validateHook(); } catch { return; }
  142. let io = await this.io.io();
  143. let ns = io.of("/");
  144. if (ns) {
  145. return ns.connected[socketId];
  146. }
  147. }
  148. async socketsFromSessionId(sessionId, cb) {
  149. try { await this._validateHook(); } catch { return; }
  150. let io = await this.io.io();
  151. let ns = io.of("/");
  152. let sockets = [];
  153. if (ns) {
  154. async.each(Object.keys(ns.connected), (id, next) => {
  155. let session = ns.connected[id].session;
  156. if (session.sessionId === sessionId) sockets.push(session.sessionId);
  157. next();
  158. }, () => {
  159. cb(sockets);
  160. });
  161. }
  162. }
  163. async socketsFromUser(userId, cb) {
  164. try { await this._validateHook(); } catch { return; }
  165. let io = await this.io.io();
  166. let ns = io.of("/");
  167. let sockets = [];
  168. if (ns) {
  169. async.each(Object.keys(ns.connected), (id, next) => {
  170. let session = ns.connected[id].session;
  171. this.cache.hget('sessions', session.sessionId, (err, session) => {
  172. if (!err && session && session.userId === userId) sockets.push(ns.connected[id]);
  173. next();
  174. });
  175. }, () => {
  176. cb(sockets);
  177. });
  178. }
  179. }
  180. async socketsFromIP(ip, cb) {
  181. try { await this._validateHook(); } catch { return; }
  182. let io = await this.io.io();
  183. let ns = io.of("/");
  184. let sockets = [];
  185. if (ns) {
  186. async.each(Object.keys(ns.connected), (id, next) => {
  187. let session = ns.connected[id].session;
  188. this.cache.hget('sessions', session.sessionId, (err, session) => {
  189. if (!err && session && ns.connected[id].ip === ip) sockets.push(ns.connected[id]);
  190. next();
  191. });
  192. }, () => {
  193. cb(sockets);
  194. });
  195. }
  196. }
  197. async socketsFromUserWithoutCache(userId, cb) {
  198. try { await this._validateHook(); } catch { return; }
  199. let io = await this.io.io();
  200. let ns = io.of("/");
  201. let sockets = [];
  202. if (ns) {
  203. async.each(Object.keys(ns.connected), (id, next) => {
  204. let session = ns.connected[id].session;
  205. if (session.userId === userId) sockets.push(ns.connected[id]);
  206. next();
  207. }, () => {
  208. cb(sockets);
  209. });
  210. }
  211. }
  212. async socketLeaveRooms(socketid) {
  213. try { await this._validateHook(); } catch { return; }
  214. let socket = await this.socketFromSession(socketid);
  215. let rooms = socket.rooms;
  216. for (let room in rooms) {
  217. socket.leave(room);
  218. }
  219. }
  220. async socketJoinRoom(socketId, room) {
  221. try { await this._validateHook(); } catch { return; }
  222. let socket = await this.socketFromSession(socketId);
  223. let rooms = socket.rooms;
  224. for (let room in rooms) {
  225. socket.leave(room);
  226. }
  227. socket.join(room);
  228. }
  229. async socketJoinSongRoom(socketId, room) {
  230. try { await this._validateHook(); } catch { return; }
  231. let socket = await this.socketFromSession(socketId);
  232. let rooms = socket.rooms;
  233. for (let room in rooms) {
  234. if (room.indexOf('song.') !== -1) socket.leave(rooms);
  235. }
  236. socket.join(room);
  237. }
  238. async socketsJoinSongRoom(sockets, room) {
  239. try { await this._validateHook(); } catch { return; }
  240. for (let id in sockets) {
  241. let socket = sockets[id];
  242. let rooms = socket.rooms;
  243. for (let room in rooms) {
  244. if (room.indexOf('song.') !== -1) socket.leave(room);
  245. }
  246. socket.join(room);
  247. }
  248. }
  249. async socketsLeaveSongRooms(sockets) {
  250. try { await this._validateHook(); } catch { return; }
  251. for (let id in sockets) {
  252. let socket = sockets[id];
  253. let rooms = socket.rooms;
  254. for (let room in rooms) {
  255. if (room.indexOf('song.') !== -1) socket.leave(room);
  256. }
  257. }
  258. }
  259. async emitToRoom(room, ...args) {
  260. try { await this._validateHook(); } catch { return; }
  261. let io = await this.io.io();
  262. let sockets = io.sockets.sockets;
  263. for (let id in sockets) {
  264. let socket = sockets[id];
  265. if (socket.rooms[room]) {
  266. socket.emit.apply(socket, args);
  267. }
  268. }
  269. }
  270. async getRoomSockets(room) {
  271. try { await this._validateHook(); } catch { return; }
  272. let io = await this.io.io();
  273. let sockets = io.sockets.sockets;
  274. let roomSockets = [];
  275. for (let id in sockets) {
  276. let socket = sockets[id];
  277. if (socket.rooms[room]) roomSockets.push(socket);
  278. }
  279. return roomSockets;
  280. }
  281. async getSongFromYouTube(songId, cb) {
  282. try { await this._validateHook(); } catch { return; }
  283. youtubeRequestCallbacks.push({cb: (test) => {
  284. youtubeRequestsActive = true;
  285. const youtubeParams = [
  286. 'part=snippet,contentDetails,statistics,status',
  287. `id=${encodeURIComponent(songId)}`,
  288. `key=${config.get('apis.youtube.key')}`
  289. ].join('&');
  290. request(`https://www.googleapis.com/youtube/v3/videos?${youtubeParams}`, (err, res, body) => {
  291. youtubeRequestCallbacks.splice(0, 1);
  292. if (youtubeRequestCallbacks.length > 0) {
  293. youtubeRequestCallbacks[0].cb(youtubeRequestCallbacks[0].songId);
  294. } else youtubeRequestsActive = false;
  295. if (err) {
  296. console.error(err);
  297. return null;
  298. }
  299. body = JSON.parse(body);
  300. //TODO Clean up duration converter
  301. let dur = body.items[0].contentDetails.duration;
  302. dur = dur.replace('PT', '');
  303. let duration = 0;
  304. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  305. v2 = Number(v2);
  306. duration = (v2 * 60 * 60);
  307. return '';
  308. });
  309. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  310. v2 = Number(v2);
  311. duration += (v2 * 60);
  312. return '';
  313. });
  314. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  315. v2 = Number(v2);
  316. duration += v2;
  317. return '';
  318. });
  319. let song = {
  320. songId: body.items[0].id,
  321. title: body.items[0].snippet.title,
  322. duration
  323. };
  324. cb(song);
  325. });
  326. }, songId});
  327. if (!youtubeRequestsActive) {
  328. youtubeRequestCallbacks[0].cb(youtubeRequestCallbacks[0].songId);
  329. }
  330. }
  331. async getPlaylistFromYouTube(url, cb) {
  332. try { await this._validateHook(); } catch { return; }
  333. let name = 'list'.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  334. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  335. let playlistId = regex.exec(url)[1];
  336. function getPage(pageToken, songs) {
  337. let nextPageToken = (pageToken) ? `pageToken=${pageToken}` : '';
  338. const youtubeParams = [
  339. 'part=contentDetails',
  340. `playlistId=${encodeURIComponent(playlistId)}`,
  341. `maxResults=5`,
  342. `key=${config.get('apis.youtube.key')}`,
  343. nextPageToken
  344. ].join('&');
  345. request(`https://www.googleapis.com/youtube/v3/playlistItems?${youtubeParams}`, (err, res, body) => {
  346. if (err) {
  347. console.error(err);
  348. return next('Failed to find playlist from YouTube');
  349. }
  350. body = JSON.parse(body);
  351. songs = songs.concat(body.items);
  352. if (body.nextPageToken) getPage(body.nextPageToken, songs);
  353. else {
  354. console.log(songs);
  355. cb(songs);
  356. }
  357. });
  358. }
  359. getPage(null, []);
  360. }
  361. async getSongFromSpotify(song, cb) {
  362. try { await this._validateHook(); } catch { return; }
  363. if (!config.get("apis.spotify.enabled")) return cb("Spotify is not enabled", null);
  364. const spotifyParams = [
  365. `q=${encodeURIComponent(song.title)}`,
  366. `type=track`
  367. ].join('&');
  368. const token = await this.spotify.getToken();
  369. const options = {
  370. url: `https://api.spotify.com/v1/search?${spotifyParams}`,
  371. headers: {
  372. Authorization: `Bearer ${token}`
  373. }
  374. };
  375. request(options, (err, res, body) => {
  376. if (err) console.error(err);
  377. body = JSON.parse(body);
  378. if (body.error) console.error(body.error);
  379. durationArtistLoop:
  380. for (let i in body) {
  381. let items = body[i].items;
  382. for (let j in items) {
  383. let item = items[j];
  384. let hasArtist = false;
  385. for (let k = 0; k < item.artists.length; k++) {
  386. let artist = item.artists[k];
  387. if (song.title.indexOf(artist.name) !== -1) hasArtist = true;
  388. }
  389. if (hasArtist && song.title.indexOf(item.name) !== -1) {
  390. song.duration = item.duration_ms / 1000;
  391. song.artists = item.artists.map(artist => {
  392. return artist.name;
  393. });
  394. song.title = item.name;
  395. song.explicit = item.explicit;
  396. song.thumbnail = item.album.images[1].url;
  397. break durationArtistLoop;
  398. }
  399. }
  400. }
  401. cb(null, song);
  402. });
  403. }
  404. async getSongsFromSpotify(title, artist, cb) {
  405. try { await this._validateHook(); } catch { return; }
  406. if (!config.get("apis.spotify.enabled")) return cb([]);
  407. const spotifyParams = [
  408. `q=${encodeURIComponent(title)}`,
  409. `type=track`
  410. ].join('&');
  411. const token = await this.spotify.getToken();
  412. const options = {
  413. url: `https://api.spotify.com/v1/search?${spotifyParams}`,
  414. headers: {
  415. Authorization: `Bearer ${token}`
  416. }
  417. };
  418. request(options, (err, res, body) => {
  419. if (err) return console.error(err);
  420. body = JSON.parse(body);
  421. if (body.error) return console.error(body.error);
  422. let songs = [];
  423. for (let i in body) {
  424. let items = body[i].items;
  425. for (let j in items) {
  426. let item = items[j];
  427. let hasArtist = false;
  428. for (let k = 0; k < item.artists.length; k++) {
  429. let localArtist = item.artists[k];
  430. if (artist.toLowerCase() === localArtist.name.toLowerCase()) hasArtist = true;
  431. }
  432. if (hasArtist && (title.indexOf(item.name) !== -1 || item.name.indexOf(title) !== -1)) {
  433. let song = {};
  434. song.duration = item.duration_ms / 1000;
  435. song.artists = item.artists.map(artist => {
  436. return artist.name;
  437. });
  438. song.title = item.name;
  439. song.explicit = item.explicit;
  440. song.thumbnail = item.album.images[1].url;
  441. songs.push(song);
  442. }
  443. }
  444. }
  445. cb(songs);
  446. });
  447. }
  448. async shuffle(array) {
  449. try { await this._validateHook(); } catch { return; }
  450. let currentIndex = array.length, temporaryValue, randomIndex;
  451. // While there remain elements to shuffle...
  452. while (0 !== currentIndex) {
  453. // Pick a remaining element...
  454. randomIndex = Math.floor(Math.random() * currentIndex);
  455. currentIndex -= 1;
  456. // And swap it with the current element.
  457. temporaryValue = array[currentIndex];
  458. array[currentIndex] = array[randomIndex];
  459. array[randomIndex] = temporaryValue;
  460. }
  461. return array;
  462. }
  463. async getError(err) {
  464. try { await this._validateHook(); } catch { return; }
  465. let error = 'An error occurred.';
  466. if (typeof err === "string") error = err;
  467. else if (err.message) {
  468. if (err.message !== 'Validation failed') error = err.message;
  469. else error = err.errors[Object.keys(err.errors)].message;
  470. }
  471. return error;
  472. }
  473. }