From 5c295ee32ebc604b47866f58c44c741a22e82e08 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 May 2021 16:15:38 -0500 Subject: split things into feature folders --- .../API/Controllers/ConversationsController.cs | 3 +- src/slskd/API/Controllers/RoomsController.cs | 3 +- src/slskd/API/Controllers/SearchesController.cs | 2 +- src/slskd/API/Controllers/TransfersController.cs | 2 +- src/slskd/API/Controllers/UserController.cs | 2 +- src/slskd/API/DTO/PrivateMessageResponse.cs | 2 +- src/slskd/API/DTO/RoomMessageResponse.cs | 2 +- src/slskd/API/DTO/RoomResponse.cs | 2 +- src/slskd/Common/ISharedFileCache.cs | 36 ---- src/slskd/Common/SearchResponseCache.cs | 77 --------- src/slskd/Common/SharedFileCache.cs | 165 ------------------ src/slskd/Entities/PrivateMessage.cs | 71 -------- src/slskd/Entities/Room.cs | 75 -------- src/slskd/Entities/RoomMessage.cs | 59 ------- src/slskd/Local/ISharedFileCache.cs | 36 ++++ src/slskd/Local/SharedFileCache.cs | 165 ++++++++++++++++++ src/slskd/Messaging/ConversationTracker.cs | 62 +++++++ src/slskd/Messaging/Entities/PrivateMessage.cs | 71 ++++++++ src/slskd/Messaging/Entities/Room.cs | 75 ++++++++ src/slskd/Messaging/Entities/RoomMessage.cs | 59 +++++++ src/slskd/Messaging/IConversationTracker.cs | 55 ++++++ src/slskd/Messaging/IRoomTracker.cs | 75 ++++++++ src/slskd/Messaging/RoomTracker.cs | 112 ++++++++++++ src/slskd/Peer/BrowseTracker.cs | 57 ++++++ src/slskd/Peer/IBrowseTracker.cs | 54 ++++++ src/slskd/Search/ISearchTracker.cs | 52 ++++++ src/slskd/Search/SearchResponseCache.cs | 77 +++++++++ src/slskd/Search/SearchTracker.cs | 62 +++++++ src/slskd/Service.cs | 7 +- src/slskd/Startup.cs | 6 +- src/slskd/Trackers/BrowseTracker.cs | 57 ------ src/slskd/Trackers/ConversationTracker.cs | 63 ------- src/slskd/Trackers/IBrowseTracker.cs | 54 ------ src/slskd/Trackers/IConversationTracker.cs | 56 ------ src/slskd/Trackers/IRoomTracker.cs | 76 -------- src/slskd/Trackers/ISearchTracker.cs | 52 ------ src/slskd/Trackers/ITransferTracker.cs | 57 ------ src/slskd/Trackers/RoomTracker.cs | 113 ------------ src/slskd/Trackers/SearchTracker.cs | 62 ------- src/slskd/Trackers/TransferTracker.cs | 192 --------------------- src/slskd/Transfer/ITransferTracker.cs | 57 ++++++ src/slskd/Transfer/TransferTracker.cs | 192 +++++++++++++++++++++ 42 files changed, 1279 insertions(+), 1278 deletions(-) delete mode 100644 src/slskd/Common/ISharedFileCache.cs delete mode 100644 src/slskd/Common/SearchResponseCache.cs delete mode 100644 src/slskd/Common/SharedFileCache.cs delete mode 100644 src/slskd/Entities/PrivateMessage.cs delete mode 100644 src/slskd/Entities/Room.cs delete mode 100644 src/slskd/Entities/RoomMessage.cs create mode 100644 src/slskd/Local/ISharedFileCache.cs create mode 100644 src/slskd/Local/SharedFileCache.cs create mode 100644 src/slskd/Messaging/ConversationTracker.cs create mode 100644 src/slskd/Messaging/Entities/PrivateMessage.cs create mode 100644 src/slskd/Messaging/Entities/Room.cs create mode 100644 src/slskd/Messaging/Entities/RoomMessage.cs create mode 100644 src/slskd/Messaging/IConversationTracker.cs create mode 100644 src/slskd/Messaging/IRoomTracker.cs create mode 100644 src/slskd/Messaging/RoomTracker.cs create mode 100644 src/slskd/Peer/BrowseTracker.cs create mode 100644 src/slskd/Peer/IBrowseTracker.cs create mode 100644 src/slskd/Search/ISearchTracker.cs create mode 100644 src/slskd/Search/SearchResponseCache.cs create mode 100644 src/slskd/Search/SearchTracker.cs delete mode 100644 src/slskd/Trackers/BrowseTracker.cs delete mode 100644 src/slskd/Trackers/ConversationTracker.cs delete mode 100644 src/slskd/Trackers/IBrowseTracker.cs delete mode 100644 src/slskd/Trackers/IConversationTracker.cs delete mode 100644 src/slskd/Trackers/IRoomTracker.cs delete mode 100644 src/slskd/Trackers/ISearchTracker.cs delete mode 100644 src/slskd/Trackers/ITransferTracker.cs delete mode 100644 src/slskd/Trackers/RoomTracker.cs delete mode 100644 src/slskd/Trackers/SearchTracker.cs delete mode 100644 src/slskd/Trackers/TransferTracker.cs create mode 100644 src/slskd/Transfer/ITransferTracker.cs create mode 100644 src/slskd/Transfer/TransferTracker.cs (limited to 'src') diff --git a/src/slskd/API/Controllers/ConversationsController.cs b/src/slskd/API/Controllers/ConversationsController.cs index cd7557a1..dafe5a71 100644 --- a/src/slskd/API/Controllers/ConversationsController.cs +++ b/src/slskd/API/Controllers/ConversationsController.cs @@ -24,8 +24,7 @@ namespace slskd.API.Controllers using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using slskd.API.DTO; - using slskd.Entities; - using slskd.Trackers; + using slskd.Messaging; using Soulseek; /// diff --git a/src/slskd/API/Controllers/RoomsController.cs b/src/slskd/API/Controllers/RoomsController.cs index 5961de7f..d309555e 100644 --- a/src/slskd/API/Controllers/RoomsController.cs +++ b/src/slskd/API/Controllers/RoomsController.cs @@ -25,8 +25,7 @@ namespace slskd.API.Controllers using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using slskd.API.DTO; - using slskd.Entities; - using slskd.Trackers; + using slskd.Messaging; using Soulseek; /// diff --git a/src/slskd/API/Controllers/SearchesController.cs b/src/slskd/API/Controllers/SearchesController.cs index d9d3115d..4a3dc7ab 100644 --- a/src/slskd/API/Controllers/SearchesController.cs +++ b/src/slskd/API/Controllers/SearchesController.cs @@ -25,7 +25,7 @@ namespace slskd.API.Controllers using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using slskd.API.DTO; - using slskd.Trackers; + using slskd.Search; using Soulseek; /// diff --git a/src/slskd/API/Controllers/TransfersController.cs b/src/slskd/API/Controllers/TransfersController.cs index f730a75e..11c5dcad 100644 --- a/src/slskd/API/Controllers/TransfersController.cs +++ b/src/slskd/API/Controllers/TransfersController.cs @@ -26,7 +26,7 @@ namespace slskd.API.Controllers using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using slskd.API.DTO; - using slskd.Trackers; + using slskd.Transfer; using Soulseek; /// diff --git a/src/slskd/API/Controllers/UserController.cs b/src/slskd/API/Controllers/UserController.cs index 1dd96f7a..439479b5 100644 --- a/src/slskd/API/Controllers/UserController.cs +++ b/src/slskd/API/Controllers/UserController.cs @@ -23,7 +23,7 @@ namespace slskd.API.Controllers using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using slskd.API.DTO; - using slskd.Trackers; + using slskd.Peer; using Soulseek; /// diff --git a/src/slskd/API/DTO/PrivateMessageResponse.cs b/src/slskd/API/DTO/PrivateMessageResponse.cs index aa2b142d..9794d762 100644 --- a/src/slskd/API/DTO/PrivateMessageResponse.cs +++ b/src/slskd/API/DTO/PrivateMessageResponse.cs @@ -17,8 +17,8 @@ namespace slskd.API.DTO { + using slskd.Messaging; using System; - using slskd.Entities; public class PrivateMessageResponse { diff --git a/src/slskd/API/DTO/RoomMessageResponse.cs b/src/slskd/API/DTO/RoomMessageResponse.cs index 520da714..48a77f51 100644 --- a/src/slskd/API/DTO/RoomMessageResponse.cs +++ b/src/slskd/API/DTO/RoomMessageResponse.cs @@ -17,8 +17,8 @@ namespace slskd.API.DTO { + using slskd.Messaging; using System; - using slskd.Entities; public class RoomMessageResponse { diff --git a/src/slskd/API/DTO/RoomResponse.cs b/src/slskd/API/DTO/RoomResponse.cs index a6da7836..552cb7f5 100644 --- a/src/slskd/API/DTO/RoomResponse.cs +++ b/src/slskd/API/DTO/RoomResponse.cs @@ -17,9 +17,9 @@ namespace slskd.API.DTO { + using slskd.Messaging; using System.Collections.Generic; using System.Linq; - using slskd.Entities; public class RoomResponse { diff --git a/src/slskd/Common/ISharedFileCache.cs b/src/slskd/Common/ISharedFileCache.cs deleted file mode 100644 index a7b8bf40..00000000 --- a/src/slskd/Common/ISharedFileCache.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Collections.Generic; - using Soulseek; - - public interface ISharedFileCache - { - event EventHandler<(int Directories, int Files)> Refreshed; - - string Directory { get; } - DateTime? LastFill { get; } - long TTL { get; } - - void Fill(); - - IEnumerable Search(SearchQuery query); - } -} \ No newline at end of file diff --git a/src/slskd/Common/SearchResponseCache.cs b/src/slskd/Common/SearchResponseCache.cs deleted file mode 100644 index eddc4fbb..00000000 --- a/src/slskd/Common/SearchResponseCache.cs +++ /dev/null @@ -1,77 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using Microsoft.Extensions.Caching.Memory; - using Soulseek; - - /// - /// Caches undelivered search responses. - /// - public class SearchResponseCache : ISearchResponseCache - { - /// - /// Initializes a new instance of the class. - /// - public SearchResponseCache() - { - Cache = new MemoryCache(new MemoryCacheOptions()); - } - - private IMemoryCache Cache { get; } - - /// - /// Caches or updates a response. - /// - /// The token for which the response is to be added or updated. - /// The response and context to cache. - public void AddOrUpdate(int responseToken, (string Username, int Token, string Query, SearchResponse SearchResponse) response) - { - Cache.Set(responseToken, response, TimeSpan.FromMinutes(3)); - } - - /// - /// Attempts to fetch a cached response and context for the specified . - /// - /// The token for the cached response. - /// The cached response and context, if present. - /// A value indicating whether a response for the specified responseToken is cached. - public bool TryGet(int responseToken, out (string Username, int Token, string Query, SearchResponse SearchResponse) response) - { - return Cache.TryGetValue(responseToken, out response); - } - - /// - /// Attempts to remove a cached Soulseek.SearchResponse and context for the specified . - /// - /// The token for the cached response. - /// The cached response and context, if present. - /// A value indicating whether a response for the specified responseToken was removed. - public bool TryRemove(int responseToken, out (string Username, int Token, string Query, SearchResponse SearchResponse) response) - { - if (Cache.TryGetValue(responseToken, out response)) - { - Cache.Remove(responseToken); - return true; - } - - return false; - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/SharedFileCache.cs b/src/slskd/Common/SharedFileCache.cs deleted file mode 100644 index 00496a47..00000000 --- a/src/slskd/Common/SharedFileCache.cs +++ /dev/null @@ -1,165 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.IO; - using System.Linq; - using System.Threading; - using Microsoft.Data.Sqlite; - using Soulseek; - - /// - /// Caches shared files. - /// - public class SharedFileCache : ISharedFileCache - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public SharedFileCache(string directory, long ttl) - { - Directory = directory; - TTL = ttl; - } - - public event EventHandler<(int Directories, int Files)> Refreshed; - - public string Directory { get; } - public DateTime? LastFill { get; set; } - public long TTL { get; } - - private Dictionary Files { get; set; } - private SqliteConnection SQLite { get; set; } - private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); - - /// - /// Scans the configured and fills the cache. - /// - public void Fill() - { - var sw = new Stopwatch(); - sw.Start(); - - Console.WriteLine($"[SHARED FILE CACHE]: Refreshing..."); - - SyncRoot.EnterWriteLock(); - - try - { - CreateTable(); - - var directories = System.IO.Directory.GetDirectories(Directory, "*", SearchOption.AllDirectories); - - Files = System.IO.Directory.GetFiles(Directory, "*", SearchOption.AllDirectories) - .Select(f => new Soulseek.File(1, f.Replace("/", @"\"), new FileInfo(f).Length, Path.GetExtension(f))) - .ToDictionary(f => f.Filename, f => f); - - // potentially optimize with multi-valued insert - // https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in Files) - { - InsertFilename(file.Key); - } - - Refreshed?.Invoke(this, (directories.Length, Files.Count)); - } - finally - { - SyncRoot.ExitWriteLock(); - } - - sw.Stop(); - - Console.WriteLine($"[SHARED FILE CACHE]: Refreshed in {sw.ElapsedMilliseconds}ms. Found {Files.Count} files."); - LastFill = DateTime.UtcNow; - } - - /// - /// Searches the cache for files matching the specified . - /// - /// - /// - public IEnumerable Search(SearchQuery query) - { - if (!LastFill.HasValue || LastFill.Value.AddMilliseconds(TTL) < DateTime.UtcNow) - { - Fill(); - } - - return QueryTable(query.Query); - } - - private void CreateTable() - { - SQLite = new SqliteConnection("Data Source=:memory:"); - SQLite.Open(); - - using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); - cmd.ExecuteNonQuery(); - } - - private void InsertFilename(string filename) - { - using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); - cmd.ExecuteNonQuery(); - } - - private IEnumerable QueryTable(string text) - { - // sanitize the query string. there's probably more to it than this. - text = text - .Replace("/", " ") - .Replace("\\", " ") - .Replace(":", " ") - .Replace("\"", " "); - - var query = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; - - SyncRoot.EnterReadLock(); - - try - { - using var cmd = new SqliteCommand(query, SQLite); - var results = new List(); - var reader = cmd.ExecuteReader(); - - while (reader.Read()) - { - results.Add(reader.GetString(0)); - } - - return results.Select(r => Files[r.Replace("''", "'")]); - } - catch (Exception ex) - { - // temporary error trap to refine substitution rules - Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); - return Enumerable.Empty(); - } - finally - { - SyncRoot.ExitReadLock(); - } - } - } -} \ No newline at end of file diff --git a/src/slskd/Entities/PrivateMessage.cs b/src/slskd/Entities/PrivateMessage.cs deleted file mode 100644 index 9aa16bdf..00000000 --- a/src/slskd/Entities/PrivateMessage.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Entities -{ - using System; - using Soulseek; - - /// - /// A private message. - /// - public class PrivateMessage - { - /// - /// A value indicating whether the message has been acknowledged. - /// - public bool Acknowledged { get; set; } = false; - - /// - /// The unique message id, used to acknowledge receipt. - /// - public int Id { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// A value indicating whether the message was replayed. - /// - public bool Replayed { get; set; } - - /// - /// The UTC timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) - { - return new PrivateMessage() - { - Id = eventArgs.Id, - Timestamp = eventArgs.Timestamp, - Username = eventArgs.Username, - Message = eventArgs.Message, - Acknowledged = false, - Replayed = eventArgs.Replayed, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Entities/Room.cs b/src/slskd/Entities/Room.cs deleted file mode 100644 index 845004cc..00000000 --- a/src/slskd/Entities/Room.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Entities -{ - using System.Collections.Generic; - using System.Linq; - using Soulseek; - - public class Room - { - /// - /// The room name. - /// - public string Name { get; set; } - - /// - /// A value indicating whether the room is private. - /// - public bool IsPrivate { get; set; } - - /// - /// The number of operators in the room, if private. - /// - public int? OperatorCount { get; set; } - - /// - /// The operators in the room, if private. - /// - public IList Operators { get; set; } - - /// - /// The owner of the room, if private. - /// - public string Owner { get; set; } - - /// - /// The list of users in the room. - /// - public IList Users { get; set; } = new List(); - - /// - /// The list of messages. - /// - public IList Messages { get; set; } = new List(); - - public static Room FromRoomData(RoomData roomData) - { - return new Room() - { - Name = roomData.Name, - IsPrivate = roomData.IsPrivate, - OperatorCount = roomData.OperatorCount, - Operators = roomData.Operators?.ToList(), - Owner = roomData.Owner, - Users = roomData.Users?.ToList(), - Messages = new List(), - }; - } - } -} diff --git a/src/slskd/Entities/RoomMessage.cs b/src/slskd/Entities/RoomMessage.cs deleted file mode 100644 index 8fca973d..00000000 --- a/src/slskd/Entities/RoomMessage.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Entities -{ - using System; - using Soulseek; - - /// - /// A message sent to a room. - /// - public class RoomMessage - { - /// - /// The timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// The room to which the message pertains. - /// - public string RoomName { get; set; } - - public static RoomMessage FromEventArgs(RoomMessageReceivedEventArgs eventArgs, DateTime? timestamp = null) - { - return new RoomMessage() - { - Timestamp = timestamp ?? DateTime.UtcNow, - Username = eventArgs.Username, - Message = eventArgs.Message, - RoomName = eventArgs.RoomName, - }; - } - } -} diff --git a/src/slskd/Local/ISharedFileCache.cs b/src/slskd/Local/ISharedFileCache.cs new file mode 100644 index 00000000..960b906d --- /dev/null +++ b/src/slskd/Local/ISharedFileCache.cs @@ -0,0 +1,36 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Local +{ + using System; + using System.Collections.Generic; + using Soulseek; + + public interface ISharedFileCache + { + event EventHandler<(int Directories, int Files)> Refreshed; + + string Directory { get; } + DateTime? LastFill { get; } + long TTL { get; } + + void Fill(); + + IEnumerable Search(SearchQuery query); + } +} \ No newline at end of file diff --git a/src/slskd/Local/SharedFileCache.cs b/src/slskd/Local/SharedFileCache.cs new file mode 100644 index 00000000..fd6abaff --- /dev/null +++ b/src/slskd/Local/SharedFileCache.cs @@ -0,0 +1,165 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Local +{ + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Threading; + using Microsoft.Data.Sqlite; + using Soulseek; + + /// + /// Caches shared files. + /// + public class SharedFileCache : ISharedFileCache + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public SharedFileCache(string directory, long ttl) + { + Directory = directory; + TTL = ttl; + } + + public event EventHandler<(int Directories, int Files)> Refreshed; + + public string Directory { get; } + public DateTime? LastFill { get; set; } + public long TTL { get; } + + private Dictionary Files { get; set; } + private SqliteConnection SQLite { get; set; } + private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); + + /// + /// Scans the configured and fills the cache. + /// + public void Fill() + { + var sw = new Stopwatch(); + sw.Start(); + + Console.WriteLine($"[SHARED FILE CACHE]: Refreshing..."); + + SyncRoot.EnterWriteLock(); + + try + { + CreateTable(); + + var directories = System.IO.Directory.GetDirectories(Directory, "*", SearchOption.AllDirectories); + + Files = System.IO.Directory.GetFiles(Directory, "*", SearchOption.AllDirectories) + .Select(f => new Soulseek.File(1, f.Replace("/", @"\"), new FileInfo(f).Length, Path.GetExtension(f))) + .ToDictionary(f => f.Filename, f => f); + + // potentially optimize with multi-valued insert + // https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + foreach (var file in Files) + { + InsertFilename(file.Key); + } + + Refreshed?.Invoke(this, (directories.Length, Files.Count)); + } + finally + { + SyncRoot.ExitWriteLock(); + } + + sw.Stop(); + + Console.WriteLine($"[SHARED FILE CACHE]: Refreshed in {sw.ElapsedMilliseconds}ms. Found {Files.Count} files."); + LastFill = DateTime.UtcNow; + } + + /// + /// Searches the cache for files matching the specified . + /// + /// + /// + public IEnumerable Search(SearchQuery query) + { + if (!LastFill.HasValue || LastFill.Value.AddMilliseconds(TTL) < DateTime.UtcNow) + { + Fill(); + } + + return QueryTable(query.Query); + } + + private void CreateTable() + { + SQLite = new SqliteConnection("Data Source=:memory:"); + SQLite.Open(); + + using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); + cmd.ExecuteNonQuery(); + } + + private void InsertFilename(string filename) + { + using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); + cmd.ExecuteNonQuery(); + } + + private IEnumerable QueryTable(string text) + { + // sanitize the query string. there's probably more to it than this. + text = text + .Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " "); + + var query = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; + + SyncRoot.EnterReadLock(); + + try + { + using var cmd = new SqliteCommand(query, SQLite); + var results = new List(); + var reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + + return results.Select(r => Files[r.Replace("''", "'")]); + } + catch (Exception ex) + { + // temporary error trap to refine substitution rules + Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); + return Enumerable.Empty(); + } + finally + { + SyncRoot.ExitReadLock(); + } + } + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/ConversationTracker.cs b/src/slskd/Messaging/ConversationTracker.cs new file mode 100644 index 00000000..27d678ca --- /dev/null +++ b/src/slskd/Messaging/ConversationTracker.cs @@ -0,0 +1,62 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + + /// + /// Tracks private message conversations. + /// + public class ConversationTracker : IConversationTracker + { + /// + /// Tracked private message conversations. + /// + public ConcurrentDictionary> Conversations { get; } = new ConcurrentDictionary>(); + + /// + /// Adds a private message conversation and appends the specified , or just appends the + /// message if the conversation exists. + /// + /// + /// + public void AddOrUpdate(string username, PrivateMessage message) + { + Conversations.AddOrUpdate(username, new List() { message }, (_, messageList) => + { + messageList.Add(message); + return messageList; + }); + } + + /// + /// Returns the list of private messages for the specified , if any exist. + /// + /// + /// + /// + public bool TryGet(string username, out IList messages) => Conversations.TryGetValue(username, out messages); + + /// + /// Removes a tracked private message conversation for the specified user. + /// + /// + public void TryRemove(string username) => Conversations.TryRemove(username, out _); + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/Entities/PrivateMessage.cs b/src/slskd/Messaging/Entities/PrivateMessage.cs new file mode 100644 index 00000000..236632aa --- /dev/null +++ b/src/slskd/Messaging/Entities/PrivateMessage.cs @@ -0,0 +1,71 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Messaging +{ + using System; + using Soulseek; + + /// + /// A private message. + /// + public class PrivateMessage + { + /// + /// A value indicating whether the message has been acknowledged. + /// + public bool Acknowledged { get; set; } = false; + + /// + /// The unique message id, used to acknowledge receipt. + /// + public int Id { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// A value indicating whether the message was replayed. + /// + public bool Replayed { get; set; } + + /// + /// The UTC timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) + { + return new PrivateMessage() + { + Id = eventArgs.Id, + Timestamp = eventArgs.Timestamp, + Username = eventArgs.Username, + Message = eventArgs.Message, + Acknowledged = false, + Replayed = eventArgs.Replayed, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/Entities/Room.cs b/src/slskd/Messaging/Entities/Room.cs new file mode 100644 index 00000000..459dea2c --- /dev/null +++ b/src/slskd/Messaging/Entities/Room.cs @@ -0,0 +1,75 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Messaging +{ + using System.Collections.Generic; + using System.Linq; + using Soulseek; + + public class Room + { + /// + /// The room name. + /// + public string Name { get; set; } + + /// + /// A value indicating whether the room is private. + /// + public bool IsPrivate { get; set; } + + /// + /// The number of operators in the room, if private. + /// + public int? OperatorCount { get; set; } + + /// + /// The operators in the room, if private. + /// + public IList Operators { get; set; } + + /// + /// The owner of the room, if private. + /// + public string Owner { get; set; } + + /// + /// The list of users in the room. + /// + public IList Users { get; set; } = new List(); + + /// + /// The list of messages. + /// + public IList Messages { get; set; } = new List(); + + public static Room FromRoomData(RoomData roomData) + { + return new Room() + { + Name = roomData.Name, + IsPrivate = roomData.IsPrivate, + OperatorCount = roomData.OperatorCount, + Operators = roomData.Operators?.ToList(), + Owner = roomData.Owner, + Users = roomData.Users?.ToList(), + Messages = new List(), + }; + } + } +} diff --git a/src/slskd/Messaging/Entities/RoomMessage.cs b/src/slskd/Messaging/Entities/RoomMessage.cs new file mode 100644 index 00000000..7a06a192 --- /dev/null +++ b/src/slskd/Messaging/Entities/RoomMessage.cs @@ -0,0 +1,59 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Messaging +{ + using System; + using Soulseek; + + /// + /// A message sent to a room. + /// + public class RoomMessage + { + /// + /// The timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// The room to which the message pertains. + /// + public string RoomName { get; set; } + + public static RoomMessage FromEventArgs(RoomMessageReceivedEventArgs eventArgs, DateTime? timestamp = null) + { + return new RoomMessage() + { + Timestamp = timestamp ?? DateTime.UtcNow, + Username = eventArgs.Username, + Message = eventArgs.Message, + RoomName = eventArgs.RoomName, + }; + } + } +} diff --git a/src/slskd/Messaging/IConversationTracker.cs b/src/slskd/Messaging/IConversationTracker.cs new file mode 100644 index 00000000..8e7a90f4 --- /dev/null +++ b/src/slskd/Messaging/IConversationTracker.cs @@ -0,0 +1,55 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + + /// + /// Tracks private message conversations. + /// + public interface IConversationTracker + { + /// + /// Tracked private message conversations. + /// + ConcurrentDictionary> Conversations { get; } + + /// + /// Adds a private message conversation and appends the specified , or just appends the + /// message if the conversation exists. + /// + /// + /// + void AddOrUpdate(string username, PrivateMessage message); + + /// + /// Returns the list of private messages for the specified , if any exist. + /// + /// + /// + /// + bool TryGet(string username, out IList messages); + + /// + /// Removes a tracked private message conversation for the specified user. + /// + /// + void TryRemove(string username); + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/IRoomTracker.cs b/src/slskd/Messaging/IRoomTracker.cs new file mode 100644 index 00000000..225e5f69 --- /dev/null +++ b/src/slskd/Messaging/IRoomTracker.cs @@ -0,0 +1,75 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Messaging +{ + using System.Collections.Concurrent; + using Soulseek; + + /// + /// Tracks rooms. + /// + public interface IRoomTracker + { + /// + /// Gets tracked rooms. + /// + ConcurrentDictionary Rooms { get; } + + /// + /// Adds a room and appends the specified , or just appends the message if the room exists. + /// + /// + /// + void AddOrUpdateMessage(string roomName, RoomMessage message); + + /// + /// Adds the specified room to the tracker. + /// + /// + /// + void TryAdd(string roomName, Room room); + + /// + /// Adds the specified to the specified room. + /// + /// + /// + void TryAddUser(string roomName, UserData userData); + + /// + /// Returns the list of messages for the specified , if it is tracked. + /// + /// + /// + /// + bool TryGet(string roomName, out Room room); + + /// + /// Removes a tracked room. + /// + /// + void TryRemove(string roomName); + + /// + /// Removes the specified from the specified room. + /// + /// + /// + void TryRemoveUser(string roomName, string username); + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/RoomTracker.cs b/src/slskd/Messaging/RoomTracker.cs new file mode 100644 index 00000000..c586f401 --- /dev/null +++ b/src/slskd/Messaging/RoomTracker.cs @@ -0,0 +1,112 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using Soulseek; + + /// + /// Tracks rooms. + /// + public class RoomTracker : IRoomTracker + { + /// + /// Initializes a new instance of the class. + /// + /// + public RoomTracker(int messageLimit = 25) + { + MessageLimit = messageLimit; + } + + /// + /// Tracked rooms. + /// + public ConcurrentDictionary Rooms { get; } = new ConcurrentDictionary(); + + private int MessageLimit { get; } + + /// + /// Adds a room and appends the specified , or just appends the message if the room exists. + /// + /// + /// + public void AddOrUpdateMessage(string roomName, RoomMessage message) + { + Rooms.AddOrUpdate(roomName, new Room() { Messages = new List() { message } }, (_, room) => + { + if (room.Messages.Count >= MessageLimit) + { + room.Messages = room.Messages.TakeLast(MessageLimit - 1).ToList(); + } + + room.Messages.Add(message); + return room; + }); + } + + /// + /// Adds the specified room to the tracker. + /// + /// + /// + public void TryAdd(string roomName, Room room) => Rooms.TryAdd(roomName, room); + + /// + /// Adds the specified to the specified room. + /// + /// + /// + public void TryAddUser(string roomName, UserData userData) + { + if (Rooms.TryGetValue(roomName, out var room)) + { + room.Users.Add(userData); + } + } + + /// + /// Removes a tracked room. + /// + /// + /// + /// + public bool TryGet(string roomName, out Room room) => Rooms.TryGetValue(roomName, out room); + + /// + /// Returns the list of messages for the specified , if it is tracked. + /// + /// + public void TryRemove(string roomName) => Rooms.TryRemove(roomName, out _); + + /// + /// Removes the specified from the specified room. + /// + /// + /// + public void TryRemoveUser(string roomName, string username) + { + if (Rooms.TryGetValue(roomName, out var room)) + { + room.Users = room.Users.Where(u => u.Username != username).ToList(); + } + } + } +} \ No newline at end of file diff --git a/src/slskd/Peer/BrowseTracker.cs b/src/slskd/Peer/BrowseTracker.cs new file mode 100644 index 00000000..5fa6b14a --- /dev/null +++ b/src/slskd/Peer/BrowseTracker.cs @@ -0,0 +1,57 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Peer +{ + using System.Collections.Concurrent; + using Soulseek; + + /// + /// Tracks browse operations. + /// + public class BrowseTracker : IBrowseTracker + { + /// + /// Tracked browse operations. + /// + public ConcurrentDictionary Browses { get; } = new ConcurrentDictionary(); + + /// + /// Adds or updates a tracked browse operation. + /// + /// + /// + public void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress) + => Browses.AddOrUpdate(username, progress, (user, oldprogress) => progress); + + /// + /// Removes a tracked browse operation for the specified user. + /// + /// + public void TryRemove(string username) + => Browses.TryRemove(username, out _); + + /// + /// Gets the browse progress for the specified user. + /// + /// + /// + /// + public bool TryGet(string username, out BrowseProgressUpdatedEventArgs progress) + => Browses.TryGetValue(username, out progress); + } +} diff --git a/src/slskd/Peer/IBrowseTracker.cs b/src/slskd/Peer/IBrowseTracker.cs new file mode 100644 index 00000000..606b8a45 --- /dev/null +++ b/src/slskd/Peer/IBrowseTracker.cs @@ -0,0 +1,54 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Peer +{ + using System.Collections.Concurrent; + using Soulseek; + + /// + /// Tracks browse operations. + /// + public interface IBrowseTracker + { + /// + /// Tracked browse operations. + /// + ConcurrentDictionary Browses { get; } + + /// + /// Adds or updates a tracked browse operation. + /// + /// + /// + void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress); + + /// + /// Gets the browse progress for the specified user. + /// + /// + /// + /// + bool TryGet(string username, out BrowseProgressUpdatedEventArgs progress); + + /// + /// Removes a tracked browse operation for the specified user. + /// + /// + void TryRemove(string username); + } +} \ No newline at end of file diff --git a/src/slskd/Search/ISearchTracker.cs b/src/slskd/Search/ISearchTracker.cs new file mode 100644 index 00000000..c2bdcbaa --- /dev/null +++ b/src/slskd/Search/ISearchTracker.cs @@ -0,0 +1,52 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search +{ + using System; + using System.Collections.Concurrent; + using Soulseek; + + /// + /// Tracks active searches. + /// + public interface ISearchTracker + { + /// + /// Gets active searches. + /// + ConcurrentDictionary Searches { get; } + + /// + /// Adds or updates a tracked search. + /// + /// + /// + void AddOrUpdate(Guid id, SearchEventArgs args); + + /// + /// Removes all tracked searches. + /// + void Clear(); + + /// + /// Removes a tracked search. + /// + /// + void TryRemove(Guid id); + } +} \ No newline at end of file diff --git a/src/slskd/Search/SearchResponseCache.cs b/src/slskd/Search/SearchResponseCache.cs new file mode 100644 index 00000000..6b223280 --- /dev/null +++ b/src/slskd/Search/SearchResponseCache.cs @@ -0,0 +1,77 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search +{ + using System; + using Microsoft.Extensions.Caching.Memory; + using Soulseek; + + /// + /// Caches undelivered search responses. + /// + public class SearchResponseCache : ISearchResponseCache + { + /// + /// Initializes a new instance of the class. + /// + public SearchResponseCache() + { + Cache = new MemoryCache(new MemoryCacheOptions()); + } + + private IMemoryCache Cache { get; } + + /// + /// Caches or updates a response. + /// + /// The token for which the response is to be added or updated. + /// The response and context to cache. + public void AddOrUpdate(int responseToken, (string Username, int Token, string Query, SearchResponse SearchResponse) response) + { + Cache.Set(responseToken, response, TimeSpan.FromMinutes(3)); + } + + /// + /// Attempts to fetch a cached response and context for the specified . + /// + /// The token for the cached response. + /// The cached response and context, if present. + /// A value indicating whether a response for the specified responseToken is cached. + public bool TryGet(int responseToken, out (string Username, int Token, string Query, SearchResponse SearchResponse) response) + { + return Cache.TryGetValue(responseToken, out response); + } + + /// + /// Attempts to remove a cached Soulseek.SearchResponse and context for the specified . + /// + /// The token for the cached response. + /// The cached response and context, if present. + /// A value indicating whether a response for the specified responseToken was removed. + public bool TryRemove(int responseToken, out (string Username, int Token, string Query, SearchResponse SearchResponse) response) + { + if (Cache.TryGetValue(responseToken, out response)) + { + Cache.Remove(responseToken); + return true; + } + + return false; + } + } +} \ No newline at end of file diff --git a/src/slskd/Search/SearchTracker.cs b/src/slskd/Search/SearchTracker.cs new file mode 100644 index 00000000..c4f124ca --- /dev/null +++ b/src/slskd/Search/SearchTracker.cs @@ -0,0 +1,62 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search +{ + using System; + using System.Collections.Concurrent; + using Soulseek; + + /// + /// Tracks active searches. + /// + public class SearchTracker : ISearchTracker + { + /// + /// Gets active searches. + /// + public ConcurrentDictionary Searches { get; private set; } = + new ConcurrentDictionary(); + + /// + /// Adds or updates a tracked search. + /// + /// + /// + public void AddOrUpdate(Guid id, SearchEventArgs args) + { + Searches.AddOrUpdate(id, args.Search, (token, search) => args.Search); + } + + /// + /// Removes all tracked searches. + /// + public void Clear() + { + Searches.Clear(); + } + + /// + /// Removes a tracked search. + /// + /// + public void TryRemove(Guid id) + { + Searches.TryRemove(id, out _); + } + } +} \ No newline at end of file diff --git a/src/slskd/Service.cs b/src/slskd/Service.cs index 4ac684ad..f46e6739 100644 --- a/src/slskd/Service.cs +++ b/src/slskd/Service.cs @@ -28,8 +28,11 @@ namespace slskd using Microsoft.Extensions.Options; using Serilog; using Serilog.Events; - using slskd.Entities; - using slskd.Trackers; + using slskd.Local; + using slskd.Messaging; + using slskd.Peer; + using slskd.Search; + using slskd.Transfer; using Soulseek; using Soulseek.Diagnostics; diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index c63699cf..f073117c 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -33,8 +33,12 @@ namespace slskd using Prometheus.SystemMetrics; using Serilog; using slskd.API.Authentication; + using slskd.Local; + using slskd.Messaging; + using slskd.Peer; + using slskd.Search; using slskd.Security; - using slskd.Trackers; + using slskd.Transfer; /// /// ASP.NET Startup. diff --git a/src/slskd/Trackers/BrowseTracker.cs b/src/slskd/Trackers/BrowseTracker.cs deleted file mode 100644 index 9eeb7561..00000000 --- a/src/slskd/Trackers/BrowseTracker.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Trackers -{ - using System.Collections.Concurrent; - using Soulseek; - - /// - /// Tracks browse operations. - /// - public class BrowseTracker : IBrowseTracker - { - /// - /// Tracked browse operations. - /// - public ConcurrentDictionary Browses { get; } = new ConcurrentDictionary(); - - /// - /// Adds or updates a tracked browse operation. - /// - /// - /// - public void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress) - => Browses.AddOrUpdate(username, progress, (user, oldprogress) => progress); - - /// - /// Removes a tracked browse operation for the specified user. - /// - /// - public void TryRemove(string username) - => Browses.TryRemove(username, out _); - - /// - /// Gets the browse progress for the specified user. - /// - /// - /// - /// - public bool TryGet(string username, out BrowseProgressUpdatedEventArgs progress) - => Browses.TryGetValue(username, out progress); - } -} diff --git a/src/slskd/Trackers/ConversationTracker.cs b/src/slskd/Trackers/ConversationTracker.cs deleted file mode 100644 index b39ba0e6..00000000 --- a/src/slskd/Trackers/ConversationTracker.cs +++ /dev/null @@ -1,63 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Trackers -{ - using System.Collections.Concurrent; - using System.Collections.Generic; - using slskd.Entities; - - /// - /// Tracks private message conversations. - /// - public class ConversationTracker : IConversationTracker - { - /// - /// Tracked private message conversations. - /// - public ConcurrentDictionary> Conversations { get; } = new ConcurrentDictionary>(); - - /// - /// Adds a private message conversation and appends the specified , or just appends the - /// message if the conversation exists. - /// - /// - /// - public void AddOrUpdate(string username, PrivateMessage message) - { - Conversations.AddOrUpdate(username, new List() { message }, (_, messageList) => - { - messageList.Add(message); - return messageList; - }); - } - - /// - /// Returns the list of private messages for the specified , if any exist. - /// - /// - /// - /// - public bool TryGet(string username, out IList messages) => Conversations.TryGetValue(username, out messages); - - /// - /// Removes a tracked private message conversation for the specified user. - /// - /// - public void TryRemove(string username) => Conversations.TryRemove(username, out _); - } -} \ No newline at end of file diff --git a/src/slskd/Trackers/IBrowseTracker.cs b/src/slskd/Trackers/IBrowseTracker.cs deleted file mode 100644 index f7607e2b..00000000 --- a/src/slskd/Trackers/IBrowseTracker.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Trackers -{ - using System.Collections.Concurrent; - using Soulseek; - - /// - /// Tracks browse operations. - /// - public interface IBrowseTracker - { - /// - /// Tracked browse operations. - /// - ConcurrentDictionary Browses { get; } - - /// - /// Adds or updates a tracked browse operation. - /// - /// - /// - void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress); - - /// - /// Gets the browse progress for the specified user. - /// - /// - /// - /// - bool TryGet(string username, out BrowseProgressUpdatedEventArgs progress); - - /// - /// Removes a tracked browse operation for the specified user. - /// - /// - void TryRemove(string username); - } -} \ No newline at end of file diff --git a/src/slskd/Trackers/IConversationTracker.cs b/src/slskd/Trackers/IConversationTracker.cs deleted file mode 100644 index 3da20b9e..00000000 --- a/src/slskd/Trackers/IConversationTracker.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Trackers -{ - using System.Collections.Concurrent; - using System.Collections.Generic; - using slskd.Entities; - - /// - /// Tracks private message conversations. - /// - public interface IConversationTracker - { - /// - /// Tracked private message conversations. - /// - ConcurrentDictionary> Conversations { get; } - - /// - /// Adds a private message conversation and appends the specified , or just appends the - /// message if the conversation exists. - /// - /// - /// - void AddOrUpdate(string username, PrivateMessage message); - - /// - /// Returns the list of private messages for the specified , if any exist. - /// - /// - /// - /// - bool TryGet(string username, out IList messages); - - /// - /// Removes a tracked private message conversation for the specified user. - /// - /// - void TryRemove(string username); - } -} \ No newline at end of file diff --git a/src/slskd/Trackers/IRoomTracker.cs b/src/slskd/Trackers/IRoomTracker.cs deleted file mode 100644 index bbeb8255..00000000 --- a/src/slskd/Trackers/IRoomTracker.cs +++ /dev/null @@ -1,76 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Trackers -{ - using System.Collections.Concurrent; - using slskd.Entities; - using Soulseek; - - /// - /// Tracks rooms. - /// - public interface IRoomTracker - { - /// - /// Gets tracked rooms. - /// - ConcurrentDictionary Rooms { get; } - - /// - /// Adds a room and appends the specified , or just appends the message if the room exists. - /// - /// - /// - void AddOrUpdateMessage(string roomName, RoomMessage message); - - /// - /// Adds the specified room to the tracker. - /// - /// - /// - void TryAdd(string roomName, Room room); - - /// - /// Adds the specified to the specified room. - /// - /// - /// - void TryAddUser(string roomName, UserData userData); - - /// - /// Returns the list of messages for the specified , if it is tracked. - /// - /// - /// - /// - bool TryGet(string roomName, out Room room); - - /// - /// Removes a tracked room. - /// - /// - void TryRemove(string roomName); - - /// - /// Removes the specified from the specified room. - /// - /// - /// - void TryRemoveUser(string roomName, string username); - } -} \ No newline at end of file diff --git a/src/slskd/Trackers/ISearchTracker.cs b/src/slskd/Trackers/ISearchTracker.cs deleted file mode 100644 index 648b6179..00000000 --- a/src/slskd/Trackers/ISearchTracker.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Trackers -{ - using System; - using System.Collections.Concurrent; - using Soulseek; - - /// - /// Tracks active searches. - /// - public interface ISearchTracker - { - /// - /// Gets active searches. - /// - ConcurrentDictionary Searches { get; } - - /// - /// Adds or updates a tracked search. - /// - /// - /// - void AddOrUpdate(Guid id, SearchEventArgs args); - - /// - /// Removes all tracked searches. - /// - void Clear(); - - /// - /// Removes a tracked search. - /// - /// - void TryRemove(Guid id); - } -} \ No newline at end of file diff --git a/src/slskd/Trackers/ITransferTracker.cs b/src/slskd/Trackers/ITransferTracker.cs deleted file mode 100644 index b16311f8..00000000 --- a/src/slskd/Trackers/ITransferTracker.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Trackers -{ - using System.Collections.Concurrent; - using System.Threading; - using Soulseek; - - /// - /// Tracks transfers. - /// - public interface ITransferTracker - { - /// - /// Tracked transfers. - /// - ConcurrentDictionary>> Transfers { get; } - - /// - /// Adds or updates a tracked transfer. - /// - /// - /// - void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource); - - /// - /// Removes a tracked transfer. - /// - /// Omitting an id will remove ALL transfers associated with the specified username. - void TryRemove(TransferDirection direction, string username, string id = null); - - /// - /// Gets the specified transfer. - /// - /// - /// - /// - /// - /// - bool TryGet(TransferDirection direction, string username, string id, out (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer); - } -} \ No newline at end of file diff --git a/src/slskd/Trackers/RoomTracker.cs b/src/slskd/Trackers/RoomTracker.cs deleted file mode 100644 index d20f2444..00000000 --- a/src/slskd/Trackers/RoomTracker.cs +++ /dev/null @@ -1,113 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Trackers -{ - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using slskd.Entities; - using Soulseek; - - /// - /// Tracks rooms. - /// - public class RoomTracker : IRoomTracker - { - /// - /// Initializes a new instance of the class. - /// - /// - public RoomTracker(int messageLimit = 25) - { - MessageLimit = messageLimit; - } - - /// - /// Tracked rooms. - /// - public ConcurrentDictionary Rooms { get; } = new ConcurrentDictionary(); - - private int MessageLimit { get; } - - /// - /// Adds a room and appends the specified , or just appends the message if the room exists. - /// - /// - /// - public void AddOrUpdateMessage(string roomName, RoomMessage message) - { - Rooms.AddOrUpdate(roomName, new Room() { Messages = new List() { message } }, (_, room) => - { - if (room.Messages.Count >= MessageLimit) - { - room.Messages = room.Messages.TakeLast(MessageLimit - 1).ToList(); - } - - room.Messages.Add(message); - return room; - }); - } - - /// - /// Adds the specified room to the tracker. - /// - /// - /// - public void TryAdd(string roomName, Room room) => Rooms.TryAdd(roomName, room); - - /// - /// Adds the specified to the specified room. - /// - /// - /// - public void TryAddUser(string roomName, UserData userData) - { - if (Rooms.TryGetValue(roomName, out var room)) - { - room.Users.Add(userData); - } - } - - /// - /// Removes a tracked room. - /// - /// - /// - /// - public bool TryGet(string roomName, out Room room) => Rooms.TryGetValue(roomName, out room); - - /// - /// Returns the list of messages for the specified , if it is tracked. - /// - /// - public void TryRemove(string roomName) => Rooms.TryRemove(roomName, out _); - - /// - /// Removes the specified from the specified room. - /// - /// - /// - public void TryRemoveUser(string roomName, string username) - { - if (Rooms.TryGetValue(roomName, out var room)) - { - room.Users = room.Users.Where(u => u.Username != username).ToList(); - } - } - } -} \ No newline at end of file diff --git a/src/slskd/Trackers/SearchTracker.cs b/src/slskd/Trackers/SearchTracker.cs deleted file mode 100644 index 35c34ae6..00000000 --- a/src/slskd/Trackers/SearchTracker.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Trackers -{ - using System; - using System.Collections.Concurrent; - using Soulseek; - - /// - /// Tracks active searches. - /// - public class SearchTracker : ISearchTracker - { - /// - /// Gets active searches. - /// - public ConcurrentDictionary Searches { get; private set; } = - new ConcurrentDictionary(); - - /// - /// Adds or updates a tracked search. - /// - /// - /// - public void AddOrUpdate(Guid id, SearchEventArgs args) - { - Searches.AddOrUpdate(id, args.Search, (token, search) => args.Search); - } - - /// - /// Removes all tracked searches. - /// - public void Clear() - { - Searches.Clear(); - } - - /// - /// Removes a tracked search. - /// - /// - public void TryRemove(Guid id) - { - Searches.TryRemove(id, out _); - } - } -} \ No newline at end of file diff --git a/src/slskd/Trackers/TransferTracker.cs b/src/slskd/Trackers/TransferTracker.cs deleted file mode 100644 index e89cb594..00000000 --- a/src/slskd/Trackers/TransferTracker.cs +++ /dev/null @@ -1,192 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Trackers -{ - using System.Collections.Concurrent; - using System.Linq; - using System.Threading; - using Soulseek; - - /// - /// Transfer extensions. - /// - public static class TransferTrackerExtensions - { - /// - /// Filters a Transfer collection by user. - /// - /// - /// - /// - public static ConcurrentDictionary FromUser( - this ConcurrentDictionary> directedTransfers, - string username) - { - directedTransfers.TryGetValue(username, out var transfers); - return transfers ?? new ConcurrentDictionary(); - } - - /// - /// Maps a Transfer collection to a serializable object. - /// - /// - /// - public static object ToMap( - this ConcurrentDictionary> directedTransfers) - { - return directedTransfers.Select(u => new - { - Username = u.Key, - Directories = u.Value.Values - .GroupBy(f => f.Transfer.Filename.DirectoryName()) - .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }), - }); - } - - /// - /// Maps a Transfer collection to a serializable object. - /// - /// - /// - public static object ToMap( - this ConcurrentDictionary userTransfers) - { - return userTransfers.Values - .GroupBy(f => f.Transfer.Filename.DirectoryName()) - .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }); - } - - /// - /// Filters a Transfer collection by direction. - /// - /// - /// - /// - public static ConcurrentDictionary> WithDirection( - this ConcurrentDictionary>> allTransfers, - TransferDirection direction) - { - allTransfers.TryGetValue(direction, out var transfers); - return transfers ?? new ConcurrentDictionary>(); - } - - /// - /// Retrieves a Transfer from a Transfer collection by id. - /// - /// - /// - /// - public static (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId( - this ConcurrentDictionary userTransfers, - string id) - { - userTransfers.TryGetValue(id, out var transfer); - return transfer; - } - } - - /// - /// Tracks transfers. - /// - public class TransferTracker : ITransferTracker - { - /// - /// Initializes a new instance of the class. - /// - public TransferTracker() - { - Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary>()); - Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary>()); - } - - /// - /// Gets tracked transfers. - /// - public ConcurrentDictionary>> Transfers { get; private set; } = - new ConcurrentDictionary>>(); - - /// - /// Adds or updates a tracked transfer. - /// - /// - /// - public void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) - { - Transfers.TryGetValue(args.Transfer.Direction, out var direction); - - direction.AddOrUpdate(args.Transfer.Username, GetNewDictionaryForUser(args, cancellationTokenSource), (user, dict) => - { - var transfer = API.DTO.Transfer.FromSoulseekTransfer(args.Transfer); - dict.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, cancellationTokenSource)); - return dict; - }); - } - - /// - /// Gets the specified transfer. - /// - /// - /// - /// - /// - /// - public bool TryGet(TransferDirection direction, string username, string id, out (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer) - { - transfer = default; - - if (Transfers.TryGetValue(direction, out var transfers) && transfers.TryGetValue(username, out var user) && user.TryGetValue(id, out transfer)) - { - return true; - } - - return false; - } - - /// - /// Removes a tracked transfer. - /// - /// Omitting an id will remove ALL transfers associated with the specified username. - public void TryRemove(TransferDirection direction, string username, string id = null) - { - Transfers.TryGetValue(direction, out var directionDict); - - if (string.IsNullOrEmpty(id)) - { - directionDict.TryRemove(username, out _); - } - else - { - directionDict.TryGetValue(username, out var userDict); - userDict.TryRemove(id, out _); - - if (userDict.IsEmpty) - { - directionDict.TryRemove(username, out _); - } - } - } - - private ConcurrentDictionary GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) - { - var r = new ConcurrentDictionary(); - var transfer = API.DTO.Transfer.FromSoulseekTransfer(args.Transfer); - r.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, record.CancellationTokenSource)); - return r; - } - } -} \ No newline at end of file diff --git a/src/slskd/Transfer/ITransferTracker.cs b/src/slskd/Transfer/ITransferTracker.cs new file mode 100644 index 00000000..ebd20b90 --- /dev/null +++ b/src/slskd/Transfer/ITransferTracker.cs @@ -0,0 +1,57 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Transfer +{ + using System.Collections.Concurrent; + using System.Threading; + using Soulseek; + + /// + /// Tracks transfers. + /// + public interface ITransferTracker + { + /// + /// Tracked transfers. + /// + ConcurrentDictionary>> Transfers { get; } + + /// + /// Adds or updates a tracked transfer. + /// + /// + /// + void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource); + + /// + /// Removes a tracked transfer. + /// + /// Omitting an id will remove ALL transfers associated with the specified username. + void TryRemove(TransferDirection direction, string username, string id = null); + + /// + /// Gets the specified transfer. + /// + /// + /// + /// + /// + /// + bool TryGet(TransferDirection direction, string username, string id, out (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer); + } +} \ No newline at end of file diff --git a/src/slskd/Transfer/TransferTracker.cs b/src/slskd/Transfer/TransferTracker.cs new file mode 100644 index 00000000..372a360e --- /dev/null +++ b/src/slskd/Transfer/TransferTracker.cs @@ -0,0 +1,192 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Transfer +{ + using System.Collections.Concurrent; + using System.Linq; + using System.Threading; + using Soulseek; + + /// + /// Transfer extensions. + /// + public static class TransferTrackerExtensions + { + /// + /// Filters a Transfer collection by user. + /// + /// + /// + /// + public static ConcurrentDictionary FromUser( + this ConcurrentDictionary> directedTransfers, + string username) + { + directedTransfers.TryGetValue(username, out var transfers); + return transfers ?? new ConcurrentDictionary(); + } + + /// + /// Maps a Transfer collection to a serializable object. + /// + /// + /// + public static object ToMap( + this ConcurrentDictionary> directedTransfers) + { + return directedTransfers.Select(u => new + { + Username = u.Key, + Directories = u.Value.Values + .GroupBy(f => f.Transfer.Filename.DirectoryName()) + .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }), + }); + } + + /// + /// Maps a Transfer collection to a serializable object. + /// + /// + /// + public static object ToMap( + this ConcurrentDictionary userTransfers) + { + return userTransfers.Values + .GroupBy(f => f.Transfer.Filename.DirectoryName()) + .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }); + } + + /// + /// Filters a Transfer collection by direction. + /// + /// + /// + /// + public static ConcurrentDictionary> WithDirection( + this ConcurrentDictionary>> allTransfers, + TransferDirection direction) + { + allTransfers.TryGetValue(direction, out var transfers); + return transfers ?? new ConcurrentDictionary>(); + } + + /// + /// Retrieves a Transfer from a Transfer collection by id. + /// + /// + /// + /// + public static (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId( + this ConcurrentDictionary userTransfers, + string id) + { + userTransfers.TryGetValue(id, out var transfer); + return transfer; + } + } + + /// + /// Tracks transfers. + /// + public class TransferTracker : ITransferTracker + { + /// + /// Initializes a new instance of the class. + /// + public TransferTracker() + { + Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary>()); + Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary>()); + } + + /// + /// Gets tracked transfers. + /// + public ConcurrentDictionary>> Transfers { get; private set; } = + new ConcurrentDictionary>>(); + + /// + /// Adds or updates a tracked transfer. + /// + /// + /// + public void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) + { + Transfers.TryGetValue(args.Transfer.Direction, out var direction); + + direction.AddOrUpdate(args.Transfer.Username, GetNewDictionaryForUser(args, cancellationTokenSource), (user, dict) => + { + var transfer = API.DTO.Transfer.FromSoulseekTransfer(args.Transfer); + dict.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, cancellationTokenSource)); + return dict; + }); + } + + /// + /// Gets the specified transfer. + /// + /// + /// + /// + /// + /// + public bool TryGet(TransferDirection direction, string username, string id, out (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer) + { + transfer = default; + + if (Transfers.TryGetValue(direction, out var transfers) && transfers.TryGetValue(username, out var user) && user.TryGetValue(id, out transfer)) + { + return true; + } + + return false; + } + + /// + /// Removes a tracked transfer. + /// + /// Omitting an id will remove ALL transfers associated with the specified username. + public void TryRemove(TransferDirection direction, string username, string id = null) + { + Transfers.TryGetValue(direction, out var directionDict); + + if (string.IsNullOrEmpty(id)) + { + directionDict.TryRemove(username, out _); + } + else + { + directionDict.TryGetValue(username, out var userDict); + userDict.TryRemove(id, out _); + + if (userDict.IsEmpty) + { + directionDict.TryRemove(username, out _); + } + } + } + + private ConcurrentDictionary GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) + { + var r = new ConcurrentDictionary(); + var transfer = API.DTO.Transfer.FromSoulseekTransfer(args.Transfer); + r.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, record.CancellationTokenSource)); + return r; + } + } +} \ No newline at end of file -- cgit v1.2.3