utils.js 11 KB

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