1
0
mirror of https://github.com/ppy/osu.git synced 2024-09-22 06:47:24 +08:00
osu-lazer/osu.Game/Online/Spectator/SpectatorStreamingClient.cs

192 lines
6.4 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
2020-10-22 16:29:43 +08:00
using Newtonsoft.Json;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
2020-10-22 16:29:38 +08:00
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Replays.Types;
namespace osu.Game.Online.Spectator
{
public class SpectatorStreamingClient : Component, ISpectatorClient
{
private HubConnection connection;
private readonly List<string> watchingUsers = new List<string>();
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
2020-10-22 14:27:04 +08:00
private bool isConnected;
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private IBindable<WorkingBeatmap> beatmap { get; set; }
2020-10-22 16:29:38 +08:00
[Resolved]
private IBindable<IReadOnlyList<Mod>> mods { get; set; }
private readonly SpectatorState currentState = new SpectatorState();
[BackgroundDependencyLoader]
private void load()
{
apiState.BindTo(api.State);
apiState.BindValueChanged(apiStateChanged, true);
}
private void apiStateChanged(ValueChangedEvent<APIState> state)
{
switch (state.NewValue)
{
case APIState.Failing:
case APIState.Offline:
connection?.StopAsync();
connection = null;
break;
case APIState.Online:
2020-10-22 14:27:04 +08:00
Task.Run(connect);
break;
}
}
#if DEBUG
private const string endpoint = "http://localhost:5009/spectator";
#else
private const string endpoint = "https://spectator.ppy.sh/spectator";
#endif
2020-10-22 14:27:04 +08:00
private async Task connect()
{
2020-10-22 14:27:04 +08:00
if (connection != null)
return;
connection = new HubConnectionBuilder()
.WithUrl(endpoint, options =>
{
options.Headers.Add("Authorization", $"Bearer {api.AccessToken}");
})
2020-10-22 16:29:43 +08:00
.AddNewtonsoftJsonProtocol(options => { options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; })
.Build();
// until strong typed client support is added, each method must be manually bound (see https://github.com/dotnet/aspnetcore/issues/15198)
2020-10-22 16:29:38 +08:00
connection.On<string, SpectatorState>(nameof(ISpectatorClient.UserBeganPlaying), ((ISpectatorClient)this).UserBeganPlaying);
connection.On<string, FrameDataBundle>(nameof(ISpectatorClient.UserSentFrames), ((ISpectatorClient)this).UserSentFrames);
2020-10-22 16:29:38 +08:00
connection.On<string, SpectatorState>(nameof(ISpectatorClient.UserFinishedPlaying), ((ISpectatorClient)this).UserFinishedPlaying);
2020-10-22 14:27:04 +08:00
connection.Closed += async ex =>
{
isConnected = false;
if (ex != null) await tryUntilConnected();
};
await tryUntilConnected();
async Task tryUntilConnected()
{
while (api.State.Value == APIState.Online)
{
try
{
// reconnect on any failure
await connection.StartAsync();
// success
isConnected = true;
break;
}
catch
{
await Task.Delay(5000);
}
}
}
}
2020-10-22 16:29:38 +08:00
Task ISpectatorClient.UserBeganPlaying(string userId, SpectatorState state)
{
if (connection.ConnectionId != userId)
{
if (watchingUsers.Contains(userId))
{
Console.WriteLine($"{connection.ConnectionId} received began playing for already watched user {userId}");
}
else
{
Console.WriteLine($"{connection.ConnectionId} requesting watch other user {userId}");
WatchUser(userId);
watchingUsers.Add(userId);
}
}
else
{
2020-10-22 16:29:38 +08:00
Console.WriteLine($"{connection.ConnectionId} Received user playing event for self {state}");
}
return Task.CompletedTask;
}
2020-10-22 16:29:38 +08:00
Task ISpectatorClient.UserFinishedPlaying(string userId, SpectatorState state)
{
2020-10-22 16:29:38 +08:00
Console.WriteLine($"{connection.ConnectionId} Received user finished event {state}");
return Task.CompletedTask;
}
Task ISpectatorClient.UserSentFrames(string userId, FrameDataBundle data)
{
2020-10-22 14:27:04 +08:00
Console.WriteLine($"{connection.ConnectionId} Received frames from {userId}: {data.Frames.First()}");
return Task.CompletedTask;
}
2020-10-22 16:29:43 +08:00
public void BeginPlaying()
2020-10-22 14:27:04 +08:00
{
if (!isConnected) return;
2020-10-22 16:29:43 +08:00
// transfer state at point of beginning play
currentState.BeatmapID = beatmap.Value.BeatmapInfo.OnlineBeatmapID;
2020-10-22 16:38:16 +08:00
currentState.Mods = mods.Value.Select(m => new APIMod(m));
2020-10-22 16:29:43 +08:00
connection.SendAsync(nameof(ISpectatorServer.BeginPlaySession), currentState);
2020-10-22 14:27:04 +08:00
}
2020-10-22 14:27:04 +08:00
public void SendFrames(FrameDataBundle data)
{
if (!isConnected) return;
connection.SendAsync(nameof(ISpectatorServer.SendFrameData), data);
}
2020-10-22 16:29:38 +08:00
public void EndPlaying()
2020-10-22 14:27:04 +08:00
{
if (!isConnected) return;
2020-10-22 16:29:38 +08:00
connection.SendAsync(nameof(ISpectatorServer.EndPlaySession), currentState);
2020-10-22 14:27:04 +08:00
}
public void WatchUser(string userId)
{
if (!isConnected) return;
connection.SendAsync(nameof(ISpectatorServer.StartWatchingUser), userId);
}
public void HandleFrame(ReplayFrame frame)
{
2020-10-22 16:29:38 +08:00
// ReSharper disable once SuspiciousTypeConversion.Global (implemented by rulesets)
if (frame is IConvertibleReplayFrame convertible)
// TODO: don't send a bundle for each individual frame
SendFrames(new FrameDataBundle(new[] { convertible.ToLegacy(beatmap.Value.Beatmap) }));
}
}
}