From 8f7b1c17d0dd0832cd38c782a4c9804ac0838145 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 May 2021 11:31:10 -0500 Subject: move app stuff into Core --- src/slskd/Core/ISharedFileCache.cs | 36 ++ src/slskd/Core/Messaging/ConversationTracker.cs | 62 ++++ src/slskd/Core/Messaging/Domain/PrivateMessage.cs | 71 ++++ src/slskd/Core/Messaging/Domain/Room.cs | 75 ++++ src/slskd/Core/Messaging/Domain/RoomMessage.cs | 59 +++ src/slskd/Core/Messaging/IConversationTracker.cs | 55 +++ src/slskd/Core/Messaging/IRoomTracker.cs | 75 ++++ src/slskd/Core/Messaging/RoomTracker.cs | 112 ++++++ src/slskd/Core/Peer/BrowseTracker.cs | 57 +++ src/slskd/Core/Peer/IBrowseTracker.cs | 54 +++ src/slskd/Core/Search/ISearchTracker.cs | 52 +++ src/slskd/Core/Search/SearchResponseCache.cs | 77 ++++ src/slskd/Core/Search/SearchTracker.cs | 62 ++++ src/slskd/Core/Security/Role.cs | 26 ++ src/slskd/Core/Service.cs | 429 ++++++++++++++++++++++ src/slskd/Core/SharedFileCache.cs | 165 +++++++++ src/slskd/Core/Transfer/ITransferTracker.cs | 57 +++ src/slskd/Core/Transfer/TransferTracker.cs | 192 ++++++++++ 18 files changed, 1716 insertions(+) create mode 100644 src/slskd/Core/ISharedFileCache.cs create mode 100644 src/slskd/Core/Messaging/ConversationTracker.cs create mode 100644 src/slskd/Core/Messaging/Domain/PrivateMessage.cs create mode 100644 src/slskd/Core/Messaging/Domain/Room.cs create mode 100644 src/slskd/Core/Messaging/Domain/RoomMessage.cs create mode 100644 src/slskd/Core/Messaging/IConversationTracker.cs create mode 100644 src/slskd/Core/Messaging/IRoomTracker.cs create mode 100644 src/slskd/Core/Messaging/RoomTracker.cs create mode 100644 src/slskd/Core/Peer/BrowseTracker.cs create mode 100644 src/slskd/Core/Peer/IBrowseTracker.cs create mode 100644 src/slskd/Core/Search/ISearchTracker.cs create mode 100644 src/slskd/Core/Search/SearchResponseCache.cs create mode 100644 src/slskd/Core/Search/SearchTracker.cs create mode 100644 src/slskd/Core/Security/Role.cs create mode 100644 src/slskd/Core/Service.cs create mode 100644 src/slskd/Core/SharedFileCache.cs create mode 100644 src/slskd/Core/Transfer/ITransferTracker.cs create mode 100644 src/slskd/Core/Transfer/TransferTracker.cs (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/ISharedFileCache.cs b/src/slskd/Core/ISharedFileCache.cs new file mode 100644 index 00000000..960b906d --- /dev/null +++ b/src/slskd/Core/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/Core/Messaging/ConversationTracker.cs b/src/slskd/Core/Messaging/ConversationTracker.cs new file mode 100644 index 00000000..27d678ca --- /dev/null +++ b/src/slskd/Core/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/Core/Messaging/Domain/PrivateMessage.cs b/src/slskd/Core/Messaging/Domain/PrivateMessage.cs new file mode 100644 index 00000000..236632aa --- /dev/null +++ b/src/slskd/Core/Messaging/Domain/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/Core/Messaging/Domain/Room.cs b/src/slskd/Core/Messaging/Domain/Room.cs new file mode 100644 index 00000000..459dea2c --- /dev/null +++ b/src/slskd/Core/Messaging/Domain/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/Core/Messaging/Domain/RoomMessage.cs b/src/slskd/Core/Messaging/Domain/RoomMessage.cs new file mode 100644 index 00000000..7a06a192 --- /dev/null +++ b/src/slskd/Core/Messaging/Domain/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/Core/Messaging/IConversationTracker.cs b/src/slskd/Core/Messaging/IConversationTracker.cs new file mode 100644 index 00000000..8e7a90f4 --- /dev/null +++ b/src/slskd/Core/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/Core/Messaging/IRoomTracker.cs b/src/slskd/Core/Messaging/IRoomTracker.cs new file mode 100644 index 00000000..225e5f69 --- /dev/null +++ b/src/slskd/Core/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/Core/Messaging/RoomTracker.cs b/src/slskd/Core/Messaging/RoomTracker.cs new file mode 100644 index 00000000..c586f401 --- /dev/null +++ b/src/slskd/Core/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/Core/Peer/BrowseTracker.cs b/src/slskd/Core/Peer/BrowseTracker.cs new file mode 100644 index 00000000..5fa6b14a --- /dev/null +++ b/src/slskd/Core/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/Core/Peer/IBrowseTracker.cs b/src/slskd/Core/Peer/IBrowseTracker.cs new file mode 100644 index 00000000..606b8a45 --- /dev/null +++ b/src/slskd/Core/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/Core/Search/ISearchTracker.cs b/src/slskd/Core/Search/ISearchTracker.cs new file mode 100644 index 00000000..c2bdcbaa --- /dev/null +++ b/src/slskd/Core/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/Core/Search/SearchResponseCache.cs b/src/slskd/Core/Search/SearchResponseCache.cs new file mode 100644 index 00000000..6b223280 --- /dev/null +++ b/src/slskd/Core/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/Core/Search/SearchTracker.cs b/src/slskd/Core/Search/SearchTracker.cs new file mode 100644 index 00000000..c4f124ca --- /dev/null +++ b/src/slskd/Core/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/Core/Security/Role.cs b/src/slskd/Core/Security/Role.cs new file mode 100644 index 00000000..9c55a572 --- /dev/null +++ b/src/slskd/Core/Security/Role.cs @@ -0,0 +1,26 @@ +// +// 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 +{ + public enum Role + { + ReadOnly = 0, + User = 1, + Administrator = 2, + } +} diff --git a/src/slskd/Core/Service.cs b/src/slskd/Core/Service.cs new file mode 100644 index 00000000..f46e6739 --- /dev/null +++ b/src/slskd/Core/Service.cs @@ -0,0 +1,429 @@ +// +// 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.Concurrent; + using System.IO; + using System.Linq; + using System.Net; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Options; + using Serilog; + using Serilog.Events; + using slskd.Local; + using slskd.Messaging; + using slskd.Peer; + using slskd.Search; + using slskd.Transfer; + using Soulseek; + using Soulseek.Diagnostics; + + public class Service : IHostedService + { + private static readonly int MaxReconnectAttempts = 3; + private static int currentReconnectAttempts = 0; + private static (int Directories, int Files) sharedCounts = (0, 0); + + public Service( + IOptions options, + ITransferTracker transferTracker, + IBrowseTracker browseTracker, + IConversationTracker conversationTracker, + IRoomTracker roomTracker, + ISharedFileCache sharedFileCache) + { + Options = options.Value; + TransferTracker = transferTracker; + BrowseTracker = browseTracker; + ConversationTracker = conversationTracker; + RoomTracker = roomTracker; + SharedFileCache = sharedFileCache; + + ProxyOptions proxyOptions = default; + + if (UsingProxy) + { + proxyOptions = new ProxyOptions( + address: Options.Soulseek.Connection.Proxy.Address, + port: Options.Soulseek.Connection.Proxy.Port.Value, + username: Options.Soulseek.Connection.Proxy.Username, + password: Options.Soulseek.Connection.Proxy.Password); + } + + var connectionOptions = new ConnectionOptions( + readBufferSize: Options.Soulseek.Connection.Buffer.Read, + writeBufferSize: Options.Soulseek.Connection.Buffer.Write, + connectTimeout: Options.Soulseek.Connection.Timeout.Connect, + inactivityTimeout: Options.Soulseek.Connection.Timeout.Inactivity, + proxyOptions: proxyOptions); + + var clientOptions = new SoulseekClientOptions( + listenPort: Options.Soulseek.ListenPort, + enableListener: true, + userEndPointCache: new UserEndPointCache(), + distributedChildLimit: Options.Soulseek.DistributedNetwork.ChildLimit, + enableDistributedNetwork: !Options.Soulseek.DistributedNetwork.Disabled, + minimumDiagnosticLevel: Options.Soulseek.DiagnosticLevel, + autoAcknowledgePrivateMessages: false, + acceptPrivateRoomInvitations: true, + serverConnectionOptions: connectionOptions, + peerConnectionOptions: connectionOptions, + transferConnectionOptions: connectionOptions, + distributedConnectionOptions: connectionOptions, + userInfoResponseResolver: UserInfoResponseResolver, + browseResponseResolver: BrowseResponseResolver, + directoryContentsResponseResolver: DirectoryContentsResponseResolver, + enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker), + searchResponseCache: new SearchResponseCache(), + searchResponseResolver: SearchResponseResolver); + + if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) + { + throw new ArgumentException("Soulseek credentials are not configured"); + } + + Client = new SoulseekClient(options: clientOptions); + + Client.DiagnosticGenerated += Client_DiagnosticGenerated; + + Client.TransferStateChanged += Client_TransferStateChanged; + Client.TransferProgressUpdated += Client_TransferProgressUpdated; + + Client.BrowseProgressUpdated += Client_BrowseProgressUpdated; + Client.UserStatusChanged += Client_UserStatusChanged; + Client.PrivateMessageReceived += Client_PrivateMessageRecieved; + + Client.PrivateRoomMembershipAdded += (e, room) => Console.WriteLine($"Added to private room {room}"); + Client.PrivateRoomMembershipRemoved += (e, room) => Console.WriteLine($"Removed from private room {room}"); + Client.PrivateRoomModerationAdded += (e, room) => Console.WriteLine($"Promoted to moderator in private room {room}"); + Client.PrivateRoomModerationRemoved += (e, room) => Console.WriteLine($"Demoted from moderator in private room {room}"); + + Client.PublicChatMessageReceived += Client_PublicChatMessageReceived; + Client.RoomMessageReceived += Client_RoomMessageReceived; + Client.RoomJoined += Client_RoomJoined; + Client.RoomLeft += Client_RoomLeft; + Client.Disconnected += Client_Disconnected; + + SoulseekClient = Client; + + SharedFileCache.Refreshed += SharedFileCache_Refreshed; + } + + public static ISoulseekClient SoulseekClient { get; private set; } + private IBrowseTracker BrowseTracker { get; set; } + private ISoulseekClient Client { get; set; } + private IConversationTracker ConversationTracker { get; set; } + private ILogger Logger { get; set; } = Log.ForContext(); + private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); + private Options Options { get; set; } + private IRoomTracker RoomTracker { get; set; } + private ISharedFileCache SharedFileCache { get; set; } + private ITransferTracker TransferTracker { get; set; } + private bool UsingProxy => !string.IsNullOrWhiteSpace(Options.Soulseek.Connection.Proxy.Address) && Options.Soulseek.Connection.Proxy.Port.HasValue; + + public async Task StartAsync(CancellationToken cancellationToken) + { + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password).ConfigureAwait(false); + + if (UsingProxy) + { + Logger.Information($"Using Proxy {Options.Soulseek.Connection.Proxy.Address}:{Options.Soulseek.Connection.Proxy.Port}"); + } + + Logger.Information("Connected and logged in as {Username}", Options.Soulseek.Username); + Logger.Information("Listening on port {Port}", Options.Soulseek.ListenPort); + Logger.Information("Client started"); + } + + public Task StopAsync(CancellationToken cancellationToken) + { + Client.Disconnect("Shutting down"); + Client.Dispose(); + Logger.Information("Client stopped"); + return Task.CompletedTask; + } + + private static void SharedFileCache_Refreshed(object sender, (int Directories, int Files) e) + { + if (sharedCounts != e) + { + _ = SoulseekClient.SetSharedCountsAsync(e.Directories, e.Files); + sharedCounts = e; + } + } + + /// + /// Creates and returns an instances of in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// A Task resolving an IEnumerable of Soulseek.Directory. + private Task BrowseResponseResolver(string username, IPEndPoint endpoint) + { + var directories = System.IO.Directory + .GetDirectories(Options.Directories.Shared, "*", SearchOption.AllDirectories) + .Select(dir => new Soulseek.Directory(dir.Replace("/", @"\"), System.IO.Directory.GetFiles(dir) + .Select(f => new Soulseek.File(1, Path.GetFileName(f), new FileInfo(f).Length, Path.GetExtension(f))))); + + return Task.FromResult(new BrowseResponse(directories)); + } + + private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) + { + BrowseTracker.AddOrUpdate(args.Username, args); + } + + private void Client_DiagnosticGenerated(object sender, DiagnosticEventArgs args) + { + static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch + { + DiagnosticLevel.Debug => LogEventLevel.Debug, + DiagnosticLevel.Info => LogEventLevel.Information, + DiagnosticLevel.Warning => LogEventLevel.Warning, + DiagnosticLevel.None => default, + _ => default, + }; + + var logger = Loggers.GetOrAdd(sender.GetType().FullName, Log.ForContext("SourceContext", "Soulseek").ForContext("SoulseekContext", sender.GetType().FullName)); + + logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); + } + + private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) + { + Console.WriteLine($"Disconnected from Soulseek server: {args.Message}"); + + // don't reconnect if the disconnecting Exception is either of these types. if KickedFromServerException, another + // client was most likely signed in, and retrying will cause a connect loop. if ObjectDisposedException, the client is + // shutting down. + if (!(args.Exception is KickedFromServerException || args.Exception is ObjectDisposedException)) + { + Interlocked.Increment(ref currentReconnectAttempts); + + if (currentReconnectAttempts <= MaxReconnectAttempts) + { + var wait = (int)Math.Pow(currentReconnectAttempts, 3); + Console.WriteLine($"Waiting {wait} second(s) before reconnect..."); + await Task.Delay(wait); + + Console.WriteLine($"Attepting to reconnect..."); + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + } + else + { + Console.WriteLine($"Unable to reconnect after {currentReconnectAttempts} tries."); + } + } + } + + private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) + { + ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); + } + + private void Client_PublicChatMessageReceived(object sender, PublicChatMessageReceivedEventArgs args) + { + Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); + } + + private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) + { + // this will fire when we join a room; track that through the join operation. + if (args.Username != Options.Soulseek.Username) + { + RoomTracker.TryAddUser(args.RoomName, args.UserData); + } + } + + private void Client_RoomLeft(object sender, RoomLeftEventArgs args) + { + RoomTracker.TryRemoveUser(args.RoomName, args.Username); + } + + private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args) + { + var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); + RoomTracker.AddOrUpdateMessage(args.RoomName, message); + } + + private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args) + { + // this is really verbose. Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}] + // [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}] + // {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s"); + } + + private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args) + { + var xfer = args.Transfer; + var direction = xfer.Direction.ToString().ToUpper(); + var user = xfer.Username; + var file = Path.GetFileName(xfer.Filename); + var oldState = args.PreviousState; + var state = xfer.State; + + var completed = xfer.State.HasFlag(TransferStates.Completed); + + Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({xfer.BytesTransferred}/{xfer.Size} = {xfer.PercentComplete}%) @ {xfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}"); + + if (xfer.Direction == TransferDirection.Upload && xfer.State.HasFlag(TransferStates.Completed | TransferStates.Succeeded)) + { + _ = Client.SendUploadSpeedAsync((int)args.Transfer.AverageSpeed); + } + } + + private void Client_UserStatusChanged(object sender, UserStatusChangedEventArgs args) + { + Console.WriteLine($"[USER] {args.Username}: {args.Status}"); + } + + /// + /// Creates and returns a in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// The unique token for the request, supplied by the requesting user. + /// The requested directory. + /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. + private Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) + { + var result = new Soulseek.Directory(directory.Replace("/", @"\"), System.IO.Directory.GetFiles(directory) + .Select(f => new Soulseek.File(1, Path.GetFileName(f), new FileInfo(f).Length, Path.GetExtension(f)))); + + return Task.FromResult(result); + } + + /// + /// Invoked upon a remote request to download a file. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// The filename of the requested file. + /// (for example purposes) the ITransferTracker used to track progress. + /// A Task representing the asynchronous operation. + /// + /// Thrown when the download is rejected. The Exception message will be passed to the remote user. + /// + /// + /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for + /// security reasons. + /// + private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) + { + _ = endpoint; + var localFilename = filename.ToLocalOSPath(); + var fileInfo = new FileInfo(localFilename); + + if (!fileInfo.Exists) + { + Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found."); + throw new DownloadEnqueueException($"File not found."); + } + + if (tracker.TryGet(TransferDirection.Upload, username, filename, out _)) + { + // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse + Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]"); + return Task.CompletedTask; + } + + // create a new cancellation token source so that we can cancel the upload from the UI. + var cts = new CancellationTokenSource(); + var topts = new TransferOptions(stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts), governor: (t, c) => Task.Delay(1, c)); + + // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and + // uploads would be handled separately. + Task.Run(async () => + { + using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + await Client.UploadAsync(username, filename, fileInfo.Length, stream, options: topts, cancellationToken: cts.Token); + }).ContinueWith(t => + { + Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); + }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget + + // return a completed task so that the invoking code can respond to the remote client. + return Task.CompletedTask; + } + + /// + /// Creates and returns a in response to the given . + /// + /// The username of the requesting user. + /// The search token. + /// The search query. + /// A Task resolving a SearchResponse, or null. + private Task SearchResponseResolver(string username, int token, SearchQuery query) + { + var defaultResponse = Task.FromResult(null); + + // some bots continually query for very common strings. blacklist known names here. + var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; + if (blacklist.Contains(username)) + { + return defaultResponse; + } + + // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. + if (query.Query.Length < 3) + { + return defaultResponse; + } + + var results = SharedFileCache.Search(query); + + if (results.Any()) + { + Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); + + return Task.FromResult(new SearchResponse( + SoulseekClient.Username, + token, + freeUploadSlots: 1, + uploadSpeed: 0, + queueLength: 0, + fileList: results)); + } + + // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no + // response will be sent to the requestor. + return Task.FromResult(null); + } + + /// + /// Creates and returns a object in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// A Task resolving the UserInfo instance. + private Task UserInfoResponseResolver(string username, IPEndPoint endpoint) + { + var info = new UserInfo( + description: $"Soulseek.NET Web Example! also, your username is {username}, and IP endpoint is {endpoint}", + picture: Array.Empty(), + uploadSlots: 1, + queueLength: 0, + hasFreeUploadSlot: false); + + return Task.FromResult(info); + } + } +} \ No newline at end of file diff --git a/src/slskd/Core/SharedFileCache.cs b/src/slskd/Core/SharedFileCache.cs new file mode 100644 index 00000000..fd6abaff --- /dev/null +++ b/src/slskd/Core/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/Core/Transfer/ITransferTracker.cs b/src/slskd/Core/Transfer/ITransferTracker.cs new file mode 100644 index 00000000..ebd20b90 --- /dev/null +++ b/src/slskd/Core/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/Core/Transfer/TransferTracker.cs b/src/slskd/Core/Transfer/TransferTracker.cs new file mode 100644 index 00000000..372a360e --- /dev/null +++ b/src/slskd/Core/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