MWSE/Source/Services/DataTransfer.js

102 lines
2.4 KiB
JavaScript

"use strict";
const { Client } = require("../Client.js");
const { register } = require("../WebSocket");
const { Room } = require("./Room");
register('pack/to', (client, msg) => {
const { to, pack, handshake } = msg;
if (!client.packReadable()) {
return handshake ? { type: 'fail' } : undefined;
}
if (!Client.clients.has(to)) {
return handshake ? { type: 'fail' } : undefined;
}
const otherPeer = Client.clients.get(to);
if (otherPeer.requiredPair) {
if (!otherPeer.pairs.has(to)) {
return handshake ? { type: 'fail' } : undefined;
}
} else {
if (!otherPeer.pairs.has(to)) {
otherPeer.pairs.add(client.id);
client.pairs.add(otherPeer.id);
}
}
if (!otherPeer.packWriteable()) {
return handshake ? { type: 'fail' } : undefined;
}
otherPeer.send([{ from: client.id, pack }, 'pack']);
return handshake ? { type: 'success' } : undefined;
});
register('request/to', (client, msg) => {
const { to, pack } = msg;
if (!Client.clients.has(to)) {
return;
}
const otherPeer = Client.clients.get(to);
if (otherPeer.requiredPair) {
if (!otherPeer.pairs.has(to)) {
return;
}
} else {
otherPeer.pairs.add(client.id);
client.pairs.add(otherPeer.id);
}
otherPeer.send([{ from: client.id, pack }, 'request']);
});
register('response/to', (client, msg) => {
const { to, pack, id } = msg;
if (!Client.clients.has(to)) {
return;
}
const otherPeer = Client.clients.get(to);
if (otherPeer.requiredPair && !otherPeer.pairs.has(to)) {
return;
}
otherPeer.send([{ from: client.id, pack }, id]);
});
register('pack/room', (client, msg) => {
const { to, pack, handshake, wom } = msg;
if (!client.packReadable()) {
return handshake ? { type: 'fail' } : undefined;
}
if (!Room.rooms.has(to)) {
return handshake ? { type: 'fail' } : undefined;
}
if (!client.rooms.has(to)) {
return handshake ? { type: 'fail' } : undefined;
}
const room = Room.rooms.get(to);
room.send(
[{ from: to, pack, sender: client.id }, 'pack/room'],
wom ? client.id : undefined,
c => c.packWriteable()
);
return handshake ? { type: 'success' } : undefined;
});