From 09b42a04b36e324c0c1f1f20bd1c66e95217f19f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Feb 2026 11:34:14 -0600 Subject: docs --- src/slskd/Integrations/VPN/Clients/Gluetun.cs | 148 ++++++++++++++++++++++++++ src/slskd/Integrations/VPN/GluetunClient.cs | 148 -------------------------- src/slskd/Integrations/VPN/VPNService.cs | 37 ++++++- 3 files changed, 182 insertions(+), 151 deletions(-) create mode 100644 src/slskd/Integrations/VPN/Clients/Gluetun.cs delete mode 100644 src/slskd/Integrations/VPN/GluetunClient.cs (limited to 'src') diff --git a/src/slskd/Integrations/VPN/Clients/Gluetun.cs b/src/slskd/Integrations/VPN/Clients/Gluetun.cs new file mode 100644 index 00000000..e9be123f --- /dev/null +++ b/src/slskd/Integrations/VPN/Clients/Gluetun.cs @@ -0,0 +1,148 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Integrations.VPN; + +using System; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using Serilog; +using static slskd.Options.IntegrationOptions.VpnOptions; + +public enum GluetunClientAuthenticationMethod +{ + None, + Basic, + ApiKey, +} + +public class Gluetun : IVPNClient +{ + public Gluetun(IHttpClientFactory httpClientFactory, IOptionsMonitor optionsMonitor) + { + HttpClientFactory = httpClientFactory; + OptionsMonitor = optionsMonitor; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IHttpClientFactory HttpClientFactory { get; } + private IOptionsMonitor OptionsMonitor { get; } + private GluetunVpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun; + + /// + /// Fetch the VPN connection status from the Gluetun control server. + /// + /// A value indicating whether the VPN is connected. + public async Task GetStatusAsync() + { + using var http = HttpClientFactory.CreateClient(); + + http.Timeout = TimeSpan.FromMilliseconds(1000); + + if (Options.Auth.Equals(GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) + { + var creds = $"{Options.Username}:{Options.Password}".ToBase64(); + http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); + } + else if (Options.Auth.Equals(GluetunClientAuthenticationMethod.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) + { + http.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); + } + else + { + // no auth + } + + try + { + var publicIp = await MakeRequest(http, "/v1/publicip/ip"); + + // per the gluetun docs/discussions, the public ip field will be an empty string if the VPN isn't up + if (string.IsNullOrEmpty(publicIp.PublicIp)) + { + return new VPNStatus { IsConnected = false }; + } + + int? port = null; + + if (OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) + { + port = (await MakeRequest(http, "/v1/portforward"))?.Port; + + // port will be 0 if port forwarding isn't enabled or ready + if (port == 0) + { + port = null; + } + } + + return new VPNStatus + { + IsConnected = true, + PublicIPAddress = IPAddress.Parse(publicIp.PublicIp), + Location = string.Join(", ", [publicIp.City, publicIp.Country]), + ForwardedPort = port, + }; + } + catch (Exception ex) + { + Log.Debug("Failed to retrieve status from Gluetun: {Message}", ex.Message); + throw new VPNClientException(ex.Message, ex); + } + } + + private async Task MakeRequest(HttpClient http, string url) + { + using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}{url}"); + response.EnsureSuccessStatusCode(); + + var result = await response.Content.ReadFromJsonAsync() + ?? throw new Exception($"Unexpected Gluetun response; expected: {nameof(T)}, got: {await response.Content.ReadAsStringAsync()}"); + + return result; + } + + private class GluetunStatusResponse + { + public string Status { get; init; } + } + + private class GluetunPortForwardResponse + { + public int? Port { get; init; } + } + + private class GluetunPublicIpResponse + { + [JsonPropertyName("public_ip")] + public string PublicIp { get; init; } + public string Region { get; init; } + public string Country { get; init; } + public string City { get; init; } + public string Location { get; init; } + public string Organization { get; init; } + + [JsonPropertyName("postal_code")] + public string PostalCode { get; init; } + public string Timezone { get; init; } + } +} \ No newline at end of file diff --git a/src/slskd/Integrations/VPN/GluetunClient.cs b/src/slskd/Integrations/VPN/GluetunClient.cs deleted file mode 100644 index 2d1588dd..00000000 --- a/src/slskd/Integrations/VPN/GluetunClient.cs +++ /dev/null @@ -1,148 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -using Microsoft.Extensions.Options; - -namespace slskd.Integrations.VPN; - -using System; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text.Json.Serialization; -using System.Threading.Tasks; -using Serilog; -using static slskd.Options.IntegrationOptions.VpnOptions; - -public enum GluetunClientAuthenticationMethod -{ - None, - Basic, - ApiKey, -} - -public class GluetunClient : IVPNClient -{ - public GluetunClient(IHttpClientFactory httpClientFactory, IOptionsMonitor optionsMonitor) - { - HttpClientFactory = httpClientFactory; - OptionsMonitor = optionsMonitor; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private IHttpClientFactory HttpClientFactory { get; } - private IOptionsMonitor OptionsMonitor { get; } - private GluetunVpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun; - - /// - /// Fetch the VPN connection status from the Gluetun control server. - /// - /// A value indicating whether the VPN is connected. - public async Task GetStatusAsync() - { - using var http = HttpClientFactory.CreateClient(); - - http.Timeout = TimeSpan.FromMilliseconds(1000); - - if (Options.Auth.Equals(GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) - { - var creds = $"{Options.Username}:{Options.Password}".ToBase64(); - http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); - } - else if (Options.Auth.Equals(GluetunClientAuthenticationMethod.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) - { - http.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); - } - else - { - // no auth - } - - try - { - var publicIp = await MakeRequest(http, "/v1/publicip/ip"); - - // per the gluetun docs/discussions, the public ip field will be an empty string if the VPN isn't up - if (string.IsNullOrEmpty(publicIp.PublicIp)) - { - return new VPNStatus { IsConnected = false }; - } - - int? port = null; - - if (OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) - { - port = (await MakeRequest(http, "/v1/portforward"))?.Port; - - // port will be 0 if port forwarding isn't enabled or ready - if (port == 0) - { - port = null; - } - } - - return new VPNStatus - { - IsConnected = true, - PublicIPAddress = IPAddress.Parse(publicIp.PublicIp), - Location = string.Join(", ", [publicIp.City, publicIp.Country]), - ForwardedPort = port, - }; - } - catch (Exception ex) - { - Log.Debug("Failed to retrieve status from Gluetun: {Message}", ex.Message); - throw new VPNClientException(ex.Message, ex); - } - } - - private async Task MakeRequest(HttpClient http, string url) - { - using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}{url}"); - response.EnsureSuccessStatusCode(); - - var result = await response.Content.ReadFromJsonAsync() - ?? throw new Exception($"Unexpected Gluetun response; expected: {nameof(T)}, got: {await response.Content.ReadAsStringAsync()}"); - - return result; - } - - private class GluetunStatusResponse - { - public string Status { get; init; } - } - - private class GluetunPortForwardResponse - { - public int? Port { get; init; } - } - - private class GluetunPublicIpResponse - { - [JsonPropertyName("public_ip")] - public string PublicIp { get; init; } - public string Region { get; init; } - public string Country { get; init; } - public string City { get; init; } - public string Location { get; init; } - public string Organization { get; init; } - - [JsonPropertyName("postal_code")] - public string PostalCode { get; init; } - public string Timezone { get; init; } - } -} \ No newline at end of file diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs index dbe7d2c1..18003341 100644 --- a/src/slskd/Integrations/VPN/VPNService.cs +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -26,8 +26,19 @@ using System.Threading.Tasks; using Serilog; using Soulseek; +/// +/// VPN integration. +/// public class VPNService : IDisposable { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + /// public VPNService( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, @@ -54,9 +65,9 @@ public class VPNService : IDisposable // we can revisit this if/when we add other options besides gluetun if (!string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun.Url)) { - Client = new GluetunClient(HttpClientFactory, OptionsMonitor); + Client = new Gluetun(HttpClientFactory, OptionsMonitor); - Log.Information("VPN integration enabled using {Client}", typeof(GluetunClient).Name); + Log.Information("VPN integration enabled using {Client}", typeof(Gluetun).Name); return; } @@ -64,7 +75,15 @@ public class VPNService : IDisposable } } + /// + /// Gets a value indicating whether the configured VPN client is ready (connected, and if port forwarding + /// is configured, a port has been provided). + /// public bool IsReady { get; private set; } = false; + + /// + /// Gets the most recent VPN client status. + /// public VPNStatus Status { get; private set; } = new VPNStatus(); private ISoulseekClient SoulseekClient { get; } @@ -78,6 +97,9 @@ public class VPNService : IDisposable private bool Disposed { get; set; } private SemaphoreSlim TimerElapsedLock { get; } = new SemaphoreSlim(1, 1); + /// + /// Starts polling the configured VPN client for status updates. + /// public void StartPolling() { if (Timer is not null && !Timer.Enabled) @@ -87,6 +109,9 @@ public class VPNService : IDisposable } } + /// + /// Stops polling the configured VPN client for status updates. + /// public void StopPolling() { if (Timer is not null && Timer.Enabled) @@ -96,12 +121,19 @@ public class VPNService : IDisposable } } + /// + /// Disposes this instance. + /// public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } + /// + /// Disposes this instance. + /// + /// protected virtual void Dispose(bool disposing) { if (!Disposed) @@ -148,7 +180,6 @@ public class VPNService : IDisposable * update VPNService state * apply a configuration overlay to set the forwarded port (if there is one) * update application state (via StateMutator) - * if IsReady changed during this invocation, disposition the ReadyTaskCompletionSource */ if (status is null || !status.IsConnected) { -- cgit v1.2.3