diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-11-09 21:37:20 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-11-09 21:37:20 -0600 |
| commit | 7fe7771af831bb6d46629869dc2490d8f14b7cf9 (patch) | |
| tree | 4499b75e43e9a3395a7d02ea75d959a40447ff46 | |
| parent | 746f40934d56637a1af529285a4054720f22f4a8 (diff) | |
| parent | 86f5e46c2dfe595d8a970cc2f9e49d2520f14b55 (diff) | |
| download | slskd-7fe7771af831bb6d46629869dc2490d8f14b7cf9.tar.gz | |
Merge pull request #245 from slskd/config
Move the default configuration location to the App directory, create a Docker volume for /app
| -rw-r--r-- | Dockerfile | 21 | ||||
| -rw-r--r-- | README.md | 2 | ||||
| -rw-r--r-- | config/slskd.example.yml (renamed from src/slskd/Properties/slskd.yml) | 1 | ||||
| -rw-r--r-- | slskd.sln | 5 | ||||
| -rw-r--r-- | src/slskd/Common/Extensions.cs | 12 | ||||
| -rw-r--r-- | src/slskd/Integrations/FTP/FTPClientFactory.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Integrations/FTP/FTPService.cs | 20 | ||||
| -rw-r--r-- | src/slskd/Options.cs | 38 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 131 | ||||
| -rw-r--r-- | src/slskd/Startup.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/Controllers/TransfersController.cs | 2 | ||||
| -rw-r--r-- | src/slskd/slskd.csproj | 4 |
12 files changed, 140 insertions, 108 deletions
@@ -1,3 +1,4 @@ +# build static web content FROM node:lts-alpine3.13 AS web ARG VERSION=0.0.1.65534-local @@ -8,6 +9,7 @@ COPY src/web src/web/. RUN sh ./bin/build --web-only --version $VERSION +# build, test, and publish application binaries # note: this needs to be pinned to an amd64 image in order to publish armv7 binaries # https://github.com/dotnet/dotnet-docker/issues/1537#issuecomment-615269150 FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim-amd64 AS publish @@ -18,6 +20,7 @@ WORKDIR /slskd COPY LICENSE . COPY bin bin/. +COPY config config/. COPY src/slskd src/slskd/. COPY tests tests/. @@ -27,8 +30,7 @@ RUN bash ./bin/build --dotnet-only --version $VERSION RUN bash ./bin/publish --no-prebuild --platform $TARGETPLATFORM --version $VERSION --output ../../dist/${TARGETPLATFORM} -# - +# application FROM mcr.microsoft.com/dotnet/runtime-deps:5.0-buster-slim AS slskd ARG TARGETPLATFORM ARG TAG=0.0.1 @@ -37,7 +39,7 @@ ARG REVISION=0 ARG BUILD_DATE LABEL org.opencontainers.image.title=slskd \ - org.opencontainers.image.description="a modern client-server application for the Soulseek file sharing network" \ + org.opencontainers.image.description="A modern client-server application for the Soulseek file sharing network" \ org.opencontainers.image.authors="slskd Team" \ org.opencontainers.image.vendor="slskd Team" \ org.opencontainers.image.licenses=AGPL-3.0 \ @@ -55,20 +57,21 @@ RUN apt-get update && apt-get install -y \ WORKDIR /slskd COPY --from=publish /slskd/dist/${TARGETPLATFORM} . -RUN bash -c 'mkdir -p /var/slskd/{incomplete,downloads,shared} \ - && chmod -R 777 /var/slskd' +RUN bash -c 'mkdir -p /app/{incomplete,downloads} \ + && chmod -R 777 /app' ENV DOTNET_BUNDLE_EXTRACT_BASE_DIR=/var/tmp/.net \ SLSKD_HTTP_PORT=5000 \ - SLSKD_APP_DIR=/var/slskd \ - SLSKD_INCOMPLETE_DIR=/var/slskd/incomplete \ - SLSKD_DOWNLOADS_DIR=/var/slskd/downloads \ - SLSKD_SHARED_DIR=/var/slskd/shared \ + SLSKD_APP_DIR=/app \ SLSKD_DOCKER_TAG=$TAG \ SLSKD_DOCKER_VERSION=$VERSION \ SLSKD_DOCKER_REVISON=$REVISION \ SLSKD_DOCKER_BUILD_DATE=$BUILD_DATE +EXPOSE 5000 + +VOLUME /app + HEALTHCHECK --interval=60s --timeout=3s --start-period=5s --retries=3 CMD wget -q -O - http://localhost:5000/health ENTRYPOINT ["./slskd"]
\ No newline at end of file @@ -61,4 +61,4 @@ A full list of the environment variables and command line arguments supported by ./slskd --help --envars ``` -An example of the yaml configuration file can be reviewed [here](https://github.com/slskd/slskd/blob/master/src/slskd/Properties/slskd.yml). +An example of the yaml configuration file can be reviewed [here](https://github.com/slskd/slskd/blob/master/config/slskd.example.yml). diff --git a/src/slskd/Properties/slskd.yml b/config/slskd.example.yml index b8450d35..643911e2 100644 --- a/src/slskd/Properties/slskd.yml +++ b/config/slskd.example.yml @@ -6,7 +6,6 @@ # no_version_check: false # instance_name: default # directories: -# app: ~ # incomplete: ~ # downloads: ~ # shared: @@ -42,6 +42,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "configuration", "configurat .github\configuration\changelog.json = .github\configuration\changelog.json EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "config", "config", "{98F684AE-507B-475A-92FE-AB4273A9F11A}" + ProjectSection(SolutionItems) = preProject + config\slskd.example.yml = config\slskd.example.yml + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 30b35d14..03bec7fe 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -25,6 +25,8 @@ namespace slskd using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; + using YamlDotNet.Serialization; + using YamlDotNet.Serialization.NamingConventions; /// <summary> /// Extensions. @@ -214,6 +216,16 @@ namespace slskd public static string ToJson(this object obj) => JsonSerializer.Serialize(obj, GetJsonSerializerOptions()); /// <summary> + /// Serializes this object to yaml. + /// </summary> + /// <param name="obj">The object to serialize.</param> + /// <returns>A string containing the serialized object.</returns> + public static string ToYaml(this object obj) => new SerializerBuilder() + .WithNamingConvention(UnderscoredNamingConvention.Instance) + .Build() + .Serialize(obj); + + /// <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 diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index e9ee0721..2e41ab03 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -37,7 +37,7 @@ namespace slskd.Integrations.FTP OptionsMonitor = optionsMonitor; } - private FTPOptions FTPOptions => OptionsMonitor.CurrentValue.Integration.FTP; + private FtpOptions FtpOptions => OptionsMonitor.CurrentValue.Integration.Ftp; private IOptionsMonitor<Options> OptionsMonitor { get; set; } /// <summary> @@ -46,9 +46,9 @@ namespace slskd.Integrations.FTP /// <returns>The created instance.</returns> public FtpClient CreateFtpClient() { - var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); - client.EncryptionMode = ParseFtpEncryptionMode(FTPOptions.EncryptionMode); - client.ValidateAnyCertificate = FTPOptions.IgnoreCertificateErrors; + var client = new FtpClient(FtpOptions.Address, FtpOptions.Port, FtpOptions.Username, FtpOptions.Password); + client.EncryptionMode = ParseFtpEncryptionMode(FtpOptions.EncryptionMode); + client.ValidateAnyCertificate = FtpOptions.IgnoreCertificateErrors; return client; } diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index becf1a12..dd1b340f 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -49,7 +49,7 @@ namespace slskd.Integrations.FTP } private IFTPClientFactory Factory { get; set; } - private FTPOptions FTPOptions => OptionsMonitor.CurrentValue.Integration.FTP; + private FtpOptions FtpOptions => OptionsMonitor.CurrentValue.Integration.Ftp; private ILogger<FTPService> Log { get; set; } private IOptionsMonitor<Options> OptionsMonitor { get; } @@ -60,7 +60,7 @@ namespace slskd.Integrations.FTP /// <returns>The operation context.</returns> public async Task UploadAsync(string filename) { - if (!FTPOptions.Enabled) + if (!FtpOptions.Enabled) { Log.LogDebug("Skipping FTP upload of {filename}; FTP integration is disabled"); return; @@ -74,7 +74,7 @@ namespace slskd.Integrations.FTP task: () => AttemptUploadAsync(filename), isRetryable: (attempts, ex) => true, onFailure: (attempts, ex) => Log.LogInformation("Failed attempt {Attempts} to upload {Filename} to FTP: {Message}", attempts, fileAndParentDirectory, ex.Message), - maxAttempts: FTPOptions.RetryAttempts, + maxAttempts: FtpOptions.RetryAttempts, maxDelayInMilliseconds: 30000); } catch (RetryException ex) @@ -84,7 +84,7 @@ namespace slskd.Integrations.FTP } catch (Exception ex) { - Log.LogWarning("Failed to upload {Filename} to FTP after {Attempts} attempts: {Message}", fileAndParentDirectory, FTPOptions.RetryAttempts, ex.Message); + Log.LogWarning("Failed to upload {Filename} to FTP after {Attempts} attempts: {Message}", fileAndParentDirectory, FtpOptions.RetryAttempts, ex.Message); throw; } } @@ -92,15 +92,15 @@ namespace slskd.Integrations.FTP private async Task AttemptUploadAsync(string filename) { var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename); - var remotePath = FTPOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); + var remotePath = FtpOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); var remoteFilename = $"{remotePath}/{fileAndParentDirectory}"; - var existsMode = FTPOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; + var existsMode = FtpOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; using var client = Factory.CreateFtpClient(); var timeoutTaskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); - using var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(FTPOptions.ConnectionTimeout)); + using var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(FtpOptions.ConnectionTimeout)); using var timeoutCancellationTokenRegistration = timeoutCancellationTokenSource.Token.Register(() => timeoutTaskCompletionSource.TrySetResult(true)); @@ -111,7 +111,7 @@ namespace slskd.Integrations.FTP if (completedTask == timeoutTaskCompletionSource.Task) { - throw new TimeoutException($"Failed to connect to server after {FTPOptions.ConnectionTimeout}ms"); + throw new TimeoutException($"Failed to connect to server after {FtpOptions.ConnectionTimeout}ms"); } if (connectTask.Exception != null) @@ -119,7 +119,7 @@ namespace slskd.Integrations.FTP throw connectTask.Exception; } - Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); + Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FtpOptions.Address, FtpOptions.Port, remoteFilename); var status = await client.UploadFileAsync(filename, remoteFilename, existsMode, createRemoteDir: true); if (status == FtpStatus.Failed) @@ -127,7 +127,7 @@ namespace slskd.Integrations.FTP throw new FtpException("FTP client reported a failed transfer"); } - Log.LogInformation("FTP upload of {Filename} to {Address}:{Port} complete", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port); + Log.LogInformation("FTP upload of {Filename} to {Address}:{Port} complete", fileAndParentDirectory, FtpOptions.Address, FtpOptions.Port); } private string GetFileAndParentDirectoryFromFilename(string filename) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 83844551..71c341e9 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -34,6 +34,7 @@ namespace slskd using Soulseek.Diagnostics; using Utility.CommandLine; using Utility.EnvironmentVariables; + using YamlDotNet.Serialization; /// <summary> /// Disambiguates options derived at startup from options that may update at run time. @@ -92,6 +93,7 @@ namespace slskd [Argument('v', "version")] [Description("display version information")] [Obsolete("Used only for documentation; see Program for actual implementation")] + [YamlIgnore] public bool ShowVersion { get; private set; } = false; /// <summary> @@ -100,6 +102,7 @@ namespace slskd [Argument('h', "help")] [Description("display command line usage")] [Obsolete("Used only for documentation; see Program for actual implementation")] + [YamlIgnore] public bool ShowHelp { get; private set; } = false; /// <summary> @@ -108,6 +111,7 @@ namespace slskd [Argument('e', "envars")] [Description("display environment variables")] [Obsolete("Used only for documentation; see Program for actual implementation")] + [YamlIgnore] public bool ShowEnvironmentVariables { get; private set; } = false; /// <summary> @@ -116,18 +120,10 @@ namespace slskd [Argument('g', "generate-cert")] [Description("generate X509 certificate and password for HTTPs")] [Obsolete("Used only for documentation; see Program for actual implementation")] + [YamlIgnore] public bool GenerateCertificate { get; private set; } = false; /// <summary> - /// Gets the path to the application configuration file. - /// </summary> - [Argument('c', "config")] - [EnvironmentVariable("CONFIG")] - [Description("path to configuration file")] - [Obsolete("Used only for documentation; see Program for actual implementation")] - public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile; - - /// <summary> /// Gets a value indicating whether the application should run in debug mode. /// </summary> [Argument('d', "debug")] @@ -191,6 +187,16 @@ namespace slskd public string InstanceName { get; private set; } = "default"; /// <summary> + /// Gets the path where application data is saved. + /// </summary> + [Argument(default, "app")] + [EnvironmentVariable("APP_DIR")] + [Description("path where application data is saved")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + [YamlIgnore] + public string AppDirectory { get; private set; } = Program.DefaultAppDirectory; + + /// <summary> /// Gets directory options. /// </summary> [Validate] @@ -249,16 +255,6 @@ namespace slskd public class DirectoriesOptions : IValidatableObject { /// <summary> - /// Gets the path where application data is saved. - /// </summary> - [Argument(default, "app")] - [EnvironmentVariable("APP_DIR")] - [Description("path where application data is saved")] - [DirectoryExists] - [RequiresRestart] - public string App { get; private set; } = Program.DefaultAppDirectory; - - /// <summary> /// Gets the path where incomplete downloads are saved. /// </summary> [Argument(default, "incomplete")] @@ -837,7 +833,7 @@ namespace slskd /// Gets FTP options. /// </summary> [Validate] - public FTPOptions FTP { get; private set; } = new FTPOptions(); + public FtpOptions Ftp { get; private set; } = new FtpOptions(); /// <summary> /// Gets Pushbullet options. @@ -848,7 +844,7 @@ namespace slskd /// <summary> /// FTP options. /// </summary> - public class FTPOptions : IValidatableObject + public class FtpOptions : IValidatableObject { /// <summary> /// Gets a value indicating whether the FTP integration is enabled. diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index edecf4e8..2403dbbf 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -54,24 +54,9 @@ namespace slskd public static readonly string AppName = "slskd"; /// <summary> - /// The default application data directory. - /// </summary> - public static readonly string DefaultAppDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify), AppName); - - /// <summary> - /// The default configuration filename. - /// </summary> - public static readonly string DefaultConfigurationFile = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.yml"); - - /// <summary> - /// The default incomplete download directory. - /// </summary> - public static readonly string DefaultIncompleteDirectory = Path.Combine(DefaultAppDirectory, "incomplete"); - - /// <summary> - /// The default downloads directory. + /// The url to the issues/support site. /// </summary> - public static readonly string DefaultDownloadsDirectory = Path.Combine(DefaultAppDirectory, "downloads"); + public static readonly string IssuesUrl = "https://github.com/slskd/slskd/issues"; /// <summary> /// The global prefix for environment variables. @@ -79,19 +64,14 @@ namespace slskd public static readonly string EnvironmentVariablePrefix = $"{AppName.ToUpperInvariant()}_"; /// <summary> - /// The url to the issues/support site. - /// </summary> - public static readonly string IssuesUrl = "https://github.com/slskd/slskd/issues"; - - /// <summary> /// The default XML documentation filename. /// </summary> public static readonly string XmlDocumentationFile = Path.Combine(AppContext.BaseDirectory, "etc", $"{AppName}.xml"); /// <summary> - /// Occurs when a new log event is emitted. + /// The default application data directory. /// </summary> - public static event EventHandler<LogRecord> LogEmitted; + public static readonly string DefaultAppDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify), AppName); /// <summary> /// Gets the assembly version of the application. @@ -99,7 +79,7 @@ namespace slskd /// <remarks> /// Inaccurate when running locally. /// </remarks> - public static Version AssemblyVersion { get; } = Assembly.GetExecutingAssembly().GetName().Version.Equals(new Version(1, 0, 0, 0)) ? new Version(0, 0, 0, 0) : Assembly.GetExecutingAssembly().GetName().Version; + public static readonly Version AssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.Equals(new Version(1, 0, 0, 0)) ? new Version(0, 0, 0, 0) : Assembly.GetExecutingAssembly().GetName().Version; /// <summary> /// Gets the informational version of the application, including the git sha at the latest commit. @@ -107,27 +87,49 @@ namespace slskd /// <remarks> /// Inaccurate when running locally. /// </remarks> - public static string InformationalVersion { get; } = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion == "1.0.0" ? "0.0.0" : Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; + public static readonly string InformationalVersion = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion == "1.0.0" ? "0.0.0" : Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; + + /// <summary> + /// Gets the full application version, including both assembly and informational versions. + /// </summary> + public static readonly string Version = $"{AssemblyVersion} ({InformationalVersion})"; + + /// <summary> + /// Gets a value indicating whether the current version is a Canary build. + /// </summary> + public static readonly bool IsCanary = AssemblyVersion.Revision == 65534; /// <summary> /// Gets the unique Id of this application invocation. /// </summary> - public static Guid InvocationId { get; } = Guid.NewGuid(); + public static readonly Guid InvocationId = Guid.NewGuid(); /// <summary> /// Gets the Id of the current application process. /// </summary> - public static int ProcessId { get; } = Environment.ProcessId; + public static readonly int ProcessId = Environment.ProcessId; /// <summary> - /// Gets the full application version, including both assembly and informational versions. + /// Occurs when a new log event is emitted. /// </summary> - public static string Version { get; } = $"{AssemblyVersion} ({InformationalVersion})"; + public static event EventHandler<LogRecord> LogEmitted; /// <summary> - /// Gets a value indicating whether the current version is a Canary build. + /// Gets the path where application data is saved. + /// </summary> + [Argument(default, "app", "path where application data is saved")] + [EnvironmentVariable("APP_DIR")] + public static string AppDirectory { get; private set; } = DefaultAppDirectory; + + /// <summary> + /// Gets the default downloads directory. /// </summary> - public static bool IsCanary { get; } = AssemblyVersion.Revision == 65534; + public static string DefaultDownloadsDirectory => Path.Combine(AppDirectory, "downloads"); + + /// <summary> + /// Gets the default incomplete download directory. + /// </summary> + public static string DefaultIncompleteDirectory => Path.Combine(AppDirectory, "incomplete"); /// <summary> /// Gets a buffer containing the last few log events. @@ -135,12 +137,9 @@ namespace slskd public static ConcurrentFixedSizeQueue<LogRecord> LogBuffer { get; } = new ConcurrentFixedSizeQueue<LogRecord>(size: 500); private static IConfigurationRoot Configuration { get; set; } + private static string ConfigurationFile => Path.Combine(AppDirectory, $"{AppName}.yml"); private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); - [EnvironmentVariable("CONFIG")] - [Argument('c', "config", "path to configuration file")] - private static string ConfigurationFile { get; set; } = DefaultConfigurationFile; - [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -199,8 +198,23 @@ namespace slskd return; } - // the application isn't being run in command mode. load all configuration values and proceed - // with bootstrapping. + // the application isn't being run in command mode. verify (create if needed) default application + // directories. if the downloads or complete directories are overridden in config, those will be + // validated after the config is loaded. + try + { + VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true); + VerifyDirectory(Path.Combine(AppDirectory, "data"), createIfMissing: true, verifyWriteable: true); + VerifyDirectory(DefaultDownloadsDirectory, createIfMissing: true, verifyWriteable: true); + VerifyDirectory(DefaultIncompleteDirectory, createIfMissing: true, verifyWriteable: true); + } + catch (Exception ex) + { + Console.WriteLine($"Filesystem exception: {ex.Message}"); + return; + } + + // load and validate the configuration try { Configuration = new ConfigurationBuilder() @@ -227,18 +241,6 @@ namespace slskd return; } - try - { - VerifyDirectory(OptionsAtStartup.Directories.App, createIfMissing: true, verifyWriteable: true); - VerifyDirectory(OptionsAtStartup.Directories.Incomplete, createIfMissing: true, verifyWriteable: true); - VerifyDirectory(OptionsAtStartup.Directories.Downloads, createIfMissing: true, verifyWriteable: true); - } - catch (Exception ex) - { - Console.WriteLine($"Filesystem exception: {ex.Message}"); - return; - } - Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal) @@ -252,7 +254,7 @@ namespace slskd outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.Async(config => config.File( - Path.Combine(OptionsAtStartup.Directories.App, "logs", $"{AppName}-.log"), + Path.Combine(AppDirectory, "logs", $"{AppName}-.log"), outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( @@ -282,11 +284,6 @@ namespace slskd PrintLogo(Version); } - if (ConfigurationFile != DefaultConfigurationFile && !IOFile.Exists(ConfigurationFile)) - { - logger.Warning($"Specified configuration file '{ConfigurationFile}' could not be found and was not loaded."); - } - logger.Information("Version: {Version}", Version); if (IsCanary) @@ -296,9 +293,29 @@ namespace slskd logger.Warning($"Please report any issues here: {IssuesUrl}"); } - logger.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); logger.Information("Invocation ID: {InvocationId}", InvocationId); logger.Information("Process ID: {ProcessId}", ProcessId); + logger.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); + + logger.Information("Using application directory {AppDirectory}", AppDirectory); + logger.Information("Using configuration file {ConfigurationFile}", ConfigurationFile); + + // for convenience, try to copy the example configuration file to the application directory if no configuration + // file exists. if any part fails, just move on silently. + if (!IOFile.Exists(ConfigurationFile)) + { + try + { + logger.Warning("Configuration file {ConfigurationFile} does not exist; creating from example", ConfigurationFile); + var source = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml"); + var destination = ConfigurationFile; + IOFile.Copy(source, destination); + } + catch (Exception ex) + { + logger.Error("Failed to create configuration file {ConfigurationFile}: {Message}", ConfigurationFile, ex.Message); + } + } if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 0ac5c437..98deac0d 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -218,12 +218,12 @@ namespace slskd services.AddDbContextFactory<SearchDbContext>(options => { - options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "search.db")}"); + options.UseSqlite($"Data Source={Path.Combine(Program.AppDirectory, "data", "search.db")}"); }); services.AddDbContextFactory<UserDbContext>(options => { - options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "users.db")}"); + options.UseSqlite($"Data Source={Path.Combine(Program.AppDirectory, "data", "users.db")}"); }); services.AddHttpClient(); diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index b912bbda..12d6bfcf 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -137,7 +137,7 @@ namespace slskd.Transfers.API MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); - if (Options.Integration.FTP.Enabled) + if (Options.Integration.Ftp.Enabled) { _ = FTP.UploadAsync(request.Filename.ToLocalFilename(Options.Directories.Downloads)); } diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 4c33e6f0..124238e4 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -32,12 +32,12 @@ <Target Name="CopyAfterBuild" AfterTargets="AfterBuild"> <Copy SourceFiles="..\..\LICENSE" DestinationFolder="$(OutDir)" /> - <Copy SourceFiles="Properties\slskd.yml" DestinationFolder="$(OutDir)\config" /> + <Copy SourceFiles="..\..\config\slskd.example.yml" DestinationFolder="$(OutDir)\config" /> <Copy SourceFiles="$(OutDir)\slskd.xml" DestinationFolder="$(OutDir)\etc" /> </Target> <Target Name="CopyOnPublish" AfterTargets="Publish"> <Copy SourceFiles="..\..\LICENSE" DestinationFolder="$(PublishDir)" /> - <Copy SourceFiles="Properties\slskd.yml" DestinationFolder="$(PublishDir)\config" /> + <Copy SourceFiles="..\..\config\slskd.example.yml" DestinationFolder="$(PublishDir)\config" /> <Move SourceFiles="$(PublishDir)\slskd.xml" DestinationFolder="$(PublishDir)\etc" /> </Target> |
