1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-15 17:02:55 +08:00
osu-lazer/osu.Game/Online/Notifications/NotificationsClient.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

80 lines
2.3 KiB
C#
Raw Normal View History

// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.Chat;
namespace osu.Game.Online.Notifications
{
/// <summary>
/// An abstract client which receives notification-related events (chat/notifications).
/// </summary>
public abstract class NotificationsClient : PersistentEndpointClient
{
public Action<Channel>? ChannelJoined;
2022-11-07 10:36:55 +08:00
public Action<Channel>? ChannelParted;
public Action<List<Message>>? NewMessages;
public Action? PresenceReceived;
protected readonly IAPIProvider API;
private long lastMessageId;
protected NotificationsClient(IAPIProvider api)
{
API = api;
}
2022-11-04 17:48:34 +08:00
public override Task ConnectAsync(CancellationToken cancellationToken)
{
2022-11-21 14:22:57 +08:00
API.Queue(CreateInitialFetchRequest(0));
return Task.CompletedTask;
}
2022-11-21 14:22:57 +08:00
protected APIRequest CreateInitialFetchRequest(long? lastMessageId = null)
{
var fetchReq = new GetUpdatesRequest(lastMessageId ?? this.lastMessageId);
fetchReq.Success += updates =>
{
if (updates?.Presence != null)
{
foreach (var channel in updates.Presence)
2022-11-07 13:35:42 +08:00
HandleChannelJoined(channel);
//todo: handle left channels
HandleMessages(updates.Messages);
}
PresenceReceived?.Invoke();
};
return fetchReq;
}
2022-11-07 13:35:42 +08:00
protected void HandleChannelJoined(Channel channel)
{
channel.Joined.Value = true;
ChannelJoined?.Invoke(channel);
}
2022-11-07 10:36:55 +08:00
protected void HandleChannelParted(Channel channel) => ChannelParted?.Invoke(channel);
protected void HandleMessages(List<Message>? messages)
{
if (messages == null)
return;
NewMessages?.Invoke(messages);
lastMessageId = Math.Max(lastMessageId, messages.LastOrDefault()?.Id ?? 0);
}
}
}