Files
archived-discord-bot/CompatBot/Providers/PiracyStringProvider.cs
13xforever 7fd7d09973 RPCS3 Compatibility Bot reimplemented in C# for .NET Core
RPCS3 Compatibility Bot reimplemented in C# for .NET Core

Current status of this PR:
* tested and targeted for .NET Core 2.1
* all functionality is either on par or improved compared to the python version
* compatibility with current bot.db should be preserved in all upgrade scenarios
* some bot management commands were changed (now under !sudo bot)
* standard help generator for the new discord client is ... different;
  compatibility with old format could be restored through custom formatter if needed
* everything has been split in more loosely tied components for easier extensibility and maintenance
* log parsing has been rewritten and should work ~2x as fast
2018-07-20 09:22:28 +02:00

81 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CompatBot.Database;
using Microsoft.EntityFrameworkCore;
using NReco.Text;
namespace CompatBot.Providers
{
internal static class PiracyStringProvider
{
private static readonly object SyncObj = new object();
private static readonly List<string> PiracyStrings;
private static AhoCorasickDoubleArrayTrie<string> matcher;
static PiracyStringProvider()
{
PiracyStrings = BotDb.Instance.Piracystring.Select(ps => ps.String).ToList();
RebuildMatcher();
}
public static async Task<bool> AddAsync(string trigger)
{
if (PiracyStrings.Contains(trigger, StringComparer.InvariantCultureIgnoreCase))
return false;
lock (SyncObj)
{
if (PiracyStrings.Contains(trigger, StringComparer.InvariantCultureIgnoreCase))
return false;
PiracyStrings.Add(trigger);
RebuildMatcher();
}
var db = BotDb.Instance;
await db.Piracystring.AddAsync(new Piracystring {String = trigger}).ConfigureAwait(false);
await db.SaveChangesAsync().ConfigureAwait(false);
return true;
}
public static async Task<bool> RemoveAsync(int id)
{
var db = BotDb.Instance;
var dbItem = await db.Piracystring.FirstOrDefaultAsync(ps => ps.Id == id).ConfigureAwait(false);
if (dbItem == null)
return false;
db.Piracystring.Remove(dbItem);
if (!PiracyStrings.Contains(dbItem.String))
return false;
lock (SyncObj)
{
if (!PiracyStrings.Remove(dbItem.String))
return false;
RebuildMatcher();
}
await db.SaveChangesAsync().ConfigureAwait(false);
return true;
}
public static Task<string> FindTriggerAsync(string str)
{
string result = null;
matcher?.ParseText(str, h =>
{
result = h.Value;
return false;
});
return Task.FromResult(result);
}
private static void RebuildMatcher()
{
matcher = PiracyStrings.Count == 0 ? null : new AhoCorasickDoubleArrayTrie<string>(PiracyStrings.ToDictionary(s => s, s => s));
}
}
}