diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-06-24 09:42:34 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-06-24 09:42:34 -0500 |
| commit | d0ae5db8e0ebb989c6470c3b8f1c1793dafb1d8f (patch) | |
| tree | be15aee66b361efe6e6d2c97db59236be4c0202f /src | |
| parent | 73f5c8a5cbe56745156d24b6c744cbe24567c23f (diff) | |
| parent | 7383d448e7481ca5dc046b8118e5709ab571b69f (diff) | |
| download | slskd-d0ae5db8e0ebb989c6470c3b8f1c1793dafb1d8f.tar.gz | |
Merge pull request #102 from slskd/connections
Add the ability to connect and disconnect the client from the API/UI
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application/Exceptions/IntentionalDisconnectException.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Application/Management/API/Controllers/ServerController.cs | 58 | ||||
| -rw-r--r-- | src/slskd/Application/Management/Domain/ServerState.cs (renamed from src/slskd/Application/Management/API/DTO/ConnectRequest.cs) | 16 | ||||
| -rw-r--r-- | src/slskd/Application/Management/IManagementService.cs | 47 | ||||
| -rw-r--r-- | src/slskd/Application/Management/ManagementService.cs | 73 | ||||
| -rw-r--r-- | src/slskd/Application/Service.cs | 16 | ||||
| -rw-r--r-- | src/slskd/Startup.cs | 2 | ||||
| -rw-r--r-- | src/web/src/components/App.css | 15 | ||||
| -rw-r--r-- | src/web/src/components/App.js | 62 | ||||
| -rw-r--r-- | src/web/src/lib/server.js | 13 |
10 files changed, 333 insertions, 41 deletions
diff --git a/src/slskd/Application/Exceptions/IntentionalDisconnectException.cs b/src/slskd/Application/Exceptions/IntentionalDisconnectException.cs new file mode 100644 index 00000000..d5293e63 --- /dev/null +++ b/src/slskd/Application/Exceptions/IntentionalDisconnectException.cs @@ -0,0 +1,72 @@ +// <copyright file="IntentionalDisconnectException.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.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents an intentional client disconnect. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class IntentionalDisconnectException : SlskdException + { + /// <summary> + /// Initializes a new instance of the <see cref="IntentionalDisconnectException"/> class. + /// </summary> + public IntentionalDisconnectException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="IntentionalDisconnectException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public IntentionalDisconnectException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="IntentionalDisconnectException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public IntentionalDisconnectException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="IntentionalDisconnectException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected IntentionalDisconnectException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Application/Management/API/Controllers/ServerController.cs b/src/slskd/Application/Management/API/Controllers/ServerController.cs index ed911a13..6468063c 100644 --- a/src/slskd/Application/Management/API/Controllers/ServerController.cs +++ b/src/slskd/Application/Management/API/Controllers/ServerController.cs @@ -20,7 +20,6 @@ namespace slskd.Management.API using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; - using Soulseek; /// <summary> /// Server. @@ -32,40 +31,31 @@ namespace slskd.Management.API [Consumes("application/json")] public class ServerController : ControllerBase { - public ServerController(ISoulseekClient client) + public ServerController( + IManagementService managementService) { - Client = client; + Management = managementService; } - private ISoulseekClient Client { get; } + private IManagementService Management { get; } /// <summary> /// Connects the client. /// </summary> - /// <param name="req"></param> /// <returns></returns> - [HttpPost] + [HttpPut] + [Route("")] [Authorize] - public async Task<IActionResult> Connect([FromBody] ConnectRequest req) + [ProducesResponseType(200)] + [ProducesResponseType(403)] + public async Task<IActionResult> Connect() { - var addr = !string.IsNullOrEmpty(req.Address); - var port = req.Port.HasValue; - var un = !string.IsNullOrEmpty(req.Username); - var pw = !string.IsNullOrEmpty(req.Password); - - if (addr && port && un && pw) - { - await Client.ConnectAsync(req.Address, req.Port.Value, req.Username, req.Password); - return Ok(); - } - - if (!addr && !port && un && pw) + if (!Management.GetServerState().IsConnected) { - await Client.ConnectAsync(req.Username, req.Password); - return Ok(); + await Management.ConnectServerAsync(); } - return BadRequest("Provide one of the following: address and port, username and password, or address, port, username and password"); + return Ok(); } /// <summary> @@ -74,11 +64,33 @@ namespace slskd.Management.API /// <param name="message"></param> /// <returns></returns> [HttpDelete] + [Route("")] [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(403)] public IActionResult Disconnect([FromBody] string message) { - Client.Disconnect(message); + if (Management.GetServerState().IsConnected) + { + Management.DisconnectServer(message); + } + return NoContent(); } + + /// <summary> + /// Retrieves the current state of the server. + /// </summary> + /// <returns></returns> + /// <response code="200"></response> + [HttpGet] + [Route("")] + [Authorize] + [ProducesResponseType(typeof(ServerState), 200)] + [ProducesResponseType(403)] + public IActionResult Get() + { + return Ok(Management.GetServerState()); + } } }
\ No newline at end of file diff --git a/src/slskd/Application/Management/API/DTO/ConnectRequest.cs b/src/slskd/Application/Management/Domain/ServerState.cs index e53dece7..80c1e856 100644 --- a/src/slskd/Application/Management/API/DTO/ConnectRequest.cs +++ b/src/slskd/Application/Management/Domain/ServerState.cs @@ -1,4 +1,4 @@ -// <copyright file="ConnectRequest.cs" company="slskd Team"> +// <copyright file="ServerState.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -15,13 +15,19 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Management.API +namespace slskd.Management { - public class ConnectRequest + using System.Net; + using Soulseek; + + public class ServerState { public string Address { get; set; } - public int? Port { get; set; } + public IPEndPoint IPEndPoint { get; set; } + public SoulseekClientStates State { get; set; } public string Username { get; set; } - public string Password { get; set; } + public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); + public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); + public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); } } diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs new file mode 100644 index 00000000..4ee2185e --- /dev/null +++ b/src/slskd/Application/Management/IManagementService.cs @@ -0,0 +1,47 @@ +// <copyright file="IManagementService.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.Management +{ + using System; + using System.Threading.Tasks; + + /// <summary> + /// Application and Soulseek client management. + /// </summary> + public interface IManagementService + { + /// <summary> + /// Disconnects the Soulseek client from the server. + /// </summary> + /// <param name="message">An optional message containing the reason for the disconnect.</param> + /// <param name="exception">An optional Exception to associate with the disconnect.</param> + void DisconnectServer(string message = null, Exception exception = null); + + /// <summary> + /// Connects the Soulseek client to the server using the configured username and password. + /// </summary> + /// <returns>The operation context.</returns> + Task ConnectServerAsync(); + + /// <summary> + /// Gets the current state of the connection to the Soulseek server. + /// </summary> + /// <returns>The current server state.</returns> + ServerState GetServerState(); + } +} diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs new file mode 100644 index 00000000..84935879 --- /dev/null +++ b/src/slskd/Application/Management/ManagementService.cs @@ -0,0 +1,73 @@ +// <copyright file="ManagementService.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.Management +{ + using System; + using System.Threading.Tasks; + using Soulseek; + + /// <summary> + /// Application and Soulseek client management. + /// </summary> + public class ManagementService : IManagementService + { + /// <summary> + /// Initializes a new instance of the <see cref="ManagementService"/> class. + /// </summary> + /// <param name="optionsMonitor">The options monitor used to derive application options.</param> + /// <param name="soulseekClient">The Soulseek client.</param> + public ManagementService( + Microsoft.Extensions.Options.IOptionsMonitor<Options> optionsMonitor, + ISoulseekClient soulseekClient) + { + Options = optionsMonitor.CurrentValue; + Client = soulseekClient; + } + + private ISoulseekClient Client { get; } + private Options Options { get; } + + /// <summary> + /// Disconnects the Soulseek client from the server. + /// </summary> + /// <param name="message">An optional message containing the reason for the disconnect.</param> + /// <param name="exception">An optional Exception to associate with the disconnect.</param> + public void DisconnectServer(string message = null, Exception exception = null) + => Client.Disconnect(message, exception ?? new IntentionalDisconnectException(message)); + + /// <summary> + /// Connects the Soulseek client to the server using the configured username and password. + /// </summary> + /// <returns>The operation context.</returns> + public Task ConnectServerAsync() + => Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + + /// <summary> + /// Gets the current state of the connection to the Soulseek server. + /// </summary> + /// <returns>The current server state.</returns> + public ServerState GetServerState() => + new ServerState() + { + Address = Client.Address, + IPEndPoint = Client.IPEndPoint, + State = Client.State, + Username = Client.Username, + }; + } +} diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 246e7fc6..60fae0cc 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -121,6 +121,7 @@ namespace slskd Client.RoomLeft += Client_RoomLeft; Client.Disconnected += Client_Disconnected; Client.Connected += Client_Connected; + Client.LoggedIn += Client_LoggedIn; SoulseekClient = Client; @@ -207,14 +208,23 @@ namespace slskd private void Client_Connected(object sender, EventArgs e) { - Logger.Information("Connected and logged in as {Username}", Options.Soulseek.Username); + Logger.Information("Connected to the Soulseek server"); + } + + private void Client_LoggedIn(object sender, EventArgs e) + { + Logger.Information("Logged in to the Soulseek server as {Username}", Options.Soulseek.Username); } private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) { if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException) { - Logger.Debug("Disconnected from the Soulseek server: the client is shutting down"); + Logger.Information("Disconnected from the Soulseek server: the client is shutting down"); + } + else if (args.Exception is IntentionalDisconnectException) + { + Logger.Information("Disconnected from the Soulseek server: disconnected by the user"); } else if (args.Exception is LoginRejectedException) { @@ -226,7 +236,7 @@ namespace slskd } else { - Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception.Message); + Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); var attempts = 1; diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 2f35e6fc..dd44fd87 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -35,6 +35,7 @@ namespace slskd using Serilog; using slskd.Authentication; using slskd.Cryptography; + using slskd.Management; using slskd.Messaging; using slskd.Peer; using slskd.Search; @@ -184,6 +185,7 @@ namespace slskd services.AddSingleton<ISearchService, SearchService>(); services.AddSingleton<IPeerService, PeerService>(); + services.AddSingleton<IManagementService, ManagementService>(); services.AddHostedService<Service>(); services.AddSingleton(_ => Service.SoulseekClient); diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css index 99d3767a..8fbb639d 100644 --- a/src/web/src/components/App.css +++ b/src/web/src/components/App.css @@ -7,6 +7,10 @@ body { padding-bottom: 5px !important; } +.ui.inverted.menu .item:before { + background: rgba(255,255,255, 0); +} + .app { margin: auto; border: 0px !important; @@ -122,4 +126,15 @@ body { .placeholder-segment { opacity: .25; +} + +.menu-icon-group { + font-size: 1.71428571em !important; + margin: 0 auto .5rem !important; + text-shadow: unset !important; +} + +.menu-icon-no-shadow { + font-size: 1rem !important; + text-shadow: unset !important; }
\ No newline at end of file diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 26ff028d..d3c0156c 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -2,6 +2,7 @@ import React, { Component } from 'react'; import { Route, Link, Switch } from "react-router-dom"; import { tokenKey, tokenPassthroughValue } from '../config'; import * as session from '../lib/session'; +import * as server from '../lib/server'; import './App.css'; import Search from './Search/Search'; @@ -27,7 +28,9 @@ const initialState = { initialized: false, pending: false, error: undefined - } + }, + serverStateInterval: undefined, + serverState: {} }; class App extends Component { @@ -35,6 +38,8 @@ class App extends Component { componentDidMount = async () => { const { login } = this.state; + + await this.fetchServerState(); const securityEnabled = await session.getSecurityEnabled(); if (!securityEnabled) { @@ -46,11 +51,17 @@ class App extends Component { login: { ...login, initialized: true - } + }, + serverStateInterval: window.setInterval(this.fetchServerState, 5000) }); await this.checkToken(); - } + }; + + componentWillUnmount = () => { + clearInterval(this.state.serverStateInterval); + this.setState({ serverStateInterval: undefined }); + }; checkToken = async () => { try { @@ -58,7 +69,7 @@ class App extends Component { } catch (error) { this.logout(); } - } + }; getToken = () => JSON.parse(sessionStorage.getItem(tokenKey) || localStorage.getItem(tokenKey)); setToken = (storage, token) => storage.setItem(tokenKey, JSON.stringify(token)); @@ -73,21 +84,37 @@ class App extends Component { this.setState({ login: { ...this.state.login, pending: false, error }}); } }); - } + }; logout = () => { localStorage.removeItem(tokenKey); sessionStorage.removeItem(tokenKey); this.setState({ ...initialState, login: { ...initialState.login, initialized: true }}); - } + }; withTokenCheck = (component) => { this.checkToken(); // async, runs in the background return { ...component }; + }; + + connect = async () => { + await server.connect(); + this.fetchServerState(); + }; + + disconnect = async () => { + await server.disconnect(); + this.fetchServerState(); } + fetchServerState = async () => { + this.setState({ + serverState: await server.getState() + }); + }; + render = () => { - const { token, login } = this.state; + const { token, login, serverState } = this.state; return ( <> @@ -143,9 +170,24 @@ class App extends Component { <Icon name='folder open'/>Browse </Menu.Item> </Link> + {serverState.isConnected && <Menu.Item + position='right' + onClick={() => this.disconnect()} + > + <Icon name='wifi' color='green'/>Connected + </Menu.Item>} + {(!serverState.isConnected || serverState.isTransitioning) && <Menu.Item + position='right' + onClick={() => this.connect()} + > + <Icon.Group className='menu-icon-group'> + <Icon name='wifi' color='grey'/> + <Icon name='close' color='red' corner='bottom right' className='menu-icon-no-shadow'/> + </Icon.Group>Disconnected + </Menu.Item>} {token !== tokenPassthroughValue && <Modal trigger={ - <Menu.Item position='right'> + <Menu.Item> <Icon name='sign-out'/>Log Out </Menu.Item> } @@ -171,7 +213,7 @@ class App extends Component { } </> ) - } -} + }; +}; export default App; diff --git a/src/web/src/lib/server.js b/src/web/src/lib/server.js new file mode 100644 index 00000000..13881df7 --- /dev/null +++ b/src/web/src/lib/server.js @@ -0,0 +1,13 @@ +import api from './api'; + +export const getState = async () => { + return (await api.get('/server')).data; +}; + +export const connect = () => { + return api.put('/server'); +}; + +export const disconnect = ({ message = 'client disconnected from web UI' } = {}) => { + return api.delete('/server', { data: JSON.stringify(message) }); +};
\ No newline at end of file |
