aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-05-14 14:34:46 -0500
committerGitHub <noreply@github.com>2021-05-14 14:34:46 -0500
commite22472791be56eb3b44d7af7064400aa5e6ef9fc (patch)
tree8b6629c2a81de5889a0084a8f12d5c73b0cfdf36 /src
parent5926fd44420da613b4c4c00d043151916f24b989 (diff)
parenta0458827d19f21fe3efe40b5630bc18d0e28fd38 (diff)
downloadslskd-e22472791be56eb3b44d7af7064400aa5e6ef9fc.tar.gz
Merge pull request #70 from slskd/incomplete-downloads
Save incomplete downloads in a separate directory
Diffstat (limited to 'src')
-rw-r--r--src/slskd/API/Controllers/TransfersController.cs57
-rw-r--r--src/slskd/Common/Extensions.cs35
-rw-r--r--src/slskd/Options.cs38
-rw-r--r--src/slskd/Program.cs65
-rw-r--r--src/slskd/Properties/analysis.ruleset4
-rw-r--r--src/slskd/Properties/slskd.yml4
-rw-r--r--src/slskd/Service.cs16
-rw-r--r--src/slskd/Startup.cs6
-rw-r--r--src/slskd/Trackers/TransferTracker.cs2
9 files changed, 173 insertions, 54 deletions
diff --git a/src/slskd/API/Controllers/TransfersController.cs b/src/slskd/API/Controllers/TransfersController.cs
index 948bf7ff..8ba1ef72 100644
--- a/src/slskd/API/Controllers/TransfersController.cs
+++ b/src/slskd/API/Controllers/TransfersController.cs
@@ -2,18 +2,17 @@
namespace slskd.API.Controllers
{
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Soulseek;
using System;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
using slskd.API.DTO;
using slskd.Trackers;
- using slskd.Configuration;
+ using Soulseek;
/// <summary>
/// Transfers
@@ -33,13 +32,13 @@ namespace slskd.API.Controllers
/// <param name="tracker"></param>
public TransfersController(IOptionsSnapshot<Options> options, ISoulseekClient client, ITransferTracker tracker)
{
- OutputDirectory = options.Value.Directories.Downloads;
Client = client;
Tracker = tracker;
+ Options = options.Value;
}
+ private Options Options { get; }
private ISoulseekClient Client { get; }
- private string OutputDirectory { get; }
private ITransferTracker Tracker { get; }
/// <summary>
@@ -97,19 +96,24 @@ namespace slskd.API.Controllers
try
{
var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
- var stream = GetLocalFileStream(request.Filename, OutputDirectory);
+ var stream = GetLocalFileStream(request.Filename, Options.Directories.Incomplete);
var cts = new CancellationTokenSource();
- var downloadTask = Client.DownloadAsync(username, request.Filename, stream, request.Size, 0, request.Token, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) =>
+ var downloadTask = Task.Run(async () =>
{
- Tracker.AddOrUpdate(e, cts);
-
- if (e.Transfer.State == TransferStates.Queued || e.Transfer.State == TransferStates.Initializing)
+ await Client.DownloadAsync(username, request.Filename, stream, request.Size, 0, request.Token, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) =>
{
- waitUntilEnqueue.TrySetResult(true);
- }
- }, progressUpdated: (e) => Tracker.AddOrUpdate(e, cts)), cts.Token);
+ Tracker.AddOrUpdate(e, cts);
+
+ if (e.Transfer.State == TransferStates.Queued || e.Transfer.State == TransferStates.Initializing)
+ {
+ waitUntilEnqueue.TrySetResult(true);
+ }
+ }, progressUpdated: (e) => Tracker.AddOrUpdate(e, cts)), cts.Token);
+
+ MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads);
+ });
// wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the
// downloadTask throws due to an error prior to successfully queueing.
@@ -246,24 +250,35 @@ namespace slskd.API.Controllers
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)), "")}";
+ var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory);
+ var path = Path.GetDirectoryName(localFilename);
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
- var sanitizedFilename = Path.GetFileName(localFilename);
+ return new FileStream(localFilename, FileMode.Create);
+ }
+
+ private static void MoveFile(string filename, string sourceDirectory, string destinationDirectory)
+ {
+ var sourceFilename = filename.ToLocalFilename(sourceDirectory);
+ var destinationFilename = filename.ToLocalFilename(destinationDirectory);
- foreach (var c in Path.GetInvalidFileNameChars())
+ var destinationPath = Path.GetDirectoryName(destinationFilename);
+
+ if (!System.IO.Directory.Exists(destinationPath))
{
- sanitizedFilename = sanitizedFilename.Replace(c, '_');
+ System.IO.Directory.CreateDirectory(destinationPath);
}
- localFilename = Path.Combine(path, sanitizedFilename);
+ System.IO.File.Move(sourceFilename, destinationFilename, overwrite: true);
- return new FileStream(localFilename, FileMode.Create);
+ if (!System.IO.Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any())
+ {
+ System.IO.Directory.Delete(Path.GetDirectoryName(sourceFilename));
+ }
}
private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false)
diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs
index b7243549..4e08ed02 100644
--- a/src/slskd/Common/Extensions.cs
+++ b/src/slskd/Common/Extensions.cs
@@ -87,6 +87,41 @@ namespace slskd
}
/// <summary>
+ /// Converts a fully qualified remote filename to a local filename, swapping directory characters for those specific
+ /// to the local OS, removing any characters that are invalid for the local OS, and making the path relative to the
+ /// remote store (including the filename and the parent folder).
+ /// </summary>
+ /// <param name="remoteFilename">The fully qualified remote filename to convert.</param>
+ /// <returns>The converted filename.</returns>
+ public static string ToLocalRelativeFilename(this string remoteFilename)
+ {
+ var localFilename = remoteFilename.ToLocalOSPath();
+ var path = $"{Path.GetDirectoryName(localFilename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(localFilename)), string.Empty)}";
+
+ var sanitizedFilename = Path.GetFileName(localFilename);
+
+ foreach (var c in Path.GetInvalidFileNameChars())
+ {
+ sanitizedFilename = sanitizedFilename.Replace(c, '_');
+ }
+
+ return Path.Combine(path, sanitizedFilename).TrimStart('\\').TrimStart('/');
+ }
+
+ /// <summary>
+ /// Converts a fully qualified remote filename to a local filename based in the provided <paramref name="baseDirectory"/>, swapping directory characters for those specific
+ /// to the local OS, removing any characters that are invalid for the local OS, and making the path relative to the
+ /// remote store (including the filename and the parent folder).
+ /// </summary>
+ /// <param name="remoteFilename">The fully qualified remote filename to convert.</param>
+ /// <param name="baseDirectory">The base directory for the local filename.</param>
+ /// <returns>The converted filename.</returns>
+ public static string ToLocalFilename(this string remoteFilename, string baseDirectory)
+ {
+ return Path.Combine(baseDirectory, remoteFilename.ToLocalRelativeFilename());
+ }
+
+ /// <summary>
/// Converts the given path to the local format (normalizes path separators).
/// </summary>
/// <param name="path">The path to convert.</param>
diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs
index 527cfc42..6074d650 100644
--- a/src/slskd/Options.cs
+++ b/src/slskd/Options.cs
@@ -127,13 +127,20 @@ namespace slskd
public class DirectoriesOptions
{
/// <summary>
- /// Gets the path to shared files.
+ /// Gets the path where application data is saved.
/// </summary>
- [Argument('s', "shared")]
- [EnvironmentVariable("SHARED_DIR")]
- [Description("path to shared files")]
- [Required]
- public string Shared { get; private set; } = null;
+ [Argument(default, "app")]
+ [EnvironmentVariable("APP_DIR")]
+ [Description("path where application data is saved")]
+ public string App { get; private set; } = Program.DefaultAppDirectory;
+
+ /// <summary>
+ /// Gets the path where incomplete downloads are saved.
+ /// </summary>
+ [Argument(default, "incomplete")]
+ [EnvironmentVariable("INCOMPLETE_DIR")]
+ [Description("path where incomplete downloads are saved")]
+ public string Incomplete { get; private set; } = Program.DefaultIncompleteDirectory;
/// <summary>
/// Gets the path where downloaded files are saved.
@@ -141,8 +148,15 @@ namespace slskd
[Argument('o', "downloads")]
[EnvironmentVariable("DOWNLOADS_DIR")]
[Description("path where downloaded files are saved")]
- [Required]
- public string Downloads { get; private set; } = null;
+ public string Downloads { get; private set; } = Program.DefaultDownloadsDirectory;
+
+ /// <summary>
+ /// Gets the path to shared files.
+ /// </summary>
+ [Argument('s', "shared")]
+ [EnvironmentVariable("SHARED_DIR")]
+ [Description("path to shared files")]
+ public string Shared { get; private set; } = Program.DefaultSharedDirectory;
}
/// <summary>
@@ -357,7 +371,7 @@ namespace slskd
[Argument(default, "content-path")]
[EnvironmentVariable("CONTENT_PATH")]
[Description("path to static web content")]
- [Required]
+ [StringLength(255, MinimumLength = 1)]
public string ContentPath { get; private set; } = "wwwroot";
/// <summary>
@@ -385,7 +399,7 @@ namespace slskd
[Argument('u', "username")]
[EnvironmentVariable("USERNAME")]
[Description("username for web UI")]
- [Required]
+ [StringLength(255, MinimumLength = 1)]
public string Username { get; private set; } = Program.AppName;
/// <summary>
@@ -394,7 +408,7 @@ namespace slskd
[Argument('p', "password")]
[EnvironmentVariable("PASSWORD")]
[Description("password for web UI")]
- [Required]
+ [StringLength(255, MinimumLength = 1)]
public string Password { get; private set; } = Program.AppName;
/// <summary>
@@ -414,7 +428,7 @@ namespace slskd
[Argument(default, "jwt-key")]
[EnvironmentVariable("JWT_KEY")]
[Description("JWT signing key")]
- [Required]
+ [StringLength(255, MinimumLength = 1)]
public string Key { get; private set; } = Guid.NewGuid().ToString();
/// <summary>
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 00d6d5b4..d70b50c1 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -20,6 +20,7 @@ namespace slskd
using System;
using System.Collections.Generic;
using System.ComponentModel;
+ using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Net;
@@ -52,9 +53,9 @@ namespace slskd
public static readonly string AppName = "slskd";
/// <summary>
- /// The default database filename.
+ /// The default application data directory.
/// </summary>
- public static readonly string DefaultDatabaseFile = Path.Combine(AppContext.BaseDirectory, "data", $"{AppName}.db");
+ public static readonly string DefaultAppDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppName);
/// <summary>
/// The default configuration filename.
@@ -64,7 +65,22 @@ namespace slskd
/// <summary>
/// The default XML documentation filename.
/// </summary>
- public static readonly string DefaultXmlDocumentaitonFile = Path.Combine(AppContext.BaseDirectory, "etc", $"{AppName}.xml");
+ public static readonly string DefaultXmlDocumentationFile = Path.Combine(AppContext.BaseDirectory, "etc", $"{AppName}.xml");
+
+ /// <summary>
+ /// The default incomplete download directory.
+ /// </summary>
+ public static readonly string DefaultIncompleteDirectory = Path.Combine(DefaultAppDirectory, "incomplete");
+
+ /// <summary>
+ /// The default downloads directory.
+ /// </summary>
+ public static readonly string DefaultDownloadsDirectory = Path.Combine(DefaultAppDirectory, "downloads");
+
+ /// <summary>
+ /// The default shared directory.
+ /// </summary>
+ public static readonly string DefaultSharedDirectory = Path.Combine(DefaultAppDirectory, "shared");
/// <summary>
/// The global prefix for environment variables.
@@ -198,6 +214,37 @@ namespace slskd
return;
}
+ // ensure the application directory exists and is writeable. the most comprehensive way to test this is to try
+ // to write a file to it.
+ try
+ {
+ if (!Directory.Exists(Options.Directories.App))
+ {
+ Directory.CreateDirectory(Options.Directories.App);
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"App directory {Options.Directories.App} does not exist, and could not be created: {ex.Message}");
+ }
+
+ try
+ {
+ if (!Directory.Exists(Options.Directories.App))
+ {
+ Directory.CreateDirectory(Options.Directories.App);
+ }
+
+ var probe = Path.Combine(Options.Directories.App, "probe");
+ File.WriteAllText(Path.Combine(Options.Directories.App, "probe"), string.Empty);
+ File.Delete(probe);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"App directory {Options.Directories.App} is not writeable: {ex.Message}");
+ return;
+ }
+
if (!Options.NoLogo)
{
PrintLogo(Version);
@@ -374,6 +421,7 @@ namespace slskd
{
var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute));
var descriptionAttribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(DescriptionAttribute));
+ var isRequired = property.CustomAttributes.Any(a => a.AttributeType == typeof(RequiredAttribute));
if (attribute != default)
{
@@ -381,9 +429,9 @@ namespace slskd
var longName = (string)attribute.ConstructorArguments[1].Value;
var description = descriptionAttribute?.ConstructorArguments[0].Value;
- var suffix = property.PropertyType == typeof(bool) ? string.Empty : $" (default: {property.GetValue(defaults) ?? "<null>"})";
- var item = $"{shortName}{(shortName == default ? " " : "|")}--{GetLongName(longName, property.PropertyType)}";
- var desc = $"{description}{suffix}";
+ var suffix = isRequired ? " (required)" : $" (default: {property.GetValue(defaults) ?? "<null>"})";
+ var item = $"{(shortName == default ? " " : $"{shortName}|")}--{GetLongName(longName, property.PropertyType)}";
+ var desc = $"{description}{(property.PropertyType == typeof(bool) ? string.Empty : suffix)}";
lines.Add(new(item, desc));
}
else
@@ -421,15 +469,16 @@ namespace slskd
{
var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EnvironmentVariableAttribute));
var descriptionAttribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(DescriptionAttribute));
+ var isRequired = property.CustomAttributes.Any(a => a.AttributeType == typeof(RequiredAttribute));
if (attribute != default)
{
var name = (string)attribute.ConstructorArguments[0].Value;
var description = descriptionAttribute?.ConstructorArguments[0].Value;
- var suffix = type == typeof(bool) ? string.Empty : $" (default: {property.GetValue(defaults) ?? "<null>"})";
+ var suffix = isRequired ? " (required)" : $" (default: {property.GetValue(defaults) ?? "<null>"})";
var item = $"{prefix}{GetName(name, property.PropertyType)}";
- var desc = $"{description}{suffix}";
+ var desc = $"{description}{(type == typeof(bool) ? string.Empty : suffix)}";
lines.Add(new(item, desc));
}
else
diff --git a/src/slskd/Properties/analysis.ruleset b/src/slskd/Properties/analysis.ruleset
index 6605f525..a57b2b42 100644
--- a/src/slskd/Properties/analysis.ruleset
+++ b/src/slskd/Properties/analysis.ruleset
@@ -18,7 +18,7 @@
<Rule Id="CA1805" Action="None" />
<Rule Id="CA1819" Action="None" />
<Rule Id="CA1822" Action="None" />
- <Rule Id="CA2007" Action="Warning" />
+ <Rule Id="CA2007" Action="None" />
<Rule Id="CA2200" Action="Warning" />
<Rule Id="CA2214" Action="Warning" />
<Rule Id="CA2231" Action="Warning" />
@@ -32,12 +32,14 @@
</Rules>
<Rules AnalyzerId="SonarAnalyzer.CSharp" RuleNamespace="SonarAnalyzer.CSharp">
<Rule Id="S2589" Action="None" />
+ <Rule Id="S3011" Action="None" />
<Rule Id="S3427" Action="Info" />
</Rules>
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
<Rule Id="SA1008" Action="None" />
<Rule Id="SA1009" Action="None" />
<Rule Id="SA1101" Action="None" />
+ <Rule Id="SA1117" Action="None" />
<Rule Id="SA1124" Action="None" />
<Rule Id="SA1300" Action="None" />
<Rule Id="SA1402" Action="None" />
diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml
index d5519b65..c049aa7a 100644
--- a/src/slskd/Properties/slskd.yml
+++ b/src/slskd/Properties/slskd.yml
@@ -20,8 +20,10 @@
# key: ~
# ttl: 604800000
# directories:
-# shared: ~
+# app: ~
+# incomplete: ~
# downloads: ~
+# shared: ~
# logger:
# loki: ~
# feature:
diff --git a/src/slskd/Service.cs b/src/slskd/Service.cs
index 95c04595..7f5c1901 100644
--- a/src/slskd/Service.cs
+++ b/src/slskd/Service.cs
@@ -127,6 +127,7 @@ namespace slskd
await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password).ConfigureAwait(false);
Logger.Information("Connected and logged in as {Username}", Options.Soulseek.Username);
+ Logger.Information("Listening on port {Port}", Options.Soulseek.ListenPort);
Logger.Information("Client started");
}
@@ -249,17 +250,18 @@ namespace slskd
private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args)
{
- var direction = args.Transfer.Direction.ToString().ToUpper();
- var user = args.Transfer.Username;
- var file = Path.GetFileName(args.Transfer.Filename);
+ var xfer = args.Transfer;
+ var direction = xfer.Direction.ToString().ToUpper();
+ var user = xfer.Username;
+ var file = Path.GetFileName(xfer.Filename);
var oldState = args.PreviousState;
- var state = args.Transfer.State;
+ var state = xfer.State;
- var completed = args.Transfer.State.HasFlag(TransferStates.Completed);
+ var completed = xfer.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)}");
+ Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({xfer.BytesTransferred}/{xfer.Size} = {xfer.PercentComplete}%) @ {xfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}");
- if (args.Transfer.State.HasFlag(TransferStates.Succeeded) && args.Transfer.Direction == TransferDirection.Upload)
+ if (xfer.Direction == TransferDirection.Upload && xfer.State.HasFlag(TransferStates.Completed | TransferStates.Succeeded))
{
_ = Client.SendUploadSpeedAsync((int)args.Transfer.AverageSpeed);
}
diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs
index f7787409..c63699cf 100644
--- a/src/slskd/Startup.cs
+++ b/src/slskd/Startup.cs
@@ -145,13 +145,13 @@ namespace slskd
Version = "v0",
});
- if (File.Exists(Program.DefaultXmlDocumentaitonFile))
+ if (File.Exists(Program.DefaultXmlDocumentationFile))
{
- options.IncludeXmlComments(Program.DefaultXmlDocumentaitonFile);
+ options.IncludeXmlComments(Program.DefaultXmlDocumentationFile);
}
else
{
- logger.Warning($"Unable to find XML documentation in {Program.DefaultXmlDocumentaitonFile}, Swagger will not include metadata");
+ logger.Warning($"Unable to find XML documentation in {Program.DefaultXmlDocumentationFile}, Swagger will not include metadata");
}
});
}
diff --git a/src/slskd/Trackers/TransferTracker.cs b/src/slskd/Trackers/TransferTracker.cs
index 6efa7345..270f25cb 100644
--- a/src/slskd/Trackers/TransferTracker.cs
+++ b/src/slskd/Trackers/TransferTracker.cs
@@ -71,7 +71,7 @@ namespace slskd.Trackers
directedTransfers.TryGetValue(username, out var transfers);
return transfers ?? new ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>();
}
-
+
/// <summary>
/// Maps a Transfer collection to a serializable object.
/// </summary>