utils.js 13 KB

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