utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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 = delay;
  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. socketsFromSessionId: function(sessionId, 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. if (session.sessionId === sessionId) sockets.push(session.sessionId);
  133. next();
  134. }, () => {
  135. cb(sockets);
  136. });
  137. }
  138. },
  139. socketsFromUser: function(userId, cb) {
  140. let ns = io.io.of("/");
  141. let sockets = [];
  142. if (ns) {
  143. async.each(Object.keys(ns.connected), (id, next) => {
  144. let session = ns.connected[id].session;
  145. cache.hget('sessions', session.sessionId, (err, session) => {
  146. if (!err && session && session.userId === userId) {
  147. sockets.push(ns.connected[id]);
  148. }
  149. next();
  150. });
  151. }, () => {
  152. cb(sockets);
  153. });
  154. }
  155. },
  156. socketLeaveRooms: function(socketid) {
  157. let socket = this.socketFromSession(socketid);
  158. let rooms = socket.rooms;
  159. for (let room in rooms) {
  160. socket.leave(room);
  161. }
  162. },
  163. socketJoinRoom: function(socketId, room) {
  164. let socket = this.socketFromSession(socketId);
  165. let rooms = socket.rooms;
  166. for (let room in rooms) {
  167. socket.leave(room);
  168. }
  169. socket.join(room);
  170. },
  171. socketJoinSongRoom: function(socketId, room) {
  172. let socket = this.socketFromSession(socketId);
  173. let rooms = socket.rooms;
  174. for (let room in rooms) {
  175. if (room.indexOf('song.') !== -1) socket.leave(rooms);
  176. }
  177. socket.join(room);
  178. },
  179. socketsJoinSongRoom: function(sockets, room) {
  180. for (let id in sockets) {
  181. let socket = sockets[id];
  182. let rooms = socket.rooms;
  183. for (let room in rooms) {
  184. if (room.indexOf('song.') !== -1) socket.leave(room);
  185. }
  186. socket.join(room);
  187. }
  188. },
  189. socketsLeaveSongRooms: function(sockets) {
  190. for (let id in sockets) {
  191. let socket = sockets[id];
  192. let rooms = socket.rooms;
  193. for (let room in rooms) {
  194. if (room.indexOf('song.') !== -1) socket.leave(room);
  195. }
  196. }
  197. },
  198. emitToRoom: function(room) {
  199. let sockets = io.io.sockets.sockets;
  200. for (let id in sockets) {
  201. let socket = sockets[id];
  202. if (socket.rooms[room]) {
  203. let args = [];
  204. for (let i = 1; i < Object.keys(arguments).length; i++) {
  205. args.push(arguments[i]);
  206. }
  207. socket.emit.apply(socket, args);
  208. }
  209. }
  210. },
  211. getRoomSockets: function(room) {
  212. let sockets = io.io.sockets.sockets;
  213. let roomSockets = [];
  214. for (let id in sockets) {
  215. let socket = sockets[id];
  216. if (socket.rooms[room]) roomSockets.push(socket);
  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 youtubeRequestsActive = false;
  233. if (err) {
  234. console.error(err);
  235. return null;
  236. }
  237. body = JSON.parse(body);
  238. //TODO Clean up duration converter
  239. let dur = body.items[0].contentDetails.duration;
  240. dur = dur.replace('PT', '');
  241. let duration = 0;
  242. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  243. v2 = Number(v2);
  244. duration = (v2 * 60 * 60);
  245. return '';
  246. });
  247. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  248. v2 = Number(v2);
  249. duration += (v2 * 60);
  250. return '';
  251. });
  252. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  253. v2 = Number(v2);
  254. duration += v2;
  255. return '';
  256. });
  257. let song = {
  258. songId: body.items[0].id,
  259. title: body.items[0].snippet.title,
  260. duration
  261. };
  262. cb(song);
  263. });
  264. }, songId});
  265. if (!youtubeRequestsActive) {
  266. youtubeRequestCallbacks[0].cb(youtubeRequestCallbacks[0].songId);
  267. }
  268. },
  269. getPlaylistFromYouTube: (url, cb) => {
  270. let name = 'list'.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  271. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  272. let playlistId = regex.exec(url)[1];
  273. function getPage(pageToken, songs) {
  274. let nextPageToken = (pageToken) ? `pageToken=${pageToken}` : '';
  275. const youtubeParams = [
  276. 'part=contentDetails',
  277. `playlistId=${encodeURIComponent(playlistId)}`,
  278. `maxResults=5`,
  279. `key=${config.get('apis.youtube.key')}`,
  280. nextPageToken
  281. ].join('&');
  282. request(`https://www.googleapis.com/youtube/v3/playlistItems?${youtubeParams}`, (err, res, body) => {
  283. if (err) {
  284. console.error(err);
  285. return next('Failed to find playlist from YouTube');
  286. }
  287. body = JSON.parse(body);
  288. songs = songs.concat(body.items);
  289. if (body.nextPageToken) getPage(body.nextPageToken, songs);
  290. else {
  291. console.log(songs);
  292. cb(songs);
  293. }
  294. });
  295. }
  296. getPage(null, []);
  297. },
  298. getSongFromSpotify: (song, cb) => {
  299. const spotifyParams = [
  300. `q=${encodeURIComponent(song.title)}`,
  301. `type=track`
  302. ].join('&');
  303. request(`https://api.spotify.com/v1/search?${spotifyParams}`, (err, res, body) => {
  304. if (err) console.error(err);
  305. body = JSON.parse(body);
  306. durationArtistLoop:
  307. for (let i in body) {
  308. let items = body[i].items;
  309. for (let j in items) {
  310. let item = items[j];
  311. let hasArtist = false;
  312. for (let k = 0; k < item.artists.length; k++) {
  313. let artist = item.artists[k];
  314. if (song.title.indexOf(artist.name) !== -1) hasArtist = true;
  315. }
  316. if (hasArtist && song.title.indexOf(item.name) !== -1) {
  317. song.duration = item.duration_ms / 1000;
  318. song.artists = item.artists.map(artist => {
  319. return artist.name;
  320. });
  321. song.title = item.name;
  322. song.explicit = item.explicit;
  323. song.thumbnail = item.album.images[1].url;
  324. break durationArtistLoop;
  325. }
  326. }
  327. }
  328. cb(song);
  329. });
  330. },
  331. getSongsFromSpotify: (title, artist, cb) => {
  332. const spotifyParams = [
  333. `q=${encodeURIComponent(title)}`,
  334. `type=track`
  335. ].join('&');
  336. request(`https://api.spotify.com/v1/search?${spotifyParams}`, (err, res, body) => {
  337. if (err) return console.error(err);
  338. body = JSON.parse(body);
  339. let songs = [];
  340. for (let i in body) {
  341. let items = body[i].items;
  342. for (let j in items) {
  343. let item = items[j];
  344. let hasArtist = false;
  345. for (let k = 0; k < item.artists.length; k++) {
  346. let localArtist = item.artists[k];
  347. if (artist.toLowerCase() === localArtist.name.toLowerCase()) hasArtist = true;
  348. }
  349. if (hasArtist && (title.indexOf(item.name) !== -1 || item.name.indexOf(title) !== -1)) {
  350. let song = {};
  351. song.duration = item.duration_ms / 1000;
  352. song.artists = item.artists.map(artist => {
  353. return artist.name;
  354. });
  355. song.title = item.name;
  356. song.explicit = item.explicit;
  357. song.thumbnail = item.album.images[1].url;
  358. songs.push(song);
  359. }
  360. }
  361. }
  362. cb(songs);
  363. });
  364. },
  365. shuffle: (array) => {
  366. let currentIndex = array.length, temporaryValue, randomIndex;
  367. // While there remain elements to shuffle...
  368. while (0 !== currentIndex) {
  369. // Pick a remaining element...
  370. randomIndex = Math.floor(Math.random() * currentIndex);
  371. currentIndex -= 1;
  372. // And swap it with the current element.
  373. temporaryValue = array[currentIndex];
  374. array[currentIndex] = array[randomIndex];
  375. array[randomIndex] = temporaryValue;
  376. }
  377. return array;
  378. },
  379. getError: (err) => {
  380. let error = 'An error occurred.';
  381. if (typeof err === "string") error = err;
  382. else if (err.message) error = err.message;
  383. return error;
  384. },
  385. canUserBeInStation: (station, userId, cb) => {
  386. async.waterfall([
  387. (next) => {
  388. if (station.privacy !== 'private') return next(true);
  389. if (!session.userId) return next(false);
  390. next();
  391. },
  392. (next) => {
  393. db.models.user.findOne({_id: session.userId}, next);
  394. },
  395. (user, next) => {
  396. if (!user) return next(false);
  397. if (user.role === 'admin') return next(true);
  398. if (station.type === 'official') return next(false);
  399. if (station.owner === session.userId) return next(true);
  400. next(false);
  401. }
  402. ], (err) => {
  403. if (err === true) return cb(true);
  404. return cb(false);
  405. });
  406. }
  407. };