Remove TwentyTwenty.Storage and use local file storage (#7848)
What changed, and why it matters
This commit removes support for external cloud storage providers (Amazon S3, Azure Blob, Google Cloud) and switches BTCPay Server to storing uploaded files only on the local server disk. It also adds a safety check to prevent uploaded files from being written outside the intended storage folder. The change is mostly a feature simplification, but it introduces a new local file-handling path that must be secure against path-traversal attacks.
Review the new FileService path validation logic for completeness (e.g., symlink/hardlink race conditions, case-insensitive checks on Windows, and handling of alternate path separators). Ensure the LocalStorage directory has restrictive filesystem permissions and is not on a shared/network volume. Verify that static-file middleware does not inadvertently expose sensitive files placed in the storage directory. Consider whether existing deployments previously using cloud providers need migration of existing files.
Security signals we found
New local file write path with path-traversal guard in FileService.GetFilePath
Removal of cloud storage credential/configuration surfaces reduces cloud-credential exposure
Addition of InvalidOperationException test for '../outside.txt' filename
Static file middleware now serves the LocalStorage directory directly
IFileService marked Obsolete; application controllers now depend on concrete FileService
Evidence from the diff
The patch deletes the TwentyTwenty.Storage abstraction and all provider implementations (S3, Azure, GCS) and replaces them with a single FileService that writes files under DataDirectories.StorageDir. FileService.AddFile creates a StoredFile with a GUID-prefixed, lower-cased filename, writes it via FileStream, and records metadata. FileService.GetFilePath resolves the absolute path and verifies it stays under the storage root using Path.GetFullPath and a prefix check. A new LegacyFileService adapter keeps the old IFileService interface for plugins. Tests were updated to remove cloud-provider tests and add a path-traversal rejection test (../outside.txt).
Changed components
BTCPayServer.Storage.Services.FileServiceBTCPayServer.Storage.Services.LegacyFileServiceBTCPayServer.Storage.StorageExtensionsBTCPayServer.Controllers.UIServerController.StorageBTCPayServer.Controllers.GreenfieldFilesControllerBTCPayServer.Controllers.GreenfieldAppsControllerBTCPayServer.Controllers.GreenfieldStoresControllerBTCPayServer.Controllers.GreenfieldUsersControllerBTCPayServer.Controllers.UIAppsControllerBTCPayServer.Controllers.UIManageControllerBTCPayServer.Controllers.UIStoresControllerBTCPayServer.Plugins.Crowdfund.Controllers.UICrowdfundControllerBTCPayServer.Services.UriResolverBTCPayServer.Hosting.StartupBTCPayServer.Hosting.MigrationStartupTaskInspect captured patch +312 / −1225
### BTCPayServer.Abstractions/Contracts/IFileService.cs
@@ -1,11 +1,12 @@
#nullable enable
using System;
using System.Threading.Tasks;
-using Microsoft.AspNetCore.Http;
using BTCPayServer.Abstractions.Models;
+using Microsoft.AspNetCore.Http;
namespace BTCPayServer.Abstractions.Contracts;
+[Obsolete("Inject FileService instead.")]
public interface IFileService
{
Task<bool> IsAvailable();
### BTCPayServer.Tests/LightningTests.cs
@@ -802,7 +802,23 @@ await TestUtils.EventuallyAsync(async () =>
//BTCPay will attempt to cancel previous bolt11 invoices so that there are less weird edge case scenarios
TestLogs.LogInformation($"Attempting to pay invoice {invoice.Id} original full amount bolt11 invoice");
var res = await tester.SendLightningPaymentAsync(invoice);
- Assert.Equal(PayResult.Error, res.Result);
+ if (res.Result == PayResult.Unknown)
+ {
+ // xpay can report the rejection before listpays records the final failure.
+ // Observe the existing payment rather than trying to pay the invoice again.
+ var bolt11 = invoice.CryptoInfo.First(o => o.PaymentUrls.BOLT11 != null).PaymentUrls.BOLT11;
+ var paymentHash = BOLT11PaymentRequest.Parse(bolt11, Network.RegTest).PaymentHash.ToString();
+ await TestUtils.EventuallyAsync(async () =>
+ {
+ var payment = await tester.CustomerLightningD.GetPayment(paymentHash);
+ Assert.NotNull(payment);
+ Assert.Equal(LightningPaymentStatus.Failed, payment.Status);
+ }, 5000);
+ }
+ else
+ {
+ Assert.Equal(PayResult.Error, res.Result);
+ }
//NOTE: Eclair does not support cancelling invoice so the below test case would make sense for it
// TestLogs.LogInformation($"Paying invoice {invoice.Id} original full amount bolt11 invoice ");
### BTCPayServer.Tests/ThirdPartyTests.cs
@@ -15,8 +15,6 @@
using BTCPayServer.Rating;
using BTCPayServer.Services.Fees;
using BTCPayServer.Services.Rates;
-using BTCPayServer.Storage.Models;
-using BTCPayServer.Storage.Services.Providers.AzureBlobStorage.Configuration;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
@@ -37,41 +35,6 @@ public ThirdPartyTests(ITestOutputHelper helper) : base(helper)
}
- [FactWithSecret("AzureBlobStorageConnectionString")]
- public async Task CanUseAzureBlobStorage()
- {
- using var tester = CreateServerTester();
- await tester.StartAsync();
- var user = tester.NewAccount();
- user.GrantAccess();
- var controller = tester.PayTester.GetController<UIServerController>(user.UserId, user.StoreId);
- var azureBlobStorageConfiguration = Assert.IsType<AzureBlobStorageConfiguration>(Assert
- .IsType<ViewResult>(await controller.StorageProvider(StorageProvider.AzureBlobStorage.ToString()))
- .Model);
-
- azureBlobStorageConfiguration.ConnectionString = FactWithSecretAttribute.GetFromSecrets("AzureBlobStorageConnectionString");
- azureBlobStorageConfiguration.ContainerName = "testscontainer";
- Assert.IsType<ViewResult>(
- await controller.EditAzureBlobStorageStorageProvider(azureBlobStorageConfiguration));
-
- var shouldBeRedirectingToAzureStorageConfigPage =
- Assert.IsType<RedirectToActionResult>(await controller.Storage());
- Assert.Equal(nameof(StorageProvider), shouldBeRedirectingToAzureStorageConfigPage.ActionName);
- Assert.Equal(StorageProvider.AzureBlobStorage,
- shouldBeRedirectingToAzureStorageConfigPage.RouteValues["provider"]);
-
- //seems like azure config worked, let's see if the conn string was actually saved
-
- Assert.Equal(azureBlobStorageConfiguration.ConnectionString, Assert
- .IsType<AzureBlobStorageConfiguration>(Assert
- .IsType<ViewResult>(
- await controller.StorageProvider(StorageProvider.AzureBlobStorage.ToString()))
- .Model).ConnectionString);
-
- var fileId = await UnitTest1.CanUploadFile(controller);
- await UnitTest1.CanRemoveFile(controller, fileId);
- }
-
[Fact(Skip = "Fail on CI")]
public async Task CanQueryMempoolFeeProvider()
{
### BTCPayServer.Tests/UnitTest1.cs
@@ -46,9 +46,7 @@
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Labels;
using BTCPayServer.Services.Notifications;
-using BTCPayServer.Storage.Models;
-using BTCPayServer.Storage.Services.Providers.FileSystemStorage.Configuration;
-using BTCPayServer.Storage.ViewModels;
+using BTCPayServer.Storage.Services;
using Fido2NetLib;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -2758,134 +2756,67 @@ await TestUtils.EventuallyAsync(async () =>
[Fact(Timeout = TestUtils.TestTimeout)]
[Trait("Integration", "Integration")]
- public async Task CanInitializeStorageOnFirstRun()
+ public async Task CanViewFiles()
{
using var tester = CreateServerTester(newDb: true);
await tester.StartAsync();
- var settings = tester.PayTester.GetService<SettingsRepository>();
- var storage = await settings.GetSettingAsync<StorageSettings>();
- Assert.NotNull(storage);
- Assert.Equal(StorageProvider.FileSystem, storage.Provider);
- Assert.Equal(JObject.FromObject(new FileSystemStorageConfiguration()), storage.Configuration);
-
- storage = new StorageSettings
- {
- Provider = StorageProvider.AmazonS3,
- Configuration = new JObject { ["BucketName"] = "existing-bucket" }
- };
- await settings.UpdateSetting(storage);
- await settings.UpdateSetting<MigrationSettings>(null, SettingsRepository.KeyNameByType(typeof(MigrationSettings)));
- await tester.PayTester.RestartStartupTask<MigrationStartupTask>();
- var existingStorage = await settings.GetSettingAsync<StorageSettings>();
- Assert.Equal(StorageProvider.AmazonS3, existingStorage.Provider);
- Assert.Equal(storage.Configuration, existingStorage.Configuration);
- }
-
- [Fact(Timeout = TestUtils.TestTimeout)]
- [Trait("Integration", "Integration")]
- public async Task CanConfigureStorage()
- {
- using var tester = CreateServerTester();
- await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
var controller = tester.PayTester.GetController<UIServerController>(user.UserId, user.StoreId);
-
-
- //Once we select a provider, redirect to its view
- var localResult = Assert
- .IsType<RedirectToActionResult>(controller.Storage(new StorageSettings()
- {
- Provider = StorageProvider.FileSystem
- }));
- Assert.Equal(nameof(UIServerController.StorageProvider), localResult.ActionName);
- Assert.Equal(StorageProvider.FileSystem.ToString(), localResult.RouteValues["provider"]);
-
-
- var AmazonS3result = Assert
- .IsType<RedirectToActionResult>(controller.Storage(new StorageSettings()
- {
- Provider = StorageProvider.AmazonS3
- }));
- Assert.Equal(nameof(UIServerController.StorageProvider), AmazonS3result.ActionName);
- Assert.Equal(StorageProvider.AmazonS3.ToString(), AmazonS3result.RouteValues["provider"]);
-
- var GoogleResult = Assert
- .IsType<RedirectToActionResult>(controller.Storage(new StorageSettings()
- {
- Provider = StorageProvider.GoogleCloudStorage
- }));
- Assert.Equal(nameof(UIServerController.StorageProvider), GoogleResult.ActionName);
- Assert.Equal(StorageProvider.GoogleCloudStorage.ToString(), GoogleResult.RouteValues["provider"]);
-
-
- var AzureResult = Assert
- .IsType<RedirectToActionResult>(controller.Storage(new StorageSettings()
- {
- Provider = StorageProvider.AzureBlobStorage
- }));
- Assert.Equal(nameof(UIServerController.StorageProvider), AzureResult.ActionName);
- Assert.Equal(StorageProvider.AzureBlobStorage.ToString(), AzureResult.RouteValues["provider"]);
-
- //Cool, we get redirected to the config pages
- //Let's configure this stuff
-
- //Let's try and cheat and go to an invalid storage provider config
- Assert.Equal(nameof(Storage), (Assert
- .IsType<RedirectToActionResult>(await controller.StorageProvider("I am not a real provider"))
- .ActionName));
-
- //ok no more messing around, let's configure this shit.
- var fileSystemStorageConfiguration = Assert.IsType<FileSystemStorageConfiguration>(Assert
- .IsType<ViewResult>(await controller.StorageProvider(StorageProvider.FileSystem.ToString()))
- .Model);
-
- //local file system does not need config, easy days!
- Assert.IsType<ViewResult>(
- await controller.EditFileSystemStorageProvider(fileSystemStorageConfiguration));
-
- //ok cool, let's see if this got set right
- var shouldBeRedirectingToLocalStorageConfigPage =
- Assert.IsType<RedirectToActionResult>(await controller.Storage());
- Assert.Equal(nameof(StorageProvider), shouldBeRedirectingToLocalStorageConfigPage.ActionName);
- Assert.Equal(StorageProvider.FileSystem,
- shouldBeRedirectingToLocalStorageConfigPage.RouteValues["provider"]);
-
-
- //if we tell the settings page to force, it should allow us to select a new provider
- Assert.IsType<ChooseStorageViewModel>(Assert.IsType<ViewResult>(await controller.Storage(true)).Model);
-
- //awesome, now let's see if the files result says we're all set up
var viewFilesViewModel =
Assert.IsType<ViewFilesViewModel>(Assert.IsType<ViewResult>(await controller.Files()).Model);
- Assert.True(viewFilesViewModel.StorageConfigured);
Assert.Empty(viewFilesViewModel.Files);
}
[Fact]
[Trait("Integration", "Integration")]
- public async Task CanUseLocalProviderFiles()
+ public async Task CanUseLocalFiles()
{
- using var tester = CreateServerTester();
+ using var tester = CreateServerTester(newDb: true);
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
var controller = tester.PayTester.GetController<UIServerController>(user.UserId, user.StoreId);
- var fileSystemStorageConfiguration = Assert.IsType<FileSystemStorageConfiguration>(Assert
- .IsType<ViewResult>(await controller.StorageProvider(StorageProvider.FileSystem.ToString()))
- .Model);
- Assert.IsType<ViewResult>(
- await controller.EditFileSystemStorageProvider(fileSystemStorageConfiguration));
-
- var shouldBeRedirectingToLocalStorageConfigPage =
- Assert.IsType<RedirectToActionResult>(await controller.Storage());
- Assert.Equal(nameof(StorageProvider), shouldBeRedirectingToLocalStorageConfigPage.ActionName);
- Assert.Equal(StorageProvider.FileSystem,
- shouldBeRedirectingToLocalStorageConfigPage.RouteValues["provider"]);
-
var fileId = await CanUploadFile(controller);
await CanRemoveFile(controller, fileId);
+
+ var fileService = tester.PayTester.GetService<FileService>();
+ var repository = tester.PayTester.GetService<StoredFileRepository>();
+ var root = tester.PayTester.GetService<Microsoft.Extensions.Options.IOptions<DataDirectories>>().Value.StorageDir;
+ using var http = new HttpClient();
+ foreach (var deletingUserId in new[] { user.UserId, null })
+ {
+ var name = "Photo 日本語 #100%.TXT";
+ var file = await fileService.AddFile(TestUtils.GetFormFile(name, "local content"), user.UserId);
+ var storedFile = await repository.GetFile(file.Id);
+ Assert.Equal(name, storedFile.FileName);
+ Assert.True(Guid.TryParse(storedFile.StorageFileName[..36], out _));
+ Assert.EndsWith("-" + name.ToLowerInvariant(), storedFile.StorageFileName);
+ var path = Path.Combine(root, storedFile.StorageFileName);
+ Assert.Equal("local content", await File.ReadAllTextAsync(path));
+ var url = await fileService.GetFileUrl(tester.PayTester.ServerUri, file.Id);
+ Assert.Equal("local content", await http.GetStringAsync(url));
+ using (var response = await http.GetAsync(url + "?download"))
+ {
+ Assert.Equal("attachment", response.Content.Headers.ContentDisposition?.DispositionType);
+ Assert.Equal("nosniff", Assert.Single(response.Headers.GetValues("X-Content-Type-Options")));
+ }
+ var prefixedUrl = await fileService.GetFileUrl(new Uri("https://example.com/btcpay/"), file.Id);
+ Assert.Equal("https://example.com/btcpay/LocalStorage/" +
+ Uri.EscapeDataString(storedFile.StorageFileName), prefixedUrl);
+
+ await fileService.RemoveFile(file.Id, "another-user");
+ Assert.True(File.Exists(path));
+ Assert.NotNull(await repository.GetFile(file.Id));
+ await fileService.RemoveFile(file.Id, deletingUserId);
+ Assert.False(File.Exists(path));
+ Assert.Null(await repository.GetFile(file.Id));
+ }
+
+ // Reject invalid input before writing files.
+ await Assert.ThrowsAsync<InvalidOperationException>(() =>
+ fileService.AddFile(new FormFile(Stream.Null, 0, 0, "file", "../outside.txt"), user.UserId));
}
internal static async Task<string> CanUploadFile(UIServerController controller)
### BTCPayServer/BTCPayServer.csproj
@@ -52,11 +52,6 @@
<PackageReference Include="Serilog" Version="4.4.0" />
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
- <PackageReference Include="TwentyTwenty.Storage" Version="3.0.0" />
- <PackageReference Include="TwentyTwenty.Storage.Amazon" Version="3.0.0" />
- <PackageReference Include="TwentyTwenty.Storage.Azure" Version="3.0.0" />
- <PackageReference Include="TwentyTwenty.Storage.Google" Version="3.0.0" />
- <PackageReference Include="TwentyTwenty.Storage.Local" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="10.0.15" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson" Version="10.0.15" />
</ItemGroup>
### BTCPayServer/Controllers/GreenField/GreenfieldAppsController.cs
@@ -16,6 +16,7 @@
using BTCPayServer.Services.Apps;
using BTCPayServer.Services.Rates;
using BTCPayServer.Services.Stores;
+using BTCPayServer.Storage.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
@@ -34,7 +35,7 @@ public class GreenfieldAppsController : ControllerBase
private readonly UriResolver _uriResolver;
private readonly StoreRepository _storeRepository;
private readonly CurrencyNameTable _currencies;
- private readonly IFileService _fileService;
+ private readonly FileService _fileService;
public Safe Safe { get; }
@@ -43,7 +44,7 @@ public GreenfieldAppsController(
UriResolver uriResolver,
StoreRepository storeRepository,
CurrencyNameTable currencies,
- IFileService fileService,
+ FileService fileService,
Safe safe
)
{
### BTCPayServer/Controllers/GreenField/GreenfieldFilesController.cs
@@ -18,7 +18,7 @@ namespace BTCPayServer.Controllers.Greenfield;
[EnableCors(CorsPolicies.All)]
[Authorize(Policy = Policies.CanModifyServerSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public class GreenfieldFilesController(
- IFileService fileService,
+ FileService fileService,
StoredFileRepository fileRepository)
: ControllerBase
{
### BTCPayServer/Controllers/GreenField/GreenfieldStoresController.cs
@@ -15,6 +15,7 @@
using BTCPayServer.Services;
using BTCPayServer.Services.Rates;
using BTCPayServer.Services.Stores;
+using BTCPayServer.Storage.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
@@ -35,7 +36,7 @@ public class GreenfieldStoresController : ControllerBase
private readonly StoreRepository _storeRepository;
private readonly CurrencyNameTable _currencyNameTable;
private readonly UserManager<ApplicationUser> _userManager;
- private readonly IFileService _fileService;
+ private readonly FileService _fileService;
private readonly UriResolver _uriResolver;
private readonly JsonSerializerSettings _serializedSettings;
private readonly PoliciesSettings _policiesSettings;
@@ -45,7 +46,7 @@ public GreenfieldStoresController(
StoreRepository storeRepository,
CurrencyNameTable currencyNameTable,
UserManager<ApplicationUser> userManager,
- IFileService fileService,
+ FileService fileService,
IOptions<MvcNewtonsoftJsonOptions> jsonOptions,
UriResolver uriResolver,
PoliciesSettings policiesSettings,
### BTCPayServer/Controllers/GreenField/GreenfieldUsersController.cs
@@ -17,6 +17,7 @@
using BTCPayServer.Security;
using BTCPayServer.Security.Greenfield;
using BTCPayServer.Services;
+using BTCPayServer.Storage.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
@@ -45,7 +46,7 @@ public class GreenfieldUsersController : ControllerBase
private readonly IAuthorizationService _authorizationService;
private readonly UserService _userService;
private readonly UriResolver _uriResolver;
- private readonly IFileService _fileService;
+ private readonly FileService _fileService;
public GreenfieldUsersController(UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
@@ -59,7 +60,7 @@ public GreenfieldUsersController(UserManager<ApplicationUser> userManager,
IAuthorizationService authorizationService,
UserService userService,
UriResolver uriResolver,
- IFileService fileService,
+ FileService fileService,
Logs logs)
{
this.Logs = logs;
### BTCPayServer/Controllers/UIAppsController.cs
@@ -12,6 +12,7 @@
using BTCPayServer.Services.Apps;
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Stores;
+using BTCPayServer.Storage.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -26,7 +27,7 @@ public partial class UIAppsController(
PaymentMethodHandlerDictionary handlers,
BTCPayNetworkProvider networkProvider,
StoreRepository storeRepository,
- IFileService fileService,
+ FileService fileService,
AppService appService,
IStringLocalizer stringLocalizer,
ViewLocalizer viewLocalizer,
### BTCPayServer/Controllers/UIManageController.cs
@@ -14,6 +14,7 @@
using BTCPayServer.Security.Greenfield;
using BTCPayServer.Services;
using BTCPayServer.Services.Stores;
+using BTCPayServer.Storage.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
@@ -39,7 +40,7 @@ public partial class UIManageController : Controller
private readonly IHtmlHelper Html;
private readonly UserService _userService;
private readonly UriResolver _uriResolver;
- private readonly IFileService _fileService;
+ private readonly FileService _fileService;
private readonly EventAggregator _eventAggregator;
private readonly PermissionService _permissionService;
readonly StoreRepository _StoreRepository;
@@ -59,7 +60,7 @@ public UIManageController(
CallbackGenerator callbackGenerator,
UserService userService,
UriResolver uriResolver,
- IFileService fileService,
+ FileService fileService,
IStringLocalizer stringLocalizer,
IHtmlHelper htmlHelper,
EventAggregator eventAggregator,
### BTCPayServer/Controllers/UIServerController.Storage.cs
@@ -1,25 +1,11 @@
using System;
using System.Collections.Generic;
-using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Models.ServerViewModels;
-using BTCPayServer.Storage.Models;
-using BTCPayServer.Storage.Services.Providers.AmazonS3Storage;
-using BTCPayServer.Storage.Services.Providers.AmazonS3Storage.Configuration;
-using BTCPayServer.Storage.Services.Providers.AzureBlobStorage;
-using BTCPayServer.Storage.Services.Providers.AzureBlobStorage.Configuration;
-using BTCPayServer.Storage.Services.Providers.FileSystemStorage;
-using BTCPayServer.Storage.Services.Providers.FileSystemStorage.Configuration;
-using BTCPayServer.Storage.Services.Providers.GoogleCloudStorage;
-using BTCPayServer.Storage.Services.Providers.GoogleCloudStorage.Configuration;
-using BTCPayServer.Storage.Services.Providers.Models;
-using BTCPayServer.Storage.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.Mvc.Rendering;
-using Newtonsoft.Json.Linq;
namespace BTCPayServer.Controllers
{
@@ -31,8 +17,7 @@ public async Task<IActionResult> Files([FromQuery] string[] fileIds = null)
var model = new ViewFilesViewModel()
{
Files = await _StoredFileRepository.GetFiles(),
- DirectUrlByFiles = null,
- StorageConfigured = (await _SettingsRepository.GetSettingAsync<StorageSettings>()) != null
+ DirectUrlByFiles = null
};
if (fileIds != null && fileIds.Length > 0)
@@ -145,134 +130,5 @@ public async Task<IActionResult> CreateFiles(List<IFormFile> files)
private string GetUserId() => ControllerContext.HttpContext.User.GetIdOrNull();
- [HttpGet("server/storage")]
- public async Task<IActionResult> Storage(bool forceChoice = false)
- {
- var savedSettings = await _SettingsRepository.GetSettingAsync<StorageSettings>();
- if (forceChoice || savedSettings == null)
- {
- var providersList = _StorageProviderServices.Select(a =>
- new SelectListItem(typeof(StorageProvider).DisplayName(a.StorageProvider().ToString()), a.StorageProvider().ToString())
- );
-
- return View(new ChooseStorageViewModel
- {
- ProvidersList = providersList,
- ShowChangeWarning = savedSettings != null,
- Provider = savedSettings?.Provider ?? BTCPayServer.Storage.Models.StorageProvider.FileSystem
- });
- }
-
- return RedirectToAction(nameof(StorageProvider), new
- {
- provider = savedSettings.Provider
- });
- }
-
- [HttpPost("server/storage")]
- public IActionResult Storage(StorageSettings viewModel)
- {
- return RedirectToAction("StorageProvider", "UIServer", new
- {
- provider = viewModel.Provider.ToString()
- });
- }
-
- [HttpGet("server/storage/{provider}")]
- public async Task<IActionResult> StorageProvider(string provider)
- {
- if (!Enum.TryParse(typeof(StorageProvider), provider, out var storageProvider))
- {
- TempData.SetStatusMessageModel(new StatusMessageModel
- {
- Severity = StatusMessageModel.StatusSeverity.Error,
- Message = StringLocalizer["{0} provider is not supported", provider].Value
- });
- return RedirectToAction(nameof(Storage));
- }
-
- var data = (await _SettingsRepository.GetSettingAsync<StorageSettings>()) ?? new StorageSettings();
-
- var storageProviderService =
- _StorageProviderServices.SingleOrDefault(service => service.StorageProvider().Equals(storageProvider));
-
- switch (storageProviderService)
- {
- case null:
- TempData.SetStatusMessageModel(new StatusMessageModel
- {
- Severity = StatusMessageModel.StatusSeverity.Error,
- Message = StringLocalizer["{0} provider is not supported", storageProvider].Value
- });
- return RedirectToAction(nameof(Storage));
- case AzureBlobStorageFileProviderService fileProviderService:
- return View(nameof(EditAzureBlobStorageStorageProvider),
- fileProviderService.GetProviderConfiguration(data));
-
- case AmazonS3FileProviderService fileProviderService:
- return View(nameof(EditAmazonS3StorageProvider),
- fileProviderService.GetProviderConfiguration(data));
- case GoogleCloudStorageFileProviderService fileProviderService:
- return View(nameof(EditGoogleCloudStorageStorageProvider),
- fileProviderService.GetProviderConfiguration(data));
- case FileSystemFileProviderService fileProviderService:
- if (data.Provider != BTCPayServer.Storage.Models.StorageProvider.FileSystem)
- {
- _ = await SaveStorageProvider(new FileSystemStorageConfiguration(),
- BTCPayServer.Storage.Models.StorageProvider.FileSystem);
- }
-
- return View(nameof(EditFileSystemStorageProvider),
- fileProviderService.GetProviderConfiguration(data));
- }
-
- return NotFound();
- }
-
-
- [HttpPost("server/storage/AzureBlobStorage")]
- public async Task<IActionResult> EditAzureBlobStorageStorageProvider(AzureBlobStorageConfiguration viewModel)
- {
- return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.AzureBlobStorage);
- }
-
- [HttpPost("server/storage/AmazonS3")]
- public async Task<IActionResult> EditAmazonS3StorageProvider(AmazonS3StorageConfiguration viewModel)
- {
- return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.AmazonS3);
- }
-
- [HttpPost("server/storage/GoogleCloudStorage")]
- public async Task<IActionResult> EditGoogleCloudStorageStorageProvider(
- GoogleCloudStorageConfiguration viewModel)
- {
- return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.GoogleCloudStorage);
- }
-
- [HttpPost("server/storage/FileSystem")]
- public async Task<IActionResult> EditFileSystemStorageProvider(FileSystemStorageConfiguration viewModel)
- {
- return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.FileSystem);
- }
-
- private async Task<IActionResult> SaveStorageProvider(IBaseStorageConfiguration viewModel,
- StorageProvider storageProvider)
- {
- if (!ModelState.IsValid)
- {
- return View(viewModel);
- }
-
- var data = (await _SettingsRepository.GetSettingAsync<StorageSettings>()) ?? new StorageSettings();
- data.Provider = storageProvider;
- data.Configuration = JObject.FromObject(viewModel);
- await _SettingsRepository.UpdateSetting(data);
- TempData.SetStatusMessageModel(new StatusMessageModel
- {
- Severity = StatusMessageModel.StatusSeverity.Success,
- Message = StringLocalizer["Storage settings updated successfully"].Value
- });
- return View(viewModel);
- }
}
}
### BTCPayServer/Controllers/UIServerController.cs
@@ -28,7 +28,6 @@
using BTCPayServer.Services.Apps;
using BTCPayServer.Services.Stores;
using BTCPayServer.Storage.Services;
-using BTCPayServer.Storage.Services.Providers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Identity;
@@ -66,8 +65,7 @@ public partial class UIServerController : Controller
private readonly IOptions<ExternalServicesOptions> _externalServiceOptions;
private readonly Logs Logs;
private readonly StoredFileRepository _StoredFileRepository;
- private readonly IFileService _fileService;
- private readonly IEnumerable<IStorageProviderService> _StorageProviderServices;
+ private readonly FileService _fileService;
private readonly CallbackGenerator _callbackGenerator;
private readonly UriResolver _uriResolver;
private readonly TransactionLinkProviders _transactionLinkProviders;
@@ -80,9 +78,8 @@ public UIServerController(
UserManager<ApplicationUser> userManager,
UserService userService,
StoredFileRepository storedFileRepository,
- IFileService fileService,
+ FileService fileService,
EmailSenderFactory emailSenderFactory,
- IEnumerable<IStorageProviderService> storageProviderServices,
BTCPayServerOptions options,
SettingsRepository settingsRepository,
PoliciesSettings policiesSettings,
@@ -112,7 +109,6 @@ BTCPayServerSecurityStampValidator.SecurityStampInvalidator securityStampInvalid
_Options = options;
_StoredFileRepository = storedFileRepository;
_fileService = fileService;
- _StorageProviderServices = storageProviderServices;
_UserManager = userManager;
_userService = userService;
_SettingsRepository = settingsRepository;
### BTCPayServer/Controllers/UIStoresController.cs
@@ -18,6 +18,7 @@
using BTCPayServer.Services.Rates;
using BTCPayServer.Services.Stores;
using BTCPayServer.Services.Wallets;
+using BTCPayServer.Storage.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
@@ -47,7 +48,7 @@ public UIStoresController(
PoliciesSettings policiesSettings,
IAuthorizationService authorizationService,
AppService appService,
- IFileService fileService,
+ FileService fileService,
IDataProtectionProvider dataProtector,
IOptions<LightningNetworkOptions> lightningNetworkOptions,
IOptions<ExternalServicesOptions> externalServiceOptions,
@@ -114,7 +115,7 @@ public UIStoresController(
private readonly PoliciesSettings _policiesSettings;
private readonly IAuthorizationService _authorizationService;
private readonly AppService _appService;
- private readonly IFileService _fileService;
+ private readonly FileService _fileService;
private readonly IOptions<ExternalServicesOptions> _externalServiceOptions;
private readonly EmailSenderFactory _emailSenderFactory;
private readonly WalletFileParsers _onChainWalletParsers;
### BTCPayServer/Extensions.cs
@@ -983,7 +983,7 @@ public static DataDirectories Configure(this DataDirectories dataDirectories, IC
var defaultSettings = BTCPayDefaultSettings.GetDefaultSettings(networkType);
dataDirectories.DataDir = configuration["datadir"] ?? defaultSettings.DefaultDataDirectory;
dataDirectories.PluginDir = configuration["plugindir"] ?? defaultSettings.DefaultPluginDirectory;
- dataDirectories.StorageDir = Path.Combine(dataDirectories.DataDir, Storage.Services.Providers.FileSystemStorage.FileSystemFileProviderService.LocalStorageDirectoryName);
+ dataDirectories.StorageDir = Path.Combine(dataDirectories.DataDir, Storage.Services.FileService.LocalStorageDirectoryName);
dataDirectories.TempStorageDir = Path.Combine(dataDirectories.StorageDir, "tmp");
dataDirectories.TempDir = Path.Combine(dataDirectories.DataDir, "tmp");
dataDirectories.LangsDir = Path.Combine(dataDirectories.DataDir, "Langs");
### BTCPayServer/Hosting/MigrationStartupTask.cs
@@ -11,8 +11,6 @@
using BTCPayServer.Payments.Lightning;
using BTCPayServer.Services;
using BTCPayServer.Services.Invoices;
-using BTCPayServer.Storage.Models;
-using BTCPayServer.Storage.Services.Providers.FileSystemStorage.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
@@ -43,14 +41,6 @@ public async Task ExecuteAsync(CancellationToken cancellationToken = default)
{
prop.SetValue(settings, true);
}
- if (await settingsRepository.GetSettingAsync<StorageSettings>() is null)
- {
- await settingsRepository.UpdateSetting(new StorageSettings
- {
- Provider = StorageProvider.FileSystem,
- Configuration = JObject.FromObject(new FileSystemStorageConfiguration())
- });
- }
await settingsRepository.UpdateSetting(new ThemeSettings());
await settingsRepository.UpdateSetting(settings);
}
### BTCPayServer/Hosting/Startup.cs
@@ -127,7 +127,7 @@ public void ConfigureServices(IServiceCollection services)
});
services.AddBTCPayServer(Configuration, Logs);
- services.AddProviderStorage();
+ services.AddFileStorage();
services.AddSession();
services.AddSignalR().AddNewtonsoftJsonProtocol(options =>
{
@@ -359,7 +359,7 @@ private void ConfigureCore(IApplicationBuilder app, IWebHostEnvironment env, ISe
});
}
- app.UseProviderStorage(dataDirectories);
+ app.UseFileStorage(dataDirectories);
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<UserLanguageMiddleware>();
### BTCPayServer/Models/ServerViewModels/ViewFilesViewModel.cs
@@ -7,6 +7,5 @@ public class ViewFilesViewModel
{
public List<StoredFile> Files { get; set; }
public Dictionary<string, string> DirectUrlByFiles { get; set; }
- public bool StorageConfigured { get; set; }
}
}
### BTCPayServer/Plugins/Crowdfund/Controllers/UICrowdfundController.cs
@@ -25,6 +25,7 @@
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Rates;
using BTCPayServer.Services.Stores;
+using BTCPayServer.Storage.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
@@ -46,7 +47,7 @@ public class UICrowdfundController(
EventAggregator eventAggregator,
UriResolver uriResolver,
StoreRepository storeRepository,
- IFileService fileService,
+ FileService fileService,
UIInvoiceController invoiceController,
FormDataService formDataService,
IStringLocalizer stringLocalizer,
### BTCPayServer/Plugins/Crowdfund/Views/UpdateCrowdfund.cshtml
@@ -1,17 +1,14 @@
@using System.Globalization
-@using BTCPayServer.Abstractions.Contracts
@using BTCPayServer.Client
@using BTCPayServer.Forms
@using BTCPayServer.Plugins.Crowdfund
@inject FormDataService FormDataService
-@inject IFileService FileService
@inject BTCPayServer.Security.ContentSecurityPolicies Csp
@model BTCPayServer.Plugins.Crowdfund.Models.UpdateCrowdfundViewModel
@{
Layout = "_Layout";
ViewData.SetLayoutModel(new LayoutModel($"{nameof(CrowdfundPlugin)}-{Model.AppId}", StringLocalizer["Update Crowdfund"]));
Csp.UnsafeEval();
- var canUpload = await FileService.IsAvailable();
var checkoutFormOptions = await FormDataService.GetSelect(Context.GetStoreData().Id, Model.FormId);
}
@@ -82,22 +79,14 @@
</button>
}
</div>
- @if (canUpload)
- {
- <div class="d-flex align-items-center gap-3">
- <input asp-for="MainImageFile" type="file" class="form-control flex-grow">
- @if (!string.IsNullOrEmpty(Model.MainImageUrl))
- {
- <img src="@Model.MainImageUrl" alt="Logo" style="height:2.1rem;max-width:10.5rem;" />
- }
- </div>
- <span asp-validation-for="MainImageFile" class="text-danger"></span>
- }
- else
- {
- <input asp-for="MainImageFile" type="file" class="form-control" disabled>
- <div class="form-text">@ViewLocalizer["In order to upload, a {0} must be configured.", Html.ActionLink(StringLocalizer["file storage"], "Files", "UIServer")]</div>
- }
+ <div class="d-flex align-items-center gap-3">
+ <input asp-for="MainImageFile" type="file" class="form-control flex-grow">
+ @if (!string.IsNullOrEmpty(Model.MainImageUrl))
+ {
+ <img src="@Model.MainImageUrl" alt="Logo" style="height:2.1rem;max-width:10.5rem;" />
+ }
+ </div>
+ <span asp-validation-for="MainImageFile" class="text-danger"></span>
</div>
<div class="form-group">
<div class="d-flex align-items-center">
### BTCPayServer/Services/UriResolver.cs
@@ -1,15 +1,15 @@
#nullable enable
using System;
using System.Threading.Tasks;
-using BTCPayServer.Abstractions.Contracts;
+using BTCPayServer.Storage.Services;
namespace BTCPayServer.Services
{
public class UriResolver
{
- private readonly IFileService _fileService;
+ private readonly FileService _fileService;
- public UriResolver(IFileService fileService)
+ public UriResolver(FileService fileService)
{
_fileService = fileService;
}
### BTCPayServer/Storage/Models/StorageProvider.cs
@@ -1,19 +0,0 @@
-using System.ComponentModel.DataAnnotations;
-
-namespace BTCPayServer.Storage.Models
-{
- public enum StorageProvider
- {
- [Display(Name = "Azure Blob Storage")]
- AzureBlobStorage = 0,
-
- [Display(Name = "Amazon S3")]
- AmazonS3 = 1,
-
- [Display(Name = "Google Cloud Storage")]
- GoogleCloudStorage = 2,
-
- [Display(Name = "Local File System")]
- FileSystem = 3
- }
-}
### BTCPayServer/Storage/Models/StorageSettings.cs
@@ -1,18 +0,0 @@
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-
-namespace BTCPayServer.Storage.Models
-{
- public class StorageSettings
- {
- public StorageProvider Provider { get; set; }
- public string ConfigurationStr { get; set; }
-
- [JsonIgnore]
- public JObject Configuration
- {
- get => JsonConvert.DeserializeObject<JObject>(string.IsNullOrEmpty(ConfigurationStr) ? "{}" : ConfigurationStr);
- set => ConfigurationStr = value.ToString();
- }
- }
-}
### BTCPayServer/Storage/Services/FileService.cs
@@ -1,56 +1,36 @@
#nullable enable
using System;
-using System.Collections.Generic;
using System.IO;
-using System.Linq;
-using System.Net.Http;
-using System.Text.RegularExpressions;
using System.Threading.Tasks;
-using System.Web;
using BTCPayServer.Abstractions.Contracts;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Configuration;
+using BTCPayServer.Data;
using BTCPayServer.Services;
-using BTCPayServer.Storage.Models;
-using BTCPayServer.Storage.Services.Providers;
using Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
namespace BTCPayServer.Storage.Services
{
- public class FileService : IFileService
+ public class FileService
{
+ public const string LocalStorageDirectoryName = "LocalStorage";
+
private readonly StoredFileRepository _fileRepository;
- private readonly IEnumerable<IStorageProviderService> _providers;
- private readonly SettingsRepository _settingsRepository;
private readonly IOptions<DataDirectories> _dataDirectories;
- private readonly IHttpClientFactory _httpClientFactory;
private IStringLocalizer StringLocalizer { get; }
public FileService(StoredFileRepository fileRepository,
- SettingsRepository settingsRepository,
- IEnumerable<IStorageProviderService> providers,
- IHttpClientFactory httpClientFactory,
IStringLocalizer stringLocalizer,
IOptions<DataDirectories> dataDirectories)
{
_fileRepository = fileRepository;
- _providers = providers;
- _settingsRepository = settingsRepository;
- _httpClientFactory = httpClientFactory;
_dataDirectories = dataDirectories;
StringLocalizer = stringLocalizer;
}
- public async Task<bool> IsAvailable()
- {
- var settings = await _settingsRepository.GetSettingAsync<StorageSettings>();
- return settings is not null;
- }
-
public async Task<UploadImageResultModel> UploadImage(IFormFile file, string userId, long maxFileSizeInBytes = 1_000_000)
{
var result = new UploadImageResultModel();
@@ -91,68 +71,60 @@ public async Task<UploadImageResultModel> UploadImage(IFormFile file, string use
public async Task<IStoredFile> AddFile(IFormFile file, string userId)
{
- var settings = await _settingsRepository.GetSettingAsync<StorageSettings>();
- if (settings is null)
- throw new InvalidOperationException("StoreSettings not configured");
if (!file.FileName.IsValidFileName())
throw new InvalidOperationException("Invalid file name");
- var provider = GetProvider(settings);
- var storedFile = await provider.AddFile(file, settings);
- storedFile.ApplicationUserId = userId;
+ var storedFile = new StoredFile
+ {
+ Timestamp = DateTime.UtcNow,
+ FileName = file.FileName,
+ StorageFileName = $"{Guid.NewGuid()}-{file.FileName.ToLowerInvariant()}",
+ ApplicationUserId = userId
+ };
+ var path = GetFilePath(storedFile);
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ await using (var output = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, true))
+ {
+ await file.CopyToAsync(output);
+ }
await _fileRepository.AddFile(storedFile);
return storedFile;
}
public async Task<string?> GetFileUrl(Uri baseUri, string fileId)
{
- var settings = await _settingsRepository.GetSettingAsync<StorageSettings>();
- if (settings is null)
- return null;
- var provider = GetProvider(settings);
var storedFile = await _fileRepository.GetFile(fileId);
- return storedFile == null ? null : await provider.GetFileUrl(baseUri, storedFile, settings);
+ if (storedFile is null)
+ return null;
+
+ var escapedPath = Uri.EscapeDataString(Path.GetFileName(GetFilePath(storedFile)));
+ return new Uri(baseUri, $"{baseUri.AbsolutePath.TrimEnd('/')}/{LocalStorageDirectoryName}/{escapedPath}").AbsoluteUri;
}
public async Task RemoveFile(string fileId, string userId)
{
- var settings = await _settingsRepository.GetSettingAsync<StorageSettings>();
- if (settings is null)
- return;
- var provider = GetProvider(settings);
var storedFile = await _fileRepository.GetFile(fileId);
if (storedFile != null && (string.IsNullOrEmpty(userId) ||
storedFile.ApplicationUserId.Equals(userId, StringComparison.InvariantCultureIgnoreCase)))
{
- await provider.RemoveFile(storedFile, settings);
+ var path = GetFilePath(storedFile);
+ if (!File.Exists(path))
+ throw new FileNotFoundException("The stored file was not found.", path);
+ File.Delete(path);
await _fileRepository.RemoveFile(storedFile);
}
}
- private IStorageProviderService GetProvider(StorageSettings storageSettings)
+ private string GetFilePath(StoredFile storedFile)
{
- return _providers.First(service => service.StorageProvider().Equals(storageSettings.Provider));
- }
-
- private static string GetContentType(string filePath)
- {
- var mimeProvider = new FileExtensionContentTypeProvider();
- if (!mimeProvider.TryGetContentType(filePath, out string? contentType))
- {
- contentType = "application/octet-stream";
- }
-
- return contentType;
- }
-
- private static string Sanitize(string fileName)
- {
- var invalid = Path.GetInvalidFileNameChars().Concat(":").ToArray();
- // replace invalid chars in url-decoded filename
- var name = string.Join("_", HttpUtility.UrlDecode(fileName)
- .Split(invalid, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
- // replace multiple underscores with just one
- return Regex.Replace(name, @"_+", "_");
+ if (!storedFile.StorageFileName.IsValidFileName())
+ throw new InvalidOperationException("Invalid file name");
+ var root = Path.GetFullPath(_dataDirectories.Value.StorageDir);
+ var path = Path.GetFullPath(Path.Combine(root, storedFile.StorageFileName));
+ var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
+ if (!path.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, comparison))
+ throw new InvalidOperationException("Invalid storage path");
+ return path;
}
}
}
### BTCPayServer/Storage/Services/LegacyFileService.cs
@@ -0,0 +1,24 @@
+#nullable enable
+using System;
+using System.Threading.Tasks;
+using BTCPayServer.Abstractions.Contracts;
+using BTCPayServer.Abstractions.Models;
+using Microsoft.AspNetCore.Http;
+
+namespace BTCPayServer.Storage.Services;
+
+#pragma warning disable CS0618 // Compatibility adapter for plugins using IFileService.
+class LegacyFileService(FileService fileService) : IFileService
+#pragma warning restore CS0618
+{
+ public Task<bool> IsAvailable() => Task.FromResult(true);
+
+ public Task<IStoredFile> AddFile(IFormFile file, string userId) => fileService.AddFile(file, userId);
+
+ public Task<string?> GetFileUrl(Uri baseUri, string fileId) => fileService.GetFileUrl(baseUri, fileId);
+
+ public Task RemoveFile(string fileId, string userId) => fileService.RemoveFile(fileId, userId);
+
+ public Task<UploadImageResultModel> UploadImage(IFormFile file, string userId, long maxFileSizeInBytes = 1_000_000) =>
+ fileService.UploadImage(file, userId, maxFileSizeInBytes);
+}
### BTCPayServer/Storage/Services/Providers/AmazonS3Storage/AmazonS3FileProviderService.cs
@@ -1,22 +0,0 @@
-using System.Threading.Tasks;
-using BTCPayServer.Storage.Models;
-using BTCPayServer.Storage.Services.Providers.AmazonS3Storage.Configuration;
-using TwentyTwenty.Storage;
-using TwentyTwenty.Storage.Amazon;
-
-namespace BTCPayServer.Storage.Services.Providers.AmazonS3Storage
-{
- public class
- AmazonS3FileProviderService : BaseTwentyTwentyStorageFileProviderServiceBase<AmazonS3StorageConfiguration>
- {
- public override StorageProvider StorageProvider()
- {
- return Storage.Models.StorageProvider.AmazonS3;
- }
-
- protected override Task<IStorageProvider> GetStorageProvider(AmazonS3StorageConfiguration configuration)
- {
- return Task.FromResult<IStorageProvider>(new AmazonStorageProvider(configuration));
- }
- }
-}
### BTCPayServer/Storage/Services/Providers/AmazonS3Storage/Configuration/AmazonS3StorageConfiguration.cs
@@ -1,10 +0,0 @@
-using BTCPayServer.Storage.Services.Providers.Models;
-using TwentyTwenty.Storage.Amazon;
-
-namespace BTCPayServer.Storage.Services.Providers.AmazonS3Storage.Configuration
-{
- public class AmazonS3StorageConfiguration : AmazonProviderOptions, IBaseStorageConfiguration
- {
- public string ContainerName { get; set; }
- }
-}
### BTCPayServer/Storage/Services/Providers/AzureBlobStorage/AzureBlobStorageFileProviderService.cs
@@ -1,22 +0,0 @@
-using System.Threading.Tasks;
-using BTCPayServer.Storage.Models;
-using BTCPayServer.Storage.Services.Providers.AzureBlobStorage.Configuration;
-using TwentyTwenty.Storage;
-using TwentyTwenty.Storage.Azure;
-
-namespace BTCPayServer.Storage.Services.Providers.AzureBlobStorage
-{
- public class
- AzureBlobStorageFileProviderService : BaseTwentyTwentyStorageFileProviderServiceBase<
- AzureBlobStorageConfiguration>
- {
- public override StorageProvider StorageProvider()
- {
- return Storage.Models.StorageProvider.AzureBlobStorage;
- }
- protected override Task<IStorageProvider> GetStorageProvider(AzureBlobStorageConfiguration configuration)
- {
- return Task.FromResult<IStorageProvider>(new AzureStorageProvider(configuration));
- }
- }
-}
### BTCPayServer/Storage/Services/Providers/AzureBlobStorage/Configuration/AzureBlobStorageConfiguration.cs
@@ -1,18 +0,0 @@
-using System.ComponentModel.DataAnnotations;
-using BTCPayServer.Storage.Services.Providers.Models;
-using Microsoft.AspNetCore.Mvc;
-using TwentyTwenty.Storage.Azure;
-
-namespace BTCPayServer.Storage.Services.Providers.AzureBlobStorage.Configuration
-{
- [ModelMetadataType(typeof(AzureBlobStorageConfigurationMetadata))]
- public class AzureBlobStorageConfiguration : AzureProviderOptions, IBaseStorageConfiguration
- {
- [Required]
- [MinLength(3)]
- [MaxLength(63)]
- [RegularExpression(@"[a-z0-9-]+",
- ErrorMessage = "Characters must be lowercase or digits or -")]
- public string ContainerName { get; set; }
- }
-}
### BTCPayServer/Storage/Services/Providers/AzureBlobStorage/Configuration/AzureBlobStorageConfigurationMetadata.cs
@@ -1,11 +0,0 @@
-using System.ComponentModel.DataAnnotations;
-
-namespace BTCPayServer.Storage.Services.Providers.AzureBlobStorage.Configuration
-{
- public class AzureBlobStorageConfigurationMetadata
- {
- [Required]
- [AzureBlobStorageConnectionStringValidator]
- public string ConnectionString { get; set; }
- }
-}
### BTCPayServer/Storage/Services/Providers/AzureBlobStorage/Configuration/AzureBlobStorageConnectionStringValidator.cs
@@ -1,21 +0,0 @@
-using System;
-using System.ComponentModel.DataAnnotations;
-
-namespace BTCPayServer.Storage.Services.Providers.AzureBlobStorage.Configuration
-{
- public class AzureBlobStorageConnectionStringValidator : ValidationAttribute
- {
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
- {
- try
- {
- new Azure.Storage.Blobs.BlobClient(value as string, "unusedcontainer", "unusedblob");
- return ValidationResult.Success;
- }
- catch (Exception e)
- {
- return new ValidationResult(e.Message);
- }
- }
- }
-}
### BTCPayServer/Storage/Services/Providers/BaseTwentyTwentyStorageFileProviderServiceBase.cs
@@ -1,64 +0,0 @@
-using System;
-using System.Threading.Tasks;
-using BTCPayServer.Data;
-using BTCPayServer.Storage.Models;
-using BTCPayServer.Storage.Services.Providers.Models;
-using Microsoft.AspNetCore.Http;
-using TwentyTwenty.Storage;
-
-namespace BTCPayServer.Storage.Services.Providers
-{
- public abstract class
- BaseTwentyTwentyStorageFileProviderServiceBase<TStorageConfiguration> : IStorageProviderService
- where TStorageConfiguration : IBaseStorageConfiguration
- {
- public abstract StorageProvider StorageProvider();
-
- public async Task<StoredFile> AddFile(IFormFile file, StorageSettings configuration)
- {
- //respect https://www.microsoftpressstore.com/articles/article.aspx?p=2224058&seqNum=8 in naming
- var storageFileName = $"{Guid.NewGuid()}-{file.FileName.ToLowerInvariant()}";
- var providerConfiguration = GetProviderConfiguration(configuration);
- var provider = await GetStorageProvider(providerConfiguration);
- using (var fileStream = file.OpenReadStream())
- {
- await provider.SaveBlobStreamAsync(providerConfiguration.ContainerName, storageFileName, fileStream,
- new BlobProperties()
- {
- ContentType = file.ContentType,
- ContentDisposition = file.ContentDisposition,
- Security = BlobSecurity.Public,
- });
- }
-
- return new StoredFile()
- {
- Timestamp = DateTime.UtcNow,
- FileName = file.FileName,
- StorageFileName = storageFileName
- };
- }
-
- public virtual async Task<string> GetFileUrl(Uri baseUri, StoredFile storedFile, StorageSettings configuration)
- {
- var providerConfiguration = GetProviderConfiguration(configuration);
- var provider = await GetStorageProvider(providerConfiguration);
- return provider.GetBlobUrl(providerConfiguration.ContainerName, storedFile.StorageFileName);
- }
-
- public async Task RemoveFile(StoredFile storedFile, StorageSettings configuration)
- {
- var providerConfiguration = GetProviderConfiguration(configuration);
- var provider = await GetStorageProvider(providerConfiguration);
- await provider.DeleteBlobAsync(providerConfiguration.ContainerName, storedFile.StorageFileName);
- }
-
- public TStorageConfiguration GetProviderConfiguration(StorageSettings configuration)
- {
- return configuration.Configuration.ToObject<TStorageConfiguration>();
- }
-
-
- protected abstract Task<IStorageProvider> GetStorageProvider(TStorageConfiguration configuration);
- }
-}
### BTCPayServer/Storage/Services/Providers/FileSystemStorage/Configuration/FileSystemStorageConfiguration.cs
@@ -1,9 +0,0 @@
-using BTCPayServer.Storage.Services.Providers.Models;
-
-namespace BTCPayServer.Storage.Services.Providers.FileSystemStorage.Configuration
-{
- public class FileSystemStorageConfiguration : IBaseStorageConfiguration
- {
- public string ContainerName { get; set; } = string.Empty;
- }
-}
### BTCPayServer/Storage/Services/Providers/FileSystemStorage/FileSystemFileProviderService.cs
@@ -1,50 +0,0 @@
-using System;
-using System.IO;
-using System.Threading.Tasks;
-using BTCPayServer.Configuration;
-using BTCPayServer.Data;
-using BTCPayServer.Storage.Models;
-using BTCPayServer.Storage.Services.Providers.FileSystemStorage.Configuration;
-using Microsoft.Extensions.Options;
-using Newtonsoft.Json;
-using TwentyTwenty.Storage;
-using TwentyTwenty.Storage.Local;
-
-namespace BTCPayServer.Storage.Services.Providers.FileSystemStorage
-{
- public class
- FileSystemFileProviderService : BaseTwentyTwentyStorageFileProviderServiceBase<FileSystemStorageConfiguration>
- {
- private readonly IOptions<DataDirectories> _datadirs;
-
- public FileSystemFileProviderService(IOptions<DataDirectories> datadirs)
- {
- _datadirs = datadirs;
- }
- public const string LocalStorageDirectoryName = "LocalStorage";
-
- public override StorageProvider StorageProvider()
- {
- return Storage.Models.StorageProvider.FileSystem;
- }
-
- protected override Task<IStorageProvider> GetStorageProvider(FileSystemStorageConfiguration configuration)
- {
- return Task.FromResult<IStorageProvider>(
- new LocalStorageProvider(new DirectoryInfo(_datadirs.Value.StorageDir).FullName));
- }
-
- public override async Task<string> GetFileUrl(Uri baseUri, StoredFile storedFile, StorageSettings configuration)
- {
- var baseResult = await base.GetFileUrl(baseUri, storedFile, configuration);
- // Set the relative URL to the directory name if the root path is default, otherwise add root path before the directory name
- var relativeUrl = baseUri.AbsolutePath == "/" ? LocalStorageDirectoryName : $"{baseUri.AbsolutePath}/{LocalStorageDirectoryName}";
- var url = new Uri(baseUri, relativeUrl);
- var r = baseResult.Replace(new DirectoryInfo(_datadirs.Value.StorageDir).FullName, url.AbsoluteUri,
- StringComparison.InvariantCultureIgnoreCase);
- if (Path.DirectorySeparatorChar == '\\')
- r = r.Replace(Path.DirectorySeparatorChar, '/');
- return r;
- }
- }
-}
### BTCPayServer/Storage/Services/Providers/GoogleCloudStorage/Configuration/GoogleCloudStorageConfiguration.cs
@@ -1,11 +0,0 @@
-using BTCPayServer.Storage.Services.Providers.Models;
-using TwentyTwenty.Storage.Google;
-
-namespace BTCPayServer.Storage.Services.Providers.GoogleCloudStorage.Configuration
-{
- public class GoogleCloudStorageConfiguration : GoogleProviderOptions, IBaseStorageConfiguration
- {
- public string JsonCredentials { get; set; }
- public string ContainerName { get; set; }
- }
-}
### BTCPayServer/Storage/Services/Providers/GoogleCloudStorage/GoogleCloudStorageFileProviderService.cs
@@ -1,25 +0,0 @@
-using System.Threading.Tasks;
-using BTCPayServer.Storage.Models;
-using BTCPayServer.Storage.Services.Providers.GoogleCloudStorage.Configuration;
-using Google.Apis.Auth.OAuth2;
-using TwentyTwenty.Storage;
-using TwentyTwenty.Storage.Google;
-
-namespace BTCPayServer.Storage.Services.Providers.GoogleCloudStorage
-{
- public class
- GoogleCloudStorageFileProviderService : BaseTwentyTwentyStorageFileProviderServiceBase<
- GoogleCloudStorageConfiguration>
- {
- public override StorageProvider StorageProvider()
- {
- return Storage.Models.StorageProvider.GoogleCloudStorage;
- }
-
- protected override Task<IStorageProvider> GetStorageProvider(
- GoogleCloudStorageConfiguration configuration)
- {
- return Task.FromResult<IStorageProvider>(new GoogleStorageProvider(CredentialFactory.FromJson<ServiceAccountCredential>(configuration.JsonCredentials).ToGoogleCredential(), configuration));
- }
- }
-}
### BTCPayServer/Storage/Services/Providers/IStorageProviderService.cs
@@ -1,18 +0,0 @@
-#nullable enable
-using System;
-using System.Threading.Tasks;
-using BTCPayServer.Data;
-using BTCPayServer.Storage.Models;
-using Microsoft.AspNetCore.Http;
-using TwentyTwenty.Storage;
-
-namespace BTCPayServer.Storage.Services.Providers
-{
- public interface IStorageProviderService
- {
- Task<StoredFile> AddFile(IFormFile formFile, StorageSettings configuration);
- Task RemoveFile(StoredFile storedFile, StorageSettings configuration);
- Task<string> GetFileUrl(Uri baseUri, StoredFile storedFile, StorageSettings configuration);
- StorageProvider StorageProvider();
- }
-}
### BTCPayServer/Storage/Services/Providers/Models/IBaseStorageConfiguration.cs
@@ -1,7 +0,0 @@
-namespace BTCPayServer.Storage.Services.Providers.Models
-{
- public interface IBaseStorageConfiguration
- {
- string ContainerName { get; set; }
- }
-}
### BTCPayServer/Storage/StorageExtensions.cs
@@ -3,9 +3,6 @@
using BTCPayServer.Abstractions.Contracts;
using BTCPayServer.Configuration;
using BTCPayServer.Storage.Services;
-using BTCPayServer.Storage.Services.Providers;
-using BTCPayServer.Storage.Services.Providers.AzureBlobStorage;
-using BTCPayServer.Storage.Services.Providers.FileSystemStorage;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
@@ -19,16 +16,16 @@ namespace BTCPayServer.Storage
{
public static class StorageExtensions
{
- public static void AddProviderStorage(this IServiceCollection serviceCollection)
+ public static void AddFileStorage(this IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<StoredFileRepository>();
serviceCollection.AddSingleton<FileService>();
- serviceCollection.AddSingleton<IFileService>(provider => provider.GetRequiredService<FileService>());
- serviceCollection.AddSingleton<IStorageProviderService, AzureBlobStorageFileProviderService>();
- serviceCollection.AddSingleton<IStorageProviderService, FileSystemFileProviderService>();
+#pragma warning disable CS0618 // Keep legacy plugin injection working; application code uses FileService.
+ serviceCollection.AddSingleton<IFileService, LegacyFileService>();
+#pragma warning restore CS0618
}
- public static void UseProviderStorage(this IApplicationBuilder builder, IOptions<DataDirectories> datadirs)
+ public static void UseFileStorage(this IApplicationBuilder builder, IOptions<DataDirectories> datadirs)
{
try
{
@@ -44,7 +41,7 @@ public static void UseProviderStorage(this IApplicationBuilder builder, IOptions
builder.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
- RequestPath = new PathString($"/{FileSystemFileProviderService.LocalStorageDirectoryName}"),
+ RequestPath = new PathString($"/{FileService.LocalStorageDirectoryName}"),
FileProvider = new PhysicalFileProvider(dirInfo.FullName),
OnPrepareResponse = HandleStaticFileResponse()
});
### BTCPayServer/Storage/ViewModels/ChooseStorageViewModel.cs
@@ -1,13 +0,0 @@
-using System.Collections.Generic;
-using BTCPayServer.Storage.Models;
-using Microsoft.AspNetCore.Mvc.Rendering;
-
-namespace BTCPayServer.Storage.ViewModels
-{
- public class ChooseStorageViewModel
- {
- public IEnumerable<SelectListItem> ProvidersList { get; set; }
- public StorageProvider Provider { get; set; }
- public bool ShowChangeWarning { get; set; }
- }
-}
### BTCPayServer/Views/UIManage/Index.cshtml
@@ -1,10 +1,7 @@
-@using BTCPayServer.Abstractions.Contracts
-@inject IFileService FileService
@model IndexViewModel
@{
ViewData.SetLayoutModel(new LayoutModel("Account", StringLocalizer["Update your account"])
.SetCategory(nameof(ManageNavPages)));
- var canUpload = await FileService.IsAvailable();
}
<form method="post" enctype="multipart/form-data">
@@ -56,29 +53,26 @@
<div class="form-text" text-translate="true">Your personal language for the BTCPay administration UI.</div>
<span asp-validation-for="LangTranslation" class="text-danger"></span>
</div>
- @if (canUpload)
- {
- <div class="form-group">
- <div class="d-flex align-items-center justify-content-between gap-2">
- <label asp-for="ImageFile" class="form-label"></label>
- @if (!string.IsNullOrEmpty(Model.ImageUrl))
- {
- <button type="submit" class="btn btn-link p-0 text-danger" name="RemoveImageFile" value="true">
- <vc:icon symbol="cross" />
- <span text-translate="true">Remove</span>
- </button>
- }
- </div>
- <div class="d-flex align-items-center gap-3">
- <input asp-for="ImageFile" type="file" class="form-control flex-grow">
- @if (!string.IsNullOrEmpty(Model.ImageUrl))
- {
- <img src="@Model.ImageUrl" alt="@StringLocalizer["Profile Picture"]" class="profile-picture"/>
- }
- </div>
- <span asp-validation-for="ImageFile" class="text-danger"></span>
+ <div class="form-group">
+ <div class="d-flex align-items-center justify-content-between gap-2">
+ <label asp-for="ImageFile" class="form-label"></label>
+ @if (!string.IsNullOrEmpty(Model.ImageUrl))
+ {
+ <button type="submit" class="btn btn-link p-0 text-danger" name="RemoveImageFile" value="true">
+ <vc:icon symbol="cross" />
+ <span text-translate="true">Remove</span>
+ </button>
+ }
</div>
- }
+ <div class="d-flex align-items-center gap-3">
+ <input asp-for="ImageFile" type="file" class="form-control flex-grow">
+ @if (!string.IsNullOrEmpty(Model.ImageUrl))
+ {
+ <img src="@Model.ImageUrl" alt="@StringLocalizer["Profile Picture"]" class="profile-picture"/>
+ }
+ </div>
+ <span asp-validation-for="ImageFile" class="text-danger"></span>
+ </div>
<div class="form-group">
<div class="form-check">
<input asp-for="AllowGreenfieldBasicAuth" class="form-check-input" />
### BTCPayServer/Views/UIServer/Branding.cshtml
@@ -1,11 +1,8 @@
-@using BTCPayServer.Abstractions.Contracts
@using BTCPayServer.Services
@model BrandingViewModel;
-@inject IFileService FileService
@{
ViewData.SetLayoutModel(new LayoutModel(nameof(ServerNavPages.Branding), StringLocalizer["Branding"])
.SetCategory(WellKnownCategories.Server));
- var canUpload = await FileService.IsAvailable();
var themeExtension = ((ThemeExtension[])Enum.GetValues(typeof(ThemeExtension))).Select(t =>
new SelectListItem(typeof(ThemeExtension).DisplayName(t.ToString()), t.ToString()));
}
@@ -62,22 +59,14 @@
</button>
}
</div>
- @if (canUpload)
- {
- <div class="d-flex align-items-center gap-3">
- <input asp-for="LogoFile" type="file" class="form-control flex-grow">
- @if (!string.IsNullOrEmpty(Model.LogoUrl))
- {
- <img src="@Model.LogoUrl" alt="Logo" style="height:2.1rem;max-width:10.5rem;"/>
- }
- </div>
- <span asp-validation-for="LogoFile" class="text-danger"></span>
- }
- else
- {
- <input asp-for="LogoFile" type="file" class="form-control" disabled>
- <div class="form-text">@ViewLocalizer["In order to upload, a {0} must be configured.", Html.ActionLink(StringLocalizer["file storage"], "Files", "UIServer")]</div>
- }
+ <div class="d-flex align-items-center gap-3">
+ <input asp-for="LogoFile" type="file" class="form-control flex-grow">
+ @if (!string.IsNullOrEmpty(Model.LogoUrl))
+ {
+ <img src="@Model.LogoUrl" alt="Logo" style="height:2.1rem;max-width:10.5rem;"/>
+ }
+ </div>
+ <span asp-validation-for="LogoFile" class="text-danger"></span>
</div>
</div>
@@ -113,22 +102,14 @@
</button>
}
</div>
- @if (canUpload)
- {
- <div class="d-flex align-items-center gap-3">
- <input asp-for="CustomThemeFile" type="file" class="form-control flex-grow">
- @if (!string.IsNullOrEmpty(Model.CustomThemeCssUrl))
- {
- <a href="@Model.CustomThemeCssUrl" target="_blank" rel="noreferrer noopener" class="text-nowrap" text-translate="true">Custom CSS</a>
- }
- </div>
- <span asp-validation-for="CustomThemeFile" class="text-danger"></span>
- }
- else
- {
- <input asp-for="CustomThemeFile" type="file" class="form-control" disabled>
- <div class="form-text">@ViewLocalizer["In order to upload, a {0} must be configured.", Html.ActionLink(StringLocalizer["file storage"], "Files", "UIServer")]</div>
- }
+ <div class="d-flex align-items-center gap-3">
+ <input asp-for="CustomThemeFile" type="file" class="form-control flex-grow">
+ @if (!string.IsNullOrEmpty(Model.CustomThemeCssUrl))
+ {
+ <a href="@Model.CustomThemeCssUrl" target="_blank" rel="noreferrer noopener" class="text-nowrap" text-translate="true">Custom CSS</a>
+ }
+ </div>
+ <span asp-validation-for="CustomThemeFile" class="text-danger"></span>
</div>
</div>
</div>
### BTCPayServer/Views/UIServer/EditAmazonS3StorageProvider.cshtml
@@ -1,66 +0,0 @@
-@model BTCPayServer.Storage.Services.Providers.AmazonS3Storage.Configuration.AmazonS3StorageConfiguration
-@{
- ViewData.SetLayoutModel(new LayoutModel(nameof(ServerNavPages.Files), StringLocalizer["Amazon S3 Storage"])
- .SetCategory(WellKnownCategories.Server));
- ViewData.SetBreadcrumbs([
- new(StringLocalizer["Files"], Action: nameof(BTCPayServer.Controllers.UIServerController.Files)),
- new(StringLocalizer["Storage Provider"], Action: nameof(BTCPayServer.Controllers.UIServerController.Storage)),
- new(StringLocalizer["Provider"], Active: true)
- ]);
-}
-
-<div class="sticky-header">
- <vc:title-header />
-</div>
-<partial name="_StatusMessage" />
-
-<div class="row">
- <div class="col-xl-10 col-xxl-constrain">
- <form method="post">
- <div class="settings-section">
- <div class="form-group">
- <label asp-for="ContainerName" class="form-label"></label>
- <input class="form-control" asp-for="ContainerName"/>
- <span asp-validation-for="ContainerName" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="SecretKey" class="form-label"></label>
- <input class="form-control" asp-for="SecretKey"/>
- <span asp-validation-for="SecretKey" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Bucket" class="form-label"></label>
- <input class="form-control" asp-for="Bucket"/>
- <span asp-validation-for="Bucket" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="ServiceUrl" class="form-label"></label>
- <input class="form-control" asp-for="ServiceUrl"/>
- <span asp-validation-for="ServiceUrl" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="ServerSideEncryptionMethod" class="form-label"></label>
- <input class="form-control" asp-for="ServerSideEncryptionMethod"/>
- <span asp-validation-for="ServerSideEncryptionMethod" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="ProfileName" class="form-label"></label>
- <input class="form-control" asp-for="ProfileName"/>
- <span asp-validation-for="ProfileName" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="ChunkedUploadThreshold" class="form-label"></label>
- <input class="form-control" type="number" asp-for="ChunkedUploadThreshold"/>
- <span asp-validation-for="ChunkedUploadThreshold" class="text-danger"></span>
- </div>
-
- <button type="submit" class="btn btn-primary" name="command" value="Save" text-translate="true">Save</button>
- <a asp-action="Storage" asp-route-forceChoice="true" text-translate="true">Change Storage provider</a>
- </div>
- </form>
- </div>
-</div>
-
-@section PageFootContent {
- <partial name="_ValidationScriptsPartial" />
-}
### BTCPayServer/Views/UIServer/EditAzureBlobStorageStorageProvider.cshtml
@@ -1,41 +0,0 @@
-@model BTCPayServer.Storage.Services.Providers.AzureBlobStorage.Configuration.AzureBlobStorageConfiguration
-@{
- ViewData.SetLayoutModel(new LayoutModel(nameof(ServerNavPages.Files), StringLocalizer["Azure Blob Storage"])
- .SetCategory(WellKnownCategories.Server));
- ViewData.SetBreadcrumbs([
- new(StringLocalizer["Files"], Action: nameof(BTCPayServer.Controllers.UIServerController.Files)),
- new(StringLocalizer["Storage Provider"], Action: nameof(BTCPayServer.Controllers.UIServerController.Storage)),
- new(StringLocalizer["Provider"], Active: true)
- ]);
-}
-
-<div class="sticky-header">
- <vc:title-header />
-</div>
-<partial name="_StatusMessage" />
-
-<div class="row">
- <div class="col-xl-10 col-xxl-constrain">
- <form method="post">
- <div class="settings-section">
- <div class="form-group">
- <label asp-for="ContainerName" class="form-label" text-translate="true">Container Name</label>
- <input asp-for="ContainerName" class="form-control" />
- <span asp-validation-for="ContainerName" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="ConnectionString" class="form-label" text-translate="true">Connection String</label>
- <input asp-for="ConnectionString" class="form-control" />
- <span asp-validation-for="ConnectionString" class="text-danger"></span>
- </div>
-
- <button type="submit" class="btn btn-primary" name="command" value="Save" text-translate="true">Save</button>
- <a asp-action="Storage" asp-route-forceChoice="true" class="ms-2" text-translate="true">Change Storage provider</a>
- </div>
- </form>
- </div>
-</div>
-
-@section PageFootContent {
- <partial name="_ValidationScriptsPartial" />
-}
### BTCPayServer/Views/UIServer/EditFileSystemStorageProvider.cshtml
@@ -1,28 +0,0 @@
-@model BTCPayServer.Storage.Services.Providers.FileSystemStorage.Configuration.FileSystemStorageConfiguration
-@{
- ViewData.SetLayoutModel(new LayoutModel(nameof(ServerNavPages.Files), StringLocalizer["Local Filesystem Storage"])
- .SetCategory(WellKnownCategories.Server));
- ViewData.SetBreadcrumbs([
- new(StringLocalizer["Files"], Action: nameof(BTCPayServer.Controllers.UIServerController.Files)),
- new(StringLocalizer["Storage Provider"], Action: nameof(BTCPayServer.Controllers.UIServerController.Storage)),
- new(StringLocalizer["Provider"], Active: true)
- ]);
-}
-
-<div class="sticky-header">
- <vc:title-header />
-</div>
-<partial name="_StatusMessage" />
-
-<div class="row">
- <div class="col-xl-10 col-xxl-constrain">
- <div class="settings-section">
- <p text-translate="true">Any uploaded files are being saved on the same machine that hosts BTCPay; please pay attention to your storage space.</p>
- <a asp-action="Storage" asp-route-forceChoice="true" text-translate="true">Change Storage provider</a>
- </div>
- </div>
-</div>
-
-@section PageFootContent {
- <partial name="_ValidationScriptsPartial" />
-}
### BTCPayServer/Views/UIServer/EditGoogleCloudStorageStorageProvider.cshtml
@@ -1,46 +0,0 @@
-@model BTCPayServer.Storage.Services.Providers.GoogleCloudStorage.Configuration.GoogleCloudStorageConfiguration
-@{
- ViewData.SetLayoutModel(new LayoutModel(nameof(ServerNavPages.Files), StringLocalizer["Google Cloud Storage"])
- .SetCategory(WellKnownCategories.Server));
- ViewData.SetBreadcrumbs([
- new(StringLocalizer["Files"], Action: nameof(BTCPayServer.Controllers.UIServerController.Files)),
- new(StringLocalizer["Storage Provider"], Action: nameof(BTCPayServer.Controllers.UIServerController.Storage)),
- new(StringLocalizer["Provider"], Active: true)
- ]);
-}
-
-<div class="sticky-header">
- <vc:title-header />
-</div>
-<partial name="_StatusMessage" />
-
-<div class="row">
- <div class="col-xl-10 col-xxl-constrain">
- <form method="post">
- <div class="settings-section">
- <div class="form-group">
- <label asp-for="ContainerName" class="form-label" text-translate="true">Container Name</label>
- <input asp-for="ContainerName" class="form-control" />
- <span asp-validation-for="ContainerName" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="JsonCredentials" class="form-label" text-translate="true">JSON Credentials</label>
- <input asp-for="JsonCredentials" class="form-control" />
- <span asp-validation-for="JsonCredentials" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Bucket" class="form-label"></label>
- <input asp-for="Bucket" class="form-control" />
- <span asp-validation-for="Bucket" class="text-danger"></span>
- </div>
-
- <button type="submit" class="btn btn-primary" name="command" value="Save" text-translate="true">Save</button>
- <a asp-action="Storage" asp-route-forceChoice="true" class="ms-2" text-translate="true">Change Storage provider</a>
- </div>
- </form>
- </div>
-</div>
-
-@section PageFootContent {
- <partial name="_ValidationScriptsPartial" />
-}
### BTCPayServer/Views/UIServer/Files.cshtml
@@ -7,134 +7,109 @@
<div class="sticky-header align-items-start">
<div class="d-flex flex-column gap-1 flex-grow-1">
<h2 class="mb-0">@ViewData["Title"]</h2>
- <p class="text-secondary mb-0" text-translate="true">Upload and manage files stored with your configured storage provider.</p>
+ <p class="text-secondary mb-0" text-translate="true">Upload and manage files stored on this server.</p>
</div>
- <a asp-action="storage" asp-route-forceChoice="true" asp-route-returnurl="@ViewData["ReturnUrl"]" class="btn btn-secondary d-flex align-items-center">
- <vc:icon symbol="settings" />
- </a>
</div>
<partial name="_StatusMessage" />
-@if (!Model.StorageConfigured)
-{
- <p>
- @ViewLocalizer["Before being able to upload you first need to {0}.", Html.ActionLink(StringLocalizer["choose your file storage service provider"], "Storage", "UIServer", new { forceChoice = "true", returnurl = ViewData["ReturnUrl"] })]
- <a href="https://docs.btcpayserver.org/FAQ/ServerSettings/#how-to-upload-files-to-btcpay" target="_blank" rel="noreferrer noopener" title="@StringLocalizer["More information..."]">
- <vc:icon symbol="info" />
- </a>
- </p>
-}
-else
-{
- <p>
- @ViewLocalizer["Change your {0} provider.", Html.ActionLink(StringLocalizer["file storage service"], "Storage", "UIServer", new { forceChoice = "true", returnurl = ViewData["ReturnUrl"] })]
- <a href="https://docs.btcpayserver.org/FAQ/ServerSettings/#how-to-upload-files-to-btcpay" target="_blank" rel="noreferrer noopener" title="@StringLocalizer["More information..."]">
- <vc:icon symbol="info" />
- </a>
- </p>
-
- @if (Model.StorageConfigured)
- {
- <h3 class="settings-section__heading" text-translate="true">Upload</h3>
- <div class="settings-section">
- <form asp-action="CreateFiles" method="post" enctype="multipart/form-data">
- <div class="d-flex">
- <input multiple type="file" class="form-control mb-0" name="files" id="files" required>
- <button class="btn btn-primary mb-0 ms-3" role="button" text-translate="true">Upload</button>
- </div>
- </form>
+<h3 class="settings-section__heading" text-translate="true">Upload</h3>
+<div class="settings-section">
+ <form asp-action="CreateFiles" method="post" enctype="multipart/form-data">
+ <div class="d-flex">
+ <input multiple type="file" class="form-control mb-0" name="files" id="files" required>
+ <button class="btn btn-primary mb-0 ms-3" role="button" text-translate="true">Upload</button>
</div>
- }
+ </form>
+</div>
- @if (Model.DirectUrlByFiles is { Count: > 0 })
+@if (Model.DirectUrlByFiles is { Count: > 0 })
+{
+ foreach (var fileUrlPair in Model.DirectUrlByFiles)
{
- foreach (var fileUrlPair in Model.DirectUrlByFiles)
- {
- var fileId = fileUrlPair.Key;
- var file = Model.Files.Single(storedFile => storedFile.Id.Equals(fileId, StringComparison.InvariantCultureIgnoreCase));
- var url = Url.Action("GetFile", "UIStorage", new { fileId }, Context.Request.Scheme, Context.Request.Host.ToString());
- <div class="border border-light rounded bg-tile mt-3">
- <div class="row">
- <div class="col-sm-12 col-md-4">
- <div class="input-group">
- <div class="form-floating">
- <input id="@fileId-name" class="form-control-plaintext" readonly="readonly" value="@file.FileName">
- <label text-translate="true">File name</label>
- </div>
- <button type="button" class="btn btn-link clipboard-button" data-clipboard="@file.FileName">
- <vc:icon symbol="actions-copy" />
- </button>
+ var fileId = fileUrlPair.Key;
+ var file = Model.Files.Single(storedFile => storedFile.Id.Equals(fileId, StringComparison.InvariantCultureIgnoreCase));
+ var url = Url.Action("GetFile", "UIStorage", new { fileId }, Context.Request.Scheme, Context.Request.Host.ToString());
+ <div class="border border-light rounded bg-tile mt-3">
+ <div class="row">
+ <div class="col-sm-12 col-md-4">
+ <div class="input-group">
+ <div class="form-floating">
+ <input id="@fileId-name" class="form-control-plaintext" readonly="readonly" value="@file.FileName">
+ <label text-translate="true">File name</label>
</div>
+ <button type="button" class="btn btn-link clipboard-button" data-clipboard="@file.FileName">
+ <vc:icon symbol="actions-copy" />
+ </button>
</div>
- <div class="col-sm-12 col-md-4 ">
- <div class="input-group ">
- <div class="form-floating">
- <input id="@fileId" class="form-control-plaintext" readonly="readonly" value="@fileId">
- <label text-translate="true">File Id</label>
- </div>
- <button type="button" class="btn btn-link clipboard-button" data-clipboard="@fileId">
- <vc:icon symbol="actions-copy" />
- </button>
+ </div>
+ <div class="col-sm-12 col-md-4 ">
+ <div class="input-group ">
+ <div class="form-floating">
+ <input id="@fileId" class="form-control-plaintext" readonly="readonly" value="@fileId">
+ <label text-translate="true">File Id</label>
</div>
+ <button type="button" class="btn btn-link clipboard-button" data-clipboard="@fileId">
+ <vc:icon symbol="actions-copy" />
+ </button>
</div>
- <div class=" col-sm-12 col-md-4">
- <div class="input-group">
- <div class="form-floating">
- <input id="@fileId-url" class="form-control-plaintext" readonly="readonly" value="@url">
- <label text-translate="true">Permanent Url</label>
- </div>
- <button type="button" class="btn btn-link clipboard-button" data-clipboard="@url">
- <vc:icon symbol="actions-copy" />
- </button>
+ </div>
+ <div class=" col-sm-12 col-md-4">
+ <div class="input-group">
+ <div class="form-floating">
+ <input id="@fileId-url" class="form-control-plaintext" readonly="readonly" value="@url">
+ <label text-translate="true">Permanent Url</label>
</div>
+ <button type="button" class="btn btn-link clipboard-button" data-clipboard="@url">
+ <vc:icon symbol="actions-copy" />
+ </button>
</div>
- <button type="button" class="btn btn-link clipboard-button" data-clipboard="@url">
- <vc:icon symbol="copy" />
- </button>
</div>
+ <button type="button" class="btn btn-link clipboard-button" data-clipboard="@url">
+ <vc:icon symbol="copy" />
+ </button>
</div>
- }
+ </div>
}
+}
- @if (Model.Files.Any())
- {
- <h3 class="settings-section__heading" text-translate="true">Files</h3>
- <div class="settings-section">
- <div class="table-responsive settings-section__table">
- <table class="table table-hover mb-0">
- <thead>
+@if (Model.Files.Any())
+{
+ <h3 class="settings-section__heading" text-translate="true">Files</h3>
+ <div class="settings-section">
+ <div class="table-responsive settings-section__table">
+ <table class="table table-hover mb-0">
+ <thead>
+ <tr>
+ <th text-translate="true">Name</th>
+ <th text-translate="true">Timestamp</th>
+ <th text-translate="true">Uploaded By</th>
+ <th text-translate="true" class="text-end">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ @foreach (var file in Model.Files)
+ {
<tr>
- <th text-translate="true">Name</th>
- <th text-translate="true">Timestamp</th>
- <th text-translate="true">Uploaded By</th>
- <th text-translate="true" class="text-end">Actions</th>
+ <td>
+ <a asp-action="Files" asp-route-fileIds="@file.Id">@file.FileName</a>
+ </td>
+ <td>@file.Timestamp.ToBrowserDate()</td>
+ <td>@file.ApplicationUser.UserName</td>
+ <td class="text-end">
+ <a href="@Url.Action("Files", "UIServer", new {fileIds = new [] { file.Id }})" class="text-nowrap" text-translate="true">Get Link</a>
+ -
+ <form method="post" asp-action="DeleteFile" asp-route-fileId="@file.Id" class="d-inline">
+ <button type="submit" class="btn btn-link p-0 align-baseline" text-translate="true">Remove</button>
+ </form>
+ </td>
</tr>
- </thead>
- <tbody>
- @foreach (var file in Model.Files)
- {
- <tr>
- <td>
- <a asp-action="Files" asp-route-fileIds="@file.Id">@file.FileName</a>
- </td>
- <td>@file.Timestamp.ToBrowserDate()</td>
- <td>@file.ApplicationUser.UserName</td>
- <td class="text-end">
- <a href="@Url.Action("Files", "UIServer", new {fileIds = new [] { file.Id }})" class="text-nowrap" text-translate="true">Get Link</a>
- -
- <form method="post" asp-action="DeleteFile" asp-route-fileId="@file.Id" class="d-inline">
- <button type="submit" class="btn btn-link p-0 align-baseline" text-translate="true">Remove</button>
- </form>
- </td>
- </tr>
- }
- </tbody>
- </table>
- </div>
- </div>
- }
- else
- {
- <p class="text-secondary mt-3" text-translate="true">There are no files yet.</p>
- }
+ }
+ </tbody>
+ </table>
+ </div>
+ </div>
+}
+else
+{
+ <p class="text-secondary mt-3" text-translate="true">There are no files yet.</p>
}
### BTCPayServer/Views/UIServer/Storage.cshtml
@@ -1,39 +0,0 @@
-@model BTCPayServer.Storage.ViewModels.ChooseStorageViewModel
-@{
- ViewData.SetLayoutModel(new LayoutModel(nameof(ServerNavPages.Files), StringLocalizer["Storage Provider"])
- .SetCategory(WellKnownCategories.Server));
- ViewData.SetBreadcrumbs([new(StringLocalizer["Files"], Action: nameof(BTCPayServer.Controllers.UIServerController.Files))]);
-}
-
-<form method="post">
- <div class="sticky-header">
- <vc:title-header />
- <button id="page-primary" type="submit" class="btn btn-primary" name="command" value="Save" text-translate="true">Next</button>
- </div>
- <partial name="_StatusMessage" />
-
- <div class="row">
- <div class="col-xl-10 col-xxl-constrain">
- @if (Model.ShowChangeWarning)
- {
- <div class="alert alert-danger mb-4" text-translate="true">
- If you change your configured storage provider, your current files will become inaccessible.
- </div>
- }
- @if (!ViewContext.ModelState.IsValid)
- {
- <div asp-validation-summary="All"></div>
- }
- <div class="settings-section">
- <div class="form-group mb-0">
- <label asp-for="Provider" class="form-label"></label>
- <select asp-for="Provider" asp-items="@Model.ProvidersList" class="form-select w-auto"></select>
- </div>
- </div>
- </div>
- </div>
-</form>
-
-@section PageFootContent {
- <partial name="_ValidationScriptsPartial" />
-}
### BTCPayServer/Views/UIServer/User.cshtml
@@ -1,13 +1,10 @@
-@using BTCPayServer.Abstractions.Contracts
@model UsersViewModel.UserViewModel
-@inject IFileService FileService
@{
ViewData.SetLayoutModel(new(nameof(ServerNavPages.Users), Model.Email));
ViewData.SetBreadcrumbs([
new(StringLocalizer["Users"], Action: nameof(BTCPayServer.Controllers.UIServerController.ListUsers)),
new(StringLocalizer["User"], Active: true)
]);
- var canUpload = await FileService.IsAvailable();
}
<form method="post" enctype="multipart/form-data">
@@ -51,22 +48,14 @@
</button>
}
</div>
- @if (canUpload)
- {
- <div class="d-flex align-items-center gap-3">
- <input asp-for="ImageFile" type="file" class="form-control flex-grow">
- @if (!string.IsNullOrEmpty(Model.ImageUrl))
- {
- <img src="@Model.ImageUrl" alt="Profile picture" class="profile-picture" />
- }
- </div>
- <span asp-validation-for="ImageFile" class="text-danger"></span>
- }
- else
- {
- <input asp-for="ImageFile" type="file" class="form-control" disabled>
- <div class="form-text">@ViewLocalizer["In order to upload, a {0} must be configured.", Html.ActionLink(StringLocalizer["file storage"], "Files", "UIServer")]</div>
- }
+ <div class="d-flex align-items-center gap-3">
+ <input asp-for="ImageFile" type="file" class="form-control flex-grow">
+ @if (!string.IsNullOrEmpty(Model.ImageUrl))
+ {
+ <img src="@Model.ImageUrl" alt="Profile picture" class="profile-picture" />
+ }
+ </div>
+ <span asp-validation-for="ImageFile" class="text-danger"></span>
</div>
<div class="form-check my-3">
<input asp-for="IsAdmin" type="checkbox" class="form-check-input" />
### BTCPayServer/Views/UIStores/CheckoutAppearance.cshtml
@@ -1,12 +1,9 @@
@using BTCPayServer.Payments
-@using BTCPayServer.Abstractions.Contracts
@using BTCPayServer.Client
-@inject IFileService FileService
@inject BTCPayServer.Services.PrettyNameProvider PrettyName
@model CheckoutAppearanceViewModel
@{
ViewData.SetLayoutModel(new LayoutModel(nameof(StoreNavPages.CheckoutAppearance), StringLocalizer["Checkout Experience"]).SetCategory(WellKnownCategories.Store));
- var canUpload = await FileService.IsAvailable();
var unifiedQrApplies = Model.PaymentMethods.Any(o => o.Value == PaymentTypes.CHAIN.GetPaymentMethodId("BTC").ToString()) &&
Model.PaymentMethods.Any(o => o.Value == PaymentTypes.LN.GetPaymentMethodId("BTC").ToString() || o.Value == PaymentTypes.LNURL.GetPaymentMethodId("BTC").ToString());
}
@@ -191,19 +188,11 @@
</button>
}
</div>
- @if (canUpload)
- {
- <div class="d-flex align-items-center gap-3">
- <input asp-for="SoundFile" type="file" class="form-control flex-grow">
- <audio controls src="@Model.PaymentSoundUrl" style="height:2.1rem;max-width:10.5rem;"></audio>
- </div>
- <span asp-validation-for="SoundFile" class="text-danger"></span>
- }
- else
- {
- <input asp-for="SoundFile" type="file" class="form-control" disabled>
- <div class="form-text">@ViewLocalizer["In order to upload, a {0} must be configured.", Html.ActionLink(StringLocalizer["file storage"], "Files", "UIServer")]</div>
- }
+ <div class="d-flex align-items-center gap-3">
+ <input asp-for="SoundFile" type="file" class="form-control flex-grow">
+ <audio controls src="@Model.PaymentSoundUrl" style="height:2.1rem;max-width:10.5rem;"></audio>
+ </div>
+ <span asp-validation-for="SoundFile" class="text-danger"></span>
</div>
</div>
</div>
### BTCPayServer/Views/UIStores/GeneralSettings.cshtml
@@ -1,11 +1,8 @@
-@using BTCPayServer.Abstractions.Contracts
@using BTCPayServer.Client
@inject BTCPayServer.Security.ContentSecurityPolicies Csp
-@inject IFileService FileService;
@model GeneralSettingsViewModel
@{
ViewData.SetLayoutModel(new LayoutModel("General", StringLocalizer["General"]).SetCategory(WellKnownCategories.Store));
- var canUpload = await FileService.IsAvailable();
Csp.UnsafeEval();
}
<form method="post" enctype="multipart/form-data" permissioned="@Policies.CanModifyStoreSettings">
@@ -95,22 +92,14 @@
</button>
}
</div>
- @if (canUpload)
- {
- <div class="d-flex align-items-center gap-3">
- <input asp-for="LogoFile" type="file" class="form-control flex-grow">
- @if (!string.IsNullOrEmpty(Model.LogoUrl))
- {
- <img src="@Model.LogoUrl" alt="@Model.StoreName Logo" style="height:2.1rem;max-width:10.5rem;"/>
- }
- </div>
- <span asp-validation-for="LogoFile" class="text-danger"></span>
- }
- else
- {
- <input asp-for="LogoFile" type="file" class="form-control" disabled>
- <div class="form-text">@ViewLocalizer["In order to upload, a {0} must be configured.", Html.ActionLink(StringLocalizer["file storage"], "Files", "UIServer")]</div>
- }
+ <div class="d-flex align-items-center gap-3">
+ <input asp-for="LogoFile" type="file" class="form-control flex-grow">
+ @if (!string.IsNullOrEmpty(Model.LogoUrl))
+ {
+ <img src="@Model.LogoUrl" alt="@Model.StoreName Logo" style="height:2.1rem;max-width:10.5rem;"/>
+ }
+ </div>
+ <span asp-validation-for="LogoFile" class="text-danger"></span>
</div>
<div class="form-group mb-0">
<div class="d-flex align-items-center justify-content-between gap-2">
@@ -122,22 +111,14 @@
</button>
}
</div>
- @if (canUpload)
- {
- <div class="d-flex align-items-center gap-3">
- <input asp-for="CssFile" type="file" class="form-control flex-grow">
- @if (Uri.TryCreate(Model.CssUrl, UriKind.Absolute, out var cssUri) && cssUri.Scheme is ("http" or "https"))
- {
- <a href="@Model.CssUrl" target="_blank" rel="noreferrer noopener" class="text-nowrap" text-translate="true">Custom CSS</a>
- }
- </div>
- <span asp-validation-for="CssFile" class="text-danger"></span>
- }
- else
- {
- <input asp-for="CssFile" type="file" class="form-control" disabled>
- <div class="form-text">@ViewLocalizer["In order to upload, a {0} must be configured.", Html.ActionLink(StringLocalizer["file storage"], "Files", "UIServer")]</div>
- }
+ <div class="d-flex align-items-center gap-3">
+ <input asp-for="CssFile" type="file" class="form-control flex-grow">
+ @if (Uri.TryCreate(Model.CssUrl, UriKind.Absolute, out var cssUri) && cssUri.Scheme is ("http" or "https"))
+ {
+ <a href="@Model.CssUrl" target="_blank" rel="noreferrer noopener" class="text-nowrap" text-translate="true">Custom CSS</a>
+ }
+ </div>
+ <span asp-validation-for="CssFile" class="text-danger"></span>
</div>
</div>
Why this scored 41/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.