aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/API
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-06-14 20:03:36 -0500
committerJP Dillingham <jpdillingham@gmail.com>2021-06-14 20:03:36 -0500
commit050be311e68bb316cfc40fbd23bfd5a812e1a060 (patch)
tree1476cba9e90845f224bbc0a380e4633697e1306e /src/slskd/API
parent4cf8f8fa862b08131e9cc51c4bad3d6c9838342b (diff)
downloadslskd-050be311e68bb316cfc40fbd23bfd5a812e1a060.tar.gz
move stuff around
Diffstat (limited to 'src/slskd/API')
-rw-r--r--src/slskd/API/Authentication/PassthroughAuthentication.cs91
-rw-r--r--src/slskd/API/Controllers/ApplicationController.cs76
-rw-r--r--src/slskd/API/Controllers/ConversationsController.cs214
-rw-r--r--src/slskd/API/Controllers/PeersController.cs171
-rw-r--r--src/slskd/API/Controllers/PublicChatController.cs67
-rw-r--r--src/slskd/API/Controllers/RoomsController.cs303
-rw-r--r--src/slskd/API/Controllers/SearchesController.cs137
-rw-r--r--src/slskd/API/Controllers/ServerController.cs85
-rw-r--r--src/slskd/API/Controllers/SessionController.cs144
-rw-r--r--src/slskd/API/Controllers/TransfersController.cs321
-rw-r--r--src/slskd/API/DTO/ConnectRequest.cs27
-rw-r--r--src/slskd/API/DTO/LoginRequest.cs25
-rw-r--r--src/slskd/API/DTO/PrivateMessageResponse.cs74
-rw-r--r--src/slskd/API/DTO/QueueDownloadRequest.cs37
-rw-r--r--src/slskd/API/DTO/RoomInfoResponse.cs60
-rw-r--r--src/slskd/API/DTO/RoomMessageResponse.cs62
-rw-r--r--src/slskd/API/DTO/RoomResponse.cs75
-rw-r--r--src/slskd/API/DTO/SearchRequest.cs116
-rw-r--r--src/slskd/API/DTO/TokenResponse.cs67
-rw-r--r--src/slskd/API/DTO/Transfer.cs148
-rw-r--r--src/slskd/API/DTO/UserDataResponse.cs85
21 files changed, 0 insertions, 2385 deletions
diff --git a/src/slskd/API/Authentication/PassthroughAuthentication.cs b/src/slskd/API/Authentication/PassthroughAuthentication.cs
deleted file mode 100644
index 65bbb7db..00000000
--- a/src/slskd/API/Authentication/PassthroughAuthentication.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-// <copyright file="PassthroughAuthentication.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.API.Authentication
-{
- using System.Security.Principal;
- using System.Text.Encodings.Web;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
-
- /// <summary>
- /// Passthrough authentication.
- /// </summary>
- public static class PassthroughAuthentication
- {
- /// <summary>
- /// Gets the Passthrough authentication scheme name.
- /// </summary>
- public static string AuthenticationScheme { get; } = "Passthrough";
- }
-
- /// <summary>
- /// Handles passthrough authentication.
- /// </summary>
- public class PassthroughAuthenticationHandler : AuthenticationHandler<PassthroughAuthenticationOptions>
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="PassthroughAuthenticationHandler"/> class.
- /// </summary>
- /// <param name="optionsMonitor">An options monitor.</param>
- /// <param name="logger">A logger factory.</param>
- /// <param name="urlEncoder">A url encoder.</param>
- /// <param name="systemClock">A system clock interface.</param>
- public PassthroughAuthenticationHandler(IOptionsMonitor<PassthroughAuthenticationOptions> optionsMonitor, ILoggerFactory logger, UrlEncoder urlEncoder, ISystemClock systemClock)
- : base(optionsMonitor, logger, urlEncoder, systemClock)
- {
- }
-
- /// <summary>
- /// Authenticates using the configured <see cref="PassthroughAuthenticationOptions.Username"/> and <see cref="PassthroughAuthenticationOptions.Role"/>.
- /// </summary>
- /// <returns>A successful authentication result containing a default ticket.</returns>
- protected override Task<AuthenticateResult> HandleAuthenticateAsync()
- {
- var identity = new GenericIdentity(Options.Username);
- var principal = new GenericPrincipal(identity, new[] { Options.Role.ToString() });
- var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), PassthroughAuthentication.AuthenticationScheme);
-
- return Task.FromResult(AuthenticateResult.Success(ticket));
- }
- }
-
- /// <summary>
- /// Passthrough authentication options.
- /// </summary>
- public class PassthroughAuthenticationOptions : AuthenticationSchemeOptions
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="PassthroughAuthenticationOptions"/> class.
- /// </summary>
- public PassthroughAuthenticationOptions()
- {
- }
-
- /// <summary>
- /// Gets or sets the username for the passed-through authentication ticket.
- /// </summary>
- public string Username { get; set; } = "Anonymous";
-
- /// <summary>
- /// Gets or sets the role for the passed-through authentication ticket.
- /// </summary>
- public Role Role { get; set; } = Role.Administrator;
- }
-}
diff --git a/src/slskd/API/Controllers/ApplicationController.cs b/src/slskd/API/Controllers/ApplicationController.cs
deleted file mode 100644
index 4b70b654..00000000
--- a/src/slskd/API/Controllers/ApplicationController.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-// <copyright file="ApplicationController.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.API.Controllers
-{
- using System;
- using System.Diagnostics;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Hosting;
- using Soulseek;
-
- /// <summary>
- /// Application.
- /// </summary>
- [Route("api/v{version:apiVersion}/[controller]")]
- [ApiVersion("0")]
- [ApiController]
- [Produces("application/json")]
- [Consumes("application/json")]
- public class ApplicationController : ControllerBase
- {
- public ApplicationController(ISoulseekClient client, IHostApplicationLifetime lifetime)
- {
- Client = client;
- Lifetime = lifetime;
- }
-
- private ISoulseekClient Client { get; }
- private IHostApplicationLifetime Lifetime { get; }
-
- /// <summary>
- /// Stops the application.
- /// </summary>
- /// <returns></returns>
- [HttpDelete]
- [Authorize]
- public IActionResult Shutdown()
- {
- Client.Disconnect("Shut down via API");
-
- Lifetime.StopApplication();
- return NoContent();
- }
-
- /// <summary>
- /// Restarts the application.
- /// </summary>
- /// <returns></returns>
- [HttpPut]
- [Authorize]
- public IActionResult Restart()
- {
- Client.Disconnect("Restarted via API");
-
- Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine);
- Lifetime.StopApplication();
-
- return NoContent();
- }
- }
-}
diff --git a/src/slskd/API/Controllers/ConversationsController.cs b/src/slskd/API/Controllers/ConversationsController.cs
deleted file mode 100644
index dafe5a71..00000000
--- a/src/slskd/API/Controllers/ConversationsController.cs
+++ /dev/null
@@ -1,214 +0,0 @@
-// <copyright file="ConversationsController.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.API.Controllers
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using slskd.API.DTO;
- using slskd.Messaging;
- using Soulseek;
-
- /// <summary>
- /// Conversations.
- /// </summary>
- [Route("api/v{version:apiVersion}/[controller]")]
- [ApiVersion("0")]
- [ApiController]
- [Produces("application/json")]
- [Consumes("application/json")]
- public class ConversationsController : ControllerBase
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ConversationsController"/> class.
- /// </summary>
- /// <param name="client"></param>
- /// <param name="tracker"></param>
- public ConversationsController(ISoulseekClient client, IConversationTracker tracker)
- {
- Client = client;
- Tracker = tracker;
- }
-
- private ISoulseekClient Client { get; }
- private IConversationTracker Tracker { get; }
-
- /// <summary>
- /// Acknowledges the given message id for the given username.
- /// </summary>
- /// <param name="username"></param>
- /// <param name="id"></param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- /// <response code="404">
- /// A conversation with the specified username, or a message matching the specified id could not be found.
- /// </response>
- [HttpPut("{username}/{id}")]
- [Authorize]
- [ProducesResponseType(200)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> Acknowledge([FromRoute]string username, [FromRoute]int id)
- {
- Tracker.Conversations.TryGetValue(username, out var conversation);
-
- if (conversation == default || !conversation.Any(p => p.Id == id))
- {
- return NotFound();
- }
-
- await Client.AcknowledgePrivateMessageAsync(id);
- return StatusCode(200);
- }
-
- /// <summary>
- /// Acknowledges all messages for the given username.
- /// </summary>
- /// <param name="username"></param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- /// <response code="404">A conversation with the specified username could not be found.</response>
- [HttpPut("{username}")]
- [Authorize]
- [ProducesResponseType(200)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> AcknowledgeAll([FromRoute]string username)
- {
- Tracker.Conversations.TryGetValue(username, out var conversation);
-
- if (conversation == default)
- {
- return NotFound();
- }
-
- var tasks = new List<Task>();
-
- foreach (var message in conversation.Where(p => !p.Acknowledged))
- {
- tasks.Add(Task.Run(async () =>
- {
- await Client.AcknowledgePrivateMessageAsync(message.Id);
- message.Acknowledged = true;
- }));
- }
-
- await Task.WhenAll(tasks);
- return StatusCode(200);
- }
-
- /// <summary>
- /// Deletes the conversation associated with the given username.
- /// </summary>
- /// <returns></returns>
- /// <response code="204">The request completed successfully.</response>
- /// <response code="404">A conversation with the specified username could not be found.</response>
- [HttpDelete("{username}")]
- [Authorize]
- [ProducesResponseType(404)]
- [ProducesResponseType(204)]
- public IActionResult Delete([FromRoute]string username)
- {
- var deleted = Tracker.Conversations.TryRemove(username, out _);
-
- if (deleted)
- {
- return StatusCode(204);
- }
-
- return StatusCode(404);
- }
-
- /// <summary>
- /// Gets all tracked conversations.
- /// </summary>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- [HttpGet("")]
- [Authorize]
- [ProducesResponseType(typeof(Dictionary<string, List<PrivateMessageResponse>>), 200)]
- public IActionResult GetAll()
- {
- var response = Tracker.Conversations.ToDictionary(
- entry => entry.Key,
- entry => entry.Value
- .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username))
- .OrderBy(m => m.Timestamp));
-
- return Ok(response);
- }
-
- /// <summary>
- /// Gets the conversation associated with the specified username.
- /// </summary>
- /// <param name="username">The username associated with the desired conversation.</param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- /// <response code="404">A matching search was not found.</response>
- [HttpGet("{username}")]
- [Authorize]
- [ProducesResponseType(typeof(List<PrivateMessageResponse>), 200)]
- [ProducesResponseType(404)]
- public IActionResult GetByUsername([FromRoute]string username)
- {
- if (Tracker.TryGet(username, out var conversation))
- {
- var response = conversation
- .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username))
- .OrderBy(m => m.Timestamp);
-
- return Ok(response);
- }
-
- return NotFound();
- }
-
- /// <summary>
- /// Sends a private message to the specified username.
- /// </summary>
- /// <param name="username"></param>
- /// <param name="message"></param>
- /// <returns></returns>
- /// <response code="201">The request completed successfully.</response>
- /// <response code="400">The specified message is null or empty.</response>
- [HttpPost("{username}")]
- [Authorize]
- [ProducesResponseType(201)]
- [ProducesResponseType(400)]
- public async Task<IActionResult> Send([FromRoute]string username, [FromBody]string message)
- {
- if (string.IsNullOrEmpty(message))
- {
- return BadRequest();
- }
-
- await Client.SendPrivateMessageAsync(username, message);
-
- Tracker.AddOrUpdate(username, new PrivateMessage()
- {
- Username = Client.Username,
- Timestamp = DateTime.UtcNow,
- Message = message,
- Acknowledged = true,
- });
-
- return StatusCode(201);
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/API/Controllers/PeersController.cs b/src/slskd/API/Controllers/PeersController.cs
deleted file mode 100644
index 81175984..00000000
--- a/src/slskd/API/Controllers/PeersController.cs
+++ /dev/null
@@ -1,171 +0,0 @@
-// <copyright file="PeersController.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.API.Controllers
-{
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Net;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using slskd.Peer;
- using Soulseek;
-
- /// <summary>
- /// Users.
- /// </summary>
- [Route("api/v{version:apiVersion}/[controller]")]
- [ApiVersion("0")]
- [ApiController]
- [Produces("application/json")]
- [Consumes("application/json")]
- public class PeersController : ControllerBase
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="PeersController"/> class.
- /// </summary>
- /// <param name="client"></param>
- /// <param name="browseTracker"></param>
- public PeersController(ISoulseekClient client, IBrowseTracker browseTracker, IPeerService peerService)
- {
- Client = client;
- BrowseTracker = browseTracker;
- Peers = peerService;
- }
-
- private IBrowseTracker BrowseTracker { get; }
- private ISoulseekClient Client { get; }
- private IPeerService Peers { get; }
-
- /// <summary>
- /// Retrieves the address of the specified <paramref name="username"/>.
- /// </summary>
- /// <param name="username">The username of the user.</param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- [HttpGet("{username}/endpoint")]
- [Authorize]
- [ProducesResponseType(typeof(IPEndPoint), 200)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> Endpoint([FromRoute, Required] string username)
- {
- try
- {
- var endpoint = await Peers.GetIPEndPointAsync(username);
- return Ok(endpoint);
- }
- catch (UserOfflineException ex)
- {
- return NotFound(ex.Message);
- }
- }
-
- /// <summary>
- /// Retrieves the files shared by the specified <paramref name="username"/>.
- /// </summary>
- /// <param name="username">The username of the user.</param>
- /// <returns></returns>
- [HttpGet("{username}/browse")]
- [Authorize]
- [ProducesResponseType(typeof(IEnumerable<Directory>), 200)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> Browse([FromRoute, Required] string username)
- {
- try
- {
- var result = await Client.BrowseAsync(username);
-
- _ = Task.Run(async () =>
- {
- await Task.Delay(5000);
- BrowseTracker.TryRemove(username);
- });
-
- return Ok(result);
- }
- catch (UserOfflineException ex)
- {
- return NotFound(ex.Message);
- }
- }
-
- /// <summary>
- /// Retrieves the status of the current browse operation for the specified <paramref name="username"/>, if any.
- /// </summary>
- /// <param name="username">The username of the user.</param>
- /// <returns></returns>
- [HttpGet("{username}/browse/status")]
- [Authorize]
- [ProducesResponseType(typeof(decimal), 200)]
- [ProducesResponseType(404)]
- public IActionResult BrowseStatus([FromRoute, Required] string username)
- {
- if (BrowseTracker.TryGet(username, out var progress))
- {
- return Ok(progress);
- }
-
- return NotFound();
- }
-
- /// <summary>
- /// Retrieves information about the specified <paramref name="username"/>.
- /// </summary>
- /// <param name="username">The username of the user.</param>
- /// <param name="bypassCache">Bypasses the internal cache and requests the latest information from the peer.</param>
- /// <returns></returns>
- [HttpGet("{username}/info")]
- [Authorize]
- [ProducesResponseType(typeof(Info), 200)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> Info([FromRoute, Required] string username, [FromQuery]bool bypassCache = false)
- {
- try
- {
- var response = await Peers.GetInfoAsync(username, bypassCache);
- return Ok(response);
- }
- catch (UserOfflineException ex)
- {
- return NotFound(ex.Message);
- }
- }
-
- /// <summary>
- /// Retrieves status for the specified <paramref name="username"/>.
- /// </summary>
- /// <param name="username">The username of the user.</param>
- /// <returns></returns>
- [HttpGet("{username}/status")]
- [Authorize]
- [ProducesResponseType(typeof(Status), 200)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> Status([FromRoute, Required] string username)
- {
- try
- {
- var response = await Peers.GetStatusAsync(username);
- return Ok(response);
- }
- catch (UserOfflineException ex)
- {
- return NotFound(ex.Message);
- }
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/API/Controllers/PublicChatController.cs b/src/slskd/API/Controllers/PublicChatController.cs
deleted file mode 100644
index 6bc54145..00000000
--- a/src/slskd/API/Controllers/PublicChatController.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-// <copyright file="PublicChatController.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.API.Controllers
-{
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Soulseek;
-
- /// <summary>
- /// Server.
- /// </summary>
- [Route("api/v{version:apiVersion}/[controller]")]
- [ApiVersion("0")]
- [ApiController]
- [Produces("application/json")]
- [Consumes("application/json")]
- public class PublicChatController : ControllerBase
- {
- public PublicChatController(ISoulseekClient client)
- {
- Client = client;
- }
-
- private ISoulseekClient Client { get; }
-
- /// <summary>
- /// Starts public chat.
- /// </summary>
- /// <returns></returns>
- [HttpPost]
- [Authorize]
- public async Task<IActionResult> Start()
- {
- await Client.StartPublicChatAsync();
- return StatusCode(StatusCodes.Status201Created);
- }
-
- /// <summary>
- /// Stops public chat.
- /// </summary>
- /// <returns></returns>
- [HttpDelete]
- [Authorize]
- public async Task<IActionResult> Stop()
- {
- await Client.StopPublicChatAsync();
- return StatusCode(StatusCodes.Status204NoContent);
- }
- }
-}
diff --git a/src/slskd/API/Controllers/RoomsController.cs b/src/slskd/API/Controllers/RoomsController.cs
deleted file mode 100644
index d309555e..00000000
--- a/src/slskd/API/Controllers/RoomsController.cs
+++ /dev/null
@@ -1,303 +0,0 @@
-// <copyright file="RoomsController.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.API.Controllers
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using slskd.API.DTO;
- using slskd.Messaging;
- using Soulseek;
-
- /// <summary>
- /// Rooms.
- /// </summary>
- [Route("api/v{version:apiVersion}/[controller]")]
- [ApiVersion("0")]
- [ApiController]
- [Produces("application/json")]
- [Consumes("application/json")]
- public class RoomsController : ControllerBase
- {
- public RoomsController(ISoulseekClient client, IRoomTracker tracker)
- {
- Client = client;
- Tracker = tracker;
- }
-
- private ISoulseekClient Client { get; }
- private IRoomTracker Tracker { get; }
-
- /// <summary>
- /// Gets all rooms.
- /// </summary>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- [HttpGet("joined")]
- [Authorize]
- [ProducesResponseType(typeof(Dictionary<string, Dictionary<string, Room>>), 200)]
- public IActionResult GetAll()
- {
- return Ok(Tracker.Rooms.Keys);
- }
-
- /// <summary>
- /// Gets the specified room.
- /// </summary>
- /// <param name="roomName"></param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- /// <response code="404">The specified roomName could not be found.</response>
- [HttpGet("joined/{roomName}")]
- [Authorize]
- [ProducesResponseType(typeof(Room), 200)]
- [ProducesResponseType(404)]
- public IActionResult GetByRoomName([FromRoute]string roomName)
- {
- if (Tracker.TryGet(roomName, out var room))
- {
- return Ok(MapRoomToRoomResponse(room));
- }
-
- return NotFound();
- }
-
- /// <summary>
- /// Sends a message to the specified room.
- /// </summary>
- /// <param name="roomName"></param>
- /// <param name="message"></param>
- /// <returns></returns>
- /// <response code="201">The request completed successfully.</response>
- /// <response code="404">The specified roomName could not be found.</response>
- [HttpPost("joined/{roomName}/messages")]
- [Authorize]
- [ProducesResponseType(201)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> SendMessage([FromRoute]string roomName, [FromBody]string message)
- {
- if (Tracker.TryGet(roomName, out var _))
- {
- await Client.SendRoomMessageAsync(roomName, message);
- return StatusCode(StatusCodes.Status201Created);
- }
-
- return NotFound();
- }
-
- /// <summary>
- /// Sets a ticker for the specified room.
- /// </summary>
- /// <param name="roomName"></param>
- /// <param name="message"></param>
- /// <returns></returns>
- /// <response code="201">The request completed successfully.</response>
- /// <response code="404">The specified roomName could not be found.</response>
- [HttpPost("joined/{roomName}/ticker")]
- [Authorize]
- [ProducesResponseType(201)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> SetTicker([FromRoute] string roomName, [FromBody] string message)
- {
- if (Tracker.TryGet(roomName, out var _))
- {
- await Client.SetRoomTickerAsync(roomName, message);
- return StatusCode(StatusCodes.Status201Created);
- }
-
- return NotFound();
- }
-
- /// <summary>
- /// Adds a member to a private room.
- /// </summary>
- /// <param name="roomName"></param>
- /// <param name="username"></param>
- /// <returns></returns>
- /// <response code="201">The request completed successfully.</response>
- /// <response code="404">The specified roomName could not be found.</response>
- [HttpPost("joined/{roomName}/members")]
- [Authorize]
- [ProducesResponseType(201)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> AddRoomMember([FromRoute]string roomName, [FromBody]string username)
- {
- if (Tracker.TryGet(roomName, out var _))
- {
- await Client.AddPrivateRoomMemberAsync(roomName, username);
- return StatusCode(StatusCodes.Status201Created);
- }
-
- return NotFound();
- }
-
- /// <summary>
- /// Gets the current list of users for the specified room.
- /// </summary>
- /// <param name="roomName"></param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- /// <response code="404">The specified roomName could not be found.</response>
- [HttpGet("joined/{roomName}/users")]
- [Authorize]
- [ProducesResponseType(typeof(IList<UserData>), 200)]
- [ProducesResponseType(404)]
- public IActionResult GetUsersByRoomName([FromRoute]string roomName)
- {
- if (Tracker.TryGet(roomName, out var room))
- {
- var response = room.Users
- .Select(user => UserDataResponse.FromUserData(user, self: user.Username == Client.Username));
-
- return Ok(response);
- }
-
- return NotFound();
- }
-
- /// <summary>
- /// Gets the current list of messages for the specified room.
- /// </summary>
- /// <param name="roomName"></param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- /// <response code="404">The specified roomName could not be found.</response>
- [HttpGet("joined/{roomName}/messages")]
- [Authorize]
- [ProducesResponseType(typeof(IList<RoomMessage>), 200)]
- [ProducesResponseType(404)]
- public IActionResult GetMessagesByRoomName([FromRoute]string roomName)
- {
- if (Tracker.TryGet(roomName, out var room))
- {
- var response = room.Messages
- .Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == Client.Username));
-
- return Ok(response);
- }
-
- return NotFound();
- }
-
- /// <summary>
- /// Gets a list of rooms from the server.
- /// </summary>
- /// <returns></returns>
- [HttpGet("available")]
- [Authorize]
- [ProducesResponseType(typeof(List<RoomInfo>), 200)]
- public async Task<IActionResult> GetRooms()
- {
- var list = await Client.GetRoomListAsync();
-
- var response = new List<RoomInfoResponse>();
-
- response.AddRange(list.Public.Select(r => RoomInfoResponse.FromRoomInfo(r)));
- response.AddRange(list.Private.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true)));
- response.AddRange(list.Owned.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true, isOwned: true)));
-
- foreach (var room in response)
- {
- room.IsModerated = list.ModeratedRoomNames.Contains(room.Name);
- }
-
- return Ok(response);
- }
-
- /// <summary>
- /// Joins a room.
- /// </summary>
- /// <param name="roomName"></param>
- /// <returns></returns>
- /// <response code="201">The request completed successfully.</response>
- /// <response code="304">The room has already been joined.</response>
- [HttpPost("joined/{roomName}")]
- [Authorize]
- [ProducesResponseType(typeof(Room), 201)]
- [ProducesResponseType(304)]
- public async Task<IActionResult> JoinRoom([FromRoute]string roomName)
- {
- if (Tracker.Rooms.ContainsKey(roomName))
- {
- return StatusCode(StatusCodes.Status304NotModified);
- }
-
- try
- {
- var roomData = await Client.JoinRoomAsync(roomName);
- var room = Room.FromRoomData(roomData);
- Tracker.TryAdd(roomName, room);
-
- return StatusCode(StatusCodes.Status201Created, MapRoomToRoomResponse(room));
- }
- catch (Exception ex)
- {
- if (ex.InnerException is RoomJoinForbiddenException)
- {
- return StatusCode(StatusCodes.Status403Forbidden, $"The server rejected your request to join {roomName}");
- }
-
- throw;
- }
- }
-
- /// <summary>
- /// Leaves a room.
- /// </summary>
- /// <param name="roomName"></param>
- /// <returns></returns>
- /// <response code="204">The request completed successfully.</response>
- /// <response code="404">The room has not been joined.</response>
- [HttpDelete("joined/{roomName}")]
- [Authorize]
- [ProducesResponseType(204)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> LeaveRoom([FromRoute]string roomName)
- {
- if (!Tracker.Rooms.ContainsKey(roomName))
- {
- return StatusCode(StatusCodes.Status404NotFound);
- }
-
- await Client.LeaveRoomAsync(roomName);
- Tracker.TryRemove(roomName);
-
- return StatusCode(StatusCodes.Status204NoContent);
- }
-
- private RoomResponse MapRoomToRoomResponse(Room room)
- {
- bool IsSelf(string username)
- {
- return username == Client.Username;
- }
-
- var response = RoomResponse.FromRoom(room);
- response.Users = room.Users
- .Select(user => UserDataResponse.FromUserData(user, self: IsSelf(user.Username)));
- response.Messages = room.Messages
- .Select(message => RoomMessageResponse.FromRoomMessage(message, self: IsSelf(message.Username)));
-
- return response;
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/API/Controllers/SearchesController.cs b/src/slskd/API/Controllers/SearchesController.cs
deleted file mode 100644
index 89095cb1..00000000
--- a/src/slskd/API/Controllers/SearchesController.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-// <copyright file="SearchesController.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.API.Controllers
-{
- using System;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using slskd.API.DTO;
- using slskd.Search;
- using SearchQuery = Soulseek.SearchQuery;
- using SearchScope = Soulseek.SearchScope;
-
- /// <summary>
- /// Search.
- /// </summary>
- [Route("api/v{version:apiVersion}/[controller]")]
- [ApiVersion("0")]
- [ApiController]
- [Produces("application/json")]
- [Consumes("application/json")]
- public class SearchesController : ControllerBase
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="SearchesController"/> class.
- /// </summary>
- /// <param name="searchService"></param>
- public SearchesController(ISearchService searchService)
- {
- Searches = searchService;
- }
-
- private ISearchService Searches { get; }
-
- /// <summary>
- /// Performs a search for the specified <paramref name="request"/>.
- /// </summary>
- /// <param name="request">The search request.</param>
- /// <returns></returns>
- /// <response code="200">The search completed successfully.</response>
- /// <response code="400">The specified <paramref name="request"/> was malformed.</response>
- /// <response code="500">The search terminated abnormally.</response>
- [HttpPost("")]
- [Authorize]
- public async Task<IActionResult> Post([FromBody]SearchRequest request)
- {
- var id = request.Id ?? Guid.NewGuid();
- var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1));
-
- Search search = null;
-
- try
- {
- search = await Searches.CreateAsync(id, SearchQuery.FromText(searchText), SearchScope.Network);
- return Ok(search.Responses);
- }
- catch (Exception ex)
- {
- return StatusCode(500, $"Search terminated abnormally: {ex.Message}");
- }
- finally
- {
- search = null;
- }
- }
-
- /// <summary>
- /// Gets the state of the search corresponding to the specified <paramref name="id"/>.
- /// </summary>
- /// <param name="id">The unique id of the search.</param>
- /// <param name="includeResponses">A value indicating whether to include search responses in the response.</param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- /// <response code="404">A matching search was not found.</response>
- [HttpGet("{id}")]
- [Authorize]
- public async Task<IActionResult> GetById([FromRoute]Guid id, [FromQuery]bool includeResponses = false)
- {
- var search = await Searches.FindAsync(search => search.Id == id, includeResponses);
-
- if (search == default)
- {
- return NotFound();
- }
-
- return Ok(search);
- }
-
- /// <summary>
- /// Gets the state of the search corresponding to the specified <paramref name="id"/>.
- /// </summary>
- /// <param name="id">The unique id of the search.</param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- /// <response code="404">A matching search was not found.</response>
- [HttpGet("{id}/responses")]
- [Authorize]
- public async Task<IActionResult> GetResponsesById([FromRoute] Guid id)
- {
- var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true);
-
- if (search == default)
- {
- return NotFound();
- }
-
- return Ok(search.Responses);
- }
-
- /// <summary>
- /// Gets the list of active and completed searches.
- /// </summary>
- /// <returns></returns>
- [HttpGet("")]
- [Authorize]
- public async Task<IActionResult> GetAll()
- {
- return Ok(await Searches.ListAsync());
- }
- }
-}
diff --git a/src/slskd/API/Controllers/ServerController.cs b/src/slskd/API/Controllers/ServerController.cs
deleted file mode 100644
index 5ec1ad93..00000000
--- a/src/slskd/API/Controllers/ServerController.cs
+++ /dev/null
@@ -1,85 +0,0 @@
-// <copyright file="ServerController.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.API.Controllers
-{
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using slskd.API.DTO;
- using Soulseek;
-
- /// <summary>
- /// Server.
- /// </summary>
- [Route("api/v{version:apiVersion}/[controller]")]
- [ApiVersion("0")]
- [ApiController]
- [Produces("application/json")]
- [Consumes("application/json")]
- public class ServerController : ControllerBase
- {
- public ServerController(ISoulseekClient client)
- {
- Client = client;
- }
-
- private ISoulseekClient Client { get; }
-
- /// <summary>
- /// Connects the client.
- /// </summary>
- /// <param name="req"></param>
- /// <returns></returns>
- [HttpPost]
- [Authorize]
- public async Task<IActionResult> Connect([FromBody] ConnectRequest req)
- {
- 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)
- {
- await Client.ConnectAsync(req.Username, req.Password);
- return Ok();
- }
-
- return BadRequest("Provide one of the following: address and port, username and password, or address, port, username and password");
- }
-
- /// <summary>
- /// Disconnects the client.
- /// </summary>
- /// <param name="message"></param>
- /// <returns></returns>
- [HttpDelete]
- [Authorize]
- public IActionResult Disconnect([FromBody] string message)
- {
- Client.Disconnect(message);
- return NoContent();
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/API/Controllers/SessionController.cs b/src/slskd/API/Controllers/SessionController.cs
deleted file mode 100644
index 2011aba3..00000000
--- a/src/slskd/API/Controllers/SessionController.cs
+++ /dev/null
@@ -1,144 +0,0 @@
-// <copyright file="SessionController.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.API.Controllers
-{
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens.Jwt;
- using System.Security.Claims;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.IdentityModel.Tokens;
- using slskd;
- using slskd.API.DTO;
-
- /// <summary>
- /// Session.
- /// </summary>
- [Route("api/v{version:apiVersion}/[controller]")]
- [ApiVersion("0")]
- [ApiController]
- [Produces("application/json")]
- [Consumes("application/json")]
- public class SessionController : ControllerBase
- {
- public SessionController(
- Microsoft.Extensions.Options.IOptionsSnapshot<Options> optionsSnapshot,
- SymmetricSecurityKey jwtSigningKey)
- {
- Options = optionsSnapshot.Value;
- JwtSigningKey = jwtSigningKey;
- }
-
- private SymmetricSecurityKey JwtSigningKey { get; set; }
- private Options Options { get; set; }
-
- /// <summary>
- /// Checks whether the provided authentication is valid.
- /// </summary>
- /// <remarks>This is a no-op provided so that the application can test for an expired token on load.</remarks>
- /// <returns></returns>
- /// <response code="200">The authentication is valid.</response>
- /// <response code="403">The authentication is is invalid.</response>
- [HttpGet]
- [Route("")]
- [Authorize]
- [ProducesResponseType(200)]
- [ProducesResponseType(401)]
- public IActionResult Check()
- {
- return Ok();
- }
-
- /// <summary>
- /// Checks whether security is enabled.
- /// </summary>
- /// <returns></returns>
- /// <response code="200">True if security is enabled, false otherwise.</response>
- [HttpGet]
- [Route("enabled")]
- [AllowAnonymous]
- [ProducesResponseType(typeof(bool), 200)]
- public IActionResult Enabled()
- {
- return Ok(!Options.Web.Authentication.Disable);
- }
-
- /// <summary>
- /// Logs in.
- /// </summary>
- /// <param name="login"></param>
- /// <returns></returns>
- /// <response code="200">Login was successful.</response>
- /// <response code="400">Bad request.</response>
- /// <response code="401">Login failed.</response>
- [HttpPost]
- [Route("")]
- [AllowAnonymous]
- [ProducesResponseType(typeof(TokenResponse), 200)]
- [ProducesResponseType(400)]
- [ProducesResponseType(401)]
- [ProducesResponseType(typeof(string), 500)]
- public IActionResult Login([FromBody] LoginRequest login)
- {
- if (login == default)
- {
- return BadRequest();
- }
-
- if (string.IsNullOrWhiteSpace(login.Username) || string.IsNullOrWhiteSpace(login.Password))
- {
- return BadRequest("Username and/or Password missing or invalid");
- }
-
- // only admin login for now
- if (Options.Web.Authentication.Username == login.Username && Options.Web.Authentication.Password == login.Password)
- {
- return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator)));
- }
-
- return Unauthorized();
- }
-
- private JwtSecurityToken GetJwtSecurityToken(string username, Role role)
- {
- var issuedUtc = DateTime.UtcNow;
- var expiresUtc = DateTime.UtcNow.AddMilliseconds(Options.Web.Authentication.Jwt.Ttl);
-
- var claims = new List<Claim>()
- {
- new Claim(ClaimTypes.Name, username),
- new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
- new Claim(ClaimTypes.Role, role.ToString()),
- new Claim("name", username),
- new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()),
- };
-
- var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256);
-
- var token = new JwtSecurityToken(
- issuer: Program.AppName,
- claims: claims,
- notBefore: issuedUtc,
- expires: expiresUtc,
- signingCredentials: credentials);
-
- return token;
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/API/Controllers/TransfersController.cs b/src/slskd/API/Controllers/TransfersController.cs
deleted file mode 100644
index 11c5dcad..00000000
--- a/src/slskd/API/Controllers/TransfersController.cs
+++ /dev/null
@@ -1,321 +0,0 @@
-// <copyright file="TransfersController.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.API.Controllers
-{
- using System;
- using System.ComponentModel.DataAnnotations;
- using System.IO;
- using System.Linq;
- using System.Threading;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using slskd.API.DTO;
- using slskd.Transfer;
- using Soulseek;
-
- /// <summary>
- /// Transfers.
- /// </summary>
- [Route("api/v{version:apiVersion}/[controller]")]
- [ApiVersion("0")]
- [ApiController]
- [Produces("application/json")]
- [Consumes("application/json")]
- public class TransfersController : ControllerBase
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="TransfersController"/> class.
- /// </summary>
- /// <param name="options"></param>
- /// <param name="client"></param>
- /// <param name="tracker"></param>
- public TransfersController(
- Microsoft.Extensions.Options.IOptionsSnapshot<Options> options,
- ISoulseekClient client,
- ITransferTracker tracker)
- {
- Client = client;
- Tracker = tracker;
- Options = options.Value;
- }
-
- private Options Options { get; }
- private ISoulseekClient Client { get; }
- private ITransferTracker Tracker { get; }
-
- /// <summary>
- /// Cancels the specified download.
- /// </summary>
- /// <param name="username">The username of the download source.</param>
- /// <param name="id">The id of the download.</param>
- /// <param name="remove">A value indicating whether the tracked download should be removed after cancellation.</param>
- /// <returns></returns>
- /// <response code="204">The download was cancelled successfully.</response>
- /// <response code="404">The specified download was not found.</response>
- [HttpDelete("downloads/{username}/{id}")]
- [Authorize]
- [ProducesResponseType(204)]
- [ProducesResponseType(404)]
- public IActionResult CancelDownload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false)
- {
- return CancelTransfer(TransferDirection.Download, username, id, remove);
- }
-
- /// <summary>
- /// Cancels the specified upload.
- /// </summary>
- /// <param name="username">The username of the upload destination.</param>
- /// <param name="id">The id of the upload.</param>
- /// <param name="remove">A value indicating whether the tracked upload should be removed after cancellation.</param>
- /// <returns></returns>
- /// <response code="204">The upload was cancelled successfully.</response>
- /// <response code="404">The specified upload was not found.</response>
- [HttpDelete("uploads/{username}/{id}")]
- [Authorize]
- [ProducesResponseType(204)]
- [ProducesResponseType(404)]
- public IActionResult CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false)
- {
- return CancelTransfer(TransferDirection.Upload, username, id, remove);
- }
-
- /// <summary>
- /// Enqueues the specified download.
- /// </summary>
- /// <param name="username">The username of the download source.</param>
- /// <param name="request">The download request.</param>
- /// <returns></returns>
- /// <response code="201">The download was successfully enqueued.</response>
- /// <response code="403">The download was rejected.</response>
- /// <response code="500">An unexpected error was encountered.</response>
- [HttpPost("downloads/{username}")]
- [Authorize]
- [ProducesResponseType(201)]
- [ProducesResponseType(typeof(string), 403)]
- [ProducesResponseType(typeof(string), 500)]
- public async Task<IActionResult> Enqueue([FromRoute, Required]string username, [FromBody]QueueDownloadRequest request)
- {
- try
- {
- var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
- var stream = GetLocalFileStream(request.Filename, Options.Directories.Incomplete);
-
- var cts = new CancellationTokenSource();
-
- var downloadTask = Task.Run(async () =>
- {
- await Client.DownloadAsync(username, request.Filename, stream, request.Size, 0, request.Token, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) =>
- {
- Tracker.AddOrUpdate(e, cts);
-
- if (e.Transfer.State == TransferStates.Queued || e.Transfer.State == TransferStates.Initializing)
- {
- waitUntilEnqueue.TrySetResult(true);
- }
- }, progressUpdated: (e) => Tracker.AddOrUpdate(e, cts)), cts.Token);
-
- MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads);
- });
-
- // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the
- // downloadTask throws due to an error prior to successfully queueing.
- var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask);
-
- if (task == downloadTask)
- {
- if (downloadTask.Exception is AggregateException)
- {
- var rejected = downloadTask.Exception?.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty<Exception>();
- if (rejected.Any())
- {
- return StatusCode(403, rejected.First().Message);
- }
- }
-
- return StatusCode(500, downloadTask.Exception.Message);
- }
-
- // if it didn't throw, just return ok. the download will continue waiting in the background.
- return StatusCode(201);
- }
- catch (Exception ex)
- {
- return StatusCode(500, ex.Message);
- }
- }
-
- /// <summary>
- /// Gets all downloads.
- /// </summary>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- [HttpGet("downloads")]
- [Authorize]
- [ProducesResponseType(200)]
- public IActionResult GetDownloads()
- {
- return Ok(Tracker.Transfers
- .WithDirection(TransferDirection.Download)
- .ToMap());
- }
-
- /// <summary>
- /// Gets all downloads for the specified username.
- /// </summary>
- /// <param name="username"></param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- [HttpGet("downloads/{username}")]
- [Authorize]
- [ProducesResponseType(200)]
- public IActionResult GetDownloads([FromRoute, Required]string username)
- {
- return Ok(Tracker.Transfers
- .WithDirection(TransferDirection.Download)
- .FromUser(username)
- .ToMap());
- }
-
- /// <summary>
- /// Gets the downlaod for the specified username matching the specified filename, and requests
- /// the current place in the remote queue of the specified download.
- /// </summary>
- /// <param name="username">The username of the download source.</param>
- /// <param name="id">The id of the download.</param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- /// <response code="404">The specified download was not found.</response>
- [HttpGet("downloads/{username}/{id}")]
- [Authorize]
- [ProducesResponseType(typeof(DTO.Transfer), 200)]
- [ProducesResponseType(404)]
- public async Task<IActionResult> GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id)
- {
- var record = Tracker.Transfers.WithDirection(TransferDirection.Download).FromUser(username).WithId(id);
-
- if (record == default)
- {
- return NotFound();
- }
-
- record.Transfer.PlaceInQueue = await Client.GetDownloadPlaceInQueueAsync(username, record.Transfer.Filename);
- return Ok(record.Transfer);
- }
-
- /// <summary>
- /// Gets all uploads.
- /// </summary>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- [HttpGet("uploads")]
- [Authorize]
- [ProducesResponseType(200)]
- public IActionResult GetUploads()
- {
- return Ok(Tracker.Transfers
- .WithDirection(TransferDirection.Upload)
- .ToMap());
- }
-
- /// <summary>
- /// Gets all uploads for the specified username.
- /// </summary>
- /// <param name="username"></param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- [HttpGet("uploads/{username}")]
- [Authorize]
- [ProducesResponseType(200)]
- public IActionResult GetUploads([FromRoute, Required]string username)
- {
- return Ok(Tracker.Transfers
- .WithDirection(TransferDirection.Upload)
- .FromUser(username)
- .ToMap());
- }
-
- /// <summary>
- /// Gets the upload for the specified username matching the specified filename.
- /// </summary>
- /// <param name="username">The username of the upload destination.</param>
- /// <param name="id">The id of the upload.</param>
- /// <returns></returns>
- /// <response code="200">The request completed successfully.</response>
- [HttpGet("uploads/{username}/{id}")]
- [Authorize]
- [ProducesResponseType(200)]
- public IActionResult GetUploads([FromRoute, Required]string username, [FromRoute, Required]string id)
- {
- return Ok(Tracker.Transfers
- .WithDirection(TransferDirection.Upload)
- .FromUser(username)
- .WithId(id).Transfer);
- }
-
- private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory)
- {
- var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory);
- var path = Path.GetDirectoryName(localFilename);
-
- if (!System.IO.Directory.Exists(path))
- {
- System.IO.Directory.CreateDirectory(path);
- }
-
- return new FileStream(localFilename, FileMode.Create);
- }
-
- private static void MoveFile(string filename, string sourceDirectory, string destinationDirectory)
- {
- var sourceFilename = filename.ToLocalFilename(sourceDirectory);
- var destinationFilename = filename.ToLocalFilename(destinationDirectory);
-
- var destinationPath = Path.GetDirectoryName(destinationFilename);
-
- if (!System.IO.Directory.Exists(destinationPath))
- {
- System.IO.Directory.CreateDirectory(destinationPath);
- }
-
- System.IO.File.Move(sourceFilename, destinationFilename, overwrite: true);
-
- if (!System.IO.Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any())
- {
- System.IO.Directory.Delete(Path.GetDirectoryName(sourceFilename));
- }
- }
-
- private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false)
- {
- if (Tracker.TryGet(direction, username, id, out var transfer))
- {
- transfer.CancellationTokenSource.Cancel();
-
- if (remove)
- {
- Tracker.TryRemove(direction, username, id);
- }
-
- return NoContent();
- }
-
- return NotFound();
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/API/DTO/ConnectRequest.cs b/src/slskd/API/DTO/ConnectRequest.cs
deleted file mode 100644
index 155db2da..00000000
--- a/src/slskd/API/DTO/ConnectRequest.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// <copyright file="ConnectRequest.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.API.DTO
-{
- public class ConnectRequest
- {
- public string Address { get; set; }
- public int? Port { get; set; }
- public string Username { get; set; }
- public string Password { get; set; }
- }
-}
diff --git a/src/slskd/API/DTO/LoginRequest.cs b/src/slskd/API/DTO/LoginRequest.cs
deleted file mode 100644
index 9f3ccf2e..00000000
--- a/src/slskd/API/DTO/LoginRequest.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-// <copyright file="LoginRequest.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.API.DTO
-{
- public class LoginRequest
- {
- public string Username { get; set; }
- public string Password { get; set; }
- }
-}
diff --git a/src/slskd/API/DTO/PrivateMessageResponse.cs b/src/slskd/API/DTO/PrivateMessageResponse.cs
deleted file mode 100644
index 9794d762..00000000
--- a/src/slskd/API/DTO/PrivateMessageResponse.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-// <copyright file="PrivateMessageResponse.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.API.DTO
-{
- using slskd.Messaging;
- using System;
-
- public class PrivateMessageResponse
- {
- /// <summary>
- /// A value indicating whether the message has been acknowledged.
- /// </summary>
- public bool Acknowledged { get; set; } = false;
-
- /// <summary>
- /// The unique message id, used to acknowledge receipt.
- /// </summary>
- public int Id { get; set; }
-
- /// <summary>
- /// The message.
- /// </summary>
- public string Message { get; set; }
-
- /// <summary>
- /// A value indicating whether the message was replayed.
- /// </summary>
- public bool Replayed { get; set; }
-
- /// <summary>
- /// The UTC timestamp of the message.
- /// </summary>
- public DateTime Timestamp { get; set; } = DateTime.UtcNow;
-
- /// <summary>
- /// The username of the user who sent the message.
- /// </summary>
- public string Username { get; set; }
-
- /// <summary>
- /// A value indicating whether this message was sent by the currently logged in user.
- /// </summary>
- public bool? Self { get; set; }
-
- public static PrivateMessageResponse FromPrivateMessage(PrivateMessage privateMessage, bool self = false)
- {
- return new PrivateMessageResponse()
- {
- Id = privateMessage.Id,
- Timestamp = privateMessage.Timestamp,
- Username = privateMessage.Username,
- Message = privateMessage.Message,
- Acknowledged = privateMessage.Acknowledged,
- Replayed = privateMessage.Replayed,
- Self = self ? self : (bool?)null,
- };
- }
- }
-}
diff --git a/src/slskd/API/DTO/QueueDownloadRequest.cs b/src/slskd/API/DTO/QueueDownloadRequest.cs
deleted file mode 100644
index a849fefa..00000000
--- a/src/slskd/API/DTO/QueueDownloadRequest.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// <copyright file="QueueDownloadRequest.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.API.DTO
-{
- public class QueueDownloadRequest
- {
- /// <summary>
- /// Gets or sets the filename to download.
- /// </summary>
- public string Filename { get; set; }
-
- /// <summary>
- /// Gets or sets the size of the file.
- /// </summary>
- public long? Size { get; set; }
-
- /// <summary>
- /// Gets or sets the optional transfer token.
- /// </summary>
- public int? Token { get; set; }
- }
-}
diff --git a/src/slskd/API/DTO/RoomInfoResponse.cs b/src/slskd/API/DTO/RoomInfoResponse.cs
deleted file mode 100644
index 6f135d56..00000000
--- a/src/slskd/API/DTO/RoomInfoResponse.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-// <copyright file="RoomInfoResponse.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.API.DTO
-{
- using Soulseek;
-
- public class RoomInfoResponse
- {
- /// <summary>
- /// Gets the room name.
- /// </summary>
- public string Name { get; init; }
-
- /// <summary>
- /// Gets the number of users in the room.
- /// </summary>
- public int UserCount { get; init; }
-
- /// <summary>
- /// Gets a value indicating whether the room is private.
- /// </summary>
- public bool IsPrivate { get; init; }
-
- /// <summary>
- /// Gets a value indicating whether the room is owned by the currently logged in user.
- /// </summary>
- public bool IsOwned { get; init; }
-
- /// <summary>
- /// Gets a value indicating whether the room is moderated by the currently logged in user.
- /// </summary>
- public bool IsModerated { get; set; }
-
- public static RoomInfoResponse FromRoomInfo(RoomInfo info, bool isPrivate = false, bool isOwned = false)
- {
- return new RoomInfoResponse()
- {
- Name = info.Name,
- UserCount = info.UserCount,
- IsPrivate = isPrivate,
- IsOwned = isOwned,
- };
- }
- }
-}
diff --git a/src/slskd/API/DTO/RoomMessageResponse.cs b/src/slskd/API/DTO/RoomMessageResponse.cs
deleted file mode 100644
index 48a77f51..00000000
--- a/src/slskd/API/DTO/RoomMessageResponse.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-// <copyright file="RoomMessageResponse.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.API.DTO
-{
- using slskd.Messaging;
- using System;
-
- public class RoomMessageResponse
- {
- /// <summary>
- /// The timestamp of the message.
- /// </summary>
- public DateTime Timestamp { get; set; } = DateTime.UtcNow;
-
- /// <summary>
- /// The username of the user who sent the message.
- /// </summary>
- public string Username { get; set; }
-
- /// <summary>
- /// The message.
- /// </summary>
- public string Message { get; set; }
-
- /// <summary>
- /// The room to which the message pertains.
- /// </summary>
- public string RoomName { get; set; }
-
- /// <summary>
- /// A value indicating whether this user data belongs to the currently logged in user.
- /// </summary>
- public bool? Self { get; set; }
-
- public static RoomMessageResponse FromRoomMessage(RoomMessage roomMessage, bool self = false)
- {
- return new RoomMessageResponse()
- {
- Timestamp = roomMessage.Timestamp,
- Username = roomMessage.Username,
- Message = roomMessage.Message,
- RoomName = roomMessage.RoomName,
- Self = self ? self : (bool?)null,
- };
- }
- }
-}
diff --git a/src/slskd/API/DTO/RoomResponse.cs b/src/slskd/API/DTO/RoomResponse.cs
deleted file mode 100644
index 552cb7f5..00000000
--- a/src/slskd/API/DTO/RoomResponse.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-// <copyright file="RoomResponse.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.API.DTO
-{
- using slskd.Messaging;
- using System.Collections.Generic;
- using System.Linq;
-
- public class RoomResponse
- {
- /// <summary>
- /// The room name.
- /// </summary>
- public string Name { get; set; }
-
- /// <summary>
- /// A value indicating whether the room is private.
- /// </summary>
- public bool IsPrivate { get; set; }
-
- /// <summary>
- /// The number of operators in the room, if private.
- /// </summary>
- public int? OperatorCount { get; set; }
-
- /// <summary>
- /// The operators in the room, if private.
- /// </summary>
- public IList<string> Operators { get; set; }
-
- /// <summary>
- /// The owner of the room, if private.
- /// </summary>
- public string Owner { get; set; }
-
- /// <summary>
- /// The list of users in the room.
- /// </summary>
- public IEnumerable<UserDataResponse> Users { get; set; } = new List<UserDataResponse>();
-
- /// <summary>
- /// The list of messages.
- /// </summary>
- public IEnumerable<RoomMessageResponse> Messages { get; set; } = new List<RoomMessageResponse>();
-
- public static RoomResponse FromRoom(Room room)
- {
- return new RoomResponse()
- {
- Name = room.Name,
- IsPrivate = room.IsPrivate,
- OperatorCount = room.OperatorCount,
- Operators = room.Operators?.ToList(),
- Owner = room.Owner,
- Users = new List<UserDataResponse>(),
- Messages = new List<RoomMessageResponse>(),
- };
- }
- }
-}
diff --git a/src/slskd/API/DTO/SearchRequest.cs b/src/slskd/API/DTO/SearchRequest.cs
deleted file mode 100644
index 147eb205..00000000
--- a/src/slskd/API/DTO/SearchRequest.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-// <copyright file="SearchRequest.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.API.DTO
-{
- using System;
- using Soulseek;
-
- /// <summary>
- /// A search request.
- /// </summary>
- public class SearchRequest
- {
- /// <summary>
- /// Gets or sets the unique search identifier.
- /// </summary>
- public Guid? Id { get; set; }
-
- /// <summary>
- /// Gets or sets the maximum number of file results to accept before the search is considered complete. (Default = 10,000).
- /// </summary>
- public int? FileLimit { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether responses are to be filtered. (Default = true).
- /// </summary>
- public bool? FilterResponses { get; set; }
-
- /// <summary>
- /// Gets or sets the maximum queue depth a peer may have in order for a response to be processed. (Default = 1000000).
- /// </summary>
- public int? MaximumPeerQueueLength { get; set; }
-
- /// <summary>
- /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed.
- /// (Default = 0).
- /// </summary>
- public int? MinimumPeerFreeUploadSlots { get; set; }
-
- /// <summary>
- /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0).
- /// </summary>
- public int? MinimumPeerUploadSpeed { get; set; }
-
- /// <summary>
- /// Gets or sets the minimum number of files a response must contain in order to be processed. (Default = 1).
- /// </summary>
- public int? MinimumResponseFileCount { get; set; }
-
- /// <summary>
- /// Gets or sets the maximum number of search results to accept before the search is considered complete. (Default = 100).
- /// </summary>
- public int? ResponseLimit { get; set; }
-
- /// <summary>
- /// Gets or sets the search text.
- /// </summary>
- public string SearchText { get; set; }
-
- /// <summary>
- /// Gets or sets the search timeout value, in seconds, used to determine when the search is complete. (Default = 15).
- /// </summary>
- /// <remarks>The timeout duration is from the time of the last response.</remarks>
- public int? SearchTimeout { get; set; }
-
- /// <summary>
- /// Gets or sets the search token.
- /// </summary>
- public int? Token { get; set; }
-
- /// <summary>
- /// Maps to a new instance of <see cref="SearchOptions"/>.
- /// </summary>
- /// <param name="responseFilter"></param>
- /// <param name="fileFilter"></param>
- /// <param name="stateChanged"></param>
- /// <param name="responseReceived"></param>
- /// <returns></returns>
- public SearchOptions ToSearchOptions(
- Func<SearchResponse, bool> responseFilter = null,
- Func<File, bool> fileFilter = null,
- Action<SearchStateChangedEventArgs> stateChanged = null,
- Action<SearchResponseReceivedEventArgs> responseReceived = null)
- {
- var def = new SearchOptions();
-
- return new SearchOptions(
- searchTimeout: SearchTimeout ?? def.SearchTimeout,
- responseLimit: ResponseLimit ?? def.ResponseLimit,
- fileLimit: FileLimit ?? def.FileLimit,
- filterResponses: FilterResponses ?? def.FilterResponses,
- minimumResponseFileCount: MinimumResponseFileCount ?? def.MinimumResponseFileCount,
- minimumPeerFreeUploadSlots: MinimumPeerFreeUploadSlots ?? def.MinimumPeerFreeUploadSlots,
- maximumPeerQueueLength: MaximumPeerQueueLength ?? def.MaximumPeerQueueLength,
- minimumPeerUploadSpeed: MinimumPeerUploadSpeed ?? def.MinimumPeerUploadSpeed,
- responseFilter: responseFilter,
- fileFilter: fileFilter,
- responseReceived: responseReceived,
- stateChanged: stateChanged);
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/API/DTO/TokenResponse.cs b/src/slskd/API/DTO/TokenResponse.cs
deleted file mode 100644
index c20e325c..00000000
--- a/src/slskd/API/DTO/TokenResponse.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-// <copyright file="TokenResponse.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.API.DTO
-{
- using System;
- using System.IdentityModel.Tokens.Jwt;
- using System.Linq;
- using System.Security.Claims;
- using System.Text.Json.Serialization;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
-
- public class TokenResponse
- {
- public TokenResponse(JwtSecurityToken jwtSecurityToken)
- {
- JwtSecurityToken = jwtSecurityToken;
- }
-
- /// <summary>
- /// Gets the time at which the Access Token expires.
- /// </summary>
- public long Expires => ((DateTimeOffset)JwtSecurityToken.ValidTo).ToUnixTimeSeconds();
-
- /// <summary>
- /// Gets the time at which the Access Token was issued.
- /// </summary>
- public long Issued => ((DateTimeOffset)JwtSecurityToken.ValidFrom).ToUnixTimeSeconds();
-
- /// <summary>
- /// Gets the value of the Name claim from the Access Token.
- /// </summary>
- public string Name => JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
-
- /// <summary>
- /// Gets the value of the Not Before claim from the Access Token.
- /// </summary>
- public long NotBefore => long.Parse(JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == "nbf").Value);
-
- /// <summary>
- /// Gets the Access Token string.
- /// </summary>
- public string Token => new JwtSecurityTokenHandler().WriteToken(JwtSecurityToken);
-
- /// <summary>
- /// Gets the Token type.
- /// </summary>
- public string TokenType => JwtBearerDefaults.AuthenticationScheme;
-
- [JsonIgnore]
- private JwtSecurityToken JwtSecurityToken { get; }
- }
-} \ No newline at end of file
diff --git a/src/slskd/API/DTO/Transfer.cs b/src/slskd/API/DTO/Transfer.cs
deleted file mode 100644
index c3e4ac22..00000000
--- a/src/slskd/API/DTO/Transfer.cs
+++ /dev/null
@@ -1,148 +0,0 @@
-// <copyright file="Transfer.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.API.DTO
-{
- using System;
- using System.Net;
- using Soulseek;
-
- /// <summary>
- /// A single file transfer.
- /// </summary>
- public class Transfer
- {
- /// <summary>
- /// Gets the current average transfer speed.
- /// </summary>
- public double AverageSpeed { get; set; }
-
- /// <summary>
- /// Gets the number of remaining bytes to be transferred.
- /// </summary>
- public long BytesRemaining { get; set; }
-
- /// <summary>
- /// Gets the total number of bytes transferred.
- /// </summary>
- public long BytesTransferred { get; set; }
-
- /// <summary>
- /// Gets the transfer direction.
- /// </summary>
- public TransferDirection Direction { get; set; }
-
- /// <summary>
- /// Gets the current duration of the transfer, if it has been started.
- /// </summary>
- public double? ElapsedTime { get; set; }
-
- /// <summary>
- /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.Completed"/> state.
- /// </summary>
- public DateTime? EndTime { get; set; }
-
- /// <summary>
- /// Gets the filename of the file to be transferred.
- /// </summary>
- public string Filename { get; set; }
-
- /// <summary>
- /// Gets the transfer id.
- /// </summary>
- public string Id => Filename.Sha1();
-
- /// <summary>
- /// Gets the ip endpoint of the remote transfer connection, if one has been established.
- /// </summary>
- public IPEndPoint IPEndPoint { get; set; }
-
- /// <summary>
- /// Gets the current progress in percent.
- /// </summary>
- public double PercentComplete { get; set; }
-
- /// <summary>
- /// Gets the current place in queue, if it has been fetched.
- /// </summary>
- public int? PlaceInQueue { get; set; }
-
- /// <summary>
- /// Gets the projected remaining duration of the transfer.
- /// </summary>
- public double? RemainingTime { get; set; }
-
- /// <summary>
- /// Gets the remote unique token for the transfer.
- /// </summary>
- public int? RemoteToken { get; set; }
-
- /// <summary>
- /// Gets the size of the file to be transferred, in bytes.
- /// </summary>
- public long Size { get; set; }
-
- /// <summary>
- /// Gets the starting offset of the transfer, in bytes.
- /// </summary>
- public long StartOffset { get; set; }
-
- /// <summary>
- /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.InProgress"/> state.
- /// </summary>
- public DateTime? StartTime { get; set; }
-
- /// <summary>
- /// Gets the state of the transfer.
- /// </summary>
- public TransferStates State { get; set; }
-
- /// <summary>
- /// Gets the unique token for the transfer.
- /// </summary>
- public int Token { get; set; }
-
- /// <summary>
- /// Gets the username of the peer to or from which the file is to be transferred.
- /// </summary>
- public string Username { get; set; }
-
- public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer)
- {
- return new Transfer()
- {
- AverageSpeed = transfer.AverageSpeed,
- BytesRemaining = transfer.BytesRemaining,
- BytesTransferred = transfer.BytesTransferred,
- Direction = transfer.Direction,
- ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds,
- EndTime = transfer.EndTime,
- Filename = transfer.Filename,
- IPEndPoint = transfer.IPEndPoint,
- PercentComplete = transfer.PercentComplete,
- RemainingTime = transfer.RemainingTime?.TotalMilliseconds,
- RemoteToken = transfer.RemoteToken,
- Size = transfer.Size,
- StartOffset = transfer.StartOffset,
- StartTime = transfer.StartTime,
- State = transfer.State,
- Token = transfer.Token,
- Username = transfer.Username,
- };
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/API/DTO/UserDataResponse.cs b/src/slskd/API/DTO/UserDataResponse.cs
deleted file mode 100644
index e854922e..00000000
--- a/src/slskd/API/DTO/UserDataResponse.cs
+++ /dev/null
@@ -1,85 +0,0 @@
-// <copyright file="UserDataResponse.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.API.DTO
-{
- using Soulseek;
-
- public class UserDataResponse
- {
- /// <summary>
- /// The average upload speed of the user.
- /// </summary>
- public int AverageSpeed { get; set; }
-
- /// <summary>
- /// The user's country code, if provided.
- /// </summary>
- public string CountryCode { get; set; }
-
- /// <summary>
- /// The number of directories shared by the user.
- /// </summary>
- public int DirectoryCount { get; set; }
-
- /// <summary>
- /// The number of active user downloads.
- /// </summary>
- public long DownloadCount { get; set; }
-
- /// <summary>
- /// The number of files shared by the user.
- /// </summary>
- public int FileCount { get; set; }
-
- /// <summary>
- /// A value indicating whether this user data belongs to the currently logged in user.
- /// </summary>
- public bool? Self { get; set; }
-
- /// <summary>
- /// The number of the user's free download slots, if provided.
- /// </summary>
- public int? SlotsFree { get; set; }
-
- /// <summary>
- /// The status of the user (0 = offline, 1 = away, 2 = online).
- /// </summary>
- public UserPresence Status { get; set; }
-
- /// <summary>
- /// The username of the user.
- /// </summary>
- public string Username { get; set; }
-
- public static UserDataResponse FromUserData(UserData userData, bool self = false)
- {
- return new UserDataResponse()
- {
- AverageSpeed = userData.AverageSpeed,
- CountryCode = userData.CountryCode,
- DirectoryCount = userData.DirectoryCount,
- DownloadCount = userData.DownloadCount,
- FileCount = userData.FileCount,
- SlotsFree = userData.SlotsFree,
- Status = userData.Status,
- Username = userData.Username,
- Self = self ? self : (bool?)null,
- };
- }
- }
-} \ No newline at end of file