-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsync.js
2917 lines (2317 loc) · 79.1 KB
/
sync.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// University of Illinois/NCSA
// Open Source License
// http://otm.illinois.edu/disclose-protect/illinois-open-source-license
// Copyright (c) 2020 Grainger Engineering Library Information Center. All rights reserved.
// Developed by: IDEA Lab
// Grainger Engineering Library Information Center - University of Illinois Urbana-Champaign
// https://library.illinois.edu/enx
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal with
// the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to
// do so, subject to the following conditions:
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the documentation
// and/or other materials provided with the distribution.
// * Neither the names of IDEA Lab, Grainger Engineering Library Information Center,
// nor the names of its contributors may be used to endorse or promote products
// derived from this Software without specific prior written permission.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
// SOFTWARE.
/* jshint esversion: 6 */
// configuration
const config = require("./config");
const fs = require("fs");
const path = require("path");
const util = require("util");
const { syslog } = require("winston/lib/winston/config");
const Session = require("./session");
const SocketRepairCenter = require("./socket-repair-center");
const SocketActivityMonitor = require("./socket-activity-monitor");
const chat = require("./chat");
const { debug } = require("console");
// event data globals
// NOTE(rob): deprecated.
// const POS_FIELDS = 14;
// const POS_BYTES_PER_FIELD = 4;
// const POS_COUNT = 10000;
// const INT_FIELDS = 7;
// const INT_BYTES_PER_FIELD = 4;
// const INT_COUNT = 128;
// interaction event values
// TODO(rob): finish deprecate.
// const INTERACTION_LOOK = 0;
// const INTERACTION_LOOK_END = 1;
const INTERACTION_RENDER = 2;
const INTERACTION_RENDER_END = 3;
// const INTERACTION_GRAB = 4;
// const INTERACTION_GRAB_END = 5;
const INTERACTION_SCENE_CHANGE = 6;
// const INTERACTION_UNSET = 7; // NOTE(rob): this value is currently unused. 2020-12-1
const INTERACTION_LOCK = 8;
const INTERACTION_LOCK_END = 9;
const SYNC_OBJECTS = 3;
const STATE_VERSION = 2;
const SERVER_NAME = "Komodo Dev (IL)";
const SYNC_NAMESPACE = "/sync";
//TODO refactor this.sessions into instances of the Session object.
// Courtesy of Casey Foster on Stack Overflow
// https://stackoverflow.com/a/14368628
function compareKeys(a, b) {
var aKeys = Object.keys(a).sort();
var bKeys = Object.keys(b).sort();
return JSON.stringify(aKeys) === JSON.stringify(bKeys);
}
const SocketIOEvents = {
connection: "connection",
disconnect: "disconnect",
disconnecting: "disconnecting",
error: "error"
};
const KomodoReceiveEvents = {
requestToJoinSession: "join",
leave: "leave",
sessionInfo: "sessionInfo",
requestOwnStateCatchup: "state",
draw: "draw",
message: "message",
update: "update",
interact: "interact",
start_recording: "start_recording",
end_recording: "end_recording",
playback: "playback",
};
const KomodoSendEvents = {
connectionError: "connectionError",
interactionUpdate: "interactionUpdate",
clientJoined: "joined",
failedToJoin: "failedToJoin",
successfullyJoined: "successfullyJoined",
left: "left",
failedToLeave: "failedToLeave",
successfullyLeft: "successfullyLeft",
disconnected: "disconnected",
serverName: "serverName",
sessionInfo: "sessionInfo",
state: "state",
draw: "draw",
message: "message",
relayUpdate: "relayUpdate",
notifyBump: "bump",
rejectUser: "rejectUser",
};
const KomodoMessages = {
interaction: {
type: "interaction",
minLength: 5, //TODO: what should this number be?
indices: {
sourceId: 3,
targetId: 4,
interactionType: 5,
},
},
sync: {
type: "sync",
minLength: 4, //TODO: what should this number be?
indices: {
entityId: 3,
entityType: 4,
},
}
};
// see https://socket.io/docs/v2/server-api/index.html
const DisconnectKnownReasons = {
// the disconnection was initiated by the server
"server namespace disconnect": {
doReconnect: false,
},
// The socket was manually disconnected using socket.disconnect()
"client namespace disconnect": {
doReconnect: false,
},
// The connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)
"transport close": {
doReconnect: true,
},
// The connection has encountered an error (example: the server was killed during a HTTP long-polling cycle)
"transport error": {
doReconnect: true,
},
// The server did not send a PING within the pingInterval + pingTimeout range.
"ping timeout": {
doReconnect: true,
},
};
const doReconnectOnUnknownReason = true;
module.exports = {
// NOTE(rob): deprecated. sessions must use message_buffer.
// // write buffers are multiples of corresponding chunks
// positionWriteBufferSize: function () {
// return POS_COUNT * positionChunkSize();
// },
// // write buffers are multiples of corresponding chunks
// interactionWriteBufferSize: function () {
// return INT_COUNT * interactionChunkSize();
// },
logInfoSessionClientSocketAction: function (
session_id,
client_id,
socket_id,
action
) {
if (session_id == null) {
session_id = "---";
}
session_id = `s${session_id}`;
if (client_id == null) {
client_id = "---";
}
client_id = `c${client_id}`;
if (socket_id == null) {
socket_id = "---.......................";
}
if (action == null) {
action = "---";
}
if (!this.logger) {
return;
}
if (this.logger)
this.logger.info(
`${socket_id}\t${session_id}\t${client_id}\t${action}`
);
},
logErrorSessionClientSocketAction: function (
session_id,
client_id,
socket_id,
action
) {
if (session_id == null) {
session_id = "---";
}
session_id = `s${session_id}`;
if (client_id == null) {
client_id = "---";
}
client_id = `c${client_id}`;
if (socket_id == null) {
socket_id = "---.......................";
}
if (action == null) {
action = "---";
}
if (!this.logger) {
return;
}
if (this.logger)
this.logger.error(
`${socket_id}\t${session_id}\t${client_id}\t${action}`
);
},
logWarningSessionClientSocketAction: function (
session_id,
client_id,
socket_id,
action
) {
if (session_id == null) {
session_id = "---";
}
session_id = `s${session_id}`;
if (client_id == null) {
client_id = "---";
}
client_id = `c${client_id}`;
if (socket_id == null) {
socket_id = "---.......................";
}
if (action == null) {
action = "---";
}
if (!this.logger) {
return;
}
if (this.logger)
this.logger.warn(
`${socket_id}\t${session_id}\t${client_id}\t${action}`
);
},
// generate formatted path for session capture files
getCapturePath: function (session_id, start, type) {
return path.join(
__dirname,
config.capture.path,
session_id.toString(),
start.toString(),
type
);
},
start_recording: function (pool, session_id) {
// TODO(rob): require client id and token
console.log(
`start_recording called with pool: ${pool}, session: ${session_id}`
);
let session = this.sessions.get(session_id);
if (!session) {
this.logErrorSessionClientSocketAction(
session_id,
null,
null,
`Tried to start recording, but session was null`
);
return;
}
if (session && !session.isRecording) {
session.isRecording = true;
session.recordingStart = Date.now();
let path = this.getCapturePath(session_id, session.recordingStart, "");
fs.mkdir(path, { recursive: true }, (err) => {
if (err)
if (this.logger)
this.logger.warn(`Error creating capture path: ${err}`);
});
let capture_id = session_id + "_" + session.recordingStart;
session.capture_id = capture_id;
if (pool) {
pool.query(
"INSERT INTO captures(capture_id, session_id, start) VALUES(?, ?, ?)",
[capture_id, session_id, session.recordingStart],
(err, res) => {
if (err != undefined) {
if (this.logger)
this.logger.error(
`Error writing recording start event to database: ${err} ${res}`
);
}
}
);
}
if (this.logger) this.logger.info(`Capture started: ${session_id}`);
} else if (session && session.isRecording) {
if (this.logger)
this.logger.warn(
`Requested session capture, but session is already recording: ${session_id}`
);
}
},
// define end_recording event handler, use on socket event as well as on server cleanup for empty sessions
end_recording: function (pool, session_id) {
if (session_id) {
let session = this.sessions.get(session_id);
if (session && session.isRecording) {
session.isRecording = false;
if (this.logger) this.logger.info(`Capture ended: ${session_id}`);
// write out the buffers if not empty, but only up to where the cursor is
// NOTE(rob): deprecated, use messages.
// let pos_writer = session.writers.pos;
// if (pos_writer.cursor > 0) {
// let path = this.getCapturePath(session_id, session.recordingStart, 'pos');
// let wstream = fs.createWriteStream(path, { flags: 'a' });
// wstream.write(pos_writer.buffer.slice(0, pos_writer.cursor));
// wstream.close();
// pos_writer.cursor = 0;
// }
// let int_writer = session.writers.int;
// if (int_writer.cursor > 0) {
// let path = this.getCapturePath(session_id, session.recordingStart, 'int');
// let wstream = fs.createWriteStream(path, { flags: 'a' });
// wstream.write(int_writer.buffer.slice(0, int_writer.cursor));
// wstream.close();
// int_writer.cursor = 0;
// }
// write out message buffer.
let path = this.getCapturePath(
session_id,
session.recordingStart,
"data"
); // [capturesDirectoryHere]/[session_id_here]/[session.recordingStartHere]/data
fs.writeFile(path, JSON.stringify(session.message_buffer), (e) => {
if (e) {
console.log(`Error writing message buffer: ${e}`);
}
});
//TODO(Brandon): add success event here. Possibly notify Unity client.
// reset the buffer.
session.message_buffer = [];
// write the capture end event to database
if (pool) {
let capture_id = session.capture_id;
pool.query(
"UPDATE captures SET end = ? WHERE capture_id = ?",
[Date.now(), capture_id],
(err, res) => {
if (err != undefined) {
if (this.logger)
this.logger.error(
`Error writing recording end event to database: ${err} ${res}`
);
}
}
);
session.capture_id = null;
}
} else if (session && !session.isRecording) {
if (this.logger)
this.logger.warn(
`Requested to end session capture, but capture is already ended: ${session_id}`
);
session.capture_id = null;
} else {
if (this.logger)
this.logger.warn(`Error ending capture for session: ${session_id}`);
}
}
},
record_message_data: function (data) {
if (data) {
let session = this.sessions.get(data.session_id);
if (!session) {
this.logErrorSessionClientSocketAction(
data.session_id,
null,
null,
`Tried to record message data, but session was null`
);
return;
}
// calculate a canonical session sequence number for this message from session start and message timestamp.
// NOTE(rob): investigate how we might timestamp incoming packets WHEN THEY ARE RECEIVED BY THE NETWORKING LAYER, ie. not
// when they are handled by the socket.io library. From a business logic perspective, the canonical order of events is based
// on when they arrive at the relay server, NOT when the client emits them. 8/3/2021
data.seq = data.ts - session.recordingStart;
data.capture_id = session.capture_id; // copy capture id session property and attach it to the message data.
let session_id = data.session_id;
let client_id = data.client_id;
if (typeof data.message != `object`) {
try {
data.message = JSON.parse(data.message);
} catch (e) {
// if (this.logger) this.logger.warn(`Failed to parse message payload: ${message} ${e}`);
console.log(`Failed to parse message payload: ${data.message}; ${e}`);
return;
}
}
if (!session_id || !client_id) {
this.logErrorSessionClientSocketAction(
session_id,
null,
null,
`Tried to record message data. One of these properties is missing. session_id: ${session_id}, client_id: ${client_id}, message: ${data}`
);
return;
}
if (session.message_buffer) {
// TODO(rob): find optimal buffer size
// if (session.message_buffer.length < MESSAGE_BUFFER_MAX_SIZE) {
// this.session.message_buffer.push(data)
// } else
session.message_buffer.push(data);
// DEBUG(rob):
// let mb_str = JSON.stringify(session.message_buffer);
// let bytes = new util.TextEncoder().encode(mb_str).length;
// console.log(`Session ${data.session_id} message buffer size: ${bytes} bytes`);
}
} else {
this.logErrorSessionClientSocketAction(
null,
null,
null,
`message was null`
);
}
},
handlePlayback: function (io, data) {
// TODO(rob): need to use playback object to track seq and group by playback_id,
// so users can request to pause playback, maybe rewind?
if (this.logger) this.logger.info(`Playback request: ${data.playback_id}`);
let client_id = data.client_id;
let session_id = data.session_id;
let playback_id = data.playback_id;
let capture_id = null;
let start = null;
if (client_id && session_id && playback_id) {
capture_id = playback_id.split("_")[0];
start = playback_id.split("_")[1];
// TODO(rob): check that this client has permission to playback this session
} else {
console.log("Invalid playback request:", data);
return;
}
// Everything looks good, getting ref to session.
let session = this.sessions.get(session_id);
// playback sequence counter
let current_seq = 0;
// let audioStarted = false;
// NOTE(rob): deprecated; playback data must use message system.
// check that all params are valid
// if (capture_id && start) {
// // TODO(rob): Mar 3 2021 -- audio playback on hold to focus on data.
// // build audio file manifest
// // if (this.logger) this.logger.info(`Buiding audio file manifest for capture replay: ${playback_id}`)
// // let audioManifest = [];
// // let baseAudioPath = this.getCapturePath(capture_id, start, 'audio');
// // if(fs.existsSync(baseAudioPath)) { // TODO(rob): change this to async operation
// // let items = fs.readdirSync(baseAudioPath); // TODO(rob): change this to async operation
// // items.forEach(clientDir => {
// // let clientPath = path.join(baseAudioPath, clientDir)
// // let files = fs.readdirSync(clientPath) // TODO(rob): change this to async operation
// // files.forEach(file => {
// // let client_id = clientDir;
// // let seq = file.split('.')[0];
// // let audioFilePath = path.join(clientPath, file);
// // let item = {
// // seq: seq,
// // client_id: client_id,
// // path: audioFilePath,
// // data: null
// // }
// // audioManifest.push(item);
// // });
// // });
// // }
// // // emit audio manifest to connected clients
// // io.of('chat').to(session_id.toString()).emit(KomodoSendEvents.playbackAudioManifest', audioManifest);
// // // stream all audio files for caching and playback by client
// // audioManifest.forEach((file) => {
// // fs.readFile(file.path, (err, data) => {
// // file.data = data;
// // if(err) if (this.logger) this.logger.error(`Error reading audio file: ${file.path}`);
// // // console.log('emitting audio packet:', file);
// // io.of('chat').to(session_id.toString()).emit(KomodoSendEvents.playbackAudioData', file);
// // });
// // });
// // position streaming
// let capturePath = this.getCapturePath(capture_id, start, 'pos');
// let stream = fs.createReadStream(capturePath, { highWaterMark: positionChunkSize() });
// // set actual playback start time
// let playbackStart = Date.now();
// // position data emit loop
// stream.on(KomodoReceiveEvents.data, function(chunk) {
// stream.pause();
// // start data buffer loop
// let buff = Buffer.from(chunk);
// let farr = new Float32Array(chunk.byteLength / 4);
// for (var i = 0; i < farr.length; i++) {
// farr[i] = buff.readFloatLE(i * 4);
// }
// var arr = Array.from(farr);
// let timer = setInterval( () => {
// current_seq = Date.now() - playbackStart;
// // console.log(`=== POS === current seq ${current_seq}; arr seq ${arr[POS_FIELDS-1]}`);
// if (arr[POS_FIELDS-1] <= current_seq) {
// // alias client and entity id with prefix if entity type is not an asset
// if (arr[4] != 3) {
// arr[2] = 90000 + arr[2];
// arr[3] = 90000 + arr[3];
// }
// // if (!audioStarted) {
// // // HACK(rob): trigger clients to begin playing buffered audio
// // audioStarted = true;
// // io.of('chat').to(session_id.toString()).emit(KomodoSendEvents.startPlaybackAudio');
// // }
// io.to(session_id.toString()).emit(KomodoSendEvents.relayUpdate', arr);
// stream.resume();
// clearInterval(timer);
// }
// }, 1);
// });
// stream.on(KomodoReceiveEvents.error, function(err) {
// if (this.logger) this.logger.error(`Error creating position playback stream for ${playback_id} ${start}: ${err}`);
// io.to(session_id.toString()).emit(KomodoSendEvents.playbackEnd');
// });
// stream.on(KomodoReceiveEvents.end, function() {
// if (this.logger) this.logger.info(`End of pos data for playback session: ${session_id}`);
// io.to(session_id.toString()).emit(KomodoSendEvents.playbackEnd');
// });
// // interaction streaming
// let ipath = this.getCapturePath(capture_id, start, 'int');
// let istream = fs.createReadStream(ipath, { highWaterMark: interactionChunkSize() });
// istream.on(KomodoReceiveEvents.data, function(chunk) {
// istream.pause();
// let buff = Buffer.from(chunk);
// let farr = new Int32Array(chunk.byteLength / 4);
// for (var i = 0; i < farr.length; i++) {
// farr[i] = buff.readInt32LE(i * 4);
// }
// var arr = Array.from(farr);
// let timer = setInterval( () => {
// // console.log(`=== INT === current seq ${current_seq}; arr seq ${arr[INT_FIELDS-1]}`);
// if (arr[INT_FIELDS-1] <= current_seq) {
// io.to(session_id.toString()).emit(KomodoSendEvents.interactionUpdate', arr);
// istream.resume();
// clearInterval(timer);
// }
// }, 1);
// });
// istream.on(KomodoReceiveEvents.error, function(err) {
// if (this.logger) this.logger.error(`Error creating interaction playback stream for session ${session_id}: ${err}`);
// io.to(session_id.toString()).emit(KomodoSendEvents.interactionpPlaybackEnd');
// });
// istream.on(KomodoReceiveEvents.end, function() {
// if (this.logger) this.logger.info(`End of int data for playback session: ${session_id}`);
// io.to(session_id.toString()).emit(KomodoSendEvents.interactionPlaybackEnd');
// });
// }
},
isValidRelayPacket: function (data) {
let session_id = data[1];
let client_id = data[2];
if (session_id && client_id) {
let session = this.sessions.get(session_id);
if (!session) {
return;
}
// check if the incoming packet is from a client who is valid for this session
return session.hasClient(client_id);
}
},
// NOTE(rob): DEPRECATED. 8/5/21.
// writeRecordedRelayData: function (data) {
// if (!data) {
// throw new ReferenceError ("data was null");
// }
// let session_id = data[1];
// let session = this.sessions.get(session_id);
// if (!session) {
// throw new ReferenceError ("session was null");
// }
// if (!session.isRecording) {
// return;
// }
// // calculate and write session sequence number using client timestamp
// data[POS_FIELDS-1] = data[POS_FIELDS-1] - session.recordingStart;
// // get reference to session writer (buffer and cursor)
// let writer = session.writers.pos;
// if (positionChunkSize() + writer.cursor > writer.buffer.byteLength) {
// // if buffer is full, dump to disk and reset the cursor
// let path = this.getCapturePath(session_id, session.recordingStart, 'pos');
// let wstream = fs.createWriteStream(path, { flags: 'a' });
// wstream.write(writer.buffer.slice(0, writer.cursor));
// wstream.close();
// writer.cursor = 0;
// }
// for (let i = 0; i < data.length; i++) {
// writer.buffer.writeFloatLE(data[i], (i*POS_BYTES_PER_FIELD) + writer.cursor);
// }
// writer.cursor += positionChunkSize();
// },
updateSessionState: function (data) {
if (!data || data.length < 5) {
this.logErrorSessionClientSocketAction(
null,
null,
null,
`Tried to update session state, but data was null or not long enough`
);
return;
}
let session_id = data[1];
let session = this.sessions.get(session_id);
if (!session) {
this.logErrorSessionClientSocketAction(
session_id,
null,
null,
`Tried to update session state, but there was no such session`
);
return;
}
// update session state with latest entity positions
let entity_type = data[4];
if (entity_type == 3) {
let entity_id = data[3];
let i = session.entities.findIndex((e) => e.id == entity_id);
if (i != -1) {
session.entities[i].latest = data;
} else {
let entity = {
id: entity_id,
latest: data,
render: true,
locked: false,
};
session.entities.push(entity);
}
}
},
handleInteraction: function (socket, data) {
let session_id = data[1];
let client_id = data[2];
if (session_id && client_id) {
// relay interaction events to all connected clients
socket
.to(session_id.toString())
.emit(KomodoSendEvents.interactionUpdate, data);
// do session state update if needed
let source_id = data[3];
let target_id = data[4];
let interaction_type = data[5];
let session = this.sessions.get(session_id);
if (!session) return;
// check if the incoming packet is from a client who is valid for this session
if (!session.hasClient(client_id)) {
return;
}
// entity should be rendered
if (interaction_type == INTERACTION_RENDER) {
let i = session.entities.findIndex((e) => e.id == target_id);
if (i != -1) {
session.entities[i].render = true;
} else {
let entity = {
id: target_id,
latest: [],
render: true,
locked: false,
};
session.entities.push(entity);
}
}
// entity should stop being rendered
if (interaction_type == INTERACTION_RENDER_END) {
let i = session.entities.findIndex((e) => e.id == target_id);
if (i != -1) {
session.entities[i].render = false;
} else {
let entity = {
id: target_id,
latest: data,
render: false,
locked: false,
};
session.entities.push(entity);
}
}
// scene has changed
if (interaction_type == INTERACTION_SCENE_CHANGE) {
session.scene = target_id;
}
// entity is locked
if (interaction_type == INTERACTION_LOCK) {
let i = session.entities.findIndex((e) => e.id == target_id);
if (i != -1) {
session.entities[i].locked = true;
} else {
let entity = {
id: target_id,
latest: [],
render: false,
locked: true,
};
session.entities.push(entity);
}
}
// entity is unlocked
if (interaction_type == INTERACTION_LOCK_END) {
let i = session.entities.findIndex((e) => e.id == target_id);
if (i != -1) {
session.entities[i].locked = false;
} else {
let entity = {
id: target_id,
latest: [],
render: false,
locked: false,
};
session.entities.push(entity);
}
}
// NOTE(rob): deprecated, use messages.
// write to file as binary data
// if (session.isRecording) {
// // calculate and write session sequence number
// data[INT_FIELDS-1] = data[INT_FIELDS-1] - session.recordingStart;
// // get reference to session writer (buffer and cursor)
// let writer = session.writers.int;
// if (interactionChunkSize() + writer.cursor > writer.buffer.byteLength) {
// // if buffer is full, dump to disk and reset the cursor
// let path = this.getCapturePath(session_id, session.recordingStart, 'int');
// let wstream = fs.createWriteStream(path, { flags: 'a' });
// wstream.write(writer.buffer.slice(0, writer.cursor));
// wstream.close();
// writer.cursor = 0;
// }
// for (let i = 0; i < data.length; i++) {
// writer.buffer.writeInt32LE(data[i], (i*INT_BYTES_PER_FIELD) + writer.cursor);
// }
// writer.cursor += interactionChunkSize();
// }
}
},
getState: function (socket, session_id, version) {
let session = this.sessions.get(session_id);
if (!session) {
this.stateErrorAction(
socket,
"The session was null, so no state could be found."
);
return { session_id: -1, state: null };
}
let state = {};
// check requested api version
if (version === 2) {
state = {
clients: session.getClients(),
entities: session.entities,
scene: session.scene,
isRecording: session.isRecording,
};
} else {
// version 1 or no api version indicated
let entities = [];
let locked = [];
for (let i = 0; i < session.entities.length; i++) {
entities.push(session.entities[i].id);
if (session.entities[i].locked) {
locked.push(session.entities[i].id);
}
}
state = {
clients: session.getClients(),
entities: entities,
locked: locked,
scene: session.scene,
isRecording: session.isRecording,
};
}
return state;
},
handleStateCatchupRequest: function (socket, data) {
if (!socket) {
this.logErrorSessionClientSocketAction(
null,
null,
null,
`tried to handle state, but socket was null`
);
return { session_id: -1, state: null };
}
if (!data) {
this.logErrorSessionClientSocketAction(
null,
null,
socket.id,
`tried to handle state, but data was null`
);
return { session_id: -1, state: null };
}
let session_id = data.session_id;
let client_id = data.client_id;
let version = data.version;
this.logInfoSessionClientSocketAction(
session_id,
client_id,
socket.id,
`Received state catch-up request, version ${data.version}`
);
if (!session_id || !client_id) {
this.connectionAuthorizationErrorAction(
socket,
"You must provide a session ID and a client ID in the URL options."
);
return { session_id: -1, state: null };
}
return {
session_id: session_id,
state: this.getState(socket, session_id, version)
};
},
// returns true on success and false on failure
addClientToSession: function (session_id, client_id) {
let { success, session } = this.getSession(session_id);
if (!success) {
this.logWarningSessionClientSocketAction(