Kopie van https://gitlab.com/studieverenigingvia/ict/centurion met een paar aanpassingen
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
108 lines
2.7 KiB
108 lines
2.7 KiB
import {Socket} from "socket.io";
|
|
|
|
import Room from "./Room";
|
|
import {getTimelineNames} from "./timeline";
|
|
|
|
export default class User {
|
|
socket: Socket;
|
|
id: string;
|
|
|
|
room: Room | null = null;
|
|
readyToParticipate: boolean = false;
|
|
|
|
constructor(socket: Socket) {
|
|
this.socket = socket;
|
|
this.id = socket.id;
|
|
}
|
|
|
|
onDisconnect() {
|
|
if (this.room != null) {
|
|
|
|
}
|
|
}
|
|
|
|
setRoom(room: Room | null) {
|
|
if (this.room === room) return;
|
|
|
|
if (this.room != null) {
|
|
this.socket.leave(this.room.id.toString());
|
|
this.readyToParticipate = false;
|
|
}
|
|
|
|
this.room = room;
|
|
|
|
if (this.room != null) {
|
|
this.socket.join(this.room.id.toString());
|
|
}
|
|
|
|
this.sync();
|
|
}
|
|
|
|
getConfig() {
|
|
return {
|
|
'availableTimelines': getTimelineNames()
|
|
}
|
|
}
|
|
|
|
sentConfig: any = null;
|
|
sentRoom: any = null;
|
|
sentTimelineName: string | null = null;
|
|
|
|
sync() {
|
|
// Config
|
|
let config = this.getConfig();
|
|
if (!this.syncEquals(this.sentConfig, config)) {
|
|
this.sentConfig = config;
|
|
this.emit('config', {
|
|
'config': this.sentConfig
|
|
});
|
|
}
|
|
|
|
// Room
|
|
if (!this.syncEquals(this.sentRoom, this.room?.serialize(this))) {
|
|
this.sentRoom = this.room?.serialize(this);
|
|
this.emit('room', {
|
|
'room': this.sentRoom
|
|
})
|
|
}
|
|
|
|
// Timeline
|
|
if (!this.syncEquals(this.sentTimelineName, this.room?.timelineName)) {
|
|
this.sentTimelineName = this.room?.timelineName || null;
|
|
this.emit('timeline', {
|
|
'timeline': this.sentTimelineName == null ? null : this.room!!.serializeTimeline(this)
|
|
})
|
|
}
|
|
}
|
|
|
|
emit(eventName: string, obj: any) {
|
|
this.socket.emit(eventName, obj);
|
|
}
|
|
|
|
syncEquals(obj1: any, obj2: any): boolean {
|
|
if (obj1 === undefined && obj2 === undefined)
|
|
return true;
|
|
|
|
if ((obj1 === undefined && obj2 !== undefined) || (obj1 !== undefined && obj2 === undefined))
|
|
return false;
|
|
|
|
if (obj1 === null && obj2 === null)
|
|
return true;
|
|
|
|
if ((obj1 === null && obj2 !== null) || (obj1 !== null && obj2 === null))
|
|
return false;
|
|
|
|
if (typeof (obj1) !== typeof (obj2))
|
|
return false;
|
|
|
|
if (typeof (obj1) === 'string' || typeof (obj1) === 'number' || typeof (obj1) === 'boolean') {
|
|
return obj1 === obj2;
|
|
}
|
|
|
|
if (Object.keys(obj1).length !== Object.keys(obj2).length) return false
|
|
|
|
return Object.keys(obj1).every(key =>
|
|
obj2.hasOwnProperty(key) && this.syncEquals(obj1[key], obj2[key])
|
|
);
|
|
}
|
|
}
|
|
|