Skip to content

Commit

Permalink
Merge pull request #179 from Itokoyamato/next
Browse files Browse the repository at this point in the history
Dylan Thuillier authored Aug 19, 2020
2 parents eeef1fd + 7070763 commit 3c53208
Showing 5 changed files with 83 additions and 17 deletions.
9 changes: 9 additions & 0 deletions fivem_script/tokovoip_script/nui/index.html
Original file line number Diff line number Diff line change
@@ -58,6 +58,14 @@
padding-inline-start: 27px;
margin-block-start: 6px;
}

#latency {
top: 80px;
position: absolute;
color: white;
font-size: 10px;
font-weight: 100;
}
</style>
<script src="nui://game/ui/jquery.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
@@ -117,6 +125,7 @@
</div>
<div id="tokovoipInfo" class="tokovoipInfo">
</div>
<div id="latency" style="display: none;"></div>
</body>

</html>
35 changes: 33 additions & 2 deletions fivem_script/tokovoip_script/nui/script.js
Original file line number Diff line number Diff line change
@@ -24,7 +24,10 @@ let websocket;
let endpoint;
let connected = false;
let lastOk = 0;
let scriptName = GetParentResourceName()
let scriptName = GetParentResourceName();
let clientIp;
let latency = {};
let displayLatency = false;

let voip = {};

@@ -57,9 +60,29 @@ function disconnect (src) {
}
}

function init (address, serverId) {
async function updateClientIP(endpoint) {
if (!endpoint) {
console.error('updateClientIP: endpoint missing');
return;
}
if (voipStatus !== OK) {
const res = await fetch(`http://${endpoint}/getmyip`)
.catch(e => console.error('TokoVOIP: failed to update cient IP', e));

if (res) {
const ip = await res.text();
clientIp = ip;
console.log('TokoVOIP: updated client IP');
if (websocket && websocket.readyState === websocket.OPEN) websocket.send(`42${JSON.stringify(['updateClientIP', { ip: clientIp }])}`);
}
}
setTimeout(_ => updateClientIP(endpoint), 10000);
}

async function init(address, serverId) {
if (!address) return;
endpoint = address;
await updateClientIP(endpoint);
console.log('TokoVOIP: attempt new connection');
websocket = new WebSocket(`ws://${endpoint}/socket.io/?EIO=3&transport=websocket&from=fivem&serverId=${serverId}`);

@@ -91,6 +114,11 @@ function init (address, serverId) {
if (msg.event === 'ping') websocket.send(`42${JSON.stringify(['pong', ''])}`);

if (msg.event === 'disconnectMessage') { console.error('disconnectMessage: ' + msg.data); disconnect('Ts3') }

if (msg.event === 'onLatency') {
latency = msg.data;
document.querySelector('#latency').innerHTML = `Latency Total: ${latency.total}ms<br>Latency FiveM: ${latency.fivem}ms<br>Latency TS3: ${latency.ts3}ms`;
}
};

websocket.onerror = (evt) => {
@@ -171,6 +199,9 @@ function receivedClientCall (event) {
} else if (eventName == 'disconnect') {
sendData('disconnect');
voipStatus = NOT_CONNECTED;
} else if (eventName == 'toggleLatency') {
displayLatency = !displayLatency;
document.querySelector('#latency').style.display = (displayLatency) ? 'block' : 'none';
}
}

6 changes: 5 additions & 1 deletion fivem_script/tokovoip_script/src/c_main.lua
Original file line number Diff line number Diff line change
@@ -17,7 +17,7 @@
local targetPed;
local useLocalPed = true;
local isRunning = false;
local scriptVersion = "1.5.4";
local scriptVersion = "1.5.5";
local animStates = {}
local displayingPluginScreen = false;
local HeadBone = 0x796e;
@@ -382,6 +382,10 @@ AddEventHandler('TokoVoip:setRadioVolume', setRadioVolume);
-- Specific utils
--------------------------------------------------------------------------------

RegisterCommand("tokovoiplatency", function()
SendNUIMessage({ type = "toggleLatency" });
end);

-- Toggle the blocking screen with usage explanation
-- Not used
function displayPluginScreen(toggle)
48 changes: 35 additions & 13 deletions ws_server/index.js
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@ const lodash = require('lodash');
const chalk = require('chalk');
const config = require('./config.js');
const publicIp = require('public-ip');
const IPv4Regex = new RegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$');

let hostIP;

@@ -45,7 +46,6 @@ Missing one of TSServer, WSServerIP or WSServerPort}`
http.listen(config.WSServerPort, async _ => {
console.log('Checking configuration ...');
let configError = false;
const IPv4Regex = new RegExp('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$');
if (!IPv4Regex.test(config.TSServer)) {
configError = true;
console.error(chalk`{red Config error:
@@ -98,6 +98,11 @@ app.get('/playerbyip', (req, res) => {
return res.status(204).send();
});

app.get('getmyip', (req, res) => {
const ip = (lodash.get(req, `headers.['x-forwarded-for']`) || lodash.get(req, `headers.['x-real-ip']`) || lodash.get(req, 'connection.remoteAddress')).replace('::ffff:', '');
res.send(ip);
});

http.on('upgrade', (req, socket) => {
if (!req._query || !req._query.from) return socket.destroy();
if (req._query.from === 'ts3' && !req._query.uuid) return socket.destroy();
@@ -147,8 +152,13 @@ io.on('connection', async socket => {
// FiveM Handshake
} else if (socket.from === 'fivem') {
socketHeartbeat(socket);
socket.on('updateClientIP', data => {
if (!data || !data.ip || !IPv4Regex.test(data.ip) || !clients[socket.uuid]) return;
if (lodash.get(clients, `[${socket.uuid}].fivem.socket`)) clients[socket.uuid].fivem.socket.clientIp = data.ip;
if (lodash.get(clients, `[${socket.uuid}].ts3.socket`)) clients[socket.uuid].ts3.socket.clientIp = data.ip;
});
await registerHandshake(socket);
socket.on('data', (data) => onIncomingData(socket, data));
socket.on('data', data => onIncomingData(socket, data));
}
});

@@ -165,14 +175,19 @@ async function registerHandshake(socket) {
return;
}
client = Object.values(clients).find(item => !item.fivem.socket && item.ip === socket.clientIp);
await axios.post('https://master.tokovoip.itokoyamato.net/register', {
ip: socket.clientIp,
server: {
tsServer: config.TSServer,
ip: config.WSServerIP,
port: config.WSServerPort,
},
});
try {
await axios.post('https://master.tokovoip.itokoyamato.net/register', {
ip: socket.clientIp,
server: {
tsServer: config.TSServer,
ip: config.WSServerIP,
port: config.WSServerPort,
},
});
} catch (e) {
console.error(e);
throw e;
}
}
socket.uuid = client.uuid;
client.fivem.socket = socket;
@@ -218,13 +233,20 @@ async function onSocketDisconnect(socket) {
function socketHeartbeat(socket) {
if (!socket) return;
const start = new Date();
socket.emit('ping');
socket.once('pong', _ => {
setTimeout(_ => socketHeartbeat(socket), 1000);
socket.latency = (new Date).getTime() - start.getTime();
socket.latency = (new Date()).getTime() - start.getTime();
if (!socket.uuid || !clients[socket.uuid]) return;
clients[socket.uuid].latency = lodash.get(clients[socket.uuid], 'fivem.latency', 0) + lodash.get(clients[socket.uuid], 'ts3.latency', 0);
clients[socket.uuid].latency = lodash.get(clients[socket.uuid], 'fivem.socket.latency', 0) + lodash.get(clients[socket.uuid], 'ts3.socket.latency', 0);
if (socket.from === 'fivem') {
socket.emit('onLatency', {
total: clients[socket.uuid].latency,
fivem: lodash.get(clients[socket.uuid], 'fivem.socket.latency', 0),
ts3: lodash.get(clients[socket.uuid], 'ts3.socket.latency', 0),
});
}
});
socket.emit('ping');
}

async function masterHeartbeat() {
2 changes: 1 addition & 1 deletion ws_server/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ws_server",
"version": "1.5.4",
"version": "1.5.5",
"description": "",
"main": "index.js",
"scripts": {

0 comments on commit 3c53208

Please sign in to comment.