aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-05-07 15:07:39 -0500
committerGitHub <noreply@github.com>2022-05-07 15:07:39 -0500
commit06fffb8b217bc11beadc49e665f38313447c49ec (patch)
tree67a764cc9b412ba8e251f0added063039a97f7a2 /src
parent1f560268681b7eac9b21b7d63a6e6f9dfae0a52c (diff)
parent6ac44e4540e5b0bf42f99563b47317add8d22aff (diff)
downloadslskd-06fffb8b217bc11beadc49e665f38313447c49ec.tar.gz
Merge branch 'master' into feat/fold-user-transfers
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs3
-rw-r--r--src/slskd/Common/Logging/ConsoleWriteLineLogger.cs34
-rw-r--r--src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs118
-rw-r--r--src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs124
-rw-r--r--src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs80
-rw-r--r--src/slskd/Core/API/Controllers/ApplicationController.cs7
-rw-r--r--src/slskd/Messaging/API/Controllers/RoomsController.cs4
-rw-r--r--src/slskd/Options.cs10
-rw-r--r--src/slskd/Program.cs611
-rw-r--r--src/slskd/Startup.cs409
-rw-r--r--src/slskd/Transfers/Uploads/UploadQueue.cs2
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs19
-rw-r--r--src/slskd/Users/UserService.cs2
-rw-r--r--src/slskd/slskd.csproj2
-rw-r--r--src/web/src/components/App.js36
-rw-r--r--src/web/src/components/System/System.js51
-rw-r--r--src/web/src/components/Users/Users.js2
-rw-r--r--src/web/src/config.js10
-rw-r--r--src/web/src/lib/api.js4
-rw-r--r--src/web/src/lib/hubFactory.js6
-rw-r--r--src/web/src/lib/rooms.js10
-rw-r--r--src/web/src/lib/users.js12
22 files changed, 967 insertions, 589 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 115d0b37..1064e56a 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -44,7 +44,7 @@ namespace slskd
using slskd.Users;
using Soulseek;
using Soulseek.Diagnostics;
-
+
public interface IApplication : IHostedService
{
public Task CheckVersionAsync();
@@ -892,7 +892,6 @@ namespace slskd
private void State_OnChange((State Previous, State Current) state)
{
- //Log.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson());
_ = ApplicationHub.BroadcastStateAsync(state.Current);
}
diff --git a/src/slskd/Common/Logging/ConsoleWriteLineLogger.cs b/src/slskd/Common/Logging/ConsoleWriteLineLogger.cs
new file mode 100644
index 00000000..4e829df6
--- /dev/null
+++ b/src/slskd/Common/Logging/ConsoleWriteLineLogger.cs
@@ -0,0 +1,34 @@
+// <copyright file="ConsoleWriteLineLogger.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 Serilog.Events;
+
+ /// <summary>
+ /// Logs messages to stdout via <see cref="Console.WriteLine(string)"/>.
+ /// </summary>
+ public class ConsoleWriteLineLogger : Serilog.ILogger
+ {
+ /// <inheritdoc/>
+ public void Write(LogEvent logEvent)
+ {
+ Console.WriteLine(logEvent.RenderMessage());
+ }
+ }
+}
diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs
new file mode 100644
index 00000000..217b2bce
--- /dev/null
+++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs
@@ -0,0 +1,118 @@
+// <copyright file="HTMLInjectionMiddleware.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.IO;
+ using System.Linq;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Builder;
+ using Microsoft.AspNetCore.Http;
+
+ /// <summary>
+ /// Adds the <see cref="HTMLInjectionMiddleware"/>.
+ /// </summary>
+ public static class HTMLInjectionMiddlewareExtensions
+ {
+ /// <summary>
+ /// Injects the specified <paramref name="html"/> into html files.
+ /// </summary>
+ /// <param name="builder"></param>
+ /// <param name="html"></param>
+ /// <returns></returns>
+ public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html)
+ {
+ return builder.UseMiddleware<HTMLInjectionMiddleware>(html);
+ }
+ }
+
+ /// <summary>
+ /// Injects content into html files.
+ /// </summary>
+ public class HTMLInjectionMiddleware
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HTMLInjectionMiddleware"/> class.
+ /// </summary>
+ /// <param name="next"></param>
+ /// <param name="html"></param>
+ public HTMLInjectionMiddleware(RequestDelegate next, string html)
+ {
+ Next = next;
+ HTML = html;
+ }
+
+ private string HTML { get; }
+ private RequestDelegate Next { get; }
+
+ /// <summary>
+ /// Executes this middleware, returning the contents of the requested HTML file with the specified HTML appended.
+ /// </summary>
+ /// <param name="context"></param>
+ /// <returns></returns>
+ public async Task InvokeAsync(HttpContext context)
+ {
+ context.Request.Headers.TryGetValue("accept", out var accept);
+ var requestedTypes = accept.ToString().Split(',');
+
+ var injectableTypes = new[] { "text/html", "application/xhtml + xml", "application/xml" };
+
+ var isApiRoute = context.Request.Path.ToString().StartsWith("/api");
+ var isGET = context.Request.Method == "GET";
+
+ var isInjectableType = requestedTypes
+ .Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase)
+ .Any();
+
+ if (!isApiRoute && isGET && isInjectableType)
+ {
+ var originalStream = context.Response.Body;
+
+ // swap the response body out with a memory stream so we can manipulate it later
+ // the downstream middleware will write the response to it
+ var stream = new MemoryStream();
+ context.Response.Body = stream;
+
+ await Next.Invoke(context);
+
+ if (context.Response.StatusCode == 200)
+ {
+ // something downstream responded with a 200, meaning there's data in the body
+ // we need to read it, so we can reset then play it back with the appended HTML
+ context.Response.Body.Seek(0, SeekOrigin.Begin);
+ var body = await new StreamReader(context.Response.Body).ReadToEndAsync();
+
+ context.Response.Clear();
+ await context.Response.WriteAsync(body + HTML);
+ }
+
+ // rewind the stream we injected to the beginning, then replay the data to the
+ // original stream
+ stream.Seek(0, SeekOrigin.Begin);
+ await stream.CopyToAsync(originalStream);
+
+ // swap the original stream back in
+ context.Response.Body = originalStream;
+ }
+ else
+ {
+ await Next.Invoke(context);
+ }
+ }
+ }
+}
diff --git a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs
new file mode 100644
index 00000000..a15ba1e0
--- /dev/null
+++ b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs
@@ -0,0 +1,124 @@
+// <copyright file="HTMLRewriteMiddleware.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.IO;
+ using System.Linq;
+ using System.Text.RegularExpressions;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Builder;
+ using Microsoft.AspNetCore.Http;
+
+ /// <summary>
+ /// Adds the <see cref="HTMLRewriteMiddleware"/>.
+ /// </summary>
+ public static class HTMLRewriteMiddlewareExtensions
+ {
+ /// <summary>
+ /// Replaces the specified <paramref name="pattern"/> with the specified <paramref name="replacement"/>.
+ /// </summary>
+ /// <param name="builder"></param>
+ /// <param name="pattern"></param>
+ /// <param name="replacement"></param>
+ /// <returns></returns>
+ public static IApplicationBuilder UseHTMLRewrite(this IApplicationBuilder builder, string pattern, string replacement)
+ {
+ return builder.UseMiddleware<HTMLRewriteMiddleware>(pattern, replacement);
+ }
+ }
+
+ /// <summary>
+ /// Replaces parts of HTML files.
+ /// </summary>
+ public class HTMLRewriteMiddleware
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HTMLRewriteMiddleware"/> class.
+ /// </summary>
+ /// <param name="next"></param>
+ /// <param name="pattern"></param>
+ /// <param name="replacement"></param>
+ public HTMLRewriteMiddleware(RequestDelegate next, string pattern, string replacement)
+ {
+ Next = next;
+ Pattern = pattern;
+ Replacement = replacement;
+ }
+
+ private string Pattern { get; }
+ private string Replacement { get; }
+ private RequestDelegate Next { get; }
+
+ /// <summary>
+ /// Executes this middleware, returning the contents of the requested HTML file with the specified replacesments made.
+ /// </summary>
+ /// <param name="context"></param>
+ /// <returns></returns>
+ public async Task InvokeAsync(HttpContext context)
+ {
+ context.Request.Headers.TryGetValue("accept", out var accept);
+ var requestedTypes = accept.ToString().Split(',');
+
+ var rewriteableType = new[] { "text/html", "application/xhtml + xml", "application/xml" };
+
+ var isApiRoute = context.Request.Path.ToString().StartsWith("/api");
+ var isGET = context.Request.Method == "GET";
+
+ var isRewriteableType = requestedTypes
+ .Intersect(rewriteableType, StringComparer.InvariantCultureIgnoreCase)
+ .Any();
+
+ if (!isApiRoute && isGET && isRewriteableType)
+ {
+ var originalStream = context.Response.Body;
+
+ // swap the response body out with a memory stream so we can manipulate it later
+ // the downstream middleware will write the response to it
+ var stream = new MemoryStream();
+ context.Response.Body = stream;
+
+ await Next.Invoke(context);
+
+ if (context.Response.StatusCode == 200)
+ {
+ // something downstream responded with a 200, meaning there's data in the body
+ // we need to read it, so we can reset then play it back with the appended HTML
+ context.Response.Body.Seek(0, SeekOrigin.Begin);
+ var body = await new StreamReader(context.Response.Body).ReadToEndAsync();
+
+ context.Response.Clear();
+
+ await context.Response.WriteAsync(Regex.Replace(body, Pattern, Replacement));
+ }
+
+ // rewind the stream we injected to the beginning, then replay the data to the
+ // original stream
+ stream.Seek(0, SeekOrigin.Begin);
+ await stream.CopyToAsync(originalStream);
+
+ // swap the original stream back in
+ context.Response.Body = originalStream;
+ }
+ else
+ {
+ await Next.Invoke(context);
+ }
+ }
+ }
+}
diff --git a/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs b/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs
new file mode 100644
index 00000000..7efdd171
--- /dev/null
+++ b/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs
@@ -0,0 +1,80 @@
+// <copyright file="StrictUrlBaseMiddleware.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.Threading.Tasks;
+ using Microsoft.AspNetCore.Builder;
+ using Microsoft.AspNetCore.Http;
+ using Serilog;
+
+ /// <summary>
+ /// Adds the <see cref="StrictUrlBaseMiddleware"/>.
+ /// </summary>
+ public static class StrictUrlBaseMiddlewareExtensions
+ {
+ /// <summary>
+ /// Ensures that routes are prefixed with <paramref name="urlBase"/>.
+ /// </summary>
+ /// <param name="builder"></param>
+ /// <param name="urlBase"></param>
+ /// <returns></returns>
+ public static IApplicationBuilder EnforceUrlBase(
+ this IApplicationBuilder builder, string urlBase)
+ {
+ return builder.UseMiddleware<StrictUrlBaseMiddleware>(urlBase);
+ }
+ }
+
+ /// <summary>
+ /// Ensures that routes are prefixed with UrlBase.
+ /// </summary>
+ public class StrictUrlBaseMiddleware
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StrictUrlBaseMiddleware"/> class.
+ /// </summary>
+ /// <param name="next"></param>
+ /// <param name="urlBase"></param>
+ public StrictUrlBaseMiddleware(RequestDelegate next, string urlBase)
+ {
+ Next = next;
+ UrlBase = urlBase;
+ }
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<StrictUrlBaseMiddleware>();
+ private RequestDelegate Next { get; }
+ private string UrlBase { get; }
+
+ /// <summary>
+ /// Executes this middleware, returning a 404 response if the path is not prefixed with UrlBase.
+ /// </summary>
+ /// <param name="context"></param>
+ /// <returns></returns>
+ public async Task InvokeAsync(HttpContext context)
+ {
+ if (!context.Request.Path.ToString().StartsWith(UrlBase))
+ {
+ Log.Debug("Request to {Path} rejected with 404; URL Base {UrlBase} is strictly enforced", context.Request.Path.ToString(), UrlBase);
+ context.Response.StatusCode = 404;
+ return;
+ }
+
+ await Next(context);
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs
index 19360fe1..cd03d96f 100644
--- a/src/slskd/Core/API/Controllers/ApplicationController.cs
+++ b/src/slskd/Core/API/Controllers/ApplicationController.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Options;
+
namespace slskd.Core.API
{
using System;
@@ -37,15 +39,18 @@ namespace slskd.Core.API
public ApplicationController(
IHostApplicationLifetime lifetime,
IApplication application,
+ IOptionsMonitor<Options> optionsMonitor,
IStateMonitor<State> applicationStateMonitor)
{
Lifetime = lifetime;
Application = application;
+ OptionsMonitor = optionsMonitor;
ApplicationStateMonitor = applicationStateMonitor;
}
private IApplication Application { get; }
private IStateMonitor<State> ApplicationStateMonitor { get; }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
private IHostApplicationLifetime Lifetime { get; }
/// <summary>
@@ -109,7 +114,7 @@ namespace slskd.Core.API
/// <returns></returns>
[HttpGet("version/latest")]
[Authorize]
- public async Task<IActionResult> CheckVersion([FromQuery]bool forceCheck = false)
+ public async Task<IActionResult> CheckVersion([FromQuery] bool forceCheck = false)
{
if (forceCheck)
{
diff --git a/src/slskd/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Messaging/API/Controllers/RoomsController.cs
index 743df527..79c06989 100644
--- a/src/slskd/Messaging/API/Controllers/RoomsController.cs
+++ b/src/slskd/Messaging/API/Controllers/RoomsController.cs
@@ -236,11 +236,11 @@ namespace slskd.Messaging.API
/// <returns></returns>
/// <response code="201">The request completed successfully.</response>
/// <response code="304">The room has already been joined.</response>
- [HttpPost("joined/{roomName}")]
+ [HttpPost("joined")]
[Authorize]
[ProducesResponseType(typeof(Room), 201)]
[ProducesResponseType(304)]
- public async Task<IActionResult> JoinRoom([FromRoute]string roomName)
+ public async Task<IActionResult> JoinRoom([FromBody]string roomName)
{
if (Tracker.Rooms.ContainsKey(roomName))
{
diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs
index 507006a4..a1493ca4 100644
--- a/src/slskd/Options.cs
+++ b/src/slskd/Options.cs
@@ -965,6 +965,7 @@ namespace slskd
[EnvironmentVariable("CONTENT_PATH")]
[Description("path to static web content")]
[StringLength(255, MinimumLength = 1)]
+ [DirectoryExists]
[RequiresRestart]
public string ContentPath { get; init; } = "wwwroot";
@@ -1057,6 +1058,15 @@ namespace slskd
public class HttpsOptions
{
/// <summary>
+ /// Gets a value indicating whether HTTPS should be disabled.
+ /// </summary>
+ [Argument(default, "no-https")]
+ [EnvironmentVariable("NO_HTTPS")]
+ [Description("disable HTTPS")]
+ [RequiresRestart]
+ public bool Disabled { get; init; } = false;
+
+ /// <summary>
/// Gets the HTTPS listen port.
/// </summary>
[Argument('L', "https-port")]
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 289e898c..ecf028b4 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -26,19 +26,42 @@ namespace slskd
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
- using Microsoft.AspNetCore;
+ using System.Text;
+ using System.Text.Json.Serialization;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authentication.JwtBearer;
+ using Microsoft.AspNetCore.Builder;
+ using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
+ using Microsoft.AspNetCore.Http;
+ using Microsoft.AspNetCore.Mvc.ApiExplorer;
+ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.FileProviders.Physical;
+ using Microsoft.IdentityModel.Tokens;
+ using Microsoft.OpenApi.Models;
+ using Prometheus;
using Prometheus.DotNetRuntime;
+ using Prometheus.SystemMetrics;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Grafana.Loki;
+ using slskd.Authentication;
using slskd.Configuration;
+ using slskd.Core.API;
using slskd.Cryptography;
+ using slskd.Integrations.FTP;
+ using slskd.Integrations.Pushbullet;
+ using slskd.Messaging;
+ using slskd.Search;
+ using slskd.Search.API;
+ using slskd.Shares;
+ using slskd.Transfers;
+ using slskd.Users;
using slskd.Validation;
+ using Soulseek;
using Utility.CommandLine;
using Utility.EnvironmentVariables;
using IOFile = System.IO.File;
@@ -154,6 +177,7 @@ namespace slskd
private static IConfigurationRoot Configuration { get; set; }
private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup();
+ private static ILogger Log { get; set; } = new ConsoleWriteLineLogger();
[Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")]
private static bool GenerateCertificate { get; set; }
@@ -181,9 +205,10 @@ namespace slskd
EnvironmentVariables.Populate(prefix: EnvironmentVariablePrefix);
Arguments.Populate(clearExistingValues: false);
+ // if a user has used one of the arguments above, perform the requested task, then quit
if (ShowVersion)
{
- Console.WriteLine(FullVersion);
+ Log.Information(FullVersion);
return;
}
@@ -225,9 +250,8 @@ namespace slskd
// if not, set it to the default.
ConfigurationFile ??= DefaultConfigurationFile;
- // verify(create if needed) default application
- // directories. if the downloads or complete directories are overridden in config, those will be
- // validated after the config is loaded.
+ // verify(create if needed) default application directories. if the downloads or complete
+ // directories are overridden in config, those will be validated after the config is loaded.
try
{
VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true);
@@ -237,7 +261,7 @@ namespace slskd
}
catch (Exception ex)
{
- Console.WriteLine($"Filesystem exception: {ex.Message}");
+ Log.Information($"Filesystem exception: {ex.Message}");
return;
}
@@ -253,114 +277,58 @@ namespace slskd
if (OptionsAtStartup.Debug)
{
- Console.WriteLine($"Configuration:\n{Configuration.GetDebugView()}");
+ Log.Information($"Configuration:\n{Configuration.GetDebugView()}");
}
if (!OptionsAtStartup.TryValidate(out var result))
{
- Console.WriteLine(result.GetResultView());
+ Log.Information(result.GetResultView());
return;
}
}
catch (Exception ex)
{
- Console.WriteLine($"Invalid configuration: {(!OptionsAtStartup.Debug ? ex : ex.Message)}");
+ Log.Information($"Invalid configuration: {(!OptionsAtStartup.Debug ? ex : ex.Message)}");
return;
}
- Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information())
- .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
- .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal)
- .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning)
- .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName)
- .Enrich.WithProperty("InvocationId", InvocationId)
- .Enrich.WithProperty("ProcessId", ProcessId)
- .Enrich.FromLogContext()
- .WriteTo.Console(
- outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
- .WriteTo.Async(config =>
- config.File(
- Path.Combine(AppDirectory, "logs", $"{AppName}-.log"),
- outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
- rollingInterval: RollingInterval.Day))
- .WriteTo.Conditional(
- e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki),
- config => config.GrafanaLoki(
- OptionsAtStartup.Logger.Loki ?? string.Empty,
- outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
- .WriteTo.Sink(new DelegatingSink(logEvent =>
- {
- try
- {
- var record = new LogRecord()
- {
- Timestamp = logEvent.Timestamp.LocalDateTime,
- Context = logEvent.Properties["SourceContext"].ToString().TrimStart('"').TrimEnd('"'),
- SubContext = logEvent.Properties.ContainsKey("SubContext") ? logEvent.Properties["SubContext"].ToString().TrimStart('"').TrimEnd('"') : null,
- Level = logEvent.Level.ToString(),
- Message = logEvent.RenderMessage().TrimStart('"').TrimEnd('"'),
- };
-
- LogBuffer.Enqueue(record);
- LogEmitted?.Invoke(null, record);
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Misconfigured delegating logger: {ex.Message}");
- }
- }))
- .CreateLogger();
-
- var logger = Log.ForContext(typeof(Program));
+ ConfigureGlobalLogger();
+ Log = Serilog.Log.ForContext(typeof(Program));
if (!OptionsAtStartup.NoLogo)
{
PrintLogo(FullVersion);
}
- logger.Information("Version: {Version}", FullVersion);
+ Log.Information("Version: {Version}", FullVersion);
if (IsDevelopment)
{
- logger.Warning("This is a Development build; YMMV");
+ Log.Warning("This is a Development build; YMMV");
}
if (IsCanary)
{
- logger.Warning("This is a canary build");
- logger.Warning("Canary builds are considered UNSTABLE and may be completely BROKEN");
- logger.Warning($"Please report any issues here: {IssuesUrl}");
+ Log.Warning("This is a canary build");
+ Log.Warning("Canary builds are considered UNSTABLE and may be completely BROKEN");
+ Log.Warning($"Please report any issues here: {IssuesUrl}");
}
- logger.Information("Invocation ID: {InvocationId}", InvocationId);
- logger.Information("Process ID: {ProcessId}", ProcessId);
- logger.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName);
+ Log.Information("Invocation ID: {InvocationId}", InvocationId);
+ Log.Information("Process ID: {ProcessId}", ProcessId);
+ Log.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName);
- logger.Information("Using application directory {AppDirectory}", AppDirectory);
- logger.Information("Using configuration file {ConfigurationFile}", ConfigurationFile);
+ Log.Information("Using application directory {AppDirectory}", AppDirectory);
+ Log.Information("Using configuration file {ConfigurationFile}", ConfigurationFile);
- // for convenience, try to copy the example configuration file to the application directory if no configuration
- // file exists. if any part fails, just move on silently.
- if (!IOFile.Exists(ConfigurationFile))
- {
- try
- {
- logger.Warning("Configuration file {ConfigurationFile} does not exist; creating from example", ConfigurationFile);
- var source = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml");
- var destination = ConfigurationFile;
- IOFile.Copy(source, destination);
- }
- catch (Exception ex)
- {
- logger.Error("Failed to create configuration file {ConfigurationFile}: {Message}", ConfigurationFile, ex.Message);
- }
- }
+ RecreateConfigurationFileIfMissing(ConfigurationFile);
if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki))
{
- logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki);
+ Log.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki);
}
+ // bootstrap the ASP.NET application
try
{
if (OptionsAtStartup.Feature.Prometheus)
@@ -368,58 +336,417 @@ namespace slskd
using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting();
}
- var webHost = WebHost.CreateDefaultBuilder(args)
- .SuppressStatusMessages(true)
- .ConfigureAppConfiguration((hostingContext, builder) =>
- {
- builder.Sources.Clear();
- builder.AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile);
- })
- .UseSerilog()
+ var builder = WebApplication.CreateBuilder(args);
+
+ builder.Configuration
+ .AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile);
+
+ builder.Host
+ .UseSerilog();
+
+ builder.WebHost
.UseUrls()
.UseKestrel(options =>
{
- logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/");
+ Log.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/");
options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port);
- logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/");
- options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions =>
+ if (!OptionsAtStartup.Web.Https.Disabled)
{
- var cert = OptionsAtStartup.Web.Https.Certificate;
-
- if (!string.IsNullOrEmpty(cert.Pfx))
- {
- logger.Information($"Using certificate from {cert.Pfx}");
- listenOptions.UseHttps(cert.Pfx, cert.Password);
- }
- else
+ Log.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/");
+ options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions =>
{
- logger.Information($"Using randomly generated self-signed certificate");
- listenOptions.UseHttps(X509.Generate(subject: AppName));
- }
- });
- })
- .UseStartup<Startup>()
- .Build();
+ var cert = OptionsAtStartup.Web.Https.Certificate;
+
+ if (!string.IsNullOrEmpty(cert.Pfx))
+ {
+ Log.Information($"Using certificate from {cert.Pfx}");
+ listenOptions.UseHttps(cert.Pfx, cert.Password);
+ }
+ else
+ {
+ Log.Information($"Using randomly generated self-signed certificate");
+ listenOptions.UseHttps(X509.Generate(subject: AppName));
+ }
+ });
+ }
+ });
+
+ builder.Services
+ .ConfigureAspDotNetServices()
+ .ConfigureDependencyInjectionContainer();
+
+ var app = builder.Build();
+
+ app.ConfigureAspDotNetPipeline();
if (OptionsAtStartup.NoStart)
{
- logger.Information("Qutting because 'no-start' option is enabled");
+ Log.Information("Qutting because 'no-start' option is enabled");
return;
}
- webHost.Run();
+ app.Run();
}
catch (Exception ex)
{
- logger.Fatal(ex, "Application terminated unexpectedly");
+ Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
- Log.CloseAndFlush();
+ Serilog.Log.CloseAndFlush();
}
}
+ private static IServiceCollection ConfigureDependencyInjectionContainer(this IServiceCollection services)
+ {
+ // add the instance of OptionsAtStartup to DI as they were at startup. use when Options might change, but
+ // the values at startup are to be used (generally anything marked RequiresRestart).
+ services.AddSingleton(OptionsAtStartup);
+
+ // add IOptionsMonitor and IOptionsSnapshot to DI.
+ // use when the current Options are to be used (generally anything not marked RequiresRestart)
+ // the monitor should be used for services with Singleton lifetime, snapshots for everything else
+ services.AddOptions<Options>()
+ .Bind(Configuration.GetSection(AppName), o => { o.BindNonPublicProperties = true; })
+ .Validate(options =>
+ {
+ if (!options.TryValidate(out var result))
+ {
+ Log.Warning("Options (re)configuration rejected.");
+ Log.Warning(result.GetResultView());
+ return false;
+ }
+
+ return true;
+ });
+
+ // add IManagedState, IStateMutator, IStateMonitor, and IStateSnapshot state to DI.
+ // the mutator should be used any time application state needs to be mutated (as the name implies)
+ // as with options, the monitor should be used for services with Singleton lifetime, snapshots for everything else
+ // IManagedState should be used where state is being mutated and accessed in the same context
+ services.AddManagedState<State>();
+
+ // add IHttpClientFactory
+ // use through 'using var http = HttpClientFactory.CreateClient()' wherever HTTP calls will be made
+ // this is important to prevent memory leaks
+ services.AddHttpClient();
+
+ // add a partially configured instance of SoulseekClient. the Application instance will
+ // complete configuration at startup.
+ services.AddSingleton<ISoulseekClient, SoulseekClient>(_ =>
+ new SoulseekClient(options: new SoulseekClientOptions(
+ maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots,
+ maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots,
+ minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel)));
+
+ // add the core application service to DI as well as a hosted service so that other services can
+ // access instance methods
+ services.AddSingleton<IApplication, Application>();
+ services.AddHostedService(p => p.GetRequiredService<IApplication>());
+
+ services.AddDbContext<SearchDbContext>("search.db");
+
+ services.AddSingleton<ITransferTracker, TransferTracker>();
+ services.AddSingleton<IBrowseTracker, BrowseTracker>();
+ services.AddSingleton<IConversationTracker, ConversationTracker>();
+ services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250));
+
+ services.AddSingleton<ISharedFileCache, SharedFileCache>();
+
+ services.AddSingleton<ISearchService, SearchService>();
+ services.AddSingleton<IUserService, UserService>();
+ services.AddSingleton<IRoomService, RoomService>();
+ services.AddSingleton<ITransferService, TransferService>();
+
+ services.AddSingleton<IFTPClientFactory, FTPClientFactory>();
+ services.AddSingleton<IFTPService, FTPService>();
+
+ services.AddSingleton<IPushbulletService, PushbulletService>();
+
+ return services;
+ }
+
+ private static IServiceCollection ConfigureAspDotNetServices(this IServiceCollection services)
+ {
+ services.AddCors(options => options.AddPolicy("AllowAll", builder => builder
+ .AllowAnyHeader()
+ .AllowAnyMethod()
+ .SetIsOriginAllowed((host) => true)
+ .AllowCredentials()));
+
+ var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key));
+
+ services.AddSingleton(jwtSigningKey);
+
+ if (!OptionsAtStartup.Web.Authentication.Disabled)
+ {
+ services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+ .AddJwtBearer(options =>
+ {
+ options.TokenValidationParameters = new TokenValidationParameters
+ {
+ ClockSkew = TimeSpan.FromMinutes(5),
+ RequireSignedTokens = true,
+ RequireExpirationTime = true,
+ ValidateLifetime = true,
+ ValidIssuer = AppName,
+ ValidateIssuer = true,
+ ValidateAudience = false,
+ IssuerSigningKey = jwtSigningKey,
+ ValidateIssuerSigningKey = true,
+ };
+
+ options.Events = new JwtBearerEvents
+ {
+ OnMessageReceived = context =>
+ {
+ // assign the request token from the access_token query parameter
+ // but only if the destination is a SignalR hub
+ // https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-5.0
+ if (context.HttpContext.Request.Path.StartsWithSegments("/hub"))
+ {
+ context.Token = context.Request.Query["access_token"];
+ }
+
+ return Task.CompletedTask;
+ },
+ };
+ });
+ }
+ else
+ {
+ Log.Warning("Authentication of web requests is DISABLED");
+
+ services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme)
+ .AddScheme<PassthroughAuthenticationOptions, PassthroughAuthenticationHandler>(PassthroughAuthentication.AuthenticationScheme, options =>
+ {
+ options.Username = "Anonymous";
+ options.Role = Role.Administrator;
+ });
+ }
+
+ services.AddRouting(options => options.LowercaseUrls = true);
+ services.AddControllers().AddJsonOptions(options =>
+ {
+ options.JsonSerializerOptions.Converters.Add(new IPAddressConverter());
+ options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
+ options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
+ });
+
+ services.AddSignalR().AddJsonProtocol(options =>
+ {
+ options.PayloadSerializerOptions.Converters.Add(new IPAddressConverter());
+ options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter());
+ });
+
+ services.AddHealthChecks();
+
+ services.AddApiVersioning(options => options.ReportApiVersions = true);
+ services.AddVersionedApiExplorer(options =>
+ {
+ options.GroupNameFormat = "'v'VVV";
+ options.SubstituteApiVersionInUrl = true;
+ });
+
+ if (OptionsAtStartup.Feature.Swagger)
+ {
+ services.AddSwaggerGen(options =>
+ {
+ options.DescribeAllParametersInCamelCase();
+ options.SwaggerDoc(
+ "v0",
+ new OpenApiInfo
+ {
+ Title = AppName,
+ Version = "v0",
+ });
+
+ if (System.IO.File.Exists(XmlDocumentationFile))
+ {
+ options.IncludeXmlComments(XmlDocumentationFile);
+ }
+ else
+ {
+ Log.Warning($"Unable to find XML documentation in {XmlDocumentationFile}, Swagger will not include metadata");
+ }
+ });
+ }
+
+ if (OptionsAtStartup.Feature.Prometheus)
+ {
+ services.AddSystemMetrics();
+ }
+
+ return services;
+ }
+
+ private static WebApplication ConfigureAspDotNetPipeline(this WebApplication app)
+ {
+ app.UseExceptionHandler(a => a.Run(async context =>
+ {
+ await context.Response.WriteAsJsonAsync(context.Features.Get<IExceptionHandlerPathFeature>().Error.Message);
+ }));
+
+ app.UseCors("AllowAll");
+
+ if (OptionsAtStartup.Web.Https.Force)
+ {
+ app.UseHttpsRedirection();
+ app.UseHsts();
+
+ Log.Information($"Forcing HTTP requests to HTTPS");
+ }
+
+ // allow users to specify a custom path base, for use behind a reverse proxy
+ var urlBase = OptionsAtStartup.Web.UrlBase;
+ urlBase = urlBase.StartsWith("/") ? urlBase : "/" + urlBase;
+
+ // 404 if a custom urlBase is set, but the request doesn't include it.
+ // this is necessary to make sure the development-time and run-time behavior
+ // are consistent.
+ app.EnforceUrlBase(urlBase);
+
+ // use urlBase. this effectively just removes urlBase from the path, which is
+ // why the enforcement behavior exists above (the actually requested path becomes ambiguous)
+ // inject urlBase into any html files we serve, and rewrite links to ./static or /static to
+ // prepend the url base.
+ app.UsePathBase(urlBase);
+ app.UseHTMLRewrite("((\\.)?\\/static)", $"{(urlBase == "/" ? string.Empty : urlBase)}/static");
+ app.UseHTMLInjection($"<script>window.urlBase=\"{urlBase}\"</script>");
+ Log.Information("Using base url {UrlBase}", urlBase);
+
+ // serve static content from the configured path
+ FileServerOptions fileServerOptions = default;
+ var contentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath);
+
+ fileServerOptions = new FileServerOptions
+ {
+ FileProvider = new PhysicalFileProvider(contentPath),
+ RequestPath = string.Empty,
+ EnableDirectoryBrowsing = false,
+ EnableDefaultFiles = true,
+ };
+
+ app.UseFileServer(fileServerOptions);
+ Log.Information("Serving static content from {ContentPath}", contentPath);
+
+ if (OptionsAtStartup.Feature.Prometheus)
+ {
+ app.UseHttpMetrics();
+ Log.Information("Publishing Prometheus metrics to /metrics");
+ }
+
+ if (OptionsAtStartup.Web.Logging)
+ {
+ app.UseSerilogRequestLogging();
+ }
+
+ app.UseAuthentication();
+
+ app.UseRouting();
+ app.UseAuthorization();
+ app.UseEndpoints(endpoints =>
+ {
+ endpoints.MapHub<ApplicationHub>("/hub/application");
+ endpoints.MapHub<LogsHub>("/hub/logs");
+ endpoints.MapHub<SearchHub>("/hub/search");
+
+ endpoints.MapControllers();
+ endpoints.MapHealthChecks("/health");
+
+ if (OptionsAtStartup.Feature.Prometheus)
+ {
+ endpoints.MapMetrics("/metrics");
+ }
+ });
+
+ // if this is an /api route and no API controller was matched, give up and return a 404.
+ app.Use(async (context, next) =>
+ {
+ if (context.Request.Path.StartsWithSegments("/api"))
+ {
+ context.Response.StatusCode = 404;
+ return;
+ }
+
+ await next();
+ });
+
+ if (OptionsAtStartup.Feature.Swagger)
+ {
+ app.UseSwagger();
+ app.UseSwaggerUI(options => app.Services.GetRequiredService<IApiVersionDescriptionProvider>().ApiVersionDescriptions.ToList()
+ .ForEach(description => options.SwaggerEndpoint($"{(urlBase == "/" ? string.Empty : urlBase)}/swagger/{description.GroupName}/swagger.json", description.GroupName)));
+
+ Log.Information("Publishing Swagger documentation to /swagger");
+ }
+
+ // if we made it this far, the caller is either looking for a route that was synthesized with a SPA router, or is genuinely confused.
+ // if the request is for a directory, modify the request to redirect it to the index, otherwise leave it alone and let it 404 in the next
+ // middleware
+ app.Use(async (context, next) =>
+ {
+ if (Path.GetExtension(context.Request.Path.ToString()) == string.Empty)
+ {
+ context.Request.Path = "/";
+ }
+
+ await next();
+ });
+
+ // either serve the index, or 404
+ app.UseFileServer(fileServerOptions);
+
+ return app;
+ }
+
+ private static void ConfigureGlobalLogger()
+ {
+ Serilog.Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information())
+ .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
+ .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal)
+ .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning)
+ .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName)
+ .Enrich.WithProperty("InvocationId", InvocationId)
+ .Enrich.WithProperty("ProcessId", ProcessId)
+ .Enrich.FromLogContext()
+ .WriteTo.Console(
+ outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
+ .WriteTo.Async(config =>
+ config.File(
+ Path.Combine(AppDirectory, "logs", $"{AppName}-.log"),
+ outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
+ rollingInterval: RollingInterval.Day))
+ .WriteTo.Conditional(
+ e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki),
+ config => config.GrafanaLoki(
+ OptionsAtStartup.Logger.Loki ?? string.Empty,
+ outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
+ .WriteTo.Sink(new DelegatingSink(logEvent =>
+ {
+ try
+ {
+ var record = new LogRecord()
+ {
+ Timestamp = logEvent.Timestamp.LocalDateTime,
+ Context = logEvent.Properties["SourceContext"].ToString().TrimStart('"').TrimEnd('"'),
+ SubContext = logEvent.Properties.ContainsKey("SubContext") ? logEvent.Properties["SubContext"].ToString().TrimStart('"').TrimEnd('"') : null,
+ Level = logEvent.Level.ToString(),
+ Message = logEvent.RenderMessage().TrimStart('"').TrimEnd('"'),
+ };
+
+ LogBuffer.Enqueue(record);
+ LogEmitted?.Invoke(null, record);
+ }
+ catch (Exception ex)
+ {
+ Log.Information($"Misconfigured delegating logger: {ex.Message}");
+ }
+ }))
+ .CreateLogger();
+ }
+
private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile)
{
configurationFile = Path.GetFullPath(configurationFile);
@@ -454,16 +781,60 @@ namespace slskd
commandLine: Environment.CommandLine);
}
+ private static IServiceCollection AddDbContext<T>(this IServiceCollection services, string filename)
+ where T : DbContext
+ {
+ Log.Debug($"Initializing database context {typeof(T).Name}");
+
+ try
+ {
+ services.AddDbContextFactory<SearchDbContext>(options =>
+ {
+ options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", filename)}");
+ });
+
+ using var ctx = services
+ .BuildServiceProvider()
+ .GetRequiredService<IDbContextFactory<T>>()
+ .CreateDbContext();
+
+ return services;
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, $"Failed to initialize database context {typeof(T).Name}: ${ex.Message}");
+ throw;
+ }
+ }
+
+ private static void RecreateConfigurationFileIfMissing(string configurationFile)
+ {
+ if (!IOFile.Exists(configurationFile))
+ {
+ try
+ {
+ Log.Warning("Configuration file {ConfigurationFile} does not exist; creating from example", configurationFile);
+ var source = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml");
+ var destination = configurationFile;
+ IOFile.Copy(source, destination);
+ }
+ catch (Exception ex)
+ {
+ Log.Error("Failed to create configuration file {ConfigurationFile}: {Message}", configurationFile, ex.Message);
+ }
+ }
+ }
+
private static void GenerateX509Certificate(string password, string filename)
{
- Console.WriteLine("Generating X509 certificate...");
+ Log.Information("Generating X509 certificate...");
filename = Path.Combine(AppContext.BaseDirectory, filename);
var cert = X509.Generate(subject: AppName, password, X509KeyStorageFlags.Exportable);
IOFile.WriteAllBytes(filename, cert.Export(X509ContentType.Pkcs12, password));
- Console.WriteLine($"Password: {password}");
- Console.WriteLine($"Certificate exported to {filename}");
+ Log.Information($"Password: {password}");
+ Log.Information($"Certificate exported to {filename}");
}
private static void PrintCommandLineArguments(Type targetType)
@@ -513,12 +884,12 @@ namespace slskd
var longestItem = lines.Max(l => l.Item.Length);
- Console.WriteLine("\nusage: slskd [arguments]\n");
- Console.WriteLine("arguments:\n");
+ Log.Information("\nusage: slskd [arguments]\n");
+ Log.Information("arguments:\n");
foreach (var line in lines)
{
- Console.WriteLine($" {line.Item.PadRight(longestItem)} {line.Description}");
+ Log.Information($" {line.Item.PadRight(longestItem)} {line.Description}");
}
}
@@ -567,11 +938,11 @@ namespace slskd
var longestItem = lines.Max(l => l.Item.Length);
- Console.WriteLine("\nenvironment variables (arguments and config file have precedence):\n");
+ Log.Information("\nenvironment variables (arguments and config file have precedence):\n");
foreach (var line in lines)
{
- Console.WriteLine($" {line.Item.PadRight(longestItem)} {line.Description}");
+ Log.Information($" {line.Item.PadRight(longestItem)} {line.Description}");
}
}
@@ -624,13 +995,13 @@ namespace slskd
private static void VerifyDirectory(string directory, bool createIfMissing = true, bool verifyWriteable = true)
{
- if (!Directory.Exists(directory))
+ if (!System.IO.Directory.Exists(directory))
{
if (createIfMissing)
{
try
{
- Directory.CreateDirectory(directory);
+ System.IO.Directory.CreateDirectory(directory);
}
catch (Exception ex)
{
diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs
deleted file mode 100644
index 29f9717f..00000000
--- a/src/slskd/Startup.cs
+++ /dev/null
@@ -1,409 +0,0 @@
-// <copyright file="Startup.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.IO;
- using System.Linq;
- using System.Text;
- using System.Text.Json.Serialization;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Diagnostics;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc.ApiExplorer;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.FileProviders;
- using Microsoft.IdentityModel.Tokens;
- using Microsoft.OpenApi.Models;
- using Prometheus;
- using Prometheus.SystemMetrics;
- using Serilog;
- using slskd.Authentication;
- using slskd.Core.API;
- using slskd.Integrations.FTP;
- using slskd.Integrations.Pushbullet;
- using slskd.Messaging;
- using slskd.Search;
- using slskd.Search.API;
- using slskd.Shares;
- using slskd.Transfers;
- using slskd.Users;
- using slskd.Validation;
- using Soulseek;
-
- /// <summary>
- /// ASP.NET Startup.
- /// </summary>
- public class Startup
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="Startup"/> class.
- /// </summary>
- /// <param name="configuration">The application configuration root.</param>
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
-
- OptionsAtStartup = new OptionsAtStartup();
- Configuration.GetSection(Program.AppName).Bind(OptionsAtStartup, (o) =>
- {
- o.BindNonPublicProperties = true;
- });
-
- UrlBase = OptionsAtStartup.Web.UrlBase;
- UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase;
-
- ContentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath);
-
- JwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key));
- }
-
- private IConfiguration Configuration { get; }
- private string ContentPath { get; set; }
- private SymmetricSecurityKey JwtSigningKey { get; set; }
- private OptionsAtStartup OptionsAtStartup { get; }
- private string UrlBase { get; set; }
-
- /// <summary>
- /// Configure services.
- /// </summary>
- /// <param name="services">The service collection.</param>
- public void ConfigureServices(IServiceCollection services)
- {
- var logger = Log.ForContext<Startup>();
-
- // add the instance of OptionsAtStartup to DI as they were at startup. use when Options might change, but
- // the values at startup are to be used.
- services.AddSingleton(OptionsAtStartup);
-
- // add IOptionsMonitor and IOptionsSnapshot to DI. use when the current Options are to be used.
- services.AddOptions<Options>()
- .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; })
- .Validate(options =>
- {
- if (!options.TryValidate(out var result))
- {
- logger.Warning("Options (re)configuration rejected.");
- logger.Warning(result.GetResultView());
- return false;
- }
-
- return true;
- });
-
- services.AddManagedState<State>();
-
- services.AddCors(options => options.AddPolicy("AllowAll", builder => builder
- .AllowAnyHeader()
- .AllowAnyMethod()
- .SetIsOriginAllowed((host) => true)
- .AllowCredentials()));
-
- services.AddSingleton(JwtSigningKey);
-
- if (!OptionsAtStartup.Web.Authentication.Disabled)
- {
- services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
- .AddJwtBearer(options =>
- {
- options.TokenValidationParameters = new TokenValidationParameters
- {
- ClockSkew = TimeSpan.FromMinutes(5),
- RequireSignedTokens = true,
- RequireExpirationTime = true,
- ValidateLifetime = true,
- ValidIssuer = Program.AppName,
- ValidateIssuer = true,
- ValidateAudience = false,
- IssuerSigningKey = JwtSigningKey,
- ValidateIssuerSigningKey = true,
- };
-
- options.Events = new JwtBearerEvents
- {
- OnMessageReceived = context =>
- {
- // assign the request token from the access_token query parameter
- // but only if the destination is a SignalR hub
- // https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-5.0
- if (context.HttpContext.Request.Path.StartsWithSegments("/hub"))
- {
- context.Token = context.Request.Query["access_token"];
- }
-
- return Task.CompletedTask;
- },
- };
- });
- }
- else
- {
- logger.Warning("Authentication of web requests is DISABLED");
-
- services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme)
- .AddScheme<PassthroughAuthenticationOptions, PassthroughAuthenticationHandler>(PassthroughAuthentication.AuthenticationScheme, options =>
- {
- options.Username = "Anonymous";
- options.Role = Role.Administrator;
- });
- }
-
- services.AddRouting(options => options.LowercaseUrls = true);
- services.AddControllers().AddJsonOptions(options =>
- {
- options.JsonSerializerOptions.Converters.Add(new IPAddressConverter());
- options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
- options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
- });
-
- services.AddSignalR().AddJsonProtocol(options =>
- {
- options.PayloadSerializerOptions.Converters.Add(new IPAddressConverter());
- options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter());
- });
-
- services.AddHealthChecks();
-
- services.AddApiVersioning(options => options.ReportApiVersions = true);
- services.AddVersionedApiExplorer(options =>
- {
- options.GroupNameFormat = "'v'VVV";
- options.SubstituteApiVersionInUrl = true;
- });
-
- if (OptionsAtStartup.Feature.Swagger)
- {
- services.AddSwaggerGen(options =>
- {
- options.DescribeAllParametersInCamelCase();
- options.SwaggerDoc(
- "v0",
- new OpenApiInfo
- {
- Title = Program.AppName,
- Version = "v0",
- });
-
- if (System.IO.File.Exists(Program.XmlDocumentationFile))
- {
- options.IncludeXmlComments(Program.XmlDocumentationFile);
- }
- else
- {
- logger.Warning($"Unable to find XML documentation in {Program.XmlDocumentationFile}, Swagger will not include metadata");
- }
- });
- }
-
- if (OptionsAtStartup.Feature.Prometheus)
- {
- services.AddSystemMetrics();
- }
-
- services.AddDbContextFactory<SearchDbContext>(options =>
- {
- options.UseSqlite($"Data Source={Path.Combine(Program.AppDirectory, "data", "search.db")}");
- });
-
- services.AddHttpClient();
-
- // add a partially configured instance of SoulseekClient. the Application instance will
- // complete configuration at startup.
- services.AddSingleton<ISoulseekClient, SoulseekClient>(_ =>
- new SoulseekClient(options: new SoulseekClientOptions(
- maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots,
- maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots,
- minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel)));
-
- // add the core application service to DI as well as a hosted service so that other services can
- // access instance methods
- services.AddSingleton<IApplication, Application>();
- services.AddHostedService(p => p.GetRequiredService<IApplication>());
-
- services.AddSingleton<ITransferTracker, TransferTracker>();
- services.AddSingleton<IBrowseTracker, BrowseTracker>();
- services.AddSingleton<IConversationTracker, ConversationTracker>();
- services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250));
-
- services.AddSingleton<ISharedFileCache, SharedFileCache>();
-
- services.AddSingleton<ISearchService, SearchService>();
- services.AddSingleton<IUserService, UserService>();
- services.AddSingleton<IRoomService, RoomService>();
- services.AddSingleton<ITransferService, TransferService>();
-
- services.AddSingleton<IFTPClientFactory, FTPClientFactory>();
- services.AddSingleton<IFTPService, FTPService>();
-
- services.AddSingleton<IPushbulletService, PushbulletService>();
- }
-
- /// <summary>
- /// Configure middleware.
- /// </summary>
- /// <param name="app">The application builder.</param>
- /// <param name="apiVersionDescriptionProvider">The api version description provider.</param>
- public void Configure(
- IApplicationBuilder app,
- IApiVersionDescriptionProvider apiVersionDescriptionProvider)
- {
- var logger = Log.ForContext<Startup>();
-
- // initialize DbContext instances to avoid race conditions when a db needs to be
- // created from scratch. note that this method needs to be updated to include each
- // DbContext explicitly.
- InitializeDbContexts(app);
-
- app.UseExceptionHandler(a => a.Run(async context =>
- {
- await context.Response.WriteAsJsonAsync(context.Features.Get<IExceptionHandlerPathFeature>().Error.Message);
- }));
-
- app.UseCors("AllowAll");
-
- if (OptionsAtStartup.Web.Https.Force)
- {
- app.UseHttpsRedirection();
- app.UseHsts();
-
- logger.Information($"Forcing HTTP requests to HTTPS");
- }
-
- // allow users to specify a custom path base, for use behind a reverse proxy
- app.UsePathBase(UrlBase);
- logger.Information("Using base url {UrlBase}", UrlBase);
-
- // remove any errant double forward slashes which may have been introduced by manipulating the path base
- app.Use(async (context, next) =>
- {
- var path = context.Request.Path.ToString();
-
- if (path.StartsWith("//"))
- {
- context.Request.Path = new string(path.Skip(1).ToArray());
- }
-
- await next();
- });
-
- FileServerOptions fileServerOptions = default;
-
- if (!System.IO.Directory.Exists(ContentPath))
- {
- logger.Warning($"Static content disabled; cannot find content path '{ContentPath}'");
- }
- else
- {
- fileServerOptions = new FileServerOptions
- {
- FileProvider = new PhysicalFileProvider(ContentPath),
- RequestPath = string.Empty,
- EnableDirectoryBrowsing = false,
- EnableDefaultFiles = true,
- };
-
- app.UseFileServer(fileServerOptions);
- logger.Information("Serving static content from {ContentPath}", ContentPath);
- }
-
- if (OptionsAtStartup.Feature.Prometheus)
- {
- app.UseHttpMetrics();
- logger.Information("Publishing Prometheus metrics to /metrics");
- }
-
- if (OptionsAtStartup.Web.Logging)
- {
- app.UseSerilogRequestLogging();
- }
-
- app.UseAuthentication();
-
- app.UseRouting();
- app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapHub<ApplicationHub>("/hub/application");
- endpoints.MapHub<LogsHub>("/hub/logs");
- endpoints.MapHub<SearchHub>("/hub/search");
-
- endpoints.MapControllers();
- endpoints.MapHealthChecks("/health");
-
- if (OptionsAtStartup.Feature.Prometheus)
- {
- endpoints.MapMetrics("/metrics");
- }
- });
-
- if (OptionsAtStartup.Feature.Swagger)
- {
- app.UseSwagger();
- app.UseSwaggerUI(options => apiVersionDescriptionProvider.ApiVersionDescriptions.ToList()
- .ForEach(description => options.SwaggerEndpoint($"{(UrlBase == "/" ? string.Empty : UrlBase)}/swagger/{description.GroupName}/swagger.json", description.GroupName)));
-
- logger.Information("Publishing Swagger documentation to /swagger");
- }
-
- // if we made it this far and the route still wasn't matched, return the index unless it's an api route. this is
- // required so that SPA routing (React Router, etc) can work properly
- app.Use(async (context, next) =>
- {
- // exclude API routes which are not matched or return a 404
- if (!context.Request.Path.StartsWithSegments("/api"))
- {
- context.Request.Path = "/";
- }
-
- await next();
- });
-
- // 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))
- {
- app.UseFileServer(fileServerOptions);
- }
- }
-
- private void InitializeDbContexts(IApplicationBuilder app)
- {
- var logger = Log.ForContext<Startup>();
-
- IDbContextFactory<T> GetFactory<T>()
- where T : DbContext
- => app.ApplicationServices.GetRequiredService<IDbContextFactory<T>>();
-
- logger.Debug("Initializing database contexts");
-
- try
- {
- using var search = GetFactory<SearchDbContext>().CreateDbContext();
- }
- catch (Exception ex)
- {
- logger.Error(ex, "Failed to initialize one or more application databases");
- throw;
- }
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs
index e5b8c5f5..de8cc031 100644
--- a/src/slskd/Transfers/Uploads/UploadQueue.cs
+++ b/src/slskd/Transfers/Uploads/UploadQueue.cs
@@ -199,7 +199,9 @@ namespace slskd.Transfers
}
}
+#pragma warning disable S3241 // Methods should not return values that are never used
private Upload Process()
+#pragma warning restore S3241 // Methods should not return values that are never used
{
SyncRoot.Wait();
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index 99f12df4..f88e80a8 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -1,4 +1,21 @@
-namespace slskd.Transfers.Uploads
+// <copyright file="UploadService.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.Transfers.Uploads
{
/// <summary>
/// Manages uploads.
diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs
index aa2ae234..95fed12d 100644
--- a/src/slskd/Users/UserService.cs
+++ b/src/slskd/Users/UserService.cs
@@ -54,7 +54,7 @@ namespace slskd.Users
// binding these events will cause multiple redundant round trips when initially watching a user
// or when explicitly requesting via GetStatus/GetStatistics. this is wasteful, but there's no functional side effect.
Client.UserStatisticsChanged += (_, userStatistics) => UpdateStatistics(userStatistics.Username, userStatistics.ToStatistics());
- Client.UserStatusChanged += (_, userStatus) =>
+ Client.UserStatusChanged += (sender, userStatus) =>
{
UpdateStatus(userStatus.Username, userStatus.ToStatus());
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index b4d28967..e0e83f41 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -69,7 +69,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
- <PackageReference Include="Soulseek" Version="4.5.1" />
+ <PackageReference Include="Soulseek" Version="4.5.2" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.354">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js
index 3a22e0c8..09f3f742 100644
--- a/src/web/src/components/App.js
+++ b/src/web/src/components/App.js
@@ -1,8 +1,9 @@
import React, { Component } from 'react';
-import { Route, Link, Switch } from "react-router-dom";
+import { Route, Link, Switch, Redirect } from "react-router-dom";
import * as session from '../lib/session';
import { connect, disconnect } from '../lib/server';
+import { urlBase } from '../config';
import { createApplicationHubConnection } from '../lib/hubFactory';
@@ -150,37 +151,37 @@ class App extends Component {
{version.isCanary && <Menu.Item>
<Icon name='flask' color='yellow'/>Canary
</Menu.Item>}
- <Link to='.'>
+ <Link to={`${urlBase}/searches`}>
<Menu.Item>
<Icon name='search'/>Search
</Menu.Item>
</Link>
- <Link to='downloads'>
+ <Link to={`${urlBase}/downloads`}>
<Menu.Item>
<Icon name='download'/>Downloads
</Menu.Item>
</Link>
- <Link to='uploads'>
+ <Link to={`${urlBase}/uploads`}>
<Menu.Item>
<Icon name='upload'/>Uploads
</Menu.Item>
</Link>
- <Link to='rooms'>
+ <Link to={`${urlBase}/rooms`}>
<Menu.Item>
<Icon name='comments'/>Rooms
</Menu.Item>
</Link>
- <Link to='chat'>
+ <Link to={`${urlBase}/chat`}>
<Menu.Item>
<Icon name='comment'/>Chat
</Menu.Item>
</Link>
- <Link to='users'>
+ <Link to={`${urlBase}/users`}>
<Menu.Item>
<Icon name='users'/>Users
</Menu.Item>
</Link>
- <Link to='browse'>
+ <Link to={`${urlBase}/browse`}>
<Menu.Item>
<Icon name='folder open'/>Browse
</Menu.Item>
@@ -221,7 +222,7 @@ class App extends Component {
href="https://github.com/slskd/slskd/releases">See Release Notes</Button>
</Modal.Actions>
</Modal>}
- <Link to='system'>
+ <Link to={`${urlBase}/system`}>
<Menu.Item>
<Icon name='cogs'/>System
</Menu.Item>
@@ -242,14 +243,15 @@ class App extends Component {
</Sidebar>
<Sidebar.Pusher className='app-content'>
<Switch>
- <Route path='*/browse' render={(props) => this.withTokenCheck(<Browse {...props}/>)}/>
- <Route path='*/users' render={(props) => this.withTokenCheck(<Users {...props}/>)}/>
- <Route path='*/chat' render={(props) => this.withTokenCheck(<Chat {...props}/>)}/>
- <Route path='*/rooms' render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/>
- <Route path='*/uploads' render={(props) => this.withTokenCheck(<Transfers {...props} direction='upload'/>)}/>
- <Route path='*/downloads' render={(props) => this.withTokenCheck(<Transfers {...props} direction='download'/>)}/>
- <Route path='*/system' render={(props) => this.withTokenCheck(<System state={applicationState} options={applicationOptions}/>)}/>
- <Route path='*/' render={(props) => this.withTokenCheck(<Search {...props}/>)}/>
+ <Route path={`${urlBase}/searches`} render={(props) => this.withTokenCheck(<Search {...props}/>)}/>
+ <Route path={`${urlBase}/browse`} render={(props) => this.withTokenCheck(<Browse {...props}/>)}/>
+ <Route path={`${urlBase}/users`} render={(props) => this.withTokenCheck(<Users {...props}/>)}/>
+ <Route path={`${urlBase}/chat`} render={(props) => this.withTokenCheck(<Chat {...props}/>)}/>
+ <Route path={`${urlBase}/rooms`} render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/>
+ <Route path={`${urlBase}/uploads`} render={(props) => this.withTokenCheck(<Transfers {...props} direction='upload'/>)}/>
+ <Route path={`${urlBase}/downloads`} render={(props) => this.withTokenCheck(<Transfers {...props} direction='download'/>)}/>
+ <Route path={`${urlBase}/system/:tab?`} render={(props) => this.withTokenCheck(<System {...props} state={applicationState} options={applicationOptions}/>)}/>
+ <Redirect from='*' to={`${urlBase}/searches`}/>
</Switch>
</Sidebar.Pusher>
</Sidebar.Pushable>
diff --git a/src/web/src/components/System/System.js b/src/web/src/components/System/System.js
index 8b0ea4d4..ca88c50d 100644
--- a/src/web/src/components/System/System.js
+++ b/src/web/src/components/System/System.js
@@ -1,24 +1,45 @@
-import React, { Component } from 'react';
+import React from 'react';
+import { useRouteMatch, useHistory, Redirect } from "react-router-dom";
+
import { Segment, Tab } from 'semantic-ui-react';
+
import './System.css';
+
import Info from './Info';
import Logs from './Logs';
import Options from './Options';
-class System extends Component {
- render = () => {
- return (
- <div className='system'>
- <Segment raised>
- <Tab panes={[
- { menuItem: 'Info', render: () => <Tab.Pane><Info state={this.props.state}/></Tab.Pane> },
- { menuItem: 'Options', render: () => <Tab.Pane className='full-height'><Options options={this.props.options}/></Tab.Pane> },
- { menuItem: 'Logs', render: () => <Tab.Pane><Logs/></Tab.Pane> },
- ]}/>
- </Segment>
- </div>
- );
+const System = ({ state = {}, options = {} }) => {
+ const { params: { tab }, ...route } = useRouteMatch();
+ const history = useHistory();
+
+ const panes = [
+ { route: 'info', menuItem: 'Info', render: () => <Tab.Pane><Info state={state}/></Tab.Pane> },
+ { route: 'options', menuItem: 'Options', render: () => <Tab.Pane className='full-height'><Options options={options}/></Tab.Pane> },
+ { route: 'logs', menuItem: 'Logs', render: () => <Tab.Pane><Logs/></Tab.Pane> },
+ ]
+
+ const activeIndex = panes.findIndex(pane => pane.route === tab)
+
+ const onTabChange = (e, { activeIndex }) => {
+ history.push(panes[activeIndex].route)
+ }
+
+ if (tab === undefined) {
+ return <Redirect to={`${route.url}/${panes[0].route}`}/>
}
-}
+
+ return (
+ <div className='system'>
+ <Segment raised>
+ <Tab
+ activeIndex={activeIndex > -1 ? activeIndex : 0}
+ panes={panes}
+ onTabChange={onTabChange}
+ />
+ </Segment>
+ </div>
+ );
+};
export default System; \ No newline at end of file
diff --git a/src/web/src/components/Users/Users.js b/src/web/src/components/Users/Users.js
index d07772e7..7927b718 100644
--- a/src/web/src/components/Users/Users.js
+++ b/src/web/src/components/Users/Users.js
@@ -45,7 +45,7 @@ const Users = (props) => {
try {
const [info, status, endpoint] = await Promise.all([
- users.getInfo({ username: selectedUsername, bypassCache: true }),
+ users.getInfo({ username: selectedUsername }),
users.getStatus({ username: selectedUsername }),
users.getEndpoint({ username: selectedUsername })
]);
diff --git a/src/web/src/config.js b/src/web/src/config.js
index ea71e9dd..6f899564 100644
--- a/src/web/src/config.js
+++ b/src/web/src/config.js
@@ -1,5 +1,7 @@
-const rootUrl = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:5000/';
-const baseUrl = `${rootUrl}api/v0`;
+const urlBase = (window.urlBase === '/' ? '' : window.urlBase) || '';
+const rootUrl = process.env.NODE_ENV === 'production' ? urlBase : `http://localhost:5000/${urlBase}`;
+const apiBaseUrl = `${rootUrl}/api/v0`;
+const hubBaseUrl = `${rootUrl}/hub`;
const tokenKey = 'slskd-token';
const tokenPassthroughValue = 'n/a';
const activeChatKey = 'slskd-active-chat';
@@ -7,8 +9,10 @@ const activeRoomKey = 'slskd-active-room';
const activeUserInfoKey = 'slskd-active-user';
export {
+ urlBase,
rootUrl,
- baseUrl,
+ apiBaseUrl,
+ hubBaseUrl,
tokenKey,
tokenPassthroughValue,
activeChatKey,
diff --git a/src/web/src/lib/api.js b/src/web/src/lib/api.js
index 73e75373..0e7d8050 100644
--- a/src/web/src/lib/api.js
+++ b/src/web/src/lib/api.js
@@ -1,8 +1,8 @@
import axios from 'axios';
-import { baseUrl } from '../config';
+import { apiBaseUrl } from '../config';
import * as session from './session';
-axios.defaults.baseURL = baseUrl;
+axios.defaults.baseURL = apiBaseUrl;
const api = axios.create({
withCredentials: true
diff --git a/src/web/src/lib/hubFactory.js b/src/web/src/lib/hubFactory.js
index a64c5c40..246e9d03 100644
--- a/src/web/src/lib/hubFactory.js
+++ b/src/web/src/lib/hubFactory.js
@@ -4,7 +4,7 @@ import {
LogLevel
} from '@microsoft/signalr'
-import { rootUrl } from '../config';
+import { hubBaseUrl } from '../config';
import * as session from '../lib/session';
export const createHubConnection = ({ url }) =>
@@ -18,6 +18,6 @@ export const createHubConnection = ({ url }) =>
.configureLogging(LogLevel.Warning)
.build();
-export const createApplicationHubConnection = () => createHubConnection({ url: `${rootUrl}hub/application` });
+export const createApplicationHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/application` });
-export const createLogsHubConnection = () => createHubConnection({ url: `${rootUrl}hub/logs` }); \ No newline at end of file
+export const createLogsHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/logs` }); \ No newline at end of file
diff --git a/src/web/src/lib/rooms.js b/src/web/src/lib/rooms.js
index c2a36187..c30a7a15 100644
--- a/src/web/src/lib/rooms.js
+++ b/src/web/src/lib/rooms.js
@@ -23,7 +23,7 @@ export const getJoined = async () => {
};
export const getMessages = async ({ roomName }) => {
- const response = (await api.get(`/rooms/joined/${roomName}/messages`)).data;
+ const response = (await api.get(`/rooms/joined/${encodeURIComponent(roomName)}/messages`)).data;
if (!Array.isArray(response)) {
console.warn('got non-array response from rooms API', response)
@@ -34,7 +34,7 @@ export const getMessages = async ({ roomName }) => {
};
export const getUsers = async ({ roomName }) => {
- const response = (await api.get(`/rooms/joined/${roomName}/users`)).data;
+ const response = (await api.get(`/rooms/joined/${encodeURIComponent(roomName)}/users`)).data;
if (!Array.isArray(response)) {
console.warn('got non-array response from rooms API', response)
@@ -45,13 +45,13 @@ export const getUsers = async ({ roomName }) => {
};
export const join = async ({ roomName }) => {
- return api.post(`/rooms/joined/${roomName}`);
+ return api.post('/rooms/joined', roomName);
};
export const leave = async ({ roomName }) => {
- return api.delete(`/rooms/joined/${roomName}`);
+ return api.delete(`/rooms/joined/${encodeURIComponent(roomName)}`);
};
export const sendMessage = async ({ roomName, message }) => {
- return api.post(`/rooms/joined/${roomName}/messages`, JSON.stringify(message));
+ return api.post(`/rooms/joined/${encodeURIComponent(roomName)}/messages`, JSON.stringify(message));
}; \ No newline at end of file
diff --git a/src/web/src/lib/users.js b/src/web/src/lib/users.js
index a8cd4f88..f79cea20 100644
--- a/src/web/src/lib/users.js
+++ b/src/web/src/lib/users.js
@@ -1,21 +1,21 @@
import api from './api';
-export const getInfo = ({ username, bypassCache = false }) => {
- return api.get(`/users/${username}/info?bypassCache=${bypassCache}`);
+export const getInfo = ({ username }) => {
+ return api.get(`/users/${encodeURIComponent(username)}/info`);
};
export const getStatus = ({ username }) => {
- return api.get(`/users/${username}/status`);
+ return api.get(`/users/${encodeURIComponent(username)}/status`);
};
export const getEndpoint = ({ username }) => {
- return api.get(`/users/${username}/endpoint`);
+ return api.get(`/users/${encodeURIComponent(username)}/endpoint`);
};
export const browse = async ({ username }) => {
- return (await api.get(`/users/${username}/browse`)).data;
+ return (await api.get(`/users/${encodeURIComponent(username)}/browse`)).data;
};
export const getBrowseStatus = ({ username }) => {
- return api.get(`/users/${username}/browse/status`);
+ return api.get(`/users/${encodeURIComponent(username)}/browse/status`);
}; \ No newline at end of file