// Copyright (c) 2007-2018 ppy Pty Ltd . // 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 Joined = new Bindable(); public readonly SortedList Messages = new SortedList(Comparer.Default); private readonly List pendingMessages = new List(); public event Action> NewMessagesArrived; public event Action PendingMessageResolved; public event Action 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); } /// /// Replace or remove a message from the chat. /// /// The local echo message (client-side). /// The response message, or null if the message became invalid. 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); } } }