utils.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. module.exports = {
  79. htmlEntities: str => String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'),
  80. generateRandomString: function(len) {
  81. let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
  82. let result = [];
  83. for (let i = 0; i < len; i++) {
  84. result.push(chars[this.getRandomNumber(0, chars.length - 1)]);
  85. }
  86. return result.join("");
  87. },
  88. getSocketFromId: function(socketId) {
  89. return globals.io.sockets.sockets[socketId];
  90. },
  91. getRandomNumber: (min, max) => Math.floor(Math.random() * (max - min + 1)) + min,
  92. convertTime,
  93. Timer,
  94. 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(''),
  95. cookies: {
  96. parseCookies: cookieString => {
  97. let cookies = {};
  98. if (cookieString) cookieString.split("; ").map((cookie) => {
  99. (cookies[cookie.substring(0, cookie.indexOf("="))] = cookie.substring(cookie.indexOf("=") + 1, cookie.length));
  100. });
  101. return cookies;
  102. },
  103. toString: cookies => {
  104. let newCookie = [];
  105. for (let prop in cookie) {
  106. newCookie.push(prop + "=" + cookie[prop]);
  107. }
  108. return newCookie.join("; ");
  109. },
  110. removeCookie: (cookieString, cookieName) => {
  111. var cookies = this.parseCookies(cookieString);
  112. delete cookies[cookieName];
  113. return this.toString(cookies);
  114. }
  115. },
  116. socketFromSession: function(socketId) {
  117. let ns = io.io.of("/");
  118. if (ns) {
  119. return ns.connected[socketId];
  120. }
  121. },
  122. socketsFromUser: function(userId, cb) {
  123. let ns = io.io.of("/");
  124. let sockets = [];
  125. if (ns) {
  126. let total = Object.keys(ns.connected).length;
  127. let done = 0;
  128. for (let id in ns.connected) {
  129. let session = ns.connected[id].session;
  130. cache.hget('sessions', session.sessionId, (err, session) => {
  131. if (!err && session && session.userId === userId) {
  132. sockets.push(ns.connected[id]);
  133. }
  134. checkComplete();
  135. });
  136. }
  137. function checkComplete() {
  138. done++;
  139. if (done === total) {
  140. cb(sockets);
  141. }
  142. }
  143. }
  144. },
  145. socketLeaveRooms: function(socketid) {
  146. let socket = this.socketFromSession(socketid);
  147. let rooms = socket.rooms;
  148. for (let j = 0; j < rooms.length; j++) {
  149. socket.leave(rooms[j]);
  150. }
  151. },
  152. socketJoinRoom: function(socketId, room) {
  153. let socket = this.socketFromSession(socketId);
  154. let rooms = socket.rooms;
  155. for (let j = 0; j < rooms.length; j++) {
  156. socket.leave(rooms[j]);
  157. }
  158. socket.join(room);
  159. },
  160. socketJoinSongRoom: function(socketId, room) {
  161. let socket = this.socketFromSession(socketId);
  162. let rooms = socket.rooms;
  163. for (let j = 0; j < rooms.length; j++) {
  164. if (socket.indexOf('song.') !== -1) {
  165. socket.leave(rooms[j]);
  166. }
  167. }
  168. socket.join(room);
  169. },
  170. socketsJoinSongRoom: function(sockets, room) {
  171. for (let id in sockets) {
  172. let socket = sockets[id];
  173. let rooms = socket.rooms;
  174. for (let roomId in rooms) {
  175. console.log(roomId);
  176. if (roomId.indexOf('song.') !== -1) {
  177. socket.leave(roomId);
  178. }
  179. }
  180. socket.join(room);
  181. }
  182. },
  183. socketsLeaveSongRooms: function(sockets) {
  184. for (let id in sockets) {
  185. let socket = sockets[id];
  186. let rooms = socket.rooms;
  187. for (let roomId in rooms) {
  188. console.log(roomId);
  189. if (roomId.indexOf('song.') !== -1) {
  190. socket.leave(roomId);
  191. }
  192. }
  193. }
  194. },
  195. getSongFromYouTube: (songId, cb) => {
  196. const youtubeParams = [
  197. 'part=snippet,contentDetails,statistics,status',
  198. `id=${encodeURIComponent(songId)}`,
  199. `key=${config.get('apis.youtube.key')}`
  200. ].join('&');
  201. request(`https://www.googleapis.com/youtube/v3/videos?${youtubeParams}`, (err, res, body) => {
  202. if (err) {
  203. console.error(err);
  204. return next('Failed to find song from YouTube');
  205. }
  206. body = JSON.parse(body);
  207. //TODO Clean up duration converter
  208. let dur = body.items[0].contentDetails.duration;
  209. dur = dur.replace('PT', '');
  210. let duration = 0;
  211. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  212. v2 = Number(v2);
  213. duration = (v2 * 60 * 60);
  214. return '';
  215. });
  216. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  217. v2 = Number(v2);
  218. duration = (v2 * 60);
  219. return '';
  220. });
  221. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  222. v2 = Number(v2);
  223. duration += v2;
  224. return '';
  225. });
  226. let song = {
  227. _id: body.items[0].id,
  228. title: body.items[0].snippet.title,
  229. duration
  230. };
  231. cb(song);
  232. });
  233. }
  234. };