From 8f1068ac3135bcccf09374bc787ef22049b43461 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 30 Dec 2020 21:16:50 -0600 Subject: copy files from example --- .gitignore | 351 +- Dockerfile | 14 + bin/build | 26 + bin/publish | 10 + bin/run | 14 + bin/start | 16 + slskd.sln | 45 + src/slskd/.gitignore | 350 + src/slskd/Controllers/ConversationsController.cs | 198 + src/slskd/Controllers/PublicChatController.cs | 50 + src/slskd/Controllers/RoomsController.cs | 287 + src/slskd/Controllers/SearchesController.cs | 102 + src/slskd/Controllers/ServerController.cs | 74 + src/slskd/Controllers/SessionController.cs | 120 + src/slskd/Controllers/TransfersController.cs | 284 + src/slskd/Controllers/UserController.cs | 151 + src/slskd/DTO/ConnectRequest.cs | 10 + src/slskd/DTO/LoginRequest.cs | 8 + src/slskd/DTO/PrivateMessageResponse.cs | 57 + src/slskd/DTO/QueueDownloadRequest.cs | 20 + src/slskd/DTO/RoomInfoResponse.cs | 43 + src/slskd/DTO/RoomMessageResponse.cs | 45 + src/slskd/DTO/RoomResponse.cs | 57 + src/slskd/DTO/SearchRequest.cs | 99 + src/slskd/DTO/TokenResponse.cs | 50 + src/slskd/DTO/Transfer.cs | 131 + src/slskd/DTO/UserAddress.cs | 18 + src/slskd/DTO/UserDataResponse.cs | 68 + src/slskd/Entities/PrivateMessage.cs | 54 + src/slskd/Entities/RoomMessage.cs | 42 + src/slskd/Extensions.cs | 82 + src/slskd/ISharedFileCache.cs | 17 + src/slskd/Program.cs | 31 + src/slskd/Properties/launchSettings.json | 19 + src/slskd/Room.cs | 59 + src/slskd/Security/PBKDF2.cs | 28 + src/slskd/Security/PassthroughAuthentication.cs | 40 + src/slskd/SharedFileCache.cs | 141 + src/slskd/Startup.cs | 540 + src/slskd/Trackers/BrowseTracker.cs | 40 + src/slskd/Trackers/ConversationTracker.cs | 46 + src/slskd/Trackers/IBrowseTracker.cs | 37 + src/slskd/Trackers/IConversationTracker.cs | 39 + src/slskd/Trackers/IRoomTracker.cs | 59 + src/slskd/Trackers/ISearchTracker.cs | 35 + src/slskd/Trackers/ITransferTracker.cs | 40 + src/slskd/Trackers/RoomTracker.cs | 96 + src/slskd/Trackers/SearchTracker.cs | 45 + src/slskd/Trackers/TransferTracker.cs | 180 + src/slskd/slskd.csproj | 42 + src/slskd/wwwroot/.gitkeep | 0 src/web/.gitignore | 23 + src/web/README.md | 68 + src/web/package.json | 38 + src/web/public/index.html | 12 + src/web/src/components/App.css | 125 + src/web/src/components/App.js | 170 + src/web/src/components/Browse/Browse.css | 68 + src/web/src/components/Browse/Browse.js | 233 + src/web/src/components/Browse/Directory.js | 101 + src/web/src/components/Browse/DirectoryTree.js | 40 + src/web/src/components/Chat/Chat.css | 100 + src/web/src/components/Chat/Chat.js | 215 + src/web/src/components/Chat/ChatMenu.js | 50 + src/web/src/components/Chat/SendMessageModal.js | 75 + src/web/src/components/LoginForm.js | 83 + src/web/src/components/Rooms/RoomJoinModal.js | 142 + src/web/src/components/Rooms/RoomMenu.js | 41 + src/web/src/components/Rooms/RoomUserList.js | 44 + src/web/src/components/Rooms/Rooms.css | 132 + src/web/src/components/Rooms/Rooms.js | 219 + src/web/src/components/Search/Response.js | 127 + src/web/src/components/Search/Search.css | 61 + src/web/src/components/Search/Search.js | 244 + src/web/src/components/Shared/FileList.js | 75 + .../src/components/Shared/PlaceholderSegment.js | 14 + src/web/src/components/Transfers/TransferGroup.js | 147 + src/web/src/components/Transfers/TransferList.js | 121 + src/web/src/components/Transfers/Transfers.js | 46 + src/web/src/config.js | 13 + src/web/src/index.js | 11 + src/web/src/lib/api.js | 39 + src/web/src/lib/chat.js | 17 + src/web/src/lib/rooms.js | 29 + src/web/src/lib/search.js | 9 + src/web/src/lib/session.js | 13 + src/web/src/lib/transfers.js | 17 + src/web/src/lib/user.js | 9 + src/web/src/lib/util.js | 76 + src/web/yarn.lock | 10498 +++++++++++++++++++ 90 files changed, 17605 insertions(+), 350 deletions(-) create mode 100644 Dockerfile create mode 100644 bin/build create mode 100644 bin/publish create mode 100644 bin/run create mode 100644 bin/start create mode 100644 slskd.sln create mode 100644 src/slskd/.gitignore create mode 100644 src/slskd/Controllers/ConversationsController.cs create mode 100644 src/slskd/Controllers/PublicChatController.cs create mode 100644 src/slskd/Controllers/RoomsController.cs create mode 100644 src/slskd/Controllers/SearchesController.cs create mode 100644 src/slskd/Controllers/ServerController.cs create mode 100644 src/slskd/Controllers/SessionController.cs create mode 100644 src/slskd/Controllers/TransfersController.cs create mode 100644 src/slskd/Controllers/UserController.cs create mode 100644 src/slskd/DTO/ConnectRequest.cs create mode 100644 src/slskd/DTO/LoginRequest.cs create mode 100644 src/slskd/DTO/PrivateMessageResponse.cs create mode 100644 src/slskd/DTO/QueueDownloadRequest.cs create mode 100644 src/slskd/DTO/RoomInfoResponse.cs create mode 100644 src/slskd/DTO/RoomMessageResponse.cs create mode 100644 src/slskd/DTO/RoomResponse.cs create mode 100644 src/slskd/DTO/SearchRequest.cs create mode 100644 src/slskd/DTO/TokenResponse.cs create mode 100644 src/slskd/DTO/Transfer.cs create mode 100644 src/slskd/DTO/UserAddress.cs create mode 100644 src/slskd/DTO/UserDataResponse.cs create mode 100644 src/slskd/Entities/PrivateMessage.cs create mode 100644 src/slskd/Entities/RoomMessage.cs create mode 100644 src/slskd/Extensions.cs create mode 100644 src/slskd/ISharedFileCache.cs create mode 100644 src/slskd/Program.cs create mode 100644 src/slskd/Properties/launchSettings.json create mode 100644 src/slskd/Room.cs create mode 100644 src/slskd/Security/PBKDF2.cs create mode 100644 src/slskd/Security/PassthroughAuthentication.cs create mode 100644 src/slskd/SharedFileCache.cs create mode 100644 src/slskd/Startup.cs create mode 100644 src/slskd/Trackers/BrowseTracker.cs create mode 100644 src/slskd/Trackers/ConversationTracker.cs create mode 100644 src/slskd/Trackers/IBrowseTracker.cs create mode 100644 src/slskd/Trackers/IConversationTracker.cs create mode 100644 src/slskd/Trackers/IRoomTracker.cs create mode 100644 src/slskd/Trackers/ISearchTracker.cs create mode 100644 src/slskd/Trackers/ITransferTracker.cs create mode 100644 src/slskd/Trackers/RoomTracker.cs create mode 100644 src/slskd/Trackers/SearchTracker.cs create mode 100644 src/slskd/Trackers/TransferTracker.cs create mode 100644 src/slskd/slskd.csproj create mode 100644 src/slskd/wwwroot/.gitkeep create mode 100644 src/web/.gitignore create mode 100644 src/web/README.md create mode 100644 src/web/package.json create mode 100644 src/web/public/index.html create mode 100644 src/web/src/components/App.css create mode 100644 src/web/src/components/App.js create mode 100644 src/web/src/components/Browse/Browse.css create mode 100644 src/web/src/components/Browse/Browse.js create mode 100644 src/web/src/components/Browse/Directory.js create mode 100644 src/web/src/components/Browse/DirectoryTree.js create mode 100644 src/web/src/components/Chat/Chat.css create mode 100644 src/web/src/components/Chat/Chat.js create mode 100644 src/web/src/components/Chat/ChatMenu.js create mode 100644 src/web/src/components/Chat/SendMessageModal.js create mode 100644 src/web/src/components/LoginForm.js create mode 100644 src/web/src/components/Rooms/RoomJoinModal.js create mode 100644 src/web/src/components/Rooms/RoomMenu.js create mode 100644 src/web/src/components/Rooms/RoomUserList.js create mode 100644 src/web/src/components/Rooms/Rooms.css create mode 100644 src/web/src/components/Rooms/Rooms.js create mode 100644 src/web/src/components/Search/Response.js create mode 100644 src/web/src/components/Search/Search.css create mode 100644 src/web/src/components/Search/Search.js create mode 100644 src/web/src/components/Shared/FileList.js create mode 100644 src/web/src/components/Shared/PlaceholderSegment.js create mode 100644 src/web/src/components/Transfers/TransferGroup.js create mode 100644 src/web/src/components/Transfers/TransferList.js create mode 100644 src/web/src/components/Transfers/Transfers.js create mode 100644 src/web/src/config.js create mode 100644 src/web/src/index.js create mode 100644 src/web/src/lib/api.js create mode 100644 src/web/src/lib/chat.js create mode 100644 src/web/src/lib/rooms.js create mode 100644 src/web/src/lib/search.js create mode 100644 src/web/src/lib/session.js create mode 100644 src/web/src/lib/transfers.js create mode 100644 src/web/src/lib/user.js create mode 100644 src/web/src/lib/util.js create mode 100644 src/web/yarn.lock diff --git a/.gitignore b/.gitignore index dfcfd56f..360ea127 100644 --- a/.gitignore +++ b/.gitignore @@ -1,350 +1 @@ -## 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/ +.vs diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..e84b35a4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +FROM mcr.microsoft.com/dotnet/aspnet:5.0 + +COPY api/bin/Release/net5.0/publish app/ + +RUN mkdir /var/slsk +RUN mkdir /var/slsk/shared +RUN mkdir /var/slsk/download + +ENV SLSK_OUTPUT_DIR=/var/slsk/download +ENV SLSK_SHARED_DIR=/var/slsk/shared + +ENV ASPNETCORE_URLS=http://+:5000 + +ENTRYPOINT ["dotnet", "app/slskd.dll"] \ No newline at end of file diff --git a/bin/build b/bin/build new file mode 100644 index 00000000..8b3470ad --- /dev/null +++ b/bin/build @@ -0,0 +1,26 @@ +#!/bin/bash +set -e + +# build web +cd web +pwd +npm install +npm run build + +# remove old build, but keep .gitkeep +rm -rf ../api/wwwroot +mkdir ../api/wwwroot +touch ../api/wwwroot/.gitkeep + +# copy new files +cp -r build/* ../api/wwwroot/ + +# publish api + web +cd ../api +pwd +dotnet publish --configuration Release + +# build docker +cd .. +pwd +docker build -t jpdillingham/slsk-web-example:latest . \ No newline at end of file diff --git a/bin/publish b/bin/publish new file mode 100644 index 00000000..c2e2faf6 --- /dev/null +++ b/bin/publish @@ -0,0 +1,10 @@ +#!/bin/bash +set -e + +cd api +pwd + +dotnet publish --configuration Release --self-contained --runtime win-x64 +dotnet publish --configuration Release --self-contained --runtime linux-x64 +dotnet publish --configuration Release --self-contained --runtime linux-arm +dotnet publish --configuration Release --self-contained --runtime osx-x64 \ No newline at end of file diff --git a/bin/run b/bin/run new file mode 100644 index 00000000..24d81890 --- /dev/null +++ b/bin/run @@ -0,0 +1,14 @@ +docker run -i \ + -p 5000:5000 \ + -p 50000:50000 \ + -v $SLSK_OUTPUT_DIR:/var/slsk/download \ + -v $SLSK_SHARED_DIR:/var/slsk/shared \ + -e "SLSK_USERNAME=$SLSK_USERNAME" \ + -e "SLSK_PASSWORD=$SLSK_PASSWORD" \ + -e "SLSK_LISTEN_PORT=50000" \ + -e "SLSK_ENABLE_DNET=true" \ + -e "SLSK_DNET_CHILD_LIMIT=10" \ + -e "SLSK_DIAGNOSTIC=Info" \ + -e "SLSK_CONNECT_TIMEOUT=5000" \ + -e "SLSK_INACTIVITY_TIMEOUT=15000" \ + jpdillingham/slsk-web-example:latest \ No newline at end of file diff --git a/bin/start b/bin/start new file mode 100644 index 00000000..949fa365 --- /dev/null +++ b/bin/start @@ -0,0 +1,16 @@ +docker run -d \ + -p 5000:5000 \ + -p 50000:50000 \ + -v $SLSK_OUTPUT_DIR:/var/slsk/download \ + -v $SLSK_SHARED_DIR:/var/slsk/shared \ + -e "SLSK_USERNAME=$SLSK_USERNAME" \ + -e "SLSK_PASSWORD=$SLSK_PASSWORD" \ + -e "SLSK_LISTEN_PORT=50000" \ + -e "SLSK_ENABLE_DNET=true" \ + -e "SLSK_DNET_CHILD_LIMIT=10" \ + -e "SLSK_DIAGNOSTIC=Info" \ + -e "SLSK_CONNECT_TIMEOUT=5000" \ + -e "SLSK_INACTIVITY_TIMEOUT=15000" \ + --name soulseek \ + --restart always \ + jpdillingham/slsk-web-example:latest \ No newline at end of file diff --git a/slskd.sln b/slskd.sln new file mode 100644 index 00000000..dd3310be --- /dev/null +++ b/slskd.sln @@ -0,0 +1,45 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30804.86 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "bin", "bin", "{6C7C4DA1-0F1A-444C-9946-9996F8D40338}" + ProjectSection(SolutionItems) = preProject + bin\build = bin\build + bin\publish = bin\publish + bin\run = bin\run + bin\start = bin\start + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{5478DBA0-A595-4273-9F9D-3D5E11A8ECE8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "slskd", "src\slskd\slskd.csproj", "{E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CA2A6837-A966-4198-9B62-32D0110CA078}" + ProjectSection(SolutionItems) = preProject + Dockerfile = Dockerfile + LICENSE = LICENSE + README.md = README.md + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC} = {5478DBA0-A595-4273-9F9D-3D5E11A8ECE8} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A793ED59-76F4-4874-846B-2A199C92A48E} + EndGlobalSection +EndGlobal 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; + + /// + /// Conversations + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("1")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ConversationsController : ControllerBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public ConversationsController(ISoulseekClient client, IConversationTracker tracker) + { + Client = client; + Tracker = tracker; + } + + private ISoulseekClient Client { get; } + private IConversationTracker Tracker { get; } + + /// + /// Acknowledges the given message id for the given username. + /// + /// + /// + /// + /// The request completed successfully. + /// + /// A conversation with the specified username, or a message matching the specified id could not be found. + /// + [HttpPut("{username}/{id}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(404)] + public async Task Acknowledge([FromRoute]string username, [FromRoute]int id) + { + Tracker.Conversations.TryGetValue(username, out var conversation); + + if (conversation == default || !conversation.Any(p => p.Id == id)) + { + return NotFound(); + } + + await Client.AcknowledgePrivateMessageAsync(id); + return StatusCode(200); + } + + /// + /// Acknowledges all messages for the given username. + /// + /// + /// + /// The request completed successfully. + /// A conversation with the specified username could not be found. + [HttpPut("{username}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(404)] + public async Task AcknowledgeAll([FromRoute]string username) + { + Tracker.Conversations.TryGetValue(username, out var conversation); + + if (conversation == default) + { + return NotFound(); + } + + var tasks = new List(); + + foreach (var message in conversation.Where(p => !p.Acknowledged)) + { + tasks.Add(Task.Run(async () => + { + await Client.AcknowledgePrivateMessageAsync(message.Id); + message.Acknowledged = true; + })); + } + + await Task.WhenAll(tasks); + return StatusCode(200); + } + + /// + /// Deletes the conversation associated with the given username. + /// + /// + /// The request completed successfully. + /// A conversation with the specified username could not be found. + [HttpDelete("{username}")] + [Authorize] + [ProducesResponseType(404)] + [ProducesResponseType(204)] + public IActionResult Delete([FromRoute]string username) + { + var deleted = Tracker.Conversations.TryRemove(username, out _); + + if (deleted) + { + return StatusCode(204); + } + + return StatusCode(404); + } + + /// + /// Gets all tracked conversations. + /// + /// + /// The request completed successfully. + [HttpGet("")] + [Authorize] + [ProducesResponseType(typeof(Dictionary>), 200)] + public IActionResult GetAll() + { + var response = Tracker.Conversations.ToDictionary( + entry => entry.Key, + entry => entry.Value + .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username)) + .OrderBy(m => m.Timestamp)); + + return Ok(response); + } + + /// + /// Gets the conversation associated with the specified username. + /// + /// The username associated with the desired conversation. + /// + /// The request completed successfully. + /// A matching search was not found. + [HttpGet("{username}")] + [Authorize] + [ProducesResponseType(typeof(List), 200)] + [ProducesResponseType(404)] + public IActionResult GetByUsername([FromRoute]string username) + { + if (Tracker.TryGet(username, out var conversation)) + { + var response = conversation + .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username)) + .OrderBy(m => m.Timestamp); + + return Ok(response); + } + + return NotFound(); + } + + /// + /// Sends a private message to the specified username. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified message is null or empty. + [HttpPost("{username}")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(400)] + public async Task Send([FromRoute]string username, [FromBody]string message) + { + if (string.IsNullOrEmpty(message)) + { + return BadRequest(); + } + + await Client.SendPrivateMessageAsync(username, message); + + Tracker.AddOrUpdate(username, new PrivateMessage() + { + Username = Client.Username, + Timestamp = DateTime.UtcNow, + Message = message, + Acknowledged = true + }); + + return StatusCode(201); + } + } +} \ No newline at end of file diff --git a/src/slskd/Controllers/PublicChatController.cs b/src/slskd/Controllers/PublicChatController.cs 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; + + /// + /// Server + /// + [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; + } + + /// + /// Starts public chat. + /// + /// + [HttpPost] + [Authorize] + public async Task Start() + { + await Client.StartPublicChatAsync(); + return StatusCode(StatusCodes.Status201Created); + } + + /// + /// Stops public chat. + /// + /// + [HttpDelete] + [Authorize] + public async Task Stop() + { + await Client.StopPublicChatAsync(); + return StatusCode(StatusCodes.Status204NoContent); + } + } +} diff --git a/src/slskd/Controllers/RoomsController.cs b/src/slskd/Controllers/RoomsController.cs 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; + + /// + /// Rooms. + /// + [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; } + + /// + /// Gets all rooms. + /// + /// + /// The request completed successfully. + [HttpGet("joined")] + [Authorize] + [ProducesResponseType(typeof(Dictionary>), 200)] + public IActionResult GetAll() + { + return Ok(Tracker.Rooms.Keys); + } + + /// + /// Gets the specified room. + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpGet("joined/{roomName}")] + [Authorize] + [ProducesResponseType(typeof(Room), 200)] + [ProducesResponseType(404)] + public IActionResult GetByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + return Ok(MapRoomToRoomResponse(room)); + } + + return NotFound(); + } + + /// + /// Sends a message to the specified room. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpPost("joined/{roomName}/messages")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task SendMessage([FromRoute]string roomName, [FromBody]string message) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.SendRoomMessageAsync(roomName, message); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// + /// Sets a ticker for the specified room. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpPost("joined/{roomName}/ticker")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task SetTicker([FromRoute] string roomName, [FromBody] string message) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.SetRoomTickerAsync(roomName, message); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// + /// Adds a member to a private room. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpPost("joined/{roomName}/members")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task AddRoomMember([FromRoute]string roomName, [FromBody]string username) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.AddPrivateRoomMemberAsync(roomName, username); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// + /// Gets the current list of users for the specified room. + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpGet("joined/{roomName}/users")] + [Authorize] + [ProducesResponseType(typeof(IList), 200)] + [ProducesResponseType(404)] + public IActionResult GetUsersByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + var response = room.Users + .Select(user => UserDataResponse.FromUserData(user, self: user.Username == Client.Username)); + + return Ok(response); + } + + return NotFound(); + } + + /// + /// Gets the current list of messages for the specified room. + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpGet("joined/{roomName}/messages")] + [Authorize] + [ProducesResponseType(typeof(IList), 200)] + [ProducesResponseType(404)] + public IActionResult GetMessagesByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + var response = room.Messages + .Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == Client.Username)); + + return Ok(response); + } + + return NotFound(); + } + + /// + /// Gets a list of rooms from the server. + /// + /// + [HttpGet("available")] + [Authorize] + [ProducesResponseType(typeof(List), 200)] + public async Task GetRooms() + { + var list = await Client.GetRoomListAsync(); + + var response = new List(); + + response.AddRange(list.Public.Select(r => RoomInfoResponse.FromRoomInfo(r))); + response.AddRange(list.Private.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true))); + response.AddRange(list.Owned.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true, isOwned: true))); + + foreach (var room in response) + { + room.IsModerated = list.ModeratedRoomNames.Contains(room.Name); + } + + return Ok(response); + } + + /// + /// Joins a room. + /// + /// + /// + /// The request completed successfully. + /// The room has already been joined. + [HttpPost("joined/{roomName}")] + [Authorize] + [ProducesResponseType(typeof(Room), 201)] + [ProducesResponseType(304)] + public async Task JoinRoom([FromRoute]string roomName) + { + if (Tracker.Rooms.ContainsKey(roomName)) + { + return StatusCode(StatusCodes.Status304NotModified); + } + + try + { + var roomData = await Client.JoinRoomAsync(roomName); + var room = Room.FromRoomData(roomData); + Tracker.TryAdd(roomName, room); + + return StatusCode(StatusCodes.Status201Created, MapRoomToRoomResponse(room)); + } + catch (Exception ex) + { + if (ex.InnerException is RoomJoinForbiddenException) + { + return StatusCode(StatusCodes.Status403Forbidden, $"The server rejected your request to join {roomName}"); + } + + throw; + } + } + + /// + /// Leaves a room. + /// + /// + /// + /// The request completed successfully. + /// The room has not been joined. + [HttpDelete("joined/{roomName}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public async Task LeaveRoom([FromRoute]string roomName) + { + if (!Tracker.Rooms.ContainsKey(roomName)) + { + return StatusCode(StatusCodes.Status404NotFound); + } + + await Client.LeaveRoomAsync(roomName); + Tracker.TryRemove(roomName); + + return StatusCode(StatusCodes.Status204NoContent); + } + + private RoomResponse MapRoomToRoomResponse(Room room) + { + bool IsSelf(string username) + { + return username == Client.Username; + } + + var response = RoomResponse.FromRoom(room); + response.Users = room.Users + .Select(user => UserDataResponse.FromUserData(user, self: IsSelf(user.Username))); + response.Messages = room.Messages + .Select(message => RoomMessageResponse.FromRoomMessage(message, self: IsSelf(message.Username))); + + return response; + } + } +} \ No newline at end of file diff --git a/src/slskd/Controllers/SearchesController.cs b/src/slskd/Controllers/SearchesController.cs 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; + + /// + /// Search + /// + [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; } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + public SearchesController(ISoulseekClient client, ISearchTracker tracker) + { + Client = client; + Tracker = tracker; + } + + /// + /// Performs a search for the specified . + /// + /// The search request. + /// + /// The search completed successfully. + /// The specified was malformed. + /// The search terminated abnormally. + [HttpPost("")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(400)] + [ProducesResponseType(typeof(string), 500)] + public async Task Post([FromBody]SearchRequest request) + { + var id = request.Id ?? Guid.NewGuid(); + + var options = request.ToSearchOptions( + responseReceived: (e) => Tracker.AddOrUpdate(id, e), + stateChanged: (e) => Tracker.AddOrUpdate(id, e)); + + var results = new ConcurrentBag(); + + var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1)); + + try + { + await Client.SearchAsync(SearchQuery.FromText(searchText), (r) => results.Add(r), SearchScope.Network, request.Token, options); + return Ok(results); + } + catch (Exception ex) + { + return StatusCode(500, $"Search terminated abnormally: {ex.Message}"); + } + finally + { + results = null; + Tracker.TryRemove(id); + } + } + + /// + /// Gets the state of the search corresponding to the specified . + /// + /// The unique id of the search. + /// + /// The request completed successfully. + /// A matching search was not found. + [HttpGet("{id}")] + [Authorize] + [ProducesResponseType(typeof(Search), 200)] + [ProducesResponseType(404)] + public IActionResult GetById([FromRoute]Guid id) + { + Tracker.Searches.TryGetValue(id, out var search); + + if (search == default) + { + return NotFound(); + } + + return Ok(search); + } + } +} diff --git a/src/slskd/Controllers/ServerController.cs b/src/slskd/Controllers/ServerController.cs 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; + + /// + /// Server + /// + [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; + } + + /// + /// Disconnects the client. + /// + /// + /// + [HttpDelete] + [Authorize] + public IActionResult Disconnect([FromBody]string message) + { + Client.Disconnect(message); + return NoContent(); + } + + /// + /// Connects the client. + /// + /// + /// + [HttpPost] + [Authorize] + public async Task Connect([FromBody]ConnectRequest req) + { + var addr = !string.IsNullOrEmpty(req.Address); + var port = req.Port.HasValue; + var un = !string.IsNullOrEmpty(req.Username); + var pw = !string.IsNullOrEmpty(req.Password); + + if (addr && port && un && pw) + { + await Client.ConnectAsync(req.Address, req.Port.Value, req.Username, req.Password); + return Ok(); + } + + if (addr && port && !un && !pw) + { + await Client.ConnectAsync(req.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; + + /// + /// Session + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("1")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class SessionController : ControllerBase + { + public SessionController() + { + } + + /// + /// Checks whether security is enabled. + /// + /// + /// True if security is enabled, false otherwise. + [HttpGet] + [Route("enabled")] + [AllowAnonymous] + [ProducesResponseType(typeof(bool), 200)] + public IActionResult Enabled() + { + return Ok(Startup.EnableSecurity); + } + + /// + /// Checks whether the provided authentication is valid. + /// + /// + /// This is a no-op provided so that the application can test for an expired token on load. + /// + /// + /// The authentication is valid. + /// The authentication is is invalid. + [HttpGet] + [Route("")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(401)] + public IActionResult Check() + { + return Ok(); + } + + /// + /// Logs in. + /// + /// + /// + /// Login was successful. + /// Bad request. + /// Login failed. + [HttpPost] + [Route("")] + [AllowAnonymous] + [ProducesResponseType(typeof(TokenResponse), 200)] + [ProducesResponseType(400)] + [ProducesResponseType(401)] + [ProducesResponseType(typeof(string), 500)] + public IActionResult Login([FromBody]LoginRequest login) + { + if (login == default) + { + return BadRequest(); + } + + if (string.IsNullOrWhiteSpace(login.Username) || string.IsNullOrWhiteSpace(login.Password)) + { + return BadRequest("Username and/or Password missing or invalid"); + } + + 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() + { + 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; + + /// + /// Transfers + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("1")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class TransfersController : ControllerBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + public TransfersController(IConfiguration configuration, ISoulseekClient client, ITransferTracker tracker) + { + OutputDirectory = configuration.GetValue("OUTPUT_DIR"); + Client = client; + Tracker = tracker; + } + + private ISoulseekClient Client { get; } + private string OutputDirectory { get; } + private ITransferTracker Tracker { get; } + + /// + /// Cancels the specified download. + /// + /// The username of the download source. + /// The id of the download. + /// A value indicating whether the tracked download should be removed after cancellation. + /// + /// The download was cancelled successfully. + /// The specified download was not found. + [HttpDelete("downloads/{username}/{id}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public IActionResult CancelDownload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) + { + return CancelTransfer(TransferDirection.Download, username, id, remove); + } + + /// + /// Cancels the specified upload. + /// + /// The username of the upload destination. + /// The id of the upload. + /// A value indicating whether the tracked upload should be removed after cancellation. + /// + /// The upload was cancelled successfully. + /// The specified upload was not found. + [HttpDelete("uploads/{username}/{id}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public IActionResult CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) + { + return CancelTransfer(TransferDirection.Upload, username, id, remove); + } + + /// + /// Enqueues the specified download. + /// + /// The username of the download source. + /// The download request. + /// + /// The download was successfully enqueued. + /// The download was rejected. + /// An unexpected error was encountered. + [HttpPost("downloads/{username}")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 500)] + public async Task Enqueue([FromRoute, Required]string username, [FromBody]QueueDownloadRequest request) + { + try + { + var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var stream = GetLocalFileStream(request.Filename, OutputDirectory); + + var cts = new CancellationTokenSource(); + + var downloadTask = Client.DownloadAsync(username, request.Filename, stream, request.Size, 0, request.Token, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) => + { + Tracker.AddOrUpdate(e, cts); + + if (e.Transfer.State == TransferStates.Queued || e.Transfer.State == TransferStates.Initializing) + { + waitUntilEnqueue.TrySetResult(true); + } + }, progressUpdated: (e) => Tracker.AddOrUpdate(e, cts)), cts.Token); + + // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the + // downloadTask throws due to an error prior to successfully queueing. + var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask); + + if (task == downloadTask && downloadTask.Exception is AggregateException) + { + var rejected = downloadTask.Exception?.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); + + if (rejected.Any()) + { + return StatusCode(403, rejected.First().Message); + } + + return StatusCode(500, downloadTask.Exception.Message); + } + + // if it didn't throw, just return ok. the download will continue waiting in the background. + return StatusCode(201); + } + catch (Exception ex) + { + return StatusCode(500, ex.Message); + } + } + + /// + /// Gets all downloads. + /// + /// + /// The request completed successfully. + [HttpGet("downloads")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetDownloads() + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Download) + .ToMap()); + } + + /// + /// Gets all downloads for the specified username. + /// + /// + /// + /// The request completed successfully. + [HttpGet("downloads/{username}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetDownloads([FromRoute, Required]string username) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Download) + .FromUser(username) + .ToMap()); + } + + /// + /// Gets the downlaod for the specified username matching the specified filename, and requests + /// the current place in the remote queue of the specified download. + /// + /// The username of the download source. + /// The id of the download. + /// + /// The request completed successfully. + /// The specified download was not found. + [HttpGet("downloads/{username}/{id}")] + [Authorize] + [ProducesResponseType(typeof(DTO.Transfer), 200)] + [ProducesResponseType(404)] + public async Task GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id) + { + var record = Tracker.Transfers.WithDirection(TransferDirection.Download).FromUser(username).WithId(id); + + if (record == default) + { + return NotFound(); + } + + record.Transfer.PlaceInQueue = await Client.GetDownloadPlaceInQueueAsync(username, record.Transfer.Filename); + return Ok(record.Transfer); + } + + /// + /// Gets all uploads. + /// + /// + /// The request completed successfully. + [HttpGet("uploads")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads() + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .ToMap()); + } + + /// + /// Gets all uploads for the specified username. + /// + /// + /// + /// The request completed successfully. + [HttpGet("uploads/{username}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads([FromRoute, Required]string username) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .FromUser(username) + .ToMap()); + } + + /// + /// Gets the upload for the specified username matching the specified filename. + /// + /// The username of the upload destination. + /// The id of the upload. + /// + /// The request completed successfully. + [HttpGet("uploads/{username}/{id}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads([FromRoute, Required]string username, [FromRoute, Required]string id) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .FromUser(username) + .WithId(id).Transfer); + } + + private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) + { + var localFilename = remoteFilename.ToLocalOSPath(); + var path = $"{saveDirectory}{Path.DirectorySeparatorChar}{Path.GetDirectoryName(localFilename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(localFilename)), "")}"; + + if (!System.IO.Directory.Exists(path)) + { + System.IO.Directory.CreateDirectory(path); + } + + var sanitizedFilename = Path.GetFileName(localFilename); + + foreach (var c in Path.GetInvalidFileNameChars()) + { + sanitizedFilename = sanitizedFilename.Replace(c, '_'); + } + + localFilename = Path.Combine(path, sanitizedFilename); + + return new FileStream(localFilename, FileMode.Create); + } + + private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false) + { + if (Tracker.TryGet(direction, username, id, out var transfer)) + { + transfer.CancellationTokenSource.Cancel(); + + if (remove) + { + Tracker.TryRemove(direction, username, id); + } + + return NoContent(); + } + + return NotFound(); + } + } +} \ No newline at end of file diff --git a/src/slskd/Controllers/UserController.cs b/src/slskd/Controllers/UserController.cs 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; + + /// + /// Users + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("1")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class UserController : ControllerBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public UserController(ISoulseekClient client, IBrowseTracker browseTracker) + { + Client = client; + BrowseTracker = browseTracker; + } + + private ISoulseekClient Client { get; } + private IBrowseTracker BrowseTracker { get; } + + /// + /// Retrieves the address of the specified . + /// + /// The username of the user. + /// + /// The request completed successfully. + [HttpGet("{username}/address")] + [Authorize] + [ProducesResponseType(typeof(UserAddress), 200)] + [ProducesResponseType(404)] + public async Task Address([FromRoute, Required]string username) + { + try + { + var endpoint = await Client.GetUserEndPointAsync(username); + return Ok(new UserAddress() { IPAddress = endpoint.Address.ToString(), Port = endpoint.Port }); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// + /// Retrieves the files shared by the specified . + /// + /// The username of the user. + /// + [HttpGet("{username}/browse")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(404)] + public async Task Browse([FromRoute, Required]string username) + { + try + { + var result = await Client.BrowseAsync(username); + + _ = Task.Run(async () => + { + await Task.Delay(5000); + BrowseTracker.TryRemove(username); + }); + + return Ok(result); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// + /// Retrieves the status of the current browse operation for the specified , if any. + /// + /// The username of the user. + /// + [HttpGet("{username}/browse/status")] + [Authorize] + [ProducesResponseType(typeof(decimal), 200)] + [ProducesResponseType(404)] + public IActionResult BrowseStatus([FromRoute, Required]string username) + { + if (BrowseTracker.TryGet(username, out var progress)) + { + return Ok(progress); + } + + return NotFound(); + } + + /// + /// Retrieves information about the specified . + /// + /// The username of the user. + /// + [HttpGet("{username}/info")] + [Authorize] + [ProducesResponseType(typeof(UserInfo), 200)] + [ProducesResponseType(404)] + public async Task Info([FromRoute, Required]string username) + { + try + { + var response = await Client.GetUserInfoAsync(username); + return Ok(response); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// + /// Retrieves status for the specified . + /// + /// The username of the user. + /// + [HttpGet("{username}/status")] + [Authorize] + [ProducesResponseType(typeof(UserStatus), 200)] + [ProducesResponseType(404)] + public async Task Status([FromRoute, Required]string username) + { + try + { + var response = await Client.GetUserStatusAsync(username); + return Ok(response); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/src/slskd/DTO/ConnectRequest.cs b/src/slskd/DTO/ConnectRequest.cs 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 + { + /// + /// A value indicating whether the message has been acknowledged. + /// + public bool Acknowledged { get; set; } = false; + + /// + /// The unique message id, used to acknowledge receipt. + /// + public int Id { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// A value indicating whether the message was replayed. + /// + public bool Replayed { get; set; } + + /// + /// The UTC timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + /// + /// A value indicating whether this message was sent by the currently logged in user. + /// + public bool? Self { get; set; } + + public static PrivateMessageResponse FromPrivateMessage(PrivateMessage privateMessage, bool self = false) + { + return new PrivateMessageResponse() + { + Id = privateMessage.Id, + Timestamp = privateMessage.Timestamp, + Username = privateMessage.Username, + Message = privateMessage.Message, + Acknowledged = privateMessage.Acknowledged, + Replayed = privateMessage.Replayed, + Self = self ? self: (bool?)null + }; + } + } +} diff --git a/src/slskd/DTO/QueueDownloadRequest.cs b/src/slskd/DTO/QueueDownloadRequest.cs 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 + { + /// + /// Gets or sets the filename to download. + /// + public string Filename { get; set; } + + /// + /// Gets or sets the size of the file. + /// + public long? Size { get; set; } + + /// + /// Gets or sets the optional transfer token. + /// + public int? Token { get; set; } + } +} diff --git a/src/slskd/DTO/RoomInfoResponse.cs b/src/slskd/DTO/RoomInfoResponse.cs 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 + { + /// + /// Gets the room name. + /// + public string Name { get; init; } + + /// + /// Gets the number of users in the room. + /// + public int UserCount { get; init; } + + /// + /// Gets a value indicating whether the room is private. + /// + public bool IsPrivate { get; init; } + + /// + /// Gets a value indicating whether the room is owned by the currently logged in user. + /// + public bool IsOwned { get; init; } + + /// + /// Gets a value indicating whether the room is moderated by the currently logged in user. + /// + public bool IsModerated { get; set; } + + public static RoomInfoResponse FromRoomInfo(RoomInfo info, bool isPrivate = false, bool isOwned = false) + { + return new RoomInfoResponse() + { + Name = info.Name, + UserCount = info.UserCount, + IsPrivate = isPrivate, + IsOwned = isOwned + }; + } + } +} diff --git a/src/slskd/DTO/RoomMessageResponse.cs b/src/slskd/DTO/RoomMessageResponse.cs 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 + { + /// + /// The timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// The room to which the message pertains. + /// + public string RoomName { get; set; } + + /// + /// A value indicating whether this user data belongs to the currently logged in user. + /// + public bool? Self { get; set; } + + public static RoomMessageResponse FromRoomMessage(RoomMessage roomMessage, bool self = false) + { + return new RoomMessageResponse() + { + Timestamp = roomMessage.Timestamp, + Username = roomMessage.Username, + Message = roomMessage.Message, + RoomName = roomMessage.RoomName, + Self = self ? self : (bool?)null + }; + } + } +} diff --git a/src/slskd/DTO/RoomResponse.cs b/src/slskd/DTO/RoomResponse.cs 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 + { + /// + /// The room name. + /// + public string Name { get; set; } + + /// + /// A value indicating whether the room is private. + /// + public bool IsPrivate { get; set; } + + /// + /// The number of operators in the room, if private. + /// + public int? OperatorCount { get; set; } + + /// + /// The operators in the room, if private. + /// + public IList Operators { get; set; } + + /// + /// The owner of the room, if private. + /// + public string Owner { get; set; } + + /// + /// The list of users in the room. + /// + public IEnumerable Users { get; set; } = new List(); + + /// + /// The list of messages. + /// + public IEnumerable Messages { get; set; } = new List(); + + public static RoomResponse FromRoom(Room room) + { + return new RoomResponse() + { + Name = room.Name, + IsPrivate = room.IsPrivate, + OperatorCount = room.OperatorCount, + Operators = room.Operators.ToList(), + Owner = room.Owner, + Users = new List(), + Messages = new List() + }; + } + } +} diff --git a/src/slskd/DTO/SearchRequest.cs b/src/slskd/DTO/SearchRequest.cs 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 +{ + /// + /// A search request. + /// + public class SearchRequest + { + /// + /// Gets or sets the unique search identifier + /// + public Guid? Id { get; set; } + + /// + /// Gets or sets the maximum number of file results to accept before the search is considered complete. (Default = 10,000). + /// + public int? FileLimit { get; set; } + + /// + /// Gets or sets a value indicating whether responses are to be filtered. (Default = true). + /// + public bool? FilterResponses { get; set; } + + /// + /// Gets or sets the maximum queue depth a peer may have in order for a response to be processed. (Default = 1000000). + /// + public int? MaximumPeerQueueLength { get; set; } + + /// + /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed. + /// (Default = 0). + /// + public int? MinimumPeerFreeUploadSlots { get; set; } + + /// + /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0). + /// + public int? MinimumPeerUploadSpeed { get; set; } + + /// + /// Gets or sets the minimum number of files a response must contain in order to be processed. (Default = 1). + /// + public int? MinimumResponseFileCount { get; set; } + + /// + /// Gets or sets the maximum number of search results to accept before the search is considered complete. (Default = 100). + /// + public int? ResponseLimit { get; set; } + + /// + /// Gets or sets the search text. + /// + public string SearchText { get; set; } + + /// + /// Gets or sets the search timeout value, in seconds, used to determine when the search is complete. (Default = 15). + /// + /// The timeout duration is from the time of the last response. + public int? SearchTimeout { get; set; } + + /// + /// Gets or sets the search token. + /// + public int? Token { get; set; } + + /// + /// Maps to a new instance of . + /// + /// + /// + /// + /// + /// + public SearchOptions ToSearchOptions( + Func responseFilter = null, + Func fileFilter = null, + Action stateChanged = null, + Action responseReceived = null) + { + var def = new SearchOptions(); + + return new SearchOptions( + searchTimeout: SearchTimeout ?? def.SearchTimeout, + responseLimit: ResponseLimit ?? def.ResponseLimit, + fileLimit: FileLimit ?? def.FileLimit, + filterResponses: FilterResponses ?? def.FilterResponses, + minimumResponseFileCount: MinimumResponseFileCount ?? def.MinimumResponseFileCount, + minimumPeerFreeUploadSlots: MinimumPeerFreeUploadSlots ?? def.MinimumPeerFreeUploadSlots, + maximumPeerQueueLength: MaximumPeerQueueLength ?? def.MaximumPeerQueueLength, + minimumPeerUploadSpeed: MinimumPeerUploadSpeed ?? def.MinimumPeerUploadSpeed, + responseFilter: responseFilter, + fileFilter: fileFilter, + responseReceived: responseReceived, + stateChanged: stateChanged); + } + } +} \ No newline at end of file diff --git a/src/slskd/DTO/TokenResponse.cs b/src/slskd/DTO/TokenResponse.cs 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; } + + /// + /// Gets the Access Token string. + /// + public string Token => new JwtSecurityTokenHandler().WriteToken(JwtSecurityToken); + + /// + /// Gets the time at which the Access Token expires. + /// + public long Expires => ((DateTimeOffset)JwtSecurityToken.ValidTo).ToUnixTimeSeconds(); + + /// + /// Gets the time at which the Access Token was issued. + /// + public long Issued => ((DateTimeOffset)JwtSecurityToken.ValidFrom).ToUnixTimeSeconds(); + + /// + /// Gets the value of the Name claim from the Access Token. + /// + public string Name => JwtSecurityToken.Claims.Where(c => c.Type == ClaimTypes.Name).SingleOrDefault().Value; + + /// + /// Gets the value of the Not Before claim from the Access Token. + /// + public long NotBefore => long.Parse(JwtSecurityToken.Claims.Where(c => c.Type == "nbf").SingleOrDefault().Value); + + /// + /// Gets the Token type. + /// + public string TokenType => JwtBearerDefaults.AuthenticationScheme; + } +} \ No newline at end of file diff --git a/src/slskd/DTO/Transfer.cs b/src/slskd/DTO/Transfer.cs 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; + + /// + /// A single file transfer. + /// + public class Transfer + { + /// + /// Gets the current average transfer speed. + /// + public double AverageSpeed { get; set; } + + /// + /// Gets the number of remaining bytes to be transferred. + /// + public long BytesRemaining { get; set; } + + /// + /// Gets the total number of bytes transferred. + /// + public long BytesTransferred { get; set; } + + /// + /// Gets the transfer direction. + /// + public TransferDirection Direction { get; set; } + + /// + /// Gets the current duration of the transfer, if it has been started. + /// + public double? ElapsedTime { get; set; } + + /// + /// Gets the UTC time at which the transfer transitioned into the state. + /// + public DateTime? EndTime { get; set; } + + /// + /// Gets the filename of the file to be transferred. + /// + public string Filename { get; set; } + + /// + /// Gets the transfer id. + /// + public string Id => Filename.Sha1(); + + /// + /// Gets the ip endpoint of the remote transfer connection, if one has been established. + /// + public IPEndPoint IPEndPoint { get; set; } + + /// + /// Gets the current progress in percent. + /// + public double PercentComplete { get; set; } + + /// + /// Gets the current place in queue, if it has been fetched. + /// + public int? PlaceInQueue { get; set; } + + /// + /// Gets the projected remaining duration of the transfer. + /// + public double? RemainingTime { get; set; } + + /// + /// Gets the remote unique token for the transfer. + /// + public int? RemoteToken { get; set; } + + /// + /// Gets the size of the file to be transferred, in bytes. + /// + public long Size { get; set; } + + /// + /// Gets the starting offset of the transfer, in bytes. + /// + public long StartOffset { get; set; } + + /// + /// Gets the UTC time at which the transfer transitioned into the state. + /// + public DateTime? StartTime { get; set; } + + /// + /// Gets the state of the transfer. + /// + public TransferStates State { get; set; } + + /// + /// Gets the unique token for the transfer. + /// + public int Token { get; set; } + + /// + /// Gets the username of the peer to or from which the file is to be transferred. + /// + public string Username { get; set; } + + public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer) + { + return new Transfer() + { + AverageSpeed = transfer.AverageSpeed, + BytesRemaining = transfer.BytesRemaining, + BytesTransferred = transfer.BytesTransferred, + Direction = transfer.Direction, + ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds, + EndTime = transfer.EndTime, + Filename = transfer.Filename, + IPEndPoint = transfer.IPEndPoint, + PercentComplete = transfer.PercentComplete, + RemainingTime = transfer.RemainingTime?.TotalMilliseconds, + RemoteToken = transfer.RemoteToken, + Size = transfer.Size, + StartOffset = transfer.StartOffset, + StartTime = transfer.StartTime, + State = transfer.State, + Token = transfer.Token, + Username = transfer.Username + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/DTO/UserAddress.cs b/src/slskd/DTO/UserAddress.cs new file mode 100644 index 00000000..1a69bf7f --- /dev/null +++ b/src/slskd/DTO/UserAddress.cs @@ -0,0 +1,18 @@ +namespace slskd.DTO +{ + /// + /// A user's IP address and port. + /// + public class UserAddress + { + /// + /// Gets or sets the IP address. + /// + public string IPAddress { get; set; } + + /// + /// Gets or sets the port. + /// + public int Port { get; set; } + } +} diff --git a/src/slskd/DTO/UserDataResponse.cs b/src/slskd/DTO/UserDataResponse.cs 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 + { + /// + /// The average upload speed of the user. + /// + public int AverageSpeed { get; set; } + + /// + /// The user's country code, if provided. + /// + public string CountryCode { get; set; } + + /// + /// The number of directories shared by the user. + /// + public int DirectoryCount { get; set; } + + /// + /// The number of active user downloads. + /// + public long DownloadCount { get; set; } + + /// + /// The number of files shared by the user. + /// + public int FileCount { get; set; } + + /// + /// A value indicating whether this user data belongs to the currently logged in user. + /// + public bool? Self { get; set; } + + /// + /// The number of the user's free download slots, if provided. + /// + public int? SlotsFree { get; set; } + + /// + /// The status of the user (0 = offline, 1 = away, 2 = online). + /// + public UserPresence Status { get; set; } + + /// + /// The username of the user. + /// + public string Username { get; set; } + + public static UserDataResponse FromUserData(UserData userData, bool self = false) + { + return new UserDataResponse() + { + AverageSpeed = userData.AverageSpeed, + CountryCode = userData.CountryCode, + DirectoryCount = userData.DirectoryCount, + DownloadCount = userData.DownloadCount, + FileCount = userData.FileCount, + SlotsFree = userData.SlotsFree, + Status = userData.Status, + Username = userData.Username, + Self = self ? self : (bool?)null + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/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; + + /// + /// A private message. + /// + public class PrivateMessage + { + /// + /// A value indicating whether the message has been acknowledged. + /// + public bool Acknowledged { get; set; } = false; + + /// + /// The unique message id, used to acknowledge receipt. + /// + public int Id { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// A value indicating whether the message was replayed. + /// + public bool Replayed { get; set; } + + /// + /// The UTC timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + 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; + + /// + /// A message sent to a room. + /// + public class RoomMessage + { + /// + /// The timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// The room to which the message pertains. + /// + public string RoomName { get; set; } + + 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; + + /// + /// Extensions. + /// + public static class Extensions + { + /// + /// Converts the given path to the local format (normalizes path separators). + /// + /// + /// + public static string ToLocalOSPath(this string path) + { + return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); + } + + /// + /// Returns the directory from the given path, regardless of separator format. + /// + /// + /// + 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)); + } + + /// + /// Returns the SHA1 hash of the given string. + /// + /// + /// + public static string Sha1(this string str) + { + using (var sha1 = new SHA1Managed()) + { + return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", ""); + } + } + + /// + /// Formats byte to nearest size (KB, MB, etc.) + /// + /// + /// + /// + 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 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(); + } +} 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 + { + /// + /// The room name. + /// + public string Name { get; set; } + + /// + /// A value indicating whether the room is private. + /// + public bool IsPrivate { get; set; } + + /// + /// The number of operators in the room, if private. + /// + public int? OperatorCount { get; set; } + + /// + /// The operators in the room, if private. + /// + public IList Operators { get; set; } + + /// + /// The owner of the room, if private. + /// + public string Owner { get; set; } + + /// + /// The list of users in the room. + /// + public IList Users { get; set; } = new List(); + + /// + /// The list of messages. + /// + public IList Messages { get; set; } = new List(); + + 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() + }; + } + } +} 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; + + /// + /// PBKDF2/RFC 2898 implementation + /// + public static class PBKDF2 + { + /// + /// Gets a 256 bit (32 byte) key derived from the specified using PBKDF2/RFC 2898 + /// + /// + /// + 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 + { + public PassthroughAuthenticationHandler(IOptionsMonitor optionsMonitor, ILoggerFactory logger, UrlEncoder urlEncoder, ISystemClock systemClock) + : base(optionsMonitor, logger, urlEncoder, systemClock) + { + } + + protected override Task 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; + + /// + /// Caches shared files. + /// + public class SharedFileCache : ISharedFileCache + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public SharedFileCache(string directory, long ttl) + { + Directory = directory; + TTL = ttl; + } + + public string Directory { get; } + private Dictionary Files { get; set; } + public DateTime? LastFill { get; set; } + private SqliteConnection SQLite { get; set; } + private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); + public long TTL { get; } + + /// + /// Scans the configured and fills the cache. + /// + 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; + } + + /// + /// Searches the cache for files matching the specified . + /// + /// + /// + public IEnumerable 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 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(); + 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(); + } + 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("USERNAME"); + Password = Configuration.GetValue("PASSWORD"); + BasePath = Configuration.GetValue("BASE_PATH"); + WebRoot = Configuration.GetValue("WEB_ROOT"); + ListenPort = Configuration.GetValue("LISTEN_PORT", 50000); + OutputDirectory = Configuration.GetValue("OUTPUT_DIR"); + SharedDirectory = Configuration.GetValue("SHARED_DIR"); + SharedCacheTTL = Configuration.GetValue("SHARED_CACHE_TTL", 3600000); // 1 hour + EnableDistributedNetwork = Configuration.GetValue("ENABLE_DNET", true); + DistributedChildLimit = Configuration.GetValue("DNET_CHILD_LIMIT", 10); + DiagnosticLevel = Configuration.GetValue("DIAGNOSTIC", DiagnosticLevel.Info); + ConnectTimeout = Configuration.GetValue("CONNECT_TIMEOUT", 5000); + InactivityTimeout = Configuration.GetValue("INACTIVITY_TIMEOUT", 15000); + EnableSecurity = Configuration.GetValue("ENABLE_SECURITY", true); + SecurityTokenTTL = Configuration.GetValue("SECURITY_TOKEN_TTL", 604800000); // 7 days + RoomMessageLimit = Configuration.GetValue("ROOM_MESSAGE_LIMIT", 250); + ReadBufferSize = Configuration.GetValue("READ_BUFFER_SIZE", 16384); + WriteBufferSize = Configuration.GetValue("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(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(serviceProvider => Client); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(_ => 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."); + } + + /// + /// Creates and returns a object in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// A Task resolving the UserInfo instance. + private Task 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); + } + + /// + /// Creates and returns an of in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// A Task resolving an IEnumerable of Soulseek.Directory. + private Task 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)); + } + + /// + /// Creates and returns a in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// The unique token for the request, supplied by the requesting user. + /// The requested directory. + /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. + private Task 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); + } + + /// + /// Invoked upon a remote request to download a file. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// The filename of the requested file. + /// (for example purposes) the ITransferTracker used to track progress. + /// A Task representing the asynchronous operation. + /// Thrown when the download is rejected. The Exception message will be passed to the remote user. + /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for security reasons. + 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; + } + + /// + /// Creates and returns a in response to the given . + /// + /// The username of the requesting user. + /// The search token. + /// The search query. + /// A Task resolving a SearchResponse, or null. + private Task SearchResponseResolver(string username, int token, SearchQuery query) + { + var defaultResponse = Task.FromResult(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(null); + } + + class IPAddressConverter : JsonConverter + { + 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; + + /// + /// Tracks browse operations. + /// + public class BrowseTracker : IBrowseTracker + { + /// + /// Tracked browse operations. + /// + public ConcurrentDictionary Browses { get; } = new ConcurrentDictionary(); + + /// + /// Adds or updates a tracked browse operation. + /// + /// + /// + public void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress) + => Browses.AddOrUpdate(username, progress, (user, oldprogress) => progress); + + /// + /// Removes a tracked browse operation for the specified user. + /// + /// + public void TryRemove(string username) + => Browses.TryRemove(username, out _); + + /// + /// Gets the browse progress for the specified user. + /// + /// + /// + /// + 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; + + /// + /// Tracks private message conversations. + /// + public class ConversationTracker : IConversationTracker + { + /// + /// Tracked private message conversations. + /// + public ConcurrentDictionary> Conversations { get; } = new ConcurrentDictionary>(); + + /// + /// Adds a private message conversation and appends the specified , or just appends the + /// message if the conversation exists. + /// + /// + /// + public void AddOrUpdate(string username, PrivateMessage message) + { + Conversations.AddOrUpdate(username, new List() { message }, (_, messageList) => + { + messageList.Add(message); + return messageList; + }); + } + + /// + /// Returns the list of private messages for the specified , if any exist. + /// + /// + /// + /// + public bool TryGet(string username, out IList messages) => Conversations.TryGetValue(username, out messages); + + /// + /// Removes a tracked private message conversation for the specified user. + /// + /// + 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; + + /// + /// Tracks browse operations. + /// + public interface IBrowseTracker + { + /// + /// Tracked browse operations. + /// + ConcurrentDictionary Browses { get; } + + /// + /// Adds or updates a tracked browse operation. + /// + /// + /// + void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress); + + /// + /// Removes a tracked browse operation for the specified user. + /// + /// + void TryRemove(string username); + + /// + /// Gets the browse progress for the specified user. + /// + /// + /// + /// + 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; + + /// + /// Tracks private message conversations. + /// + public interface IConversationTracker + { + /// + /// Tracked private message conversations. + /// + ConcurrentDictionary> Conversations { get; } + + /// + /// Adds a private message conversation and appends the specified , or just appends the + /// message if the conversation exists. + /// + /// + /// + void AddOrUpdate(string username, PrivateMessage message); + + /// + /// Returns the list of private messages for the specified , if any exist. + /// + /// + /// + /// + bool TryGet(string username, out IList messages); + + /// + /// Removes a tracked private message conversation for the specified user. + /// + /// + 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; + + /// + /// Tracks rooms. + /// + public interface IRoomTracker + { + /// + /// Tracked rooms. + /// + ConcurrentDictionary Rooms { get; } + + /// + /// Adds a room and appends the specified , or just appends the message if the room exists. + /// + /// + /// + void AddOrUpdateMessage(string roomName, RoomMessage message); + + /// + /// Adds the specified room to the tracker + /// + /// + /// + void TryAdd(string roomName, Room room); + + /// + /// Adds the specified to the specified room. + /// + /// + /// + void TryAddUser(string roomName, UserData userData); + + /// + /// Returns the list of messages for the specified , if it is tracked. + /// + /// + /// + /// + bool TryGet(string roomName, out Room room); + + /// + /// Removes a tracked room. + /// + /// + void TryRemove(string roomName); + + /// + /// Removes the specified from the specified room. + /// + /// + /// + 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; + + /// + /// Tracks active searches. + /// + public interface ISearchTracker + { + /// + /// Gets active searches. + /// + ConcurrentDictionary Searches { get; } + + /// + /// Adds or updates a tracked search. + /// + /// + /// + void AddOrUpdate(Guid id, SearchEventArgs args); + + /// + /// Removes all tracked searches. + /// + void Clear(); + + /// + /// Removes a tracked search. + /// + /// + 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; + + /// + /// Tracks transfers. + /// + public interface ITransferTracker + { + /// + /// Tracked transfers. + /// + ConcurrentDictionary>> Transfers { get; } + + /// + /// Adds or updates a tracked transfer. + /// + /// + /// + void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource); + + /// + /// Removes a tracked transfer. + /// + /// Omitting an id will remove ALL transfers associated with the specified username. + void TryRemove(TransferDirection direction, string username, string id = null); + + /// + /// Gets the specified transfer. + /// + /// + /// + /// + /// + /// + 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; + + /// + /// Tracks rooms. + /// + public class RoomTracker : IRoomTracker + { + /// + /// Initializes a new instance of the class. + /// + /// + public RoomTracker(int messageLimit = 25) + { + MessageLimit = messageLimit; + } + + /// + /// Tracked rooms. + /// + public ConcurrentDictionary Rooms { get; } = new ConcurrentDictionary(); + + private int MessageLimit { get; } + + /// + /// Adds a room and appends the specified , or just appends the message if the room exists. + /// + /// + /// + public void AddOrUpdateMessage(string roomName, RoomMessage message) + { + Rooms.AddOrUpdate(roomName, new Room() { Messages = new List() { message } }, (_, room) => + { + if (room.Messages.Count >= MessageLimit) + { + room.Messages = room.Messages.TakeLast(MessageLimit - 1).ToList(); + } + + room.Messages.Add(message); + return room; + }); + } + + /// + /// Adds the specified room to the tracker + /// + /// + /// + public void TryAdd(string roomName, Room room) => Rooms.TryAdd(roomName, room); + + /// + /// Adds the specified to the specified room. + /// + /// + /// + public void TryAddUser(string roomName, UserData userData) + { + if (Rooms.TryGetValue(roomName, out var room)) + { + room.Users.Add(userData); + } + } + + /// + /// Removes a tracked room. + /// + /// + /// + public bool TryGet(string roomName, out Room room) => Rooms.TryGetValue(roomName, out room); + + /// + /// Returns the list of messages for the specified , if it is tracked. + /// + /// + /// + public void TryRemove(string roomName) => Rooms.TryRemove(roomName, out _); + + /// + /// Removes the specified from the specified room. + /// + /// + /// + 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; + + /// + /// Tracks active searches. + /// + public class SearchTracker : ISearchTracker + { + /// + /// Gets active searches. + /// + public ConcurrentDictionary Searches { get; private set; } = + new ConcurrentDictionary(); + + /// + /// Adds or updates a tracked search. + /// + /// + /// + public void AddOrUpdate(Guid id, SearchEventArgs args) + { + Searches.AddOrUpdate(id, args.Search, (token, search) => args.Search); + } + + /// + /// Removes all tracked searches. + /// + public void Clear() + { + Searches.Clear(); + } + + /// + /// Removes a tracked search. + /// + /// + 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; + + /// + /// Transfer extensions. + /// + public static class TransferTrackerExtensions + { + /// + /// Filters a Transfer collection by direction. + /// + /// + /// + /// + public static ConcurrentDictionary> WithDirection( + this ConcurrentDictionary>> allTransfers, + TransferDirection direction) + { + allTransfers.TryGetValue(direction, out var transfers); + return transfers ?? new ConcurrentDictionary>(); + } + + /// + /// Maps a Transfer collection to a serializable object. + /// + /// + /// + public static object ToMap( + this ConcurrentDictionary> 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)}) + }); + } + + /// + /// Filters a Transfer collection by user. + /// + /// + /// + /// + public static ConcurrentDictionary FromUser( + this ConcurrentDictionary> directedTransfers, + string username) + { + directedTransfers.TryGetValue(username, out var transfers); + return transfers ?? new ConcurrentDictionary(); + } + + /// + /// Maps a Transfer collection to a serializable object. + /// + /// + public static object ToMap( + this ConcurrentDictionary userTransfers) + { + return userTransfers.Values + .GroupBy(f => f.Transfer.Filename.DirectoryName()) + .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer)}); + } + + /// + /// Retrieves a Transfer from a Transfer collection by id. + /// + /// + /// + /// + public static (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId( + this ConcurrentDictionary userTransfers, + string id) + { + userTransfers.TryGetValue(id, out var transfer); + return transfer; + } + } + + /// + /// Tracks transfers. + /// + public class TransferTracker : ITransferTracker + { + /// + /// Tracked transfers. + /// + public ConcurrentDictionary>> Transfers { get; private set; } = + new ConcurrentDictionary>>(); + + /// + /// Initializes a new instance of the class. + /// + public TransferTracker() + { + Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary>()); + Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary>()); + } + + /// + /// Adds or updates a tracked transfer. + /// + /// + /// + 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; + }); + } + + /// + /// Removes a tracked transfer. + /// + /// Omitting an id will remove ALL transfers associated with the specified username. + 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 _); + } + } + } + + /// + /// Gets the specified transfer. + /// + /// + /// + /// + /// + /// + 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 GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) + { + var r = new ConcurrentDictionary(); + 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 @@ + + + + net5.0 + 9.0 + + + + false + 0.0.1 + + + + + + 1701;1702;1591 + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + + diff --git a/src/slskd/wwwroot/.gitkeep b/src/slskd/wwwroot/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/src/web/.gitignore b/src/web/.gitignore new file mode 100644 index 00000000..4d29575d --- /dev/null +++ b/src/web/.gitignore @@ -0,0 +1,23 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/src/web/README.md b/src/web/README.md new file mode 100644 index 00000000..9d9614c4 --- /dev/null +++ b/src/web/README.md @@ -0,0 +1,68 @@ +This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.
+Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.
+You will also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.
+It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.
+Your app is ready to be deployed! + +See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +## Learn More + +You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). + +To learn React, check out the [React documentation](https://reactjs.org/). + +### Code Splitting + +This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting + +### Analyzing the Bundle Size + +This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size + +### Making a Progressive Web App + +This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app + +### Advanced Configuration + +This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration + +### Deployment + +This section has moved here: https://facebook.github.io/create-react-app/docs/deployment + +### `npm run build` fails to minify + +This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify diff --git a/src/web/package.json b/src/web/package.json new file mode 100644 index 00000000..6fdc55c1 --- /dev/null +++ b/src/web/package.json @@ -0,0 +1,38 @@ +{ + "name": "web", + "version": "0.1.0", + "private": true, + "homepage": ".", + "dependencies": { + "axios": "^0.19.0", + "react": "^16.8.6", + "react-dom": "^16.8.6", + "react-router-dom": "^5.0.0", + "react-scripts": "3.0.1", + "semantic-ui-css": "^2.4.1", + "semantic-ui-react": "^2.0.0", + "signalr": "^2.4.1", + "uuid": "^8.3.0" + }, + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test", + "eject": "react-scripts eject" + }, + "eslintConfig": { + "extends": "react-app" + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } +} diff --git a/src/web/public/index.html b/src/web/public/index.html new file mode 100644 index 00000000..f12c2697 --- /dev/null +++ b/src/web/public/index.html @@ -0,0 +1,12 @@ + + + + + + Soulseek.NET + + + +
+ + diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css new file mode 100644 index 00000000..99d3767a --- /dev/null +++ b/src/web/src/components/App.css @@ -0,0 +1,125 @@ +body { + background: #c8c8c8 !important; +} + +.ui.table td, th { + padding-top: 5px !important; + padding-bottom: 5px !important; +} + +.app { + margin: auto; + border: 0px !important; + border-radius: 0% !important; + box-shadow: none !important; +} + +.app-content { + margin-top: 70px; + background: #c8c8c8 !important; +} + +.result-card { + width: 100% !important; +} + +.result-card:last-child, .transfer-card:last-child { + margin-bottom: 17px !important; +} + +.result-meta { + margin-top: 5px; +} + +@media only screen and (min-width: 768px) { + .transferlist-progress { + max-width: 300px; + width: 300px; + } +} + +@media only screen and (max-width: 767px) { + .transferlist-progress { + width: 100%; + } +} + +.filelist-header { + margin-top: 20px !important; +} + +.filelist-selector, .transferlist-selector { + width: 40px; +} + +.filelist-filename { + word-wrap: break-word !important; +} + +.filelist-size { + width: 100px; +} + +.filelist-bitrate { + width: 70px; +} + +.filelist-length{ + width: 65px; +} + +.transfer-button { + color: black; +} + +.transfer-card { + width: 1200px !important; + margin-left: auto !important; + margin-right: auto !important; +} + +.transfer-segment { + margin-top: 16px; + padding-left: 15px; + padding-right: 15px; +} + +.transfer-placeholder { + font-weight: 100; + text-align: center; + margin-top: 50px !important; +} + +.transferlist-size { + width: 150px; + min-width: 150px; +} + +.transferlist-filename { + word-wrap: break-word !important; +} + +.showmore-button { + padding: 20px !important; + max-width: 1200px !important; + margin-bottom: 17px !important; +} + +.login-button { + margin-top: 0px !important; +} + +.login-failure { + text-align: left; +} + +.close-button { + float: right; + margin-right: 0px !important; + font-size: 16pt !important; + line-height: 1.15 !important; +} + +.placeholder-segment { + opacity: .25; +} \ No newline at end of file diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js new file mode 100644 index 00000000..46bbcf72 --- /dev/null +++ b/src/web/src/components/App.js @@ -0,0 +1,170 @@ +import React, { Component } from 'react'; +import { Route, Link, Switch } from "react-router-dom"; +import { tokenKey, tokenPassthroughValue } from '../config'; +import * as session from '../lib/session'; + +import './App.css'; +import Search from './Search/Search'; +import Browse from './Browse/Browse'; +import Transfers from './Transfers/Transfers'; +import Chat from './Chat/Chat'; +import LoginForm from './LoginForm'; + +import { + Sidebar, + Segment, + Menu, + Icon, + Modal, + Header +} from 'semantic-ui-react'; +import Rooms from './Rooms/Rooms'; + +const initialState = { + token: undefined, + login: { + initialized: false, + pending: false, + error: undefined + } +}; + +class App extends Component { + state = initialState; + + componentDidMount = async () => { + const { login } = this.state; + const securityEnabled = await session.getSecurityEnabled(); + + if (!securityEnabled) { + this.setToken(sessionStorage, tokenPassthroughValue) + } + + this.setState({ + token: this.getToken(), + login: { + ...login, + initialized: true + } + }); + + await this.checkToken(); + } + + checkToken = async () => { + try { + await session.check(); + } catch (error) { + this.logout(); + } + } + + getToken = () => JSON.parse(sessionStorage.getItem(tokenKey) || localStorage.getItem(tokenKey)); + setToken = (storage, token) => storage.setItem(tokenKey, JSON.stringify(token)); + + login = (username, password, rememberMe) => { + this.setState({ login: { ...this.state.login, pending: true, error: undefined }}, async () => { + try { + const response = await session.login({ username, password }); + this.setToken(rememberMe ? localStorage : sessionStorage, response.data.token); + window.location.reload(); + } catch (error) { + this.setState({ login: { ...this.state.login, pending: false, error }}); + } + }); + } + + logout = () => { + localStorage.removeItem(tokenKey); + sessionStorage.removeItem(tokenKey); + this.setState({ ...initialState, login: { ...initialState.login, initialized: true }}); + } + + withTokenCheck = (component) => { + this.checkToken(); // async, runs in the background + return { ...component }; + } + + render = () => { + const { token, login } = this.state; + + return ( + <> + {!token ? + : + login.initialized && + + + + Search + + + + + Downloads + + + + + Uploads + + + + + Browse + + + + + Rooms + + + + + Chat + + + {token !== tokenPassthroughValue && + Log Out + + } + centered + size='mini' + header={
} + content='Are you sure you want to log out?' + actions={['Cancel', { key: 'done', content: 'Log Out', negative: true, onClick: this.logout }]} + />} + + + + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + + + + } + + ) + } +} + +export default App; diff --git a/src/web/src/components/Browse/Browse.css b/src/web/src/components/Browse/Browse.css new file mode 100644 index 00000000..336dfd6c --- /dev/null +++ b/src/web/src/components/Browse/Browse.css @@ -0,0 +1,68 @@ +.browse-results { + margin: unset !important; +} + +.browse-error { + display: block; + text-align: center; + font-size: 18px; + margin-top: 50px; +} + +.browse-results-row { + padding-top: 0px !important; +} + +.browse-results-row:last-child { + padding-bottom: 0px !important; +} + +.browse-folderlist { + width: 100% !important; + white-space: pre; + overflow: auto !important; + max-height: 400px; + padding: 1em !important; + box-shadow: unset !important; +} + +.browse-folderlist-list { + margin: 0px !important; + margin-bottom: 1px !important; +} + +.browse-folderlist-header { + cursor: pointer; + margin-left: 3px !important; +} + +.browse-folderlist-icon { + float: left; +} + +.browse-filelist { + width: 100% !important; + padding: 1em !important; +} + +.ui.list .list, ol.ui.list ol, ul.ui.list ul { + padding-left: 0px !important; + padding-top: 3px !important; + padding-bottom: 0px !important; +} + +.ui.list .list>.item>.icon+.content, .ui.list .list>.item>.image+.content, .ui.list>.item>.icon+.content, .ui.list>.item>.image+.content { + padding-left: 0px !important; +} + +.browse-tree-card { + width: 100% !important; +} + +.browse-container:last-child { + margin-bottom: 17px; +} + +.browse-meta { + margin-top: 5px; +} \ No newline at end of file diff --git a/src/web/src/components/Browse/Browse.js b/src/web/src/components/Browse/Browse.js new file mode 100644 index 00000000..27a7591b --- /dev/null +++ b/src/web/src/components/Browse/Browse.js @@ -0,0 +1,233 @@ +import React, { Component } from 'react'; +import * as user from '../../lib/user'; + +import './Browse.css'; + +import DirectoryTree from './DirectoryTree'; + +import { + Segment, + Input, + Loader, + Card, + Icon, +} from 'semantic-ui-react'; + +import Directory from './Directory'; +import PlaceholderSegment from '../Shared/PlaceholderSegment'; + +const initialState = { + username: '', + browseState: 'idle', + browseStatus: 0, + browseError: undefined, + interval: undefined, + selectedDirectory: {}, + selectedFiles: [], + tree: [], + info: { + directories: 0, + files: 0, + lockedDirectories: 0, + lockedFiles: 0 + } +}; + +class Browse extends Component { + state = initialState; + + browse = () => { + let username = this.inputtext.inputRef.current.value; + + this.setState({ username , browseState: 'pending', browseError: undefined }, () => { + user.browse({ username }) + .then(response => { + let { directories, lockedDirectories } = response; + + const directoryCount = directories.length; + const fileCount = directories.reduce((acc, dir) => acc += dir.fileCount, 0); + + const lockedDirectoryCount = lockedDirectories.length; + const lockedFileCount = lockedDirectories.reduce((acc, dir) => acc += dir.fileCount, 0); + + directories = directories.concat(lockedDirectories.map(d => ({ ...d, locked: true }))); + + this.setState({ + tree: this.getDirectoryTree(directories), + info: { + directories: directoryCount, + files: fileCount, + lockedDirectories: lockedDirectoryCount, + lockedFiles: lockedFileCount + } + }); + }) + .then(() => this.setState({ browseState: 'complete', browseError: undefined }, () => { + this.saveState(); + })) + .catch(err => this.setState({ browseState: 'error', browseError: err })) + }); + } + + clear = () => { + this.setState(initialState, () => { + this.saveState(); + this.inputtext.focus(); + }); + } + + keyUp = (event) => event.key === 'Escape' ? this.clear() : ''; + + onUsernameChange = (event, data) => { + this.setState({ username: data.value }); + } + + saveState = () => { + this.inputtext.inputRef.current.value = this.state.username; + this.inputtext.inputRef.current.disabled = this.state.browseState !== 'idle'; + + try { + localStorage.setItem('soulseek-example-browse-state', JSON.stringify(this.state)); + } catch (error) { + console.log(error); + } + } + + loadState = () => { + this.setState(JSON.parse(localStorage.getItem('soulseek-example-browse-state')) || initialState); + } + + componentDidMount = () => { + this.fetchStatus(); + this.loadState(); + this.setState({ + interval: window.setInterval(this.fetchStatus, 500) + }, () => this.saveState()); + + document.addEventListener("keyup", this.keyUp, false); + } + + componentWillUnmount = () => { + clearInterval(this.state.interval); + this.setState({ interval: undefined }); + document.removeEventListener("keyup", this.keyUp, false); + } + + fetchStatus = () => { + const { browseState, username } = this.state; + if (browseState === 'pending') { + user.getBrowseStatus({ username }) + .then(response => this.setState({ + browseStatus: response.data + })); + } + } + + getDirectoryTree = (directories) => { + if (directories.length === 0 || directories[0].directoryName === undefined) { + return []; + } + + const separator = this.sep(directories[0].directoryName); + const depth = Math.min.apply(null, directories.map(d => d.directoryName.split(separator).length)); + + const topLevelDirs = directories + .filter(d => d.directoryName.split(separator).length === depth); + + return topLevelDirs.map(directory => this.getChildDirectories(directories, directory, separator, depth)); + } + + getChildDirectories = (directories, root, separator, depth) => { + const children = directories + .filter(d => d.directoryName !== root.directoryName) + .filter(d => d.directoryName.split(separator).length === depth + 1) + .filter(d => d.directoryName.startsWith(root.directoryName)); + + return { ...root, children: children.map(c => this.getChildDirectories(directories, c, separator, depth + 1)) }; + } + + selectDirectory = (directory) => { + this.setState({ selectedDirectory: { ...directory, children: [] }}, () => this.saveState()); + } + + deselectDirectory = () => { + this.setState({ selectedDirectory: initialState.selectedDirectory }, () => this.saveState()); + } + + sep = (directoryName) => directoryName.includes('\\') ? '\\' : '/'; + + render = () => { + const { browseState, browseStatus, browseError, tree, selectedDirectory, username, info } = this.state; + const { directoryName, locked } = selectedDirectory; + const pending = browseState === 'pending'; + + const emptyTree = !(tree && tree.length > 0); + + const files = (selectedDirectory.files || []).map(f => ({ ...f, filename: `${directoryName}${this.sep(directoryName)}${f.filename}`})); + + return ( +
+ + } + size='big' + ref={input => this.inputtext = input} + loading={pending} + disabled={pending} + className='search-input' + placeholder="Username" + action={!pending && (browseState === 'idle' ? { icon: 'search', onClick: this.browse } : { icon: 'x', color: 'red', onClick: this.clear })} + onKeyUp={(e) => e.key === 'Enter' ? this.browse() : ''} + /> + + {pending ? + + Downloaded {Math.round(browseStatus.percentComplete || 0)}% of Response + + : +
+ {browseError ? + Failed to browse {username} : +
+ {emptyTree ? + : + + + + + {username} + + + {`${info.files + info.lockedFiles} files in ${info.directories + info.lockedDirectories} directories (including ${info.lockedFiles} files in ${info.lockedDirectories} locked directories)`} + + + this.selectDirectory(value)} + /> + + + } + {directoryName && } +
+ } +
} +
+ ) + } +} + +export default Browse; \ No newline at end of file diff --git a/src/web/src/components/Browse/Directory.js b/src/web/src/components/Browse/Directory.js new file mode 100644 index 00000000..8b49a3e6 --- /dev/null +++ b/src/web/src/components/Browse/Directory.js @@ -0,0 +1,101 @@ +import React, { Component } from 'react'; +import * as transfers from '../../lib/transfers'; + +import { formatBytes } from '../../lib/util'; + +import FileList from '../Shared/FileList' + +import { + Button, + Card, + Icon, + Label +} from 'semantic-ui-react'; + +const initialState = { + downloadRequest: undefined, + downloadError: '' +} + +class Directory extends Component { + state = { + ...initialState, + files: this.props.files.map(f => ({ selected: false, ...f })) + } + + onFileSelectionChange = (file, state) => { + file.selected = state; + this.setState({ tree: this.state.tree, downloadRequest: undefined, downloadError: '' }) + } + + download = (username, files) => { + this.setState({ downloadRequest: 'inProgress' }, () => { + Promise.all(files.map(f => this.downloadOne(username, f))) + .then(() => this.setState({ downloadRequest: 'complete' })) + .catch(err => this.setState({ downloadRequest: 'error', downloadError: err.response })) + }); + } + + componentDidUpdate = (prevProps) => { + if (this.props.name !== prevProps.name) { + this.setState({ files: this.props.files.map(f => ({ selected: false, ...f }))}); + } + } + + downloadOne = (username, file) => { + const { filename, size } = file; + return transfers.download({ username, filename, size }); + } + + render = () => { + let { username, name, locked, marginTop, onClose } = this.props; + let { files, downloadRequest, downloadError } = this.state; + + let selectedFiles = files + .filter(f => f.selected); + + let selectedSize = formatBytes(selectedFiles.reduce((total, f) => total + f.size, 0)); + + return ( + + +
+ +
+
+ {selectedFiles.length > 0 && + + + } + centered + size='small' + {...rest} + /> + + + ) +} + +export default ChatMenu; \ No newline at end of file diff --git a/src/web/src/components/Chat/SendMessageModal.js b/src/web/src/components/Chat/SendMessageModal.js new file mode 100644 index 00000000..3c91d570 --- /dev/null +++ b/src/web/src/components/Chat/SendMessageModal.js @@ -0,0 +1,75 @@ +import React, { useEffect } from 'react'; +import './Chat.css'; + +import { + Icon, Button, Modal, Form, Header, Input +} from 'semantic-ui-react'; + +const usernameRef = React.createRef(); + +const SendMessageModal = ({ initiateConversation, ...rest }) => { + const [open, setOpen] = React.useState(false); + const [username, setUsername] = React.useState(''); + const [message, setMessage] = React.useState(''); + + useEffect(() => { + if (open) { + usernameRef.current.focus(); + } + }, [open]); + + const sendMessage = async () => { + if (!validInput()) { + usernameRef.current.focus(); + return; + } + + await initiateConversation(username, message); + setOpen(false); + } + + const validInput = () => { + return username.length > 0 && message.length > 0 + } + + return ( + setOpen(false)} + onOpen={() => setOpen(true)} + {...rest} + > +
+ + Send Private Message +
+ +
+ + setUsername(data.value)} + /> + + + setMessage(data.value)} + /> + +
+
+ + + + +
+ ) +} + +export default SendMessageModal; \ No newline at end of file diff --git a/src/web/src/components/LoginForm.js b/src/web/src/components/LoginForm.js new file mode 100644 index 00000000..e76b6cfc --- /dev/null +++ b/src/web/src/components/LoginForm.js @@ -0,0 +1,83 @@ +import React, { Component } from 'react' +import { Button, Form, Grid, Header, Icon, Segment, Checkbox, Message } from 'semantic-ui-react' + +const initialState = { + username: '', + password: '', + rememberMe: true, + ready: false, +} + +class LoginForm extends Component { + state = initialState; + + handleChange = (field, value) => { + this.setState({ + [field]: value, + }, () => { + if (this.state.username !== '' && this.state.password !== '') { + this.setState({ ready: true }) + } else { + this.setState({ ready: false }) + } + }); + } + + render = () => { + const { initialized, onLoginAttempt, loading, error } = this.props; + const { username, password, rememberMe, ready } = this.state; + + return ( + <> + {initialized && + +
+ Soulseek Web Example +
+
+ + this.handleChange('username', event.target.value)} + /> + this.handleChange('password', event.target.value)} + /> + this.handleChange('rememberMe', !rememberMe)} + checked={rememberMe} + /> + + + {error && + + {error.message} + } +
+
+
} + + ) + } +} + +export default LoginForm \ No newline at end of file diff --git a/src/web/src/components/Rooms/RoomJoinModal.js b/src/web/src/components/Rooms/RoomJoinModal.js new file mode 100644 index 00000000..4dffe840 --- /dev/null +++ b/src/web/src/components/Rooms/RoomJoinModal.js @@ -0,0 +1,142 @@ +import React, { useEffect, useState, useMemo } from 'react'; +import * as rooms from '../../lib/rooms'; +import './Rooms.css'; + +import { + Icon, Button, Modal, Table, Header, Input, Loader, Dimmer +} from 'semantic-ui-react'; + +const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { + const [open, setOpen] = useState(false); + const [available, setAvailable] = useState([]); + const [selected, setSelected] = useState(undefined); + const [sortBy, setSortBy] = useState('name'); + const [sortOrder, setSortOrder] = useState('desc'); + const [filter, setFilter] = useState(''); + const [loading, setLoading] = useState(true); + + useEffect(() => { + const getAvailableRooms = async () => { + setLoading(true); + const available = await rooms.getAvailable(); + setAvailable(available); + setLoading(false); + } + + if (open) getAvailableRooms(); + }, [open]); + + const sortedAvailable = useMemo(() => { + const sorted = [...available].filter(room => room.name.includes(filter)); + + sorted.sort((a, b) => { + if (sortOrder === 'asc') { + if (typeof(a[sortBy]) === 'string') { + return b[sortBy].localeCompare(a[sortBy]); + } + + return a[sortBy] - b[sortBy]; + } + + if (typeof(a[sortBy]) === 'string') { + return a[sortBy].localeCompare(b[sortBy]); + } + + return b[sortBy] - a[sortBy] + }); + + return sorted; + }, [available, sortBy, sortOrder, filter]); + + const joinRoom = async () => { + await parentJoinRoom(selected); + close(); + } + + const isSelected = (room) => selected === room.name; + + const close = () => { + setAvailable([]); + setSelected(undefined); + setSortBy('name'); + setSortOrder('desc'); + setFilter(''); + setOpen(false); + } + + return ( + close()} + onOpen={() => setOpen(true)} + {...modalOptions} + > +
+ + Join Room +
+ + {loading ? : + <> + setFilter(e.value)} + placeholder='Room Filter' + icon='filter' + /> + + + + setSortBy('name')}> + Name + setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')} + /> + + setSortBy('userCount')}> + Users + setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')} + /> + + + + + {sortedAvailable.map((room, index) => + setSelected(room.name)} + > + + {isSelected(room) && } + {room.isPrivate && } + {room.isOwned && } + {room.isModerated && } + {room.name} + + {room.userCount} + + )} + +
+ } +
+ + + + +
+ ) +} + +export default RoomJoinModal; \ No newline at end of file diff --git a/src/web/src/components/Rooms/RoomMenu.js b/src/web/src/components/Rooms/RoomMenu.js new file mode 100644 index 00000000..c77dd8fb --- /dev/null +++ b/src/web/src/components/Rooms/RoomMenu.js @@ -0,0 +1,41 @@ +import React from 'react'; +import './Rooms.css'; + +import { + Icon, Button, Menu +} from 'semantic-ui-react'; +import RoomJoinModal from './RoomJoinModal'; + +const RoomMenu = ({ joined, active, onRoomChange, ...rest }) => { + const names = [...joined]; + const isActive = (name) => active === name; + + return ( + + {names.map((name, index) => + onRoomChange(name)} + > + + {name} + + )} + + + } + centered + size='small' + {...rest} + /> + + + ) +} + +export default RoomMenu; \ No newline at end of file diff --git a/src/web/src/components/Rooms/RoomUserList.js b/src/web/src/components/Rooms/RoomUserList.js new file mode 100644 index 00000000..c719e5f1 --- /dev/null +++ b/src/web/src/components/Rooms/RoomUserList.js @@ -0,0 +1,44 @@ +import React, { useMemo } from 'react'; +import './Rooms.css'; + +import { + Icon, Flag, List, Popup +} from 'semantic-ui-react'; + +const RoomUserList = ({ users }) => { + const getFlag = (user) => { + if (!(user || {}).countryCode) return ; + + return ; + } + + const getDetails = (user) => { + return user.countryCode || '?'; + } + + const sortedUsers = useMemo(() => { + const filtered = [...users] + .sort((a, b) => a.username.localeCompare(b.username)) + .reduce((acc, user) => { + (user.status === 'Online' ? acc.online : acc.offline).push(user); + return acc; + }, { online: [], offline: []}); + + return [...filtered.online, ...filtered.offline]; + }, [users]); + + return ( + + {sortedUsers.map((user, index) => + + + + {user.username} + + + )} + + ) +} + +export default RoomUserList; \ No newline at end of file diff --git a/src/web/src/components/Rooms/Rooms.css b/src/web/src/components/Rooms/Rooms.css new file mode 100644 index 00000000..87180fd5 --- /dev/null +++ b/src/web/src/components/Rooms/Rooms.css @@ -0,0 +1,132 @@ +.rooms { + padding-left: 15px; + padding-right: 15px; + max-width: 1200px !important; + margin-left: auto !important; + margin-right: auto !important; + margin-bottom: 17px; +} + +.rooms > .segment:first-child { + margin-top: 15px !important; + height: 78px; +} + +.room-menu { + overflow-x: auto; + box-shadow: unset !important; + height: 47px; +} + +.room-menu > .menu-item { + font-size: 14pt; +} + +.room-menu > .menu-active { + font-weight: bold !important; +} + +.room-menu > .menu > .add-button { + margin: 0px; + border-top-left-radius: 0%; + border-bottom-left-radius: 0%; + border-radius: 0%; +} + +.join-room-modal > .content > .table > thead > tr > th > .icon { + float: right !important; +} + +@media only screen and (max-width: 767px) { + .room-users { + display: none; + } +} + +.room { + display: flex; + margin-top: 1rem; + height: calc(100vh - 255px); +} + +.room-active-card { + width: 100% !important; +} + +.room-active-card > .content > .room > .segments { + box-shadow: unset !important; + margin-bottom: 0px; + border-top-right-radius: unset !important; + border-bottom-right-radius: unset !important; + width: 100% !important; +} + +.room-history { + padding: .5em .5em 0 .5em !important; + overflow-y: auto; + overscroll-behavior-y: contain; + scroll-snap-type: y proximity; + display: grid; + height: calc(100vh - 292px); +} + +.room-history > .list { + align-self: end; + margin-bottom: .5em !important; +} + +.room-users { + margin-top: 0px !important; + overflow-y: auto; + overscroll-behavior-y: contain; + scroll-snap-type: y proximity; + overflow-x: hidden; + min-width: 250px; + max-width: 250px; + box-shadow: unset !important; + border-left: unset !important; + border-bottom-left-radius: unset !important; + border-top-left-radius: unset !important; + padding: 7px !important; +} + +.room-message-name { + font-weight: bold; +} + +.room-message-time { + float:right; + opacity: .5; + font-size: smaller; + font-variant: small-caps; + font-style: italic; +} + +.room-message-self, .room-user-self { + color: blue; +} + +.room-input { + padding: 0px 0px 0px 1em !important; +} + +.room-message-button { + background-color: transparent !important; +} + +#room-history-scroll-anchor { + scroll-snap-align: start +} + +/* semantic-ui-react colors the border of inputs + when a right aligned action is used, even when + transparent is specified, and it uses !important. + this had to be added to an id to override the class + declaration. */ +#room-message-input { + border-right-color: transparent !important; +} + +.unknown-user-flag { + opacity: .1 !important; +} \ No newline at end of file diff --git a/src/web/src/components/Rooms/Rooms.js b/src/web/src/components/Rooms/Rooms.js new file mode 100644 index 00000000..306696bb --- /dev/null +++ b/src/web/src/components/Rooms/Rooms.js @@ -0,0 +1,219 @@ +import React, { Component, createRef } from 'react'; +import * as rooms from '../../lib/rooms'; +import { activeRoomKey } from '../../config'; + +import { Segment, Card, Icon, Input, Ref, List, Loader, Dimmer } from 'semantic-ui-react'; + +import RoomMenu from './RoomMenu'; +import RoomUserList from './RoomUserList'; +import PlaceholderSegment from '../Shared/PlaceholderSegment'; + +const initialState = { + active: '', + joined: [], + room: { + messages: [], + users: [] + }, + intervals: { + rooms: undefined, + messages: undefined + }, + loading: false +} + +class Rooms extends Component { + state = initialState; + messageRef = undefined; + listRef = createRef(); + + componentDidMount = async () => { + this.setState({ + intervals: { + rooms: window.setInterval(this.fetchJoinedRooms, 500), + messages: window.setInterval(this.fetchActiveRoom, 1000) + }, + active: sessionStorage.getItem(activeRoomKey) || '' + }, async () => { + await this.fetchJoinedRooms(); + this.selectRoom(this.state.active || this.getFirstRoom()) + }); + }; + + componentWillUnmount = () => { + const { rooms, messages } = this.state.intervals; + + clearInterval(rooms); + clearInterval(messages); + + this.setState({ intervals: initialState.intervals }); + } + + getFirstRoom = () => { + return this.state.joined.length > 0 ? this.state.joined[0] : ''; + } + + fetchJoinedRooms = async () => { + const joined = await rooms.getJoined();; + this.setState({ + joined + }, () => { + if (!this.state.joined.includes(this.state.active)) { + this.selectRoom(this.getFirstRoom()); + } + }); + }; + + fetchActiveRoom = async () => { + const { active } = this.state; + + if (active.length === 0) return; + + const messages = await rooms.getMessages({ roomName: active }); + const users = await rooms.getUsers({ roomName: active }); + + this.setState({ + room: { + users, + messages + } + }); + }; + + selectRoom = async (roomName) => { + this.setState({ + active: roomName, + room: initialState.room, + loading: true + }, async () => { + const { active } = this.state; + + sessionStorage.setItem(activeRoomKey, active); + + await this.fetchActiveRoom(); + this.setState({ loading: false }, () => { + try { + this.listRef.current.lastChild.scrollIntoView(); + } catch {} + }); + }); + }; + + joinRoom = async (roomName) => { + await rooms.join({ roomName }); + await this.fetchJoinedRooms(); + this.selectRoom(roomName); + }; + + leaveRoom = async (roomName) => { + await rooms.leave({ roomName }); + await this.fetchJoinedRooms(); + this.selectRoom(this.getFirstRoom()); + }; + + validInput = () => (this.state.active || '').length > 0 && ((this.messageRef && this.messageRef.current && this.messageRef.current.value) || '').length > 0; + + focusInput = () => { + this.messageRef.current.focus(); + }; + + formatTimestamp = (timestamp) => { + const date = new Date(timestamp); + const dtfUS = new Intl.DateTimeFormat('en', { + month: 'numeric', + day: 'numeric', + hour: 'numeric', + minute: '2-digit' + }); + + return dtfUS.format(date); + }; + + sendMessage = async () => { + const { active } = this.state; + const message = this.messageRef.current.value; + + if (!this.validInput()) { + return; + } + + await rooms.sendMessage({ roomName: active, message }); + this.messageRef.current.value = ''; + }; + + render = () => { + const { joined, active, room, loading } = this.state; + + return ( +
+ + this.selectRoom(name)} + joinRoom={this.joinRoom} + /> + + {!active ? + : + + this.focusInput()}> + + + {active} + this.leaveRoom(active)} + /> + +
+ {loading ? : <> + + + + + {room.messages.map((message, index) => + + {this.formatTimestamp(message.timestamp)} + {message.username}: + {message.message} + + )} + + + + + + } + ref={input => this.messageRef = input && input.inputRef} + action={{ + icon: , + className: 'room-message-button', onClick: this.sendMessage, + disabled: !this.validInput() + }} + onKeyUp={(e) => e.key === 'Enter' ? this.sendMessage() : ''} + /> + + + + + + } +
+
+
} +
+ ) + }; +}; + +export default Rooms; \ No newline at end of file diff --git a/src/web/src/components/Search/Response.js b/src/web/src/components/Search/Response.js new file mode 100644 index 00000000..74b96b93 --- /dev/null +++ b/src/web/src/components/Search/Response.js @@ -0,0 +1,127 @@ +import React, { Component } from 'react'; +import * as transfers from '../../lib/transfers'; + +import { formatBytes, getDirectoryName } from '../../lib/util'; + +import FileList from '../Shared/FileList' + +import { + Button, + Card, + Icon, + Label +} from 'semantic-ui-react'; + +const buildTree = (response) => { + let { files = [], lockedFiles = [] } = response; + files = files.concat(lockedFiles.map(file => ({ ...file, locked: true }))); + + return files.reduce((dict, file) => { + let dir = getDirectoryName(file.filename); + let selectable = { selected: false, ...file }; + dict[dir] = dict[dir] === undefined ? [ selectable ] : dict[dir].concat(selectable); + return dict; + }, {}); +} + +class Response extends Component { + state = { + tree: buildTree(this.props.response), + downloadRequest: undefined, + downloadError: '' + } + + componentDidUpdate = (prevProps) => { + if (this.props.response !== prevProps.response) { + this.setState({ tree: buildTree(this.props.response) }); + } + } + + onFileSelectionChange = (file, state) => { + file.selected = state; + console.log(this.state.tree); + this.setState({ tree: this.state.tree, downloadRequest: undefined, downloadError: '' }) + } + + download = (username, files) => { + this.setState({ downloadRequest: 'inProgress' }, () => { + Promise.all((files || []).map(f => this.downloadOne(username, f))) + .then(() => this.setState({ downloadRequest: 'complete' })) + .catch(err => this.setState({ downloadRequest: 'error', downloadError: err.response })) + }); + } + + downloadOne = (username, file) => { + const { filename, size } = file; + return transfers.download({ username, filename, size }); + } + + render = () => { + let response = this.props.response; + let free = response.freeUploadSlots > 0; + + let { tree, downloadRequest, downloadError } = this.state; + + let selectedFiles = Object.keys(tree) + .reduce((list, dict) => list.concat(tree[dict]), []) + .filter(f => f.selected); + + let selectedSize = formatBytes(selectedFiles.reduce((total, f) => total + f.size, 0)); + + return ( + + + + + {response.username} + this.props.onHide()} + /> + + + Upload Speed: {formatBytes(response.uploadSpeed)}/s, Free Upload Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength} + + {(Object.keys(tree) || []).map((dir, i) => + file.locked)} + files={tree[dir]} + disabled={downloadRequest === 'inProgress'} + onSelectionChange={this.onFileSelectionChange} + /> + )} + + {selectedFiles.length > 0 && + + + : ''} + } + + ) + } +} + +export default Search; \ No newline at end of file diff --git a/src/web/src/components/Shared/FileList.js b/src/web/src/components/Shared/FileList.js new file mode 100644 index 00000000..e470563f --- /dev/null +++ b/src/web/src/components/Shared/FileList.js @@ -0,0 +1,75 @@ +import React from 'react'; + +import { formatSeconds, formatBytes, getFileName } from '../../lib/util'; + +import { + Header, + Table, + Icon, + List, + Checkbox +} from 'semantic-ui-react'; + +const FileList = ({ directoryName, files, locked, onSelectionChange, disabled, onClose }) => ( +
+
+
+ + {directoryName} + + {!!onClose && onClose()} + />} +
+
+ {files && files.length > 0 && + + + + + + files.map(f => onSelectionChange(f, data.checked))} + checked={files.filter(f => !f.selected).length === 0} + disabled={disabled} + /> + + File + Size + Bitrate + Length + + + + {files.sort((a, b) => a.filename > b.filename ? 1 : -1).map((f, i) => + + + onSelectionChange(f, data.checked)} + checked={f.selected} + disabled={disabled} + /> + + {locked ? : ''}{getFileName(f.filename)} + {formatBytes(f.size)} + {f.bitRate} + {formatSeconds(f.length)} + + )} + +
+
+
} +
+); + +export default FileList; diff --git a/src/web/src/components/Shared/PlaceholderSegment.js b/src/web/src/components/Shared/PlaceholderSegment.js new file mode 100644 index 00000000..4bea0846 --- /dev/null +++ b/src/web/src/components/Shared/PlaceholderSegment.js @@ -0,0 +1,14 @@ +import React from 'react'; + +import { Segment, Header, Icon } from 'semantic-ui-react'; + +const PlaceholderSegment = ({ icon, caption }) => ( + +
+ + {caption} +
+
+); + +export default PlaceholderSegment; \ No newline at end of file diff --git a/src/web/src/components/Transfers/TransferGroup.js b/src/web/src/components/Transfers/TransferGroup.js new file mode 100644 index 00000000..db093303 --- /dev/null +++ b/src/web/src/components/Transfers/TransferGroup.js @@ -0,0 +1,147 @@ +import React, { Component } from 'react'; +import * as transfers from '../../lib/transfers'; + +import { + Card, + Button +} from 'semantic-ui-react'; + +import TransferList from './TransferList'; + +class TransferGroup extends Component { + state = { selections: new Set() } + + onSelectionChange = (directoryName, file, selected) => { + const { selections } = this.state; + const obj = JSON.stringify({ directory: directoryName, filename: file.filename }); + selected ? selections.add(obj) : selections.delete(obj); + + this.setState({ selections }); + } + + isSelected = (directoryName, file) => + this.state.selections.has(JSON.stringify({ directory: directoryName, filename: file.filename })); + + getSelectedFiles = () => { + const { user } = this.props; + + return Array.from(this.state.selections) + .map(s => JSON.parse(s)) + .map(s => user.directories + .find(d => d.directory === s.directory) + .files.find(f => f.filename === s.filename) + ).filter(s => s !== undefined); + } + + removeFileSelection = (file) => { + const { selections } = this.state; + + const match = Array.from(selections) + .map(s => JSON.parse(s)) + .find(s => s.filename === file.filename); + + if (match) { + selections.delete(JSON.stringify(match)); + this.setState({ selections }); + } + } + + isStateRetryable = (state) => this.props.direction === 'download' && state.includes('Completed') && state !== 'Completed, Succeeded'; + isStateCancellable = (state) => ['InProgress', 'Requested', 'Queued', 'Initializing'].find(s => s === state); + isStateRemovable = (state) => state.includes('Completed'); + + retryAll = async (selected) => { + await Promise.all(selected.map(file => this.retry(file))); + } + + cancelAll = async (direction, username, selected) => { + await Promise.all(selected.map(file => transfers.cancel({ direction, username, id: file.id}))); + } + + removeAll = async (direction, username, selected) => { + await Promise.all(selected.map(file => + transfers.cancel({ direction, username, id: file.id, remove: true }) + .then(() => this.removeFileSelection(file)))); + } + + retry = async (file) => { + const { username, filename, size } = file; + + try { + await transfers.download({username, filename, size }); + } catch (error) { + console.log(error); + } + } + + fetchPlaceInQueue = async (file) => { + const { username, id } = file; + + try { + await transfers.getPlaceInQueue({ username, id }); + } catch (error) { + console.log(error); + } + } + + render = () => { + const { user, direction } = this.props; + + const selected = this.getSelectedFiles(); + const all = selected.length > 1 ? ' Selected' : ''; + + const allRetryable = selected.filter(f => this.isStateRetryable(f.state)).length === selected.length; + const anyCancellable = selected.filter(f => this.isStateCancellable(f.state)).length > 0; + const allRemovable = selected.filter(f => this.isStateRemovable(f.state)).length === selected.length; + + return ( + + + {user.username} + {user.directories && user.directories + .map((dir, index) => + ({ ...f, selected: this.isSelected(dir.directory, f) }))} + onSelectionChange={this.onSelectionChange} + direction={this.props.direction} + onPlaceInQueueRequested={this.fetchPlaceInQueue} + onRetryRequested={this.retry} + /> + )} + + {selected && selected.length > 0 && + + { + {allRetryable && +