aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2020-12-30 21:16:50 -0600
committerJP Dillingham <jpdillingham@gmail.com>2020-12-30 21:16:50 -0600
commit8f1068ac3135bcccf09374bc787ef22049b43461 (patch)
tree5d80a254f5ee7b7c6b3956f6a7307591bc5a93e2 /src/slskd
parentec4a85e4e8b64a0ae91c494e3c8ef520f0a8b8c3 (diff)
downloadslskd-8f1068ac3135bcccf09374bc787ef22049b43461.tar.gz
copy files from example
Diffstat (limited to 'src/slskd')
-rw-r--r--src/slskd/.gitignore350
-rw-r--r--src/slskd/Controllers/ConversationsController.cs198
-rw-r--r--src/slskd/Controllers/PublicChatController.cs50
-rw-r--r--src/slskd/Controllers/RoomsController.cs287
-rw-r--r--src/slskd/Controllers/SearchesController.cs102
-rw-r--r--src/slskd/Controllers/ServerController.cs74
-rw-r--r--src/slskd/Controllers/SessionController.cs120
-rw-r--r--src/slskd/Controllers/TransfersController.cs284
-rw-r--r--src/slskd/Controllers/UserController.cs151
-rw-r--r--src/slskd/DTO/ConnectRequest.cs10
-rw-r--r--src/slskd/DTO/LoginRequest.cs8
-rw-r--r--src/slskd/DTO/PrivateMessageResponse.cs57
-rw-r--r--src/slskd/DTO/QueueDownloadRequest.cs20
-rw-r--r--src/slskd/DTO/RoomInfoResponse.cs43
-rw-r--r--src/slskd/DTO/RoomMessageResponse.cs45
-rw-r--r--src/slskd/DTO/RoomResponse.cs57
-rw-r--r--src/slskd/DTO/SearchRequest.cs99
-rw-r--r--src/slskd/DTO/TokenResponse.cs50
-rw-r--r--src/slskd/DTO/Transfer.cs131
-rw-r--r--src/slskd/DTO/UserAddress.cs18
-rw-r--r--src/slskd/DTO/UserDataResponse.cs68
-rw-r--r--src/slskd/Entities/PrivateMessage.cs54
-rw-r--r--src/slskd/Entities/RoomMessage.cs42
-rw-r--r--src/slskd/Extensions.cs82
-rw-r--r--src/slskd/ISharedFileCache.cs17
-rw-r--r--src/slskd/Program.cs31
-rw-r--r--src/slskd/Properties/launchSettings.json19
-rw-r--r--src/slskd/Room.cs59
-rw-r--r--src/slskd/Security/PBKDF2.cs28
-rw-r--r--src/slskd/Security/PassthroughAuthentication.cs40
-rw-r--r--src/slskd/SharedFileCache.cs141
-rw-r--r--src/slskd/Startup.cs540
-rw-r--r--src/slskd/Trackers/BrowseTracker.cs40
-rw-r--r--src/slskd/Trackers/ConversationTracker.cs46
-rw-r--r--src/slskd/Trackers/IBrowseTracker.cs37
-rw-r--r--src/slskd/Trackers/IConversationTracker.cs39
-rw-r--r--src/slskd/Trackers/IRoomTracker.cs59
-rw-r--r--src/slskd/Trackers/ISearchTracker.cs35
-rw-r--r--src/slskd/Trackers/ITransferTracker.cs40
-rw-r--r--src/slskd/Trackers/RoomTracker.cs96
-rw-r--r--src/slskd/Trackers/SearchTracker.cs45
-rw-r--r--src/slskd/Trackers/TransferTracker.cs180
-rw-r--r--src/slskd/slskd.csproj42
-rw-r--r--src/slskd/wwwroot/.gitkeep0
44 files changed, 3934 insertions, 0 deletions
diff --git a/src/slskd/.gitignore b/src/slskd/.gitignore
new file mode 100644
index 00000000..dfcfd56f
--- /dev/null
+++ b/src/slskd/.gitignore
@@ -0,0 +1,350 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
diff --git a/src/slskd/Controllers/ConversationsController.cs b/src/slskd/Controllers/ConversationsController.cs
new file mode 100644
index 00000000..82a5ac6e
--- /dev/null
+++ b/src/slskd/Controllers/ConversationsController.cs
@@ -0,0 +1,198 @@
+namespace slskd.Controllers
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
+ using Soulseek;
+ using slskd.DTO;
+ using slskd.Entities;
+ using slskd.Trackers;
+
+ /// <summary>
+ /// Conversations
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("1")]
+ [ApiController]
+ [Produces("application/json")]
+ [Consumes("application/json")]
+ public class ConversationsController : ControllerBase
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConversationsController"/> class.
+ /// </summary>
+ /// <param name="client"></param>
+ /// <param name="tracker"></param>
+ public ConversationsController(ISoulseekClient client, IConversationTracker tracker)
+ {
+ Client = client;
+ Tracker = tracker;
+ }
+
+ private ISoulseekClient Client { get; }
+ private IConversationTracker Tracker { get; }
+
+ /// <summary>
+ /// Acknowledges the given message id for the given username.
+ /// </summary>
+ /// <param name="username"></param>
+ /// <param name="id"></param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">
+ /// A conversation with the specified username, or a message matching the specified id could not be found.
+ /// </response>
+ [HttpPut("{username}/{id}")]
+ [Authorize]
+ [ProducesResponseType(200)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> Acknowledge([FromRoute]string username, [FromRoute]int id)
+ {
+ Tracker.Conversations.TryGetValue(username, out var conversation);
+
+ if (conversation == default || !conversation.Any(p => p.Id == id))
+ {
+ return NotFound();
+ }
+
+ await Client.AcknowledgePrivateMessageAsync(id);
+ return StatusCode(200);
+ }
+
+ /// <summary>
+ /// Acknowledges all messages for the given username.
+ /// </summary>
+ /// <param name="username"></param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">A conversation with the specified username could not be found.</response>
+ [HttpPut("{username}")]
+ [Authorize]
+ [ProducesResponseType(200)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> AcknowledgeAll([FromRoute]string username)
+ {
+ Tracker.Conversations.TryGetValue(username, out var conversation);
+
+ if (conversation == default)
+ {
+ return NotFound();
+ }
+
+ var tasks = new List<Task>();
+
+ foreach (var message in conversation.Where(p => !p.Acknowledged))
+ {
+ tasks.Add(Task.Run(async () =>
+ {
+ await Client.AcknowledgePrivateMessageAsync(message.Id);
+ message.Acknowledged = true;
+ }));
+ }
+
+ await Task.WhenAll(tasks);
+ return StatusCode(200);
+ }
+
+ /// <summary>
+ /// Deletes the conversation associated with the given username.
+ /// </summary>
+ /// <returns></returns>
+ /// <response code="204">The request completed successfully.</response>
+ /// <response code="404">A conversation with the specified username could not be found.</response>
+ [HttpDelete("{username}")]
+ [Authorize]
+ [ProducesResponseType(404)]
+ [ProducesResponseType(204)]
+ public IActionResult Delete([FromRoute]string username)
+ {
+ var deleted = Tracker.Conversations.TryRemove(username, out _);
+
+ if (deleted)
+ {
+ return StatusCode(204);
+ }
+
+ return StatusCode(404);
+ }
+
+ /// <summary>
+ /// Gets all tracked conversations.
+ /// </summary>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ [HttpGet("")]
+ [Authorize]
+ [ProducesResponseType(typeof(Dictionary<string, List<PrivateMessageResponse>>), 200)]
+ public IActionResult GetAll()
+ {
+ var response = Tracker.Conversations.ToDictionary(
+ entry => entry.Key,
+ entry => entry.Value
+ .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username))
+ .OrderBy(m => m.Timestamp));
+
+ return Ok(response);
+ }
+
+ /// <summary>
+ /// Gets the conversation associated with the specified username.
+ /// </summary>
+ /// <param name="username">The username associated with the desired conversation.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">A matching search was not found.</response>
+ [HttpGet("{username}")]
+ [Authorize]
+ [ProducesResponseType(typeof(List<PrivateMessageResponse>), 200)]
+ [ProducesResponseType(404)]
+ public IActionResult GetByUsername([FromRoute]string username)
+ {
+ if (Tracker.TryGet(username, out var conversation))
+ {
+ var response = conversation
+ .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username))
+ .OrderBy(m => m.Timestamp);
+
+ return Ok(response);
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Sends a private message to the specified username.
+ /// </summary>
+ /// <param name="username"></param>
+ /// <param name="message"></param>
+ /// <returns></returns>
+ /// <response code="201">The request completed successfully.</response>
+ /// <response code="400">The specified message is null or empty.</response>
+ [HttpPost("{username}")]
+ [Authorize]
+ [ProducesResponseType(201)]
+ [ProducesResponseType(400)]
+ public async Task<IActionResult> Send([FromRoute]string username, [FromBody]string message)
+ {
+ if (string.IsNullOrEmpty(message))
+ {
+ return BadRequest();
+ }
+
+ await Client.SendPrivateMessageAsync(username, message);
+
+ Tracker.AddOrUpdate(username, new PrivateMessage()
+ {
+ Username = Client.Username,
+ Timestamp = DateTime.UtcNow,
+ Message = message,
+ Acknowledged = true
+ });
+
+ return StatusCode(201);
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Controllers/PublicChatController.cs b/src/slskd/Controllers/PublicChatController.cs
new file mode 100644
index 00000000..f3f2c297
--- /dev/null
+++ b/src/slskd/Controllers/PublicChatController.cs
@@ -0,0 +1,50 @@
+namespace slskd.Controllers
+{
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Http;
+ using Microsoft.AspNetCore.Mvc;
+ using Soulseek;
+ using System.Threading.Tasks;
+
+ /// <summary>
+ /// Server
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("1")]
+ [ApiController]
+ [Produces("application/json")]
+ [Consumes("application/json")]
+ public class PublicChatController : ControllerBase
+ {
+ private ISoulseekClient Client { get; }
+
+ public PublicChatController(ISoulseekClient client)
+ {
+ Client = client;
+ }
+
+ /// <summary>
+ /// Starts public chat.
+ /// </summary>
+ /// <returns></returns>
+ [HttpPost]
+ [Authorize]
+ public async Task<IActionResult> Start()
+ {
+ await Client.StartPublicChatAsync();
+ return StatusCode(StatusCodes.Status201Created);
+ }
+
+ /// <summary>
+ /// Stops public chat.
+ /// </summary>
+ /// <returns></returns>
+ [HttpDelete]
+ [Authorize]
+ public async Task<IActionResult> Stop()
+ {
+ await Client.StopPublicChatAsync();
+ return StatusCode(StatusCodes.Status204NoContent);
+ }
+ }
+}
diff --git a/src/slskd/Controllers/RoomsController.cs b/src/slskd/Controllers/RoomsController.cs
new file mode 100644
index 00000000..bd621444
--- /dev/null
+++ b/src/slskd/Controllers/RoomsController.cs
@@ -0,0 +1,287 @@
+namespace slskd.Controllers
+{
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Http;
+ using Microsoft.AspNetCore.Mvc;
+ using Soulseek;
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Threading.Tasks;
+ using slskd.DTO;
+ using slskd.Entities;
+ using slskd.Trackers;
+
+ /// <summary>
+ /// Rooms.
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("1")]
+ [ApiController]
+ [Produces("application/json")]
+ [Consumes("application/json")]
+ public class RoomsController : ControllerBase
+ {
+ public RoomsController(ISoulseekClient client, IRoomTracker tracker)
+ {
+ Client = client;
+ Tracker = tracker;
+ }
+
+ private ISoulseekClient Client { get; }
+ private IRoomTracker Tracker { get; }
+
+ /// <summary>
+ /// Gets all rooms.
+ /// </summary>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ [HttpGet("joined")]
+ [Authorize]
+ [ProducesResponseType(typeof(Dictionary<string, Dictionary<string, Room>>), 200)]
+ public IActionResult GetAll()
+ {
+ return Ok(Tracker.Rooms.Keys);
+ }
+
+ /// <summary>
+ /// Gets the specified room.
+ /// </summary>
+ /// <param name="roomName"></param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">The specified roomName could not be found.</response>
+ [HttpGet("joined/{roomName}")]
+ [Authorize]
+ [ProducesResponseType(typeof(Room), 200)]
+ [ProducesResponseType(404)]
+ public IActionResult GetByRoomName([FromRoute]string roomName)
+ {
+ if (Tracker.TryGet(roomName, out var room))
+ {
+ return Ok(MapRoomToRoomResponse(room));
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Sends a message to the specified room.
+ /// </summary>
+ /// <param name="roomName"></param>
+ /// <param name="message"></param>
+ /// <returns></returns>
+ /// <response code="201">The request completed successfully.</response>
+ /// <response code="404">The specified roomName could not be found.</response>
+ [HttpPost("joined/{roomName}/messages")]
+ [Authorize]
+ [ProducesResponseType(201)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> SendMessage([FromRoute]string roomName, [FromBody]string message)
+ {
+ if (Tracker.TryGet(roomName, out var _))
+ {
+ await Client.SendRoomMessageAsync(roomName, message);
+ return StatusCode(StatusCodes.Status201Created);
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Sets a ticker for the specified room.
+ /// </summary>
+ /// <param name="roomName"></param>
+ /// <param name="message"></param>
+ /// <returns></returns>
+ /// <response code="201">The request completed successfully.</response>
+ /// <response code="404">The specified roomName could not be found.</response>
+ [HttpPost("joined/{roomName}/ticker")]
+ [Authorize]
+ [ProducesResponseType(201)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> SetTicker([FromRoute] string roomName, [FromBody] string message)
+ {
+ if (Tracker.TryGet(roomName, out var _))
+ {
+ await Client.SetRoomTickerAsync(roomName, message);
+ return StatusCode(StatusCodes.Status201Created);
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Adds a member to a private room.
+ /// </summary>
+ /// <param name="roomName"></param>
+ /// <param name="username"></param>
+ /// <returns></returns>
+ /// <response code="201">The request completed successfully.</response>
+ /// <response code="404">The specified roomName could not be found.</response>
+ [HttpPost("joined/{roomName}/members")]
+ [Authorize]
+ [ProducesResponseType(201)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> AddRoomMember([FromRoute]string roomName, [FromBody]string username)
+ {
+ if (Tracker.TryGet(roomName, out var _))
+ {
+ await Client.AddPrivateRoomMemberAsync(roomName, username);
+ return StatusCode(StatusCodes.Status201Created);
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Gets the current list of users for the specified room.
+ /// </summary>
+ /// <param name="roomName"></param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">The specified roomName could not be found.</response>
+ [HttpGet("joined/{roomName}/users")]
+ [Authorize]
+ [ProducesResponseType(typeof(IList<UserData>), 200)]
+ [ProducesResponseType(404)]
+ public IActionResult GetUsersByRoomName([FromRoute]string roomName)
+ {
+ if (Tracker.TryGet(roomName, out var room))
+ {
+ var response = room.Users
+ .Select(user => UserDataResponse.FromUserData(user, self: user.Username == Client.Username));
+
+ return Ok(response);
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Gets the current list of messages for the specified room.
+ /// </summary>
+ /// <param name="roomName"></param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">The specified roomName could not be found.</response>
+ [HttpGet("joined/{roomName}/messages")]
+ [Authorize]
+ [ProducesResponseType(typeof(IList<RoomMessage>), 200)]
+ [ProducesResponseType(404)]
+ public IActionResult GetMessagesByRoomName([FromRoute]string roomName)
+ {
+ if (Tracker.TryGet(roomName, out var room))
+ {
+ var response = room.Messages
+ .Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == Client.Username));
+
+ return Ok(response);
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Gets a list of rooms from the server.
+ /// </summary>
+ /// <returns></returns>
+ [HttpGet("available")]
+ [Authorize]
+ [ProducesResponseType(typeof(List<RoomInfo>), 200)]
+ public async Task<IActionResult> GetRooms()
+ {
+ var list = await Client.GetRoomListAsync();
+
+ var response = new List<RoomInfoResponse>();
+
+ response.AddRange(list.Public.Select(r => RoomInfoResponse.FromRoomInfo(r)));
+ response.AddRange(list.Private.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true)));
+ response.AddRange(list.Owned.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true, isOwned: true)));
+
+ foreach (var room in response)
+ {
+ room.IsModerated = list.ModeratedRoomNames.Contains(room.Name);
+ }
+
+ return Ok(response);
+ }
+
+ /// <summary>
+ /// Joins a room.
+ /// </summary>
+ /// <param name="roomName"></param>
+ /// <returns></returns>
+ /// <response code="201">The request completed successfully.</response>
+ /// <response code="304">The room has already been joined.</response>
+ [HttpPost("joined/{roomName}")]
+ [Authorize]
+ [ProducesResponseType(typeof(Room), 201)]
+ [ProducesResponseType(304)]
+ public async Task<IActionResult> JoinRoom([FromRoute]string roomName)
+ {
+ if (Tracker.Rooms.ContainsKey(roomName))
+ {
+ return StatusCode(StatusCodes.Status304NotModified);
+ }
+
+ try
+ {
+ var roomData = await Client.JoinRoomAsync(roomName);
+ var room = Room.FromRoomData(roomData);
+ Tracker.TryAdd(roomName, room);
+
+ return StatusCode(StatusCodes.Status201Created, MapRoomToRoomResponse(room));
+ }
+ catch (Exception ex)
+ {
+ if (ex.InnerException is RoomJoinForbiddenException)
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, $"The server rejected your request to join {roomName}");
+ }
+
+ throw;
+ }
+ }
+
+ /// <summary>
+ /// Leaves a room.
+ /// </summary>
+ /// <param name="roomName"></param>
+ /// <returns></returns>
+ /// <response code="204">The request completed successfully.</response>
+ /// <response code="404">The room has not been joined.</response>
+ [HttpDelete("joined/{roomName}")]
+ [Authorize]
+ [ProducesResponseType(204)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> LeaveRoom([FromRoute]string roomName)
+ {
+ if (!Tracker.Rooms.ContainsKey(roomName))
+ {
+ return StatusCode(StatusCodes.Status404NotFound);
+ }
+
+ await Client.LeaveRoomAsync(roomName);
+ Tracker.TryRemove(roomName);
+
+ return StatusCode(StatusCodes.Status204NoContent);
+ }
+
+ private RoomResponse MapRoomToRoomResponse(Room room)
+ {
+ bool IsSelf(string username)
+ {
+ return username == Client.Username;
+ }
+
+ var response = RoomResponse.FromRoom(room);
+ response.Users = room.Users
+ .Select(user => UserDataResponse.FromUserData(user, self: IsSelf(user.Username)));
+ response.Messages = room.Messages
+ .Select(message => RoomMessageResponse.FromRoomMessage(message, self: IsSelf(message.Username)));
+
+ return response;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Controllers/SearchesController.cs b/src/slskd/Controllers/SearchesController.cs
new file mode 100644
index 00000000..986b75e4
--- /dev/null
+++ b/src/slskd/Controllers/SearchesController.cs
@@ -0,0 +1,102 @@
+namespace slskd.Controllers
+{
+ using System;
+ using System.Collections.Concurrent;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
+ using Soulseek;
+ using slskd.DTO;
+ using slskd.Trackers;
+
+ /// <summary>
+ /// Search
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("1")]
+ [ApiController]
+ [Produces("application/json")]
+ [Consumes("application/json")]
+ public class SearchesController : ControllerBase
+ {
+ private ISoulseekClient Client { get; }
+ private ISearchTracker Tracker { get; }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SearchesController"/> class.
+ /// </summary>
+ /// <param name="client"></param>
+ /// <param name="tracker"></param>
+ public SearchesController(ISoulseekClient client, ISearchTracker tracker)
+ {
+ Client = client;
+ Tracker = tracker;
+ }
+
+ /// <summary>
+ /// Performs a search for the specified <paramref name="request"/>.
+ /// </summary>
+ /// <param name="request">The search request.</param>
+ /// <returns></returns>
+ /// <response code="200">The search completed successfully.</response>
+ /// <response code="400">The specified <paramref name="request"/> was malformed.</response>
+ /// <response code="500">The search terminated abnormally.</response>
+ [HttpPost("")]
+ [Authorize]
+ [ProducesResponseType(typeof(IEnumerable<SearchResponse>), 200)]
+ [ProducesResponseType(400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public async Task<IActionResult> Post([FromBody]SearchRequest request)
+ {
+ var id = request.Id ?? Guid.NewGuid();
+
+ var options = request.ToSearchOptions(
+ responseReceived: (e) => Tracker.AddOrUpdate(id, e),
+ stateChanged: (e) => Tracker.AddOrUpdate(id, e));
+
+ var results = new ConcurrentBag<SearchResponse>();
+
+ var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1));
+
+ try
+ {
+ await Client.SearchAsync(SearchQuery.FromText(searchText), (r) => results.Add(r), SearchScope.Network, request.Token, options);
+ return Ok(results);
+ }
+ catch (Exception ex)
+ {
+ return StatusCode(500, $"Search terminated abnormally: {ex.Message}");
+ }
+ finally
+ {
+ results = null;
+ Tracker.TryRemove(id);
+ }
+ }
+
+ /// <summary>
+ /// Gets the state of the search corresponding to the specified <paramref name="id"/>.
+ /// </summary>
+ /// <param name="id">The unique id of the search.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">A matching search was not found.</response>
+ [HttpGet("{id}")]
+ [Authorize]
+ [ProducesResponseType(typeof(Search), 200)]
+ [ProducesResponseType(404)]
+ public IActionResult GetById([FromRoute]Guid id)
+ {
+ Tracker.Searches.TryGetValue(id, out var search);
+
+ if (search == default)
+ {
+ return NotFound();
+ }
+
+ return Ok(search);
+ }
+ }
+}
diff --git a/src/slskd/Controllers/ServerController.cs b/src/slskd/Controllers/ServerController.cs
new file mode 100644
index 00000000..c2393dcb
--- /dev/null
+++ b/src/slskd/Controllers/ServerController.cs
@@ -0,0 +1,74 @@
+namespace slskd.Controllers
+{
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
+ using Soulseek;
+ using System.Threading.Tasks;
+ using slskd.DTO;
+
+ /// <summary>
+ /// Server
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("1")]
+ [ApiController]
+ [Produces("application/json")]
+ [Consumes("application/json")]
+ public class ServerController : ControllerBase
+ {
+ private ISoulseekClient Client { get; }
+
+ public ServerController(ISoulseekClient client)
+ {
+ Client = client;
+ }
+
+ /// <summary>
+ /// Disconnects the client.
+ /// </summary>
+ /// <param name="message"></param>
+ /// <returns></returns>
+ [HttpDelete]
+ [Authorize]
+ public IActionResult Disconnect([FromBody]string message)
+ {
+ Client.Disconnect(message);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Connects the client.
+ /// </summary>
+ /// <param name="req"></param>
+ /// <returns></returns>
+ [HttpPost]
+ [Authorize]
+ public async Task<IActionResult> Connect([FromBody]ConnectRequest req)
+ {
+ var addr = !string.IsNullOrEmpty(req.Address);
+ var port = req.Port.HasValue;
+ var un = !string.IsNullOrEmpty(req.Username);
+ var pw = !string.IsNullOrEmpty(req.Password);
+
+ if (addr && port && un && pw)
+ {
+ await Client.ConnectAsync(req.Address, req.Port.Value, req.Username, req.Password);
+ return Ok();
+ }
+
+ if (addr && port && !un && !pw)
+ {
+ await Client.ConnectAsync(req.Address, req.Port.Value);
+ return Ok();
+ }
+
+ if (!addr && !port && un && pw)
+ {
+ await Client.ConnectAsync(req.Username, req.Password);
+ return Ok();
+ }
+
+ return BadRequest("Provide one of the following: address and port, username and password, or address, port, username and password");
+ }
+ }
+}
diff --git a/src/slskd/Controllers/SessionController.cs b/src/slskd/Controllers/SessionController.cs
new file mode 100644
index 00000000..ab657b99
--- /dev/null
+++ b/src/slskd/Controllers/SessionController.cs
@@ -0,0 +1,120 @@
+namespace slskd.Controllers
+{
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
+ using Microsoft.IdentityModel.Tokens;
+ using System;
+ using System.Collections.Generic;
+ using System.IdentityModel.Tokens.Jwt;
+ using System.Security.Claims;
+ using slskd.DTO;
+
+ /// <summary>
+ /// Session
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("1")]
+ [ApiController]
+ [Produces("application/json")]
+ [Consumes("application/json")]
+ public class SessionController : ControllerBase
+ {
+ public SessionController()
+ {
+ }
+
+ /// <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(Startup.EnableSecurity);
+ }
+
+ /// <summary>
+ /// Checks whether the provided authentication is valid.
+ /// </summary>
+ /// <remarks>
+ /// This is a no-op provided so that the application can test for an expired token on load.
+ /// </remarks>
+ /// <returns></returns>
+ /// <response code="200">The authentication is valid.</response>
+ /// <response code="403">The authentication is is invalid.</response>
+ [HttpGet]
+ [Route("")]
+ [Authorize]
+ [ProducesResponseType(200)]
+ [ProducesResponseType(401)]
+ public IActionResult Check()
+ {
+ return Ok();
+ }
+
+ /// <summary>
+ /// Logs in.
+ /// </summary>
+ /// <param name="login"></param>
+ /// <returns></returns>
+ /// <response code="200">Login was successful.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="401">Login failed.</response>
+ [HttpPost]
+ [Route("")]
+ [AllowAnonymous]
+ [ProducesResponseType(typeof(TokenResponse), 200)]
+ [ProducesResponseType(400)]
+ [ProducesResponseType(401)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult Login([FromBody]LoginRequest login)
+ {
+ if (login == default)
+ {
+ return BadRequest();
+ }
+
+ if (string.IsNullOrWhiteSpace(login.Username) || string.IsNullOrWhiteSpace(login.Password))
+ {
+ return BadRequest("Username and/or Password missing or invalid");
+ }
+
+ if (login.Username == Startup.Username && login.Password == Startup.Password)
+ {
+ return Ok(new TokenResponse(GetJwtSecurityToken()));
+ }
+
+ return Unauthorized();
+ }
+
+ private JwtSecurityToken GetJwtSecurityToken()
+ {
+ var issuedUtc = DateTime.UtcNow;
+ var expiresUtc = DateTime.UtcNow.AddMilliseconds(Startup.SecurityTokenTTL);
+
+ var claims = new List<Claim>()
+ {
+ new Claim(ClaimTypes.Name, Startup.Username),
+ new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
+ new Claim(ClaimTypes.Role, "User"),
+ new Claim("name", Startup.Username),
+ new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString())
+ };
+
+ var credentials = new SigningCredentials(Startup.JwtSigningKey, SecurityAlgorithms.HmacSha256);
+
+ var token = new JwtSecurityToken(
+ issuer: "slsk-web-example",
+ claims: claims,
+ notBefore: issuedUtc,
+ expires: expiresUtc,
+ signingCredentials: credentials);
+
+ return token;
+ }
+ }
+}
diff --git a/src/slskd/Controllers/TransfersController.cs b/src/slskd/Controllers/TransfersController.cs
new file mode 100644
index 00000000..2b6fa768
--- /dev/null
+++ b/src/slskd/Controllers/TransfersController.cs
@@ -0,0 +1,284 @@
+namespace slskd.Controllers
+{
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
+ using Microsoft.Extensions.Configuration;
+ using Soulseek;
+ using System;
+ using System.ComponentModel.DataAnnotations;
+ using System.IO;
+ using System.Linq;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using slskd.DTO;
+ using slskd.Trackers;
+
+ /// <summary>
+ /// Transfers
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("1")]
+ [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="configuration"></param>
+ /// <param name="client"></param>
+ /// <param name="tracker"></param>
+ public TransfersController(IConfiguration configuration, ISoulseekClient client, ITransferTracker tracker)
+ {
+ OutputDirectory = configuration.GetValue<string>("OUTPUT_DIR");
+ Client = client;
+ Tracker = tracker;
+ }
+
+ private ISoulseekClient Client { get; }
+ private string OutputDirectory { get; }
+ private ITransferTracker Tracker { get; }
+
+ /// <summary>
+ /// Cancels the specified download.
+ /// </summary>
+ /// <param name="username">The username of the download source.</param>
+ /// <param name="id">The id of the download.</param>
+ /// <param name="remove">A value indicating whether the tracked download should be removed after cancellation.</param>
+ /// <returns></returns>
+ /// <response code="204">The download was cancelled successfully.</response>
+ /// <response code="404">The specified download was not found.</response>
+ [HttpDelete("downloads/{username}/{id}")]
+ [Authorize]
+ [ProducesResponseType(204)]
+ [ProducesResponseType(404)]
+ public IActionResult CancelDownload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false)
+ {
+ return CancelTransfer(TransferDirection.Download, username, id, remove);
+ }
+
+ /// <summary>
+ /// Cancels the specified upload.
+ /// </summary>
+ /// <param name="username">The username of the upload destination.</param>
+ /// <param name="id">The id of the upload.</param>
+ /// <param name="remove">A value indicating whether the tracked upload should be removed after cancellation.</param>
+ /// <returns></returns>
+ /// <response code="204">The upload was cancelled successfully.</response>
+ /// <response code="404">The specified upload was not found.</response>
+ [HttpDelete("uploads/{username}/{id}")]
+ [Authorize]
+ [ProducesResponseType(204)]
+ [ProducesResponseType(404)]
+ public IActionResult CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false)
+ {
+ return CancelTransfer(TransferDirection.Upload, username, id, remove);
+ }
+
+ /// <summary>
+ /// Enqueues the specified download.
+ /// </summary>
+ /// <param name="username">The username of the download source.</param>
+ /// <param name="request">The download request.</param>
+ /// <returns></returns>
+ /// <response code="201">The download was successfully enqueued.</response>
+ /// <response code="403">The download was rejected.</response>
+ /// <response code="500">An unexpected error was encountered.</response>
+ [HttpPost("downloads/{username}")]
+ [Authorize]
+ [ProducesResponseType(201)]
+ [ProducesResponseType(typeof(string), 403)]
+ [ProducesResponseType(typeof(string), 500)]
+ public async Task<IActionResult> Enqueue([FromRoute, Required]string username, [FromBody]QueueDownloadRequest request)
+ {
+ try
+ {
+ var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
+ var stream = GetLocalFileStream(request.Filename, OutputDirectory);
+
+ var cts = new CancellationTokenSource();
+
+ var downloadTask = Client.DownloadAsync(username, request.Filename, stream, request.Size, 0, request.Token, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) =>
+ {
+ Tracker.AddOrUpdate(e, cts);
+
+ if (e.Transfer.State == TransferStates.Queued || e.Transfer.State == TransferStates.Initializing)
+ {
+ waitUntilEnqueue.TrySetResult(true);
+ }
+ }, progressUpdated: (e) => Tracker.AddOrUpdate(e, cts)), cts.Token);
+
+ // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the
+ // downloadTask throws due to an error prior to successfully queueing.
+ var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask);
+
+ if (task == downloadTask && downloadTask.Exception is AggregateException)
+ {
+ var rejected = downloadTask.Exception?.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty<Exception>();
+
+ if (rejected.Any())
+ {
+ return StatusCode(403, rejected.First().Message);
+ }
+
+ return StatusCode(500, downloadTask.Exception.Message);
+ }
+
+ // if it didn't throw, just return ok. the download will continue waiting in the background.
+ return StatusCode(201);
+ }
+ catch (Exception ex)
+ {
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets all downloads.
+ /// </summary>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ [HttpGet("downloads")]
+ [Authorize]
+ [ProducesResponseType(200)]
+ public IActionResult GetDownloads()
+ {
+ return Ok(Tracker.Transfers
+ .WithDirection(TransferDirection.Download)
+ .ToMap());
+ }
+
+ /// <summary>
+ /// Gets all downloads for the specified username.
+ /// </summary>
+ /// <param name="username"></param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ [HttpGet("downloads/{username}")]
+ [Authorize]
+ [ProducesResponseType(200)]
+ public IActionResult GetDownloads([FromRoute, Required]string username)
+ {
+ return Ok(Tracker.Transfers
+ .WithDirection(TransferDirection.Download)
+ .FromUser(username)
+ .ToMap());
+ }
+
+ /// <summary>
+ /// Gets the downlaod for the specified username matching the specified filename, and requests
+ /// the current place in the remote queue of the specified download.
+ /// </summary>
+ /// <param name="username">The username of the download source.</param>
+ /// <param name="id">The id of the download.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">The specified download was not found.</response>
+ [HttpGet("downloads/{username}/{id}")]
+ [Authorize]
+ [ProducesResponseType(typeof(DTO.Transfer), 200)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id)
+ {
+ var record = Tracker.Transfers.WithDirection(TransferDirection.Download).FromUser(username).WithId(id);
+
+ if (record == default)
+ {
+ return NotFound();
+ }
+
+ record.Transfer.PlaceInQueue = await Client.GetDownloadPlaceInQueueAsync(username, record.Transfer.Filename);
+ return Ok(record.Transfer);
+ }
+
+ /// <summary>
+ /// Gets all uploads.
+ /// </summary>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ [HttpGet("uploads")]
+ [Authorize]
+ [ProducesResponseType(200)]
+ public IActionResult GetUploads()
+ {
+ return Ok(Tracker.Transfers
+ .WithDirection(TransferDirection.Upload)
+ .ToMap());
+ }
+
+ /// <summary>
+ /// Gets all uploads for the specified username.
+ /// </summary>
+ /// <param name="username"></param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ [HttpGet("uploads/{username}")]
+ [Authorize]
+ [ProducesResponseType(200)]
+ public IActionResult GetUploads([FromRoute, Required]string username)
+ {
+ return Ok(Tracker.Transfers
+ .WithDirection(TransferDirection.Upload)
+ .FromUser(username)
+ .ToMap());
+ }
+
+ /// <summary>
+ /// Gets the upload for the specified username matching the specified filename.
+ /// </summary>
+ /// <param name="username">The username of the upload destination.</param>
+ /// <param name="id">The id of the upload.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ [HttpGet("uploads/{username}/{id}")]
+ [Authorize]
+ [ProducesResponseType(200)]
+ public IActionResult GetUploads([FromRoute, Required]string username, [FromRoute, Required]string id)
+ {
+ return Ok(Tracker.Transfers
+ .WithDirection(TransferDirection.Upload)
+ .FromUser(username)
+ .WithId(id).Transfer);
+ }
+
+ private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory)
+ {
+ var localFilename = remoteFilename.ToLocalOSPath();
+ var path = $"{saveDirectory}{Path.DirectorySeparatorChar}{Path.GetDirectoryName(localFilename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(localFilename)), "")}";
+
+ if (!System.IO.Directory.Exists(path))
+ {
+ System.IO.Directory.CreateDirectory(path);
+ }
+
+ var sanitizedFilename = Path.GetFileName(localFilename);
+
+ foreach (var c in Path.GetInvalidFileNameChars())
+ {
+ sanitizedFilename = sanitizedFilename.Replace(c, '_');
+ }
+
+ localFilename = Path.Combine(path, sanitizedFilename);
+
+ return new FileStream(localFilename, FileMode.Create);
+ }
+
+ private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false)
+ {
+ if (Tracker.TryGet(direction, username, id, out var transfer))
+ {
+ transfer.CancellationTokenSource.Cancel();
+
+ if (remove)
+ {
+ Tracker.TryRemove(direction, username, id);
+ }
+
+ return NoContent();
+ }
+
+ return NotFound();
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Controllers/UserController.cs b/src/slskd/Controllers/UserController.cs
new file mode 100644
index 00000000..dc955376
--- /dev/null
+++ b/src/slskd/Controllers/UserController.cs
@@ -0,0 +1,151 @@
+namespace slskd.Controllers
+{
+ using System.Collections.Generic;
+ using System.ComponentModel.DataAnnotations;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
+ using Soulseek;
+ using slskd.DTO;
+ using slskd.Trackers;
+
+ /// <summary>
+ /// Users
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("1")]
+ [ApiController]
+ [Produces("application/json")]
+ [Consumes("application/json")]
+ public class UserController : ControllerBase
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserController"/> class.
+ /// </summary>
+ /// <param name="client"></param>
+ /// <param name="browseTracker"></param>
+ public UserController(ISoulseekClient client, IBrowseTracker browseTracker)
+ {
+ Client = client;
+ BrowseTracker = browseTracker;
+ }
+
+ private ISoulseekClient Client { get; }
+ private IBrowseTracker BrowseTracker { get; }
+
+ /// <summary>
+ /// Retrieves the address of the specified <paramref name="username"/>.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ [HttpGet("{username}/address")]
+ [Authorize]
+ [ProducesResponseType(typeof(UserAddress), 200)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> Address([FromRoute, Required]string username)
+ {
+ try
+ {
+ var endpoint = await Client.GetUserEndPointAsync(username);
+ return Ok(new UserAddress() { IPAddress = endpoint.Address.ToString(), Port = endpoint.Port });
+ }
+ catch (UserOfflineException ex)
+ {
+ return NotFound(ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Retrieves the files shared by the specified <paramref name="username"/>.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <returns></returns>
+ [HttpGet("{username}/browse")]
+ [Authorize]
+ [ProducesResponseType(typeof(IEnumerable<Directory>), 200)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> Browse([FromRoute, Required]string username)
+ {
+ try
+ {
+ var result = await Client.BrowseAsync(username);
+
+ _ = Task.Run(async () =>
+ {
+ await Task.Delay(5000);
+ BrowseTracker.TryRemove(username);
+ });
+
+ return Ok(result);
+ }
+ catch (UserOfflineException ex)
+ {
+ return NotFound(ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Retrieves the status of the current browse operation for the specified <paramref name="username"/>, if any.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <returns></returns>
+ [HttpGet("{username}/browse/status")]
+ [Authorize]
+ [ProducesResponseType(typeof(decimal), 200)]
+ [ProducesResponseType(404)]
+ public IActionResult BrowseStatus([FromRoute, Required]string username)
+ {
+ if (BrowseTracker.TryGet(username, out var progress))
+ {
+ return Ok(progress);
+ }
+
+ return NotFound();
+ }
+
+ /// <summary>
+ /// Retrieves information about the specified <paramref name="username"/>.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <returns></returns>
+ [HttpGet("{username}/info")]
+ [Authorize]
+ [ProducesResponseType(typeof(UserInfo), 200)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> Info([FromRoute, Required]string username)
+ {
+ try
+ {
+ var response = await Client.GetUserInfoAsync(username);
+ return Ok(response);
+ }
+ catch (UserOfflineException ex)
+ {
+ return NotFound(ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Retrieves status for the specified <paramref name="username"/>.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <returns></returns>
+ [HttpGet("{username}/status")]
+ [Authorize]
+ [ProducesResponseType(typeof(UserStatus), 200)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> Status([FromRoute, Required]string username)
+ {
+ try
+ {
+ var response = await Client.GetUserStatusAsync(username);
+ return Ok(response);
+ }
+ catch (UserOfflineException ex)
+ {
+ return NotFound(ex.Message);
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/DTO/ConnectRequest.cs b/src/slskd/DTO/ConnectRequest.cs
new file mode 100644
index 00000000..6d2203b7
--- /dev/null
+++ b/src/slskd/DTO/ConnectRequest.cs
@@ -0,0 +1,10 @@
+namespace slskd.DTO
+{
+ public class ConnectRequest
+ {
+ public string Address { get; set; }
+ public int? Port { get; set; }
+ public string Username { get; set; }
+ public string Password { get; set; }
+ }
+}
diff --git a/src/slskd/DTO/LoginRequest.cs b/src/slskd/DTO/LoginRequest.cs
new file mode 100644
index 00000000..04c3dd65
--- /dev/null
+++ b/src/slskd/DTO/LoginRequest.cs
@@ -0,0 +1,8 @@
+namespace slskd.DTO
+{
+ public class LoginRequest
+ {
+ public string Username { get; set; }
+ public string Password { get; set; }
+ }
+}
diff --git a/src/slskd/DTO/PrivateMessageResponse.cs b/src/slskd/DTO/PrivateMessageResponse.cs
new file mode 100644
index 00000000..fb60be32
--- /dev/null
+++ b/src/slskd/DTO/PrivateMessageResponse.cs
@@ -0,0 +1,57 @@
+namespace slskd.DTO
+{
+ using System;
+ using slskd.Entities;
+
+ 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/DTO/QueueDownloadRequest.cs b/src/slskd/DTO/QueueDownloadRequest.cs
new file mode 100644
index 00000000..c2c1c2d4
--- /dev/null
+++ b/src/slskd/DTO/QueueDownloadRequest.cs
@@ -0,0 +1,20 @@
+namespace slskd.DTO
+{
+ public class QueueDownloadRequest
+ {
+ /// <summary>
+ /// Gets or sets the filename to download.
+ /// </summary>
+ public string Filename { get; set; }
+
+ /// <summary>
+ /// Gets or sets the size of the file.
+ /// </summary>
+ public long? Size { get; set; }
+
+ /// <summary>
+ /// Gets or sets the optional transfer token.
+ /// </summary>
+ public int? Token { get; set; }
+ }
+}
diff --git a/src/slskd/DTO/RoomInfoResponse.cs b/src/slskd/DTO/RoomInfoResponse.cs
new file mode 100644
index 00000000..0b0aadf0
--- /dev/null
+++ b/src/slskd/DTO/RoomInfoResponse.cs
@@ -0,0 +1,43 @@
+namespace slskd.DTO
+{
+ using Soulseek;
+
+ public class RoomInfoResponse
+ {
+ /// <summary>
+ /// Gets the room name.
+ /// </summary>
+ public string Name { get; init; }
+
+ /// <summary>
+ /// Gets the number of users in the room.
+ /// </summary>
+ public int UserCount { get; init; }
+
+ /// <summary>
+ /// Gets a value indicating whether the room is private.
+ /// </summary>
+ public bool IsPrivate { get; init; }
+
+ /// <summary>
+ /// Gets a value indicating whether the room is owned by the currently logged in user.
+ /// </summary>
+ public bool IsOwned { get; init; }
+
+ /// <summary>
+ /// Gets a value indicating whether the room is moderated by the currently logged in user.
+ /// </summary>
+ public bool IsModerated { get; set; }
+
+ public static RoomInfoResponse FromRoomInfo(RoomInfo info, bool isPrivate = false, bool isOwned = false)
+ {
+ return new RoomInfoResponse()
+ {
+ Name = info.Name,
+ UserCount = info.UserCount,
+ IsPrivate = isPrivate,
+ IsOwned = isOwned
+ };
+ }
+ }
+}
diff --git a/src/slskd/DTO/RoomMessageResponse.cs b/src/slskd/DTO/RoomMessageResponse.cs
new file mode 100644
index 00000000..b64bedf3
--- /dev/null
+++ b/src/slskd/DTO/RoomMessageResponse.cs
@@ -0,0 +1,45 @@
+namespace slskd.DTO
+{
+ using System;
+ using slskd.Entities;
+
+ 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/DTO/RoomResponse.cs b/src/slskd/DTO/RoomResponse.cs
new file mode 100644
index 00000000..ff47b253
--- /dev/null
+++ b/src/slskd/DTO/RoomResponse.cs
@@ -0,0 +1,57 @@
+namespace slskd.DTO
+{
+ using System.Collections.Generic;
+ using System.Linq;
+
+ public class RoomResponse
+ {
+ /// <summary>
+ /// The room name.
+ /// </summary>
+ public string Name { get; set; }
+
+ /// <summary>
+ /// A value indicating whether the room is private.
+ /// </summary>
+ public bool IsPrivate { get; set; }
+
+ /// <summary>
+ /// The number of operators in the room, if private.
+ /// </summary>
+ public int? OperatorCount { get; set; }
+
+ /// <summary>
+ /// The operators in the room, if private.
+ /// </summary>
+ public IList<string> Operators { get; set; }
+
+ /// <summary>
+ /// The owner of the room, if private.
+ /// </summary>
+ public string Owner { get; set; }
+
+ /// <summary>
+ /// The list of users in the room.
+ /// </summary>
+ public IEnumerable<UserDataResponse> Users { get; set; } = new List<UserDataResponse>();
+
+ /// <summary>
+ /// The list of messages.
+ /// </summary>
+ public IEnumerable<RoomMessageResponse> Messages { get; set; } = new List<RoomMessageResponse>();
+
+ public static RoomResponse FromRoom(Room room)
+ {
+ return new RoomResponse()
+ {
+ Name = room.Name,
+ IsPrivate = room.IsPrivate,
+ OperatorCount = room.OperatorCount,
+ Operators = room.Operators.ToList(),
+ Owner = room.Owner,
+ Users = new List<UserDataResponse>(),
+ Messages = new List<RoomMessageResponse>()
+ };
+ }
+ }
+}
diff --git a/src/slskd/DTO/SearchRequest.cs b/src/slskd/DTO/SearchRequest.cs
new file mode 100644
index 00000000..7123a348
--- /dev/null
+++ b/src/slskd/DTO/SearchRequest.cs
@@ -0,0 +1,99 @@
+using Soulseek;
+using System;
+
+namespace slskd.DTO
+{
+ /// <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/DTO/TokenResponse.cs b/src/slskd/DTO/TokenResponse.cs
new file mode 100644
index 00000000..c1766852
--- /dev/null
+++ b/src/slskd/DTO/TokenResponse.cs
@@ -0,0 +1,50 @@
+namespace slskd.DTO
+{
+ using System;
+ using System.IdentityModel.Tokens.Jwt;
+ using System.Linq;
+ using System.Security.Claims;
+ using Microsoft.AspNetCore.Authentication.JwtBearer;
+ using Newtonsoft.Json;
+
+ public class TokenResponse
+ {
+ public TokenResponse(JwtSecurityToken jwtSecurityToken)
+ {
+ JwtSecurityToken = jwtSecurityToken;
+ }
+
+ [JsonIgnore]
+ private JwtSecurityToken JwtSecurityToken { get; }
+
+ /// <summary>
+ /// Gets the Access Token string.
+ /// </summary>
+ public string Token => new JwtSecurityTokenHandler().WriteToken(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.Where(c => c.Type == ClaimTypes.Name).SingleOrDefault().Value;
+
+ /// <summary>
+ /// Gets the value of the Not Before claim from the Access Token.
+ /// </summary>
+ public long NotBefore => long.Parse(JwtSecurityToken.Claims.Where(c => c.Type == "nbf").SingleOrDefault().Value);
+
+ /// <summary>
+ /// Gets the Token type.
+ /// </summary>
+ public string TokenType => JwtBearerDefaults.AuthenticationScheme;
+ }
+} \ No newline at end of file
diff --git a/src/slskd/DTO/Transfer.cs b/src/slskd/DTO/Transfer.cs
new file mode 100644
index 00000000..dfefa5c8
--- /dev/null
+++ b/src/slskd/DTO/Transfer.cs
@@ -0,0 +1,131 @@
+namespace slskd.DTO
+{
+ using Soulseek;
+ using System;
+ using System.Net;
+
+ /// <summary>
+ /// A single file transfer.
+ /// </summary>
+ public class Transfer
+ {
+ /// <summary>
+ /// Gets the current average transfer speed.
+ /// </summary>
+ public double AverageSpeed { get; set; }
+
+ /// <summary>
+ /// Gets the number of remaining bytes to be transferred.
+ /// </summary>
+ public long BytesRemaining { get; set; }
+
+ /// <summary>
+ /// Gets the total number of bytes transferred.
+ /// </summary>
+ public long BytesTransferred { get; set; }
+
+ /// <summary>
+ /// Gets the transfer direction.
+ /// </summary>
+ public TransferDirection Direction { get; set; }
+
+ /// <summary>
+ /// Gets the current duration of the transfer, if it has been started.
+ /// </summary>
+ public double? ElapsedTime { get; set; }
+
+ /// <summary>
+ /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.Completed"/> state.
+ /// </summary>
+ public DateTime? EndTime { get; set; }
+
+ /// <summary>
+ /// Gets the filename of the file to be transferred.
+ /// </summary>
+ public string Filename { get; set; }
+
+ /// <summary>
+ /// Gets the transfer id.
+ /// </summary>
+ public string Id => Filename.Sha1();
+
+ /// <summary>
+ /// Gets the ip endpoint of the remote transfer connection, if one has been established.
+ /// </summary>
+ public IPEndPoint IPEndPoint { get; set; }
+
+ /// <summary>
+ /// Gets the current progress in percent.
+ /// </summary>
+ public double PercentComplete { get; set; }
+
+ /// <summary>
+ /// Gets the current place in queue, if it has been fetched.
+ /// </summary>
+ public int? PlaceInQueue { get; set; }
+
+ /// <summary>
+ /// Gets the projected remaining duration of the transfer.
+ /// </summary>
+ public double? RemainingTime { get; set; }
+
+ /// <summary>
+ /// Gets the remote unique token for the transfer.
+ /// </summary>
+ public int? RemoteToken { get; set; }
+
+ /// <summary>
+ /// Gets the size of the file to be transferred, in bytes.
+ /// </summary>
+ public long Size { get; set; }
+
+ /// <summary>
+ /// Gets the starting offset of the transfer, in bytes.
+ /// </summary>
+ public long StartOffset { get; set; }
+
+ /// <summary>
+ /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.InProgress"/> state.
+ /// </summary>
+ public DateTime? StartTime { get; set; }
+
+ /// <summary>
+ /// Gets the state of the transfer.
+ /// </summary>
+ public TransferStates State { get; set; }
+
+ /// <summary>
+ /// Gets the unique token for the transfer.
+ /// </summary>
+ public int Token { get; set; }
+
+ /// <summary>
+ /// Gets the username of the peer to or from which the file is to be transferred.
+ /// </summary>
+ public string Username { get; set; }
+
+ public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer)
+ {
+ return new Transfer()
+ {
+ AverageSpeed = transfer.AverageSpeed,
+ BytesRemaining = transfer.BytesRemaining,
+ BytesTransferred = transfer.BytesTransferred,
+ Direction = transfer.Direction,
+ ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds,
+ EndTime = transfer.EndTime,
+ Filename = transfer.Filename,
+ IPEndPoint = transfer.IPEndPoint,
+ PercentComplete = transfer.PercentComplete,
+ RemainingTime = transfer.RemainingTime?.TotalMilliseconds,
+ RemoteToken = transfer.RemoteToken,
+ Size = transfer.Size,
+ StartOffset = transfer.StartOffset,
+ StartTime = transfer.StartTime,
+ State = transfer.State,
+ Token = transfer.Token,
+ Username = transfer.Username
+ };
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/DTO/UserAddress.cs b/src/slskd/DTO/UserAddress.cs
new file mode 100644
index 00000000..1a69bf7f
--- /dev/null
+++ b/src/slskd/DTO/UserAddress.cs
@@ -0,0 +1,18 @@
+namespace slskd.DTO
+{
+ /// <summary>
+ /// A user's IP address and port.
+ /// </summary>
+ public class UserAddress
+ {
+ /// <summary>
+ /// Gets or sets the IP address.
+ /// </summary>
+ public string IPAddress { get; set; }
+
+ /// <summary>
+ /// Gets or sets the port.
+ /// </summary>
+ public int Port { get; set; }
+ }
+}
diff --git a/src/slskd/DTO/UserDataResponse.cs b/src/slskd/DTO/UserDataResponse.cs
new file mode 100644
index 00000000..fcbf8899
--- /dev/null
+++ b/src/slskd/DTO/UserDataResponse.cs
@@ -0,0 +1,68 @@
+namespace slskd.DTO
+{
+ using Soulseek;
+
+ public class UserDataResponse
+ {
+ /// <summary>
+ /// The average upload speed of the user.
+ /// </summary>
+ public int AverageSpeed { get; set; }
+
+ /// <summary>
+ /// The user's country code, if provided.
+ /// </summary>
+ public string CountryCode { get; set; }
+
+ /// <summary>
+ /// The number of directories shared by the user.
+ /// </summary>
+ public int DirectoryCount { get; set; }
+
+ /// <summary>
+ /// The number of active user downloads.
+ /// </summary>
+ public long DownloadCount { get; set; }
+
+ /// <summary>
+ /// The number of files shared by the user.
+ /// </summary>
+ public int FileCount { get; set; }
+
+ /// <summary>
+ /// A value indicating whether this user data belongs to the currently logged in user.
+ /// </summary>
+ public bool? Self { get; set; }
+
+ /// <summary>
+ /// The number of the user's free download slots, if provided.
+ /// </summary>
+ public int? SlotsFree { get; set; }
+
+ /// <summary>
+ /// The status of the user (0 = offline, 1 = away, 2 = online).
+ /// </summary>
+ public UserPresence Status { get; set; }
+
+ /// <summary>
+ /// The username of the user.
+ /// </summary>
+ public string Username { get; set; }
+
+ public static UserDataResponse FromUserData(UserData userData, bool self = false)
+ {
+ return new UserDataResponse()
+ {
+ AverageSpeed = userData.AverageSpeed,
+ CountryCode = userData.CountryCode,
+ DirectoryCount = userData.DirectoryCount,
+ DownloadCount = userData.DownloadCount,
+ FileCount = userData.FileCount,
+ SlotsFree = userData.SlotsFree,
+ Status = userData.Status,
+ Username = userData.Username,
+ Self = self ? self : (bool?)null
+ };
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Entities/PrivateMessage.cs b/src/slskd/Entities/PrivateMessage.cs
new file mode 100644
index 00000000..eba70e8f
--- /dev/null
+++ b/src/slskd/Entities/PrivateMessage.cs
@@ -0,0 +1,54 @@
+namespace slskd.Entities
+{
+ using Soulseek;
+ using System;
+
+ /// <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/Entities/RoomMessage.cs b/src/slskd/Entities/RoomMessage.cs
new file mode 100644
index 00000000..47c937c8
--- /dev/null
+++ b/src/slskd/Entities/RoomMessage.cs
@@ -0,0 +1,42 @@
+namespace slskd.Entities
+{
+ using Soulseek;
+ using System;
+
+ /// <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/Extensions.cs b/src/slskd/Extensions.cs
new file mode 100644
index 00000000..e4d8a582
--- /dev/null
+++ b/src/slskd/Extensions.cs
@@ -0,0 +1,82 @@
+namespace slskd
+{
+ using System;
+ using System.IO;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+
+ /// <summary>
+ /// Extensions.
+ /// </summary>
+ public static class Extensions
+ {
+ /// <summary>
+ /// Converts the given path to the local format (normalizes path separators).
+ /// </summary>
+ /// <param name="path"></param>
+ /// <returns></returns>
+ public static string ToLocalOSPath(this string path)
+ {
+ return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
+ }
+
+ /// <summary>
+ /// Returns the directory from the given path, regardless of separator format.
+ /// </summary>
+ /// <param name="path"></param>
+ /// <returns></returns>
+ public static string DirectoryName(this string path)
+ {
+ var separator = path.Contains('\\') ? '\\' : '/';
+ var parts = path.Split(separator);
+ return string.Join(separator, parts.Take(parts.Length - 1));
+ }
+
+ /// <summary>
+ /// Returns the SHA1 hash of the given string.
+ /// </summary>
+ /// <param name="str"></param>
+ /// <returns></returns>
+ public static string Sha1(this string str)
+ {
+ using (var sha1 = new SHA1Managed())
+ {
+ return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", "");
+ }
+ }
+
+ /// <summary>
+ /// Formats byte to nearest size (KB, MB, etc.)
+ /// </summary>
+ /// <param name="value"></param>
+ /// <param name="decimalPlaces"></param>
+ /// <returns></returns>
+ public static string SizeSuffix(this double value, int decimalPlaces = 1)
+ {
+ string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
+
+ if (value < 0) { return "-" + SizeSuffix(-value); }
+ if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }
+
+ // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
+ int mag = (int)Math.Log(value, 1024);
+
+ // 1L << (mag * 10) == 2 ^ (10 * mag)
+ // [i.e. the number of bytes in the unit corresponding to mag]
+ decimal adjustedSize = (decimal)value / (1L << (mag * 10));
+
+ // make adjustment when the value is large enough that
+ // it would round up to 1000 or more
+ if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
+ {
+ mag += 1;
+ adjustedSize /= 1024;
+ }
+
+ return string.Format("{0:n" + decimalPlaces + "} {1}",
+ adjustedSize,
+ SizeSuffixes[mag]);
+ }
+ }
+}
diff --git a/src/slskd/ISharedFileCache.cs b/src/slskd/ISharedFileCache.cs
new file mode 100644
index 00000000..f3c75f71
--- /dev/null
+++ b/src/slskd/ISharedFileCache.cs
@@ -0,0 +1,17 @@
+namespace slskd
+{
+ using Soulseek;
+ using System;
+ using System.Collections.Generic;
+
+ internal interface ISharedFileCache
+ {
+ 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/Program.cs b/src/slskd/Program.cs
new file mode 100644
index 00000000..a9553bd8
--- /dev/null
+++ b/src/slskd/Program.cs
@@ -0,0 +1,31 @@
+namespace slskd
+{
+ using Microsoft.AspNetCore;
+ using Microsoft.AspNetCore.Hosting;
+ using Microsoft.Extensions.Configuration;
+ using Microsoft.Extensions.Logging;
+
+ public class Program
+ {
+ public static void Main(string[] args)
+ {
+ CreateWebHostBuilder(args).Build().Run();
+ }
+
+ public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
+ WebHost.CreateDefaultBuilder(args)
+ .ConfigureAppConfiguration((hostingContext, config) =>
+ {
+ config.AddEnvironmentVariables(prefix: "SLSK_");
+ config.AddJsonFile("config.json", optional: true, reloadOnChange: false);
+ })
+ .ConfigureLogging((context, logging) =>
+ {
+ if (!System.Diagnostics.Debugger.IsAttached)
+ {
+ logging.ClearProviders();
+ }
+ })
+ .UseStartup<Startup>();
+ }
+}
diff --git a/src/slskd/Properties/launchSettings.json b/src/slskd/Properties/launchSettings.json
new file mode 100644
index 00000000..f5409d71
--- /dev/null
+++ b/src/slskd/Properties/launchSettings.json
@@ -0,0 +1,19 @@
+{
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:57117/",
+ "sslPort": 44332
+ }
+ },
+ "profiles": {
+ "slskd": {
+ "commandName": "Project",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ },
+ "applicationUrl": "https://localhost:5001;http://localhost:5000"
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Room.cs b/src/slskd/Room.cs
new file mode 100644
index 00000000..28c992f1
--- /dev/null
+++ b/src/slskd/Room.cs
@@ -0,0 +1,59 @@
+namespace slskd
+{
+ using Soulseek;
+ using System.Collections.Generic;
+ using System.Linq;
+ using slskd.Entities;
+
+ 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/Security/PBKDF2.cs b/src/slskd/Security/PBKDF2.cs
new file mode 100644
index 00000000..4a857135
--- /dev/null
+++ b/src/slskd/Security/PBKDF2.cs
@@ -0,0 +1,28 @@
+namespace slskd.Security
+{
+ using Microsoft.AspNetCore.Cryptography.KeyDerivation;
+ using System.Security.Cryptography;
+
+ /// <summary>
+ /// PBKDF2/RFC 2898 implementation
+ /// </summary>
+ public static class PBKDF2
+ {
+ /// <summary>
+ /// Gets a 256 bit (32 byte) key derived from the specified <paramref name="password"/> using PBKDF2/RFC 2898
+ /// </summary>
+ /// <param name="password"></param>
+ /// <returns></returns>
+ public static byte[] GetKey(string password)
+ {
+ byte[] salt = new byte[16];
+ int iterations = 1000;
+
+ using (var rng = RandomNumberGenerator.Create())
+ {
+ rng.GetBytes(salt);
+ return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, 32);
+ }
+ }
+ }
+}
diff --git a/src/slskd/Security/PassthroughAuthentication.cs b/src/slskd/Security/PassthroughAuthentication.cs
new file mode 100644
index 00000000..69b94df5
--- /dev/null
+++ b/src/slskd/Security/PassthroughAuthentication.cs
@@ -0,0 +1,40 @@
+namespace slskd.Security
+{
+ using Microsoft.AspNetCore.Authentication;
+ using Microsoft.Extensions.Logging;
+ using Microsoft.Extensions.Options;
+ using System.Security.Principal;
+ using System.Text.Encodings.Web;
+ using System.Threading.Tasks;
+
+ public class PassthroughAuthentication
+ {
+ public static string AuthenticationScheme { get; } = "Passthrough";
+ }
+
+ public class PassthroughAuthenticationHandler : AuthenticationHandler<PassthroughAuthenticationOptions>
+ {
+ public PassthroughAuthenticationHandler(IOptionsMonitor<PassthroughAuthenticationOptions> optionsMonitor, ILoggerFactory logger, UrlEncoder urlEncoder, ISystemClock systemClock)
+ : base(optionsMonitor, logger, urlEncoder, systemClock)
+ {
+ }
+
+ protected override Task<AuthenticateResult> HandleAuthenticateAsync()
+ {
+ var identity = new GenericIdentity(Options.Username);
+ var principal = new GenericPrincipal(identity, new[] { "User" });
+ var ticket = new AuthenticationTicket(principal , new AuthenticationProperties(), PassthroughAuthentication.AuthenticationScheme);
+
+ return Task.FromResult(AuthenticateResult.Success(ticket));
+ }
+ }
+
+ public class PassthroughAuthenticationOptions : AuthenticationSchemeOptions
+ {
+ public PassthroughAuthenticationOptions()
+ {
+ }
+
+ public string Username { get; set; }
+ }
+}
diff --git a/src/slskd/SharedFileCache.cs b/src/slskd/SharedFileCache.cs
new file mode 100644
index 00000000..ba88b31a
--- /dev/null
+++ b/src/slskd/SharedFileCache.cs
@@ -0,0 +1,141 @@
+namespace slskd
+{
+ using Microsoft.Data.Sqlite;
+ using Soulseek;
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.IO;
+ using System.Linq;
+ using System.Threading;
+
+ /// <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 string Directory { get; }
+ private Dictionary<string, Soulseek.File> Files { get; set; }
+ public DateTime? LastFill { get; set; }
+ private SqliteConnection SQLite { get; set; }
+ private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim();
+ public long TTL { get; }
+
+ /// <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();
+
+ Files = System.IO.Directory.GetFiles(Directory, "*", SearchOption.AllDirectories)
+ .Select(f => new Soulseek.File(1, f, 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);
+ }
+ }
+ 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/Startup.cs b/src/slskd/Startup.cs
new file mode 100644
index 00000000..cd1fa9d7
--- /dev/null
+++ b/src/slskd/Startup.cs
@@ -0,0 +1,540 @@
+namespace slskd
+{
+ using System;
+ using System.Collections.Generic;
+ using System.IO;
+ using System.Linq;
+ using System.Net;
+ using System.Reflection;
+ using System.Text.Json;
+ using System.Text.Json.Serialization;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authentication.JwtBearer;
+ using Microsoft.AspNetCore.Builder;
+ using Microsoft.AspNetCore.Hosting;
+ using Microsoft.AspNetCore.Mvc;
+ using Microsoft.AspNetCore.Mvc.ApiExplorer;
+ using Microsoft.Extensions.Caching.Memory;
+ using Microsoft.Extensions.Configuration;
+ using Microsoft.Extensions.DependencyInjection;
+ using Microsoft.Extensions.FileProviders;
+ using Microsoft.Extensions.Hosting;
+ using Microsoft.IdentityModel.Tokens;
+ using Microsoft.OpenApi.Models;
+ using Newtonsoft.Json;
+ using Soulseek;
+ using Soulseek.Diagnostics;
+ using slskd.Entities;
+ using slskd.Security;
+ using slskd.Trackers;
+
+ public class Startup
+ {
+ internal static string Username { get; set; }
+ internal static string Password { get; set; }
+ internal static string BasePath { get; set; }
+ internal static string WebRoot { get; set; }
+ internal static int ListenPort { get; set; }
+ internal static string OutputDirectory { get; set; }
+ internal static string SharedDirectory { get; set; }
+ internal static long SharedCacheTTL { get; set; }
+ internal static bool EnableDistributedNetwork { get; set; }
+ internal static int DistributedChildLimit { get; set; }
+ internal static DiagnosticLevel DiagnosticLevel { get; set; }
+ internal static int ConnectTimeout { get; set; }
+ internal static int InactivityTimeout { get; set; }
+ internal static bool EnableSecurity { get; set; }
+ internal static int SecurityTokenTTL { get; set; }
+ internal static int RoomMessageLimit { get; set; }
+ internal static int ReadBufferSize { get; set; }
+ internal static int WriteBufferSize { get; set; }
+
+ internal static SymmetricSecurityKey JwtSigningKey { get; set; }
+
+ private SoulseekClient Client { get; set; }
+ private object ConsoleSyncRoot { get; } = new object();
+ private ISharedFileCache SharedFileCache { get; set; }
+
+ public Startup(IConfiguration configuration)
+ {
+ Configuration = configuration;
+
+ Username = Configuration.GetValue<string>("USERNAME");
+ Password = Configuration.GetValue<string>("PASSWORD");
+ BasePath = Configuration.GetValue<string>("BASE_PATH");
+ WebRoot = Configuration.GetValue<string>("WEB_ROOT");
+ ListenPort = Configuration.GetValue<int>("LISTEN_PORT", 50000);
+ OutputDirectory = Configuration.GetValue<string>("OUTPUT_DIR");
+ SharedDirectory = Configuration.GetValue<string>("SHARED_DIR");
+ SharedCacheTTL = Configuration.GetValue<long>("SHARED_CACHE_TTL", 3600000); // 1 hour
+ EnableDistributedNetwork = Configuration.GetValue<bool>("ENABLE_DNET", true);
+ DistributedChildLimit = Configuration.GetValue<int>("DNET_CHILD_LIMIT", 10);
+ DiagnosticLevel = Configuration.GetValue<DiagnosticLevel>("DIAGNOSTIC", DiagnosticLevel.Info);
+ ConnectTimeout = Configuration.GetValue<int>("CONNECT_TIMEOUT", 5000);
+ InactivityTimeout = Configuration.GetValue<int>("INACTIVITY_TIMEOUT", 15000);
+ EnableSecurity = Configuration.GetValue<bool>("ENABLE_SECURITY", true);
+ SecurityTokenTTL = Configuration.GetValue<int>("SECURITY_TOKEN_TTL", 604800000); // 7 days
+ RoomMessageLimit = Configuration.GetValue<int>("ROOM_MESSAGE_LIMIT", 250);
+ ReadBufferSize = Configuration.GetValue<int>("READ_BUFFER_SIZE", 16384);
+ WriteBufferSize = Configuration.GetValue<int>("WRITE_BUFFER_SIZE", 16384);
+
+ JwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Password));
+
+ SharedFileCache = new SharedFileCache(SharedDirectory, SharedCacheTTL);
+ }
+
+ public IConfiguration Configuration { get; }
+
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
+
+ if (EnableSecurity)
+ {
+ services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+ .AddJwtBearer(options =>
+ {
+ options.TokenValidationParameters = new TokenValidationParameters
+ {
+ ClockSkew = TimeSpan.FromMinutes(5),
+ RequireSignedTokens = true,
+ RequireExpirationTime = true,
+ ValidateLifetime = true,
+ ValidIssuer = "slsk-web-example",
+ ValidateIssuer = true,
+ ValidateAudience = false,
+ IssuerSigningKey = JwtSigningKey,
+ ValidateIssuerSigningKey = true,
+ };
+ });
+ }
+ else
+ {
+ services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme)
+ .AddScheme<PassthroughAuthenticationOptions, PassthroughAuthenticationHandler>(PassthroughAuthentication.AuthenticationScheme, options =>
+ {
+ options.Username = Username;
+ });
+ }
+
+ services.AddMvc(options =>
+ {
+ options.EnableEndpointRouting = false;
+ })
+ .SetCompatibilityVersion(CompatibilityVersion.Latest)
+ .AddJsonOptions(options =>
+ {
+ options.JsonSerializerOptions.Converters.Add(new IPAddressConverter());
+ options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
+ options.JsonSerializerOptions.IgnoreNullValues = true;
+ });
+
+ services.AddRouting(options => options.LowercaseUrls = true);
+
+ services.AddApiVersioning(options => options.ReportApiVersions = true);
+ services.AddVersionedApiExplorer(options =>
+ {
+ options.GroupNameFormat = "'v'VVV";
+ options.SubstituteApiVersionInUrl = true;
+ });
+
+ services.AddSwaggerGen(options =>
+ {
+ options.DescribeAllParametersInCamelCase();
+ options.SwaggerDoc("v1",
+ new OpenApiInfo
+ {
+ Title = "Soulseek.NET Example API",
+ Version = "v1"
+ }
+ );
+
+ options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, typeof(Startup).GetTypeInfo().Assembly.GetName().Name + ".xml"));
+ });
+
+ services.AddSingleton<ISoulseekClient, SoulseekClient>(serviceProvider => Client);
+ services.AddSingleton<ITransferTracker, TransferTracker>();
+ services.AddSingleton<ISearchTracker, SearchTracker>();
+ services.AddSingleton<IBrowseTracker, BrowseTracker>();
+ services.AddSingleton<IConversationTracker, ConversationTracker>();
+ services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: RoomMessageLimit));
+ }
+
+ public void Configure(
+ IApplicationBuilder app,
+ IWebHostEnvironment env,
+ IApiVersionDescriptionProvider provider,
+ ITransferTracker tracker,
+ IBrowseTracker browseTracker,
+ IConversationTracker conversationTracker,
+ IRoomTracker roomTracker)
+ {
+ if (!env.IsDevelopment())
+ {
+ app.UseHsts();
+ }
+
+ app.UseCors("AllowAll");
+
+ BasePath ??= "/";
+ BasePath = BasePath.StartsWith("/") ? BasePath : $"/{BasePath}";
+
+ app.UsePathBase(BasePath);
+
+ // remove any errant double forward slashes which may have been introduced
+ // by a reverse proxy or having the base path removed
+ app.Use(async (context, next) =>
+ {
+ var path = context.Request.Path.ToString();
+
+ if (path.StartsWith("//"))
+ {
+ context.Request.Path = new string(path.Skip(1).ToArray());
+ }
+
+ await next();
+ });
+
+ WebRoot ??= Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).AbsolutePath), "wwwroot");
+ Console.WriteLine($"Serving static content from {WebRoot}");
+
+ var fileServerOptions = new FileServerOptions
+ {
+ FileProvider = new PhysicalFileProvider(WebRoot),
+ RequestPath = "",
+ EnableDirectoryBrowsing = false,
+ EnableDefaultFiles = true
+ };
+
+ app.UseFileServer(fileServerOptions);
+
+ app.UseAuthentication();
+ app.UseMvc();
+
+ app.UseSwagger();
+ app.UseSwaggerUI(options => provider.ApiVersionDescriptions.ToList()
+ .ForEach(description => options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName)));
+
+ // if we made it this far and the route still wasn't matched, return the index
+ // this is required so that SPA routing (React Router, etc) can work properly
+ app.Use(async (context, next) =>
+ {
+ // exclude API routes which are not matched or return a 404
+ if (!context.Request.Path.StartsWithSegments("/api"))
+ {
+ context.Request.Path = "/";
+ }
+
+ await next();
+ });
+
+ app.UseFileServer(fileServerOptions);
+
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
+ // begin SoulseekClient implementation
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
+
+ var connectionOptions = new ConnectionOptions(
+ readBufferSize: ReadBufferSize,
+ writeBufferSize: WriteBufferSize,
+ connectTimeout: ConnectTimeout,
+ inactivityTimeout: InactivityTimeout);
+
+ // create options for the client.
+ // see the implementation of Func<> and Action<> options for detailed info.
+ var clientOptions = new SoulseekClientOptions(
+ listenPort: ListenPort,
+ userEndPointCache: new UserEndPointCache(),
+ distributedChildLimit: DistributedChildLimit,
+ enableDistributedNetwork: EnableDistributedNetwork,
+ minimumDiagnosticLevel: DiagnosticLevel,
+ autoAcknowledgePrivateMessages: false,
+ acceptPrivateRoomInvitations: true,
+ serverConnectionOptions: connectionOptions,
+ peerConnectionOptions: connectionOptions,
+ transferConnectionOptions: connectionOptions,
+ userInfoResponseResolver: UserInfoResponseResolver,
+ browseResponseResolver: BrowseResponseResolver,
+ directoryContentsResponseResolver: DirectoryContentsResponseResolver,
+ enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, tracker),
+ searchResponseResolver: SearchResponseResolver);
+
+ Client = new SoulseekClient(options: clientOptions);
+
+ // bind the DiagnosticGenerated event so we can trap and display diagnostic messages. this is optional, and if the event
+ // isn't bound the minimumDiagnosticLevel should be set to None.
+ Client.DiagnosticGenerated += (e, args) =>
+ {
+ lock (ConsoleSyncRoot)
+ {
+ if (args.Level == DiagnosticLevel.Debug) Console.ForegroundColor = ConsoleColor.DarkGray;
+ if (args.Level == DiagnosticLevel.Warning) Console.ForegroundColor = ConsoleColor.Yellow;
+
+ Console.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] [DIAGNOSTIC:{e.GetType().Name}] [{args.Level}] {args.Message}");
+ Console.ResetColor();
+ }
+ };
+
+ // bind transfer events. see TransferStateChangedEventArgs and TransferProgressEventArgs.
+ Client.TransferStateChanged += (e, args) =>
+ {
+ var direction = args.Transfer.Direction.ToString().ToUpper();
+ var user = args.Transfer.Username;
+ var file = Path.GetFileName(args.Transfer.Filename);
+ var oldState = args.PreviousState;
+ var state = args.Transfer.State;
+
+ var completed = args.Transfer.State.HasFlag(TransferStates.Completed);
+
+ Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({args.Transfer.BytesTransferred}/{args.Transfer.Size} = {args.Transfer.PercentComplete}%) @ {args.Transfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}");
+ };
+
+ Client.TransferProgressUpdated += (e, 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");
+ };
+
+ // bind BrowseProgressUpdated to track progress of browse response payload transfers.
+ // these can take a while depending on number of files shared.
+ Client.BrowseProgressUpdated += (e, args) =>
+ {
+ browseTracker.AddOrUpdate(args.Username, args);
+ };
+
+ // bind UserStatusChanged to monitor the status of users added via AddUserAsync().
+ Client.UserStatusChanged += (e, args) =>
+ {
+ // Console.WriteLine($"[USER] {args.Username}: {args.Status}");
+ };
+
+ Client.PrivateMessageReceived += (e, args) =>
+ {
+ conversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args));
+ };
+
+ 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 += (e, args) =>
+ {
+ Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}");
+ };
+
+ Client.RoomMessageReceived += (e, args) =>
+ {
+ var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow);
+ roomTracker.AddOrUpdateMessage(args.RoomName, message);
+ };
+
+ Client.RoomJoined += (e, args) =>
+ {
+ if (args.Username != Username) // this will fire when we join a room; track that through the join operation.
+ {
+ roomTracker.TryAddUser(args.RoomName, args.UserData);
+ }
+ };
+
+ Client.RoomLeft += (e, args) =>
+ {
+ roomTracker.TryRemoveUser(args.RoomName, args.Username);
+ };
+
+ Client.Disconnected += async (e, args) =>
+ {
+ Console.WriteLine($"Disconnected from Soulseek server: {args.Message}");
+
+ // don't reconnect if the disconnecting Exception is either of these types.
+ // if KickedFromServerException, another client was most likely signed in, and retrying will cause a connect loop.
+ // if ObjectDisposedException, the client is shutting down.
+ if (!(args.Exception is KickedFromServerException || args.Exception is ObjectDisposedException))
+ {
+ Console.WriteLine($"Attepting to reconnect...");
+ await Client.ConnectAsync(Username, Password);
+ }
+ };
+
+ Task.Run(async () =>
+ {
+ await Client.ConnectAsync(Username, Password);
+ }).GetAwaiter().GetResult();
+
+ Console.WriteLine($"Connected and logged in.");
+ }
+
+ /// <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: System.IO.File.ReadAllBytes(@"slsk_bird.jpg"),
+ uploadSlots: 1,
+ queueLength: 0,
+ hasFreeUploadSlot: false);
+
+ return Task.FromResult(info);
+ }
+
+ /// <summary>
+ /// Creates and returns an <see cref="IEnumerable{T}"/> of <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>
+ /// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns>
+ private Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint)
+ {
+ var directories = System.IO.Directory
+ .GetDirectories(SharedDirectory, "*", SearchOption.AllDirectories)
+ .Select(dir => new Soulseek.Directory(dir, 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));
+ }
+
+ /// <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, 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;
+ filename = filename.ToLocalOSPath();
+ var fileInfo = new FileInfo(filename);
+
+ if (!fileInfo.Exists)
+ {
+ Console.WriteLine($"[UPLOAD REJECTED] File {filename} 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, fileInfo.FullName, 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="SearchResponse"/> 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<SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query)
+ {
+ var defaultResponse = Task.FromResult<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 SearchResponse(
+ 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<SearchResponse>(null);
+ }
+
+ class IPAddressConverter : JsonConverter<IPAddress>
+ {
+ public override bool CanConvert(Type objectType) => (objectType == typeof(IPAddress));
+
+ public override IPAddress Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => IPAddress.Parse(reader.GetString());
+
+ public override void Write(Utf8JsonWriter writer, IPAddress value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString());
+ }
+
+ class UserEndPointCache : IUserEndPointCache
+ {
+ public UserEndPointCache()
+ {
+ Cache = new MemoryCache(new MemoryCacheOptions());
+ }
+
+ private IMemoryCache Cache { get; }
+
+ public void AddOrUpdate(string username, IPEndPoint endPoint)
+ {
+ Cache.Set(username, endPoint, TimeSpan.FromSeconds(60));
+ }
+
+ public bool TryGet(string username, out IPEndPoint endPoint)
+ {
+ return Cache.TryGetValue(username, out endPoint);
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Trackers/BrowseTracker.cs b/src/slskd/Trackers/BrowseTracker.cs
new file mode 100644
index 00000000..410cfca1
--- /dev/null
+++ b/src/slskd/Trackers/BrowseTracker.cs
@@ -0,0 +1,40 @@
+namespace slskd.Trackers
+{
+ using Soulseek;
+ using System.Collections.Concurrent;
+
+ /// <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/Trackers/ConversationTracker.cs b/src/slskd/Trackers/ConversationTracker.cs
new file mode 100644
index 00000000..e5ea02eb
--- /dev/null
+++ b/src/slskd/Trackers/ConversationTracker.cs
@@ -0,0 +1,46 @@
+namespace slskd.Trackers
+{
+ using System.Collections.Concurrent;
+ using System.Collections.Generic;
+ using slskd.Entities;
+
+ /// <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/Trackers/IBrowseTracker.cs b/src/slskd/Trackers/IBrowseTracker.cs
new file mode 100644
index 00000000..89396143
--- /dev/null
+++ b/src/slskd/Trackers/IBrowseTracker.cs
@@ -0,0 +1,37 @@
+namespace slskd.Trackers
+{
+ using Soulseek;
+ using System.Collections.Concurrent;
+
+ /// <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>
+ /// Removes a tracked browse operation for the specified user.
+ /// </summary>
+ /// <param name="username"></param>
+ void TryRemove(string username);
+
+ /// <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);
+ }
+}
diff --git a/src/slskd/Trackers/IConversationTracker.cs b/src/slskd/Trackers/IConversationTracker.cs
new file mode 100644
index 00000000..c738692c
--- /dev/null
+++ b/src/slskd/Trackers/IConversationTracker.cs
@@ -0,0 +1,39 @@
+namespace slskd.Trackers
+{
+ using System.Collections.Concurrent;
+ using System.Collections.Generic;
+ using slskd.Entities;
+
+ /// <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/Trackers/IRoomTracker.cs b/src/slskd/Trackers/IRoomTracker.cs
new file mode 100644
index 00000000..fe768910
--- /dev/null
+++ b/src/slskd/Trackers/IRoomTracker.cs
@@ -0,0 +1,59 @@
+namespace slskd.Trackers
+{
+ using Soulseek;
+ using System.Collections.Concurrent;
+ using slskd.Entities;
+
+ /// <summary>
+ /// Tracks rooms.
+ /// </summary>
+ public interface IRoomTracker
+ {
+ /// <summary>
+ /// 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/Trackers/ISearchTracker.cs b/src/slskd/Trackers/ISearchTracker.cs
new file mode 100644
index 00000000..4361c5e0
--- /dev/null
+++ b/src/slskd/Trackers/ISearchTracker.cs
@@ -0,0 +1,35 @@
+namespace slskd.Trackers
+{
+ using Soulseek;
+ using System;
+ using System.Collections.Concurrent;
+
+ /// <summary>
+ /// Tracks active searches.
+ /// </summary>
+ public interface ISearchTracker
+ {
+ /// <summary>
+ /// Gets active searches.
+ /// </summary>
+ ConcurrentDictionary<Guid, Search> Searches { get; }
+
+ /// <summary>
+ /// Adds or updates a tracked search.
+ /// </summary>
+ /// <param name="id"></param>
+ /// <param name="args"></param>
+ void AddOrUpdate(Guid id, SearchEventArgs args);
+
+ /// <summary>
+ /// Removes all tracked searches.
+ /// </summary>
+ void Clear();
+
+ /// <summary>
+ /// Removes a tracked search.
+ /// </summary>
+ /// <param name="id"></param>
+ void TryRemove(Guid id);
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Trackers/ITransferTracker.cs b/src/slskd/Trackers/ITransferTracker.cs
new file mode 100644
index 00000000..f55a23ac
--- /dev/null
+++ b/src/slskd/Trackers/ITransferTracker.cs
@@ -0,0 +1,40 @@
+namespace slskd.Trackers
+{
+ using Soulseek;
+ using System.Collections.Concurrent;
+ using System.Threading;
+
+ /// <summary>
+ /// Tracks transfers.
+ /// </summary>
+ public interface ITransferTracker
+ {
+ /// <summary>
+ /// Tracked transfers.
+ /// </summary>
+ ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.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 (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer);
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Trackers/RoomTracker.cs b/src/slskd/Trackers/RoomTracker.cs
new file mode 100644
index 00000000..3eec1f24
--- /dev/null
+++ b/src/slskd/Trackers/RoomTracker.cs
@@ -0,0 +1,96 @@
+namespace slskd.Trackers
+{
+ using Soulseek;
+ using System.Collections.Concurrent;
+ using System.Collections.Generic;
+ using System.Linq;
+ using slskd.Entities;
+
+ /// <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>
+ 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>
+ /// <returns></returns>
+ 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/Trackers/SearchTracker.cs b/src/slskd/Trackers/SearchTracker.cs
new file mode 100644
index 00000000..bf7569a9
--- /dev/null
+++ b/src/slskd/Trackers/SearchTracker.cs
@@ -0,0 +1,45 @@
+namespace slskd.Trackers
+{
+ using Soulseek;
+ using System;
+ using System.Collections.Concurrent;
+
+ /// <summary>
+ /// Tracks active searches.
+ /// </summary>
+ public class SearchTracker : ISearchTracker
+ {
+ /// <summary>
+ /// Gets active searches.
+ /// </summary>
+ public ConcurrentDictionary<Guid, Search> Searches { get; private set; } =
+ new ConcurrentDictionary<Guid, Search>();
+
+ /// <summary>
+ /// Adds or updates a tracked search.
+ /// </summary>
+ /// <param name="id"></param>
+ /// <param name="args"></param>
+ public void AddOrUpdate(Guid id, SearchEventArgs args)
+ {
+ Searches.AddOrUpdate(id, args.Search, (token, search) => args.Search);
+ }
+
+ /// <summary>
+ /// Removes all tracked searches.
+ /// </summary>
+ public void Clear()
+ {
+ Searches.Clear();
+ }
+
+ /// <summary>
+ /// Removes a tracked search.
+ /// </summary>
+ /// <param name="id"></param>
+ public void TryRemove(Guid id)
+ {
+ Searches.TryRemove(id, out _);
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Trackers/TransferTracker.cs b/src/slskd/Trackers/TransferTracker.cs
new file mode 100644
index 00000000..8739b7ca
--- /dev/null
+++ b/src/slskd/Trackers/TransferTracker.cs
@@ -0,0 +1,180 @@
+namespace slskd.Trackers
+{
+ using System.Collections.Concurrent;
+ using System.Threading;
+ using System.Linq;
+ using Soulseek;
+
+ /// <summary>
+ /// Transfer extensions.
+ /// </summary>
+ public static class TransferTrackerExtensions
+ {
+ /// <summary>
+ /// Filters a Transfer collection by direction.
+ /// </summary>
+ /// <param name="allTransfers"></param>
+ /// <param name="direction"></param>
+ /// <returns></returns>
+ public static ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> WithDirection(
+ this ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> allTransfers,
+ TransferDirection direction)
+ {
+ allTransfers.TryGetValue(direction, out var transfers);
+ return transfers ?? new ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.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, (DTO.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>
+ /// Filters a Transfer collection by user.
+ /// </summary>
+ /// <param name="directedTransfers"></param>
+ /// <param name="username"></param>
+ /// <returns></returns>
+ public static ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> FromUser(
+ this ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> directedTransfers,
+ string username)
+ {
+ directedTransfers.TryGetValue(username, out var transfers);
+ return transfers ?? new ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>();
+ }
+
+ /// <summary>
+ /// Maps a Transfer collection to a serializable object.
+ /// </summary>
+ /// <param name="userTransfers"></param>
+ public static object ToMap(
+ this ConcurrentDictionary<string, (DTO.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>
+ /// Retrieves a Transfer from a Transfer collection by id.
+ /// </summary>
+ /// <param name="userTransfers"></param>
+ /// <param name="id"></param>
+ /// <returns></returns>
+ public static (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId(
+ this ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers,
+ string id)
+ {
+ userTransfers.TryGetValue(id, out var transfer);
+ return transfer;
+ }
+ }
+
+ /// <summary>
+ /// Tracks transfers.
+ /// </summary>
+ public class TransferTracker : ITransferTracker
+ {
+ /// <summary>
+ /// Tracked transfers.
+ /// </summary>
+ public ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; private set; } =
+ new ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer, CancellationTokenSource)>>>();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TransferTracker"/> class.
+ /// </summary>
+ public TransferTracker()
+ {
+ Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>());
+ Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource 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 = DTO.Transfer.FromSoulseekTransfer(args.Transfer);
+ dict.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, cancellationTokenSource));
+ return dict;
+ });
+ }
+
+ /// <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 _);
+ }
+ }
+ }
+
+ /// <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 (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer)
+ {
+ transfer = default;
+
+ if (Transfers.TryGetValue(direction, out var transfers))
+ {
+ if (transfers.TryGetValue(username, out var user))
+ {
+ if (user.TryGetValue(id, out transfer))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource)
+ {
+ var r = new ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>();
+ var transfer = DTO.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/slskd.csproj b/src/slskd/slskd.csproj
new file mode 100644
index 00000000..7163629d
--- /dev/null
+++ b/src/slskd/slskd.csproj
@@ -0,0 +1,42 @@
+<Project Sdk="Microsoft.NET.Sdk.Web">
+
+ <PropertyGroup>
+ <TargetFramework>net5.0</TargetFramework>
+ <LangVersion>9.0</LangVersion>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <ServerGarbageCollection>false</ServerGarbageCollection>
+ <Version>0.0.1</Version>
+ </PropertyGroup>
+
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
+ <DocumentationFile></DocumentationFile>
+ <OutputPath></OutputPath>
+ <NoWarn>1701;1702;1591</NoWarn>
+ </PropertyGroup>
+
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
+ <DocumentationFile></DocumentationFile>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
+ <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="4.1.1" />
+ <PackageReference Include="Microsoft.Data.Sqlite" Version="3.1.9" />
+ <PackageReference Include="Soulseek" Version="1.0.0" />
+ <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
+ <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Folder Include="wwwroot\" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Content Update="wwwroot\.gitkeep">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ </ItemGroup>
+
+</Project>
diff --git a/src/slskd/wwwroot/.gitkeep b/src/slskd/wwwroot/.gitkeep
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/src/slskd/wwwroot/.gitkeep