Binato/server/SpectatorManager.ts

79 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-11-27 17:37:28 +00:00
import { DataStream } from "./objects/DataStream";
2023-08-20 13:03:01 +01:00
import { Shared } from "./objects/Shared";
2022-11-27 17:37:28 +00:00
import { User } from "./objects/User";
2023-08-20 13:03:01 +01:00
import { osu } from "../osuTyping";
2022-11-27 17:37:28 +00:00
export class SpectatorManager {
2023-08-20 13:03:01 +01:00
private shared:Shared;
2022-11-27 17:37:28 +00:00
2023-08-20 13:03:01 +01:00
public constructor(shared:Shared) {
this.shared = shared;
2022-11-27 17:37:28 +00:00
}
public startSpectating(user:User, userIdToSpectate:number) {
2023-08-20 13:03:01 +01:00
const userToSpectate = this.shared.users.getById(userIdToSpectate);
2022-11-27 17:37:28 +00:00
if (userToSpectate === undefined) {
return;
}
// Use existing or create spectator stream
let spectateStream:DataStream;
if (userToSpectate.spectatorStream === undefined) {
2023-08-20 13:03:01 +01:00
user.spectatorStream = spectateStream = userToSpectate.spectatorStream = this.shared.streams.CreateStream(`spectator:${userToSpectate.username}`);
2022-11-27 17:37:28 +00:00
} else {
user.spectatorStream = spectateStream = userToSpectate.spectatorStream;
}
user.spectatingUser = userToSpectate;
2023-08-20 13:03:01 +01:00
let osuPacketWriter = osu.Bancho.Writer();
2022-11-27 17:37:28 +00:00
osuPacketWriter.SpectatorJoined(user.id);
userToSpectate.addActionToQueue(osuPacketWriter.toBuffer);
2023-08-20 13:03:01 +01:00
osuPacketWriter = osu.Bancho.Writer();
2022-11-27 17:37:28 +00:00
osuPacketWriter.FellowSpectatorJoined(user.id);
spectateStream.Send(osuPacketWriter.toBuffer);
}
// TODO: Interface for spectateFrameData
public spectatorFrames(user:User, spectateFrameData:any) {
if (user.spectatorStream === undefined) {
return;
}
2023-08-20 13:03:01 +01:00
const osuPacketWriter = osu.Bancho.Writer();
2022-11-27 17:37:28 +00:00
osuPacketWriter.SpectateFrames(spectateFrameData);
user.spectatorStream.Send(osuPacketWriter.toBuffer);
}
public stopSpectating(user:User) {
if (user.spectatingUser === undefined || user.spectatorStream === undefined) {
return;
}
const spectatedUser = user.spectatingUser;
2023-08-20 13:03:01 +01:00
let osuPacketWriter = osu.Bancho.Writer();
2022-11-27 17:37:28 +00:00
osuPacketWriter.SpectatorLeft(user.id);
spectatedUser.addActionToQueue(osuPacketWriter.toBuffer);
const stream = user.spectatorStream;
stream.RemoveUser(user);
user.spectatorStream = undefined;
user.spectatingUser = undefined;
if (stream.IsActive) {
2023-08-20 13:03:01 +01:00
osuPacketWriter = osu.Bancho.Writer();
2022-11-27 17:37:28 +00:00
osuPacketWriter.FellowSpectatorLeft(user.id);
stream.Send(osuPacketWriter.toBuffer);
} else {
spectatedUser.spectatorStream = undefined;
}
}
}