utils.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 filterMusicVideosYouTube(videoIds, cb) {
  332. try { await this._validateHook(); } catch { return; }
  333. function getNextPage(cb2) {
  334. let localVideoIds = videoIds.splice(0, 50);
  335. const youtubeParams = [
  336. 'part=topicDetails',
  337. `id=${encodeURIComponent(localVideoIds.join(","))}`,
  338. `maxResults=50`,
  339. `key=${config.get('apis.youtube.key')}`
  340. ].join('&');
  341. request(`https://www.googleapis.com/youtube/v3/videos?${youtubeParams}`, async (err, res, body) => {
  342. if (err) {
  343. console.error(err);
  344. return next('Failed to find playlist from YouTube');
  345. }
  346. body = JSON.parse(body);
  347. let songIds = [];
  348. body.items.forEach(item => {
  349. const songId = item.id;
  350. if (!item.topicDetails) return;
  351. else if (item.topicDetails.topicIds.indexOf("/m/04rlf") !== -1) {
  352. songIds.push(songId);
  353. }
  354. });
  355. if (videoIds.length > 0) {
  356. getNextPage(newSongIds => {
  357. cb2(songIds.concat(newSongIds));
  358. });
  359. } else cb2(songIds);
  360. });
  361. }
  362. if (videoIds.length === 0) cb([]);
  363. else getNextPage(songIds => {
  364. cb(songIds);
  365. });
  366. }
  367. async getPlaylistFromYouTube(url, musicOnly, cb) {
  368. try { await this._validateHook(); } catch { return; }
  369. let local = this;
  370. let name = 'list'.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  371. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  372. let playlistId = regex.exec(url)[1];
  373. function getPage(pageToken, songs) {
  374. let nextPageToken = (pageToken) ? `pageToken=${pageToken}` : '';
  375. const youtubeParams = [
  376. 'part=contentDetails',
  377. `playlistId=${encodeURIComponent(playlistId)}`,
  378. `maxResults=50`,
  379. `key=${config.get('apis.youtube.key')}`,
  380. nextPageToken
  381. ].join('&');
  382. request(`https://www.googleapis.com/youtube/v3/playlistItems?${youtubeParams}`, async (err, res, body) => {
  383. if (err) {
  384. console.error(err);
  385. return next('Failed to find playlist from YouTube');
  386. }
  387. body = JSON.parse(body);
  388. songs = songs.concat(body.items);
  389. if (body.nextPageToken) getPage(body.nextPageToken, songs);
  390. else {
  391. songs = songs.map(song => song.contentDetails.videoId);
  392. if (!musicOnly) cb(songs);
  393. else {
  394. local.filterMusicVideosYouTube(songs.slice(), (filteredSongs) => {
  395. cb(filteredSongs, songs);
  396. });
  397. }
  398. }
  399. });
  400. }
  401. getPage(null, []);
  402. }
  403. async getSongFromSpotify(song, cb) {
  404. try { await this._validateHook(); } catch { return; }
  405. if (!config.get("apis.spotify.enabled")) return cb("Spotify is not enabled", null);
  406. const spotifyParams = [
  407. `q=${encodeURIComponent(song.title)}`,
  408. `type=track`
  409. ].join('&');
  410. const token = await this.spotify.getToken();
  411. const options = {
  412. url: `https://api.spotify.com/v1/search?${spotifyParams}`,
  413. headers: {
  414. Authorization: `Bearer ${token}`
  415. }
  416. };
  417. request(options, (err, res, body) => {
  418. if (err) console.error(err);
  419. body = JSON.parse(body);
  420. if (body.error) console.error(body.error);
  421. durationArtistLoop:
  422. for (let i in body) {
  423. let items = body[i].items;
  424. for (let j in items) {
  425. let item = items[j];
  426. let hasArtist = false;
  427. for (let k = 0; k < item.artists.length; k++) {
  428. let artist = item.artists[k];
  429. if (song.title.indexOf(artist.name) !== -1) hasArtist = true;
  430. }
  431. if (hasArtist && song.title.indexOf(item.name) !== -1) {
  432. song.duration = item.duration_ms / 1000;
  433. song.artists = item.artists.map(artist => {
  434. return artist.name;
  435. });
  436. song.title = item.name;
  437. song.explicit = item.explicit;
  438. song.thumbnail = item.album.images[1].url;
  439. break durationArtistLoop;
  440. }
  441. }
  442. }
  443. cb(null, song);
  444. });
  445. }
  446. async getSongsFromSpotify(title, artist, cb) {
  447. try { await this._validateHook(); } catch { return; }
  448. if (!config.get("apis.spotify.enabled")) return cb([]);
  449. const spotifyParams = [
  450. `q=${encodeURIComponent(title)}`,
  451. `type=track`
  452. ].join('&');
  453. const token = await this.spotify.getToken();
  454. const options = {
  455. url: `https://api.spotify.com/v1/search?${spotifyParams}`,
  456. headers: {
  457. Authorization: `Bearer ${token}`
  458. }
  459. };
  460. request(options, (err, res, body) => {
  461. if (err) return console.error(err);
  462. body = JSON.parse(body);
  463. if (body.error) return console.error(body.error);
  464. let songs = [];
  465. for (let i in body) {
  466. let items = body[i].items;
  467. for (let j in items) {
  468. let item = items[j];
  469. let hasArtist = false;
  470. for (let k = 0; k < item.artists.length; k++) {
  471. let localArtist = item.artists[k];
  472. if (artist.toLowerCase() === localArtist.name.toLowerCase()) hasArtist = true;
  473. }
  474. if (hasArtist && (title.indexOf(item.name) !== -1 || item.name.indexOf(title) !== -1)) {
  475. let song = {};
  476. song.duration = item.duration_ms / 1000;
  477. song.artists = item.artists.map(artist => {
  478. return artist.name;
  479. });
  480. song.title = item.name;
  481. song.explicit = item.explicit;
  482. song.thumbnail = item.album.images[1].url;
  483. songs.push(song);
  484. }
  485. }
  486. }
  487. cb(songs);
  488. });
  489. }
  490. async shuffle(array) {
  491. try { await this._validateHook(); } catch { return; }
  492. let currentIndex = array.length, temporaryValue, randomIndex;
  493. // While there remain elements to shuffle...
  494. while (0 !== currentIndex) {
  495. // Pick a remaining element...
  496. randomIndex = Math.floor(Math.random() * currentIndex);
  497. currentIndex -= 1;
  498. // And swap it with the current element.
  499. temporaryValue = array[currentIndex];
  500. array[currentIndex] = array[randomIndex];
  501. array[randomIndex] = temporaryValue;
  502. }
  503. return array;
  504. }
  505. async getError(err) {
  506. try { await this._validateHook(); } catch { return; }
  507. let error = 'An error occurred.';
  508. if (typeof err === "string") error = err;
  509. else if (err.message) {
  510. if (err.message !== 'Validation failed') error = err.message;
  511. else error = err.errors[Object.keys(err.errors)].message;
  512. }
  513. return error;
  514. }
  515. }