diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-02-15 21:57:53 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-02-15 21:57:53 -0600 |
| commit | 0e9db9ca4f1a7b0f9025fa9ab277581a85afe0cb (patch) | |
| tree | 9696ee0e491645958f7b48c055dbaaa879b271e9 /src | |
| parent | af1bdbcdafe5d63bfef8fb5f5e85dbc3f2352118 (diff) | |
| parent | 236241ba35163a18c78bb6af60545a6c9a42a28e (diff) | |
| download | slskd-0e9db9ca4f1a7b0f9025fa9ab277581a85afe0cb.tar.gz | |
Merge pull request #42 from slskd/hosted-service
Use IHostedService for SoulseekClient
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/IPAddressConverter.cs | 36 | ||||
| -rw-r--r-- | src/slskd/Common/ISharedFileCache.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Common/UserEndPointCache.cs | 61 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Service.cs | 387 | ||||
| -rw-r--r-- | src/slskd/Startup.cs | 385 |
6 files changed, 503 insertions, 376 deletions
diff --git a/src/slskd/Common/IPAddressConverter.cs b/src/slskd/Common/IPAddressConverter.cs new file mode 100644 index 00000000..00ef5a4c --- /dev/null +++ b/src/slskd/Common/IPAddressConverter.cs @@ -0,0 +1,36 @@ +// <copyright file="IPAddressConverter.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Net; + using System.Text.Json; + using System.Text.Json.Serialization; + + /// <summary> + /// Serializes IPAddress instances. + /// </summary> + public class IPAddressConverter : JsonConverter<IPAddress> + { + public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(IPAddress); + + public override IPAddress Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => IPAddress.Parse(reader.GetString()); + + public override void Write(Utf8JsonWriter writer, IPAddress value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString()); + } +} diff --git a/src/slskd/Common/ISharedFileCache.cs b/src/slskd/Common/ISharedFileCache.cs index 53070777..e81cb5e4 100644 --- a/src/slskd/Common/ISharedFileCache.cs +++ b/src/slskd/Common/ISharedFileCache.cs @@ -21,7 +21,7 @@ namespace slskd using System.Collections.Generic; using Soulseek; - internal interface ISharedFileCache + public interface ISharedFileCache { string Directory { get; } DateTime? LastFill { get; } diff --git a/src/slskd/Common/UserEndPointCache.cs b/src/slskd/Common/UserEndPointCache.cs new file mode 100644 index 00000000..c84264de --- /dev/null +++ b/src/slskd/Common/UserEndPointCache.cs @@ -0,0 +1,61 @@ +// <copyright file="UserEndPointCache.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Net; + using Microsoft.Extensions.Caching.Memory; + using Soulseek; + + /// <summary> + /// Caches user EndPoints. + /// </summary> + public class UserEndPointCache : IUserEndPointCache + { + /// <summary> + /// Initializes a new instance of the <see cref="UserEndPointCache"/> class. + /// </summary> + public UserEndPointCache() + { + Cache = new MemoryCache(new MemoryCacheOptions()); + } + + private IMemoryCache Cache { get; } + + /// <summary> + /// Caches or updates an entry. + /// </summary> + /// <param name="username">The username for which to cache the endpoint.</param> + /// <param name="endPoint">The endpoint to cache.</param> + public void AddOrUpdate(string username, IPEndPoint endPoint) + { + Cache.Set(username, endPoint, TimeSpan.FromSeconds(60)); + } + + /// <summary> + /// Gets the cached endpoint for the specified <paramref name="username"/>, if it exists. + /// </summary> + /// <param name="username">The username for which to retrieve the endpoint.</param> + /// <param name="endPoint">The cached endpoint, if it exists.</param> + /// <returns>A value indicating whether the endpoint was found in the cache.</returns> + public bool TryGet(string username, out IPEndPoint endPoint) + { + return Cache.TryGetValue(username, out endPoint); + } + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 9b17a1dd..00d6d5b4 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -28,6 +28,7 @@ namespace slskd using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders.Physical; using Prometheus.DotNetRuntime; @@ -63,7 +64,7 @@ namespace slskd /// <summary> /// The default XML documentation filename. /// </summary> - public static readonly string DefaultXmlDocumentaitonFile = Path.Combine(AppContext.BaseDirectory, "etc", $"{AppName}.xml"); + public static readonly string DefaultXmlDocumentaitonFile = Path.Combine(AppContext.BaseDirectory, "etc", $"{AppName}.xml"); /// <summary> /// The global prefix for environment variables. @@ -209,7 +210,8 @@ namespace slskd Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) + .MinimumLevel.Override("slskd.API.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Information) .Enrich.WithProperty("Version", Version) .Enrich.WithProperty("InstanceName", Options.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) @@ -234,7 +236,7 @@ namespace slskd Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) - .MinimumLevel.Override("slskd.Security.PassthroughAuthenticationHandler", LogEventLevel.Information) + .MinimumLevel.Override("slskd.API.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Information) .Enrich.WithProperty("Version", Version) .Enrich.WithProperty("InstanceName", Options.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) diff --git a/src/slskd/Service.cs b/src/slskd/Service.cs new file mode 100644 index 00000000..adc6ae13 --- /dev/null +++ b/src/slskd/Service.cs @@ -0,0 +1,387 @@ +// <copyright file="Service.cs" company="slskd Team"> +// 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/. +// </copyright> + +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.Entities; + using slskd.Trackers; + using Soulseek; + using Soulseek.Diagnostics; + + public class Service : IHostedService + { + private static readonly int MaxReconnectAttempts = 3; + private static int currentReconnectAttempts = 0; + + public Service( + IOptions<Options> options, + ITransferTracker transferTracker, + IBrowseTracker browseTracker, + IConversationTracker conversationTracker, + IRoomTracker roomTracker, + ISharedFileCache sharedFileCache) + { + Options = options.Value; + TransferTracker = transferTracker; + BrowseTracker = browseTracker; + ConversationTracker = conversationTracker; + RoomTracker = roomTracker; + SharedFileCache = sharedFileCache; + + 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); + + 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, + userInfoResponseResolver: UserInfoResponseResolver, + browseResponseResolver: BrowseResponseResolver, + directoryContentsResponseResolver: DirectoryContentsResponseResolver, + enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker), + 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; + } + + public static ISoulseekClient SoulseekClient { get; private set; } + + private ISoulseekClient Client { get; set; } + private IBrowseTracker BrowseTracker { get; set; } + private IConversationTracker ConversationTracker { get; set; } + private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>(); + private ILogger Logger { get; set; } = Log.ForContext<Service>(); + private Options Options { get; set; } + private IRoomTracker RoomTracker { get; set; } + private ISharedFileCache SharedFileCache { get; set; } + private ITransferTracker TransferTracker { get; set; } + + public async Task StartAsync(CancellationToken cancellationToken) + { + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password).ConfigureAwait(false); + + Logger.Information("Connected and logged in as {Username}", Options.Soulseek.Username); + Logger.Information("Client started"); + } + + public Task StopAsync(CancellationToken cancellationToken) + { + Client.Disconnect("Shutting down"); + Client.Dispose(); + Logger.Information("Client stopped"); + return Task.CompletedTask; + } + + /// <summary> + /// Creates and returns an <see cref="IEnumerable{T}"/> of <see cref="Soulseek.Directory"/> in response to a remote request. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="endpoint">The IP endpoint of the requesting user.</param> + /// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns> + private Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint) + { + var directories = System.IO.Directory + .GetDirectories(Options.Directories.Shared, "*", SearchOption.AllDirectories) + .Select(dir => new Soulseek.Directory(dir, 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_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 void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args) + { + var direction = args.Transfer.Direction.ToString().ToUpper(); + var user = args.Transfer.Username; + var file = Path.GetFileName(args.Transfer.Filename); + var oldState = args.PreviousState; + var state = args.Transfer.State; + + var completed = args.Transfer.State.HasFlag(TransferStates.Completed); + + Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({args.Transfer.BytesTransferred}/{args.Transfer.Size} = {args.Transfer.PercentComplete}%) @ {args.Transfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}"); + } + + 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_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) + { + BrowseTracker.AddOrUpdate(args.Username, args); + } + + private void Client_UserStatusChanged(object sender, UserStatusChangedEventArgs args) + { + // Console.WriteLine($"[USER] {args.Username}: {args.Status}"); + } + + 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_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args) + { + var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); + RoomTracker.AddOrUpdateMessage(args.RoomName, message); + } + + private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) + { + if (args.Username != Options.Soulseek.Username) // this will fire when we join a room; track that through the join operation. + { + RoomTracker.TryAddUser(args.RoomName, args.UserData); + } + } + + private void Client_RoomLeft(object sender, RoomLeftEventArgs args) + { + RoomTracker.TryRemoveUser(args.RoomName, args.Username); + } + + 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 = 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."); + } + } + } + + /// <summary> + /// Creates and returns a <see cref="Soulseek.Directory"/> in response to a remote request. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="endpoint">The IP endpoint of the requesting user.</param> + /// <param name="token">The unique token for the request, supplied by the requesting user.</param> + /// <param name="directory">The requested directory.</param> + /// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns> + private Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) + { + var result = new Soulseek.Directory(directory, 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); + } + + /// <summary> + /// Invoked upon a remote request to download a file. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="endpoint">The IP endpoint of the requesting user.</param> + /// <param name="filename">The filename of the requested file.</param> + /// <param name="tracker">(for example purposes) the ITransferTracker used to track progress.</param> + /// <returns>A Task representing the asynchronous operation.</returns> + /// <exception cref="DownloadEnqueueException"> + /// Thrown when the download is rejected. The Exception message will be passed to the remote user. + /// </exception> + /// <exception cref="Exception"> + /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for + /// security reasons. + /// </exception> + private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) + { + _ = endpoint; + filename = filename.ToLocalOSPath(); + var fileInfo = new FileInfo(filename); + + if (!fileInfo.Exists) + { + Console.WriteLine($"[UPLOAD REJECTED] File {filename} 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, fileInfo.FullName, 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; + } + + /// <summary> + /// Creates and returns a <see cref="SearchResponse"/> in response to the given <paramref name="query"/>. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="token">The search token.</param> + /// <param name="query">The search query.</param> + /// <returns>A Task resolving a SearchResponse, or null.</returns> + private Task<SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query) + { + var defaultResponse = Task.FromResult<SearchResponse>(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( + 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<SearchResponse>(null); + } + + /// <summary> + /// Creates and returns a <see cref="UserInfo"/> object in response to a remote request. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="endpoint">The IP endpoint of the requesting user.</param> + /// <returns>A Task resolving the UserInfo instance.</returns> + private Task<UserInfo> 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: System.IO.File.ReadAllBytes(@"slsk_bird.jpg"), + uploadSlots: 1, + queueLength: 0, + hasFreeUploadSlot: false); + + return Task.FromResult(info); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 39b81eea..f7787409 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -18,19 +18,12 @@ namespace slskd { using System; - using System.Collections.Concurrent; - using System.Collections.Generic; using System.IO; using System.Linq; - using System.Net; - using System.Text.Json; using System.Text.Json.Serialization; - using System.Threading; - using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc.ApiExplorer; - using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; @@ -39,22 +32,15 @@ namespace slskd using Prometheus; using Prometheus.SystemMetrics; using Serilog; - using Serilog.Events; using slskd.API.Authentication; - using slskd.Entities; using slskd.Security; using slskd.Trackers; - using Soulseek; - using Soulseek.Diagnostics; /// <summary> /// ASP.NET Startup. /// </summary> public class Startup { - private static readonly int MaxReconnectAttempts = 3; - private static int currentReconnectAttempts = 0; - /// <summary> /// Initializes a new instance of the <see cref="Startup"/> class. /// </summary> @@ -69,8 +55,6 @@ namespace slskd o.BindNonPublicProperties = true; }); - SharedFileCache = new SharedFileCache(Options.Directories.Shared, 3600000); - UrlBase = Options.Web.UrlBase; UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; @@ -79,13 +63,10 @@ namespace slskd JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(Options.Web.Authentication.Jwt.Key)); } - private SoulseekClient Client { get; set; } private IConfiguration Configuration { get; } private string ContentPath { get; set; } private SymmetricSecurityKey JwtSigningKey { get; set; } - private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>(); private Options Options { get; } - private ISharedFileCache SharedFileCache { get; set; } private string UrlBase { get; set; } /// <summary> @@ -164,7 +145,7 @@ namespace slskd Version = "v0", }); - if (System.IO.File.Exists(Program.DefaultXmlDocumentaitonFile)) + if (File.Exists(Program.DefaultXmlDocumentaitonFile)) { options.IncludeXmlComments(Program.DefaultXmlDocumentaitonFile); } @@ -180,30 +161,26 @@ namespace slskd services.AddSystemMetrics(); } - services.AddSingleton<ISoulseekClient, SoulseekClient>(serviceProvider => Client); services.AddSingleton<ITransferTracker, TransferTracker>(); services.AddSingleton<ISearchTracker, SearchTracker>(); services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IConversationTracker, ConversationTracker>(); services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); + services.AddSingleton<ISharedFileCache>(_ => + new SharedFileCache(Options.Directories.Shared, 3600000)); + + services.AddHostedService<Service>(); + services.AddSingleton(_ => Service.SoulseekClient); } /// <summary> /// Configure middleware. /// </summary> /// <param name="app">The application builder.</param> - /// <param name="provider">The api version description provider.</param> - /// <param name="tracker">The transfer tracker.</param> - /// <param name="browseTracker">The browse tracker.</param> - /// <param name="conversationTracker">The conversation tracker.</param> - /// <param name="roomTracker">The room tracker.</param> + /// <param name="apiVersionDescriptionProvider">The api version description provider.</param> public void Configure( IApplicationBuilder app, - IApiVersionDescriptionProvider provider, - ITransferTracker tracker, - IBrowseTracker browseTracker, - IConversationTracker conversationTracker, - IRoomTracker roomTracker) + IApiVersionDescriptionProvider apiVersionDescriptionProvider) { var logger = Log.ForContext<Startup>(); @@ -236,7 +213,7 @@ namespace slskd FileServerOptions fileServerOptions = default; - if (!System.IO.Directory.Exists(ContentPath)) + if (!Directory.Exists(ContentPath)) { logger.Warning($"Static content disabled; cannot find content path '{ContentPath}'"); } @@ -254,14 +231,14 @@ namespace slskd logger.Information("Serving static content from {ContentPath}", ContentPath); } - app.UseSerilogRequestLogging(); - if (Options.Feature.Prometheus) { app.UseHttpMetrics(); logger.Information("Publishing Prometheus metrics to /metrics"); } + app.UseSerilogRequestLogging(); + app.UseAuthentication(); app.UseRouting(); @@ -280,7 +257,7 @@ namespace slskd if (Options.Feature.Swagger) { app.UseSwagger(); - app.UseSwaggerUI(options => provider.ApiVersionDescriptions.ToList() + app.UseSwaggerUI(options => apiVersionDescriptionProvider.ApiVersionDescriptions.ToList() .ForEach(description => options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName))); logger.Information("Publishing Swagger documentation to /swagger"); @@ -301,346 +278,10 @@ namespace slskd // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be // returned. otherwise it will throw a final 404 back to the client. - if (System.IO.Directory.Exists(ContentPath)) + if (Directory.Exists(ContentPath)) { app.UseFileServer(fileServerOptions); } - - // --------------------------------------------------------------------------------------------------------------------------------------------- - // begin SoulseekClient implementation - // --------------------------------------------------------------------------------------------------------------------------------------------- - 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); - - var defaults = new SoulseekClientOptions(); - - // create options for the client. see the implementation of Func<> and Action<> options for detailed info. - 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, - userInfoResponseResolver: UserInfoResponseResolver, - browseResponseResolver: BrowseResponseResolver, - directoryContentsResponseResolver: DirectoryContentsResponseResolver, - enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, tracker), - searchResponseResolver: SearchResponseResolver); - - var username = Options.Soulseek.Username; - var password = Options.Soulseek.Password; - - if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) - { - throw new ArgumentException("Soulseek credentials are not configured"); - } - - Client = new SoulseekClient(options: clientOptions); - - // bind the DiagnosticGenerated event so we can trap and display diagnostic messages. this is optional, and if the - // event isn't bound the minimumDiagnosticLevel should be set to None. - Client.DiagnosticGenerated += (e, 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(e.GetType().FullName, Log.ForContext("SourceContext", "Soulseek").ForContext("SoulseekContext", e.GetType().FullName)); - - logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); - }; - - // bind transfer events. see TransferStateChangedEventArgs and TransferProgressEventArgs. - Client.TransferStateChanged += (e, args) => - { - var direction = args.Transfer.Direction.ToString().ToUpper(); - var user = args.Transfer.Username; - var file = Path.GetFileName(args.Transfer.Filename); - var oldState = args.PreviousState; - var state = args.Transfer.State; - - var completed = args.Transfer.State.HasFlag(TransferStates.Completed); - - Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({args.Transfer.BytesTransferred}/{args.Transfer.Size} = {args.Transfer.PercentComplete}%) @ {args.Transfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}"); - }; - - Client.TransferProgressUpdated += (e, 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"); - }; - - // bind BrowseProgressUpdated to track progress of browse response payload transfers. these can take a while depending - // on number of files shared. - Client.BrowseProgressUpdated += (e, args) => - { - browseTracker.AddOrUpdate(args.Username, args); - }; - - // bind UserStatusChanged to monitor the status of users added via AddUserAsync(). - Client.UserStatusChanged += (e, args) => - { - // Console.WriteLine($"[USER] {args.Username}: {args.Status}"); - }; - - Client.PrivateMessageReceived += (e, args) => - { - conversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); - }; - - 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 += (e, args) => - { - Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); - }; - - Client.RoomMessageReceived += (e, args) => - { - var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); - roomTracker.AddOrUpdateMessage(args.RoomName, message); - }; - - Client.RoomJoined += (e, args) => - { - if (args.Username != username) // this will fire when we join a room; track that through the join operation. - { - roomTracker.TryAddUser(args.RoomName, args.UserData); - } - }; - - Client.RoomLeft += (e, args) => - { - roomTracker.TryRemoveUser(args.RoomName, args.Username); - }; - - Client.Disconnected += async (e, 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 = 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."); - } - } - }; - - Task.Run(async () => - { - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); - }).GetAwaiter().GetResult(); - - logger.Information("Connected and logged in as {Username}", username); - } - - /// <summary> - /// Creates and returns an <see cref="IEnumerable{T}"/> of <see cref="Soulseek.Directory"/> in response to a remote request. - /// </summary> - /// <param name="username">The username of the requesting user.</param> - /// <param name="endpoint">The IP endpoint of the requesting user.</param> - /// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns> - private Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint) - { - var directories = System.IO.Directory - .GetDirectories(Options.Directories.Shared, "*", SearchOption.AllDirectories) - .Select(dir => new Soulseek.Directory(dir, 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)); - } - - /// <summary> - /// Creates and returns a <see cref="Soulseek.Directory"/> in response to a remote request. - /// </summary> - /// <param name="username">The username of the requesting user.</param> - /// <param name="endpoint">The IP endpoint of the requesting user.</param> - /// <param name="token">The unique token for the request, supplied by the requesting user.</param> - /// <param name="directory">The requested directory.</param> - /// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns> - private Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) - { - var result = new Soulseek.Directory(directory, 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); - } - - /// <summary> - /// Invoked upon a remote request to download a file. - /// </summary> - /// <param name="username">The username of the requesting user.</param> - /// <param name="endpoint">The IP endpoint of the requesting user.</param> - /// <param name="filename">The filename of the requested file.</param> - /// <param name="tracker">(for example purposes) the ITransferTracker used to track progress.</param> - /// <returns>A Task representing the asynchronous operation.</returns> - /// <exception cref="DownloadEnqueueException"> - /// Thrown when the download is rejected. The Exception message will be passed to the remote user. - /// </exception> - /// <exception cref="Exception"> - /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for - /// security reasons. - /// </exception> - private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) - { - _ = endpoint; - filename = filename.ToLocalOSPath(); - var fileInfo = new FileInfo(filename); - - if (!fileInfo.Exists) - { - Console.WriteLine($"[UPLOAD REJECTED] File {filename} 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, fileInfo.FullName, 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; - } - - /// <summary> - /// Creates and returns a <see cref="SearchResponse"/> in response to the given <paramref name="query"/>. - /// </summary> - /// <param name="username">The username of the requesting user.</param> - /// <param name="token">The search token.</param> - /// <param name="query">The search query.</param> - /// <returns>A Task resolving a SearchResponse, or null.</returns> - private Task<SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query) - { - var defaultResponse = Task.FromResult<SearchResponse>(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( - 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<SearchResponse>(null); - } - - /// <summary> - /// Creates and returns a <see cref="UserInfo"/> object in response to a remote request. - /// </summary> - /// <param name="username">The username of the requesting user.</param> - /// <param name="endpoint">The IP endpoint of the requesting user.</param> - /// <returns>A Task resolving the UserInfo instance.</returns> - private Task<UserInfo> 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: System.IO.File.ReadAllBytes(@"slsk_bird.jpg"), - uploadSlots: 1, - queueLength: 0, - hasFreeUploadSlot: false); - - return Task.FromResult(info); - } - - private class IPAddressConverter : JsonConverter<IPAddress> - { - public override bool CanConvert(Type objectType) => objectType == typeof(IPAddress); - - public override IPAddress Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => IPAddress.Parse(reader.GetString()); - - public override void Write(Utf8JsonWriter writer, IPAddress value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString()); - } - - private class UserEndPointCache : IUserEndPointCache - { - public UserEndPointCache() - { - Cache = new MemoryCache(new MemoryCacheOptions()); - } - - private IMemoryCache Cache { get; } - - public void AddOrUpdate(string username, IPEndPoint endPoint) - { - Cache.Set(username, endPoint, TimeSpan.FromSeconds(60)); - } - - public bool TryGet(string username, out IPEndPoint endPoint) - { - return Cache.TryGetValue(username, out endPoint); - } } } }
\ No newline at end of file |
