Advertisement
Guest User

Untitled

a guest
Dec 1st, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.84 KB | None | 0 0
  1. var express = require('express'),
  2. cluster = require('cluster'),
  3. net = require('net'),
  4. sio = require('socket.io'),
  5. farmhash = require('farmhash'),
  6. bodyParser = require('body-parser'),
  7. mysql = require('mysql');
  8.  
  9. const redis = require('redis').createClient;
  10. const adapter = require('socket.io-redis');
  11. const pub = redis('6379', 'na-redis.pushthis.io', { auth_pass: "yXcYn8ZQH5tVsakvgcvD3q2V" });
  12. const sub = redis('6379', 'na-redis.pushthis.io', { auth_pass: "yXcYn8ZQH5tVsakvgcvD3q2V" });
  13.  
  14.  
  15. let track = require('./controllers/useagecontroller.js');
  16.  
  17. var port = 3000,
  18. num_processes = require('os').cpus().length;
  19.  
  20. var pool = mysql.createPool({
  21. connectionLimit : 150,
  22. host: "45.76.19.242",
  23. user: "na-connections",
  24. password: "R4f0gjuKAMTm9ubF",
  25. database: "pushthis"
  26. });
  27.  
  28. if (cluster.isMaster) {
  29. // This stores our workers. We need to keep them to be able to reference
  30. // them based on source IP address. It's also useful for auto-restart,
  31. // for example.
  32. var workers = [];
  33.  
  34. // Helper function for spawning worker at index 'i'.
  35. var spawn = function(i) {
  36. workers[i] = cluster.fork();
  37.  
  38. // Optional: Restart worker on exit
  39. workers[i].on('exit', function(code, signal) {
  40. console.log('respawning worker', i);
  41. spawn(i);
  42. });
  43. workers[i].on('disconnect', function(worker) {
  44. console.log(workers[i].process.pid + 'disconnected -- rip')
  45. })
  46.  
  47. workers[i].on('online', (worker) => {
  48. console.log(workers[i].process.pid)
  49. console.log('notice me senpie')
  50. })
  51. };
  52.  
  53. // Spawn workers.
  54. for (var i = 0; i < num_processes; i++) {
  55. spawn(i);
  56. }
  57.  
  58. var worker_index = function(n) {
  59. return Math.floor(Math.random() * n)
  60. };
  61.  
  62. // Create the outside facing server listening on our port.
  63. var server = net.createServer({ pauseOnConnect: true }, function(connection) {
  64. var worker = workers[worker_index(num_processes)];
  65. worker.send('sticky-session:connection', connection);
  66. }).listen(port);
  67. } else {
  68. process.setMaxListeners(0);
  69. // Note we don't use a port here because the master listens on it for us.
  70. var app = new express();
  71.  
  72. app.use(bodyParser.json({
  73. limit: 5000
  74. }))
  75.  
  76. app.use(function(req, res, next) {
  77. res.setHeader('Access-Control-Allow-Origin', '*');
  78. res.header("Access-Control-Allow-Credentials: true");
  79. res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  80. next();
  81. });
  82.  
  83.  
  84. // Don't expose our internal server to the outside.
  85. var server = app.listen(0, 'localhost'),
  86. io = sio(server);
  87.  
  88. // Tell Socket.IO to use the redis adapter. By default, the redis
  89. // server is assumed to be on localhost:6379. You don't have to
  90. // specify them explicitly unless you want to change them.
  91. io.adapter(adapter({ pubClient: pub, subClient: sub }));
  92.  
  93.  
  94.  
  95. // Here you might use Socket.IO middleware for authorization etc.
  96. io.sockets.on('connection', function (socket) {
  97.  
  98. var origin = socket.request.headers['origin'];
  99. console.log('A client has connected to from: ' + origin);
  100. io.emit('demo-2', 'Authorizing your connection..');
  101.  
  102. pool.getConnection(function(err, connection) {
  103.  
  104. //get connection origin
  105. var key = socket.request.headers['origin'];
  106.  
  107. if(key === null){
  108. //Client requesting to join a channel
  109. socket.on('join', function (data) {
  110. console.log(data);
  111.  
  112. if(!data['channel']){
  113. //error just return nothing and stop
  114. return
  115. }
  116.  
  117. //Client requesting to join public channel
  118. if(!data['presense'] || data['presense'] === false){
  119. publicChannel = data['channel']
  120. socket.join(publicChannel)
  121. }
  122.  
  123. //Client requesting to join Presence channel
  124. if(data['presence'] === true && data['authorize'] === false ||
  125. data['presence'] === true && !data['authorize']){
  126. presenceChannel = data['channel']
  127. socket.join(presenceChannel)
  128.  
  129. //trigger callback to origin/pushthis/auth
  130. callback = {
  131. 'status' : 'connected',
  132. 'channel' : data['channel'],
  133. 'origin' : socket.request.headers['origin'],
  134. 'socket_id' : socket.id
  135. };
  136.  
  137.  
  138. //send back to the customers site
  139. io.to(presenceChannel).emit('info', callback);
  140. }
  141.  
  142. if(data['authorize'] === true){
  143. presenceChannel = data['channel']
  144. //trigger callback to origin/pushthis/auth
  145. callback = {
  146. 'status' : 'waiting authorization',
  147. 'channel' : data['channel'],
  148. 'origin' : socket.request.headers['origin'],
  149. 'socket_id' : socket.id
  150. };
  151.  
  152.  
  153. //send back to the customers site
  154. io.to(presenceChannel).emit('info', callback);
  155. }
  156. });
  157. }
  158.  
  159.  
  160. var getAppInformation = 'SELECT * FROM users_app WHERE origin = ?';
  161.  
  162. connection.query(getAppInformation, [key], function(err, result, fields) {
  163. if (err) throw err
  164.  
  165. if(result.length < 1){
  166.  
  167. }
  168.  
  169. //Client requesting to join a channel
  170. socket.on('join', function (data) {
  171.  
  172. console.log(data);
  173.  
  174. if(!data['channel']){
  175. //error just return nothing and stop
  176. return
  177. }
  178.  
  179. //Client requesting to join public channel
  180. if(!data['presense'] || data['presense'] === false){
  181. publicChannel = data['channel']
  182. socket.join(publicChannel)
  183. }
  184.  
  185. //Client requesting to join Presence channel
  186. if(data['presence'] === true && data['authorize'] === false ||
  187. data['presence'] === true && !data['authorize']){
  188. presenceChannel = data['channel']
  189. socket.join(presenceChannel)
  190.  
  191. //trigger callback to origin/pushthis/auth
  192. callback = {
  193. 'status' : 'connected',
  194. 'channel' : data['channel'],
  195. 'origin' : socket.request.headers['origin'],
  196. 'socket_id' : socket.id
  197. };
  198.  
  199.  
  200. //send back to the customers site
  201. io.to(presenceChannel).emit('info', callback);
  202. }
  203.  
  204. if(data['authorize'] === true){
  205. presenceChannel = data['channel']
  206. //trigger callback to origin/pushthis/auth
  207. callback = {
  208. 'status' : 'waiting authorization',
  209. 'channel' : data['channel'],
  210. 'origin' : socket.request.headers['origin'],
  211. 'socket_id' : socket.id
  212. };
  213.  
  214.  
  215. //send back to the customers site
  216. io.to(presenceChannel).emit('info', callback);
  217. }
  218. });
  219. var status = "connection";
  220. var identifier = result[0]['users_app_id'];
  221. //var identifier = result['users_app_id'];
  222. track.customersConnections(identifier, status, pool);
  223. });
  224. // And done with the connection.
  225. connection.release();
  226. });
  227.  
  228. socket.on('000100', function(data){
  229. console.log('okkkayy');
  230. });
  231.  
  232. socket.once('disconnect', function (reason, socketID, channels) {
  233. //let the customer know someone left their channels
  234. for(var channel in channels) {
  235. if(channel === socketID){
  236. //ignore
  237. }else{
  238. //trigger callback to customer
  239. callback = {
  240. 'status' : 'disconnected',
  241. 'channel' : channel,
  242. 'origin' : socket.request.headers['origin'],
  243. 'socket_id' : socketID
  244. };
  245.  
  246. io.to(channel).emit('info', callback);
  247. }
  248. }
  249.  
  250. console.log('A client has disconnected from from: ' + socket.request.headers['origin']);
  251.  
  252. pool.getConnection(function(err, connection) {
  253. var status = "disconnection";
  254. var key = socket.request.headers['origin'];
  255. var getAppInformation = 'SELECT * FROM users_app WHERE origin = ?';
  256.  
  257. connection.query(getAppInformation, [key], function(err, result, fields) {
  258. if (err) throw error
  259. if(result.length < 1){
  260. return
  261. }
  262.  
  263.  
  264. var status = "disconnection";
  265. var identifier = result[0]['users_app_id'];
  266.  
  267. track.customersConnections(identifier, status, pool);
  268.  
  269. });
  270. // And done with the connection.
  271. connection.release();
  272. });
  273. });
  274. });
  275.  
  276. // Listen to messages sent from the master. Ignore everything else.
  277. process.on('message', function(message, connection) {
  278. if (message !== 'sticky-session:connection') {
  279. return;
  280. }
  281.  
  282. // Emulate a connection event on the server by emitting the
  283. // event with the connection the master sent us.
  284. server.emit('connection', connection);
  285.  
  286. connection.resume();
  287. });
  288. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement