Skip to content

Instantly share code, notes, and snippets.

@hlmn
Created April 24, 2018 03:37
Show Gist options
  • Save hlmn/9c4a9e7b1fb25c47ea3059aef5e84803 to your computer and use it in GitHub Desktop.
Save hlmn/9c4a9e7b1fb25c47ea3059aef5e84803 to your computer and use it in GitHub Desktop.
client.js
/*jshint esversion: 6 */
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')
const os = require('os')
const spawn = require('child_process').spawn
const { exec } = require('child_process');
const ip = require('./ip.js');
var redis = require("redis")
let redisClient
var bluebird = require("bluebird");
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
const io = require('socket.io')(8888);
io.on('connection', function (skt) {
skt.emit('connected', 'connected');
console.log('connected');
skt.on('ganti_ip', function(msg){
var fs = require('fs');
fs.writeFile(__dirname+'/ip.txt', msg, function(err) {
if(err) {
return console.log(err);
}
console.log("IP Pusat diganti");
exec('echo "mmtitsmmtits" | sudo -S reboot');
});
});
// socket.on('connect', function (data) {
// socket.emit('connected', 'connected');
// });
});
let socket;
// var workerFlag = 0;
// var worker;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
const hostname = os.hostname();
// let workerSpawn = function(){
// worker = spawn('python', [__dirname+'/worker.py']);
// workerFlag=1;
// worker.stdout.on('data', function(data){
// // msg = ();
// console.log(data.toString());
// // mainWindow.webContents.send('message', msg);
// // console.log(msg)
// });
// worker.stdout.on('end', function(data){
// workerFlag = 0
// console.log('worker down')
// // mainWindow.webContents.send('app_closed', 'modul nfc terputus');
// });
// }
// workerSpawn();
var initRedis = function(){
redisClient = redis.createClient({
enable_offline_queue:false,
function (options) {
return 1000
}
});
redisClient.on('error', () =>{
app.relaunch()
// app.exit()
})
redisClient.on('ready', () => {
createWindow()
})
}
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
// mainWindow.webContents.openDevTools();
mainWindow.setFullScreen(true);
mainWindow.webContents.on('did-finish-load', () => {
setInterval(function(){
var test = ip.addr();
mainWindow.webContents.send('ipaddr', test);
}, 5000);
mainWindow.webContents.send('kelas', hostname.replace(/_/g,' '));
// mainWindow.webContents.send('ipaddr', 'kontol');
const py = spawn('python', [__dirname+'/kelas.py'])
py.stdout.on('data', function(data){
console.log(data.toString())
msg = JSON.parse(data.toString());
if(typeof msg.serial !== 'undefined'){
// console.log("dsadsadas"+msg.serial);
mainWindow.webContents.send('scan', { response : "Scanning..." });
io.emit('daftar', msg);
}
else{
if(msg.response === 'Tidak ada respon dari server, data telah ditampung!' || msg.response === 'Data telah masuk ke dalam server'){
// socket.emit('jalaninworker', 'tes');
// worker = spawn('python', [__dirname+'/worker.py']);
// worker.stdout.on('data', function(data){
// msg = data.toString() ;
// console.log(msg);
// mainWindow.webContents.send('message', msg);
// // console.log(msg)
// });
// console.log('mencoba worker ke redis server')
// if(workerFlag === 0){
// workerSpawn();
// }
}
mainWindow.webContents.send('message', msg);
}
// console.log(msg)
});
py.stdout.on('end', function(data){
console.log('modul terputus')
// mainWindow.webContents.send('app_closed', 'modul nfc terputus');
});
var baca = require('fs');
baca.readFile(__dirname+'/ip.txt', (err, ipPusat) => {
if (err) throw err;
console.log('anjeng')
var bacaQueue = require('fs');
bacaQueue.readFile(__dirname+'/queueId.txt', (err, id) => {
listen(ipPusat, id);
});
});
});
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
function listen(ipPusat, queueId){
console.log('http://'+ipPusat.toString().replace(/\n/g, '')+':9999')
var queueId = queueId.toString().replace(/\n/g, '');
socket = require('socket.io-client')('http://'+ipPusat.toString().replace(/\n/g, '')+':9999');
socket.on('connect', function(){
console.log(hostname);
socket.emit('id', {
ruangan : hostname,
ip : ip.addr()
});
socket.emit('startRabbit', {
ruangan : hostname,
queueId : queueId
})
const worker = spawn('python', [__dirname+'/worker.py'])
worker.stdout.on('data', function(data){
msg = data.toString();
msg = JSON.parse(msg)
console.log(msg);
mainWindow.webContents.send('message', msg);
console.log('connected, running worker');
});
worker.stdout.on('end', function(data){
console.log('worker down')
});
});
socket.on('rabbitOn', function(data){
socket.emit('startRabbit', {
ruangan : hostname,
queueId : queueId
});
});
socket.on('consume', function(data, fn){
console.log(data)
// fn('woot')
redisClient.lpushAsync('logs-mesin', data).then((res) =>{
console.log(data+' was pushed to logs with index '+ res)
fn(data)
})
})
socket.on('worker', function(data){
// socket.emit('id', hostname);
console.log(data);
const worker = spawn('python', [__dirname+'/worker.py']);
// if(workerFlag === 0){
// workerSpawn();
// }
worker.stdout.on('data', function(data){
console.log('connected, running worker');
msg = data.toString();
msg = JSON.parse(msg)
console.log(msg);
mainWindow.webContents.send('message', msg);
// console.log(msg)
});
worker.stdout.on('end', function(data){
console.log('worker down')
// console.log(msg)
});
});
socket.on('event', function(data){
});
socket.on('disconnect', function(){
console.log('disconnected');
});
socket.on('reboot', function(){
exec('echo "mmtitsmmtits" | sudo -S reboot');
});
socket.on('flush', function(){
console.log('cek_flush');
exec("mysql -u root -Nse 'show tables' mmtitsbaru | while read table; do mysql -u root -e "+'"SET FOREIGN_KEY_CHECKS=0;truncate table $table;SET FOREIGN_KEY_CHECKS=1;"'+" mmtitsbaru; done", (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
// console.log(`stdout: ${stdout}`);
// console.log(`stderr: ${stderr}`);
console.log('flush selesai');
socket.emit('flush_info', socket.id)
});
});
socket.on('gantiHostname', function(msg){
socket.emit('gantiHostInfo', {
lama : hostname,
baru :msg,
queueLama: queueId,
ip : ip.addr()
}, (data) => {
var fs = require('fs');
fs.writeFile(__dirname+'/queueId.txt', data, function(err) {
if(err) {
return console.log(err);
}
console.log("IP Pusat diganti");
initSyncDB = exec('python '+__dirname+'/initSyncDB.py '+ msg, { maxBuffer : 5000*1024 },(error, stdout, stderr) => {
if(error) {
console.log(error)
return;
}
else exec("echo "+'"mmtitsmmtits"'+" | sudo -S sed -i 's/"+hostname+"/"+msg+"/g' /etc/hosts;echo "+'"mmtitsmmtits"'+" | sudo -S sed -i 's/"+hostname+"/"+msg+"/g' /etc/hostname;echo "+'"mmtitsmmtits"'+" | sudo -S reboot");
})
});
})
// console.log("echo "+'"mmtitsmmtits"'+" | sudo -S sed -i 's/"+hostname+"/"+msg+"/g' /etc/hosts;echo "+'"mmtitsmmtits"'+" | sudo -S sed -i 's/"+hostname+"/"+msg+"/g' /etc/hostname;echo "+'"mmtitsmmtits"'+" | sudo -S reboot")
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', initRedis)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
// app.on('activate', function () {
// // On OS X it's common to re-create a window in the app when the
// // dock icon is clicked and there are no other windows open.
// // mainWindow.webContents.send('store-data', 'adsads');
// if (mainWindow === null) {
// createWindow()
// }
// })
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment