utils.js 9.7 KB

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