mirror of
https://github.com/osukey/osukey.git
synced 2025-08-05 07:33:55 +09:00
Split drawing and business logic of ChatOverlay
This commit is contained in:
@ -1,16 +1,11 @@
|
||||
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
|
||||
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using osu.Framework.Configuration;
|
||||
using osu.Framework.Lists;
|
||||
|
||||
namespace osu.Game.Online.Chat
|
||||
{
|
||||
public class ChannelChat
|
||||
public class ChannelChat : ChatBase
|
||||
{
|
||||
[JsonProperty(@"name")]
|
||||
public string Name;
|
||||
@ -24,82 +19,13 @@ namespace osu.Game.Online.Chat
|
||||
[JsonProperty(@"channel_id")]
|
||||
public int Id;
|
||||
|
||||
public readonly SortedList<Message> Messages = new SortedList<Message>(Comparer<Message>.Default);
|
||||
|
||||
private readonly List<LocalEchoMessage> pendingMessages = new List<LocalEchoMessage>();
|
||||
|
||||
public Bindable<bool> Joined = new Bindable<bool>();
|
||||
|
||||
public bool ReadOnly => false;
|
||||
|
||||
public const int MAX_HISTORY = 300;
|
||||
|
||||
[JsonConstructor]
|
||||
public ChannelChat()
|
||||
{
|
||||
}
|
||||
|
||||
public event Action<IEnumerable<Message>> NewMessagesArrived;
|
||||
public event Action<LocalEchoMessage, Message> PendingMessageResolved;
|
||||
public event Action<Message> MessageRemoved;
|
||||
|
||||
public void AddLocalEcho(LocalEchoMessage message)
|
||||
{
|
||||
pendingMessages.Add(message);
|
||||
Messages.Add(message);
|
||||
|
||||
NewMessagesArrived?.Invoke(new[] { message });
|
||||
}
|
||||
|
||||
public void AddNewMessages(params Message[] messages)
|
||||
{
|
||||
messages = messages.Except(Messages).ToArray();
|
||||
|
||||
Messages.AddRange(messages);
|
||||
|
||||
purgeOldMessages();
|
||||
|
||||
NewMessagesArrived?.Invoke(messages);
|
||||
}
|
||||
|
||||
private void purgeOldMessages()
|
||||
{
|
||||
// never purge local echos
|
||||
int messageCount = Messages.Count - pendingMessages.Count;
|
||||
if (messageCount > MAX_HISTORY)
|
||||
Messages.RemoveRange(0, messageCount - MAX_HISTORY);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replace or remove a message from the channel.
|
||||
/// </summary>
|
||||
/// <param name="echo">The local echo message (client-side).</param>
|
||||
/// <param name="final">The response message, or null if the message became invalid.</param>
|
||||
public void ReplaceMessage(LocalEchoMessage echo, Message final)
|
||||
{
|
||||
if (!pendingMessages.Remove(echo))
|
||||
throw new InvalidOperationException("Attempted to remove echo that wasn't present");
|
||||
|
||||
Messages.Remove(echo);
|
||||
|
||||
if (final == null)
|
||||
{
|
||||
MessageRemoved?.Invoke(echo);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Messages.Contains(final))
|
||||
{
|
||||
// message already inserted, so let's throw away this update.
|
||||
// we may want to handle this better in the future, but for the time being api requests are single-threaded so order is assumed.
|
||||
MessageRemoved?.Invoke(echo);
|
||||
return;
|
||||
}
|
||||
|
||||
Messages.Add(final);
|
||||
PendingMessageResolved?.Invoke(echo, final);
|
||||
}
|
||||
|
||||
public override string ToString() => Name;
|
||||
public override long ChatID => Id;
|
||||
public override TargetType Target => TargetType.Channel;
|
||||
}
|
||||
}
|
||||
|
85
osu.Game/Online/Chat/ChatBase.cs
Normal file
85
osu.Game/Online/Chat/ChatBase.cs
Normal file
@ -0,0 +1,85 @@
|
||||
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
|
||||
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using osu.Framework.Configuration;
|
||||
using osu.Framework.Lists;
|
||||
|
||||
namespace osu.Game.Online.Chat
|
||||
{
|
||||
public abstract class ChatBase
|
||||
{
|
||||
public const int MAX_HISTORY = 300;
|
||||
public bool ReadOnly { get; } = false;
|
||||
public abstract TargetType Target { get; }
|
||||
public abstract long ChatID { get; }
|
||||
public Bindable<bool> Joined = new Bindable<bool>();
|
||||
|
||||
public readonly SortedList<Message> Messages = new SortedList<Message>(Comparer<Message>.Default);
|
||||
private readonly List<LocalEchoMessage> pendingMessages = new List<LocalEchoMessage>();
|
||||
|
||||
public event Action<IEnumerable<Message>> NewMessagesArrived;
|
||||
public event Action<LocalEchoMessage, Message> PendingMessageResolved;
|
||||
public event Action<Message> MessageRemoved;
|
||||
|
||||
public void AddLocalEcho(LocalEchoMessage message)
|
||||
{
|
||||
pendingMessages.Add(message);
|
||||
Messages.Add(message);
|
||||
|
||||
NewMessagesArrived?.Invoke(new[] { message });
|
||||
}
|
||||
|
||||
public void AddNewMessages(params Message[] messages)
|
||||
{
|
||||
messages = messages.Except(Messages).ToArray();
|
||||
|
||||
Messages.AddRange(messages);
|
||||
|
||||
purgeOldMessages();
|
||||
|
||||
NewMessagesArrived?.Invoke(messages);
|
||||
}
|
||||
|
||||
private void purgeOldMessages()
|
||||
{
|
||||
// never purge local echos
|
||||
int messageCount = Messages.Count - pendingMessages.Count;
|
||||
if (messageCount > MAX_HISTORY)
|
||||
Messages.RemoveRange(0, messageCount - MAX_HISTORY);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replace or remove a message from the chat.
|
||||
/// </summary>
|
||||
/// <param name="echo">The local echo message (client-side).</param>
|
||||
/// <param name="final">The response message, or null if the message became invalid.</param>
|
||||
public void ReplaceMessage(LocalEchoMessage echo, Message final)
|
||||
{
|
||||
if (!pendingMessages.Remove(echo))
|
||||
throw new InvalidOperationException("Attempted to remove echo that wasn't present");
|
||||
|
||||
Messages.Remove(echo);
|
||||
|
||||
if (final == null)
|
||||
{
|
||||
MessageRemoved?.Invoke(echo);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Messages.Contains(final))
|
||||
{
|
||||
// message already inserted, so let's throw away this update.
|
||||
// we may want to handle this better in the future, but for the time being api requests are single-threaded so order is assumed.
|
||||
MessageRemoved?.Invoke(echo);
|
||||
return;
|
||||
}
|
||||
|
||||
Messages.Add(final);
|
||||
PendingMessageResolved?.Invoke(echo, final);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
193
osu.Game/Online/Chat/ChatManager.cs
Normal file
193
osu.Game/Online/Chat/ChatManager.cs
Normal file
@ -0,0 +1,193 @@
|
||||
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
|
||||
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using osu.Framework.Configuration;
|
||||
using osu.Framework.Extensions.IEnumerableExtensions;
|
||||
using osu.Framework.Logging;
|
||||
using osu.Framework.Threading;
|
||||
using osu.Game.Online.API;
|
||||
using osu.Game.Online.API.Requests;
|
||||
|
||||
namespace osu.Game.Online.Chat
|
||||
{
|
||||
/// <summary>
|
||||
/// Manages everything chat related
|
||||
/// </summary>
|
||||
public sealed class ChatManager : IOnlineComponent
|
||||
{
|
||||
/// <summary>
|
||||
/// The channels the player joins on startup
|
||||
/// </summary>
|
||||
private readonly string[] defaultChannels =
|
||||
{
|
||||
@"#lazer", @"#osu", @"#lobby"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The currently opened chat
|
||||
/// </summary>
|
||||
public Bindable<ChatBase> CurrentChat { get; } = new Bindable<ChatBase>();
|
||||
/// <summary>
|
||||
/// The Channels the player has joined
|
||||
/// </summary>
|
||||
public ObservableCollection<ChannelChat> JoinedChannels { get; } = new ObservableCollection<ChannelChat>();
|
||||
/// <summary>
|
||||
/// The channels available for the player to join
|
||||
/// </summary>
|
||||
public ObservableCollection<ChannelChat> AvailableChannels { get; } = new ObservableCollection<ChannelChat>();
|
||||
|
||||
private APIAccess api;
|
||||
private readonly Scheduler scheduler;
|
||||
private ScheduledDelegate fetchMessagesScheduleder;
|
||||
private GetChannelMessagesRequest fetchChannelMsgReq;
|
||||
private long? lastChannelMsgId;
|
||||
|
||||
public ChatManager(Scheduler scheduler)
|
||||
{
|
||||
this.scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler));
|
||||
CurrentChat.ValueChanged += currentChatChanged;
|
||||
}
|
||||
|
||||
private void currentChatChanged(ChatBase chatBase)
|
||||
{
|
||||
if (chatBase is ChannelChat channel && !JoinedChannels.Contains(channel))
|
||||
JoinedChannels.Add(channel);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Posts a message to the currently opened chat.
|
||||
/// </summary>
|
||||
/// <param name="text">The message text that is going to be posted</param>
|
||||
/// <param name="isAction">Is true if the message is an action, e.g.: user is currently eating </param>
|
||||
public void PostMessage(string text, bool isAction = false)
|
||||
{
|
||||
if (CurrentChat.Value == null)
|
||||
return;
|
||||
|
||||
if (!api.IsLoggedIn)
|
||||
{
|
||||
CurrentChat.Value.AddNewMessages(new ErrorMessage("Please sign in to participate in chat!"));
|
||||
return;
|
||||
}
|
||||
|
||||
var message = new LocalEchoMessage
|
||||
{
|
||||
Sender = api.LocalUser.Value,
|
||||
Timestamp = DateTimeOffset.Now,
|
||||
TargetType = CurrentChat.Value.Target,
|
||||
TargetId = CurrentChat.Value.ChatID,
|
||||
IsAction = isAction,
|
||||
Content = text
|
||||
};
|
||||
|
||||
CurrentChat.Value.AddLocalEcho(message);
|
||||
|
||||
var req = new PostMessageRequest(message);
|
||||
req.Failure += e => CurrentChat.Value?.ReplaceMessage(message, null);
|
||||
req.Success += m => CurrentChat.Value?.ReplaceMessage(message, m);
|
||||
api.Queue(req);
|
||||
}
|
||||
|
||||
public void PostCommand(string text)
|
||||
{
|
||||
if (CurrentChat.Value == null)
|
||||
return;
|
||||
|
||||
var parameters = text.Split(new[] { ' ' }, 2);
|
||||
string command = parameters[0];
|
||||
string content = parameters.Length == 2 ? parameters[1] : string.Empty;
|
||||
|
||||
switch (command)
|
||||
{
|
||||
case "me":
|
||||
if (string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
CurrentChat.Value.AddNewMessages(new ErrorMessage("Usage: /me [action]"));
|
||||
break;
|
||||
}
|
||||
PostMessage(content, true);
|
||||
break;
|
||||
|
||||
case "help":
|
||||
CurrentChat.Value.AddNewMessages(new InfoMessage("Supported commands: /help, /me [action]"));
|
||||
break;
|
||||
|
||||
default:
|
||||
CurrentChat.Value.AddNewMessages(new ErrorMessage($@"""/{command}"" is not supported! For a list of supported commands see /help"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void fetchNewMessages()
|
||||
{
|
||||
if (fetchChannelMsgReq == null)
|
||||
fetchNewChannelMessages();
|
||||
}
|
||||
|
||||
private void fetchNewChannelMessages()
|
||||
{
|
||||
fetchChannelMsgReq = new GetChannelMessagesRequest(JoinedChannels, lastChannelMsgId);
|
||||
|
||||
fetchChannelMsgReq.Success += messages =>
|
||||
{
|
||||
handleChannelMessages(messages);
|
||||
lastChannelMsgId = messages.LastOrDefault()?.Id ?? lastChannelMsgId;
|
||||
fetchChannelMsgReq = null;
|
||||
};
|
||||
fetchChannelMsgReq.Failure += exception => Logger.Error(exception, "Fetching channel messages failed.");
|
||||
|
||||
api.Queue(fetchChannelMsgReq);
|
||||
}
|
||||
|
||||
private void handleChannelMessages(IEnumerable<Message> messages)
|
||||
{
|
||||
var channels = JoinedChannels.ToList();
|
||||
|
||||
foreach (var group in messages.GroupBy(m => m.TargetId))
|
||||
channels.Find(c => c.Id == group.Key)?.AddNewMessages(group.ToArray());
|
||||
}
|
||||
|
||||
private void initializeDefaultChannels()
|
||||
{
|
||||
var req = new ListChannelsRequest();
|
||||
|
||||
req.Success += channels =>
|
||||
{
|
||||
channels.Where(channel => AvailableChannels.All(c => c.ChatID != channel.ChatID))
|
||||
.ForEach(channel => AvailableChannels.Add(channel));
|
||||
|
||||
channels.Where(channel => defaultChannels.Contains(channel.Name))
|
||||
.Where(channel => JoinedChannels.All(c => c.ChatID != channel.ChatID))
|
||||
.ForEach(channel => JoinedChannels.Add(channel));
|
||||
|
||||
fetchNewMessages();
|
||||
};
|
||||
req.Failure += error => Logger.Error(error, "Fetching channels failed");
|
||||
|
||||
api.Queue(req);
|
||||
}
|
||||
|
||||
public void APIStateChanged(APIAccess api, APIState state)
|
||||
{
|
||||
this.api = api ?? throw new ArgumentNullException(nameof(api));
|
||||
|
||||
switch (state)
|
||||
{
|
||||
case APIState.Online:
|
||||
if (JoinedChannels.Count == 0)
|
||||
initializeDefaultChannels();
|
||||
fetchMessagesScheduleder = scheduler.AddDelayed(fetchNewMessages, 1000, true);
|
||||
break;
|
||||
default:
|
||||
fetchChannelMsgReq?.Cancel();
|
||||
fetchMessagesScheduleder?.Cancel();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -22,7 +22,7 @@ namespace osu.Game.Online.Chat
|
||||
public TargetType TargetType;
|
||||
|
||||
[JsonProperty(@"target_id")]
|
||||
public int TargetId;
|
||||
public long TargetId;
|
||||
|
||||
[JsonProperty(@"is_action")]
|
||||
public bool IsAction;
|
||||
|
Reference in New Issue
Block a user