Advertisement
Guest User

Untitled

a guest
May 8th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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', {
  12.     auth_pass: "2V"
  13. });
  14. const sub = redis('6379', 'na-redis.pushthis.io', {
  15.     auth_pass: "y2V"
  16. });
  17.  
  18.  
  19. let track = require('./controllers/usagecontroller.js');
  20.  
  21. var port = 3000,
  22.     num_processes = require('os').cpus().length;
  23.  
  24. var pool = mysql.createPool({
  25.     connectionLimit: 150,
  26.     host: "",
  27.     user: "na-connections",
  28.     password: "",
  29.     database: "pushthis"
  30. });
  31.  
  32. if (cluster.isMaster) {
  33.     // This stores our workers. We need to keep them to be able to reference
  34.     // them based on source IP address. It's also useful for auto-restart,
  35.     // for example.
  36.     var workers = [];
  37.  
  38.     // Helper function for spawning worker at index 'i'.
  39.     var spawn = function(i) {
  40.         workers[i] = cluster.fork();
  41.  
  42.         // Optional: Restart worker on exit
  43.         workers[i].on('exit', function(code, signal) {
  44.             console.log('respawning worker', i);
  45.             spawn(i);
  46.         });
  47.         workers[i].on('disconnect', function(worker) {
  48.             console.log(workers[i].process.pid + 'disconnected -- rip')
  49.         })
  50.  
  51.         workers[i].on('online', (worker) => {
  52.             console.log(workers[i].process.pid)
  53.         })
  54.     };
  55.  
  56.     // Spawn workers.
  57.     for (var i = 0; i < num_processes; i++) {
  58.         spawn(i);
  59.     }
  60.  
  61.     var worker_index = function(n) {
  62.         return Math.floor(Math.random() * n)
  63.     };
  64.  
  65.     // Create the outside facing server listening on our port.
  66.     var server = net.createServer({
  67.         pauseOnConnect: true
  68.     }, function(connection) {
  69.         var worker = workers[worker_index(num_processes)];
  70.         worker.send('sticky-session:connection', connection);
  71.     }).listen(port);
  72. } else {
  73.     process.setMaxListeners(0);
  74.     // Note we don't use a port here because the master listens on it for us.
  75.     var app = new express();
  76.  
  77.     app.use(bodyParser.json({
  78.         limit: 5000
  79.     }))
  80.  
  81.     app.use(function(req, res, next) {
  82.         res.setHeader('Access-Control-Allow-Origin', '*');
  83.         res.header("Access-Control-Allow-Credentials: true");
  84.         res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  85.         next();
  86.     });
  87.  
  88.  
  89.     // Don't expose our internal server to the outside.
  90.     var server = app.listen(0, 'localhost'),
  91.         io = sio(server);
  92.  
  93.     // Tell Socket.IO to use the redis adapter. By default, the redis
  94.     // server is assumed to be on localhost:6379. You don't have to
  95.     // specify them explicitly unless you want to change them.
  96.     io.adapter(adapter({
  97.         pubClient: pub,
  98.         subClient: sub
  99.     }));
  100.  
  101.  
  102.  
  103.     // Here you might use Socket.IO middleware for authorization etc.
  104.     io.sockets.on('connection', function(socket) {
  105.  
  106.         var origin = socket.request.headers['origin'];
  107.         console.log('A client has connected to from: ' + origin);
  108.         if (origin === null || origin === undefined || origin === 'http://localhost') {
  109.  
  110.             //Emit the JSON data from RESTful API
  111.             socket.on('up3da3teF3romN3od3e0100010039303242##300', function(data) {
  112.                 console.log('payload sent out from rest api')
  113.                 socket.to(data.channel).emit(data.event, data.data)
  114.             });
  115.  
  116.             socket.on('authorized032490234uj29jdiofk90d0a', function(data){
  117.                 callback = {
  118.                     'status': 'socket-authorized',
  119.                     'channel': data.channel,
  120.                     'origin': data.origin,
  121.                     'socket_id': data.socket_id
  122.                 };
  123.  
  124.  
  125.                 //send back to the customers site
  126.                 socket.to(data.channel).emit('info', callback)
  127.                 console.log(data);
  128.             });
  129.  
  130.             socket.on('update-my-apps', function(data) {
  131.                 if(data.key === '0010010010010-updateMessages'){
  132.                   socket.to('pushthisNetwork').emit('my-apps', { appID: data.appID, messageTotal: data.messageTotal, messageCycle: data.messageCycle})
  133.                 }
  134.             });
  135.  
  136.  
  137.  
  138.             pool.getConnection(function(err, connection) {
  139.  
  140.                 //get connection origin
  141.                 var key = socket.handshake.query.key;
  142.                 var getAppInformation = "SELECT * FROM `users_app` WHERE `public_key` = ?";
  143.  
  144.                 connection.query(getAppInformation, [key], function(err, result, fields) {
  145.                     if (err) throw err
  146.  
  147.                     if (result.length < 1) {
  148.                       //trigger callback to origin/pushthis/auth
  149.                       callback = {
  150.                           'status': 'error',
  151.                           'key': key,
  152.                           'socket_id': socket.id,
  153.                           'message': 'Your key is not registered with Pushthis. Please register on pushthis.io to use our service.'
  154.                       };
  155.  
  156.                       //send back to the customers site
  157.                       return socket.emit('helpMePush-This', callback);
  158.                     }
  159.  
  160.  
  161.                   //count connections
  162.  
  163.  
  164.  
  165.                   //Client requesting to join a channel
  166.                   socket.on('join', function(data) {
  167.  
  168.                       console.log(data);
  169.  
  170.                       if (!data['channel']) {
  171.                           //error just return nothing and stop
  172.                           return
  173.                       }
  174.  
  175.                       //Client requesting to join public channel
  176.                       if (!data['presence'] || data['presence'] === false) {
  177.                           publicChannel = data['channel']
  178.                           socket.join(publicChannel)
  179.                       }
  180.  
  181.                       //Client requesting to join Presence channel
  182.                       if (data['presence'] === true && data['authorize'] === false ||
  183.                           data['presence'] === true && !data['authorize']) {
  184.                           presenceChannel = data['channel']
  185.  
  186.                           socket.join(presenceChannel)
  187.  
  188.                           //trigger callback to origin/pushthis/auth
  189.                           callback = {
  190.                               'status': 'connected',
  191.                               'channel': data['channel'],
  192.                               'origin': socket.request.headers['origin'],
  193.                               'socket_id': socket.id
  194.                           };
  195.  
  196.  
  197.                           //send back to the customers site
  198.                           io.to(presenceChannel).emit('info', callback);
  199.                       }
  200.  
  201.                       if (data['authorize'] === true) {
  202.                           presenceChannel = data['channel']
  203.                           //trigger callback to origin/pushthis/auth
  204.                           callback = {
  205.                               'status': 'waiting authorization',
  206.                               'channel': data['channel'],
  207.                               'origin': socket.request.headers['origin'],
  208.                               'socket_id': socket.id
  209.                           };
  210.  
  211.  
  212.                           //send back to the customers site
  213.                           io.emit('info', callback);
  214.                       }
  215.                   });
  216.               });
  217.             });
  218.         } else {
  219.             pool.getConnection(function(err, connection) {
  220.  
  221.                 //get connection origin
  222.                 var key = socket.request.headers['origin'];
  223.                 var getAppInformation = "SELECT * FROM `users_app` WHERE `origin` = ?";
  224.  
  225.                 connection.query(getAppInformation, [key], function(err, result, fields) {
  226.                     if (err) throw err
  227.  
  228.                     if (result.length < 1) {
  229.                       //trigger callback to origin/pushthis/auth
  230.                       callback = {
  231.                           'status': 'error',
  232.                           'origin': socket.request.headers['origin'],
  233.                           'socket_id': socket.id,
  234.                           'message': 'Your origin is not registered with Pushthis. Please register it to use our service.'
  235.                       };
  236.  
  237.                       //send back to the customers site
  238.                       socket.emit('helpMePush-This', callback);
  239.                       return socket.disconnect();
  240.                     }
  241.  
  242.  
  243.                     //tally customer connections
  244.  
  245.  
  246.                     //Client requesting to join a channel
  247.                     socket.on('join', function(data) {
  248.  
  249.                         console.log(data);
  250.  
  251.                         if (!data['channel']) {
  252.                             //error just return nothing and stop
  253.                             return
  254.                         }
  255.  
  256.                         //Client requesting to join public channel
  257.                         if (!data['presence'] || data['presence'] === false) {
  258.                             publicChannel = data['channel']
  259.                             socket.join(publicChannel)
  260.                         }
  261.  
  262.                         //Client requesting to join Presence channel
  263.                         if (data['presence'] === true && data['authorize'] === false ||
  264.                             data['presence'] === true && !data['authorize']) {
  265.                             presenceChannel = data['channel']
  266.  
  267.                             socket.join(presenceChannel)
  268.  
  269.                             //trigger callback to origin/pushthis/auth
  270.                             callback = {
  271.                                 'status': 'connected',
  272.                                 'channel': data['channel'],
  273.                                 'origin': socket.request.headers['origin'],
  274.                                 'socket_id': socket.id
  275.                             };
  276.  
  277.  
  278.                             //send back to the customers site
  279.                             console.log(result[0]['callback_url'];
  280.                             request.post({url: result[0]['callback_url'],
  281.                             form: {key:'value'}},
  282.                             function(err,httpResponse,body){
  283.                             console.log(httpResponse + ' and ' + body)})
  284.  
  285.                             io.to(presenceChannel).emit('info', callback);
  286.                         }
  287.  
  288.                         if (data['authorize'] === true) {
  289.                             presenceChannel = data['channel']
  290.                             //trigger callback to origin/pushthis/auth
  291.                             callback = {
  292.                                 'status': 'waiting authorization',
  293.                                 'channel': data['channel'],
  294.                                 'origin': socket.request.headers['origin'],
  295.                                 'socket_id': socket.id
  296.                             };
  297.  
  298.  
  299.                             //send back to the customers site
  300.                             io.emit('info', callback);
  301.                         }
  302.                     });
  303.  
  304.                     var status = "connection";
  305.                     var identifier = result[0]['users_app_id'];
  306.                     //var identifier = result['users_app_id'];
  307.                     track.customersConnections(identifier, status, pool, socket);;
  308.                 });
  309.                 // And done with the connection.
  310.                 connection.release();
  311.             });
  312.  
  313.             socket.once('disconnect', function(reason, socketID, channels) {
  314.                 //let the customer know someone left their channels
  315.                 for (var channel in channels) {
  316.                     if (channel === socketID) {
  317.                         //ignore
  318.                     } else {
  319.                         //trigger callback to customer
  320.                         callback = {
  321.                             'status': 'disconnected',
  322.                             'channel': channel,
  323.                             'origin': socket.request.headers['origin'],
  324.                             'socket_id': socketID
  325.                         };
  326.  
  327.                         io.to(channel).emit('info', callback);
  328.                     }
  329.                 }
  330.  
  331.  
  332.  
  333.  
  334.  
  335.                 var origin = socket.request.headers['origin'];
  336.                 console.log('A client has disconnected from from: ' + origin);
  337.                 if (origin === null || origin === undefined) {
  338.  
  339.                   //do nothing
  340.  
  341.                 }else{
  342.                   pool.getConnection(function(err, connection) {
  343.                     var status = "disconnection";
  344.                     var key = socket.request.headers['origin'];
  345.                     if(key === null || undefined){
  346.  
  347.                     }else{
  348.                       var getAppInformation = "SELECT * FROM `users_app` WHERE `origin` = ?";
  349.  
  350.                       connection.query(getAppInformation, [key], function(err, result, fields) {
  351.                           if (err) throw error
  352.                           if(result.length < 1){
  353.                             return
  354.                           }
  355.  
  356.                           io.emit('demo-2', 'Authorized.')
  357.                           var status     = "disconnection";
  358.                           var identifier = result[0]['users_app_id'];
  359.                           track.customersConnections(identifier, status, pool, socket);;
  360.                       });
  361.                     }
  362.                   // And done with the connection.
  363.                   connection.release();
  364.                   });
  365.                 }
  366.             });
  367.         }
  368.     });
  369.  
  370.     // Listen to messages sent from the master. Ignore everything else.
  371.     process.on('message', function(message, connection) {
  372.         if (message !== 'sticky-session:connection') {
  373.             return;
  374.         }
  375.  
  376.         // Emulate a connection event on the server by emitting the
  377.         // event with the connection the master sent us.
  378.         server.emit('connection', connection);
  379.  
  380.         connection.resume();
  381.     });
  382. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement