2022-10-28 16:53:28 +08:00
|
|
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
|
|
|
|
// See the LICENCE file in the repository root for full licence text.
|
|
|
|
|
2024-01-25 19:25:27 +08:00
|
|
|
using System;
|
2022-10-28 16:53:28 +08:00
|
|
|
using System.Net;
|
|
|
|
using System.Net.WebSockets;
|
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using osu.Game.Online.API;
|
|
|
|
using osu.Game.Online.API.Requests;
|
|
|
|
|
|
|
|
namespace osu.Game.Online.Notifications.WebSocket
|
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// A connector for <see cref="WebSocketNotificationsClient"/>s that receive events via a websocket.
|
|
|
|
/// </summary>
|
2024-01-25 19:25:27 +08:00
|
|
|
public class WebSocketNotificationsClientConnector : PersistentEndpointClientConnector, INotificationsClient
|
2022-10-28 16:53:28 +08:00
|
|
|
{
|
2024-01-25 19:25:27 +08:00
|
|
|
public event Action<SocketMessage>? MessageReceived;
|
|
|
|
|
2022-10-28 16:53:28 +08:00
|
|
|
private readonly IAPIProvider api;
|
|
|
|
|
|
|
|
public WebSocketNotificationsClientConnector(IAPIProvider api)
|
|
|
|
: base(api)
|
|
|
|
{
|
|
|
|
this.api = api;
|
2024-01-25 19:25:27 +08:00
|
|
|
Start();
|
2022-10-28 16:53:28 +08:00
|
|
|
}
|
|
|
|
|
2024-01-25 19:25:27 +08:00
|
|
|
protected override async Task<PersistentEndpointClient> BuildConnectionAsync(CancellationToken cancellationToken)
|
2022-10-28 16:53:28 +08:00
|
|
|
{
|
|
|
|
var req = new GetNotificationsRequest();
|
2024-01-31 04:40:23 +08:00
|
|
|
// must use `PerformAsync()`, since we may not be fully online yet
|
|
|
|
// (see `APIState.RequiresSecondFactorAuth` - in this state queued requests will not execute).
|
|
|
|
await api.PerformAsync(req).ConfigureAwait(false);
|
|
|
|
string endpoint = req.Response!.Endpoint;
|
2022-10-28 16:53:28 +08:00
|
|
|
|
|
|
|
ClientWebSocket socket = new ClientWebSocket();
|
|
|
|
socket.Options.SetRequestHeader(@"Authorization", @$"Bearer {api.AccessToken}");
|
|
|
|
socket.Options.Proxy = WebRequest.DefaultWebProxy;
|
|
|
|
if (socket.Options.Proxy != null)
|
|
|
|
socket.Options.Proxy.Credentials = CredentialCache.DefaultCredentials;
|
|
|
|
|
2024-01-25 19:25:27 +08:00
|
|
|
var client = new WebSocketNotificationsClient(socket, endpoint);
|
|
|
|
client.MessageReceived += msg => MessageReceived?.Invoke(msg);
|
|
|
|
return client;
|
|
|
|
}
|
|
|
|
|
|
|
|
public Task SendAsync(SocketMessage message, CancellationToken? cancellationToken = default)
|
|
|
|
{
|
|
|
|
if (CurrentConnection is not WebSocketNotificationsClient webSocketClient)
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
|
|
|
return webSocketClient.SendAsync(message, cancellationToken);
|
2022-10-28 16:53:28 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|