utils.js 12 KB

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