utils.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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) {
  168. socket.leave(rooms);
  169. }
  170. }
  171. socket.join(room);
  172. },
  173. socketsJoinSongRoom: function(sockets, room) {
  174. for (let id in sockets) {
  175. let socket = sockets[id];
  176. let rooms = socket.rooms;
  177. for (let room in rooms) {
  178. if (room.indexOf('song.') !== -1) {
  179. socket.leave(room);
  180. }
  181. }
  182. socket.join(room);
  183. }
  184. },
  185. socketsLeaveSongRooms: function(sockets) {
  186. for (let id in sockets) {
  187. let socket = sockets[id];
  188. let rooms = socket.rooms;
  189. for (let room in rooms) {
  190. if (room.indexOf('song.') !== -1) {
  191. socket.leave(room);
  192. }
  193. }
  194. }
  195. },
  196. emitToRoom: function(room) {
  197. let sockets = io.io.sockets.sockets;
  198. for (let id in sockets) {
  199. let socket = sockets[id];
  200. if (socket.rooms[room]) {
  201. let args = [];
  202. for (let i = 1; i < Object.keys(arguments).length; i++) {
  203. args.push(arguments[i]);
  204. }
  205. socket.emit.apply(socket, args);
  206. }
  207. }
  208. },
  209. getRoomSockets: function(room) {
  210. let sockets = io.io.sockets.sockets;
  211. let roomSockets = [];
  212. for (let id in sockets) {
  213. let socket = sockets[id];
  214. if (socket.rooms[room]) {
  215. roomSockets.push(socket);
  216. }
  217. }
  218. return roomSockets;
  219. },
  220. getSongFromYouTube: (songId, cb) => {
  221. youtubeRequestCallbacks.push({cb: (test) => {
  222. youtubeRequestsActive = true;
  223. const youtubeParams = [
  224. 'part=snippet,contentDetails,statistics,status',
  225. `id=${encodeURIComponent(songId)}`,
  226. `key=${config.get('apis.youtube.key')}`
  227. ].join('&');
  228. request(`https://www.googleapis.com/youtube/v3/videos?${youtubeParams}`, (err, res, body) => {
  229. youtubeRequestCallbacks.splice(0, 1);
  230. if (youtubeRequestCallbacks.length > 0) {
  231. youtubeRequestCallbacks[0].cb(youtubeRequestCallbacks[0].songId);
  232. } else {
  233. youtubeRequestsActive = false;
  234. }
  235. if (err) {
  236. console.error(err);
  237. return null;
  238. }
  239. body = JSON.parse(body);
  240. //TODO Clean up duration converter
  241. let dur = body.items[0].contentDetails.duration;
  242. dur = dur.replace('PT', '');
  243. let duration = 0;
  244. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  245. v2 = Number(v2);
  246. duration = (v2 * 60 * 60);
  247. return '';
  248. });
  249. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  250. v2 = Number(v2);
  251. duration += (v2 * 60);
  252. return '';
  253. });
  254. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  255. v2 = Number(v2);
  256. duration += v2;
  257. return '';
  258. });
  259. let song = {
  260. _id: body.items[0].id,
  261. title: body.items[0].snippet.title,
  262. duration
  263. };
  264. cb(song);
  265. });
  266. }, songId});
  267. if (!youtubeRequestsActive) {
  268. youtubeRequestCallbacks[0].cb(youtubeRequestCallbacks[0].songId);
  269. }
  270. },
  271. getPlaylistFromYouTube: (url, cb) => {
  272. let name = 'list'.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  273. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  274. let playlistId = regex.exec(url)[1];
  275. function getPage(pageToken, songs) {
  276. let nextPageToken = (pageToken) ? `pageToken=${pageToken}` : '';
  277. const youtubeParams = [
  278. 'part=contentDetails',
  279. `playlistId=${encodeURIComponent(playlistId)}`,
  280. `maxResults=5`,
  281. `key=${config.get('apis.youtube.key')}`,
  282. nextPageToken
  283. ].join('&');
  284. request(`https://www.googleapis.com/youtube/v3/playlistItems?${youtubeParams}`, (err, res, body) => {
  285. if (err) {
  286. console.error(err);
  287. return next('Failed to find playlist from YouTube');
  288. }
  289. body = JSON.parse(body);
  290. songs = songs.concat(body.items);
  291. if (body.nextPageToken) {
  292. getPage(body.nextPageToken, songs);
  293. } else {
  294. console.log(songs);
  295. cb(songs);
  296. }
  297. });
  298. }
  299. getPage(null, []);
  300. },
  301. getSongFromSpotify: (song, cb) => {
  302. const spotifyParams = [
  303. `q=${encodeURIComponent(song.title)}`,
  304. `type=track`
  305. ].join('&');
  306. request(`https://api.spotify.com/v1/search?${spotifyParams}`, (err, res, body) => {
  307. if (err) console.error(err);
  308. body = JSON.parse(body);
  309. durationArtistLoop:
  310. for (let i in body) {
  311. let items = body[i].items;
  312. for (let j in items) {
  313. let item = items[j];
  314. let hasArtist = false;
  315. for (let k = 0; k < item.artists.length; k++) {
  316. let artist = item.artists[k];
  317. if (song.title.indexOf(artist.name) !== -1) hasArtist = true;
  318. }
  319. if (hasArtist && song.title.indexOf(item.name) !== -1) {
  320. song.duration = item.duration_ms / 1000;
  321. song.artists = item.artists.map(artist => {
  322. return artist.name;
  323. });
  324. song.title = item.name;
  325. song.explicit = item.explicit;
  326. song.thumbnail = item.album.images[1].url;
  327. break durationArtistLoop;
  328. }
  329. }
  330. }
  331. cb(song);
  332. });
  333. }
  334. };