diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-06-14 20:03:36 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2021-06-14 20:03:36 -0500 |
| commit | 050be311e68bb316cfc40fbd23bfd5a812e1a060 (patch) | |
| tree | 1476cba9e90845f224bbc0a380e4633697e1306e /src/slskd/Service | |
| parent | 4cf8f8fa862b08131e9cc51c4bad3d6c9838342b (diff) | |
| download | slskd-050be311e68bb316cfc40fbd23bfd5a812e1a060.tar.gz | |
move stuff around
Diffstat (limited to 'src/slskd/Service')
52 files changed, 5084 insertions, 0 deletions
diff --git a/src/slskd/Service/Application/API/Controllers/ApplicationController.cs b/src/slskd/Service/Application/API/Controllers/ApplicationController.cs new file mode 100644 index 00000000..7fa59ff0 --- /dev/null +++ b/src/slskd/Service/Application/API/Controllers/ApplicationController.cs @@ -0,0 +1,76 @@ +// <copyright file="ApplicationController.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Application.API +{ + using System; + using System.Diagnostics; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Microsoft.Extensions.Hosting; + using Soulseek; + + /// <summary> + /// Application. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ApplicationController : ControllerBase + { + public ApplicationController(ISoulseekClient client, IHostApplicationLifetime lifetime) + { + Client = client; + Lifetime = lifetime; + } + + private ISoulseekClient Client { get; } + private IHostApplicationLifetime Lifetime { get; } + + /// <summary> + /// Stops the application. + /// </summary> + /// <returns></returns> + [HttpDelete] + [Authorize] + public IActionResult Shutdown() + { + Client.Disconnect("Shut down via API"); + + Lifetime.StopApplication(); + return NoContent(); + } + + /// <summary> + /// Restarts the application. + /// </summary> + /// <returns></returns> + [HttpPut] + [Authorize] + public IActionResult Restart() + { + Client.Disconnect("Restarted via API"); + + Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine); + Lifetime.StopApplication(); + + return NoContent(); + } + } +} diff --git a/src/slskd/Service/Application/API/Controllers/SessionController.cs b/src/slskd/Service/Application/API/Controllers/SessionController.cs new file mode 100644 index 00000000..b819dc57 --- /dev/null +++ b/src/slskd/Service/Application/API/Controllers/SessionController.cs @@ -0,0 +1,142 @@ +// <copyright file="SessionController.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Application.API +{ + using System; + using System.Collections.Generic; + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Microsoft.IdentityModel.Tokens; + + /// <summary> + /// Session. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class SessionController : ControllerBase + { + public SessionController( + Microsoft.Extensions.Options.IOptionsSnapshot<Options> optionsSnapshot, + SymmetricSecurityKey jwtSigningKey) + { + Options = optionsSnapshot.Value; + JwtSigningKey = jwtSigningKey; + } + + private SymmetricSecurityKey JwtSigningKey { get; set; } + private Options Options { get; set; } + + /// <summary> + /// Checks whether the provided authentication is valid. + /// </summary> + /// <remarks>This is a no-op provided so that the application can test for an expired token on load.</remarks> + /// <returns></returns> + /// <response code="200">The authentication is valid.</response> + /// <response code="403">The authentication is is invalid.</response> + [HttpGet] + [Route("")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(401)] + public IActionResult Check() + { + return Ok(); + } + + /// <summary> + /// Checks whether security is enabled. + /// </summary> + /// <returns></returns> + /// <response code="200">True if security is enabled, false otherwise.</response> + [HttpGet] + [Route("enabled")] + [AllowAnonymous] + [ProducesResponseType(typeof(bool), 200)] + public IActionResult Enabled() + { + return Ok(!Options.Web.Authentication.Disable); + } + + /// <summary> + /// Logs in. + /// </summary> + /// <param name="login"></param> + /// <returns></returns> + /// <response code="200">Login was successful.</response> + /// <response code="400">Bad request.</response> + /// <response code="401">Login failed.</response> + [HttpPost] + [Route("")] + [AllowAnonymous] + [ProducesResponseType(typeof(TokenResponse), 200)] + [ProducesResponseType(400)] + [ProducesResponseType(401)] + [ProducesResponseType(typeof(string), 500)] + public IActionResult Login([FromBody] LoginRequest login) + { + if (login == default) + { + return BadRequest(); + } + + if (string.IsNullOrWhiteSpace(login.Username) || string.IsNullOrWhiteSpace(login.Password)) + { + return BadRequest("Username and/or Password missing or invalid"); + } + + // only admin login for now + if (Options.Web.Authentication.Username == login.Username && Options.Web.Authentication.Password == login.Password) + { + return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator))); + } + + return Unauthorized(); + } + + private JwtSecurityToken GetJwtSecurityToken(string username, Role role) + { + var issuedUtc = DateTime.UtcNow; + var expiresUtc = DateTime.UtcNow.AddMilliseconds(Options.Web.Authentication.Jwt.Ttl); + + var claims = new List<Claim>() + { + new Claim(ClaimTypes.Name, username), + new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), + new Claim(ClaimTypes.Role, role.ToString()), + new Claim("name", username), + new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()), + }; + + var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); + + var token = new JwtSecurityToken( + issuer: Program.AppName, + claims: claims, + notBefore: issuedUtc, + expires: expiresUtc, + signingCredentials: credentials); + + return token; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Application/API/DTO/LoginRequest.cs b/src/slskd/Service/Application/API/DTO/LoginRequest.cs new file mode 100644 index 00000000..2f1fb072 --- /dev/null +++ b/src/slskd/Service/Application/API/DTO/LoginRequest.cs @@ -0,0 +1,25 @@ +// <copyright file="LoginRequest.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Application.API +{ + public class LoginRequest + { + public string Username { get; set; } + public string Password { get; set; } + } +} diff --git a/src/slskd/Service/Application/API/DTO/TokenResponse.cs b/src/slskd/Service/Application/API/DTO/TokenResponse.cs new file mode 100644 index 00000000..2668d566 --- /dev/null +++ b/src/slskd/Service/Application/API/DTO/TokenResponse.cs @@ -0,0 +1,67 @@ +// <copyright file="TokenResponse.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Application.API +{ + using System; + using System.IdentityModel.Tokens.Jwt; + using System.Linq; + using System.Security.Claims; + using System.Text.Json.Serialization; + using Microsoft.AspNetCore.Authentication.JwtBearer; + + public class TokenResponse + { + public TokenResponse(JwtSecurityToken jwtSecurityToken) + { + JwtSecurityToken = jwtSecurityToken; + } + + /// <summary> + /// Gets the time at which the Access Token expires. + /// </summary> + public long Expires => ((DateTimeOffset)JwtSecurityToken.ValidTo).ToUnixTimeSeconds(); + + /// <summary> + /// Gets the time at which the Access Token was issued. + /// </summary> + public long Issued => ((DateTimeOffset)JwtSecurityToken.ValidFrom).ToUnixTimeSeconds(); + + /// <summary> + /// Gets the value of the Name claim from the Access Token. + /// </summary> + public string Name => JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Name)?.Value; + + /// <summary> + /// Gets the value of the Not Before claim from the Access Token. + /// </summary> + public long NotBefore => long.Parse(JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == "nbf").Value); + + /// <summary> + /// Gets the Access Token string. + /// </summary> + public string Token => new JwtSecurityTokenHandler().WriteToken(JwtSecurityToken); + + /// <summary> + /// Gets the Token type. + /// </summary> + public string TokenType => JwtBearerDefaults.AuthenticationScheme; + + [JsonIgnore] + private JwtSecurityToken JwtSecurityToken { get; } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Application/Role.cs b/src/slskd/Service/Application/Role.cs new file mode 100644 index 00000000..74ba7f81 --- /dev/null +++ b/src/slskd/Service/Application/Role.cs @@ -0,0 +1,26 @@ +// <copyright file="Role.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Application +{ + public enum Role + { + ReadOnly = 0, + User = 1, + Administrator = 2, + } +} diff --git a/src/slskd/Service/Exceptions/ApplicationShutdownException.cs b/src/slskd/Service/Exceptions/ApplicationShutdownException.cs new file mode 100644 index 00000000..e30b5c79 --- /dev/null +++ b/src/slskd/Service/Exceptions/ApplicationShutdownException.cs @@ -0,0 +1,72 @@ +// <copyright file="ApplicationShutdownException.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents a normal application shutdown. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class ApplicationShutdownException : SlskdException + { + /// <summary> + /// Initializes a new instance of the <see cref="ApplicationShutdownException"/> class. + /// </summary> + public ApplicationShutdownException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ApplicationShutdownException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public ApplicationShutdownException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ApplicationShutdownException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public ApplicationShutdownException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ApplicationShutdownException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected ApplicationShutdownException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Exceptions/SlskdException.cs b/src/slskd/Service/Exceptions/SlskdException.cs new file mode 100644 index 00000000..6b4cfc2a --- /dev/null +++ b/src/slskd/Service/Exceptions/SlskdException.cs @@ -0,0 +1,72 @@ +// <copyright file="SlskdException.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents erorrs that originate from slskd logic. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class SlskdException : Exception + { + /// <summary> + /// Initializes a new instance of the <see cref="SlskdException"/> class. + /// </summary> + public SlskdException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="SlskdException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public SlskdException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="SlskdException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public SlskdException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="SlskdException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected SlskdException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/ISharedFileCache.cs b/src/slskd/Service/ISharedFileCache.cs new file mode 100644 index 00000000..a7b8bf40 --- /dev/null +++ b/src/slskd/Service/ISharedFileCache.cs @@ -0,0 +1,36 @@ +// <copyright file="ISharedFileCache.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using System.Collections.Generic; + using Soulseek; + + public interface ISharedFileCache + { + event EventHandler<(int Directories, int Files)> Refreshed; + + string Directory { get; } + DateTime? LastFill { get; } + long TTL { get; } + + void Fill(); + + IEnumerable<Soulseek.File> Search(SearchQuery query); + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Service/Messaging/API/Controllers/ConversationsController.cs new file mode 100644 index 00000000..2107ceb1 --- /dev/null +++ b/src/slskd/Service/Messaging/API/Controllers/ConversationsController.cs @@ -0,0 +1,212 @@ +// <copyright file="ConversationsController.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging.API +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Conversations. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ConversationsController : ControllerBase + { + /// <summary> + /// Initializes a new instance of the <see cref="ConversationsController"/> class. + /// </summary> + /// <param name="client"></param> + /// <param name="tracker"></param> + public ConversationsController(ISoulseekClient client, IConversationTracker tracker) + { + Client = client; + Tracker = tracker; + } + + private ISoulseekClient Client { get; } + private IConversationTracker Tracker { get; } + + /// <summary> + /// Acknowledges the given message id for the given username. + /// </summary> + /// <param name="username"></param> + /// <param name="id"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404"> + /// A conversation with the specified username, or a message matching the specified id could not be found. + /// </response> + [HttpPut("{username}/{id}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(404)] + public async Task<IActionResult> Acknowledge([FromRoute]string username, [FromRoute]int id) + { + Tracker.Conversations.TryGetValue(username, out var conversation); + + if (conversation == default || !conversation.Any(p => p.Id == id)) + { + return NotFound(); + } + + await Client.AcknowledgePrivateMessageAsync(id); + return StatusCode(200); + } + + /// <summary> + /// Acknowledges all messages for the given username. + /// </summary> + /// <param name="username"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">A conversation with the specified username could not be found.</response> + [HttpPut("{username}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(404)] + public async Task<IActionResult> AcknowledgeAll([FromRoute]string username) + { + Tracker.Conversations.TryGetValue(username, out var conversation); + + if (conversation == default) + { + return NotFound(); + } + + var tasks = new List<Task>(); + + foreach (var message in conversation.Where(p => !p.Acknowledged)) + { + tasks.Add(Task.Run(async () => + { + await Client.AcknowledgePrivateMessageAsync(message.Id); + message.Acknowledged = true; + })); + } + + await Task.WhenAll(tasks); + return StatusCode(200); + } + + /// <summary> + /// Deletes the conversation associated with the given username. + /// </summary> + /// <returns></returns> + /// <response code="204">The request completed successfully.</response> + /// <response code="404">A conversation with the specified username could not be found.</response> + [HttpDelete("{username}")] + [Authorize] + [ProducesResponseType(404)] + [ProducesResponseType(204)] + public IActionResult Delete([FromRoute]string username) + { + var deleted = Tracker.Conversations.TryRemove(username, out _); + + if (deleted) + { + return StatusCode(204); + } + + return StatusCode(404); + } + + /// <summary> + /// Gets all tracked conversations. + /// </summary> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("")] + [Authorize] + [ProducesResponseType(typeof(Dictionary<string, List<PrivateMessageResponse>>), 200)] + public IActionResult GetAll() + { + var response = Tracker.Conversations.ToDictionary( + entry => entry.Key, + entry => entry.Value + .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username)) + .OrderBy(m => m.Timestamp)); + + return Ok(response); + } + + /// <summary> + /// Gets the conversation associated with the specified username. + /// </summary> + /// <param name="username">The username associated with the desired conversation.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">A matching search was not found.</response> + [HttpGet("{username}")] + [Authorize] + [ProducesResponseType(typeof(List<PrivateMessageResponse>), 200)] + [ProducesResponseType(404)] + public IActionResult GetByUsername([FromRoute]string username) + { + if (Tracker.TryGet(username, out var conversation)) + { + var response = conversation + .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username)) + .OrderBy(m => m.Timestamp); + + return Ok(response); + } + + return NotFound(); + } + + /// <summary> + /// Sends a private message to the specified username. + /// </summary> + /// <param name="username"></param> + /// <param name="message"></param> + /// <returns></returns> + /// <response code="201">The request completed successfully.</response> + /// <response code="400">The specified message is null or empty.</response> + [HttpPost("{username}")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(400)] + public async Task<IActionResult> Send([FromRoute]string username, [FromBody]string message) + { + if (string.IsNullOrEmpty(message)) + { + return BadRequest(); + } + + await Client.SendPrivateMessageAsync(username, message); + + Tracker.AddOrUpdate(username, new PrivateMessage() + { + Username = Client.Username, + Timestamp = DateTime.UtcNow, + Message = message, + Acknowledged = true, + }); + + return StatusCode(201); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Messaging/API/Controllers/PublicChatController.cs b/src/slskd/Service/Messaging/API/Controllers/PublicChatController.cs new file mode 100644 index 00000000..6868d3fb --- /dev/null +++ b/src/slskd/Service/Messaging/API/Controllers/PublicChatController.cs @@ -0,0 +1,67 @@ +// <copyright file="PublicChatController.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging.API +{ + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Server. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class PublicChatController : ControllerBase + { + public PublicChatController(ISoulseekClient client) + { + Client = client; + } + + private ISoulseekClient Client { get; } + + /// <summary> + /// Starts public chat. + /// </summary> + /// <returns></returns> + [HttpPost] + [Authorize] + public async Task<IActionResult> Start() + { + await Client.StartPublicChatAsync(); + return StatusCode(StatusCodes.Status201Created); + } + + /// <summary> + /// Stops public chat. + /// </summary> + /// <returns></returns> + [HttpDelete] + [Authorize] + public async Task<IActionResult> Stop() + { + await Client.StopPublicChatAsync(); + return StatusCode(StatusCodes.Status204NoContent); + } + } +} diff --git a/src/slskd/Service/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Service/Messaging/API/Controllers/RoomsController.cs new file mode 100644 index 00000000..12789ef5 --- /dev/null +++ b/src/slskd/Service/Messaging/API/Controllers/RoomsController.cs @@ -0,0 +1,301 @@ +// <copyright file="RoomsController.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging.API +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Rooms. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class RoomsController : ControllerBase + { + public RoomsController(ISoulseekClient client, IRoomTracker tracker) + { + Client = client; + Tracker = tracker; + } + + private ISoulseekClient Client { get; } + private IRoomTracker Tracker { get; } + + /// <summary> + /// Gets all rooms. + /// </summary> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("joined")] + [Authorize] + [ProducesResponseType(typeof(Dictionary<string, Dictionary<string, Room>>), 200)] + public IActionResult GetAll() + { + return Ok(Tracker.Rooms.Keys); + } + + /// <summary> + /// Gets the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpGet("joined/{roomName}")] + [Authorize] + [ProducesResponseType(typeof(Room), 200)] + [ProducesResponseType(404)] + public IActionResult GetByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + return Ok(MapRoomToRoomResponse(room)); + } + + return NotFound(); + } + + /// <summary> + /// Sends a message to the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="message"></param> + /// <returns></returns> + /// <response code="201">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpPost("joined/{roomName}/messages")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task<IActionResult> SendMessage([FromRoute]string roomName, [FromBody]string message) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.SendRoomMessageAsync(roomName, message); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// <summary> + /// Sets a ticker for the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="message"></param> + /// <returns></returns> + /// <response code="201">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpPost("joined/{roomName}/ticker")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task<IActionResult> SetTicker([FromRoute] string roomName, [FromBody] string message) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.SetRoomTickerAsync(roomName, message); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// <summary> + /// Adds a member to a private room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="username"></param> + /// <returns></returns> + /// <response code="201">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpPost("joined/{roomName}/members")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task<IActionResult> AddRoomMember([FromRoute]string roomName, [FromBody]string username) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.AddPrivateRoomMemberAsync(roomName, username); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// <summary> + /// Gets the current list of users for the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpGet("joined/{roomName}/users")] + [Authorize] + [ProducesResponseType(typeof(IList<UserData>), 200)] + [ProducesResponseType(404)] + public IActionResult GetUsersByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + var response = room.Users + .Select(user => UserDataResponse.FromUserData(user, self: user.Username == Client.Username)); + + return Ok(response); + } + + return NotFound(); + } + + /// <summary> + /// Gets the current list of messages for the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpGet("joined/{roomName}/messages")] + [Authorize] + [ProducesResponseType(typeof(IList<RoomMessage>), 200)] + [ProducesResponseType(404)] + public IActionResult GetMessagesByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + var response = room.Messages + .Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == Client.Username)); + + return Ok(response); + } + + return NotFound(); + } + + /// <summary> + /// Gets a list of rooms from the server. + /// </summary> + /// <returns></returns> + [HttpGet("available")] + [Authorize] + [ProducesResponseType(typeof(List<RoomInfo>), 200)] + public async Task<IActionResult> GetRooms() + { + var list = await Client.GetRoomListAsync(); + + var response = new List<RoomInfoResponse>(); + + response.AddRange(list.Public.Select(r => RoomInfoResponse.FromRoomInfo(r))); + response.AddRange(list.Private.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true))); + response.AddRange(list.Owned.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true, isOwned: true))); + + foreach (var room in response) + { + room.IsModerated = list.ModeratedRoomNames.Contains(room.Name); + } + + return Ok(response); + } + + /// <summary> + /// Joins a room. + /// </summary> + /// <param name="roomName"></param> + /// <returns></returns> + /// <response code="201">The request completed successfully.</response> + /// <response code="304">The room has already been joined.</response> + [HttpPost("joined/{roomName}")] + [Authorize] + [ProducesResponseType(typeof(Room), 201)] + [ProducesResponseType(304)] + public async Task<IActionResult> JoinRoom([FromRoute]string roomName) + { + if (Tracker.Rooms.ContainsKey(roomName)) + { + return StatusCode(StatusCodes.Status304NotModified); + } + + try + { + var roomData = await Client.JoinRoomAsync(roomName); + var room = Room.FromRoomData(roomData); + Tracker.TryAdd(roomName, room); + + return StatusCode(StatusCodes.Status201Created, MapRoomToRoomResponse(room)); + } + catch (Exception ex) + { + if (ex.InnerException is RoomJoinForbiddenException) + { + return StatusCode(StatusCodes.Status403Forbidden, $"The server rejected your request to join {roomName}"); + } + + throw; + } + } + + /// <summary> + /// Leaves a room. + /// </summary> + /// <param name="roomName"></param> + /// <returns></returns> + /// <response code="204">The request completed successfully.</response> + /// <response code="404">The room has not been joined.</response> + [HttpDelete("joined/{roomName}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public async Task<IActionResult> LeaveRoom([FromRoute]string roomName) + { + if (!Tracker.Rooms.ContainsKey(roomName)) + { + return StatusCode(StatusCodes.Status404NotFound); + } + + await Client.LeaveRoomAsync(roomName); + Tracker.TryRemove(roomName); + + return StatusCode(StatusCodes.Status204NoContent); + } + + private RoomResponse MapRoomToRoomResponse(Room room) + { + bool IsSelf(string username) + { + return username == Client.Username; + } + + var response = RoomResponse.FromRoom(room); + response.Users = room.Users + .Select(user => UserDataResponse.FromUserData(user, self: IsSelf(user.Username))); + response.Messages = room.Messages + .Select(message => RoomMessageResponse.FromRoomMessage(message, self: IsSelf(message.Username))); + + return response; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Messaging/API/DTO/PrivateMessageResponse.cs b/src/slskd/Service/Messaging/API/DTO/PrivateMessageResponse.cs new file mode 100644 index 00000000..a7e08d50 --- /dev/null +++ b/src/slskd/Service/Messaging/API/DTO/PrivateMessageResponse.cs @@ -0,0 +1,74 @@ +// <copyright file="PrivateMessageResponse.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging.API +{ + using System; + using slskd.Messaging; + + public class PrivateMessageResponse + { + /// <summary> + /// A value indicating whether the message has been acknowledged. + /// </summary> + public bool Acknowledged { get; set; } = false; + + /// <summary> + /// The unique message id, used to acknowledge receipt. + /// </summary> + public int Id { get; set; } + + /// <summary> + /// The message. + /// </summary> + public string Message { get; set; } + + /// <summary> + /// A value indicating whether the message was replayed. + /// </summary> + public bool Replayed { get; set; } + + /// <summary> + /// The UTC timestamp of the message. + /// </summary> + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// <summary> + /// The username of the user who sent the message. + /// </summary> + public string Username { get; set; } + + /// <summary> + /// A value indicating whether this message was sent by the currently logged in user. + /// </summary> + public bool? Self { get; set; } + + public static PrivateMessageResponse FromPrivateMessage(PrivateMessage privateMessage, bool self = false) + { + return new PrivateMessageResponse() + { + Id = privateMessage.Id, + Timestamp = privateMessage.Timestamp, + Username = privateMessage.Username, + Message = privateMessage.Message, + Acknowledged = privateMessage.Acknowledged, + Replayed = privateMessage.Replayed, + Self = self ? self : (bool?)null, + }; + } + } +} diff --git a/src/slskd/Service/Messaging/API/DTO/RoomInfoResponse.cs b/src/slskd/Service/Messaging/API/DTO/RoomInfoResponse.cs new file mode 100644 index 00000000..46edbdc8 --- /dev/null +++ b/src/slskd/Service/Messaging/API/DTO/RoomInfoResponse.cs @@ -0,0 +1,60 @@ +// <copyright file="RoomInfoResponse.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging.API +{ + using Soulseek; + + public class RoomInfoResponse + { + /// <summary> + /// Gets the room name. + /// </summary> + public string Name { get; init; } + + /// <summary> + /// Gets the number of users in the room. + /// </summary> + public int UserCount { get; init; } + + /// <summary> + /// Gets a value indicating whether the room is private. + /// </summary> + public bool IsPrivate { get; init; } + + /// <summary> + /// Gets a value indicating whether the room is owned by the currently logged in user. + /// </summary> + public bool IsOwned { get; init; } + + /// <summary> + /// Gets a value indicating whether the room is moderated by the currently logged in user. + /// </summary> + public bool IsModerated { get; set; } + + public static RoomInfoResponse FromRoomInfo(RoomInfo info, bool isPrivate = false, bool isOwned = false) + { + return new RoomInfoResponse() + { + Name = info.Name, + UserCount = info.UserCount, + IsPrivate = isPrivate, + IsOwned = isOwned, + }; + } + } +} diff --git a/src/slskd/Service/Messaging/API/DTO/RoomMessageResponse.cs b/src/slskd/Service/Messaging/API/DTO/RoomMessageResponse.cs new file mode 100644 index 00000000..965c63a6 --- /dev/null +++ b/src/slskd/Service/Messaging/API/DTO/RoomMessageResponse.cs @@ -0,0 +1,62 @@ +// <copyright file="RoomMessageResponse.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging.API +{ + using System; + using slskd.Messaging; + + public class RoomMessageResponse + { + /// <summary> + /// The timestamp of the message. + /// </summary> + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// <summary> + /// The username of the user who sent the message. + /// </summary> + public string Username { get; set; } + + /// <summary> + /// The message. + /// </summary> + public string Message { get; set; } + + /// <summary> + /// The room to which the message pertains. + /// </summary> + public string RoomName { get; set; } + + /// <summary> + /// A value indicating whether this user data belongs to the currently logged in user. + /// </summary> + public bool? Self { get; set; } + + public static RoomMessageResponse FromRoomMessage(RoomMessage roomMessage, bool self = false) + { + return new RoomMessageResponse() + { + Timestamp = roomMessage.Timestamp, + Username = roomMessage.Username, + Message = roomMessage.Message, + RoomName = roomMessage.RoomName, + Self = self ? self : (bool?)null, + }; + } + } +} diff --git a/src/slskd/Service/Messaging/API/DTO/RoomResponse.cs b/src/slskd/Service/Messaging/API/DTO/RoomResponse.cs new file mode 100644 index 00000000..cf7e1478 --- /dev/null +++ b/src/slskd/Service/Messaging/API/DTO/RoomResponse.cs @@ -0,0 +1,75 @@ +// <copyright file="RoomResponse.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging.API +{ + using System.Collections.Generic; + using System.Linq; + using slskd.Messaging; + + public class RoomResponse + { + /// <summary> + /// The room name. + /// </summary> + public string Name { get; set; } + + /// <summary> + /// A value indicating whether the room is private. + /// </summary> + public bool IsPrivate { get; set; } + + /// <summary> + /// The number of operators in the room, if private. + /// </summary> + public int? OperatorCount { get; set; } + + /// <summary> + /// The operators in the room, if private. + /// </summary> + public IList<string> Operators { get; set; } + + /// <summary> + /// The owner of the room, if private. + /// </summary> + public string Owner { get; set; } + + /// <summary> + /// The list of users in the room. + /// </summary> + public IEnumerable<UserDataResponse> Users { get; set; } = new List<UserDataResponse>(); + + /// <summary> + /// The list of messages. + /// </summary> + public IEnumerable<RoomMessageResponse> Messages { get; set; } = new List<RoomMessageResponse>(); + + public static RoomResponse FromRoom(Room room) + { + return new RoomResponse() + { + Name = room.Name, + IsPrivate = room.IsPrivate, + OperatorCount = room.OperatorCount, + Operators = room.Operators?.ToList(), + Owner = room.Owner, + Users = new List<UserDataResponse>(), + Messages = new List<RoomMessageResponse>(), + }; + } + } +} diff --git a/src/slskd/Service/Messaging/API/DTO/UserDataResponse.cs b/src/slskd/Service/Messaging/API/DTO/UserDataResponse.cs new file mode 100644 index 00000000..53b66c32 --- /dev/null +++ b/src/slskd/Service/Messaging/API/DTO/UserDataResponse.cs @@ -0,0 +1,85 @@ +// <copyright file="UserDataResponse.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging.API +{ + using Soulseek; + + public class UserDataResponse + { + /// <summary> + /// The average upload speed of the user. + /// </summary> + public int AverageSpeed { get; set; } + + /// <summary> + /// The user's country code, if provided. + /// </summary> + public string CountryCode { get; set; } + + /// <summary> + /// The number of directories shared by the user. + /// </summary> + public int DirectoryCount { get; set; } + + /// <summary> + /// The number of active user downloads. + /// </summary> + public long DownloadCount { get; set; } + + /// <summary> + /// The number of files shared by the user. + /// </summary> + public int FileCount { get; set; } + + /// <summary> + /// A value indicating whether this user data belongs to the currently logged in user. + /// </summary> + public bool? Self { get; set; } + + /// <summary> + /// The number of the user's free download slots, if provided. + /// </summary> + public int? SlotsFree { get; set; } + + /// <summary> + /// The status of the user (0 = offline, 1 = away, 2 = online). + /// </summary> + public UserPresence Status { get; set; } + + /// <summary> + /// The username of the user. + /// </summary> + public string Username { get; set; } + + public static UserDataResponse FromUserData(UserData userData, bool self = false) + { + return new UserDataResponse() + { + AverageSpeed = userData.AverageSpeed, + CountryCode = userData.CountryCode, + DirectoryCount = userData.DirectoryCount, + DownloadCount = userData.DownloadCount, + FileCount = userData.FileCount, + SlotsFree = userData.SlotsFree, + Status = userData.Status, + Username = userData.Username, + Self = self ? self : (bool?)null, + }; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Messaging/ConversationTracker.cs b/src/slskd/Service/Messaging/ConversationTracker.cs new file mode 100644 index 00000000..27d678ca --- /dev/null +++ b/src/slskd/Service/Messaging/ConversationTracker.cs @@ -0,0 +1,62 @@ +// <copyright file="ConversationTracker.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + + /// <summary> + /// Tracks private message conversations. + /// </summary> + public class ConversationTracker : IConversationTracker + { + /// <summary> + /// Tracked private message conversations. + /// </summary> + public ConcurrentDictionary<string, IList<PrivateMessage>> Conversations { get; } = new ConcurrentDictionary<string, IList<PrivateMessage>>(); + + /// <summary> + /// Adds a private message conversation and appends the specified <paramref name="message"/>, or just appends the + /// message if the conversation exists. + /// </summary> + /// <param name="username"></param> + /// <param name="message"></param> + public void AddOrUpdate(string username, PrivateMessage message) + { + Conversations.AddOrUpdate(username, new List<PrivateMessage>() { message }, (_, messageList) => + { + messageList.Add(message); + return messageList; + }); + } + + /// <summary> + /// Returns the list of private messages for the specified <paramref name="username"/>, if any exist. + /// </summary> + /// <param name="username"></param> + /// <param name="messages"></param> + /// <returns></returns> + public bool TryGet(string username, out IList<PrivateMessage> messages) => Conversations.TryGetValue(username, out messages); + + /// <summary> + /// Removes a tracked private message conversation for the specified user. + /// </summary> + /// <param name="username"></param> + public void TryRemove(string username) => Conversations.TryRemove(username, out _); + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Messaging/Domain/PrivateMessage.cs b/src/slskd/Service/Messaging/Domain/PrivateMessage.cs new file mode 100644 index 00000000..236632aa --- /dev/null +++ b/src/slskd/Service/Messaging/Domain/PrivateMessage.cs @@ -0,0 +1,71 @@ +// <copyright file="PrivateMessage.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging +{ + using System; + using Soulseek; + + /// <summary> + /// A private message. + /// </summary> + public class PrivateMessage + { + /// <summary> + /// A value indicating whether the message has been acknowledged. + /// </summary> + public bool Acknowledged { get; set; } = false; + + /// <summary> + /// The unique message id, used to acknowledge receipt. + /// </summary> + public int Id { get; set; } + + /// <summary> + /// The message. + /// </summary> + public string Message { get; set; } + + /// <summary> + /// A value indicating whether the message was replayed. + /// </summary> + public bool Replayed { get; set; } + + /// <summary> + /// The UTC timestamp of the message. + /// </summary> + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// <summary> + /// The username of the user who sent the message. + /// </summary> + public string Username { get; set; } + + public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) + { + return new PrivateMessage() + { + Id = eventArgs.Id, + Timestamp = eventArgs.Timestamp, + Username = eventArgs.Username, + Message = eventArgs.Message, + Acknowledged = false, + Replayed = eventArgs.Replayed, + }; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Messaging/Domain/Room.cs b/src/slskd/Service/Messaging/Domain/Room.cs new file mode 100644 index 00000000..459dea2c --- /dev/null +++ b/src/slskd/Service/Messaging/Domain/Room.cs @@ -0,0 +1,75 @@ +// <copyright file="Room.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging +{ + using System.Collections.Generic; + using System.Linq; + using Soulseek; + + public class Room + { + /// <summary> + /// The room name. + /// </summary> + public string Name { get; set; } + + /// <summary> + /// A value indicating whether the room is private. + /// </summary> + public bool IsPrivate { get; set; } + + /// <summary> + /// The number of operators in the room, if private. + /// </summary> + public int? OperatorCount { get; set; } + + /// <summary> + /// The operators in the room, if private. + /// </summary> + public IList<string> Operators { get; set; } + + /// <summary> + /// The owner of the room, if private. + /// </summary> + public string Owner { get; set; } + + /// <summary> + /// The list of users in the room. + /// </summary> + public IList<UserData> Users { get; set; } = new List<UserData>(); + + /// <summary> + /// The list of messages. + /// </summary> + public IList<RoomMessage> Messages { get; set; } = new List<RoomMessage>(); + + public static Room FromRoomData(RoomData roomData) + { + return new Room() + { + Name = roomData.Name, + IsPrivate = roomData.IsPrivate, + OperatorCount = roomData.OperatorCount, + Operators = roomData.Operators?.ToList(), + Owner = roomData.Owner, + Users = roomData.Users?.ToList(), + Messages = new List<RoomMessage>(), + }; + } + } +} diff --git a/src/slskd/Service/Messaging/Domain/RoomMessage.cs b/src/slskd/Service/Messaging/Domain/RoomMessage.cs new file mode 100644 index 00000000..7a06a192 --- /dev/null +++ b/src/slskd/Service/Messaging/Domain/RoomMessage.cs @@ -0,0 +1,59 @@ +// <copyright file="RoomMessage.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging +{ + using System; + using Soulseek; + + /// <summary> + /// A message sent to a room. + /// </summary> + public class RoomMessage + { + /// <summary> + /// The timestamp of the message. + /// </summary> + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// <summary> + /// The username of the user who sent the message. + /// </summary> + public string Username { get; set; } + + /// <summary> + /// The message. + /// </summary> + public string Message { get; set; } + + /// <summary> + /// The room to which the message pertains. + /// </summary> + public string RoomName { get; set; } + + public static RoomMessage FromEventArgs(RoomMessageReceivedEventArgs eventArgs, DateTime? timestamp = null) + { + return new RoomMessage() + { + Timestamp = timestamp ?? DateTime.UtcNow, + Username = eventArgs.Username, + Message = eventArgs.Message, + RoomName = eventArgs.RoomName, + }; + } + } +} diff --git a/src/slskd/Service/Messaging/IConversationTracker.cs b/src/slskd/Service/Messaging/IConversationTracker.cs new file mode 100644 index 00000000..8e7a90f4 --- /dev/null +++ b/src/slskd/Service/Messaging/IConversationTracker.cs @@ -0,0 +1,55 @@ +// <copyright file="IConversationTracker.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + + /// <summary> + /// Tracks private message conversations. + /// </summary> + public interface IConversationTracker + { + /// <summary> + /// Tracked private message conversations. + /// </summary> + ConcurrentDictionary<string, IList<PrivateMessage>> Conversations { get; } + + /// <summary> + /// Adds a private message conversation and appends the specified <paramref name="message"/>, or just appends the + /// message if the conversation exists. + /// </summary> + /// <param name="username"></param> + /// <param name="message"></param> + void AddOrUpdate(string username, PrivateMessage message); + + /// <summary> + /// Returns the list of private messages for the specified <paramref name="username"/>, if any exist. + /// </summary> + /// <param name="username"></param> + /// <param name="messages"></param> + /// <returns></returns> + bool TryGet(string username, out IList<PrivateMessage> messages); + + /// <summary> + /// Removes a tracked private message conversation for the specified user. + /// </summary> + /// <param name="username"></param> + void TryRemove(string username); + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Messaging/IRoomTracker.cs b/src/slskd/Service/Messaging/IRoomTracker.cs new file mode 100644 index 00000000..225e5f69 --- /dev/null +++ b/src/slskd/Service/Messaging/IRoomTracker.cs @@ -0,0 +1,75 @@ +// <copyright file="IRoomTracker.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging +{ + using System.Collections.Concurrent; + using Soulseek; + + /// <summary> + /// Tracks rooms. + /// </summary> + public interface IRoomTracker + { + /// <summary> + /// Gets tracked rooms. + /// </summary> + ConcurrentDictionary<string, Room> Rooms { get; } + + /// <summary> + /// Adds a room and appends the specified <paramref name="message"/>, or just appends the message if the room exists. + /// </summary> + /// <param name="roomName"></param> + /// <param name="message"></param> + void AddOrUpdateMessage(string roomName, RoomMessage message); + + /// <summary> + /// Adds the specified room to the tracker. + /// </summary> + /// <param name="roomName"></param> + /// <param name="room"></param> + void TryAdd(string roomName, Room room); + + /// <summary> + /// Adds the specified <paramref name="userData"/> to the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="userData"></param> + void TryAddUser(string roomName, UserData userData); + + /// <summary> + /// Returns the list of messages for the specified <paramref name="roomName"/>, if it is tracked. + /// </summary> + /// <param name="roomName"></param> + /// <param name="room"></param> + /// <returns></returns> + bool TryGet(string roomName, out Room room); + + /// <summary> + /// Removes a tracked room. + /// </summary> + /// <param name="roomName"></param> + void TryRemove(string roomName); + + /// <summary> + /// Removes the specified <paramref name="username"/> from the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="username"></param> + void TryRemoveUser(string roomName, string username); + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Messaging/RoomTracker.cs b/src/slskd/Service/Messaging/RoomTracker.cs new file mode 100644 index 00000000..c586f401 --- /dev/null +++ b/src/slskd/Service/Messaging/RoomTracker.cs @@ -0,0 +1,112 @@ +// <copyright file="RoomTracker.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using Soulseek; + + /// <summary> + /// Tracks rooms. + /// </summary> + public class RoomTracker : IRoomTracker + { + /// <summary> + /// Initializes a new instance of the <see cref="RoomTracker"/> class. + /// </summary> + /// <param name="messageLimit"></param> + public RoomTracker(int messageLimit = 25) + { + MessageLimit = messageLimit; + } + + /// <summary> + /// Tracked rooms. + /// </summary> + public ConcurrentDictionary<string, Room> Rooms { get; } = new ConcurrentDictionary<string, Room>(); + + private int MessageLimit { get; } + + /// <summary> + /// Adds a room and appends the specified <paramref name="message"/>, or just appends the message if the room exists. + /// </summary> + /// <param name="roomName"></param> + /// <param name="message"></param> + public void AddOrUpdateMessage(string roomName, RoomMessage message) + { + Rooms.AddOrUpdate(roomName, new Room() { Messages = new List<RoomMessage>() { message } }, (_, room) => + { + if (room.Messages.Count >= MessageLimit) + { + room.Messages = room.Messages.TakeLast(MessageLimit - 1).ToList(); + } + + room.Messages.Add(message); + return room; + }); + } + + /// <summary> + /// Adds the specified room to the tracker. + /// </summary> + /// <param name="roomName"></param> + /// <param name="room"></param> + public void TryAdd(string roomName, Room room) => Rooms.TryAdd(roomName, room); + + /// <summary> + /// Adds the specified <paramref name="userData"/> to the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="userData"></param> + public void TryAddUser(string roomName, UserData userData) + { + if (Rooms.TryGetValue(roomName, out var room)) + { + room.Users.Add(userData); + } + } + + /// <summary> + /// Removes a tracked room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="room"></param> + /// <returns></returns> + public bool TryGet(string roomName, out Room room) => Rooms.TryGetValue(roomName, out room); + + /// <summary> + /// Returns the list of messages for the specified <paramref name="roomName"/>, if it is tracked. + /// </summary> + /// <param name="roomName"></param> + public void TryRemove(string roomName) => Rooms.TryRemove(roomName, out _); + + /// <summary> + /// Removes the specified <paramref name="username"/> from the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="username"></param> + public void TryRemoveUser(string roomName, string username) + { + if (Rooms.TryGetValue(roomName, out var room)) + { + room.Users = room.Users.Where(u => u.Username != username).ToList(); + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Peer/API/Controllers/PeersController.cs b/src/slskd/Service/Peer/API/Controllers/PeersController.cs new file mode 100644 index 00000000..94ce96dd --- /dev/null +++ b/src/slskd/Service/Peer/API/Controllers/PeersController.cs @@ -0,0 +1,171 @@ +// <copyright file="PeersController.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Peer.API +{ + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.Net; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Users. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class PeersController : ControllerBase + { + /// <summary> + /// Initializes a new instance of the <see cref="PeersController"/> class. + /// </summary> + /// <param name="client"></param> + /// <param name="browseTracker"></param> + /// <param name="peerService"></param> + public PeersController(ISoulseekClient client, IBrowseTracker browseTracker, IPeerService peerService) + { + Client = client; + BrowseTracker = browseTracker; + Peers = peerService; + } + + private IBrowseTracker BrowseTracker { get; } + private ISoulseekClient Client { get; } + private IPeerService Peers { get; } + + /// <summary> + /// Retrieves the address of the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of the user.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("{username}/endpoint")] + [Authorize] + [ProducesResponseType(typeof(IPEndPoint), 200)] + [ProducesResponseType(404)] + public async Task<IActionResult> Endpoint([FromRoute, Required] string username) + { + try + { + var endpoint = await Peers.GetIPEndPointAsync(username); + return Ok(endpoint); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// <summary> + /// Retrieves the files shared by the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of the user.</param> + /// <returns></returns> + [HttpGet("{username}/browse")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable<Directory>), 200)] + [ProducesResponseType(404)] + public async Task<IActionResult> Browse([FromRoute, Required] string username) + { + try + { + var result = await Client.BrowseAsync(username); + + _ = Task.Run(async () => + { + await Task.Delay(5000); + BrowseTracker.TryRemove(username); + }); + + return Ok(result); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// <summary> + /// Retrieves the status of the current browse operation for the specified <paramref name="username"/>, if any. + /// </summary> + /// <param name="username">The username of the user.</param> + /// <returns></returns> + [HttpGet("{username}/browse/status")] + [Authorize] + [ProducesResponseType(typeof(decimal), 200)] + [ProducesResponseType(404)] + public IActionResult BrowseStatus([FromRoute, Required] string username) + { + if (BrowseTracker.TryGet(username, out var progress)) + { + return Ok(progress); + } + + return NotFound(); + } + + /// <summary> + /// Retrieves information about the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of the user.</param> + /// <param name="bypassCache">Bypasses the internal cache and requests the latest information from the peer.</param> + /// <returns></returns> + [HttpGet("{username}/info")] + [Authorize] + [ProducesResponseType(typeof(Info), 200)] + [ProducesResponseType(404)] + public async Task<IActionResult> Info([FromRoute, Required] string username, [FromQuery]bool bypassCache = false) + { + try + { + var response = await Peers.GetInfoAsync(username, bypassCache); + return Ok(response); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// <summary> + /// Retrieves status for the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of the user.</param> + /// <returns></returns> + [HttpGet("{username}/status")] + [Authorize] + [ProducesResponseType(typeof(Status), 200)] + [ProducesResponseType(404)] + public async Task<IActionResult> Status([FromRoute, Required] string username) + { + try + { + var response = await Peers.GetStatusAsync(username); + return Ok(response); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Peer/API/DTO/UserDataResponse.cs b/src/slskd/Service/Peer/API/DTO/UserDataResponse.cs new file mode 100644 index 00000000..024b1828 --- /dev/null +++ b/src/slskd/Service/Peer/API/DTO/UserDataResponse.cs @@ -0,0 +1,85 @@ +// <copyright file="UserDataResponse.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Peer.API +{ + using Soulseek; + + public class UserDataResponse + { + /// <summary> + /// The average upload speed of the user. + /// </summary> + public int AverageSpeed { get; set; } + + /// <summary> + /// The user's country code, if provided. + /// </summary> + public string CountryCode { get; set; } + + /// <summary> + /// The number of directories shared by the user. + /// </summary> + public int DirectoryCount { get; set; } + + /// <summary> + /// The number of active user downloads. + /// </summary> + public long DownloadCount { get; set; } + + /// <summary> + /// The number of files shared by the user. + /// </summary> + public int FileCount { get; set; } + + /// <summary> + /// A value indicating whether this user data belongs to the currently logged in user. + /// </summary> + public bool? Self { get; set; } + + /// <summary> + /// The number of the user's free download slots, if provided. + /// </summary> + public int? SlotsFree { get; set; } + + /// <summary> + /// The status of the user (0 = offline, 1 = away, 2 = online). + /// </summary> + public UserPresence Status { get; set; } + + /// <summary> + /// The username of the user. + /// </summary> + public string Username { get; set; } + + public static UserDataResponse FromUserData(UserData userData, bool self = false) + { + return new UserDataResponse() + { + AverageSpeed = userData.AverageSpeed, + CountryCode = userData.CountryCode, + DirectoryCount = userData.DirectoryCount, + DownloadCount = userData.DownloadCount, + FileCount = userData.FileCount, + SlotsFree = userData.SlotsFree, + Status = userData.Status, + Username = userData.Username, + Self = self ? self : (bool?)null, + }; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Peer/BrowseTracker.cs b/src/slskd/Service/Peer/BrowseTracker.cs new file mode 100644 index 00000000..5fa6b14a --- /dev/null +++ b/src/slskd/Service/Peer/BrowseTracker.cs @@ -0,0 +1,57 @@ +// <copyright file="BrowseTracker.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Peer +{ + using System.Collections.Concurrent; + using Soulseek; + + /// <summary> + /// Tracks browse operations. + /// </summary> + public class BrowseTracker : IBrowseTracker + { + /// <summary> + /// Tracked browse operations. + /// </summary> + public ConcurrentDictionary<string, BrowseProgressUpdatedEventArgs> Browses { get; } = new ConcurrentDictionary<string, BrowseProgressUpdatedEventArgs>(); + + /// <summary> + /// Adds or updates a tracked browse operation. + /// </summary> + /// <param name="username"></param> + /// <param name="progress"></param> + public void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress) + => Browses.AddOrUpdate(username, progress, (user, oldprogress) => progress); + + /// <summary> + /// Removes a tracked browse operation for the specified user. + /// </summary> + /// <param name="username"></param> + public void TryRemove(string username) + => Browses.TryRemove(username, out _); + + /// <summary> + /// Gets the browse progress for the specified user. + /// </summary> + /// <param name="username"></param> + /// <param name="progress"></param> + /// <returns></returns> + public bool TryGet(string username, out BrowseProgressUpdatedEventArgs progress) + => Browses.TryGetValue(username, out progress); + } +} diff --git a/src/slskd/Service/Peer/Domain/Info.cs b/src/slskd/Service/Peer/Domain/Info.cs new file mode 100644 index 00000000..b2d17c8a --- /dev/null +++ b/src/slskd/Service/Peer/Domain/Info.cs @@ -0,0 +1,51 @@ +// <copyright file="Info.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Peer +{ + using System; + using System.ComponentModel.DataAnnotations; + using Soulseek; + + public class Info + { + [Key] + public string Username { get; init; } + public string Description { get; init; } + public bool HasFreeUploadSlot { get; init; } + public bool HasPicture { get; init; } + public byte[] Picture { get; init; } + public int QueueLength { get; init; } + public int UploadSlots { get; init; } + public DateTime UpdatedAt { get; init; } + + public static Info FromSoulseekUserInfo(string username, UserInfo info) + { + return new Info() + { + Username = username, + Description = info.Description, + HasFreeUploadSlot = info.HasFreeUploadSlot, + HasPicture = info.HasPicture, + Picture = info.Picture, + QueueLength = info.QueueLength, + UploadSlots = info.UploadSlots, + UpdatedAt = DateTime.UtcNow, + }; + } + } +} diff --git a/src/slskd/Service/Peer/Domain/Status.cs b/src/slskd/Service/Peer/Domain/Status.cs new file mode 100644 index 00000000..4db4e859 --- /dev/null +++ b/src/slskd/Service/Peer/Domain/Status.cs @@ -0,0 +1,36 @@ +// <copyright file="Status.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Peer +{ + using Soulseek; + + public class Status + { + public bool IsPrivileged { get; init; } + public UserPresence Presence { get; init; } + + public static Status FromSoulseekUserStatus(UserStatus status) + { + return new Status() + { + IsPrivileged = status.IsPrivileged, + Presence = status.Presence, + }; + } + } +} diff --git a/src/slskd/Service/Peer/IBrowseTracker.cs b/src/slskd/Service/Peer/IBrowseTracker.cs new file mode 100644 index 00000000..606b8a45 --- /dev/null +++ b/src/slskd/Service/Peer/IBrowseTracker.cs @@ -0,0 +1,54 @@ +// <copyright file="IBrowseTracker.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Peer +{ + using System.Collections.Concurrent; + using Soulseek; + + /// <summary> + /// Tracks browse operations. + /// </summary> + public interface IBrowseTracker + { + /// <summary> + /// Tracked browse operations. + /// </summary> + ConcurrentDictionary<string, BrowseProgressUpdatedEventArgs> Browses { get; } + + /// <summary> + /// Adds or updates a tracked browse operation. + /// </summary> + /// <param name="username"></param> + /// <param name="progress"></param> + void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress); + + /// <summary> + /// Gets the browse progress for the specified user. + /// </summary> + /// <param name="username"></param> + /// <param name="progress"></param> + /// <returns></returns> + bool TryGet(string username, out BrowseProgressUpdatedEventArgs progress); + + /// <summary> + /// Removes a tracked browse operation for the specified user. + /// </summary> + /// <param name="username"></param> + void TryRemove(string username); + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Peer/IPeerService.cs b/src/slskd/Service/Peer/IPeerService.cs new file mode 100644 index 00000000..f49cf27b --- /dev/null +++ b/src/slskd/Service/Peer/IPeerService.cs @@ -0,0 +1,72 @@ +// <copyright file="IPeerService.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Peer +{ + using System.Net; + using System.Threading.Tasks; + + /// <summary> + /// Provides information and operations for network peers. + /// </summary> + public interface IPeerService + { + /// <summary> + /// Retrieves peer <see cref="Info"/>. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <param name="bypassCache">A value indicating whether the local cache should be bypassed.</param> + /// <returns>The cached or retrieved info.</returns> + Task<Info> GetInfoAsync(string username, bool bypassCache = false); + + /// <summary> + /// Retrieves a peer's IP endpoint, including their IP address and listen port. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>The retrieved endpoint.</returns> + Task<IPEndPoint> GetIPEndPointAsync(string username); + + /// <summary> + /// Retrieves the current <see cref="Status"/> of a peer. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>The retrieved status.</returns> + Task<Status> GetStatusAsync(string username); + + /// <summary> + /// Grants the specified peer the specified number of privilege days. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <param name="days">The number of days to grant.</param> + /// <returns>The operation context.</returns> + Task GrantPrivilegesAsync(string username, int days); + + /// <summary> + /// Retrieves a value indicating whether the specified peer is privileged. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>A value indicating whether the specified peer is privileged.</returns> + Task<bool> IsPrivilegedAsync(string username); + + /// <summary> + /// Adds the specified username to the server-side user list. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>The operation context.</returns> + Task WatchAsync(string username); + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Peer/PeerDbContext.cs b/src/slskd/Service/Peer/PeerDbContext.cs new file mode 100644 index 00000000..ee5dfd04 --- /dev/null +++ b/src/slskd/Service/Peer/PeerDbContext.cs @@ -0,0 +1,32 @@ +// <copyright file="PeerDbContext.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Peer +{ + using Microsoft.EntityFrameworkCore; + + public class PeerDbContext : DbContext + { + public PeerDbContext(DbContextOptions<PeerDbContext> options) + : base(options) + { + Database.EnsureCreated(); + } + + public DbSet<Info> Info { get; set; } + } +} diff --git a/src/slskd/Service/Peer/PeerService.cs b/src/slskd/Service/Peer/PeerService.cs new file mode 100644 index 00000000..e0e03fa6 --- /dev/null +++ b/src/slskd/Service/Peer/PeerService.cs @@ -0,0 +1,138 @@ +// <copyright file="PeerService.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Peer +{ + using System; + using System.Net; + using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; + using Microsoft.Extensions.Logging; + using ISoulseekClient = Soulseek.ISoulseekClient; + + /// <summary> + /// Provides information and operations for network peers. + /// </summary> + public class PeerService : IPeerService + { + private const int CacheTTLSeconds = 300; + + /// <summary> + /// Initializes a new instance of the <see cref="PeerService"/> class. + /// </summary> + /// <param name="client">The client instance to use.</param> + /// <param name="contextFactory">The database context to use.</param> + /// <param name="log">The logger.</param> + public PeerService( + ISoulseekClient client, + IDbContextFactory<PeerDbContext> contextFactory, + ILogger<PeerService> log) + { + Client = client; + ContextFactory = contextFactory; + Log = log; + } + + private ISoulseekClient Client { get; } + private IDbContextFactory<PeerDbContext> ContextFactory { get; } + private ILogger<PeerService> Log { get; set; } + + /// <summary> + /// Retrieves peer <see cref="Info"/>. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <param name="bypassCache">A value indicating whether the local cache should be bypassed.</param> + /// <returns>The cached or retrieved info.</returns> + public async Task<Info> GetInfoAsync(string username, bool bypassCache = false) + { + using var context = ContextFactory.CreateDbContext(); + + var info = await context.Info.AsNoTracking().FirstOrDefaultAsync(peer => peer.Username == username); + var peerExists = info != default; + + if (!bypassCache && peerExists && info.UpdatedAt < DateTime.UtcNow.AddSeconds(CacheTTLSeconds)) + { + return info; + } + + var soulseekUserInfo = await Client.GetUserInfoAsync(username); + info = Info.FromSoulseekUserInfo(username, soulseekUserInfo); + + if (peerExists) + { + context.Update(info); + } + else + { + context.Add(info); + } + + await context.SaveChangesAsync(); + + return info; + } + + /// <summary> + /// Retrieves a peer's IP endpoint, including their IP address and listen port. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>The retrieved endpoint.</returns> + public Task<IPEndPoint> GetIPEndPointAsync(string username) + { + return Client.GetUserEndPointAsync(username); + } + + /// <summary> + /// Retrieves the current <see cref="Status"/> of a peer. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>The retrieved status.</returns> + public async Task<Status> GetStatusAsync(string username) + { + var soulseekStatus = await Client.GetUserStatusAsync(username); + + return Status.FromSoulseekUserStatus(soulseekStatus); + } + + /// <summary> + /// Grants the specified peer the specified number of privilege days. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <param name="days">The number of days to grant.</param> + /// <returns>The operation context.</returns> + public Task GrantPrivilegesAsync(string username, int days) + => Client.GrantUserPrivilegesAsync(username, days); + + /// <summary> + /// Retrieves a value indicating whether the specified peer is privileged. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>A value indicating whether the specified peer is privileged.</returns> + public Task<bool> IsPrivilegedAsync(string username) + => Client.GetUserPrivilegedAsync(username); + + /// <summary> + /// Adds the specified username to the server-side user list. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>The operation context.</returns> + public async Task WatchAsync(string username) + { + await Client.AddUserAsync(username); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Search/API/Controllers/SearchesController.cs b/src/slskd/Service/Search/API/Controllers/SearchesController.cs new file mode 100644 index 00000000..5f740044 --- /dev/null +++ b/src/slskd/Service/Search/API/Controllers/SearchesController.cs @@ -0,0 +1,135 @@ +// <copyright file="SearchesController.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Search.API +{ + using System; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using SearchQuery = Soulseek.SearchQuery; + using SearchScope = Soulseek.SearchScope; + + /// <summary> + /// Search. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class SearchesController : ControllerBase + { + /// <summary> + /// Initializes a new instance of the <see cref="SearchesController"/> class. + /// </summary> + /// <param name="searchService"></param> + public SearchesController(ISearchService searchService) + { + Searches = searchService; + } + + private ISearchService Searches { get; } + + /// <summary> + /// Performs a search for the specified <paramref name="request"/>. + /// </summary> + /// <param name="request">The search request.</param> + /// <returns></returns> + /// <response code="200">The search completed successfully.</response> + /// <response code="400">The specified <paramref name="request"/> was malformed.</response> + /// <response code="500">The search terminated abnormally.</response> + [HttpPost("")] + [Authorize] + public async Task<IActionResult> Post([FromBody]SearchRequest request) + { + var id = request.Id ?? Guid.NewGuid(); + var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1)); + + Search search = null; + + try + { + search = await Searches.CreateAsync(id, SearchQuery.FromText(searchText), SearchScope.Network); + return Ok(search.Responses); + } + catch (Exception ex) + { + return StatusCode(500, $"Search terminated abnormally: {ex.Message}"); + } + finally + { + search = null; + } + } + + /// <summary> + /// Gets the state of the search corresponding to the specified <paramref name="id"/>. + /// </summary> + /// <param name="id">The unique id of the search.</param> + /// <param name="includeResponses">A value indicating whether to include search responses in the response.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">A matching search was not found.</response> + [HttpGet("{id}")] + [Authorize] + public async Task<IActionResult> GetById([FromRoute]Guid id, [FromQuery]bool includeResponses = false) + { + var search = await Searches.FindAsync(search => search.Id == id, includeResponses); + + if (search == default) + { + return NotFound(); + } + + return Ok(search); + } + + /// <summary> + /// Gets the state of the search corresponding to the specified <paramref name="id"/>. + /// </summary> + /// <param name="id">The unique id of the search.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">A matching search was not found.</response> + [HttpGet("{id}/responses")] + [Authorize] + public async Task<IActionResult> GetResponsesById([FromRoute] Guid id) + { + var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true); + + if (search == default) + { + return NotFound(); + } + + return Ok(search.Responses); + } + + /// <summary> + /// Gets the list of active and completed searches. + /// </summary> + /// <returns></returns> + [HttpGet("")] + [Authorize] + public async Task<IActionResult> GetAll() + { + return Ok(await Searches.ListAsync()); + } + } +} diff --git a/src/slskd/Service/Search/API/DTO/SearchRequest.cs b/src/slskd/Service/Search/API/DTO/SearchRequest.cs new file mode 100644 index 00000000..aad5a200 --- /dev/null +++ b/src/slskd/Service/Search/API/DTO/SearchRequest.cs @@ -0,0 +1,116 @@ +// <copyright file="SearchRequest.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Search.API +{ + using System; + using Soulseek; + + /// <summary> + /// A search request. + /// </summary> + public class SearchRequest + { + /// <summary> + /// Gets or sets the unique search identifier. + /// </summary> + public Guid? Id { get; set; } + + /// <summary> + /// Gets or sets the maximum number of file results to accept before the search is considered complete. (Default = 10,000). + /// </summary> + public int? FileLimit { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether responses are to be filtered. (Default = true). + /// </summary> + public bool? FilterResponses { get; set; } + + /// <summary> + /// Gets or sets the maximum queue depth a peer may have in order for a response to be processed. (Default = 1000000). + /// </summary> + public int? MaximumPeerQueueLength { get; set; } + + /// <summary> + /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed. + /// (Default = 0). + /// </summary> + public int? MinimumPeerFreeUploadSlots { get; set; } + + /// <summary> + /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0). + /// </summary> + public int? MinimumPeerUploadSpeed { get; set; } + + /// <summary> + /// Gets or sets the minimum number of files a response must contain in order to be processed. (Default = 1). + /// </summary> + public int? MinimumResponseFileCount { get; set; } + + /// <summary> + /// Gets or sets the maximum number of search results to accept before the search is considered complete. (Default = 100). + /// </summary> + public int? ResponseLimit { get; set; } + + /// <summary> + /// Gets or sets the search text. + /// </summary> + public string SearchText { get; set; } + + /// <summary> + /// Gets or sets the search timeout value, in seconds, used to determine when the search is complete. (Default = 15). + /// </summary> + /// <remarks>The timeout duration is from the time of the last response.</remarks> + public int? SearchTimeout { get; set; } + + /// <summary> + /// Gets or sets the search token. + /// </summary> + public int? Token { get; set; } + + /// <summary> + /// Maps to a new instance of <see cref="SearchOptions"/>. + /// </summary> + /// <param name="responseFilter"></param> + /// <param name="fileFilter"></param> + /// <param name="stateChanged"></param> + /// <param name="responseReceived"></param> + /// <returns></returns> + public SearchOptions ToSearchOptions( + Func<SearchResponse, bool> responseFilter = null, + Func<File, bool> fileFilter = null, + Action<SearchStateChangedEventArgs> stateChanged = null, + Action<SearchResponseReceivedEventArgs> responseReceived = null) + { + var def = new SearchOptions(); + + return new SearchOptions( + searchTimeout: SearchTimeout ?? def.SearchTimeout, + responseLimit: ResponseLimit ?? def.ResponseLimit, + fileLimit: FileLimit ?? def.FileLimit, + filterResponses: FilterResponses ?? def.FilterResponses, + minimumResponseFileCount: MinimumResponseFileCount ?? def.MinimumResponseFileCount, + minimumPeerFreeUploadSlots: MinimumPeerFreeUploadSlots ?? def.MinimumPeerFreeUploadSlots, + maximumPeerQueueLength: MaximumPeerQueueLength ?? def.MaximumPeerQueueLength, + minimumPeerUploadSpeed: MinimumPeerUploadSpeed ?? def.MinimumPeerUploadSpeed, + responseFilter: responseFilter, + fileFilter: fileFilter, + responseReceived: responseReceived, + stateChanged: stateChanged); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Search/Domain/File.cs b/src/slskd/Service/Search/Domain/File.cs new file mode 100644 index 00000000..0a86eec3 --- /dev/null +++ b/src/slskd/Service/Search/Domain/File.cs @@ -0,0 +1,51 @@ +// <copyright file="File.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Search +{ + using SoulseekFile = Soulseek.File; + + public class File + { + public int? BitDepth { get; init; } + public int? BitRate { get; init; } + public int Code { get; init; } + public string Extension { get; init; } + public string Filename { get; init; } + public bool? IsVariableBitRate { get; init; } + public int? Length { get; init; } + public int? SampleRate { get; init; } + public long Size { get; init; } + public bool IsLocked { get; init; } + + public static File FromSoulseekFile(SoulseekFile file) + { + return new File() + { + BitDepth = file.BitDepth, + BitRate = file.BitRate, + Code = file.Code, + Extension = file.Extension, + Filename = file.Filename, + IsVariableBitRate = file.IsVariableBitRate, + Length = file.Length, + SampleRate = file.SampleRate, + Size = file.Size, + }; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Search/Domain/Response.cs b/src/slskd/Service/Search/Domain/Response.cs new file mode 100644 index 00000000..ea2e8993 --- /dev/null +++ b/src/slskd/Service/Search/Domain/Response.cs @@ -0,0 +1,51 @@ +// <copyright file="Response.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Search +{ + using System.Collections.Generic; + using System.Linq; + + public class Response + { + public int FileCount { get; init; } + public ICollection<File> Files { get; init; } = new List<File>(); + public int FreeUploadSlots { get; init; } + public int LockedFileCount { get; init; } + public ICollection<File> LockedFiles { get; init; } = new List<File>(); + public long QueueLength { get; init; } + public int Token { get; init; } + public int UploadSpeed { get; init; } + public string Username { get; init; } + + public static Response FromSoulseekSearchResponse(Soulseek.SearchResponse searchResponse) + { + return new Response() + { + FileCount = searchResponse.FileCount, + Files = searchResponse.Files.Select(file => File.FromSoulseekFile(file)).ToList(), + FreeUploadSlots = searchResponse.FreeUploadSlots, + LockedFileCount = searchResponse.LockedFileCount, + LockedFiles = searchResponse.LockedFiles.Select(file => File.FromSoulseekFile(file)).ToList(), + QueueLength = searchResponse.QueueLength, + Token = searchResponse.Token, + UploadSpeed = searchResponse.UploadSpeed, + Username = searchResponse.Username, + }; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Search/Domain/Search.cs b/src/slskd/Service/Search/Domain/Search.cs new file mode 100644 index 00000000..b93c62cb --- /dev/null +++ b/src/slskd/Service/Search/Domain/Search.cs @@ -0,0 +1,60 @@ +// <copyright file="Search.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Search +{ + using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using System.Text.Json; + using System.Text.Json.Serialization; + using Soulseek; + + public class Search + { + public DateTime? EndedAt { get; set; } + public int FileCount { get; set; } + + [Key] + public Guid Id { get; init; } + + [NotMapped] + public bool IsComplete => State.HasFlag(SearchStates.Completed); + + public int LockedFileCount { get; set; } + public int ResponseCount { get; set; } + + [NotMapped] + public IEnumerable<Response> Responses { get; set; } = new List<Response>(); + + [JsonIgnore] + public string ResponsesJson + { + get => JsonSerializer.Serialize(Responses); + set + { + Responses = JsonSerializer.Deserialize<IEnumerable<Response>>(value); + } + } + + public string SearchText { get; init; } + public DateTime StartedAt { get; init; } = DateTime.UtcNow; + public SearchStates State { get; set; } + public int Token { get; init; } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Search/Extensions.cs b/src/slskd/Service/Search/Extensions.cs new file mode 100644 index 00000000..d52975d2 --- /dev/null +++ b/src/slskd/Service/Search/Extensions.cs @@ -0,0 +1,94 @@ +// <copyright file="Extensions.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Search +{ + using System; + using System.Linq; + using Soulseek; + + public static class Extensions + { + /// <summary> + /// Returns a copy of the specified <paramref name="options"/> with the specified actions bound, while retaining the existing actions. + /// </summary> + /// <param name="options"></param> + /// <param name="stateChanged"></param> + /// <param name="responseReceived"></param> + /// <returns></returns> + public static SearchOptions WithActions( + this SearchOptions options, + Action<SearchStateChangedEventArgs> stateChanged = null, + Action<SearchResponseReceivedEventArgs> responseReceived = null) + { + stateChanged ??= (args) => { }; + responseReceived ??= (args) => { }; + + return new SearchOptions( + options.SearchTimeout, + options.ResponseLimit, + options.FilterResponses, + options.MinimumResponseFileCount, + options.MinimumPeerFreeUploadSlots, + options.MaximumPeerQueueLength, + options.MinimumPeerUploadSpeed, + options.FileLimit, + options.RemoveSingleCharacterSearchTerms, + options.ResponseFilter, + options.FileFilter, + stateChanged: (args) => + { + if (options.StateChanged != null) + { + options.StateChanged(args); + } + + stateChanged(args); + }, + responseReceived: (args) => + { + if (options.ResponseReceived != null) + { + options.ResponseReceived(args); + } + + responseReceived(args); + }); + } + + /// <summary> + /// Creates a projection over the specified <paramref name="query"/> which omits responses. + /// </summary> + /// <param name="query"></param> + /// <returns></returns> + public static IQueryable<Search> WithoutResponses(this IQueryable<Search> query) + { + return query.Select(s => new Search() + { + Id = s.Id, + StartedAt = s.StartedAt, + EndedAt = s.EndedAt, + FileCount = s.FileCount, + LockedFileCount = s.LockedFileCount, + ResponseCount = s.ResponseCount, + SearchText = s.SearchText, + State = s.State, + Token = s.Token, + }); + } + } +} diff --git a/src/slskd/Service/Search/ISearchService.cs b/src/slskd/Service/Search/ISearchService.cs new file mode 100644 index 00000000..d696617d --- /dev/null +++ b/src/slskd/Service/Search/ISearchService.cs @@ -0,0 +1,66 @@ +// <copyright file="ISearchService.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Search +{ + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Threading.Tasks; + using SearchOptions = Soulseek.SearchOptions; + using SearchQuery = Soulseek.SearchQuery; + using SearchScope = Soulseek.SearchScope; + + /// <summary> + /// Handles the lifecycle and persistence of searches. + /// </summary> + public interface ISearchService + { + /// <summary> + /// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>. + /// </summary> + /// <param name="id">A unique identifier for the search.</param> + /// <param name="query">The search query.</param> + /// <param name="scope">The search scope.</param> + /// <param name="options">Search options.</param> + /// <returns>The completed search.</returns> + Task<Search> CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); + + /// <summary> + /// Finds a single search matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">The expression to use to match searches.</param> + /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param> + /// <returns>The found search, or default if not found.</returns> + /// <exception cref="ArgumentException">Thrown an expression is not supplied.</exception> + Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = false); + + /// <summary> + /// Returns a list of all completed and in-progress searches, with responses omitted. + /// </summary> + /// <param name="expression">An optional expression used to match searches.</param> + /// <returns>The list of searches matching the specified expression.</returns> + Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null); + + /// <summary> + /// Cancels the search matching the specified <paramref name="id"/>, if it is in progress. + /// </summary> + /// <param name="id">The unique identifier for the search.</param> + /// <returns>A value indicating whether the search was sucessfully cancelled.</returns> + bool TryCancel(Guid id); + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Search/SearchDbContext.cs b/src/slskd/Service/Search/SearchDbContext.cs new file mode 100644 index 00000000..efb2fdd6 --- /dev/null +++ b/src/slskd/Service/Search/SearchDbContext.cs @@ -0,0 +1,32 @@ +// <copyright file="SearchDbContext.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Search +{ + using Microsoft.EntityFrameworkCore; + + public class SearchDbContext : DbContext + { + public SearchDbContext(DbContextOptions<SearchDbContext> options) + : base(options) + { + Database.EnsureCreated(); + } + + public DbSet<Search> Searches { get; set; } + } +} diff --git a/src/slskd/Service/Search/SearchResponseCache.cs b/src/slskd/Service/Search/SearchResponseCache.cs new file mode 100644 index 00000000..c31a3a9b --- /dev/null +++ b/src/slskd/Service/Search/SearchResponseCache.cs @@ -0,0 +1,77 @@ +// <copyright file="SearchResponseCache.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Search +{ + using System; + using Microsoft.Extensions.Caching.Memory; + using Soulseek; + + /// <summary> + /// Caches undelivered search responses. + /// </summary> + public class SearchResponseCache : ISearchResponseCache + { + /// <summary> + /// Initializes a new instance of the <see cref="SearchResponseCache"/> class. + /// </summary> + public SearchResponseCache() + { + Cache = new MemoryCache(new MemoryCacheOptions()); + } + + private IMemoryCache Cache { get; } + + /// <summary> + /// Caches or updates a response. + /// </summary> + /// <param name="responseToken">The token for which the response is to be added or updated.</param> + /// <param name="response">The response and context to cache.</param> + public void AddOrUpdate(int responseToken, (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) + { + Cache.Set(responseToken, response, TimeSpan.FromMinutes(3)); + } + + /// <summary> + /// Attempts to fetch a cached response and context for the specified <paramref name="responseToken"/>. + /// </summary> + /// <param name="responseToken">The token for the cached response.</param> + /// <param name="response">The cached response and context, if present.</param> + /// <returns>A value indicating whether a response for the specified responseToken is cached.</returns> + public bool TryGet(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) + { + return Cache.TryGetValue(responseToken, out response); + } + + /// <summary> + /// Attempts to remove a cached Soulseek.SearchResponse and context for the specified <paramref name="responseToken"/>. + /// </summary> + /// <param name="responseToken">The token for the cached response.</param> + /// <param name="response">The cached response and context, if present.</param> + /// <returns>A value indicating whether a response for the specified responseToken was removed.</returns> + public bool TryRemove(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) + { + if (Cache.TryGetValue(responseToken, out response)) + { + Cache.Remove(responseToken); + return true; + } + + return false; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Search/SearchService.cs b/src/slskd/Service/Search/SearchService.cs new file mode 100644 index 00000000..84cfd756 --- /dev/null +++ b/src/slskd/Service/Search/SearchService.cs @@ -0,0 +1,204 @@ +// <copyright file="SearchService.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Search +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Linq.Expressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; + using Microsoft.Extensions.Logging; + using ISoulseekClient = Soulseek.ISoulseekClient; + using SearchOptions = Soulseek.SearchOptions; + using SearchQuery = Soulseek.SearchQuery; + using SearchScope = Soulseek.SearchScope; + using SearchStates = Soulseek.SearchStates; + using SoulseekSearch = Soulseek.Search; + + /// <summary> + /// Handles the lifecycle and persistence of searches. + /// </summary> + public class SearchService : ISearchService + { + /// <summary> + /// Initializes a new instance of the <see cref="SearchService"/> class. + /// </summary> + /// <param name="client">The client instance to use.</param> + /// <param name="contextFactory">The database context to use.</param> + /// <param name="log">The logger.</param> + public SearchService( + ISoulseekClient client, + IDbContextFactory<SearchDbContext> contextFactory, + ILogger<SearchService> log) + { + Client = client; + ContextFactory = contextFactory; + Log = log; + } + + private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } + = new ConcurrentDictionary<Guid, CancellationTokenSource>(); + + private ISoulseekClient Client { get; } + private IDbContextFactory<SearchDbContext> ContextFactory { get; } + private ILogger<SearchService> Log { get; set; } + + /// <summary> + /// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>. + /// </summary> + /// <param name="id">A unique identifier for the search.</param> + /// <param name="query">The search query.</param> + /// <param name="scope">The search scope.</param> + /// <param name="options">Search options.</param> + /// <returns>The completed search.</returns> + public async Task<Search> CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null) + { + var token = Client.GetNextToken(); + var cancellationTokenSource = new CancellationTokenSource(); + + var search = new Search() + { + SearchText = query.SearchText, + Token = token, + Id = id, + State = SearchStates.Requested, + StartedAt = DateTime.UtcNow, + }; + + options ??= new SearchOptions(); + options = options.WithActions( + stateChanged: (args) => UpdateSearchState(search, args.Search), + responseReceived: (args) => UpdateSearchState(search, args.Search)); + + try + { + using var context = ContextFactory.CreateDbContext(); + + context.Add(search); + await context.SaveChangesAsync(); + + CancellationTokens.TryAdd(id, cancellationTokenSource); + var responses = new List<Response>(); + + var soulseekSearch = await Client.SearchAsync( + query, + responseReceived: (response) => + { + responses.Add(Response.FromSoulseekSearchResponse(response)); + }, + scope, + token, + options, + cancellationToken: cancellationTokenSource.Token); + + CancellationTokens.TryRemove(id, out _); + + search.FileCount = soulseekSearch.FileCount; + search.LockedFileCount = soulseekSearch.LockedFileCount; + search.ResponseCount = soulseekSearch.ResponseCount; + search.State = soulseekSearch.State; + search.EndedAt = DateTime.UtcNow; + search.Responses = responses; + SaveSearchState(search); + + return search; + } + finally + { + CancellationTokens.TryRemove(id, out _); + } + } + + /// <summary> + /// Finds a single search matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">The expression to use to match searches.</param> + /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param> + /// <returns>The found search, or default if not found.</returns> + /// <exception cref="ArgumentException">Thrown an expression is not supplied.</exception> + public Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = false) + { + if (expression == default) + { + throw new ArgumentException("An expression must be supplied.", nameof(expression)); + } + + using var context = ContextFactory.CreateDbContext(); + + var selector = context.Searches.Where(expression); + + if (!includeResponses) + { + selector = selector.WithoutResponses(); + } + + return selector.FirstOrDefaultAsync(); + } + + /// <summary> + /// Returns a list of all completed and in-progress searches, with responses omitted. + /// </summary> + /// <param name="expression">An optional expression used to match searches.</param> + /// <returns>The list of searches matching the specified expression.</returns> + public Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null) + { + expression ??= s => true; + using var context = ContextFactory.CreateDbContext(); + return context.Searches.Where(expression).WithoutResponses().ToListAsync(); + } + + /// <summary> + /// Cancels the search matching the specified <paramref name="id"/>, if it is in progress. + /// </summary> + /// <param name="id">The unique identifier for the search.</param> + /// <returns>A value indicating whether the search was sucessfully cancelled.</returns> + public bool TryCancel(Guid id) + { + if (CancellationTokens.TryGetValue(id, out var cts)) + { + cts.Cancel(); + return true; + } + + return false; + } + + private void UpdateSearchState(Search search, SoulseekSearch soulseekSearch) + { + if (CancellationTokens.ContainsKey(search.Id)) + { + search.FileCount = soulseekSearch.FileCount; + search.LockedFileCount = soulseekSearch.LockedFileCount; + search.ResponseCount = soulseekSearch.ResponseCount; + search.State = soulseekSearch.State; + + SaveSearchState(search); + } + } + + private void SaveSearchState(Search search) + { + var context = ContextFactory.CreateDbContext(); + context.Update(search); + context.SaveChanges(); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Server/API/Controllers/ServerController.cs b/src/slskd/Service/Server/API/Controllers/ServerController.cs new file mode 100644 index 00000000..66bc1ad6 --- /dev/null +++ b/src/slskd/Service/Server/API/Controllers/ServerController.cs @@ -0,0 +1,84 @@ +// <copyright file="ServerController.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Server.API +{ + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Server. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ServerController : ControllerBase + { + public ServerController(ISoulseekClient client) + { + Client = client; + } + + private ISoulseekClient Client { get; } + + /// <summary> + /// Connects the client. + /// </summary> + /// <param name="req"></param> + /// <returns></returns> + [HttpPost] + [Authorize] + public async Task<IActionResult> Connect([FromBody] ConnectRequest req) + { + var addr = !string.IsNullOrEmpty(req.Address); + var port = req.Port.HasValue; + var un = !string.IsNullOrEmpty(req.Username); + var pw = !string.IsNullOrEmpty(req.Password); + + if (addr && port && un && pw) + { + await Client.ConnectAsync(req.Address, req.Port.Value, req.Username, req.Password); + return Ok(); + } + + if (!addr && !port && un && pw) + { + await Client.ConnectAsync(req.Username, req.Password); + return Ok(); + } + + return BadRequest("Provide one of the following: address and port, username and password, or address, port, username and password"); + } + + /// <summary> + /// Disconnects the client. + /// </summary> + /// <param name="message"></param> + /// <returns></returns> + [HttpDelete] + [Authorize] + public IActionResult Disconnect([FromBody] string message) + { + Client.Disconnect(message); + return NoContent(); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Server/API/DTO/ConnectRequest.cs b/src/slskd/Service/Server/API/DTO/ConnectRequest.cs new file mode 100644 index 00000000..924052f3 --- /dev/null +++ b/src/slskd/Service/Server/API/DTO/ConnectRequest.cs @@ -0,0 +1,27 @@ +// <copyright file="ConnectRequest.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Server.API +{ + 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/Service/Service.cs b/src/slskd/Service/Service.cs new file mode 100644 index 00000000..246e7fc6 --- /dev/null +++ b/src/slskd/Service/Service.cs @@ -0,0 +1,451 @@ +// <copyright file="Service.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using System.Collections.Concurrent; + using System.IO; + using System.Linq; + using System.Net; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Options; + using Serilog; + using Serilog.Events; + using slskd.Messaging; + using slskd.Peer; + using slskd.Search; + using slskd.Transfer; + using Soulseek; + using Soulseek.Diagnostics; + + public class Service : IHostedService + { + private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes + + private static (int Directories, int Files) sharedCounts = (0, 0); + + public Service( + IOptions<Options> options, + ITransferTracker transferTracker, + IBrowseTracker browseTracker, + IConversationTracker conversationTracker, + IRoomTracker roomTracker, + ISharedFileCache sharedFileCache) + { + Options = options.Value; + TransferTracker = transferTracker; + BrowseTracker = browseTracker; + ConversationTracker = conversationTracker; + RoomTracker = roomTracker; + SharedFileCache = sharedFileCache; + + ProxyOptions proxyOptions = default; + + if (UsingProxy) + { + proxyOptions = new ProxyOptions( + address: Options.Soulseek.Connection.Proxy.Address, + port: Options.Soulseek.Connection.Proxy.Port.Value, + username: Options.Soulseek.Connection.Proxy.Username, + password: Options.Soulseek.Connection.Proxy.Password); + } + + var connectionOptions = new ConnectionOptions( + readBufferSize: Options.Soulseek.Connection.Buffer.Read, + writeBufferSize: Options.Soulseek.Connection.Buffer.Write, + connectTimeout: Options.Soulseek.Connection.Timeout.Connect, + inactivityTimeout: Options.Soulseek.Connection.Timeout.Inactivity, + proxyOptions: proxyOptions); + + var clientOptions = new SoulseekClientOptions( + listenPort: Options.Soulseek.ListenPort, + enableListener: true, + userEndPointCache: new UserEndPointCache(), + distributedChildLimit: Options.Soulseek.DistributedNetwork.ChildLimit, + enableDistributedNetwork: !Options.Soulseek.DistributedNetwork.Disabled, + minimumDiagnosticLevel: Options.Soulseek.DiagnosticLevel, + autoAcknowledgePrivateMessages: false, + acceptPrivateRoomInvitations: true, + serverConnectionOptions: connectionOptions, + peerConnectionOptions: connectionOptions, + transferConnectionOptions: connectionOptions, + distributedConnectionOptions: connectionOptions, + userInfoResponseResolver: UserInfoResponseResolver, + browseResponseResolver: BrowseResponseResolver, + directoryContentsResponseResolver: DirectoryContentsResponseResolver, + enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker), + searchResponseCache: new SearchResponseCache(), + searchResponseResolver: SearchResponseResolver); + + if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) + { + throw new ArgumentException("Soulseek credentials are not configured"); + } + + Client = new SoulseekClient(options: clientOptions); + + Client.DiagnosticGenerated += Client_DiagnosticGenerated; + + Client.TransferStateChanged += Client_TransferStateChanged; + Client.TransferProgressUpdated += Client_TransferProgressUpdated; + + Client.BrowseProgressUpdated += Client_BrowseProgressUpdated; + Client.UserStatusChanged += Client_UserStatusChanged; + Client.PrivateMessageReceived += Client_PrivateMessageRecieved; + + Client.PrivateRoomMembershipAdded += (e, room) => Console.WriteLine($"Added to private room {room}"); + Client.PrivateRoomMembershipRemoved += (e, room) => Console.WriteLine($"Removed from private room {room}"); + Client.PrivateRoomModerationAdded += (e, room) => Console.WriteLine($"Promoted to moderator in private room {room}"); + Client.PrivateRoomModerationRemoved += (e, room) => Console.WriteLine($"Demoted from moderator in private room {room}"); + + Client.PublicChatMessageReceived += Client_PublicChatMessageReceived; + Client.RoomMessageReceived += Client_RoomMessageReceived; + Client.RoomJoined += Client_RoomJoined; + Client.RoomLeft += Client_RoomLeft; + Client.Disconnected += Client_Disconnected; + Client.Connected += Client_Connected; + + SoulseekClient = Client; + + SharedFileCache.Refreshed += SharedFileCache_Refreshed; + } + + public static ISoulseekClient SoulseekClient { get; private set; } + private IBrowseTracker BrowseTracker { get; set; } + private ISoulseekClient Client { get; set; } + private IConversationTracker ConversationTracker { get; set; } + private ILogger Logger { get; set; } = Log.ForContext<Service>(); + private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>(); + private Options Options { get; set; } + private IRoomTracker RoomTracker { get; set; } + private ISharedFileCache SharedFileCache { get; set; } + private ITransferTracker TransferTracker { get; set; } + private bool UsingProxy => !string.IsNullOrWhiteSpace(Options.Soulseek.Connection.Proxy.Address) && Options.Soulseek.Connection.Proxy.Port.HasValue; + + public async Task StartAsync(CancellationToken cancellationToken) + { + if (UsingProxy) + { + Logger.Information($"Using Proxy {Options.Soulseek.Connection.Proxy.Address}:{Options.Soulseek.Connection.Proxy.Port}"); + } + + Logger.Information("Client started"); + Logger.Information("Listening on port {Port}", Options.Soulseek.ListenPort); + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password).ConfigureAwait(false); + } + + public Task StopAsync(CancellationToken cancellationToken) + { + Client.Disconnect("Shutting down", new ApplicationShutdownException("Shutting down")); + Client.Dispose(); + Logger.Information("Client stopped"); + return Task.CompletedTask; + } + + private static void SharedFileCache_Refreshed(object sender, (int Directories, int Files) e) + { + if (sharedCounts != e) + { + _ = SoulseekClient.SetSharedCountsAsync(e.Directories, e.Files); + sharedCounts = e; + } + } + + /// <summary> + /// Creates and returns an instances of <see cref="BrowseResponse"/> in response to a remote request. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="endpoint">The IP endpoint of the requesting user.</param> + /// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns> + private Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint) + { + var directories = System.IO.Directory + .GetDirectories(Options.Directories.Shared, "*", SearchOption.AllDirectories) + .Select(dir => new Soulseek.Directory(dir.Replace("/", @"\"), System.IO.Directory.GetFiles(dir) + .Select(f => new Soulseek.File(1, Path.GetFileName(f), new FileInfo(f).Length, Path.GetExtension(f))))); + + return Task.FromResult(new BrowseResponse(directories)); + } + + private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) + { + BrowseTracker.AddOrUpdate(args.Username, args); + } + + private void Client_DiagnosticGenerated(object sender, DiagnosticEventArgs args) + { + static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch + { + DiagnosticLevel.Debug => LogEventLevel.Debug, + DiagnosticLevel.Info => LogEventLevel.Information, + DiagnosticLevel.Warning => LogEventLevel.Warning, + DiagnosticLevel.None => default, + _ => default, + }; + + var logger = Loggers.GetOrAdd(sender.GetType().FullName, Log.ForContext("SourceContext", "Soulseek").ForContext("SoulseekContext", sender.GetType().FullName)); + + logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); + } + + private void Client_Connected(object sender, EventArgs e) + { + Logger.Information("Connected and logged in as {Username}", Options.Soulseek.Username); + } + + private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) + { + if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException) + { + Logger.Debug("Disconnected from the Soulseek server: the client is shutting down"); + } + else if (args.Exception is LoginRejectedException) + { + Logger.Error("Disconnected from the Soulseek server: invalid username or password"); + } + else if (args.Exception is KickedFromServerException) + { + Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Options.Soulseek.Username); + } + else + { + Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception.Message); + + var attempts = 1; + + while (true) + { + var (delay, jitter) = Compute.ExponentialBackoffDelay( + iteration: attempts, + maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); + + var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); + Logger.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); + await Task.Delay(delay + jitter); + + Logger.Information($"Attempting to reconnect (#{attempts})...", attempts); + + try + { + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + break; + } + catch (Exception ex) + { + attempts++; + Logger.Error("Failed to reconnect: {Message}", ex.Message); + } + } + } + } + + private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) + { + ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); + } + + private void Client_PublicChatMessageReceived(object sender, PublicChatMessageReceivedEventArgs args) + { + Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); + } + + private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) + { + // this will fire when we join a room; track that through the join operation. + if (args.Username != Options.Soulseek.Username) + { + RoomTracker.TryAddUser(args.RoomName, args.UserData); + } + } + + private void Client_RoomLeft(object sender, RoomLeftEventArgs args) + { + RoomTracker.TryRemoveUser(args.RoomName, args.Username); + } + + private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args) + { + var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); + RoomTracker.AddOrUpdateMessage(args.RoomName, message); + } + + private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args) + { + // this is really verbose. Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}] + // [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}] + // {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s"); + } + + private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args) + { + var xfer = args.Transfer; + var direction = xfer.Direction.ToString().ToUpper(); + var user = xfer.Username; + var file = Path.GetFileName(xfer.Filename); + var oldState = args.PreviousState; + var state = xfer.State; + + var completed = xfer.State.HasFlag(TransferStates.Completed); + + Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({xfer.BytesTransferred}/{xfer.Size} = {xfer.PercentComplete}%) @ {xfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}"); + + if (xfer.Direction == TransferDirection.Upload && xfer.State.HasFlag(TransferStates.Completed | TransferStates.Succeeded)) + { + _ = Client.SendUploadSpeedAsync((int)args.Transfer.AverageSpeed); + } + } + + private void Client_UserStatusChanged(object sender, UserStatusChangedEventArgs args) + { + Console.WriteLine($"[USER] {args.Username}: {args.Status}"); + } + + /// <summary> + /// Creates and returns a <see cref="Soulseek.Directory"/> in response to a remote request. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="endpoint">The IP endpoint of the requesting user.</param> + /// <param name="token">The unique token for the request, supplied by the requesting user.</param> + /// <param name="directory">The requested directory.</param> + /// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns> + private Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) + { + var result = new Soulseek.Directory(directory.Replace("/", @"\"), System.IO.Directory.GetFiles(directory) + .Select(f => new Soulseek.File(1, Path.GetFileName(f), new FileInfo(f).Length, Path.GetExtension(f)))); + + return Task.FromResult(result); + } + + /// <summary> + /// Invoked upon a remote request to download a file. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="endpoint">The IP endpoint of the requesting user.</param> + /// <param name="filename">The filename of the requested file.</param> + /// <param name="tracker">(for example purposes) the ITransferTracker used to track progress.</param> + /// <returns>A Task representing the asynchronous operation.</returns> + /// <exception cref="DownloadEnqueueException"> + /// Thrown when the download is rejected. The Exception message will be passed to the remote user. + /// </exception> + /// <exception cref="Exception"> + /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for + /// security reasons. + /// </exception> + private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) + { + _ = endpoint; + var localFilename = filename.ToLocalOSPath(); + var fileInfo = new FileInfo(localFilename); + + if (!fileInfo.Exists) + { + Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found."); + throw new DownloadEnqueueException($"File not found."); + } + + if (tracker.TryGet(TransferDirection.Upload, username, filename, out _)) + { + // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse + Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]"); + return Task.CompletedTask; + } + + // create a new cancellation token source so that we can cancel the upload from the UI. + var cts = new CancellationTokenSource(); + var topts = new TransferOptions(stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts), governor: (t, c) => Task.Delay(1, c)); + + // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and + // uploads would be handled separately. + Task.Run(async () => + { + using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + await Client.UploadAsync(username, filename, fileInfo.Length, stream, options: topts, cancellationToken: cts.Token); + }).ContinueWith(t => + { + Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); + }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget + + // return a completed task so that the invoking code can respond to the remote client. + return Task.CompletedTask; + } + + /// <summary> + /// Creates and returns a <see cref="Response"/> in response to the given <paramref name="query"/>. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="token">The search token.</param> + /// <param name="query">The search query.</param> + /// <returns>A Task resolving a SearchResponse, or null.</returns> + private Task<Soulseek.SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query) + { + var defaultResponse = Task.FromResult<Soulseek.SearchResponse>(null); + + // some bots continually query for very common strings. blacklist known names here. + var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; + if (blacklist.Contains(username)) + { + return defaultResponse; + } + + // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. + if (query.Query.Length < 3) + { + return defaultResponse; + } + + var results = SharedFileCache.Search(query); + + if (results.Any()) + { + Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); + + return Task.FromResult(new Soulseek.SearchResponse( + SoulseekClient.Username, + token, + freeUploadSlots: 1, + uploadSpeed: 0, + queueLength: 0, + fileList: results)); + } + + // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no + // response will be sent to the requestor. + return Task.FromResult<Soulseek.SearchResponse>(null); + } + + /// <summary> + /// Creates and returns a <see cref="UserInfo"/> object in response to a remote request. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="endpoint">The IP endpoint of the requesting user.</param> + /// <returns>A Task resolving the UserInfo instance.</returns> + private Task<UserInfo> UserInfoResponseResolver(string username, IPEndPoint endpoint) + { + var info = new UserInfo( + description: $"Soulseek.NET Web Example! also, your username is {username}, and IP endpoint is {endpoint}", + picture: Array.Empty<byte>(), + uploadSlots: 1, + queueLength: 0, + hasFreeUploadSlot: false); + + return Task.FromResult(info); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/SharedFileCache.cs b/src/slskd/Service/SharedFileCache.cs new file mode 100644 index 00000000..00496a47 --- /dev/null +++ b/src/slskd/Service/SharedFileCache.cs @@ -0,0 +1,165 @@ +// <copyright file="SharedFileCache.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Threading; + using Microsoft.Data.Sqlite; + using Soulseek; + + /// <summary> + /// Caches shared files. + /// </summary> + public class SharedFileCache : ISharedFileCache + { + /// <summary> + /// Initializes a new instance of the <see cref="SharedFileCache"/> class. + /// </summary> + /// <param name="directory"></param> + /// <param name="ttl"></param> + public SharedFileCache(string directory, long ttl) + { + Directory = directory; + TTL = ttl; + } + + public event EventHandler<(int Directories, int Files)> Refreshed; + + public string Directory { get; } + public DateTime? LastFill { get; set; } + public long TTL { get; } + + private Dictionary<string, Soulseek.File> Files { get; set; } + private SqliteConnection SQLite { get; set; } + private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); + + /// <summary> + /// Scans the configured <see cref="Directory"/> and fills the cache. + /// </summary> + public void Fill() + { + var sw = new Stopwatch(); + sw.Start(); + + Console.WriteLine($"[SHARED FILE CACHE]: Refreshing..."); + + SyncRoot.EnterWriteLock(); + + try + { + CreateTable(); + + var directories = System.IO.Directory.GetDirectories(Directory, "*", SearchOption.AllDirectories); + + Files = System.IO.Directory.GetFiles(Directory, "*", SearchOption.AllDirectories) + .Select(f => new Soulseek.File(1, f.Replace("/", @"\"), new FileInfo(f).Length, Path.GetExtension(f))) + .ToDictionary(f => f.Filename, f => f); + + // potentially optimize with multi-valued insert + // https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + foreach (var file in Files) + { + InsertFilename(file.Key); + } + + Refreshed?.Invoke(this, (directories.Length, Files.Count)); + } + finally + { + SyncRoot.ExitWriteLock(); + } + + sw.Stop(); + + Console.WriteLine($"[SHARED FILE CACHE]: Refreshed in {sw.ElapsedMilliseconds}ms. Found {Files.Count} files."); + LastFill = DateTime.UtcNow; + } + + /// <summary> + /// Searches the cache for files matching the specified <paramref name="query"/>. + /// </summary> + /// <param name="query"></param> + /// <returns></returns> + public IEnumerable<Soulseek.File> Search(SearchQuery query) + { + if (!LastFill.HasValue || LastFill.Value.AddMilliseconds(TTL) < DateTime.UtcNow) + { + Fill(); + } + + return QueryTable(query.Query); + } + + private void CreateTable() + { + SQLite = new SqliteConnection("Data Source=:memory:"); + SQLite.Open(); + + using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); + cmd.ExecuteNonQuery(); + } + + private void InsertFilename(string filename) + { + using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); + cmd.ExecuteNonQuery(); + } + + private IEnumerable<Soulseek.File> QueryTable(string text) + { + // sanitize the query string. there's probably more to it than this. + text = text + .Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " "); + + var query = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; + + SyncRoot.EnterReadLock(); + + try + { + using var cmd = new SqliteCommand(query, SQLite); + var results = new List<string>(); + var reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + + return results.Select(r => Files[r.Replace("''", "'")]); + } + catch (Exception ex) + { + // temporary error trap to refine substitution rules + Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); + return Enumerable.Empty<Soulseek.File>(); + } + finally + { + SyncRoot.ExitReadLock(); + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Service/Transfer/API/Controllers/TransfersController.cs new file mode 100644 index 00000000..f7274157 --- /dev/null +++ b/src/slskd/Service/Transfer/API/Controllers/TransfersController.cs @@ -0,0 +1,319 @@ +// <copyright file="TransfersController.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Transfer.API +{ + using System; + using System.ComponentModel.DataAnnotations; + using System.IO; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Transfers. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class TransfersController : ControllerBase + { + /// <summary> + /// Initializes a new instance of the <see cref="TransfersController"/> class. + /// </summary> + /// <param name="options"></param> + /// <param name="client"></param> + /// <param name="tracker"></param> + public TransfersController( + Microsoft.Extensions.Options.IOptionsSnapshot<Options> options, + ISoulseekClient client, + ITransferTracker tracker) + { + Client = client; + Tracker = tracker; + Options = options.Value; + } + + private Options Options { get; } + private ISoulseekClient Client { get; } + private ITransferTracker Tracker { get; } + + /// <summary> + /// Cancels the specified download. + /// </summary> + /// <param name="username">The username of the download source.</param> + /// <param name="id">The id of the download.</param> + /// <param name="remove">A value indicating whether the tracked download should be removed after cancellation.</param> + /// <returns></returns> + /// <response code="204">The download was cancelled successfully.</response> + /// <response code="404">The specified download was not found.</response> + [HttpDelete("downloads/{username}/{id}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public IActionResult CancelDownload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) + { + return CancelTransfer(TransferDirection.Download, username, id, remove); + } + + /// <summary> + /// Cancels the specified upload. + /// </summary> + /// <param name="username">The username of the upload destination.</param> + /// <param name="id">The id of the upload.</param> + /// <param name="remove">A value indicating whether the tracked upload should be removed after cancellation.</param> + /// <returns></returns> + /// <response code="204">The upload was cancelled successfully.</response> + /// <response code="404">The specified upload was not found.</response> + [HttpDelete("uploads/{username}/{id}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public IActionResult CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) + { + return CancelTransfer(TransferDirection.Upload, username, id, remove); + } + + /// <summary> + /// Enqueues the specified download. + /// </summary> + /// <param name="username">The username of the download source.</param> + /// <param name="request">The download request.</param> + /// <returns></returns> + /// <response code="201">The download was successfully enqueued.</response> + /// <response code="403">The download was rejected.</response> + /// <response code="500">An unexpected error was encountered.</response> + [HttpPost("downloads/{username}")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 500)] + public async Task<IActionResult> Enqueue([FromRoute, Required]string username, [FromBody]QueueDownloadRequest request) + { + try + { + var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); + var stream = GetLocalFileStream(request.Filename, Options.Directories.Incomplete); + + var cts = new CancellationTokenSource(); + + var downloadTask = Task.Run(async () => + { + await Client.DownloadAsync(username, request.Filename, stream, request.Size, 0, request.Token, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) => + { + Tracker.AddOrUpdate(e, cts); + + if (e.Transfer.State == TransferStates.Queued || e.Transfer.State == TransferStates.Initializing) + { + waitUntilEnqueue.TrySetResult(true); + } + }, progressUpdated: (e) => Tracker.AddOrUpdate(e, cts)), cts.Token); + + MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); + }); + + // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the + // downloadTask throws due to an error prior to successfully queueing. + var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask); + + if (task == downloadTask) + { + if (downloadTask.Exception is AggregateException) + { + var rejected = downloadTask.Exception?.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty<Exception>(); + if (rejected.Any()) + { + return StatusCode(403, rejected.First().Message); + } + } + + return StatusCode(500, downloadTask.Exception.Message); + } + + // if it didn't throw, just return ok. the download will continue waiting in the background. + return StatusCode(201); + } + catch (Exception ex) + { + return StatusCode(500, ex.Message); + } + } + + /// <summary> + /// Gets all downloads. + /// </summary> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("downloads")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetDownloads() + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Download) + .ToMap()); + } + + /// <summary> + /// Gets all downloads for the specified username. + /// </summary> + /// <param name="username"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("downloads/{username}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetDownloads([FromRoute, Required]string username) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Download) + .FromUser(username) + .ToMap()); + } + + /// <summary> + /// Gets the downlaod for the specified username matching the specified filename, and requests + /// the current place in the remote queue of the specified download. + /// </summary> + /// <param name="username">The username of the download source.</param> + /// <param name="id">The id of the download.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">The specified download was not found.</response> + [HttpGet("downloads/{username}/{id}")] + [Authorize] + [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(404)] + public async Task<IActionResult> GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id) + { + var record = Tracker.Transfers.WithDirection(TransferDirection.Download).FromUser(username).WithId(id); + + if (record == default) + { + return NotFound(); + } + + record.Transfer.PlaceInQueue = await Client.GetDownloadPlaceInQueueAsync(username, record.Transfer.Filename); + return Ok(record.Transfer); + } + + /// <summary> + /// Gets all uploads. + /// </summary> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("uploads")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads() + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .ToMap()); + } + + /// <summary> + /// Gets all uploads for the specified username. + /// </summary> + /// <param name="username"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("uploads/{username}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads([FromRoute, Required]string username) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .FromUser(username) + .ToMap()); + } + + /// <summary> + /// Gets the upload for the specified username matching the specified filename. + /// </summary> + /// <param name="username">The username of the upload destination.</param> + /// <param name="id">The id of the upload.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("uploads/{username}/{id}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads([FromRoute, Required]string username, [FromRoute, Required]string id) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .FromUser(username) + .WithId(id).Transfer); + } + + private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) + { + var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); + var path = Path.GetDirectoryName(localFilename); + + if (!System.IO.Directory.Exists(path)) + { + System.IO.Directory.CreateDirectory(path); + } + + return new FileStream(localFilename, FileMode.Create); + } + + private static void MoveFile(string filename, string sourceDirectory, string destinationDirectory) + { + var sourceFilename = filename.ToLocalFilename(sourceDirectory); + var destinationFilename = filename.ToLocalFilename(destinationDirectory); + + var destinationPath = Path.GetDirectoryName(destinationFilename); + + if (!System.IO.Directory.Exists(destinationPath)) + { + System.IO.Directory.CreateDirectory(destinationPath); + } + + System.IO.File.Move(sourceFilename, destinationFilename, overwrite: true); + + if (!System.IO.Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) + { + System.IO.Directory.Delete(Path.GetDirectoryName(sourceFilename)); + } + } + + private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false) + { + if (Tracker.TryGet(direction, username, id, out var transfer)) + { + transfer.CancellationTokenSource.Cancel(); + + if (remove) + { + Tracker.TryRemove(direction, username, id); + } + + return NoContent(); + } + + return NotFound(); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Transfer/API/DTO/QueueDownloadRequest.cs b/src/slskd/Service/Transfer/API/DTO/QueueDownloadRequest.cs new file mode 100644 index 00000000..2ec88007 --- /dev/null +++ b/src/slskd/Service/Transfer/API/DTO/QueueDownloadRequest.cs @@ -0,0 +1,37 @@ +// <copyright file="QueueDownloadRequest.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Transfer.API +{ + public class QueueDownloadRequest + { + /// <summary> + /// Gets or sets the filename to download. + /// </summary> + public string Filename { get; set; } + + /// <summary> + /// Gets or sets the size of the file. + /// </summary> + public long? Size { get; set; } + + /// <summary> + /// Gets or sets the optional transfer token. + /// </summary> + public int? Token { get; set; } + } +} diff --git a/src/slskd/Service/Transfer/API/DTO/Transfer.cs b/src/slskd/Service/Transfer/API/DTO/Transfer.cs new file mode 100644 index 00000000..e182db1b --- /dev/null +++ b/src/slskd/Service/Transfer/API/DTO/Transfer.cs @@ -0,0 +1,148 @@ +// <copyright file="Transfer.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Transfer.API +{ + using System; + using System.Net; + using Soulseek; + + /// <summary> + /// A single file transfer. + /// </summary> + public class Transfer + { + /// <summary> + /// Gets the current average transfer speed. + /// </summary> + public double AverageSpeed { get; set; } + + /// <summary> + /// Gets the number of remaining bytes to be transferred. + /// </summary> + public long BytesRemaining { get; set; } + + /// <summary> + /// Gets the total number of bytes transferred. + /// </summary> + public long BytesTransferred { get; set; } + + /// <summary> + /// Gets the transfer direction. + /// </summary> + public TransferDirection Direction { get; set; } + + /// <summary> + /// Gets the current duration of the transfer, if it has been started. + /// </summary> + public double? ElapsedTime { get; set; } + + /// <summary> + /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.Completed"/> state. + /// </summary> + public DateTime? EndTime { get; set; } + + /// <summary> + /// Gets the filename of the file to be transferred. + /// </summary> + public string Filename { get; set; } + + /// <summary> + /// Gets the transfer id. + /// </summary> + public string Id => Compute.Sha1Hash(Filename); + + /// <summary> + /// Gets the ip endpoint of the remote transfer connection, if one has been established. + /// </summary> + public IPEndPoint IPEndPoint { get; set; } + + /// <summary> + /// Gets the current progress in percent. + /// </summary> + public double PercentComplete { get; set; } + + /// <summary> + /// Gets the current place in queue, if it has been fetched. + /// </summary> + public int? PlaceInQueue { get; set; } + + /// <summary> + /// Gets the projected remaining duration of the transfer. + /// </summary> + public double? RemainingTime { get; set; } + + /// <summary> + /// Gets the remote unique token for the transfer. + /// </summary> + public int? RemoteToken { get; set; } + + /// <summary> + /// Gets the size of the file to be transferred, in bytes. + /// </summary> + public long Size { get; set; } + + /// <summary> + /// Gets the starting offset of the transfer, in bytes. + /// </summary> + public long StartOffset { get; set; } + + /// <summary> + /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.InProgress"/> state. + /// </summary> + public DateTime? StartTime { get; set; } + + /// <summary> + /// Gets the state of the transfer. + /// </summary> + public TransferStates State { get; set; } + + /// <summary> + /// Gets the unique token for the transfer. + /// </summary> + public int Token { get; set; } + + /// <summary> + /// Gets the username of the peer to or from which the file is to be transferred. + /// </summary> + public string Username { get; set; } + + public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer) + { + return new Transfer() + { + AverageSpeed = transfer.AverageSpeed, + BytesRemaining = transfer.BytesRemaining, + BytesTransferred = transfer.BytesTransferred, + Direction = transfer.Direction, + ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds, + EndTime = transfer.EndTime, + Filename = transfer.Filename, + IPEndPoint = transfer.IPEndPoint, + PercentComplete = transfer.PercentComplete, + RemainingTime = transfer.RemainingTime?.TotalMilliseconds, + RemoteToken = transfer.RemoteToken, + Size = transfer.Size, + StartOffset = transfer.StartOffset, + StartTime = transfer.StartTime, + State = transfer.State, + Token = transfer.Token, + Username = transfer.Username, + }; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Transfer/ITransferTracker.cs b/src/slskd/Service/Transfer/ITransferTracker.cs new file mode 100644 index 00000000..0dd41129 --- /dev/null +++ b/src/slskd/Service/Transfer/ITransferTracker.cs @@ -0,0 +1,57 @@ +// <copyright file="ITransferTracker.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Transfer +{ + using System.Collections.Concurrent; + using System.Threading; + using Soulseek; + + /// <summary> + /// Tracks transfers. + /// </summary> + public interface ITransferTracker + { + /// <summary> + /// Tracked transfers. + /// </summary> + ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; } + + /// <summary> + /// Adds or updates a tracked transfer. + /// </summary> + /// <param name="args"></param> + /// <param name="cancellationTokenSource"></param> + void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource); + + /// <summary> + /// Removes a tracked transfer. + /// </summary> + /// <remarks>Omitting an id will remove ALL transfers associated with the specified username.</remarks> + void TryRemove(TransferDirection direction, string username, string id = null); + + /// <summary> + /// Gets the specified transfer. + /// </summary> + /// <param name="direction"></param> + /// <param name="username"></param> + /// <param name="id"></param> + /// <param name="transfer"></param> + /// <returns></returns> + bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer); + } +}
\ No newline at end of file diff --git a/src/slskd/Service/Transfer/TransferTracker.cs b/src/slskd/Service/Transfer/TransferTracker.cs new file mode 100644 index 00000000..bf0a0bdb --- /dev/null +++ b/src/slskd/Service/Transfer/TransferTracker.cs @@ -0,0 +1,192 @@ +// <copyright file="TransferTracker.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Transfer +{ + using System.Collections.Concurrent; + using System.Linq; + using System.Threading; + using Soulseek; + + /// <summary> + /// Transfer extensions. + /// </summary> + public static class TransferTrackerExtensions + { + /// <summary> + /// Filters a Transfer collection by user. + /// </summary> + /// <param name="directedTransfers"></param> + /// <param name="username"></param> + /// <returns></returns> + public static ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> FromUser( + this ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> directedTransfers, + string username) + { + directedTransfers.TryGetValue(username, out var transfers); + return transfers ?? new ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>(); + } + + /// <summary> + /// Maps a Transfer collection to a serializable object. + /// </summary> + /// <param name="directedTransfers"></param> + /// <returns></returns> + public static object ToMap( + this ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> directedTransfers) + { + return directedTransfers.Select(u => new + { + Username = u.Key, + Directories = u.Value.Values + .GroupBy(f => f.Transfer.Filename.DirectoryName()) + .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }), + }); + } + + /// <summary> + /// Maps a Transfer collection to a serializable object. + /// </summary> + /// <param name="userTransfers"></param> + /// <returns></returns> + public static object ToMap( + this ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers) + { + return userTransfers.Values + .GroupBy(f => f.Transfer.Filename.DirectoryName()) + .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }); + } + + /// <summary> + /// Filters a Transfer collection by direction. + /// </summary> + /// <param name="allTransfers"></param> + /// <param name="direction"></param> + /// <returns></returns> + public static ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> WithDirection( + this ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> allTransfers, + TransferDirection direction) + { + allTransfers.TryGetValue(direction, out var transfers); + return transfers ?? new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>(); + } + + /// <summary> + /// Retrieves a Transfer from a Transfer collection by id. + /// </summary> + /// <param name="userTransfers"></param> + /// <param name="id"></param> + /// <returns></returns> + public static (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId( + this ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers, + string id) + { + userTransfers.TryGetValue(id, out var transfer); + return transfer; + } + } + + /// <summary> + /// Tracks transfers. + /// </summary> + public class TransferTracker : ITransferTracker + { + /// <summary> + /// Initializes a new instance of the <see cref="TransferTracker"/> class. + /// </summary> + public TransferTracker() + { + Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>()); + Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>()); + } + + /// <summary> + /// Gets tracked transfers. + /// </summary> + public ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; private set; } = + new ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer, CancellationTokenSource)>>>(); + + /// <summary> + /// Adds or updates a tracked transfer. + /// </summary> + /// <param name="args"></param> + /// <param name="cancellationTokenSource"></param> + public void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) + { + Transfers.TryGetValue(args.Transfer.Direction, out var direction); + + direction.AddOrUpdate(args.Transfer.Username, GetNewDictionaryForUser(args, cancellationTokenSource), (user, dict) => + { + var transfer = API.Transfer.FromSoulseekTransfer(args.Transfer); + dict.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, cancellationTokenSource)); + return dict; + }); + } + + /// <summary> + /// Gets the specified transfer. + /// </summary> + /// <param name="direction"></param> + /// <param name="username"></param> + /// <param name="id"></param> + /// <param name="transfer"></param> + /// <returns></returns> + public bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer) + { + transfer = default; + + if (Transfers.TryGetValue(direction, out var transfers) && transfers.TryGetValue(username, out var user) && user.TryGetValue(id, out transfer)) + { + return true; + } + + return false; + } + + /// <summary> + /// Removes a tracked transfer. + /// </summary> + /// <remarks>Omitting an id will remove ALL transfers associated with the specified username.</remarks> + public void TryRemove(TransferDirection direction, string username, string id = null) + { + Transfers.TryGetValue(direction, out var directionDict); + + if (string.IsNullOrEmpty(id)) + { + directionDict.TryRemove(username, out _); + } + else + { + directionDict.TryGetValue(username, out var userDict); + userDict.TryRemove(id, out _); + + if (userDict.IsEmpty) + { + directionDict.TryRemove(username, out _); + } + } + } + + private ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) + { + var r = new ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>(); + var transfer = API.Transfer.FromSoulseekTransfer(args.Transfer); + r.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, record.CancellationTokenSource)); + return r; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Service/UserEndPointCache.cs b/src/slskd/Service/UserEndPointCache.cs new file mode 100644 index 00000000..29164cc4 --- /dev/null +++ b/src/slskd/Service/UserEndPointCache.cs @@ -0,0 +1,61 @@ +// <copyright file="UserEndPointCache.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using System.Net; + using Microsoft.Extensions.Caching.Memory; + using Soulseek; + + /// <summary> + /// Caches user EndPoints. + /// </summary> + public class UserEndPointCache : IUserEndPointCache + { + /// <summary> + /// Initializes a new instance of the <see cref="UserEndPointCache"/> class. + /// </summary> + public UserEndPointCache() + { + Cache = new MemoryCache(new MemoryCacheOptions()); + } + + private IMemoryCache Cache { get; } + + /// <summary> + /// Caches or updates an entry. + /// </summary> + /// <param name="username">The username for which to cache the endpoint.</param> + /// <param name="endPoint">The endpoint to cache.</param> + public void AddOrUpdate(string username, IPEndPoint endPoint) + { + Cache.Set(username, endPoint, TimeSpan.FromSeconds(60)); + } + + /// <summary> + /// Gets the cached endpoint for the specified <paramref name="username"/>, if it exists. + /// </summary> + /// <param name="username">The username for which to retrieve the endpoint.</param> + /// <param name="endPoint">The cached endpoint, if it exists.</param> + /// <returns>A value indicating whether the endpoint was found in the cache.</returns> + public bool TryGet(string username, out IPEndPoint endPoint) + { + return Cache.TryGetValue(username, out endPoint); + } + } +}
\ No newline at end of file |
