Binato/server/SpectatorManager.ts

81 lines
2.2 KiB
TypeScript
Raw Permalink Normal View History

2023-09-10 12:59:22 +01:00
import DataStream from "./objects/DataStream";
import Shared from "./objects/Shared";
import User from "./objects/User";
import osu from "../osuTyping";
import SpectateFramesData from "./interfaces/packetTypes/SpectateFramesData";
2022-11-27 17:37:28 +00:00
2023-09-10 12:59:22 +01:00
export default 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}`);
2023-09-10 18:31:38 +01:00
2022-11-27 17:37:28 +00:00
} else {
user.spectatorStream = spectateStream = userToSpectate.spectatorStream;
}
user.spectatingUser = userToSpectate;
2023-09-10 18:31:38 +01:00
spectateStream.AddUser(user);
2022-11-27 17:37:28 +00:00
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);
}
public spectatorFrames(user:User, spectateFramesData:SpectateFramesData) {
2022-11-27 17:37:28 +00:00
if (user.spectatorStream === undefined) {
return;
}
2023-08-20 13:03:01 +01:00
const osuPacketWriter = osu.Bancho.Writer();
osuPacketWriter.SpectateFrames(spectateFramesData);
2022-11-27 17:37:28 +00:00
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;
}
}
}