utils.js 12 KB

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