Skip to content

Commit

Permalink
#2 Add websocket support and random qr code in start page
Browse files Browse the repository at this point in the history
  • Loading branch information
Baiyuan Wang committed Jun 21, 2019
1 parent b7c50c7 commit bdc9a47
Show file tree
Hide file tree
Showing 6 changed files with 202 additions and 22 deletions.
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
"electron-updater": "^4.0.6",
"fireworks-react": "^1.0.12",
"jquery": "^3.4.1",
"js-base64": "^2.5.1",
"lodash": "^4.17.11",
"qrcode.react": "^0.9.3",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-edit-inline": "^1.0.8",
Expand All @@ -36,7 +39,8 @@
"react-table": "^6.10.0",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"uuid": "^3.3.2"
"uuid": "^3.3.2",
"ws": "^7.0.0"
},
"devDependencies": {
"concurrently": "^4.1.0",
Expand Down
153 changes: 136 additions & 17 deletions public/electron.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,28 @@
const electron = require('electron');
const { autoUpdater } = require("electron-updater")
const { autoUpdater } = require("electron-updater");
const WebSocket = require('ws');

const path = require('path');
const http = require('http');
const url = require('url');
const isDev = require('electron-is-dev');
const uuidv4 = require('uuid/v4');
const flatten = require('lodash/flatten');

const package = require('../package');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const menu = electron.Menu;

let masterSocket;
let agentSocket;
let serverPort = 10086;

let mainWindow;

let activityID;
let token;

menu.setApplicationMenu(menu.buildFromTemplate([
{
label: 'Edit',
Expand Down Expand Up @@ -34,30 +53,130 @@ menu.setApplicationMenu(menu.buildFromTemplate([
]
}
]));
const path = require('path');
const url = require('url');
const isDev = require('electron-is-dev');

let mainWindow;
app.on('ready', initApp);
app.on('window-all-closed', () => {
app.quit();
agentSocket.close(() => {
console.log("Server closed.")
});
});
app.on('activate', initApp);

function initApp() {
if (!mainWindow) {
createWindow();
}
if (!agentSocket) {
createServer();
}
}


function createWindow() {
mainWindow = new BrowserWindow({ width: 1024, height: 768 });
mainWindow.loadURL(isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, '../build/index.html')}`);
const homeURL = isDev ? 'http://localhost:3000/' : `file://${path.join(__dirname, '../build/index.html')}`;
mainWindow.loadURL(`${homeURL}`);
mainWindow.on('closed', () => mainWindow = null);
mainWindow.setAutoHideMenuBar(true);
autoUpdater.checkForUpdatesAndNotify();
}

app.on('ready', createWindow);
function createServer() {
const serverIPInfo = getServerIPInfo();

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
const server = http.createServer();
server.listen(serverPort, '0.0.0.0');
server.on('listening', () => {
console.log(`Server listen on ${server.address().address}:${server.address().port}, activityID: ${activityID}`);
});
server.on('error', () => {
server.listen(++serverPort);
});
server.on('upgrade', (request, socket, head) => {
const pathname = url.parse(request.url).pathname;
if (pathname === `/agent`) {
if (!activityID) {
activityID = uuidv4();
token = uuidv4();
}
agentSocket.handleUpgrade(request, socket, head, function done(ws) {
agentSocket.emit('connection', ws, request);
});
} else if (pathname === `/master/${activityID}`) {
masterSocket.handleUpgrade(request, socket, head, function done(ws) {
masterSocket.emit('connection', ws, request);
});
} else {
console.log(pathname);
socket.destroy();
}
});

agentSocket = new WebSocket.Server({ noServer: true });
agentSocket.on('connection', function connection(ws, req) {
ws.on('message', function incoming(message) {
boardCastMsg(masterSocket, {
message
});
});
boardCastMsg(agentSocket, {
serverIPInfo,
activityID,
token,
port: server.address().port
});
});

masterSocket = new WebSocket.Server({ noServer: true });
masterSocket.on('connection', function connection(ws, req) {
ws.on('message', function incoming(message) {
boardCastMsg(agentSocket, {
message
});
});
ws.send(JSON.stringify({
size: agentSocket.clients.size,
}));
});
const timer = setInterval(function () {
token = uuidv4();
boardCastMsg(agentSocket, {
serverIPInfo,
activityID,
token,
port: server.address().port
});
// clearInterval(timer);
// };
}, 10000);

}

function boardCastMsg(socket, msg) {
const Base64 = require('js-base64').Base64;
socket.clients.forEach(client => {
client.send(Base64.encode(JSON.stringify(msg)));
})
}

function getServerIPInfo() {
const int2ip = ipInt => {
return ((ipInt >>> 24) + '.' + (ipInt >> 16 & 255) + '.' + (ipInt >> 8 & 255) + '.' + (ipInt & 255));
};

const ip2int = ip => {
return ip.split('.').reduce(function (ipInt, octet) {
return (ipInt << 8) + parseInt(octet, 10)
}, 0) >>> 0;
};
const ifaces = require('os').networkInterfaces();
const serverIPInfo = flatten(Object.keys(ifaces).map((ifname) => ifaces[ifname]
.filter(iface => ('IPv4' === iface.family && iface.internal === false))))
.map(iface => ({
ip: iface.address,
gateway: int2ip(ip2int(iface.address) & ip2int(iface.netmask)),
}));
return serverIPInfo;
}

app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
33 changes: 32 additions & 1 deletion src/component/start/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,44 @@
import React, { Component } from 'react';
import QRCode from 'qrcode.react';
import {
Link
} from 'react-router-dom'
import './start.css';

class Start extends Component {
constructor(props) {
super(props);
this.state = {
qrData: 'https://magpie.wangbaiyuan.cn',
}
}
componentDidMount() {
const ws = new WebSocket('ws://localhost:10086/agent');
ws.onopen = function open() {
ws.send('something');
};

ws.onmessage = function incoming(data) {
this.setState({
qrData: data.data
});
console.log(data);
}.bind(this);
}

render() {
return (
<div><Link to="/activity-setting" className="creat_new_activity">创建一个抽奖活动</Link></div>
<div style={{textAlign: 'center'}}>
<div>在同一局域网内打开手机APP或小程序</div>
<div>扫描二维码进行远程控制</div>
<div style={{background: '#fff', padding: 10, width: 200, height: 200, margin: 30}}>
<QRCode
value={JSON.stringify(this.state.qrData)}
size={200}
/>
</div>
<Link to="/activity-setting" className="creat_new_activity">创建一个抽奖活动</Link>
</div>
);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/index.css
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
body {
margin: 0;
padding: 0;
font-family: sans-serif;
font-family: PingFang SC,Lantinghei SC,Helvetica Neue,Helvetica,Arial,Microsoft YaHei,STHeitiSC-Light,simsun,WenQuanYi Zen Hei,WenQuanYi Micro Hei,"sans-serif";
height: 100vh;
color: aliceblue;
}
Expand Down
1 change: 1 addition & 0 deletions src/server/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

29 changes: 27 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1948,7 +1948,7 @@ async-exit-hook@^2.0.1:
resolved "https://registry.yarnpkg.com/async-exit-hook/-/async-exit-hook-2.0.1.tgz#8bd8b024b0ec9b1c01cccb9af9db29bd717dfaf3"
integrity sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==

async-limiter@~1.0.0:
async-limiter@^1.0.0, async-limiter@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/async-limiter/-/async-limiter-1.0.0.tgz#78faed8c3d074ab81f22b4e985d79e8738f720f8"
integrity sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==
Expand Down Expand Up @@ -6588,6 +6588,11 @@ jquery@^3.4.1:
resolved "https://registry.yarnpkg.com/jquery/-/jquery-3.4.1.tgz#714f1f8d9dde4bdfa55764ba37ef214630d80ef2"
integrity sha512-36+AdBzCL+y6qjw5Tx7HgzeGCzC81MDDgaUP8ld2zhx58HdqXGoBd+tHdrBMiyjGQs0Hxs/MLZTu/eHNJJuWPw==

js-base64@^2.5.1:
version "2.5.1"
resolved "https://registry.yarnpkg.com/js-base64/-/js-base64-2.5.1.tgz#1efa39ef2c5f7980bb1784ade4a8af2de3291121"
integrity sha512-M7kLczedRMYX4L8Mdh4MzyAMM9O5osx+4FcOQuTvr3A9F2D9S5JXheN0ewNbrvK2UatkTRhL5ejGmGSjNMiZuw==

js-levenshtein@^1.1.3:
version "1.1.6"
resolved "https://registry.yarnpkg.com/js-levenshtein/-/js-levenshtein-1.1.6.tgz#c6cee58eb3550372df8deb85fad5ce66ce01d59d"
Expand Down Expand Up @@ -9067,7 +9072,7 @@ prompts@^2.0.1:
kleur "^3.0.2"
sisteransi "^1.0.0"

prop-types@^15.5.10, prop-types@^15.5.7, prop-types@^15.6.2, prop-types@^15.7.2:
prop-types@^15.5.10, prop-types@^15.5.7, prop-types@^15.6.0, prop-types@^15.6.2, prop-types@^15.7.2:
version "15.7.2"
resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5"
integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==
Expand Down Expand Up @@ -9168,6 +9173,19 @@ q@^1.1.2:
resolved "https://registry.yarnpkg.com/q/-/q-1.5.1.tgz#7e32f75b41381291d04611f1bf14109ac00651d7"
integrity sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=

[email protected]:
version "0.0.0"
resolved "https://registry.yarnpkg.com/qr.js/-/qr.js-0.0.0.tgz#cace86386f59a0db8050fa90d9b6b0e88a1e364f"
integrity sha1-ys6GOG9ZoNuAUPqQ2baw6IoeNk8=

qrcode.react@^0.9.3:
version "0.9.3"
resolved "https://registry.yarnpkg.com/qrcode.react/-/qrcode.react-0.9.3.tgz#91de1287912bdc5ccfb3b091737b828d6ced60c5"
integrity sha512-gGd30Ez7cmrKxyN2M3nueaNLk/f9J7NDRgaD5fVgxGpPLsYGWMn9UQ+XnDpv95cfszTQTdaf4QGLNMf3xU0hmw==
dependencies:
prop-types "^15.6.0"
qr.js "0.0.0"

[email protected]:
version "6.7.0"
resolved "https://registry.yarnpkg.com/qs/-/qs-6.7.0.tgz#41dc1a015e3d581f1621776be31afb2876a9b1bc"
Expand Down Expand Up @@ -12013,6 +12031,13 @@ ws@^6.1.2:
dependencies:
async-limiter "~1.0.0"

ws@^7.0.0:
version "7.0.0"
resolved "https://registry.yarnpkg.com/ws/-/ws-7.0.0.tgz#79351cbc3f784b3c20d0821baf4b4ff809ffbf51"
integrity sha512-cknCal4k0EAOrh1SHHPPWWh4qm93g1IuGGGwBjWkXmCG7LsDtL8w9w+YVfaF+KSVwiHQKDIMsSLBVftKf9d1pg==
dependencies:
async-limiter "^1.0.0"

x-is-string@^0.1.0:
version "0.1.0"
resolved "https://registry.yarnpkg.com/x-is-string/-/x-is-string-0.1.0.tgz#474b50865af3a49a9c4657f05acd145458f77d82"
Expand Down

0 comments on commit bdc9a47

Please sign in to comment.