Browse Source

Added message cache import/export

tags/docs-0.9
RogueException 9 years ago
parent
commit
896004c0f3
2 changed files with 39 additions and 11 deletions
  1. +21
    -3
      src/Discord.Net/DiscordClient.Messages.cs
  2. +18
    -8
      src/Discord.Net/Helpers/AsyncCollection.cs

+ 21
- 3
src/Discord.Net/DiscordClient.Messages.cs View File

@@ -1,4 +1,5 @@
using Discord.API;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -27,8 +28,10 @@ namespace Discord
msg.Cache(); //Builds references
return msg;
}
}
}
}
public void Import(Message[] messages)
=> Import(messages.ToDictionary(x => x.Id));
}

public class MessageEventArgs : EventArgs
{
@@ -214,7 +217,6 @@ namespace Discord
}
}


/// <summary> Downloads last count messages from the server, returning all messages before or after relativeMessageId, if it's provided. </summary>
public async Task<Message[]> DownloadMessages(Channel channel, int count, long? relativeMessageId = null, RelativeDirection relativeDir = RelativeDirection.Before, bool useCache = true)
{
@@ -254,6 +256,22 @@ namespace Discord
}
return new Message[0];
}
/// <summary> Deserializes messages from JSON format and imports them into the message cache.</summary>
public void ImportMessages(string json)
{
if (json == null) throw new ArgumentNullException(nameof(json));

var msgs = JsonConvert.DeserializeObject<Message[]>(json);
_messages.Import(msgs);
}
/// <summary> Serializes the message cache for a given channel to JSON.</summary>
public string ExportMessages(Channel channel)
{
if (channel == null) throw new ArgumentNullException(nameof(channel));

return JsonConvert.SerializeObject(channel.Messages);
}

private Task MessageQueueLoop()
{


+ 18
- 8
src/Discord.Net/Helpers/AsyncCollection.cs View File

@@ -94,6 +94,15 @@ namespace Discord
}
return result;
}
protected void Import(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
lock (_writerLock)
{
foreach (var pair in items)
_dictionary.TryAdd(pair.Key, pair.Value);
}
}

public TValue TryRemove(TKey key)
{
if (_dictionary.ContainsKey(key))
@@ -110,6 +119,15 @@ namespace Discord
}
return null;
}
public void Clear()
{
lock (_writerLock)
{
_dictionary.Clear();
RaiseCleared();
}
}

public TValue Remap(TKey oldKey, TKey newKey)
{
if (_dictionary.ContainsKey(oldKey))
@@ -124,14 +142,6 @@ namespace Discord
}
return null;
}
public void Clear()
{
lock (_writerLock)
{
_dictionary.Clear();
RaiseCleared();
}
}

public IEnumerator<TValue> GetEnumerator() => _dictionary.Select(x => x.Value).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();


Loading…
Cancel
Save