86 lines
2.5 KiB
C#
86 lines
2.5 KiB
C#
using System.IO;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace LightlessSyncStaticFilesServer.Services;
|
|
|
|
public class CDNDownloadsService
|
|
{
|
|
public enum ResultStatus
|
|
{
|
|
Disabled,
|
|
Unauthorized,
|
|
NotFound,
|
|
Success,
|
|
Downloading
|
|
}
|
|
|
|
public readonly record struct Result(ResultStatus Status, FileInfo? File);
|
|
|
|
private readonly CDNDownloadUrlService _cdnDownloadUrlService;
|
|
private readonly CachedFileProvider _cachedFileProvider;
|
|
|
|
public CDNDownloadsService(CDNDownloadUrlService cdnDownloadUrlService, CachedFileProvider cachedFileProvider)
|
|
{
|
|
_cdnDownloadUrlService = cdnDownloadUrlService;
|
|
_cachedFileProvider = cachedFileProvider;
|
|
}
|
|
|
|
public bool DownloadsEnabled => _cdnDownloadUrlService.DirectDownloadsEnabled;
|
|
|
|
public async Task<Result> GetDownloadAsync(string hash, long expiresUnixSeconds, string signature)
|
|
{
|
|
if (!_cdnDownloadUrlService.DirectDownloadsEnabled)
|
|
{
|
|
return new Result(ResultStatus.Disabled, null);
|
|
}
|
|
|
|
if (string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(hash))
|
|
{
|
|
return new Result(ResultStatus.Unauthorized, null);
|
|
}
|
|
|
|
hash = hash.ToUpperInvariant();
|
|
|
|
if (!_cdnDownloadUrlService.TryValidateSignature(hash, expiresUnixSeconds, signature))
|
|
{
|
|
return new Result(ResultStatus.Unauthorized, null);
|
|
}
|
|
|
|
var fileInfo = await _cachedFileProvider.DownloadAndGetLocalFileInfo(hash).ConfigureAwait(false);
|
|
if (fileInfo == null)
|
|
{
|
|
return new Result(ResultStatus.NotFound, null);
|
|
}
|
|
|
|
return new Result(ResultStatus.Success, fileInfo);
|
|
}
|
|
|
|
public Result GetDownloadWithCacheCheck(string hash, long expiresUnixSeconds, string signature)
|
|
{
|
|
if (!_cdnDownloadUrlService.DirectDownloadsEnabled)
|
|
{
|
|
return new Result(ResultStatus.Disabled, null);
|
|
}
|
|
|
|
if (string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(hash))
|
|
{
|
|
return new Result(ResultStatus.Unauthorized, null);
|
|
}
|
|
|
|
hash = hash.ToUpperInvariant();
|
|
|
|
if (!_cdnDownloadUrlService.TryValidateSignature(hash, expiresUnixSeconds, signature))
|
|
{
|
|
return new Result(ResultStatus.Unauthorized, null);
|
|
}
|
|
|
|
var fileInfo = _cachedFileProvider.TryGetLocalFileInfo(hash);
|
|
if (fileInfo == null)
|
|
{
|
|
return new Result(ResultStatus.Downloading, null);
|
|
}
|
|
|
|
return new Result(ResultStatus.Success, fileInfo);
|
|
}
|
|
}
|