Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var express = require('express'),
- cluster = require('cluster'),
- net = require('net'),
- sio = require('socket.io'),
- farmhash = require('farmhash'),
- bodyParser = require('body-parser'),
- mysql = require('mysql');
- const redis = require('redis').createClient;
- const adapter = require('socket.io-redis');
- const pub = redis('6379', 'na-redis.pushthis.io', { auth_pass: "yXcYn8ZQH5tVsakvgcvD3q2V" });
- const sub = redis('6379', 'na-redis.pushthis.io', { auth_pass: "yXcYn8ZQH5tVsakvgcvD3q2V" });
- let track = require('./controllers/useagecontroller.js');
- var port = 3000,
- num_processes = require('os').cpus().length;
- var pool = mysql.createPool({
- connectionLimit : 150,
- host: "45.76.19.242",
- user: "na-connections",
- password: "R4f0gjuKAMTm9ubF",
- database: "pushthis"
- });
- if (cluster.isMaster) {
- // This stores our workers. We need to keep them to be able to reference
- // them based on source IP address. It's also useful for auto-restart,
- // for example.
- var workers = [];
- // Helper function for spawning worker at index 'i'.
- var spawn = function(i) {
- workers[i] = cluster.fork();
- // Optional: Restart worker on exit
- workers[i].on('exit', function(code, signal) {
- console.log('respawning worker', i);
- spawn(i);
- });
- workers[i].on('disconnect', function(worker) {
- console.log(workers[i].process.pid + 'disconnected -- rip')
- })
- workers[i].on('online', (worker) => {
- console.log(workers[i].process.pid)
- console.log('notice me senpie')
- })
- };
- // Spawn workers.
- for (var i = 0; i < num_processes; i++) {
- spawn(i);
- }
- var worker_index = function(n) {
- return Math.floor(Math.random() * n)
- };
- // Create the outside facing server listening on our port.
- var server = net.createServer({ pauseOnConnect: true }, function(connection) {
- var worker = workers[worker_index(num_processes)];
- worker.send('sticky-session:connection', connection);
- }).listen(port);
- } else {
- process.setMaxListeners(0);
- // Note we don't use a port here because the master listens on it for us.
- var app = new express();
- app.use(bodyParser.json({
- limit: 5000
- }))
- app.use(function(req, res, next) {
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.header("Access-Control-Allow-Credentials: true");
- res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
- next();
- });
- // Don't expose our internal server to the outside.
- var server = app.listen(0, 'localhost'),
- io = sio(server);
- // Tell Socket.IO to use the redis adapter. By default, the redis
- // server is assumed to be on localhost:6379. You don't have to
- // specify them explicitly unless you want to change them.
- io.adapter(adapter({ pubClient: pub, subClient: sub }));
- // Here you might use Socket.IO middleware for authorization etc.
- io.sockets.on('connection', function (socket) {
- var origin = socket.request.headers['origin'];
- console.log('A client has connected to from: ' + origin);
- io.emit('demo-2', 'Authorizing your connection..');
- pool.getConnection(function(err, connection) {
- //get connection origin
- var key = socket.request.headers['origin'];
- if(key === null){
- //Client requesting to join a channel
- socket.on('join', function (data) {
- console.log(data);
- if(!data['channel']){
- //error just return nothing and stop
- return
- }
- //Client requesting to join public channel
- if(!data['presense'] || data['presense'] === false){
- publicChannel = data['channel']
- socket.join(publicChannel)
- }
- //Client requesting to join Presence channel
- if(data['presence'] === true && data['authorize'] === false ||
- data['presence'] === true && !data['authorize']){
- presenceChannel = data['channel']
- socket.join(presenceChannel)
- //trigger callback to origin/pushthis/auth
- callback = {
- 'status' : 'connected',
- 'channel' : data['channel'],
- 'origin' : socket.request.headers['origin'],
- 'socket_id' : socket.id
- };
- //send back to the customers site
- io.to(presenceChannel).emit('info', callback);
- }
- if(data['authorize'] === true){
- presenceChannel = data['channel']
- //trigger callback to origin/pushthis/auth
- callback = {
- 'status' : 'waiting authorization',
- 'channel' : data['channel'],
- 'origin' : socket.request.headers['origin'],
- 'socket_id' : socket.id
- };
- //send back to the customers site
- io.to(presenceChannel).emit('info', callback);
- }
- });
- }
- var getAppInformation = 'SELECT * FROM users_app WHERE origin = ?';
- connection.query(getAppInformation, [key], function(err, result, fields) {
- if (err) throw err
- if(result.length < 1){
- }
- //Client requesting to join a channel
- socket.on('join', function (data) {
- console.log(data);
- if(!data['channel']){
- //error just return nothing and stop
- return
- }
- //Client requesting to join public channel
- if(!data['presense'] || data['presense'] === false){
- publicChannel = data['channel']
- socket.join(publicChannel)
- }
- //Client requesting to join Presence channel
- if(data['presence'] === true && data['authorize'] === false ||
- data['presence'] === true && !data['authorize']){
- presenceChannel = data['channel']
- socket.join(presenceChannel)
- //trigger callback to origin/pushthis/auth
- callback = {
- 'status' : 'connected',
- 'channel' : data['channel'],
- 'origin' : socket.request.headers['origin'],
- 'socket_id' : socket.id
- };
- //send back to the customers site
- io.to(presenceChannel).emit('info', callback);
- }
- if(data['authorize'] === true){
- presenceChannel = data['channel']
- //trigger callback to origin/pushthis/auth
- callback = {
- 'status' : 'waiting authorization',
- 'channel' : data['channel'],
- 'origin' : socket.request.headers['origin'],
- 'socket_id' : socket.id
- };
- //send back to the customers site
- io.to(presenceChannel).emit('info', callback);
- }
- });
- var status = "connection";
- var identifier = result[0]['users_app_id'];
- //var identifier = result['users_app_id'];
- track.customersConnections(identifier, status, pool);
- });
- // And done with the connection.
- connection.release();
- });
- socket.on('000100', function(data){
- console.log('okkkayy');
- });
- socket.once('disconnect', function (reason, socketID, channels) {
- //let the customer know someone left their channels
- for(var channel in channels) {
- if(channel === socketID){
- //ignore
- }else{
- //trigger callback to customer
- callback = {
- 'status' : 'disconnected',
- 'channel' : channel,
- 'origin' : socket.request.headers['origin'],
- 'socket_id' : socketID
- };
- io.to(channel).emit('info', callback);
- }
- }
- console.log('A client has disconnected from from: ' + socket.request.headers['origin']);
- pool.getConnection(function(err, connection) {
- var status = "disconnection";
- var key = socket.request.headers['origin'];
- var getAppInformation = 'SELECT * FROM users_app WHERE origin = ?';
- connection.query(getAppInformation, [key], function(err, result, fields) {
- if (err) throw error
- if(result.length < 1){
- return
- }
- var status = "disconnection";
- var identifier = result[0]['users_app_id'];
- track.customersConnections(identifier, status, pool);
- });
- // And done with the connection.
- connection.release();
- });
- });
- });
- // Listen to messages sent from the master. Ignore everything else.
- process.on('message', function(message, connection) {
- if (message !== 'sticky-session:connection') {
- return;
- }
- // Emulate a connection event on the server by emitting the
- // event with the connection the master sent us.
- server.emit('connection', connection);
- connection.resume();
- });
- }
Add Comment
Please, Sign In to add comment