diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-02-13 07:58:15 -0600 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2021-02-13 07:58:15 -0600 |
| commit | 936ed099a6e5258f9fd5a5ac026afc0630359b98 (patch) | |
| tree | f406e1f1b9fc29391e471c65b708ba6d94b72027 /src/slskd/Controllers | |
| parent | 87f024fa2561f751fc26c129bfaa373a966f1c67 (diff) | |
| download | slskd-936ed099a6e5258f9fd5a5ac026afc0630359b98.tar.gz | |
move controllers and DTOs to API namespace
Diffstat (limited to 'src/slskd/Controllers')
| -rw-r--r-- | src/slskd/Controllers/ApplicationController.cs | 59 | ||||
| -rw-r--r-- | src/slskd/Controllers/ConversationsController.cs | 198 | ||||
| -rw-r--r-- | src/slskd/Controllers/PublicChatController.cs | 50 | ||||
| -rw-r--r-- | src/slskd/Controllers/RoomsController.cs | 287 | ||||
| -rw-r--r-- | src/slskd/Controllers/SearchesController.cs | 102 | ||||
| -rw-r--r-- | src/slskd/Controllers/ServerController.cs | 68 | ||||
| -rw-r--r-- | src/slskd/Controllers/SessionController.cs | 132 | ||||
| -rw-r--r-- | src/slskd/Controllers/TransfersController.cs | 286 | ||||
| -rw-r--r-- | src/slskd/Controllers/UserController.cs | 151 |
9 files changed, 0 insertions, 1333 deletions
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; - - /// <summary> - /// Application - /// </summary> - [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; - } - - /// <summary> - /// Stops the application. - /// </summary> - /// <returns></returns> - [HttpDelete] - [Authorize] - public IActionResult Shutdown() - { - Client.Disconnect("Shut down via API"); - - Lifetime.StopApplication(); - return NoContent(); - } - - /// <summary> - /// Restarts the application. - /// </summary> - /// <returns></returns> - [HttpPut] - [Authorize] - public IActionResult Restart() - { - Client.Disconnect("Restarted via API"); - - Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine); - Lifetime.StopApplication(); - - return NoContent(); - } - } -} diff --git a/src/slskd/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; - - /// <summary> - /// Conversations - /// </summary> - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class ConversationsController : ControllerBase - { - /// <summary> - /// Initializes a new instance of the <see cref="ConversationsController"/> class. - /// </summary> - /// <param name="client"></param> - /// <param name="tracker"></param> - public ConversationsController(ISoulseekClient client, IConversationTracker tracker) - { - Client = client; - Tracker = tracker; - } - - private ISoulseekClient Client { get; } - private IConversationTracker Tracker { get; } - - /// <summary> - /// Acknowledges the given message id for the given username. - /// </summary> - /// <param name="username"></param> - /// <param name="id"></param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - /// <response code="404"> - /// A conversation with the specified username, or a message matching the specified id could not be found. - /// </response> - [HttpPut("{username}/{id}")] - [Authorize] - [ProducesResponseType(200)] - [ProducesResponseType(404)] - public async Task<IActionResult> Acknowledge([FromRoute]string username, [FromRoute]int id) - { - Tracker.Conversations.TryGetValue(username, out var conversation); - - if (conversation == default || !conversation.Any(p => p.Id == id)) - { - return NotFound(); - } - - await Client.AcknowledgePrivateMessageAsync(id); - return StatusCode(200); - } - - /// <summary> - /// Acknowledges all messages for the given username. - /// </summary> - /// <param name="username"></param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - /// <response code="404">A conversation with the specified username could not be found.</response> - [HttpPut("{username}")] - [Authorize] - [ProducesResponseType(200)] - [ProducesResponseType(404)] - public async Task<IActionResult> AcknowledgeAll([FromRoute]string username) - { - Tracker.Conversations.TryGetValue(username, out var conversation); - - if (conversation == default) - { - return NotFound(); - } - - var tasks = new List<Task>(); - - foreach (var message in conversation.Where(p => !p.Acknowledged)) - { - tasks.Add(Task.Run(async () => - { - await Client.AcknowledgePrivateMessageAsync(message.Id); - message.Acknowledged = true; - })); - } - - await Task.WhenAll(tasks); - return StatusCode(200); - } - - /// <summary> - /// Deletes the conversation associated with the given username. - /// </summary> - /// <returns></returns> - /// <response code="204">The request completed successfully.</response> - /// <response code="404">A conversation with the specified username could not be found.</response> - [HttpDelete("{username}")] - [Authorize] - [ProducesResponseType(404)] - [ProducesResponseType(204)] - public IActionResult Delete([FromRoute]string username) - { - var deleted = Tracker.Conversations.TryRemove(username, out _); - - if (deleted) - { - return StatusCode(204); - } - - return StatusCode(404); - } - - /// <summary> - /// Gets all tracked conversations. - /// </summary> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - [HttpGet("")] - [Authorize] - [ProducesResponseType(typeof(Dictionary<string, List<PrivateMessageResponse>>), 200)] - public IActionResult GetAll() - { - var response = Tracker.Conversations.ToDictionary( - entry => entry.Key, - entry => entry.Value - .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username)) - .OrderBy(m => m.Timestamp)); - - return Ok(response); - } - - /// <summary> - /// Gets the conversation associated with the specified username. - /// </summary> - /// <param name="username">The username associated with the desired conversation.</param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - /// <response code="404">A matching search was not found.</response> - [HttpGet("{username}")] - [Authorize] - [ProducesResponseType(typeof(List<PrivateMessageResponse>), 200)] - [ProducesResponseType(404)] - public IActionResult GetByUsername([FromRoute]string username) - { - if (Tracker.TryGet(username, out var conversation)) - { - var response = conversation - .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username)) - .OrderBy(m => m.Timestamp); - - return Ok(response); - } - - return NotFound(); - } - - /// <summary> - /// Sends a private message to the specified username. - /// </summary> - /// <param name="username"></param> - /// <param name="message"></param> - /// <returns></returns> - /// <response code="201">The request completed successfully.</response> - /// <response code="400">The specified message is null or empty.</response> - [HttpPost("{username}")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(400)] - public async Task<IActionResult> Send([FromRoute]string username, [FromBody]string message) - { - if (string.IsNullOrEmpty(message)) - { - return BadRequest(); - } - - await Client.SendPrivateMessageAsync(username, message); - - Tracker.AddOrUpdate(username, new PrivateMessage() - { - Username = Client.Username, - Timestamp = DateTime.UtcNow, - Message = message, - Acknowledged = true - }); - - return StatusCode(201); - } - } -}
\ No newline at end of file diff --git a/src/slskd/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; - - /// <summary> - /// Server - /// </summary> - [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; - } - - /// <summary> - /// Starts public chat. - /// </summary> - /// <returns></returns> - [HttpPost] - [Authorize] - public async Task<IActionResult> Start() - { - await Client.StartPublicChatAsync(); - return StatusCode(StatusCodes.Status201Created); - } - - /// <summary> - /// Stops public chat. - /// </summary> - /// <returns></returns> - [HttpDelete] - [Authorize] - public async Task<IActionResult> Stop() - { - await Client.StopPublicChatAsync(); - return StatusCode(StatusCodes.Status204NoContent); - } - } -} diff --git a/src/slskd/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; - - /// <summary> - /// Rooms. - /// </summary> - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class RoomsController : ControllerBase - { - public RoomsController(ISoulseekClient client, IRoomTracker tracker) - { - Client = client; - Tracker = tracker; - } - - private ISoulseekClient Client { get; } - private IRoomTracker Tracker { get; } - - /// <summary> - /// Gets all rooms. - /// </summary> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - [HttpGet("joined")] - [Authorize] - [ProducesResponseType(typeof(Dictionary<string, Dictionary<string, Room>>), 200)] - public IActionResult GetAll() - { - return Ok(Tracker.Rooms.Keys); - } - - /// <summary> - /// Gets the specified room. - /// </summary> - /// <param name="roomName"></param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - /// <response code="404">The specified roomName could not be found.</response> - [HttpGet("joined/{roomName}")] - [Authorize] - [ProducesResponseType(typeof(Room), 200)] - [ProducesResponseType(404)] - public IActionResult GetByRoomName([FromRoute]string roomName) - { - if (Tracker.TryGet(roomName, out var room)) - { - return Ok(MapRoomToRoomResponse(room)); - } - - return NotFound(); - } - - /// <summary> - /// Sends a message to the specified room. - /// </summary> - /// <param name="roomName"></param> - /// <param name="message"></param> - /// <returns></returns> - /// <response code="201">The request completed successfully.</response> - /// <response code="404">The specified roomName could not be found.</response> - [HttpPost("joined/{roomName}/messages")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(404)] - public async Task<IActionResult> SendMessage([FromRoute]string roomName, [FromBody]string message) - { - if (Tracker.TryGet(roomName, out var _)) - { - await Client.SendRoomMessageAsync(roomName, message); - return StatusCode(StatusCodes.Status201Created); - } - - return NotFound(); - } - - /// <summary> - /// Sets a ticker for the specified room. - /// </summary> - /// <param name="roomName"></param> - /// <param name="message"></param> - /// <returns></returns> - /// <response code="201">The request completed successfully.</response> - /// <response code="404">The specified roomName could not be found.</response> - [HttpPost("joined/{roomName}/ticker")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(404)] - public async Task<IActionResult> SetTicker([FromRoute] string roomName, [FromBody] string message) - { - if (Tracker.TryGet(roomName, out var _)) - { - await Client.SetRoomTickerAsync(roomName, message); - return StatusCode(StatusCodes.Status201Created); - } - - return NotFound(); - } - - /// <summary> - /// Adds a member to a private room. - /// </summary> - /// <param name="roomName"></param> - /// <param name="username"></param> - /// <returns></returns> - /// <response code="201">The request completed successfully.</response> - /// <response code="404">The specified roomName could not be found.</response> - [HttpPost("joined/{roomName}/members")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(404)] - public async Task<IActionResult> AddRoomMember([FromRoute]string roomName, [FromBody]string username) - { - if (Tracker.TryGet(roomName, out var _)) - { - await Client.AddPrivateRoomMemberAsync(roomName, username); - return StatusCode(StatusCodes.Status201Created); - } - - return NotFound(); - } - - /// <summary> - /// Gets the current list of users for the specified room. - /// </summary> - /// <param name="roomName"></param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - /// <response code="404">The specified roomName could not be found.</response> - [HttpGet("joined/{roomName}/users")] - [Authorize] - [ProducesResponseType(typeof(IList<UserData>), 200)] - [ProducesResponseType(404)] - public IActionResult GetUsersByRoomName([FromRoute]string roomName) - { - if (Tracker.TryGet(roomName, out var room)) - { - var response = room.Users - .Select(user => UserDataResponse.FromUserData(user, self: user.Username == Client.Username)); - - return Ok(response); - } - - return NotFound(); - } - - /// <summary> - /// Gets the current list of messages for the specified room. - /// </summary> - /// <param name="roomName"></param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - /// <response code="404">The specified roomName could not be found.</response> - [HttpGet("joined/{roomName}/messages")] - [Authorize] - [ProducesResponseType(typeof(IList<RoomMessage>), 200)] - [ProducesResponseType(404)] - public IActionResult GetMessagesByRoomName([FromRoute]string roomName) - { - if (Tracker.TryGet(roomName, out var room)) - { - var response = room.Messages - .Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == Client.Username)); - - return Ok(response); - } - - return NotFound(); - } - - /// <summary> - /// Gets a list of rooms from the server. - /// </summary> - /// <returns></returns> - [HttpGet("available")] - [Authorize] - [ProducesResponseType(typeof(List<RoomInfo>), 200)] - public async Task<IActionResult> GetRooms() - { - var list = await Client.GetRoomListAsync(); - - var response = new List<RoomInfoResponse>(); - - response.AddRange(list.Public.Select(r => RoomInfoResponse.FromRoomInfo(r))); - response.AddRange(list.Private.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true))); - response.AddRange(list.Owned.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true, isOwned: true))); - - foreach (var room in response) - { - room.IsModerated = list.ModeratedRoomNames.Contains(room.Name); - } - - return Ok(response); - } - - /// <summary> - /// Joins a room. - /// </summary> - /// <param name="roomName"></param> - /// <returns></returns> - /// <response code="201">The request completed successfully.</response> - /// <response code="304">The room has already been joined.</response> - [HttpPost("joined/{roomName}")] - [Authorize] - [ProducesResponseType(typeof(Room), 201)] - [ProducesResponseType(304)] - public async Task<IActionResult> JoinRoom([FromRoute]string roomName) - { - if (Tracker.Rooms.ContainsKey(roomName)) - { - return StatusCode(StatusCodes.Status304NotModified); - } - - try - { - var roomData = await Client.JoinRoomAsync(roomName); - var room = Room.FromRoomData(roomData); - Tracker.TryAdd(roomName, room); - - return StatusCode(StatusCodes.Status201Created, MapRoomToRoomResponse(room)); - } - catch (Exception ex) - { - if (ex.InnerException is RoomJoinForbiddenException) - { - return StatusCode(StatusCodes.Status403Forbidden, $"The server rejected your request to join {roomName}"); - } - - throw; - } - } - - /// <summary> - /// Leaves a room. - /// </summary> - /// <param name="roomName"></param> - /// <returns></returns> - /// <response code="204">The request completed successfully.</response> - /// <response code="404">The room has not been joined.</response> - [HttpDelete("joined/{roomName}")] - [Authorize] - [ProducesResponseType(204)] - [ProducesResponseType(404)] - public async Task<IActionResult> LeaveRoom([FromRoute]string roomName) - { - if (!Tracker.Rooms.ContainsKey(roomName)) - { - return StatusCode(StatusCodes.Status404NotFound); - } - - await Client.LeaveRoomAsync(roomName); - Tracker.TryRemove(roomName); - - return StatusCode(StatusCodes.Status204NoContent); - } - - private RoomResponse MapRoomToRoomResponse(Room room) - { - bool IsSelf(string username) - { - return username == Client.Username; - } - - var response = RoomResponse.FromRoom(room); - response.Users = room.Users - .Select(user => UserDataResponse.FromUserData(user, self: IsSelf(user.Username))); - response.Messages = room.Messages - .Select(message => RoomMessageResponse.FromRoomMessage(message, self: IsSelf(message.Username))); - - return response; - } - } -}
\ No newline at end of file diff --git a/src/slskd/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; - - /// <summary> - /// Search - /// </summary> - [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; } - - /// <summary> - /// Initializes a new instance of the <see cref="SearchesController"/> class. - /// </summary> - /// <param name="client"></param> - /// <param name="tracker"></param> - public SearchesController(ISoulseekClient client, ISearchTracker tracker) - { - Client = client; - Tracker = tracker; - } - - /// <summary> - /// Performs a search for the specified <paramref name="request"/>. - /// </summary> - /// <param name="request">The search request.</param> - /// <returns></returns> - /// <response code="200">The search completed successfully.</response> - /// <response code="400">The specified <paramref name="request"/> was malformed.</response> - /// <response code="500">The search terminated abnormally.</response> - [HttpPost("")] - [Authorize] - [ProducesResponseType(typeof(IEnumerable<SearchResponse>), 200)] - [ProducesResponseType(400)] - [ProducesResponseType(typeof(string), 500)] - public async Task<IActionResult> 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<SearchResponse>(); - - 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); - } - } - - /// <summary> - /// Gets the state of the search corresponding to the specified <paramref name="id"/>. - /// </summary> - /// <param name="id">The unique id of the search.</param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - /// <response code="404">A matching search was not found.</response> - [HttpGet("{id}")] - [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; - - /// <summary> - /// Server - /// </summary> - [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; - } - - /// <summary> - /// Disconnects the client. - /// </summary> - /// <param name="message"></param> - /// <returns></returns> - [HttpDelete] - [Authorize] - public IActionResult Disconnect([FromBody]string message) - { - Client.Disconnect(message); - return NoContent(); - } - - /// <summary> - /// Connects the client. - /// </summary> - /// <param name="req"></param> - /// <returns></returns> - [HttpPost] - [Authorize] - public async Task<IActionResult> Connect([FromBody]ConnectRequest req) - { - var addr = !string.IsNullOrEmpty(req.Address); - var port = req.Port.HasValue; - var un = !string.IsNullOrEmpty(req.Username); - var pw = !string.IsNullOrEmpty(req.Password); - - if (addr && port && un && pw) - { - await Client.ConnectAsync(req.Address, req.Port.Value, req.Username, req.Password); - return Ok(); - } - - if (!addr && !port && un && pw) - { - await Client.ConnectAsync(req.Username, req.Password); - return Ok(); - } - - return BadRequest("Provide one of the following: address and port, username and password, or address, port, username and password"); - } - } -} 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; - - /// <summary> - /// Session - /// </summary> - [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<Options> optionsSnapshot, - SymmetricSecurityKey jwtSigningKey) - { - Options = optionsSnapshot.Value; - JwtSigningKey = jwtSigningKey; - } - - /// <summary> - /// Checks whether security is enabled. - /// </summary> - /// <returns></returns> - /// <response code="200">True if security is enabled, false otherwise.</response> - [HttpGet] - [Route("enabled")] - [AllowAnonymous] - [ProducesResponseType(typeof(bool), 200)] - public IActionResult Enabled() - { - return base.Ok(!Options.Web.Authentication.Disable); - } - - /// <summary> - /// Checks whether the provided authentication is valid. - /// </summary> - /// <remarks> - /// This is a no-op provided so that the application can test for an expired token on load. - /// </remarks> - /// <returns></returns> - /// <response code="200">The authentication is valid.</response> - /// <response code="403">The authentication is is invalid.</response> - [HttpGet] - [Route("")] - [Authorize] - [ProducesResponseType(200)] - [ProducesResponseType(401)] - public IActionResult Check() - { - return Ok(); - } - - /// <summary> - /// Logs in. - /// </summary> - /// <param name="login"></param> - /// <returns></returns> - /// <response code="200">Login was successful.</response> - /// <response code="400">Bad request.</response> - /// <response code="401">Login failed.</response> - [HttpPost] - [Route("")] - [AllowAnonymous] - [ProducesResponseType(typeof(TokenResponse), 200)] - [ProducesResponseType(400)] - [ProducesResponseType(401)] - [ProducesResponseType(typeof(string), 500)] - public IActionResult Login([FromBody] LoginRequest login) - { - if (login == default) - { - return BadRequest(); - } - - if (string.IsNullOrWhiteSpace(login.Username) || string.IsNullOrWhiteSpace(login.Password)) - { - return BadRequest("Username and/or Password missing or invalid"); - } - - // only admin login for now - if (Options.Web.Authentication.Username == login.Username && Options.Web.Authentication.Password == login.Password) - { - return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator))); - } - - return Unauthorized(); - } - - private JwtSecurityToken GetJwtSecurityToken(string username, Role role) - { - var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(Options.Web.Authentication.Jwt.Ttl); - - var claims = new List<Claim>() - { - new Claim(ClaimTypes.Name, username), - new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), - new Claim(ClaimTypes.Role, role.ToString()), - new Claim("name", username), - new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()) - }; - - var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); - - var token = new JwtSecurityToken( - issuer: Program.AppName, - claims: claims, - notBefore: issuedUtc, - expires: expiresUtc, - signingCredentials: credentials); - - return token; - } - } -} 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; - - /// <summary> - /// Transfers - /// </summary> - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class TransfersController : ControllerBase - { - /// <summary> - /// Initializes a new instance of the <see cref="TransfersController"/> class. - /// </summary> - /// <param name="options"></param> - /// <param name="client"></param> - /// <param name="tracker"></param> - public TransfersController(IOptionsSnapshot<Options> 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; } - - /// <summary> - /// Cancels the specified download. - /// </summary> - /// <param name="username">The username of the download source.</param> - /// <param name="id">The id of the download.</param> - /// <param name="remove">A value indicating whether the tracked download should be removed after cancellation.</param> - /// <returns></returns> - /// <response code="204">The download was cancelled successfully.</response> - /// <response code="404">The specified download was not found.</response> - [HttpDelete("downloads/{username}/{id}")] - [Authorize] - [ProducesResponseType(204)] - [ProducesResponseType(404)] - public IActionResult CancelDownload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) - { - return CancelTransfer(TransferDirection.Download, username, id, remove); - } - - /// <summary> - /// Cancels the specified upload. - /// </summary> - /// <param name="username">The username of the upload destination.</param> - /// <param name="id">The id of the upload.</param> - /// <param name="remove">A value indicating whether the tracked upload should be removed after cancellation.</param> - /// <returns></returns> - /// <response code="204">The upload was cancelled successfully.</response> - /// <response code="404">The specified upload was not found.</response> - [HttpDelete("uploads/{username}/{id}")] - [Authorize] - [ProducesResponseType(204)] - [ProducesResponseType(404)] - public IActionResult CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) - { - return CancelTransfer(TransferDirection.Upload, username, id, remove); - } - - /// <summary> - /// Enqueues the specified download. - /// </summary> - /// <param name="username">The username of the download source.</param> - /// <param name="request">The download request.</param> - /// <returns></returns> - /// <response code="201">The download was successfully enqueued.</response> - /// <response code="403">The download was rejected.</response> - /// <response code="500">An unexpected error was encountered.</response> - [HttpPost("downloads/{username}")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(typeof(string), 403)] - [ProducesResponseType(typeof(string), 500)] - public async Task<IActionResult> Enqueue([FromRoute, Required]string username, [FromBody]QueueDownloadRequest request) - { - try - { - var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); - var stream = GetLocalFileStream(request.Filename, 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<Exception>(); - - if (rejected.Any()) - { - return StatusCode(403, rejected.First().Message); - } - - return StatusCode(500, downloadTask.Exception.Message); - } - - // if it didn't throw, just return ok. the download will continue waiting in the background. - return StatusCode(201); - } - catch (Exception ex) - { - return StatusCode(500, ex.Message); - } - } - - /// <summary> - /// Gets all downloads. - /// </summary> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - [HttpGet("downloads")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetDownloads() - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Download) - .ToMap()); - } - - /// <summary> - /// Gets all downloads for the specified username. - /// </summary> - /// <param name="username"></param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - [HttpGet("downloads/{username}")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetDownloads([FromRoute, Required]string username) - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Download) - .FromUser(username) - .ToMap()); - } - - /// <summary> - /// Gets the downlaod for the specified username matching the specified filename, and requests - /// the current place in the remote queue of the specified download. - /// </summary> - /// <param name="username">The username of the download source.</param> - /// <param name="id">The id of the download.</param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - /// <response code="404">The specified download was not found.</response> - [HttpGet("downloads/{username}/{id}")] - [Authorize] - [ProducesResponseType(typeof(DTO.Transfer), 200)] - [ProducesResponseType(404)] - public async Task<IActionResult> GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id) - { - var record = Tracker.Transfers.WithDirection(TransferDirection.Download).FromUser(username).WithId(id); - - if (record == default) - { - return NotFound(); - } - - record.Transfer.PlaceInQueue = await Client.GetDownloadPlaceInQueueAsync(username, record.Transfer.Filename); - return Ok(record.Transfer); - } - - /// <summary> - /// Gets all uploads. - /// </summary> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - [HttpGet("uploads")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetUploads() - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .ToMap()); - } - - /// <summary> - /// Gets all uploads for the specified username. - /// </summary> - /// <param name="username"></param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - [HttpGet("uploads/{username}")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required]string username) - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .FromUser(username) - .ToMap()); - } - - /// <summary> - /// Gets the upload for the specified username matching the specified filename. - /// </summary> - /// <param name="username">The username of the upload destination.</param> - /// <param name="id">The id of the upload.</param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - [HttpGet("uploads/{username}/{id}")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required]string username, [FromRoute, Required]string id) - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .FromUser(username) - .WithId(id).Transfer); - } - - private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) - { - var localFilename = remoteFilename.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; - - /// <summary> - /// Users - /// </summary> - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class UserController : ControllerBase - { - /// <summary> - /// Initializes a new instance of the <see cref="UserController"/> class. - /// </summary> - /// <param name="client"></param> - /// <param name="browseTracker"></param> - public UserController(ISoulseekClient client, IBrowseTracker browseTracker) - { - Client = client; - BrowseTracker = browseTracker; - } - - private ISoulseekClient Client { get; } - private IBrowseTracker BrowseTracker { get; } - - /// <summary> - /// Retrieves the address of the specified <paramref name="username"/>. - /// </summary> - /// <param name="username">The username of the user.</param> - /// <returns></returns> - /// <response code="200">The request completed successfully.</response> - [HttpGet("{username}/address")] - [Authorize] - [ProducesResponseType(typeof(UserAddress), 200)] - [ProducesResponseType(404)] - public async Task<IActionResult> 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); - } - } - - /// <summary> - /// Retrieves the files shared by the specified <paramref name="username"/>. - /// </summary> - /// <param name="username">The username of the user.</param> - /// <returns></returns> - [HttpGet("{username}/browse")] - [Authorize] - [ProducesResponseType(typeof(IEnumerable<Directory>), 200)] - [ProducesResponseType(404)] - public async Task<IActionResult> Browse([FromRoute, Required]string username) - { - try - { - var result = await Client.BrowseAsync(username); - - _ = Task.Run(async () => - { - await Task.Delay(5000); - BrowseTracker.TryRemove(username); - }); - - return Ok(result); - } - catch (UserOfflineException ex) - { - return NotFound(ex.Message); - } - } - - /// <summary> - /// Retrieves the status of the current browse operation for the specified <paramref name="username"/>, if any. - /// </summary> - /// <param name="username">The username of the user.</param> - /// <returns></returns> - [HttpGet("{username}/browse/status")] - [Authorize] - [ProducesResponseType(typeof(decimal), 200)] - [ProducesResponseType(404)] - public IActionResult BrowseStatus([FromRoute, Required]string username) - { - if (BrowseTracker.TryGet(username, out var progress)) - { - return Ok(progress); - } - - return NotFound(); - } - - /// <summary> - /// Retrieves information about the specified <paramref name="username"/>. - /// </summary> - /// <param name="username">The username of the user.</param> - /// <returns></returns> - [HttpGet("{username}/info")] - [Authorize] - [ProducesResponseType(typeof(UserInfo), 200)] - [ProducesResponseType(404)] - public async Task<IActionResult> Info([FromRoute, Required]string username) - { - try - { - var response = await Client.GetUserInfoAsync(username); - return Ok(response); - } - catch (UserOfflineException ex) - { - return NotFound(ex.Message); - } - } - - /// <summary> - /// Retrieves status for the specified <paramref name="username"/>. - /// </summary> - /// <param name="username">The username of the user.</param> - /// <returns></returns> - [HttpGet("{username}/status")] - [Authorize] - [ProducesResponseType(typeof(UserStatus), 200)] - [ProducesResponseType(404)] - public async Task<IActionResult> 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 |
