1 | import { deviceInfo, } from '@casual-simulation/causal-trees';
|
2 | import { fromEventPattern } from 'rxjs';
|
3 | import { map, shareReplay, flatMap, first, tap } from 'rxjs/operators';
|
4 | export class SocketIOConnectionServer {
|
5 | constructor(socketServer) {
|
6 | const onConnection = fromEventPattern(h => socketServer.on('connection', h));
|
7 | const connections = onConnection.pipe(flatMap(s => this._login(s), (socket, info) => ({ info, socket })), map(({ info, socket }) => new SocketIOConnection(socket, info)), shareReplay());
|
8 | this._connection = connections;
|
9 | }
|
10 | get connection() {
|
11 | return this._connection;
|
12 | }
|
13 | _login(socket) {
|
14 | console.log(`[SocketIOConnectionServer] Waiting for login...`);
|
15 | const onLogin = fromEventPattern(h => socket.on('login', h), h => socket.off('login', h));
|
16 | return onLogin.pipe(tap(() => { }), map(token => deviceInfo(token.username, token.username, token.id)), tap(info => socket.emit('login_result', info)), first());
|
17 | }
|
18 | }
|
19 | export class SocketIOConnection {
|
20 | constructor(socket, device) {
|
21 | this._socket = socket;
|
22 | this._device = device;
|
23 | }
|
24 | get device() {
|
25 | return this._device;
|
26 | }
|
27 | get disconnect() {
|
28 | return this._socketEvent('disconnect');
|
29 | }
|
30 | event(name) {
|
31 | return this._socketEvent(name);
|
32 | }
|
33 | send(name, data) {
|
34 | this._socket.emit(name, data);
|
35 | }
|
36 | _socketEvent(name) {
|
37 | return fromEventPattern(h => this._socket.on(name, h), h => this._socket.off(name, h));
|
38 | }
|
39 | }
|
40 |
|
\ | No newline at end of file |