From 936ed099a6e5258f9fd5a5ac026afc0630359b98 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Feb 2021 07:58:15 -0600 Subject: move controllers and DTOs to API namespace --- src/slskd/API/Controllers/ApplicationController.cs | 59 +++++ .../API/Controllers/ConversationsController.cs | 198 ++++++++++++++ src/slskd/API/Controllers/PublicChatController.cs | 50 ++++ src/slskd/API/Controllers/RoomsController.cs | 287 +++++++++++++++++++++ src/slskd/API/Controllers/SearchesController.cs | 102 ++++++++ src/slskd/API/Controllers/ServerController.cs | 68 +++++ src/slskd/API/Controllers/SessionController.cs | 132 ++++++++++ src/slskd/API/Controllers/TransfersController.cs | 286 ++++++++++++++++++++ src/slskd/API/Controllers/UserController.cs | 151 +++++++++++ src/slskd/API/DTO/ConnectRequest.cs | 10 + src/slskd/API/DTO/LoginRequest.cs | 8 + src/slskd/API/DTO/PrivateMessageResponse.cs | 57 ++++ src/slskd/API/DTO/QueueDownloadRequest.cs | 20 ++ src/slskd/API/DTO/RoomInfoResponse.cs | 43 +++ src/slskd/API/DTO/RoomMessageResponse.cs | 45 ++++ src/slskd/API/DTO/RoomResponse.cs | 58 +++++ src/slskd/API/DTO/SearchRequest.cs | 99 +++++++ src/slskd/API/DTO/TokenResponse.cs | 50 ++++ src/slskd/API/DTO/Transfer.cs | 131 ++++++++++ src/slskd/API/DTO/UserAddress.cs | 18 ++ src/slskd/API/DTO/UserDataResponse.cs | 68 +++++ src/slskd/Controllers/ApplicationController.cs | 59 ----- src/slskd/Controllers/ConversationsController.cs | 198 -------------- src/slskd/Controllers/PublicChatController.cs | 50 ---- src/slskd/Controllers/RoomsController.cs | 287 --------------------- src/slskd/Controllers/SearchesController.cs | 102 -------- src/slskd/Controllers/ServerController.cs | 68 ----- src/slskd/Controllers/SessionController.cs | 132 ---------- src/slskd/Controllers/TransfersController.cs | 286 -------------------- src/slskd/Controllers/UserController.cs | 151 ----------- src/slskd/DTO/ConnectRequest.cs | 10 - src/slskd/DTO/LoginRequest.cs | 8 - src/slskd/DTO/PrivateMessageResponse.cs | 57 ---- src/slskd/DTO/QueueDownloadRequest.cs | 20 -- src/slskd/DTO/RoomInfoResponse.cs | 43 --- src/slskd/DTO/RoomMessageResponse.cs | 45 ---- src/slskd/DTO/RoomResponse.cs | 58 ----- src/slskd/DTO/SearchRequest.cs | 99 ------- src/slskd/DTO/TokenResponse.cs | 50 ---- src/slskd/DTO/Transfer.cs | 131 ---------- src/slskd/DTO/UserAddress.cs | 18 -- src/slskd/DTO/UserDataResponse.cs | 68 ----- 42 files changed, 1940 insertions(+), 1940 deletions(-) create mode 100644 src/slskd/API/Controllers/ApplicationController.cs create mode 100644 src/slskd/API/Controllers/ConversationsController.cs create mode 100644 src/slskd/API/Controllers/PublicChatController.cs create mode 100644 src/slskd/API/Controllers/RoomsController.cs create mode 100644 src/slskd/API/Controllers/SearchesController.cs create mode 100644 src/slskd/API/Controllers/ServerController.cs create mode 100644 src/slskd/API/Controllers/SessionController.cs create mode 100644 src/slskd/API/Controllers/TransfersController.cs create mode 100644 src/slskd/API/Controllers/UserController.cs create mode 100644 src/slskd/API/DTO/ConnectRequest.cs create mode 100644 src/slskd/API/DTO/LoginRequest.cs create mode 100644 src/slskd/API/DTO/PrivateMessageResponse.cs create mode 100644 src/slskd/API/DTO/QueueDownloadRequest.cs create mode 100644 src/slskd/API/DTO/RoomInfoResponse.cs create mode 100644 src/slskd/API/DTO/RoomMessageResponse.cs create mode 100644 src/slskd/API/DTO/RoomResponse.cs create mode 100644 src/slskd/API/DTO/SearchRequest.cs create mode 100644 src/slskd/API/DTO/TokenResponse.cs create mode 100644 src/slskd/API/DTO/Transfer.cs create mode 100644 src/slskd/API/DTO/UserAddress.cs create mode 100644 src/slskd/API/DTO/UserDataResponse.cs delete mode 100644 src/slskd/Controllers/ApplicationController.cs delete mode 100644 src/slskd/Controllers/ConversationsController.cs delete mode 100644 src/slskd/Controllers/PublicChatController.cs delete mode 100644 src/slskd/Controllers/RoomsController.cs delete mode 100644 src/slskd/Controllers/SearchesController.cs delete mode 100644 src/slskd/Controllers/ServerController.cs delete mode 100644 src/slskd/Controllers/SessionController.cs delete mode 100644 src/slskd/Controllers/TransfersController.cs delete mode 100644 src/slskd/Controllers/UserController.cs delete mode 100644 src/slskd/DTO/ConnectRequest.cs delete mode 100644 src/slskd/DTO/LoginRequest.cs delete mode 100644 src/slskd/DTO/PrivateMessageResponse.cs delete mode 100644 src/slskd/DTO/QueueDownloadRequest.cs delete mode 100644 src/slskd/DTO/RoomInfoResponse.cs delete mode 100644 src/slskd/DTO/RoomMessageResponse.cs delete mode 100644 src/slskd/DTO/RoomResponse.cs delete mode 100644 src/slskd/DTO/SearchRequest.cs delete mode 100644 src/slskd/DTO/TokenResponse.cs delete mode 100644 src/slskd/DTO/Transfer.cs delete mode 100644 src/slskd/DTO/UserAddress.cs delete mode 100644 src/slskd/DTO/UserDataResponse.cs (limited to 'src') diff --git a/src/slskd/API/Controllers/ApplicationController.cs b/src/slskd/API/Controllers/ApplicationController.cs new file mode 100644 index 00000000..40353afa --- /dev/null +++ b/src/slskd/API/Controllers/ApplicationController.cs @@ -0,0 +1,59 @@ +namespace slskd.API.Controllers +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using System.Diagnostics; + using System; + using Microsoft.Extensions.Hosting; + using Soulseek; + + /// + /// Application + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ApplicationController : ControllerBase + { + private ISoulseekClient Client { get; } + private IHostApplicationLifetime Lifetime { get; } + + public ApplicationController(ISoulseekClient client, IHostApplicationLifetime lifetime) + { + Client = client; + Lifetime = lifetime; + } + + /// + /// Stops the application. + /// + /// + [HttpDelete] + [Authorize] + public IActionResult Shutdown() + { + Client.Disconnect("Shut down via API"); + + Lifetime.StopApplication(); + return NoContent(); + } + + /// + /// Restarts the application. + /// + /// + [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 new file mode 100644 index 00000000..10819b86 --- /dev/null +++ b/src/slskd/API/Controllers/ConversationsController.cs @@ -0,0 +1,198 @@ +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 Soulseek; + using slskd.API.DTO; + using slskd.Entities; + using slskd.Trackers; + + /// + /// Conversations + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ConversationsController : ControllerBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public ConversationsController(ISoulseekClient client, IConversationTracker tracker) + { + Client = client; + Tracker = tracker; + } + + private ISoulseekClient Client { get; } + private IConversationTracker Tracker { get; } + + /// + /// Acknowledges the given message id for the given username. + /// + /// + /// + /// + /// The request completed successfully. + /// + /// A conversation with the specified username, or a message matching the specified id could not be found. + /// + [HttpPut("{username}/{id}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(404)] + public async Task 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); + } + + /// + /// Acknowledges all messages for the given username. + /// + /// + /// + /// The request completed successfully. + /// A conversation with the specified username could not be found. + [HttpPut("{username}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(404)] + public async Task AcknowledgeAll([FromRoute]string username) + { + Tracker.Conversations.TryGetValue(username, out var conversation); + + if (conversation == default) + { + return NotFound(); + } + + var tasks = new List(); + + 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); + } + + /// + /// Deletes the conversation associated with the given username. + /// + /// + /// The request completed successfully. + /// A conversation with the specified username could not be found. + [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); + } + + /// + /// Gets all tracked conversations. + /// + /// + /// The request completed successfully. + [HttpGet("")] + [Authorize] + [ProducesResponseType(typeof(Dictionary>), 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); + } + + /// + /// Gets the conversation associated with the specified username. + /// + /// The username associated with the desired conversation. + /// + /// The request completed successfully. + /// A matching search was not found. + [HttpGet("{username}")] + [Authorize] + [ProducesResponseType(typeof(List), 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(); + } + + /// + /// Sends a private message to the specified username. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified message is null or empty. + [HttpPost("{username}")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(400)] + public async Task 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/PublicChatController.cs b/src/slskd/API/Controllers/PublicChatController.cs new file mode 100644 index 00000000..63a91ff4 --- /dev/null +++ b/src/slskd/API/Controllers/PublicChatController.cs @@ -0,0 +1,50 @@ +namespace slskd.API.Controllers +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + using System.Threading.Tasks; + + /// + /// Server + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class PublicChatController : ControllerBase + { + private ISoulseekClient Client { get; } + + public PublicChatController(ISoulseekClient client) + { + Client = client; + } + + /// + /// Starts public chat. + /// + /// + [HttpPost] + [Authorize] + public async Task Start() + { + await Client.StartPublicChatAsync(); + return StatusCode(StatusCodes.Status201Created); + } + + /// + /// Stops public chat. + /// + /// + [HttpDelete] + [Authorize] + public async Task Stop() + { + await Client.StopPublicChatAsync(); + return StatusCode(StatusCodes.Status204NoContent); + } + } +} diff --git a/src/slskd/API/Controllers/RoomsController.cs b/src/slskd/API/Controllers/RoomsController.cs new file mode 100644 index 00000000..29693bbc --- /dev/null +++ b/src/slskd/API/Controllers/RoomsController.cs @@ -0,0 +1,287 @@ +namespace slskd.API.Controllers +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using slskd.API.DTO; + using slskd.Entities; + using slskd.Trackers; + + /// + /// Rooms. + /// + [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; } + + /// + /// Gets all rooms. + /// + /// + /// The request completed successfully. + [HttpGet("joined")] + [Authorize] + [ProducesResponseType(typeof(Dictionary>), 200)] + public IActionResult GetAll() + { + return Ok(Tracker.Rooms.Keys); + } + + /// + /// Gets the specified room. + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [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(); + } + + /// + /// Sends a message to the specified room. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpPost("joined/{roomName}/messages")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task SendMessage([FromRoute]string roomName, [FromBody]string message) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.SendRoomMessageAsync(roomName, message); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// + /// Sets a ticker for the specified room. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpPost("joined/{roomName}/ticker")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task SetTicker([FromRoute] string roomName, [FromBody] string message) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.SetRoomTickerAsync(roomName, message); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// + /// Adds a member to a private room. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpPost("joined/{roomName}/members")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task AddRoomMember([FromRoute]string roomName, [FromBody]string username) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.AddPrivateRoomMemberAsync(roomName, username); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// + /// Gets the current list of users for the specified room. + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpGet("joined/{roomName}/users")] + [Authorize] + [ProducesResponseType(typeof(IList), 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(); + } + + /// + /// Gets the current list of messages for the specified room. + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpGet("joined/{roomName}/messages")] + [Authorize] + [ProducesResponseType(typeof(IList), 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(); + } + + /// + /// Gets a list of rooms from the server. + /// + /// + [HttpGet("available")] + [Authorize] + [ProducesResponseType(typeof(List), 200)] + public async Task GetRooms() + { + var list = await Client.GetRoomListAsync(); + + var response = new List(); + + 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); + } + + /// + /// Joins a room. + /// + /// + /// + /// The request completed successfully. + /// The room has already been joined. + [HttpPost("joined/{roomName}")] + [Authorize] + [ProducesResponseType(typeof(Room), 201)] + [ProducesResponseType(304)] + public async Task 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; + } + } + + /// + /// Leaves a room. + /// + /// + /// + /// The request completed successfully. + /// The room has not been joined. + [HttpDelete("joined/{roomName}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public async Task 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 new file mode 100644 index 00000000..46b6ec3e --- /dev/null +++ b/src/slskd/API/Controllers/SearchesController.cs @@ -0,0 +1,102 @@ +namespace slskd.API.Controllers +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + using slskd.API.DTO; + using slskd.Trackers; + + /// + /// Search + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class SearchesController : ControllerBase + { + private ISoulseekClient Client { get; } + private ISearchTracker Tracker { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + public SearchesController(ISoulseekClient client, ISearchTracker tracker) + { + Client = client; + Tracker = tracker; + } + + /// + /// Performs a search for the specified . + /// + /// The search request. + /// + /// The search completed successfully. + /// The specified was malformed. + /// The search terminated abnormally. + [HttpPost("")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(400)] + [ProducesResponseType(typeof(string), 500)] + public async Task Post([FromBody]SearchRequest request) + { + var id = request.Id ?? Guid.NewGuid(); + + var options = request.ToSearchOptions( + responseReceived: (e) => Tracker.AddOrUpdate(id, e), + stateChanged: (e) => Tracker.AddOrUpdate(id, e)); + + var results = new ConcurrentBag(); + + var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1)); + + try + { + await Client.SearchAsync(SearchQuery.FromText(searchText), (r) => results.Add(r), SearchScope.Network, request.Token, options); + return Ok(results); + } + catch (Exception ex) + { + return StatusCode(500, $"Search terminated abnormally: {ex.Message}"); + } + finally + { + results = null; + Tracker.TryRemove(id); + } + } + + /// + /// Gets the state of the search corresponding to the specified . + /// + /// The unique id of the search. + /// + /// The request completed successfully. + /// A matching search was not found. + [HttpGet("{id}")] + [Authorize] + [ProducesResponseType(typeof(Search), 200)] + [ProducesResponseType(404)] + public IActionResult GetById([FromRoute]Guid id) + { + Tracker.Searches.TryGetValue(id, out var search); + + if (search == default) + { + return NotFound(); + } + + return Ok(search); + } + } +} diff --git a/src/slskd/API/Controllers/ServerController.cs b/src/slskd/API/Controllers/ServerController.cs new file mode 100644 index 00000000..fb194974 --- /dev/null +++ b/src/slskd/API/Controllers/ServerController.cs @@ -0,0 +1,68 @@ +namespace slskd.API.Controllers +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + using System.Threading.Tasks; + using slskd.API.DTO; + + /// + /// Server + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ServerController : ControllerBase + { + private ISoulseekClient Client { get; } + + public ServerController(ISoulseekClient client) + { + Client = client; + } + + /// + /// Disconnects the client. + /// + /// + /// + [HttpDelete] + [Authorize] + public IActionResult Disconnect([FromBody]string message) + { + Client.Disconnect(message); + return NoContent(); + } + + /// + /// Connects the client. + /// + /// + /// + [HttpPost] + [Authorize] + public async Task 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"); + } + } +} diff --git a/src/slskd/API/Controllers/SessionController.cs b/src/slskd/API/Controllers/SessionController.cs new file mode 100644 index 00000000..d5b2c81a --- /dev/null +++ b/src/slskd/API/Controllers/SessionController.cs @@ -0,0 +1,132 @@ +using Microsoft.Extensions.Options; + +namespace slskd.API.Controllers +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Microsoft.IdentityModel.Tokens; + using System; + using System.Collections.Generic; + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using slskd.API.DTO; + using slskd; + using slskd.Configuration; + + /// + /// Session + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class SessionController : ControllerBase + { + private Options Options { get; set; } + private SymmetricSecurityKey JwtSigningKey { get; set; } + + public SessionController( + IOptionsSnapshot optionsSnapshot, + SymmetricSecurityKey jwtSigningKey) + { + Options = optionsSnapshot.Value; + JwtSigningKey = jwtSigningKey; + } + + /// + /// Checks whether security is enabled. + /// + /// + /// True if security is enabled, false otherwise. + [HttpGet] + [Route("enabled")] + [AllowAnonymous] + [ProducesResponseType(typeof(bool), 200)] + public IActionResult Enabled() + { + return base.Ok(!Options.Web.Authentication.Disable); + } + + /// + /// Checks whether the provided authentication is valid. + /// + /// + /// This is a no-op provided so that the application can test for an expired token on load. + /// + /// + /// The authentication is valid. + /// The authentication is is invalid. + [HttpGet] + [Route("")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(401)] + public IActionResult Check() + { + return Ok(); + } + + /// + /// Logs in. + /// + /// + /// + /// Login was successful. + /// Bad request. + /// Login failed. + [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() + { + 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; + } + } +} diff --git a/src/slskd/API/Controllers/TransfersController.cs b/src/slskd/API/Controllers/TransfersController.cs new file mode 100644 index 00000000..948bf7ff --- /dev/null +++ b/src/slskd/API/Controllers/TransfersController.cs @@ -0,0 +1,286 @@ +using Microsoft.Extensions.Options; + +namespace slskd.API.Controllers +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + using System; + using System.ComponentModel.DataAnnotations; + using System.IO; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using slskd.API.DTO; + using slskd.Trackers; + using slskd.Configuration; + + /// + /// Transfers + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class TransfersController : ControllerBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + public TransfersController(IOptionsSnapshot options, ISoulseekClient client, ITransferTracker tracker) + { + OutputDirectory = options.Value.Directories.Downloads; + Client = client; + Tracker = tracker; + } + + private ISoulseekClient Client { get; } + private string OutputDirectory { get; } + private ITransferTracker Tracker { get; } + + /// + /// Cancels the specified download. + /// + /// The username of the download source. + /// The id of the download. + /// A value indicating whether the tracked download should be removed after cancellation. + /// + /// The download was cancelled successfully. + /// The specified download was not found. + [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); + } + + /// + /// Cancels the specified upload. + /// + /// The username of the upload destination. + /// The id of the upload. + /// A value indicating whether the tracked upload should be removed after cancellation. + /// + /// The upload was cancelled successfully. + /// The specified upload was not found. + [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); + } + + /// + /// Enqueues the specified download. + /// + /// The username of the download source. + /// The download request. + /// + /// The download was successfully enqueued. + /// The download was rejected. + /// An unexpected error was encountered. + [HttpPost("downloads/{username}")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 500)] + public async Task Enqueue([FromRoute, Required]string username, [FromBody]QueueDownloadRequest request) + { + try + { + var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var stream = GetLocalFileStream(request.Filename, OutputDirectory); + + var cts = new CancellationTokenSource(); + + var downloadTask = 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); + + // 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 && downloadTask.Exception is AggregateException) + { + var rejected = downloadTask.Exception?.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); + + 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); + } + } + + /// + /// Gets all downloads. + /// + /// + /// The request completed successfully. + [HttpGet("downloads")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetDownloads() + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Download) + .ToMap()); + } + + /// + /// Gets all downloads for the specified username. + /// + /// + /// + /// The request completed successfully. + [HttpGet("downloads/{username}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetDownloads([FromRoute, Required]string username) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Download) + .FromUser(username) + .ToMap()); + } + + /// + /// Gets the downlaod for the specified username matching the specified filename, and requests + /// the current place in the remote queue of the specified download. + /// + /// The username of the download source. + /// The id of the download. + /// + /// The request completed successfully. + /// The specified download was not found. + [HttpGet("downloads/{username}/{id}")] + [Authorize] + [ProducesResponseType(typeof(DTO.Transfer), 200)] + [ProducesResponseType(404)] + public async Task 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); + } + + /// + /// Gets all uploads. + /// + /// + /// The request completed successfully. + [HttpGet("uploads")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads() + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .ToMap()); + } + + /// + /// Gets all uploads for the specified username. + /// + /// + /// + /// The request completed successfully. + [HttpGet("uploads/{username}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads([FromRoute, Required]string username) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .FromUser(username) + .ToMap()); + } + + /// + /// Gets the upload for the specified username matching the specified filename. + /// + /// The username of the upload destination. + /// The id of the upload. + /// + /// The request completed successfully. + [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.ToLocalOSPath(); + var path = $"{saveDirectory}{Path.DirectorySeparatorChar}{Path.GetDirectoryName(localFilename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(localFilename)), "")}"; + + if (!System.IO.Directory.Exists(path)) + { + System.IO.Directory.CreateDirectory(path); + } + + var sanitizedFilename = Path.GetFileName(localFilename); + + foreach (var c in Path.GetInvalidFileNameChars()) + { + sanitizedFilename = sanitizedFilename.Replace(c, '_'); + } + + localFilename = Path.Combine(path, sanitizedFilename); + + return new FileStream(localFilename, FileMode.Create); + } + + 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/Controllers/UserController.cs b/src/slskd/API/Controllers/UserController.cs new file mode 100644 index 00000000..73efca0f --- /dev/null +++ b/src/slskd/API/Controllers/UserController.cs @@ -0,0 +1,151 @@ +namespace slskd.API.Controllers +{ + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + using slskd.API.DTO; + using slskd.Trackers; + + /// + /// Users + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class UserController : ControllerBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public UserController(ISoulseekClient client, IBrowseTracker browseTracker) + { + Client = client; + BrowseTracker = browseTracker; + } + + private ISoulseekClient Client { get; } + private IBrowseTracker BrowseTracker { get; } + + /// + /// Retrieves the address of the specified . + /// + /// The username of the user. + /// + /// The request completed successfully. + [HttpGet("{username}/address")] + [Authorize] + [ProducesResponseType(typeof(UserAddress), 200)] + [ProducesResponseType(404)] + public async Task Address([FromRoute, Required]string username) + { + try + { + var endpoint = await Client.GetUserEndPointAsync(username); + return Ok(new UserAddress() { IPAddress = endpoint.Address.ToString(), Port = endpoint.Port }); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// + /// Retrieves the files shared by the specified . + /// + /// The username of the user. + /// + [HttpGet("{username}/browse")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(404)] + public async Task 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); + } + } + + /// + /// Retrieves the status of the current browse operation for the specified , if any. + /// + /// The username of the user. + /// + [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(); + } + + /// + /// Retrieves information about the specified . + /// + /// The username of the user. + /// + [HttpGet("{username}/info")] + [Authorize] + [ProducesResponseType(typeof(UserInfo), 200)] + [ProducesResponseType(404)] + public async Task Info([FromRoute, Required]string username) + { + try + { + var response = await Client.GetUserInfoAsync(username); + return Ok(response); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// + /// Retrieves status for the specified . + /// + /// The username of the user. + /// + [HttpGet("{username}/status")] + [Authorize] + [ProducesResponseType(typeof(UserStatus), 200)] + [ProducesResponseType(404)] + public async Task Status([FromRoute, Required]string username) + { + try + { + var response = await Client.GetUserStatusAsync(username); + return Ok(response); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/src/slskd/API/DTO/ConnectRequest.cs b/src/slskd/API/DTO/ConnectRequest.cs new file mode 100644 index 00000000..5d90073f --- /dev/null +++ b/src/slskd/API/DTO/ConnectRequest.cs @@ -0,0 +1,10 @@ +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 new file mode 100644 index 00000000..269a489b --- /dev/null +++ b/src/slskd/API/DTO/LoginRequest.cs @@ -0,0 +1,8 @@ +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 new file mode 100644 index 00000000..e20ce637 --- /dev/null +++ b/src/slskd/API/DTO/PrivateMessageResponse.cs @@ -0,0 +1,57 @@ +namespace slskd.API.DTO +{ + using System; + using slskd.Entities; + + public class PrivateMessageResponse + { + /// + /// A value indicating whether the message has been acknowledged. + /// + public bool Acknowledged { get; set; } = false; + + /// + /// The unique message id, used to acknowledge receipt. + /// + public int Id { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// A value indicating whether the message was replayed. + /// + public bool Replayed { get; set; } + + /// + /// The UTC timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + /// + /// A value indicating whether this message was sent by the currently logged in user. + /// + 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 new file mode 100644 index 00000000..fcd279ab --- /dev/null +++ b/src/slskd/API/DTO/QueueDownloadRequest.cs @@ -0,0 +1,20 @@ +namespace slskd.API.DTO +{ + public class QueueDownloadRequest + { + /// + /// Gets or sets the filename to download. + /// + public string Filename { get; set; } + + /// + /// Gets or sets the size of the file. + /// + public long? Size { get; set; } + + /// + /// Gets or sets the optional transfer token. + /// + public int? Token { get; set; } + } +} diff --git a/src/slskd/API/DTO/RoomInfoResponse.cs b/src/slskd/API/DTO/RoomInfoResponse.cs new file mode 100644 index 00000000..8b9a3cb6 --- /dev/null +++ b/src/slskd/API/DTO/RoomInfoResponse.cs @@ -0,0 +1,43 @@ +namespace slskd.API.DTO +{ + using Soulseek; + + public class RoomInfoResponse + { + /// + /// Gets the room name. + /// + public string Name { get; init; } + + /// + /// Gets the number of users in the room. + /// + public int UserCount { get; init; } + + /// + /// Gets a value indicating whether the room is private. + /// + public bool IsPrivate { get; init; } + + /// + /// Gets a value indicating whether the room is owned by the currently logged in user. + /// + public bool IsOwned { get; init; } + + /// + /// Gets a value indicating whether the room is moderated by the currently logged in user. + /// + 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 new file mode 100644 index 00000000..3a804b65 --- /dev/null +++ b/src/slskd/API/DTO/RoomMessageResponse.cs @@ -0,0 +1,45 @@ +namespace slskd.API.DTO +{ + using System; + using slskd.Entities; + + public class RoomMessageResponse + { + /// + /// The timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// The room to which the message pertains. + /// + public string RoomName { get; set; } + + /// + /// A value indicating whether this user data belongs to the currently logged in user. + /// + 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 new file mode 100644 index 00000000..d7708da7 --- /dev/null +++ b/src/slskd/API/DTO/RoomResponse.cs @@ -0,0 +1,58 @@ +namespace slskd.API.DTO +{ + using slskd.Entities; + using System.Collections.Generic; + using System.Linq; + + public class RoomResponse + { + /// + /// The room name. + /// + public string Name { get; set; } + + /// + /// A value indicating whether the room is private. + /// + public bool IsPrivate { get; set; } + + /// + /// The number of operators in the room, if private. + /// + public int? OperatorCount { get; set; } + + /// + /// The operators in the room, if private. + /// + public IList Operators { get; set; } + + /// + /// The owner of the room, if private. + /// + public string Owner { get; set; } + + /// + /// The list of users in the room. + /// + public IEnumerable Users { get; set; } = new List(); + + /// + /// The list of messages. + /// + public IEnumerable Messages { get; set; } = new List(); + + 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(), + Messages = new List() + }; + } + } +} diff --git a/src/slskd/API/DTO/SearchRequest.cs b/src/slskd/API/DTO/SearchRequest.cs new file mode 100644 index 00000000..2e6c61e6 --- /dev/null +++ b/src/slskd/API/DTO/SearchRequest.cs @@ -0,0 +1,99 @@ +using Soulseek; +using System; + +namespace slskd.API.DTO +{ + /// + /// A search request. + /// + public class SearchRequest + { + /// + /// Gets or sets the unique search identifier + /// + public Guid? Id { get; set; } + + /// + /// Gets or sets the maximum number of file results to accept before the search is considered complete. (Default = 10,000). + /// + public int? FileLimit { get; set; } + + /// + /// Gets or sets a value indicating whether responses are to be filtered. (Default = true). + /// + public bool? FilterResponses { get; set; } + + /// + /// Gets or sets the maximum queue depth a peer may have in order for a response to be processed. (Default = 1000000). + /// + public int? MaximumPeerQueueLength { get; set; } + + /// + /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed. + /// (Default = 0). + /// + public int? MinimumPeerFreeUploadSlots { get; set; } + + /// + /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0). + /// + public int? MinimumPeerUploadSpeed { get; set; } + + /// + /// Gets or sets the minimum number of files a response must contain in order to be processed. (Default = 1). + /// + public int? MinimumResponseFileCount { get; set; } + + /// + /// Gets or sets the maximum number of search results to accept before the search is considered complete. (Default = 100). + /// + public int? ResponseLimit { get; set; } + + /// + /// Gets or sets the search text. + /// + public string SearchText { get; set; } + + /// + /// Gets or sets the search timeout value, in seconds, used to determine when the search is complete. (Default = 15). + /// + /// The timeout duration is from the time of the last response. + public int? SearchTimeout { get; set; } + + /// + /// Gets or sets the search token. + /// + public int? Token { get; set; } + + /// + /// Maps to a new instance of . + /// + /// + /// + /// + /// + /// + public SearchOptions ToSearchOptions( + Func responseFilter = null, + Func fileFilter = null, + Action stateChanged = null, + Action 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 new file mode 100644 index 00000000..3490d570 --- /dev/null +++ b/src/slskd/API/DTO/TokenResponse.cs @@ -0,0 +1,50 @@ +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; + } + + [JsonIgnore] + private JwtSecurityToken JwtSecurityToken { get; } + + /// + /// Gets the Access Token string. + /// + public string Token => new JwtSecurityTokenHandler().WriteToken(JwtSecurityToken); + + /// + /// Gets the time at which the Access Token expires. + /// + public long Expires => ((DateTimeOffset)JwtSecurityToken.ValidTo).ToUnixTimeSeconds(); + + /// + /// Gets the time at which the Access Token was issued. + /// + public long Issued => ((DateTimeOffset)JwtSecurityToken.ValidFrom).ToUnixTimeSeconds(); + + /// + /// Gets the value of the Name claim from the Access Token. + /// + public string Name => JwtSecurityToken.Claims.Where(c => c.Type == ClaimTypes.Name).SingleOrDefault().Value; + + /// + /// Gets the value of the Not Before claim from the Access Token. + /// + public long NotBefore => long.Parse(JwtSecurityToken.Claims.Where(c => c.Type == "nbf").SingleOrDefault().Value); + + /// + /// Gets the Token type. + /// + public string TokenType => JwtBearerDefaults.AuthenticationScheme; + } +} \ No newline at end of file diff --git a/src/slskd/API/DTO/Transfer.cs b/src/slskd/API/DTO/Transfer.cs new file mode 100644 index 00000000..34639a40 --- /dev/null +++ b/src/slskd/API/DTO/Transfer.cs @@ -0,0 +1,131 @@ +namespace slskd.API.DTO +{ + using Soulseek; + using System; + using System.Net; + + /// + /// A single file transfer. + /// + public class Transfer + { + /// + /// Gets the current average transfer speed. + /// + public double AverageSpeed { get; set; } + + /// + /// Gets the number of remaining bytes to be transferred. + /// + public long BytesRemaining { get; set; } + + /// + /// Gets the total number of bytes transferred. + /// + public long BytesTransferred { get; set; } + + /// + /// Gets the transfer direction. + /// + public TransferDirection Direction { get; set; } + + /// + /// Gets the current duration of the transfer, if it has been started. + /// + public double? ElapsedTime { get; set; } + + /// + /// Gets the UTC time at which the transfer transitioned into the state. + /// + public DateTime? EndTime { get; set; } + + /// + /// Gets the filename of the file to be transferred. + /// + public string Filename { get; set; } + + /// + /// Gets the transfer id. + /// + public string Id => Filename.Sha1(); + + /// + /// Gets the ip endpoint of the remote transfer connection, if one has been established. + /// + public IPEndPoint IPEndPoint { get; set; } + + /// + /// Gets the current progress in percent. + /// + public double PercentComplete { get; set; } + + /// + /// Gets the current place in queue, if it has been fetched. + /// + public int? PlaceInQueue { get; set; } + + /// + /// Gets the projected remaining duration of the transfer. + /// + public double? RemainingTime { get; set; } + + /// + /// Gets the remote unique token for the transfer. + /// + public int? RemoteToken { get; set; } + + /// + /// Gets the size of the file to be transferred, in bytes. + /// + public long Size { get; set; } + + /// + /// Gets the starting offset of the transfer, in bytes. + /// + public long StartOffset { get; set; } + + /// + /// Gets the UTC time at which the transfer transitioned into the state. + /// + public DateTime? StartTime { get; set; } + + /// + /// Gets the state of the transfer. + /// + public TransferStates State { get; set; } + + /// + /// Gets the unique token for the transfer. + /// + public int Token { get; set; } + + /// + /// Gets the username of the peer to or from which the file is to be transferred. + /// + 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/UserAddress.cs b/src/slskd/API/DTO/UserAddress.cs new file mode 100644 index 00000000..4fe7dc4a --- /dev/null +++ b/src/slskd/API/DTO/UserAddress.cs @@ -0,0 +1,18 @@ +namespace slskd.API.DTO +{ + /// + /// A user's IP address and port. + /// + public class UserAddress + { + /// + /// Gets or sets the IP address. + /// + public string IPAddress { get; set; } + + /// + /// Gets or sets the port. + /// + public int Port { get; set; } + } +} diff --git a/src/slskd/API/DTO/UserDataResponse.cs b/src/slskd/API/DTO/UserDataResponse.cs new file mode 100644 index 00000000..5d79639c --- /dev/null +++ b/src/slskd/API/DTO/UserDataResponse.cs @@ -0,0 +1,68 @@ +namespace slskd.API.DTO +{ + using Soulseek; + + public class UserDataResponse + { + /// + /// The average upload speed of the user. + /// + public int AverageSpeed { get; set; } + + /// + /// The user's country code, if provided. + /// + public string CountryCode { get; set; } + + /// + /// The number of directories shared by the user. + /// + public int DirectoryCount { get; set; } + + /// + /// The number of active user downloads. + /// + public long DownloadCount { get; set; } + + /// + /// The number of files shared by the user. + /// + public int FileCount { get; set; } + + /// + /// A value indicating whether this user data belongs to the currently logged in user. + /// + public bool? Self { get; set; } + + /// + /// The number of the user's free download slots, if provided. + /// + public int? SlotsFree { get; set; } + + /// + /// The status of the user (0 = offline, 1 = away, 2 = online). + /// + public UserPresence Status { get; set; } + + /// + /// The username of the user. + /// + 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 diff --git a/src/slskd/Controllers/ApplicationController.cs b/src/slskd/Controllers/ApplicationController.cs deleted file mode 100644 index cc9d56a1..00000000 --- a/src/slskd/Controllers/ApplicationController.cs +++ /dev/null @@ -1,59 +0,0 @@ -namespace slskd.Controllers -{ - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using System.Diagnostics; - using System; - using Microsoft.Extensions.Hosting; - using Soulseek; - - /// - /// Application - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class ApplicationController : ControllerBase - { - private ISoulseekClient Client { get; } - private IHostApplicationLifetime Lifetime { get; } - - public ApplicationController(ISoulseekClient client, IHostApplicationLifetime lifetime) - { - Client = client; - Lifetime = lifetime; - } - - /// - /// Stops the application. - /// - /// - [HttpDelete] - [Authorize] - public IActionResult Shutdown() - { - Client.Disconnect("Shut down via API"); - - Lifetime.StopApplication(); - return NoContent(); - } - - /// - /// Restarts the application. - /// - /// - [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/Controllers/ConversationsController.cs b/src/slskd/Controllers/ConversationsController.cs deleted file mode 100644 index ccebf7c5..00000000 --- a/src/slskd/Controllers/ConversationsController.cs +++ /dev/null @@ -1,198 +0,0 @@ -namespace slskd.Controllers -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - using slskd.DTO; - using slskd.Entities; - using slskd.Trackers; - - /// - /// Conversations - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class ConversationsController : ControllerBase - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public ConversationsController(ISoulseekClient client, IConversationTracker tracker) - { - Client = client; - Tracker = tracker; - } - - private ISoulseekClient Client { get; } - private IConversationTracker Tracker { get; } - - /// - /// Acknowledges the given message id for the given username. - /// - /// - /// - /// - /// The request completed successfully. - /// - /// A conversation with the specified username, or a message matching the specified id could not be found. - /// - [HttpPut("{username}/{id}")] - [Authorize] - [ProducesResponseType(200)] - [ProducesResponseType(404)] - public async Task 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); - } - - /// - /// Acknowledges all messages for the given username. - /// - /// - /// - /// The request completed successfully. - /// A conversation with the specified username could not be found. - [HttpPut("{username}")] - [Authorize] - [ProducesResponseType(200)] - [ProducesResponseType(404)] - public async Task AcknowledgeAll([FromRoute]string username) - { - Tracker.Conversations.TryGetValue(username, out var conversation); - - if (conversation == default) - { - return NotFound(); - } - - var tasks = new List(); - - 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); - } - - /// - /// Deletes the conversation associated with the given username. - /// - /// - /// The request completed successfully. - /// A conversation with the specified username could not be found. - [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); - } - - /// - /// Gets all tracked conversations. - /// - /// - /// The request completed successfully. - [HttpGet("")] - [Authorize] - [ProducesResponseType(typeof(Dictionary>), 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); - } - - /// - /// Gets the conversation associated with the specified username. - /// - /// The username associated with the desired conversation. - /// - /// The request completed successfully. - /// A matching search was not found. - [HttpGet("{username}")] - [Authorize] - [ProducesResponseType(typeof(List), 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(); - } - - /// - /// Sends a private message to the specified username. - /// - /// - /// - /// - /// The request completed successfully. - /// The specified message is null or empty. - [HttpPost("{username}")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(400)] - public async Task 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/Controllers/PublicChatController.cs b/src/slskd/Controllers/PublicChatController.cs deleted file mode 100644 index 10ad9234..00000000 --- a/src/slskd/Controllers/PublicChatController.cs +++ /dev/null @@ -1,50 +0,0 @@ -namespace slskd.Controllers -{ - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - using System.Threading.Tasks; - - /// - /// Server - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class PublicChatController : ControllerBase - { - private ISoulseekClient Client { get; } - - public PublicChatController(ISoulseekClient client) - { - Client = client; - } - - /// - /// Starts public chat. - /// - /// - [HttpPost] - [Authorize] - public async Task Start() - { - await Client.StartPublicChatAsync(); - return StatusCode(StatusCodes.Status201Created); - } - - /// - /// Stops public chat. - /// - /// - [HttpDelete] - [Authorize] - public async Task Stop() - { - await Client.StopPublicChatAsync(); - return StatusCode(StatusCodes.Status204NoContent); - } - } -} diff --git a/src/slskd/Controllers/RoomsController.cs b/src/slskd/Controllers/RoomsController.cs deleted file mode 100644 index 34557d27..00000000 --- a/src/slskd/Controllers/RoomsController.cs +++ /dev/null @@ -1,287 +0,0 @@ -namespace slskd.Controllers -{ - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using slskd.DTO; - using slskd.Entities; - using slskd.Trackers; - - /// - /// Rooms. - /// - [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; } - - /// - /// Gets all rooms. - /// - /// - /// The request completed successfully. - [HttpGet("joined")] - [Authorize] - [ProducesResponseType(typeof(Dictionary>), 200)] - public IActionResult GetAll() - { - return Ok(Tracker.Rooms.Keys); - } - - /// - /// Gets the specified room. - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [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(); - } - - /// - /// Sends a message to the specified room. - /// - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpPost("joined/{roomName}/messages")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(404)] - public async Task SendMessage([FromRoute]string roomName, [FromBody]string message) - { - if (Tracker.TryGet(roomName, out var _)) - { - await Client.SendRoomMessageAsync(roomName, message); - return StatusCode(StatusCodes.Status201Created); - } - - return NotFound(); - } - - /// - /// Sets a ticker for the specified room. - /// - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpPost("joined/{roomName}/ticker")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(404)] - public async Task SetTicker([FromRoute] string roomName, [FromBody] string message) - { - if (Tracker.TryGet(roomName, out var _)) - { - await Client.SetRoomTickerAsync(roomName, message); - return StatusCode(StatusCodes.Status201Created); - } - - return NotFound(); - } - - /// - /// Adds a member to a private room. - /// - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpPost("joined/{roomName}/members")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(404)] - public async Task AddRoomMember([FromRoute]string roomName, [FromBody]string username) - { - if (Tracker.TryGet(roomName, out var _)) - { - await Client.AddPrivateRoomMemberAsync(roomName, username); - return StatusCode(StatusCodes.Status201Created); - } - - return NotFound(); - } - - /// - /// Gets the current list of users for the specified room. - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpGet("joined/{roomName}/users")] - [Authorize] - [ProducesResponseType(typeof(IList), 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(); - } - - /// - /// Gets the current list of messages for the specified room. - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpGet("joined/{roomName}/messages")] - [Authorize] - [ProducesResponseType(typeof(IList), 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(); - } - - /// - /// Gets a list of rooms from the server. - /// - /// - [HttpGet("available")] - [Authorize] - [ProducesResponseType(typeof(List), 200)] - public async Task GetRooms() - { - var list = await Client.GetRoomListAsync(); - - var response = new List(); - - 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); - } - - /// - /// Joins a room. - /// - /// - /// - /// The request completed successfully. - /// The room has already been joined. - [HttpPost("joined/{roomName}")] - [Authorize] - [ProducesResponseType(typeof(Room), 201)] - [ProducesResponseType(304)] - public async Task 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; - } - } - - /// - /// Leaves a room. - /// - /// - /// - /// The request completed successfully. - /// The room has not been joined. - [HttpDelete("joined/{roomName}")] - [Authorize] - [ProducesResponseType(204)] - [ProducesResponseType(404)] - public async Task 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/Controllers/SearchesController.cs b/src/slskd/Controllers/SearchesController.cs deleted file mode 100644 index 28637262..00000000 --- a/src/slskd/Controllers/SearchesController.cs +++ /dev/null @@ -1,102 +0,0 @@ -namespace slskd.Controllers -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - using slskd.DTO; - using slskd.Trackers; - - /// - /// Search - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class SearchesController : ControllerBase - { - private ISoulseekClient Client { get; } - private ISearchTracker Tracker { get; } - - /// - /// Initializes a new instance of the class. - /// - /// - /// - public SearchesController(ISoulseekClient client, ISearchTracker tracker) - { - Client = client; - Tracker = tracker; - } - - /// - /// Performs a search for the specified . - /// - /// The search request. - /// - /// The search completed successfully. - /// The specified was malformed. - /// The search terminated abnormally. - [HttpPost("")] - [Authorize] - [ProducesResponseType(typeof(IEnumerable), 200)] - [ProducesResponseType(400)] - [ProducesResponseType(typeof(string), 500)] - public async Task Post([FromBody]SearchRequest request) - { - var id = request.Id ?? Guid.NewGuid(); - - var options = request.ToSearchOptions( - responseReceived: (e) => Tracker.AddOrUpdate(id, e), - stateChanged: (e) => Tracker.AddOrUpdate(id, e)); - - var results = new ConcurrentBag(); - - var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1)); - - try - { - await Client.SearchAsync(SearchQuery.FromText(searchText), (r) => results.Add(r), SearchScope.Network, request.Token, options); - return Ok(results); - } - catch (Exception ex) - { - return StatusCode(500, $"Search terminated abnormally: {ex.Message}"); - } - finally - { - results = null; - Tracker.TryRemove(id); - } - } - - /// - /// Gets the state of the search corresponding to the specified . - /// - /// The unique id of the search. - /// - /// The request completed successfully. - /// A matching search was not found. - [HttpGet("{id}")] - [Authorize] - [ProducesResponseType(typeof(Search), 200)] - [ProducesResponseType(404)] - public IActionResult GetById([FromRoute]Guid id) - { - Tracker.Searches.TryGetValue(id, out var search); - - if (search == default) - { - return NotFound(); - } - - return Ok(search); - } - } -} diff --git a/src/slskd/Controllers/ServerController.cs b/src/slskd/Controllers/ServerController.cs deleted file mode 100644 index ed6e84c8..00000000 --- a/src/slskd/Controllers/ServerController.cs +++ /dev/null @@ -1,68 +0,0 @@ -namespace slskd.Controllers -{ - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - using System.Threading.Tasks; - using slskd.DTO; - - /// - /// Server - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class ServerController : ControllerBase - { - private ISoulseekClient Client { get; } - - public ServerController(ISoulseekClient client) - { - Client = client; - } - - /// - /// Disconnects the client. - /// - /// - /// - [HttpDelete] - [Authorize] - public IActionResult Disconnect([FromBody]string message) - { - Client.Disconnect(message); - return NoContent(); - } - - /// - /// Connects the client. - /// - /// - /// - [HttpPost] - [Authorize] - public async Task 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"); - } - } -} diff --git a/src/slskd/Controllers/SessionController.cs b/src/slskd/Controllers/SessionController.cs deleted file mode 100644 index 24be09f1..00000000 --- a/src/slskd/Controllers/SessionController.cs +++ /dev/null @@ -1,132 +0,0 @@ -using Microsoft.Extensions.Options; - -namespace slskd.Controllers -{ - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Microsoft.IdentityModel.Tokens; - using System; - using System.Collections.Generic; - using System.IdentityModel.Tokens.Jwt; - using System.Security.Claims; - using slskd.DTO; - using slskd; - using slskd.Configuration; - - /// - /// Session - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class SessionController : ControllerBase - { - private Options Options { get; set; } - private SymmetricSecurityKey JwtSigningKey { get; set; } - - public SessionController( - IOptionsSnapshot optionsSnapshot, - SymmetricSecurityKey jwtSigningKey) - { - Options = optionsSnapshot.Value; - JwtSigningKey = jwtSigningKey; - } - - /// - /// Checks whether security is enabled. - /// - /// - /// True if security is enabled, false otherwise. - [HttpGet] - [Route("enabled")] - [AllowAnonymous] - [ProducesResponseType(typeof(bool), 200)] - public IActionResult Enabled() - { - return base.Ok(!Options.Web.Authentication.Disable); - } - - /// - /// Checks whether the provided authentication is valid. - /// - /// - /// This is a no-op provided so that the application can test for an expired token on load. - /// - /// - /// The authentication is valid. - /// The authentication is is invalid. - [HttpGet] - [Route("")] - [Authorize] - [ProducesResponseType(200)] - [ProducesResponseType(401)] - public IActionResult Check() - { - return Ok(); - } - - /// - /// Logs in. - /// - /// - /// - /// Login was successful. - /// Bad request. - /// Login failed. - [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() - { - 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; - } - } -} diff --git a/src/slskd/Controllers/TransfersController.cs b/src/slskd/Controllers/TransfersController.cs deleted file mode 100644 index d19ec91d..00000000 --- a/src/slskd/Controllers/TransfersController.cs +++ /dev/null @@ -1,286 +0,0 @@ -using Microsoft.Extensions.Options; - -namespace slskd.Controllers -{ - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - using System; - using System.ComponentModel.DataAnnotations; - using System.IO; - using System.Linq; - using System.Threading; - using System.Threading.Tasks; - using slskd.DTO; - using slskd.Trackers; - using slskd.Configuration; - - /// - /// Transfers - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class TransfersController : ControllerBase - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// - public TransfersController(IOptionsSnapshot options, ISoulseekClient client, ITransferTracker tracker) - { - OutputDirectory = options.Value.Directories.Downloads; - Client = client; - Tracker = tracker; - } - - private ISoulseekClient Client { get; } - private string OutputDirectory { get; } - private ITransferTracker Tracker { get; } - - /// - /// Cancels the specified download. - /// - /// The username of the download source. - /// The id of the download. - /// A value indicating whether the tracked download should be removed after cancellation. - /// - /// The download was cancelled successfully. - /// The specified download was not found. - [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); - } - - /// - /// Cancels the specified upload. - /// - /// The username of the upload destination. - /// The id of the upload. - /// A value indicating whether the tracked upload should be removed after cancellation. - /// - /// The upload was cancelled successfully. - /// The specified upload was not found. - [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); - } - - /// - /// Enqueues the specified download. - /// - /// The username of the download source. - /// The download request. - /// - /// The download was successfully enqueued. - /// The download was rejected. - /// An unexpected error was encountered. - [HttpPost("downloads/{username}")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(typeof(string), 403)] - [ProducesResponseType(typeof(string), 500)] - public async Task Enqueue([FromRoute, Required]string username, [FromBody]QueueDownloadRequest request) - { - try - { - var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var stream = GetLocalFileStream(request.Filename, OutputDirectory); - - var cts = new CancellationTokenSource(); - - var downloadTask = 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); - - // 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 && downloadTask.Exception is AggregateException) - { - var rejected = downloadTask.Exception?.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); - - 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); - } - } - - /// - /// Gets all downloads. - /// - /// - /// The request completed successfully. - [HttpGet("downloads")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetDownloads() - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Download) - .ToMap()); - } - - /// - /// Gets all downloads for the specified username. - /// - /// - /// - /// The request completed successfully. - [HttpGet("downloads/{username}")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetDownloads([FromRoute, Required]string username) - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Download) - .FromUser(username) - .ToMap()); - } - - /// - /// Gets the downlaod for the specified username matching the specified filename, and requests - /// the current place in the remote queue of the specified download. - /// - /// The username of the download source. - /// The id of the download. - /// - /// The request completed successfully. - /// The specified download was not found. - [HttpGet("downloads/{username}/{id}")] - [Authorize] - [ProducesResponseType(typeof(DTO.Transfer), 200)] - [ProducesResponseType(404)] - public async Task 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); - } - - /// - /// Gets all uploads. - /// - /// - /// The request completed successfully. - [HttpGet("uploads")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetUploads() - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .ToMap()); - } - - /// - /// Gets all uploads for the specified username. - /// - /// - /// - /// The request completed successfully. - [HttpGet("uploads/{username}")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required]string username) - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .FromUser(username) - .ToMap()); - } - - /// - /// Gets the upload for the specified username matching the specified filename. - /// - /// The username of the upload destination. - /// The id of the upload. - /// - /// The request completed successfully. - [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.ToLocalOSPath(); - var path = $"{saveDirectory}{Path.DirectorySeparatorChar}{Path.GetDirectoryName(localFilename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(localFilename)), "")}"; - - if (!System.IO.Directory.Exists(path)) - { - System.IO.Directory.CreateDirectory(path); - } - - var sanitizedFilename = Path.GetFileName(localFilename); - - foreach (var c in Path.GetInvalidFileNameChars()) - { - sanitizedFilename = sanitizedFilename.Replace(c, '_'); - } - - localFilename = Path.Combine(path, sanitizedFilename); - - return new FileStream(localFilename, FileMode.Create); - } - - 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/Controllers/UserController.cs b/src/slskd/Controllers/UserController.cs deleted file mode 100644 index e4a0859f..00000000 --- a/src/slskd/Controllers/UserController.cs +++ /dev/null @@ -1,151 +0,0 @@ -namespace slskd.Controllers -{ - using System.Collections.Generic; - using System.ComponentModel.DataAnnotations; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - using slskd.DTO; - using slskd.Trackers; - - /// - /// Users - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class UserController : ControllerBase - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public UserController(ISoulseekClient client, IBrowseTracker browseTracker) - { - Client = client; - BrowseTracker = browseTracker; - } - - private ISoulseekClient Client { get; } - private IBrowseTracker BrowseTracker { get; } - - /// - /// Retrieves the address of the specified . - /// - /// The username of the user. - /// - /// The request completed successfully. - [HttpGet("{username}/address")] - [Authorize] - [ProducesResponseType(typeof(UserAddress), 200)] - [ProducesResponseType(404)] - public async Task Address([FromRoute, Required]string username) - { - try - { - var endpoint = await Client.GetUserEndPointAsync(username); - return Ok(new UserAddress() { IPAddress = endpoint.Address.ToString(), Port = endpoint.Port }); - } - catch (UserOfflineException ex) - { - return NotFound(ex.Message); - } - } - - /// - /// Retrieves the files shared by the specified . - /// - /// The username of the user. - /// - [HttpGet("{username}/browse")] - [Authorize] - [ProducesResponseType(typeof(IEnumerable), 200)] - [ProducesResponseType(404)] - public async Task 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); - } - } - - /// - /// Retrieves the status of the current browse operation for the specified , if any. - /// - /// The username of the user. - /// - [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(); - } - - /// - /// Retrieves information about the specified . - /// - /// The username of the user. - /// - [HttpGet("{username}/info")] - [Authorize] - [ProducesResponseType(typeof(UserInfo), 200)] - [ProducesResponseType(404)] - public async Task Info([FromRoute, Required]string username) - { - try - { - var response = await Client.GetUserInfoAsync(username); - return Ok(response); - } - catch (UserOfflineException ex) - { - return NotFound(ex.Message); - } - } - - /// - /// Retrieves status for the specified . - /// - /// The username of the user. - /// - [HttpGet("{username}/status")] - [Authorize] - [ProducesResponseType(typeof(UserStatus), 200)] - [ProducesResponseType(404)] - public async Task Status([FromRoute, Required]string username) - { - try - { - var response = await Client.GetUserStatusAsync(username); - return Ok(response); - } - catch (UserOfflineException ex) - { - return NotFound(ex.Message); - } - } - } -} \ No newline at end of file diff --git a/src/slskd/DTO/ConnectRequest.cs b/src/slskd/DTO/ConnectRequest.cs deleted file mode 100644 index 6d2203b7..00000000 --- a/src/slskd/DTO/ConnectRequest.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace slskd.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/DTO/LoginRequest.cs b/src/slskd/DTO/LoginRequest.cs deleted file mode 100644 index 04c3dd65..00000000 --- a/src/slskd/DTO/LoginRequest.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace slskd.DTO -{ - public class LoginRequest - { - public string Username { get; set; } - public string Password { get; set; } - } -} diff --git a/src/slskd/DTO/PrivateMessageResponse.cs b/src/slskd/DTO/PrivateMessageResponse.cs deleted file mode 100644 index fb60be32..00000000 --- a/src/slskd/DTO/PrivateMessageResponse.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace slskd.DTO -{ - using System; - using slskd.Entities; - - public class PrivateMessageResponse - { - /// - /// A value indicating whether the message has been acknowledged. - /// - public bool Acknowledged { get; set; } = false; - - /// - /// The unique message id, used to acknowledge receipt. - /// - public int Id { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// A value indicating whether the message was replayed. - /// - public bool Replayed { get; set; } - - /// - /// The UTC timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - /// - /// A value indicating whether this message was sent by the currently logged in user. - /// - 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/DTO/QueueDownloadRequest.cs b/src/slskd/DTO/QueueDownloadRequest.cs deleted file mode 100644 index c2c1c2d4..00000000 --- a/src/slskd/DTO/QueueDownloadRequest.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace slskd.DTO -{ - public class QueueDownloadRequest - { - /// - /// Gets or sets the filename to download. - /// - public string Filename { get; set; } - - /// - /// Gets or sets the size of the file. - /// - public long? Size { get; set; } - - /// - /// Gets or sets the optional transfer token. - /// - public int? Token { get; set; } - } -} diff --git a/src/slskd/DTO/RoomInfoResponse.cs b/src/slskd/DTO/RoomInfoResponse.cs deleted file mode 100644 index 0b0aadf0..00000000 --- a/src/slskd/DTO/RoomInfoResponse.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace slskd.DTO -{ - using Soulseek; - - public class RoomInfoResponse - { - /// - /// Gets the room name. - /// - public string Name { get; init; } - - /// - /// Gets the number of users in the room. - /// - public int UserCount { get; init; } - - /// - /// Gets a value indicating whether the room is private. - /// - public bool IsPrivate { get; init; } - - /// - /// Gets a value indicating whether the room is owned by the currently logged in user. - /// - public bool IsOwned { get; init; } - - /// - /// Gets a value indicating whether the room is moderated by the currently logged in user. - /// - 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/DTO/RoomMessageResponse.cs b/src/slskd/DTO/RoomMessageResponse.cs deleted file mode 100644 index b64bedf3..00000000 --- a/src/slskd/DTO/RoomMessageResponse.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace slskd.DTO -{ - using System; - using slskd.Entities; - - public class RoomMessageResponse - { - /// - /// The timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// The room to which the message pertains. - /// - public string RoomName { get; set; } - - /// - /// A value indicating whether this user data belongs to the currently logged in user. - /// - 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/DTO/RoomResponse.cs b/src/slskd/DTO/RoomResponse.cs deleted file mode 100644 index 22ea845a..00000000 --- a/src/slskd/DTO/RoomResponse.cs +++ /dev/null @@ -1,58 +0,0 @@ -namespace slskd.DTO -{ - using slskd.Entities; - using System.Collections.Generic; - using System.Linq; - - public class RoomResponse - { - /// - /// The room name. - /// - public string Name { get; set; } - - /// - /// A value indicating whether the room is private. - /// - public bool IsPrivate { get; set; } - - /// - /// The number of operators in the room, if private. - /// - public int? OperatorCount { get; set; } - - /// - /// The operators in the room, if private. - /// - public IList Operators { get; set; } - - /// - /// The owner of the room, if private. - /// - public string Owner { get; set; } - - /// - /// The list of users in the room. - /// - public IEnumerable Users { get; set; } = new List(); - - /// - /// The list of messages. - /// - public IEnumerable Messages { get; set; } = new List(); - - 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(), - Messages = new List() - }; - } - } -} diff --git a/src/slskd/DTO/SearchRequest.cs b/src/slskd/DTO/SearchRequest.cs deleted file mode 100644 index 7123a348..00000000 --- a/src/slskd/DTO/SearchRequest.cs +++ /dev/null @@ -1,99 +0,0 @@ -using Soulseek; -using System; - -namespace slskd.DTO -{ - /// - /// A search request. - /// - public class SearchRequest - { - /// - /// Gets or sets the unique search identifier - /// - public Guid? Id { get; set; } - - /// - /// Gets or sets the maximum number of file results to accept before the search is considered complete. (Default = 10,000). - /// - public int? FileLimit { get; set; } - - /// - /// Gets or sets a value indicating whether responses are to be filtered. (Default = true). - /// - public bool? FilterResponses { get; set; } - - /// - /// Gets or sets the maximum queue depth a peer may have in order for a response to be processed. (Default = 1000000). - /// - public int? MaximumPeerQueueLength { get; set; } - - /// - /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed. - /// (Default = 0). - /// - public int? MinimumPeerFreeUploadSlots { get; set; } - - /// - /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0). - /// - public int? MinimumPeerUploadSpeed { get; set; } - - /// - /// Gets or sets the minimum number of files a response must contain in order to be processed. (Default = 1). - /// - public int? MinimumResponseFileCount { get; set; } - - /// - /// Gets or sets the maximum number of search results to accept before the search is considered complete. (Default = 100). - /// - public int? ResponseLimit { get; set; } - - /// - /// Gets or sets the search text. - /// - public string SearchText { get; set; } - - /// - /// Gets or sets the search timeout value, in seconds, used to determine when the search is complete. (Default = 15). - /// - /// The timeout duration is from the time of the last response. - public int? SearchTimeout { get; set; } - - /// - /// Gets or sets the search token. - /// - public int? Token { get; set; } - - /// - /// Maps to a new instance of . - /// - /// - /// - /// - /// - /// - public SearchOptions ToSearchOptions( - Func responseFilter = null, - Func fileFilter = null, - Action stateChanged = null, - Action 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/DTO/TokenResponse.cs b/src/slskd/DTO/TokenResponse.cs deleted file mode 100644 index fb1b81ee..00000000 --- a/src/slskd/DTO/TokenResponse.cs +++ /dev/null @@ -1,50 +0,0 @@ -namespace slskd.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; - } - - [JsonIgnore] - private JwtSecurityToken JwtSecurityToken { get; } - - /// - /// Gets the Access Token string. - /// - public string Token => new JwtSecurityTokenHandler().WriteToken(JwtSecurityToken); - - /// - /// Gets the time at which the Access Token expires. - /// - public long Expires => ((DateTimeOffset)JwtSecurityToken.ValidTo).ToUnixTimeSeconds(); - - /// - /// Gets the time at which the Access Token was issued. - /// - public long Issued => ((DateTimeOffset)JwtSecurityToken.ValidFrom).ToUnixTimeSeconds(); - - /// - /// Gets the value of the Name claim from the Access Token. - /// - public string Name => JwtSecurityToken.Claims.Where(c => c.Type == ClaimTypes.Name).SingleOrDefault().Value; - - /// - /// Gets the value of the Not Before claim from the Access Token. - /// - public long NotBefore => long.Parse(JwtSecurityToken.Claims.Where(c => c.Type == "nbf").SingleOrDefault().Value); - - /// - /// Gets the Token type. - /// - public string TokenType => JwtBearerDefaults.AuthenticationScheme; - } -} \ No newline at end of file diff --git a/src/slskd/DTO/Transfer.cs b/src/slskd/DTO/Transfer.cs deleted file mode 100644 index dfefa5c8..00000000 --- a/src/slskd/DTO/Transfer.cs +++ /dev/null @@ -1,131 +0,0 @@ -namespace slskd.DTO -{ - using Soulseek; - using System; - using System.Net; - - /// - /// A single file transfer. - /// - public class Transfer - { - /// - /// Gets the current average transfer speed. - /// - public double AverageSpeed { get; set; } - - /// - /// Gets the number of remaining bytes to be transferred. - /// - public long BytesRemaining { get; set; } - - /// - /// Gets the total number of bytes transferred. - /// - public long BytesTransferred { get; set; } - - /// - /// Gets the transfer direction. - /// - public TransferDirection Direction { get; set; } - - /// - /// Gets the current duration of the transfer, if it has been started. - /// - public double? ElapsedTime { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? EndTime { get; set; } - - /// - /// Gets the filename of the file to be transferred. - /// - public string Filename { get; set; } - - /// - /// Gets the transfer id. - /// - public string Id => Filename.Sha1(); - - /// - /// Gets the ip endpoint of the remote transfer connection, if one has been established. - /// - public IPEndPoint IPEndPoint { get; set; } - - /// - /// Gets the current progress in percent. - /// - public double PercentComplete { get; set; } - - /// - /// Gets the current place in queue, if it has been fetched. - /// - public int? PlaceInQueue { get; set; } - - /// - /// Gets the projected remaining duration of the transfer. - /// - public double? RemainingTime { get; set; } - - /// - /// Gets the remote unique token for the transfer. - /// - public int? RemoteToken { get; set; } - - /// - /// Gets the size of the file to be transferred, in bytes. - /// - public long Size { get; set; } - - /// - /// Gets the starting offset of the transfer, in bytes. - /// - public long StartOffset { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? StartTime { get; set; } - - /// - /// Gets the state of the transfer. - /// - public TransferStates State { get; set; } - - /// - /// Gets the unique token for the transfer. - /// - public int Token { get; set; } - - /// - /// Gets the username of the peer to or from which the file is to be transferred. - /// - 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/DTO/UserAddress.cs b/src/slskd/DTO/UserAddress.cs deleted file mode 100644 index 1a69bf7f..00000000 --- a/src/slskd/DTO/UserAddress.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace slskd.DTO -{ - /// - /// A user's IP address and port. - /// - public class UserAddress - { - /// - /// Gets or sets the IP address. - /// - public string IPAddress { get; set; } - - /// - /// Gets or sets the port. - /// - public int Port { get; set; } - } -} diff --git a/src/slskd/DTO/UserDataResponse.cs b/src/slskd/DTO/UserDataResponse.cs deleted file mode 100644 index fcbf8899..00000000 --- a/src/slskd/DTO/UserDataResponse.cs +++ /dev/null @@ -1,68 +0,0 @@ -namespace slskd.DTO -{ - using Soulseek; - - public class UserDataResponse - { - /// - /// The average upload speed of the user. - /// - public int AverageSpeed { get; set; } - - /// - /// The user's country code, if provided. - /// - public string CountryCode { get; set; } - - /// - /// The number of directories shared by the user. - /// - public int DirectoryCount { get; set; } - - /// - /// The number of active user downloads. - /// - public long DownloadCount { get; set; } - - /// - /// The number of files shared by the user. - /// - public int FileCount { get; set; } - - /// - /// A value indicating whether this user data belongs to the currently logged in user. - /// - public bool? Self { get; set; } - - /// - /// The number of the user's free download slots, if provided. - /// - public int? SlotsFree { get; set; } - - /// - /// The status of the user (0 = offline, 1 = away, 2 = online). - /// - public UserPresence Status { get; set; } - - /// - /// The username of the user. - /// - 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 -- cgit v1.2.3