aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2022-05-07 15:44:28 -0500
committerJP Dillingham <jpdillingham@gmail.com>2022-05-07 15:44:28 -0500
commit35091805ce75a0d1a17d9a0c1d5faeea6be925fe (patch)
tree0fa2b9a98bebca4aef355c4ac121f5a24b6c4614 /src
parent581fa92428ec49f63421119a7bfcfef4e46df80a (diff)
parentb8f0e6f28ab3f189a47eb373b1efbb45abb9ccc8 (diff)
downloadslskd-35091805ce75a0d1a17d9a0c1d5faeea6be925fe.tar.gz
Merge remote-tracking branch 'origin/master' into search-list
Diffstat (limited to 'src')
-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/Options.cs1
-rw-r--r--src/slskd/Program.cs91
-rw-r--r--src/web/src/components/App.js38
-rw-r--r--src/web/src/components/Search/Response.js26
-rw-r--r--src/web/src/components/Search/Search.js13
-rw-r--r--src/web/src/components/System/System.js51
-rw-r--r--src/web/src/components/Transfers/TransferGroup.js30
-rw-r--r--src/web/src/config.js18
-rw-r--r--src/web/src/lib/api.js6
-rw-r--r--src/web/src/lib/hubFactory.js8
14 files changed, 481 insertions, 130 deletions
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/Options.cs b/src/slskd/Options.cs
index 00ae670e..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";
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index e21bf52e..94cd0eba 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -603,57 +603,34 @@ namespace slskd
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.Use((context, next) =>
- {
- context.Response.OnStarting(() =>
- {
- // the UI needs to be aware of what the URL base is,
- // so that react-router can use explicit paths.
- context.Response.Headers.Add("X-URL-Base", urlBase);
- return Task.CompletedTask;
- });
-
- return next();
- });
-
+ app.UseHTMLRewrite("((\\.)?\\/static)", $"{(urlBase == "/" ? string.Empty : urlBase)}/static");
+ app.UseHTMLInjection($"<script>window.urlBase=\"{urlBase}\"</script>");
Log.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();
- });
-
// serve static content from the configured path
FileServerOptions fileServerOptions = default;
-
var contentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath);
- if (!System.IO.Directory.Exists(contentPath))
- {
- Log.Warning($"Static content disabled; cannot find content path '{contentPath}'");
- }
- else
+ fileServerOptions = new FileServerOptions
{
- 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);
- }
+ 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)
{
@@ -685,6 +662,18 @@ namespace slskd
}
});
+ // 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();
@@ -694,12 +683,12 @@ namespace slskd
Log.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
+ // 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) =>
{
- // exclude API routes which are not matched or return a 404
- if (!context.Request.Path.StartsWithSegments("/api"))
+ if (Path.GetExtension(context.Request.Path.ToString()) == string.Empty)
{
context.Request.Path = "/";
}
@@ -707,12 +696,8 @@ namespace slskd
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);
- }
+ // either serve the index, or 404
+ app.UseFileServer(fileServerOptions);
return app;
}
diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js
index 75db94b2..09f3f742 100644
--- a/src/web/src/components/App.js
+++ b/src/web/src/components/App.js
@@ -1,16 +1,14 @@
import React, { Component } from 'react';
import { Route, Link, Switch, Redirect } from "react-router-dom";
-import { reactRouterBaseUrl } from '../config';
-
import * as session from '../lib/session';
import { connect, disconnect } from '../lib/server';
+import { urlBase } from '../config';
import { createApplicationHubConnection } from '../lib/hubFactory';
import './App.css';
import Search from './Search/Search';
-import Searches from './Search/Searches';
import Browse from './Browse/Browse';
import Users from './Users/Users';
import Transfers from './Transfers/Transfers';
@@ -153,37 +151,37 @@ class App extends Component {
{version.isCanary && <Menu.Item>
<Icon name='flask' color='yellow'/>Canary
</Menu.Item>}
- <Link to={`${reactRouterBaseUrl}/searches`}>
+ <Link to={`${urlBase}/searches`}>
<Menu.Item>
<Icon name='search'/>Search
</Menu.Item>
</Link>
- <Link to={`${reactRouterBaseUrl}/downloads`}>
+ <Link to={`${urlBase}/downloads`}>
<Menu.Item>
<Icon name='download'/>Downloads
</Menu.Item>
</Link>
- <Link to={`${reactRouterBaseUrl}/uploads`}>
+ <Link to={`${urlBase}/uploads`}>
<Menu.Item>
<Icon name='upload'/>Uploads
</Menu.Item>
</Link>
- <Link to={`${reactRouterBaseUrl}/rooms`}>
+ <Link to={`${urlBase}/rooms`}>
<Menu.Item>
<Icon name='comments'/>Rooms
</Menu.Item>
</Link>
- <Link to={`${reactRouterBaseUrl}/chat`}>
+ <Link to={`${urlBase}/chat`}>
<Menu.Item>
<Icon name='comment'/>Chat
</Menu.Item>
</Link>
- <Link to={`${reactRouterBaseUrl}/users`}>
+ <Link to={`${urlBase}/users`}>
<Menu.Item>
<Icon name='users'/>Users
</Menu.Item>
</Link>
- <Link to={`${reactRouterBaseUrl}/browse`}>
+ <Link to={`${urlBase}/browse`}>
<Menu.Item>
<Icon name='folder open'/>Browse
</Menu.Item>
@@ -224,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>
@@ -245,15 +243,15 @@ class App extends Component {
</Sidebar>
<Sidebar.Pusher className='app-content'>
<Switch>
- <Route path='*/searches' render={(props) => this.withTokenCheck(<Searches {...props}/>)}/>
- <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}/>)}/>
- <Redirect from='*' to='/searches'/>
+ <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/Search/Response.js b/src/web/src/components/Search/Response.js
index 9b8d0e49..8d134047 100644
--- a/src/web/src/components/Search/Response.js
+++ b/src/web/src/components/Search/Response.js
@@ -28,13 +28,17 @@ class Response extends Component {
state = {
tree: buildTree(this.props.response),
downloadRequest: undefined,
- downloadError: ''
+ downloadError: '',
+ isFolded: this.props.isInitiallyFolded,
}
componentDidUpdate = (prevProps) => {
if (JSON.stringify(this.props.response) !== JSON.stringify(prevProps.response)) {
this.setState({ tree: buildTree(this.props.response) });
}
+ if (this.props.isInitiallyFolded !== prevProps.isInitiallyFolded) {
+ this.setState({ isFolded: this.props.isInitiallyFolded });
+ }
}
onFileSelectionChange = (file, state) => {
@@ -55,11 +59,15 @@ class Response extends Component {
});
}
+ toggleFolded = () => {
+ this.setState({ isFolded: !this.state.isFolded });
+ }
+
render = () => {
let response = this.props.response;
let free = response.freeUploadSlots > 0;
- let { tree, downloadRequest, downloadError } = this.state;
+ let { tree, downloadRequest, downloadError, isFolded } = this.state;
let selectedFiles = Object.keys(tree)
.reduce((list, dict) => list.concat(tree[dict]), [])
@@ -71,20 +79,18 @@ class Response extends Component {
<Card className='result-card' raised>
<Card.Content>
<Card.Header>
- <Icon name='circle' color={free ? 'green' : 'yellow'}/>
- {response.username}
- <Icon
- className='close-button'
- name='close'
- color='red'
+ <Icon
link
- onClick={() => this.props.onHide()}
+ name={isFolded ? 'chevron right' : 'chevron down'}
+ onClick={this.toggleFolded}
/>
+ <Icon name='circle' color={free ? 'green' : 'yellow'}/>
+ {response.username}
</Card.Header>
<Card.Meta className='result-meta'>
<span>Upload Speed: {formatBytes(response.uploadSpeed)}/s, Free Upload Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength}</span>
</Card.Meta>
- {(Object.keys(tree) || []).map((dir, i) =>
+ {((!isFolded && Object.keys(tree)) || []).map((dir, i) =>
<FileList
key={i}
directoryName={dir}
diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js
index 887937b3..4f270a5d 100644
--- a/src/web/src/components/Search/Search.js
+++ b/src/web/src/components/Search/Search.js
@@ -33,7 +33,8 @@ const initialState = {
hiddenResults: [],
hideLocked: true,
fetching: false,
- resultFilters: ''
+ resultFilters: '',
+ foldResults: false,
};
const sortOptions = {
@@ -205,7 +206,7 @@ class Search extends Component {
}
render = () => {
- let { searchState, searchStatus, results = [], displayCount, resultSort, hideNoFreeSlots, hideLocked, hiddenResults = [], fetching, resultFilters } = this.state;
+ let { searchState, searchStatus, results = [], displayCount, resultSort, hideNoFreeSlots, hideLocked, hiddenResults = [], fetching, resultFilters, foldResults } = this.state;
let pending = fetching || searchState === 'pending';
const sortedAndFilteredResults = this.sortAndFilterResults();
@@ -272,6 +273,13 @@ class Search extends Component {
checked={hideNoFreeSlots}
label='Hide Results with No Free Slots'
/>
+ <Checkbox
+ className='search-options-fold-results'
+ toggle
+ onChange={() => this.setState({ foldResults: !foldResults }, () => this.saveState())}
+ checked={foldResults}
+ label='Fold Results'
+ />
</div>
<Input
className='search-filter'
@@ -289,6 +297,7 @@ class Search extends Component {
response={r}
onDownload={this.props.onDownload}
onHide={() => this.hideResult(r)}
+ isInitiallyFolded={foldResults}
/>
)}
{remainingCount > 0 ?
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/Transfers/TransferGroup.js b/src/web/src/components/Transfers/TransferGroup.js
index 371f0418..35955120 100644
--- a/src/web/src/components/Transfers/TransferGroup.js
+++ b/src/web/src/components/Transfers/TransferGroup.js
@@ -3,16 +3,20 @@ import * as transfers from '../../lib/transfers';
import {
Card,
- Button
+ Button,
+ Icon
} from 'semantic-ui-react';
import TransferList from './TransferList';
class TransferGroup extends Component {
- state = { selections: new Set() }
+ state = {
+ selections: new Set(),
+ isFolded: false
+ }
onSelectionChange = (directoryName, file, selected) => {
- const { selections } = this.state;
+ const selections = this.state.selections;
const obj = JSON.stringify({ directory: directoryName, filename: file.filename });
selected ? selections.add(obj) : selections.delete(obj);
@@ -34,7 +38,7 @@ class TransferGroup extends Component {
}
removeFileSelection = (file) => {
- const { selections } = this.state;
+ const selections = this.state.selections;
const match = Array.from(selections)
.map(s => JSON.parse(s))
@@ -83,9 +87,14 @@ class TransferGroup extends Component {
console.log(error);
}
}
-
+
+ toggleFolded = () => {
+ this.setState({'isFolded': !this.state.isFolded});
+ }
+
render = () => {
const { user, direction } = this.props;
+ const isFolded = this.state.isFolded;
const selected = this.getSelectedFiles();
const all = selected.length > 1 ? ' Selected' : '';
@@ -97,8 +106,15 @@ class TransferGroup extends Component {
return (
<Card key={user.username} className='transfer-card' raised>
<Card.Content>
- <Card.Header>{user.username}</Card.Header>
- {user.directories && user.directories
+ <Card.Header>
+ <Icon
+ link
+ name={isFolded ? 'chevron right' : 'chevron down'}
+ onClick={() => this.toggleFolded()}
+ />
+ {user.username}
+ </Card.Header>
+ {user.directories && !isFolded && user.directories
.map((dir, index) =>
<TransferList
key={index}
diff --git a/src/web/src/config.js b/src/web/src/config.js
index 4e0781f5..ca9f58b2 100644
--- a/src/web/src/config.js
+++ b/src/web/src/config.js
@@ -1,24 +1,18 @@
-const rootUrl = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:5000/';
-const apiBaseUrl = `${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';
const activeRoomKey = 'slskd-active-room';
const activeUserInfoKey = 'slskd-active-user';
-// url base is the value of the url base from config;
-// the route used when behind a reverse proxy. we
-// need this value so we can be explicit with react-router.
-let reactRouterBaseUrl;
-
-const setReactRouterBaseUrl = (url) => {
- reactRouterBaseUrl = (url === '/' ? '' : url);
-};
-
export {
+ urlBase,
rootUrl,
apiBaseUrl,
- reactRouterBaseUrl,
+ hubBaseUrl,
tokenKey,
tokenPassthroughValue,
activeChatKey,
diff --git a/src/web/src/lib/api.js b/src/web/src/lib/api.js
index 02fe2eca..0e7d8050 100644
--- a/src/web/src/lib/api.js
+++ b/src/web/src/lib/api.js
@@ -1,5 +1,5 @@
import axios from 'axios';
-import { apiBaseUrl, setReactRouterBaseUrl } from '../config';
+import { apiBaseUrl } from '../config';
import * as session from './session';
axios.defaults.baseURL = apiBaseUrl;
@@ -21,10 +21,6 @@ api.interceptors.request.use(config => {
});
api.interceptors.response.use(response => {
- // when behind a reverse proxy, we need the configured url base
- // so that we can be explicit with react-router. every API response
- // should contain this header, and it should be the same.
- setReactRouterBaseUrl(response.headers['x-url-base']);
return response;
}, error => {
if (error.response.status === 401 && !['/session', '/server', '/application'].includes(error.response.config.url)) {
diff --git a/src/web/src/lib/hubFactory.js b/src/web/src/lib/hubFactory.js
index e0205ec9..2b876710 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,8 +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` });
-
-export const createSearchLogHubConnection = () => createHubConnection({ url: `${rootUrl}hub/search` }); \ No newline at end of file
+export const createLogsHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/logs` });