using LibMatrix.EventTypes.Spec; using LibMatrix.Homeservers; using MiniUtils.Classes; namespace MiniUtils.Services; public class IgnoreListManager(AuthenticatedHomeserverGeneric homeserver) { private static readonly SemaphoreSlim Lock = new(1, 1); public async Task DisableAll() { await Lock.WaitAsync(); var ignoreList = await homeserver.GetAccountDataOrNullAsync(IgnoredUserListEventContent.EventId) ?? new(); if (ignoreList.IgnoredUsers.Count == 0) { Lock.Release(); return 0; } foreach (var ignore in ignoreList.IgnoredUsers) { ignoreList.DisabledIgnoredUsers.Add(ignore.Key, ignore.Value); } int count = ignoreList.DisabledIgnoredUsers.Count; ignoreList.IgnoredUsers.Clear(); await homeserver.SetAccountDataAsync(IgnoredUserListEventContent.EventId, ignoreList); Lock.Release(); return count; } public async Task EnableAll() { await Lock.WaitAsync(); var ignoreList = await homeserver.GetAccountDataOrNullAsync(IgnoredUserListEventContent.EventId) ?? new(); if (ignoreList.DisabledIgnoredUsers.Count == 0) { Lock.Release(); return 0; } foreach (var ignore in ignoreList.DisabledIgnoredUsers) { ignoreList.IgnoredUsers.Add(ignore.Key, ignore.Value); } var count = ignoreList.IgnoredUsers.Count; ignoreList.DisabledIgnoredUsers.Clear(); await homeserver.SetAccountDataAsync(IgnoredUserListEventContent.EventId, ignoreList); Lock.Release(); return count; } public async Task MoveList(bool enable, IEnumerable items) { await Lock.WaitAsync(); var ignoreList = await homeserver.GetAccountDataOrNullAsync(IgnoredUserListEventContent.EventId) ?? new(); var fromDict = enable ? ignoreList.DisabledIgnoredUsers : ignoreList.IgnoredUsers; var toDict = enable ? ignoreList.IgnoredUsers : ignoreList.DisabledIgnoredUsers; var moved = 0; foreach (var item in items) { if (fromDict.Remove(item, out var value)) { toDict.Add(item, value); moved++; } } if (moved > 0) await homeserver.SetAccountDataAsync(IgnoredUserListEventContent.EventId, ignoreList); Lock.Release(); return moved; } public async Task AddList(string[] itemsToAdd) { int added = 0; await Lock.WaitAsync(); var ignoreList = await homeserver.GetAccountDataOrNullAsync(IgnoredUserListEventContent.EventId) ?? new(); foreach (var item in itemsToAdd) { if (ignoreList.IgnoredUsers.ContainsKey(item)) continue; if (ignoreList.DisabledIgnoredUsers.Remove(item, out var value)) { ignoreList.IgnoredUsers.Add(item, value); added++; continue; } ignoreList.IgnoredUsers.Add(item, new()); added++; } if (added > 0) await homeserver.SetAccountDataAsync(IgnoredUserListEventContent.EventId, ignoreList); Lock.Release(); return added; } }