|
| 1 | +// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. |
| 2 | +// See the LICENCE file in the repository root for full licence text. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Linq; |
| 6 | +using System.Threading; |
| 7 | +using osu.Desktop.IPC.Messages; |
| 8 | +using osu.Framework.Allocation; |
| 9 | +using osu.Framework.Bindables; |
| 10 | +using osu.Framework.Extensions; |
| 11 | +using osu.Framework.Graphics; |
| 12 | +using osu.Framework.Logging; |
| 13 | +using osu.Game.Configuration; |
| 14 | +using osu.Game.IPC; |
| 15 | +using osu.Game.Online.Multiplayer; |
| 16 | +using osu.Game.Rulesets.Scoring; |
| 17 | +using osu.Game.Scoring; |
| 18 | +using JsonConvert = Newtonsoft.Json.JsonConvert; |
| 19 | + |
| 20 | +namespace osu.Desktop.IPC |
| 21 | +{ |
| 22 | + public partial class OsuWebSocketProvider : Component |
| 23 | + { |
| 24 | + private WebSocketServer? server; |
| 25 | + private readonly Bindable<ScoreInfo> lastLocalScore = new Bindable<ScoreInfo>(); |
| 26 | + |
| 27 | + [BackgroundDependencyLoader] |
| 28 | + private void load(SessionStatics sessionStatics) |
| 29 | + { |
| 30 | + server = new WebSocketServer(49727); |
| 31 | + server.StartAsync().FireAndForget(onError: ex => Logger.Error(ex, "Failed to start websocket")); |
| 32 | + |
| 33 | + sessionStatics.BindWith(Static.LastLocalUserScore, lastLocalScore); |
| 34 | + } |
| 35 | + |
| 36 | + protected override void LoadComplete() |
| 37 | + { |
| 38 | + base.LoadComplete(); |
| 39 | + |
| 40 | + lastLocalScore.BindValueChanged(val => |
| 41 | + { |
| 42 | + if (val.NewValue == null) |
| 43 | + return; |
| 44 | + |
| 45 | + if (server?.IsRunning != true) |
| 46 | + return; |
| 47 | + |
| 48 | + var msg = new HitCountMessage { NewHits = val.NewValue.Statistics.Where(kv => kv.Key.IsBasic() && kv.Key.IsHit()).Sum(kv => kv.Value) }; |
| 49 | + broadcast(msg); |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + private void broadcast(OsuWebSocketMessage message) |
| 54 | + { |
| 55 | + if (server?.IsRunning != true) |
| 56 | + return; |
| 57 | + |
| 58 | + string messageString = JsonConvert.SerializeObject(message); |
| 59 | + server.BroadcastAsync(messageString).FireAndForget(); |
| 60 | + } |
| 61 | + |
| 62 | + protected override void Dispose(bool isDisposing) |
| 63 | + { |
| 64 | + base.Dispose(isDisposing); |
| 65 | + |
| 66 | + if (server?.IsRunning == true) |
| 67 | + { |
| 68 | + var cts = new CancellationTokenSource(); |
| 69 | + cts.CancelAfter(TimeSpan.FromSeconds(10)); |
| 70 | + server.StopAsync(cts.Token).WaitSafely(); |
| 71 | + server = null; |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments