Binato/server/objects/DataStream.ts

83 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-11-19 01:06:03 +00:00
import { ConsoleHelper } from "../../ConsoleHelper";
import { Constants } from "../../Constants";
import { DataStreamArray } from "./DataStreamArray";
import { User } from "./User";
import { UserArray } from "./UserArray";
2022-11-19 15:06:03 +00:00
import { hexlify } from "../Util";
2022-11-19 01:06:03 +00:00
export class DataStream {
private users:UserArray = new UserArray();
2022-11-19 15:06:03 +00:00
public readonly name:string;
2022-11-19 01:06:03 +00:00
private readonly parent:DataStreamArray;
private readonly removeWhenEmpty:boolean;
2022-11-19 15:06:03 +00:00
private inactive:boolean = false;
2022-11-19 01:06:03 +00:00
public constructor(name:string, parent:DataStreamArray, removeWhenEmpty:boolean) {
this.name = name;
this.parent = parent;
this.removeWhenEmpty = removeWhenEmpty;
}
2022-11-19 15:06:03 +00:00
private checkInactive() {
if (this.inactive) {
throw `Stream ${this.name} is inactive (deleted) and cannot be used here.`;
}
}
public get userCount() : number {
return this.users.getLength();
}
2022-11-19 01:06:03 +00:00
public AddUser(user:User) : void {
2022-11-19 15:06:03 +00:00
this.checkInactive();
2022-11-19 01:06:03 +00:00
if (!(user.uuid in this.users.getItems())) {
this.users.add(user.uuid, user);
2022-11-19 15:06:03 +00:00
ConsoleHelper.printStream(`Added [${user.username}] to stream [${this.name}]`);
2022-11-19 01:06:03 +00:00
}
}
public RemoveUser(user:User) : void {
2022-11-19 15:06:03 +00:00
this.checkInactive();
2022-11-19 01:06:03 +00:00
if (user.uuid in this.users.getItems()) {
this.users.remove(user.uuid);
2022-11-19 15:06:03 +00:00
ConsoleHelper.printStream(`Removed [${user.username}] from stream [${this.name}]`);
2022-11-19 01:06:03 +00:00
}
if (this.removeWhenEmpty && this.users.getLength() === 0) {
2022-11-19 15:06:03 +00:00
this.Delete();
2022-11-19 01:06:03 +00:00
}
}
2022-11-19 15:06:03 +00:00
public Delete() {
this.parent.DeleteStream(this);
}
public Deactivate() {
this.inactive = true;
}
2022-11-19 01:06:03 +00:00
public Send(data:Buffer) {
2022-11-19 15:06:03 +00:00
this.checkInactive();
2022-11-19 01:06:03 +00:00
for (let user of this.users.getIterableItems()) {
user.addActionToQueue(data);
}
if (Constants.DEBUG) {
2022-11-23 00:48:28 +00:00
ConsoleHelper.printStream(`Sent Buffer<${hexlify(data)}> to all users in stream [${this.name}]`);
2022-11-19 01:06:03 +00:00
}
}
2022-11-19 15:06:03 +00:00
public SendWithExclusion(data:Buffer, exclude:User) {
this.checkInactive();
for (let user of this.users.getIterableItems()) {
if (user.uuid !== exclude.uuid) {
user.addActionToQueue(data);
}
}
if (Constants.DEBUG) {
ConsoleHelper.printStream(`Sent Buffer<${hexlify(data)}> to all users in stream [${this.name}] excluding user [${exclude.username}]`);
}
}
2022-11-19 01:06:03 +00:00
}