Last active
April 24, 2018 03:36
-
-
Save hlmn/c4c453d1052fa53bab6a0dcc8df07b5f to your computer and use it in GitHub Desktop.
server.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var client = {}; | |
var ruanganlist = {}; | |
var ipmesin = {}; | |
let webServerPort; | |
var net = require('net'); | |
var HOST = '127.0.0.1'; | |
var PORT = 8000; | |
var workerFlag = 0; | |
var axios = require('axios'); | |
var cek=0; | |
const spawn = require('child_process').spawn | |
var app = require('express')(); | |
var server = require('http').Server(app); | |
var io = require('socket.io')(server); | |
const uuidv4 = require('uuid/v4'); | |
var amqp = require('amqplib'); | |
// var rabbitMq = amqp.createConnection({ url: 'amqp://hlmn:[email protected]:5672' | |
// , reconnect: true | |
// , reconnectBackoffStrategy: 'linear' | |
// , reconnectExponentialLimit: 120000 | |
// , reconnectBackoffTime: 1000 | |
// }); | |
var jose = require('node-jose'); | |
server.listen(9999); | |
var redis =require("redis"); | |
var masukin = redis.createClient({ | |
enable_offline_queue:false, | |
}); | |
var moment = require('moment-timezone'); | |
var bluebird = require("bluebird"); | |
bluebird.promisifyAll(redis.RedisClient.prototype); | |
bluebird.promisifyAll(redis.Multi.prototype); | |
// bluebird.promisifyAll(redis.Multi.prototype); | |
// var masukin = redis.createClient({ | |
// enable_offline_queue:false, | |
// }); | |
var statusServer = 0; | |
var bodyParser = require('body-parser') | |
app.use( bodyParser.json() ); // to support JSON-encoded bodies | |
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies | |
extended: true | |
})); | |
let worker; | |
var TESSS = '{"d":"LPB7p2mH80oEcx1tAjJEXPYkh_MfqT3YDj0pUyZclw-8gdMm15REZK_lNPQXaYqt6s5qaZDtN8ytQBDWWlZPdLor3DjLX-bHkr1hOBf94vtpcbGgpi64xuUoG--tUnCqaIdNU84x8px2l99IUdsmuAuZcf-XxD5GPHRTYY1MSOj0u6rTwFw1NP4iGI751cSi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fsD0_EDdxA2bJulOaRo1jepcvE0undsO1Q8JeJ_bpaIWiWMn0fVLuYNQA_RlW7mMQfd0sEbYFHSfDO1OqOtukMcFs62vZmih7INtN_bCPS4c4gE2EMHL9n5V2F9TB5FQHx97dqwEMWljIvBTYsM","qi":"OFTFEhHAYuIEelPiVeh0sqGmKVGWIKAu8-PV4kPGuc-CuU4_9WkhQvY955ZHThEM06VBfSCfyv13fEg-GLI70QWgstt_sMPY5j0zEDUcGLeNm4Tux-BxpXCQw6XF6BYPF1d35U7VZrEWmDSdqQxqAEQ8GyXAS_8H5NqoyLYay38","enc":"A256GCM","alg":"RSA-OAEP"}'; | |
// if you'd like to select database 3, instead of 0 (default), call | |
// client.select(3, function() { /* ... */ }); | |
var kunciVerif = '{"k":"QMeHEupswaLv5uFNPgqdZF-PsAs9_emFG8g-aear8XM","kty":"oct","alg":"HS256"}'; | |
masukin.on("error", function (err) { | |
console.log("Error " + err); | |
}); | |
let VerifyDecrypt = function(token){ | |
return jose.JWK.asKey(JSON.parse(TESSS)). | |
then(function(key) { | |
return key | |
// jose.JWE.createDecrypt(key). | |
// decrypt('eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ.GMtIPD6SuEXN3cscvRTNUAmI32PVZyMBhNX94FYnSb0JeEor18YxcdL7pernUezWNFW9cdbUlTr_Anhm6S7HbVVQwkpDg1znPXFnXVIoZtEcLup76da1e_y-gMmuDUa8WnJDQ3JBiO44c0lbOnPoczSDCrvZfvlufJ2zfMvKBDbAlUbROsA8lro-EWFHYmV5Kfva95w8kmrKVBG8ZQMKFiZ-1g3l-MwaDLb95PzTSZ0viUCAmnKml5GDg5aUTYzSM6n7i-EXg02yU3zjZOqOuA7ltdQFBZq3UhiyQZvPc98QFSgRJ12aTNr98qvgrGmNkl0qor1XMpJljzBIDmQvSQ.cEmRJC7_ez643Ugx.MJWdWi2mmpVDBQupMLmYsvk21thSgBIVJbqavRX6C7-bJUfklu1zKBCc7tM-6L0vEvEfke22HnkkqCUm6PXa7SHhulYzLxZP9Ih6rf9CMJXLuIySgX1OjUQNXsLNHr1PMTF1my806kBP_feP1TwPmHPjp_4GiqZy_HKCSag-D6SJHVzP1WO7iqeUGxU9_KU5ee7rRRQXWFrJz93LDwM443O0JHe2AKFMhaOV7lWJ0HaRHHIHHqo0IfuLmb8AixUvz62PPYmNOuWkKks5rrKlYjUJ2rH2Y6JgzaHI6GnJYUvwdBJi_cyrTyWnEVS4PUgsjFY9Obyh9f8LdN3UMv7XdK33xJnU9cBtyPCM_GUqhcs7D7ri72Dnov0.69W-u28RN8ZCDENwZ7P-jQ'). | |
// then(function(result) { | |
// return result; | |
// }); | |
}); | |
// console.log(test); | |
} | |
let rabbitMqConnection | |
retryRmqConnection = () =>{ | |
if (rabbitMqConnection!==null)console.log('retry connection to rabbitMq') | |
rabbitMq = amqp.connect('amqp://hlmn:[email protected]:5672').then((conn) => { | |
rabbitMqConnection = conn | |
console.log('readyrabbit') | |
io.emit('rabbitOn', 'rabbit') | |
conn.on('close', function(err){ | |
setTimeout( function() { | |
retryRmqConnection() | |
}, 0 ); | |
}) | |
}).catch( (err) => { | |
rabbitMqConnection = null | |
setTimeout( function() { | |
retryRmqConnection() | |
}, 0 ); | |
}) | |
} | |
var rabbitMq = amqp.connect('amqp://hlmn:[email protected]:5672').then((conn) => { | |
rabbitMqConnection = conn | |
conn.on('close', function(err){ | |
retryRmqConnection() | |
}) | |
}).catch((err)=>{ | |
console.log(err) | |
retryRmqConnection() | |
}) | |
//buat yang ke redis | |
app.post('/', function (req, res) { | |
var JWK = VerifyDecrypt('dsadas'); | |
JWK.then(function(result){ | |
jose.JWE.createDecrypt(result). | |
decrypt(req.body.token). | |
then(function(ea) { | |
jose.JWK.asKey(JSON.parse(kunciVerif)). | |
then(function(key) { | |
jose.JWS.createVerify(key). | |
verify(ea.payload.toString()). | |
then(function(hasil) { | |
var payload = JSON.parse(hasil.payload.toString()); | |
if(parseInt(payload.exp)*1000 < Date.now()) res.send('{"response" : "Data expired"}'); | |
if(statusServer === 1){ //buktiin kalo dia nyala workernya | |
console.log('request') | |
console.log(payload) | |
axios.post('http://127.0.0.1:8000/absen/add/workerQueue', payload) | |
.then(function (response) { | |
console.log(response.data); | |
res.send('{"response" : "Data masuk sistem informasi"}'); | |
}) | |
.catch(function (error) {//kalo gagal | |
masukin.lpushAsync("queue", hasil.payload.toString()).then(function(data) { | |
res.send('{"response" : "Data telah masuk ke dalam queue server"}'); | |
}).catch(function(err){ | |
console.log(err); | |
res.send('{"response" : "Data gagal push"}'); | |
}) | |
}); | |
} | |
else{ | |
masukin.lpushAsync("queue", hasil.payload.toString()).then(function(data) { | |
res.send('{"response" : "Data telah masuk ke dalam queue server"}'); | |
}).catch(function(err){ | |
console.log(err); | |
res.send('{"response" : "Data gagal push"}'); | |
}) | |
} | |
}).catch(function (err){ | |
console.log(err);res.send('gagal 2'); | |
});; | |
}).catch(function (err){ | |
console.log(err);res.send('gagal 3'); | |
}); | |
}).catch(function (err){ | |
console.log(err);res.send('gagal 4'); | |
}); | |
}).catch(function (err){ | |
console.log(err);res.send('gagal 5'); | |
});; | |
}); | |
// rabbitMq.on('ready', function()) | |
io.on('connection', function (socket) { | |
var consumerChannel; | |
//nunjukin id dari socketnya | |
// socket.emit('worker', 'a'); | |
console.log(socket.id+' connected'); | |
socket.on('disconnect', function () { | |
console.log(socket.id+' disconnected'); | |
var delMesin = () => { | |
delete ruanganlist[client[socket.id]].splice(ruanganlist[client[socket.id]].indexOf(socket.id), 1); | |
if (typeof ruanganlist[client[socket.id]][0] === 'undefined') delete ruanganlist[client[socket.id]]; | |
delete client[socket.id]; | |
delete ipmesin[socket.id]; | |
if(rabbitMqConnection!== null){ | |
consumerChannel.close().then(() => { | |
console.log('rabbitMq connection closed') | |
}) | |
.catch(console.log('rabbitMq connection already closed')) | |
} | |
// console.log(consumerConn) | |
// console.log(cl | |
io.emit('klien', { | |
ruanganlist : ruanganlist, | |
ip : ipmesin}); | |
io.emit('klien1',{ | |
clientList : client, | |
}); | |
console.log(client); | |
console.log(ruanganlist); | |
} | |
// console.log('ini' + Object.keys(client)); | |
if (typeof client[socket.id] !== 'undefined'){ | |
axios.get('http://127.0.0.1:8000/mesin/add/log', { | |
params: { | |
tipe: 'mati', | |
ruangan: client[socket.id], | |
created_at: Math.round(new Date().getTime()/1000), | |
socket_id: socket.id, | |
ip:ipmesin[socket.id] | |
} | |
}) | |
.then(function (response) { | |
var waktu = moment.utc(response['data']['created_at']).tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'); | |
// console.log(response) | |
io.emit('mesinMati',{ | |
ruangan : response['data']['id_kelas'], | |
ip : response['data']['ip'], | |
created_at : waktu, | |
id :response['data']['socket_id'], | |
}) | |
delMesin(); | |
}) | |
.catch(function (error) { | |
io.emit('mesinMati',{ | |
ruangan : client[socket.id], | |
ip : ipmesin[socket.id], | |
created_at : moment.utc(Math.round(new Date().getTime())).tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'), | |
id : socket.id, | |
}) | |
console.log('error') | |
delMesin(); | |
}); | |
} | |
}); | |
socket.on('list_mesin', function(msg){ | |
console.log(msg); | |
socket.emit('klien',{ | |
ruanganlist : ruanganlist, | |
ip : ipmesin | |
}) | |
}) | |
socket.on('list_mesin_klien', function(msg){ | |
console.log(msg); | |
socket.emit('klien1',{ | |
clientList : client, | |
}) | |
}) | |
socket.on('reboot_mesin', function(msg){ | |
console.log(msg); | |
socket.to(msg).emit('reboot',msg); | |
}) | |
socket.on('flush_table', function(msg){ | |
console.log(msg); | |
socket.to(msg).emit('flush',msg); | |
}) | |
socket.on('flush_info', function(msg){ | |
console.log(msg); | |
axios.get('http://127.0.0.1:8000/mesin/add/log', { | |
params: { | |
tipe: 'flush', | |
ruangan: client[socket.id], | |
created_at: Math.round(new Date().getTime()/1000), | |
socket_id: socket.id, | |
ip:ipmesin[socket.id] | |
} | |
}) | |
.then(function (response) { | |
var waktu = moment.utc(response['data']['created_at']).tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'); | |
// console.log(response) | |
io.emit('flushTable',{ | |
ruangan : response['data']['id_kelas'], | |
ip : response['data']['ip'], | |
created_at : waktu, | |
id :response['data']['socket_id'], | |
}) | |
}) | |
.catch(function (error) { | |
io.emit('flushTable',{ | |
ruangan : client[socket.id], | |
ip : ipmesin[socket.id], | |
created_at : moment.utc(Math.round(new Date().getTime())).tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'), | |
id : socket.id, | |
}) | |
console.log('error') | |
}); | |
}) | |
socket.on('startRabbit', function(msg){ | |
console.log('startRabbit : ', msg) | |
try { | |
rabbitMqConnection.createChannel().then(function(ch) { | |
consumerChannel = ch | |
var ok = ch.assertExchange(msg['ruangan'], 'fanout', {durable: true}); | |
ok = ok.then(function() { | |
return ch.assertQueue(msg['queueId'], {exclusive: false, durable:true}); | |
}); | |
ok = ok.then(function(qok) { | |
return ch.bindQueue(qok.queue, msg['ruangan'], '').then(function() { | |
return qok.queue; | |
}); | |
}); | |
ok = ok.then(function(queue) { | |
return ch.consume(queue, logMessage, {noAck: false}); | |
}); | |
return ok.then(function() { | |
console.log(' [*] Waiting for '+msg['ruangan']+'.'); | |
}); | |
function logMessage(msg) { | |
console.log("emitting : ", msg.content.toString()); | |
console.log(socket.id) | |
socket.emit('consume', msg.content.toString(), function(data){ | |
console.log('ack', data) | |
ch.ack(msg); | |
}); | |
} | |
}).catch(console.warn); | |
} | |
catch(err){ | |
console.log(err) | |
} | |
}) | |
socket.on('gantiHostInfo', function(msg,fn){ | |
queueBaru = uuidv4(); | |
queueLama = msg['queueLama']; | |
amqp.connect('amqp://hlmn:[email protected]:5672').then(function(conn) { | |
// process.once('SIGINT', function() { conn.close(); }); | |
return conn.createChannel().then(function(ch) { | |
var ok = ch.assertExchange(msg['baru'], 'fanout', {durable: true}); | |
ok = ok.then(function() { | |
return ch.assertQueue(queueBaru, {exclusive: false, durable:true}); | |
}); | |
ok = ok.then(function(qok) { | |
return ch.bindQueue(qok.queue, msg['baru'], '').then(function() { | |
return qok.queue; | |
}); | |
}); | |
ok = ok.then(() => { | |
return consumerChannel.close() | |
}) | |
ok = ok.then((queue) => { | |
return ch.deleteQueue(queueLama) | |
}) | |
ok = ok.then(() => { | |
return conn.close() | |
}) | |
ok = ok.then(() => { | |
fn(queueBaru); | |
console.log(msg); | |
axios.get('http://127.0.0.1:8000/mesin/add/log', { | |
params: { | |
tipe: 'gantiHost', | |
ruangan: msg['lama'], | |
created_at: Math.round(new Date().getTime()/1000), | |
socket_id: socket.id, | |
ip:ipmesin[socket.id], | |
ruangan_baru:msg['baru'], | |
} | |
}) | |
.then(function (response) { | |
var waktu = moment.utc(response['data']['created_at']).tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'); | |
// console.log(response) | |
io.emit('gantiHostName',{ | |
lama : response['data']['id_kelas'], | |
baru : response['data']['id_kelas_baru'], | |
ip : response['data']['ip'], | |
created_at : waktu, | |
id :response['data']['socket_id'], | |
}) | |
}) | |
.catch(function (error) { | |
io.emit('gantiHostName',{ | |
lama : msg['lama'], | |
baru : msg['baru'], | |
ip : ipmesin[socket.id], | |
created_at : moment.utc(Math.round(new Date().getTime())).tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'), | |
id : socket.id, | |
}) | |
console.log('error') | |
}); | |
}) | |
}); | |
}) | |
.catch((err) => console.log(err)); | |
}) | |
socket.on('gantiAlamat', function(msg){ | |
console.log(msg.hostname); | |
socket.to(msg.id).emit('gantiHostname',msg.hostname); | |
}) | |
socket.on('mobile', function(msg){ | |
console.log(msg); | |
}); | |
socket.on('connected', function(){ | |
console.log('a'); | |
}); | |
socket.on('id', function (msg){ | |
console.log(msg['ruangan']); | |
ipmesin[socket.id] = msg['ip']; | |
client[socket.id] = msg['ruangan']; | |
if (typeof ruanganlist[msg['ruangan']] !== 'undefined') { | |
ruanganlist[msg['ruangan']].push(socket.id); | |
} | |
else ruanganlist[msg['ruangan']] = [socket.id]; | |
io.emit('klien', { | |
ruanganlist : ruanganlist, | |
ip : ipmesin | |
}) | |
axios.get('http://127.0.0.1:8000/mesin/add/log', { | |
params: { | |
tipe: 'nyala', | |
ruangan: client[socket.id], | |
created_at: Math.round(new Date().getTime()/1000), | |
socket_id: socket.id, | |
ip:ipmesin[socket.id], | |
} | |
}) | |
.then(function (response) { | |
var waktu = moment.utc(response['data']['created_at']).tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'); | |
console.log(waktu) | |
io.emit('alertMesin',{ | |
nama : response['data']['id_kelas'], | |
ip : response['data']['ip'], | |
created_at : waktu, | |
id :response['data']['socket_id'], | |
}) | |
// delMesin(); | |
}) | |
.catch(function (error) { | |
io.emit('alertMesin',{ | |
nama : msg['ruangan'], | |
ip : msg['ip'], | |
created_at : moment.utc(Math.round(new Date().getTime())).tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'), | |
id : socket.id, | |
}) | |
console.log('error') | |
}); | |
console.log(client); | |
console.log(ruanganlist); | |
}); | |
}); | |
function b(){ | |
webServerPort = new net.Socket(); | |
webServerPort.setKeepAlive(true); | |
webServerPort.connect(PORT, HOST, function(){ | |
// socket.emit(i) | |
if (cek == 1){ | |
console.log('cek sekali'+cek) | |
cek = 0; | |
} | |
else{ | |
io.emit('worker', 'jalan'); | |
// console.log('emit') | |
cek = 0; | |
} | |
statusServer = 1; | |
console.log('CONNECTED TO: ' + HOST + ':' + PORT); | |
// io.emit('worker', 'worker client jalan!'); | |
setTimeout(function(){ | |
worker = spawn('python', [__dirname+'/worker.py']); | |
worker.stdout.on('data', function(data){ | |
console.log(data.toString()); | |
}); | |
worker.stdout.on('end', function(data){ | |
workerFlag = 0 | |
console.log('worker down') | |
// mainWindow.webContents.send('app_closed', 'modul nfc terputus'); | |
}); | |
}, 2000); | |
console.log('worker jalanin ke laravel') | |
}); | |
webServerPort.on('error', function(e) { | |
statusServer =0; | |
console.log('dc : '+ statusServer) | |
if(e.code == 'ECONNREFUSED') { | |
webServerPort.destroy() | |
// console.log('Is the server running at ' + PORT + '?'); | |
// console.log('koneksi putus') | |
} | |
webServerPort.destroy() | |
}); | |
webServerPort.on('data', function(data) { | |
statusServer =0; | |
console.log('dc : '+ statusServer) | |
console.log('DATA: ' + data); | |
webServerPort.destroy(); | |
}); | |
webServerPort.on('close', function() { | |
++cek; | |
statusServer =0; | |
console.log('dc : '+ statusServer) | |
// setTimeout(b, 1000); | |
b(); | |
}); | |
} | |
b(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment