55 lines
2.6 KiB
C#
55 lines
2.6 KiB
C#
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
|
|
namespace LMEMappeCatastaliApp.Services;
|
|
|
|
public sealed class CloudSyncService
|
|
{
|
|
private readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromMinutes(3) };
|
|
|
|
public async Task UploadAsync(string endpoint, string userName, string password, string localPath, CancellationToken cancellationToken = default)
|
|
{
|
|
var target = BuildTarget(endpoint);
|
|
using var request = new HttpRequestMessage(HttpMethod.Put, target);
|
|
ApplyCredentials(request, userName, password);
|
|
request.Content = new StreamContent(File.OpenRead(localPath));
|
|
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
|
|
using var response = await _httpClient.SendAsync(request, cancellationToken);
|
|
response.EnsureSuccessStatusCode();
|
|
}
|
|
|
|
public async Task<string> DownloadAsync(string endpoint, string userName, string password, CancellationToken cancellationToken = default)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, BuildTarget(endpoint));
|
|
ApplyCredentials(request, userName, password);
|
|
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
|
response.EnsureSuccessStatusCode();
|
|
var directory = Path.Combine(FileSystem.CacheDirectory, "CloudSync");
|
|
Directory.CreateDirectory(directory);
|
|
var path = Path.Combine(directory, $"LME-cloud-{DateTime.Now:yyyyMMdd-HHmmss}.lmebackup.zip");
|
|
await using var input = await response.Content.ReadAsStreamAsync(cancellationToken);
|
|
await using var output = File.Create(path);
|
|
await input.CopyToAsync(output, cancellationToken);
|
|
return path;
|
|
}
|
|
|
|
private static Uri BuildTarget(string endpoint)
|
|
{
|
|
if (!Uri.TryCreate(endpoint?.Trim(), UriKind.Absolute, out var uri)
|
|
|| (uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp))
|
|
{
|
|
throw new ArgumentException("Inserisci un indirizzo WebDAV http o https valido.");
|
|
}
|
|
return uri.AbsolutePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)
|
|
? uri
|
|
: new Uri($"{uri.ToString().TrimEnd('/')}/LMEMappeCatastali-sync.lmebackup.zip");
|
|
}
|
|
|
|
private static void ApplyCredentials(HttpRequestMessage request, string userName, string password)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(userName)) return;
|
|
var value = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userName}:{password}"));
|
|
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", value);
|
|
}
|
|
}
|