Zmodyfikuj poniższy kod aplikacji w C#, aby przy pobieraniu pliku wykorzystywał FileService. W tym celu powinno się wygenereować 2 sas-linki (z innym content-disposition w metodzie AzureBlobStorageAdapter::GetSasLink)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Abp.Collections.Extensions;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Runtime.Caching;
using Abp.Runtime.Session;
using Abp.Timing;
using Hangfire.Console;
using Hangfire.Server;
using Medica.Commerce.DateTimeEnumerator;
using Medica.Common.Extensions;
using Medica.Communication;
using Medica.Configuration;
using Medica.Extensions;
using Medica.Files.Notification;
using Medica.Helpers.Cache;
using Medica.ImageProcessing;
using Medica.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
public FileService(
Lazy<IRepository<FileBucketBase, Guid>> bucketRepository,
Lazy<IRepository<FileEntity, Guid>> filesRepository,
Lazy<ISettingManager> settingManager,
Lazy<ICacheManager> cacheManager,
Lazy<IEventHelperService> eventHelperService,
Lazy<IAzureBlobStorageAdapter> azureBlobStorageAdapter,
Lazy<ICurrentUnitOfWorkProvider> currentUnitOfWorkProvider,
Lazy<IBucketNotificationService> fileNotificationService)
{
_bucketRepository = bucketRepository;
_filesRepository = filesRepository;
_settingManager = settingManager;
_eventHelperService = eventHelperService;
_azureBlobStorageAdapter = azureBlobStorageAdapter;
_fileNotificationService = fileNotificationService;
_currentUnitOfWorkProvider = currentUnitOfWorkProvider;
_tempCache = new Lazy<ITypedCache<Guid, (byte[], FileEntityDto)>>(() => cacheManager.Value.GetCache<Guid, (byte[], FileEntityDto)>("FileServiceTempCache"));
}
public Task<FileBucketBase> CreateBucketAsync(FileBucketBase bucket)
{
return CreateBucketAsync(bucket, default, BucketProps.General());
}
public Task<FileBucketBase> CreateBucketAsync(FileBucketBase bucket, IFormFile file)
{
if (file == default)
throw new ArgumentNullException(nameof(file));
return CreateBucketAsync(bucket, new[] { file }, BucketProps.General());
}
public async Task<FileBucketBase> CreateBucketAsync(FileBucketBase bucket, ICollection<IFormFile> files, BucketProps props, bool compress = true)
{
if (bucket.Id != default)
throw new InvalidOperationException($"Bucket id={bucket.Id} is not default");
var fileBucket = await _bucketRepository.Value.InsertAsync(bucket);
if (files.IsNullOrEmpty())
return fileBucket;
await _currentUnitOfWorkProvider.Value.Current.SaveChangesAsync();
return await AddFilesToBucketAsync(fileBucket, files, props, compress);
}
public async Task<FileBucketBase> DuplicateBucketAsync(FileBucketBase sourceBucket, FileBucketBase destinationBucket, BucketProps props)
{
if (destinationBucket.Id != default)
throw new InvalidOperationException($"Bucket id={destinationBucket.Id} is not default");
var fileBucket = await _bucketRepository.Value.InsertAsync(destinationBucket);
if (sourceBucket.Files.IsNullOrEmpty())
return fileBucket;
await _currentUnitOfWorkProvider.Value.Current.SaveChangesAsync();
return await CopyFilesBetweenBucketsAsync(sourceBucket, fileBucket, props);
}
public virtual async Task MigrateAsync(int limit, PerformContext context)
{
if (limit < 1 || limit > 1000)
throw new ArgumentNullException(nameof(limit));
var files = await _filesRepository
.Value
.GetAll()
.AsNoTracking()
.Where(v => v.StorageType == StorageType.Local)
.OrderByDescending(v => v.CreationTime)
.Take(limit)
.ToListAsync();
context.WriteLine($"Migrating {files.Count} files");
foreach (var file in files)
{
var filePath = GetFilePath(file);
context.WriteLine($"Migrating {filePath}");
try
{
using (var inputStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
await UploadFileAsync(inputStream, true, false, file, default);
}
file.StorageType = StorageType.Azure;
await _filesRepository.Value.UpdateAsync(file);
}
catch (Exception e)
{
context.WriteLine($"Exception while migrating {filePath}. {e.Message}");
continue;
}
}
}
public virtual async Task DeleteFileAsync(FileEntity file)
{
if (file == null)
throw new ArgumentNullException(nameof(file));
await _filesRepository.Value.DeleteAsync(file);
if (file.StorageType == StorageType.Azure)
{
await _azureBlobStorageAdapter.Value.DeleteFileAsync(file.Id);
}
else
{
var filePath = GetFilePath(file);
if (File.Exists(filePath))
File.Delete(filePath);
}
}
public virtual async Task DeleteFileAsync(Guid bucketId, Guid id)
{
var file = await _filesRepository.Value.GetAsNoTrackingAsync(id);
if (file.FileBucketId != bucketId) throw new ArgumentException($"File {id} bucket {file.FileBucketId} does not match argument bucketId: {bucketId}");
await DeleteFileAsync(file);
await _currentUnitOfWorkProvider.Value.Current.SaveChangesAsync();
}
public virtual async Task DeleteFileBucketAsync(Guid bucketId)
{
var bucket = await _bucketRepository
.Value
.GetAll()
.Include(v => v.Files)
.Where(v => v.Id == bucketId)
.SingleAsync();
await DeleteFileBucketAsync(bucket);
}
public virtual async Task ClearFileBucketAsync(Guid bucketId)
{
var bucket = await _bucketRepository
.Value
.GetAll()
.Include(v => v.Files)
.Where(v => v.Id == bucketId)
.SingleAsync();
await ClearFileBucketAsync(bucket);
}
public virtual async Task DeleteFileBucketAsync(FileBucketBase fileBucket)
{
if (fileBucket == null)
throw new ArgumentNullException(nameof(fileBucket));
await ClearFileBucketAsync(fileBucket);
await _bucketRepository.Value.DeleteAsync(fileBucket);
}
private async Task ClearFileBucketAsync(FileBucketBase fileBucket)
{
if (fileBucket == null)
throw new ArgumentNullException(nameof(fileBucket));
await _bucketRepository.Value.EnsureCollectionLoadedAsync(fileBucket, v => v.Files);
foreach (var item in fileBucket.Files)
{
await DeleteFileAsync(item);
}
}
private async Task<FileBucketBase> AddFileBiImageToBucketAsync(FileBucketBase bucket, IFormFile file, BucketProps props)
{
var isCloudStorageEnabled = await _settingManager.Value.GetSettingValueAsync<bool>(AppSettingsNames.FileStorage.CloudStorageEnabled);
if (!isCloudStorageEnabled) throw new ArgumentException("Bi images can be uploaded only to azure blob storage");
if (bucket == null) throw new ArgumentNullException(nameof(bucket));
if (file == null) throw new ArgumentNullException(nameof(file));
const StorageType storageType = StorageType.Azure;
var jpgEntity = new FileEntity()
{
ContentType = ContentTypes.Jpg,
FileBucketId = bucket.Id,
FileName = Path.ChangeExtension(file.FileName, ".jpg"),
Length = 0,
StorageType = storageType
};
var webpEntity = new FileEntity()
{
ContentType = ContentTypes.Webp,
FileBucketId = bucket.Id,
FileName = Path.ChangeExtension(file.FileName, ".webp"),
Length = 0,
StorageType = storageType
};
await _filesRepository.Value.InsertAndGetIdAsync(jpgEntity);
await _filesRepository.Value.InsertAndGetIdAsync(webpEntity);
await using (var inputStream = file.OpenReadStream())
{
await using var jpgStream = await ImageConverter.ConvertAsync(inputStream, ImageConversionProps.BiImage(props.Target, ImageFormat.Jpg));
{
(await _azureBlobStorageAdapter.Value.SaveFileAsync(jpgStream, jpgEntity.Id, props.IsHot)).OrThrow();
}
}
await using (var inputStream = file.OpenReadStream())
{
await using var webpStream = await ImageConverter.ConvertAsync(inputStream, ImageConversionProps.BiImage(props.Target, ImageFormat.WebP));
{
(await _azureBlobStorageAdapter.Value.SaveFileAsync(webpStream, webpEntity.Id, props.IsHot)).OrThrow();
}
}
return await HandleBucketUpdate(bucket.Id);
}
private async Task<FileBucketBase> AddFileToBucketAsync(FileBucketBase bucket, IFormFile file, bool encrypt, bool isHot, bool compress = true)
{
var isCloudStorageEnabled = await _settingManager.Value.GetSettingValueAsync<bool>(AppSettingsNames.FileStorage.CloudStorageEnabled);
if (bucket == null)
throw new ArgumentNullException(nameof(bucket));
if (file == null)
throw new ArgumentNullException(nameof(file));
var aesCredentialsOpt = encrypt ? AesCredentials.Generate() : null;
var fileEntity = new FileEntity()
{
ContentType = file.ContentType,
FileBucketId = bucket.Id,
FileName = file.FileName,
Length = file.Length,
AesCredentials = aesCredentialsOpt?.ToString(),
StorageType = isCloudStorageEnabled ? StorageType.Azure : StorageType.Local
};
var fileEntityId = await _filesRepository.Value.InsertAndGetIdAsync(fileEntity);
await using (var inputStream = file.OpenReadStream())
{
if (aesCredentialsOpt is { } aesCredentials)
{
using var aesAlg = aesCredentials.AesInstance();
var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using var msEncrypt = new MemoryStream();
await using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
await inputStream.CopyToAsync(csEncrypt);
csEncrypt.Close();
using var eStream = new MemoryStream(msEncrypt.ToArray());
await UploadFileAsync(eStream, isCloudStorageEnabled, isHot, fileEntity, bucket.Id, compress);
}
else
{
await UploadFileAsync(inputStream, isCloudStorageEnabled, isHot, fileEntity, bucket.Id, compress);
}
}
return await HandleBucketUpdate(bucket.Id);
}
private async Task<FileBucketBase> CopyFileToBucketAsync(FileBucketBase bucket, FileEntity sourceFile)
{
var isCloudStorageEnabled = await _settingManager.Value.GetSettingValueAsync<bool>(AppSettingsNames.FileStorage.CloudStorageEnabled);
if (bucket == null)
throw new ArgumentNullException(nameof(bucket));
if (sourceFile == null)
throw new ArgumentNullException(nameof(sourceFile));
var storageType = isCloudStorageEnabled && sourceFile.StorageType == StorageType.Azure ? StorageType.Azure : StorageType.Local;
var fileEntity = new FileEntity()
{
ContentType = sourceFile.ContentType,
FileBucketId = bucket.Id,
FileName = sourceFile.FileName,
Length = sourceFile.Length,
AesCredentials = sourceFile.AesCredentials,
StorageType = storageType
};
var fileEntityId = await _filesRepository.Value.InsertAndGetIdAsync(fileEntity);
return await CopyFileAsync(isCloudStorageEnabled, sourceFile, fileEntity, bucket.Id);
}
private async Task<FileBucketBase> HandleBucketUpdate(Guid bucketId)
{
await _currentUnitOfWorkProvider.Value.Current.SaveChangesAsync();
var bucket = await _bucketRepository
.Value
.GetAll()
.AsNoTracking()
.Where(v => v.Id == bucketId)
.Include(v => v.Files)
.FirstAsync();
var dto = GetFileBucketDto(bucket);
await _eventHelperService.Value.NewFileBucketChangedEventAsync(MedicaSession.GetTenantId(), dto);
if (MedicaSession.UserId.HasValue)
await _fileNotificationService.Value.NewFileBucketEventAsync(bucketId, MedicaSession.GetUserId(), bucket.Variant);
return bucket;
}
public async Task<FileEntity> UploadFile(byte[] content, string contentType, string name, Guid bucketId, bool isHot)
{
var isCloudStorageEnabled = await _settingManager.Value.GetSettingValueAsync<bool>(AppSettingsNames.FileStorage.CloudStorageEnabled);
if (content == null) throw new ArgumentNullException(nameof(content));
var fileEntity = new FileEntity()
{
ContentType = contentType,
FileBucketId = bucketId,
FileName = name,
Length = content.Length,
StorageType = isCloudStorageEnabled ? StorageType.Azure : StorageType.Local
};
await _filesRepository.Value.InsertAndGetIdAsync(fileEntity);
await using var inputStream = new MemoryStream(content);
await UploadFileAsync(inputStream, isCloudStorageEnabled, isHot, fileEntity, bucketId);
await _currentUnitOfWorkProvider.Value.Current.SaveChangesAsync();
return fileEntity;
}
private async Task<FileBucketBase> CopyFileAsync(bool isCloudStorageEnabled, FileEntity sourceFileEntity, FileEntity destinationFileEntity, Guid bucketId)
{
if (isCloudStorageEnabled)
{
(await _azureBlobStorageAdapter.Value.CopyAsync(sourceFileEntity.Id, destinationFileEntity.Id)).OrThrow();
}
else
{
var sourceFilePath = GetFilePath(sourceFileEntity);
await using var sourceFileStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read);
var destinationDirectoryPath = GetBucketDirectoryPath(bucketId);
var destinationFilePath = GetFilePath(destinationFileEntity);
Directory.CreateDirectory(destinationDirectoryPath);
await using var destinationFileStream = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write);
await sourceFileStream.CopyToAsync(destinationFileStream);
}
return await HandleBucketUpdate(bucketId);
}
private async Task UploadFileAsync(Stream inputStream, bool isCloudStorageEnabled, bool isHot, FileEntity fileEntity, Guid bucketId, bool compress = true)
{
var shouldOptimize = ContentTypes.IsImage(fileEntity.ContentType);
if (shouldOptimize)
{
fileEntity.ContentType = ContentTypes.Jpg;
fileEntity.FileName = Path.ChangeExtension(fileEntity.FileName, ".jpg");
}
const int maxSize200dpi = 2339;
var optimizedStream = shouldOptimize && compress
? await ImageConverter.ConvertAsync(inputStream, ImageConversionProps.Attachment(maxSize200dpi))
: inputStream;
try
{
if (isCloudStorageEnabled)
{
(await _azureBlobStorageAdapter.Value.SaveFileAsync(optimizedStream, fileEntity.Id, isHot)).OrThrow();
}
else
{
var dirPath = GetBucketDirectoryPath(bucketId);
var filePath = GetFilePath(fileEntity);
Directory.CreateDirectory(dirPath);
using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
await optimizedStream.CopyToAsync(fileStream);
}
}
finally
{
if (shouldOptimize)
optimizedStream?.Dispose();
}
}
public virtual async Task<FileBucketBase> AddFilesToBucketAsync(FileBucketBase bucket, ICollection<IFormFile> files, BucketProps props, bool compress = true)
{
if (bucket == null)
throw new ArgumentNullException(nameof(bucket));
if (props.BiImage)
{
if (files.FirstIfSingle() is not { } imageFile) throw new ArgumentException("Bi image input must contain single file");
var contentType = imageFile.ContentType;
if (contentType is not (ContentTypes.Jpg or ContentTypes.Png or ContentTypes.Webp)) throw new ArgumentException($"Bi image input must be of image content type: {contentType} ");
bucket = await AddFileBiImageToBucketAsync(bucket, imageFile, props);
}
else
{
foreach (var file in files)
{
bucket = await AddFileToBucketAsync(bucket, file, props.Encrypt, props.IsHot, compress);
}
}
await _currentUnitOfWorkProvider.Value.Current.SaveChangesAsync();
if (bucket is SurveyFileBucket surveyFileBucket)
{
var tenantId = MedicaSession.GetTenantId();
await _eventHelperService.Value.NewSurveyFileBucketsChangedEventAsync(tenantId, surveyFileBucket.EntityType, surveyFileBucket.EntityId);
}
return bucket;
}
private async Task<FileBucketBase> CopyFilesBetweenBucketsAsync(FileBucketBase sourceBucket, FileBucketBase destinationBucket, BucketProps props)
{
if (sourceBucket == null)
throw new ArgumentNullException(nameof(sourceBucket));
if (props.BiImage)
{
throw new NotImplementedException("Copying BiImage not yet supported");
}
else
{
foreach (var file in sourceBucket.Files)
{
destinationBucket = await CopyFileToBucketAsync(destinationBucket, file);
}
}
await _currentUnitOfWorkProvider.Value.Current.SaveChangesAsync();
if (destinationBucket is SurveyFileBucket surveyFileBucket)
{
var tenantId = MedicaSession.GetTenantId();
await _eventHelperService.Value.NewSurveyFileBucketsChangedEventAsync(tenantId, surveyFileBucket.EntityType, surveyFileBucket.EntityId);
}
return destinationBucket;
}
public Task<FileBucketBase> GetFileBucketAsync(Guid bucketId)
{
return _bucketRepository
.Value
.GetAll()
.AsNoTracking()
.Where(v => v.Id == bucketId)
.Include(v => v.Files)
.SingleOrDefaultAsync();
}
public async Task<(Stream, FileEntity)> GetFileAsync(Guid id, DateTime exp, string key)
{
var file = await GetFileEntityAsync(id);
var hash = MakeExpiryHash(file.FileBucketId, exp);
if (key != hash)
throw new AuthenticationException("Invalid key");
if (file.StorageType != StorageType.Local)
throw new ArgumentException("Requested file is not stored locally");
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "files", file.FileBucketId.ToString(), id.ToString());
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return (stream, file);
}
public async Task<Uri> GetFileSasLinkAsync(Guid id)
{
var file = await GetFileEntityAsync(id);
if (file.StorageType != StorageType.Azure)
throw new ArgumentException("Requested file is not stored locally");
return (_azureBlobStorageAdapter.Value.GetSasLink(file)).OrThrow();
}
public async Task<DisposableCollection<Attachment>> GetAsAttachments(IEnumerable<Guid> ids)
{
var list = new List<Attachment>();
foreach (var id in ids)
{
if (_tempCache.Value.TryGetValue(id, out var cached))
{
var cachedStream = new MemoryStream(cached.Item1);
var dto = cached.Item2;
list.Add(new Attachment(cachedStream, dto.FileName, dto.ContentType) { ContentId = id.ToString() });
continue;
}
var entity = await GetFileEntityAsync(id);
if (entity.StorageType != StorageType.Azure) throw new ArgumentException("Only Azure blobs can be used as attachments");
var stream = new MemoryStream();
await _azureBlobStorageAdapter.Value.DownloadAsync(id, stream);
list.Add(new Attachment(stream, entity.FileName, entity.ContentType) { ContentId = id.ToString() });
}
return DisposableCollection.Wrap(list);
}
public async Task<Stream> GetStream(Guid id)
{
var entity = await GetFileEntityAsync(id);
var stream = new MemoryStream();
await _azureBlobStorageAdapter.Value.DownloadAsync(id, stream);
stream.Position = 0;
if (entity.AesCredentials is { } aesCredentialsStr)
{
using var aesAlg = AesCredentials.FromString(aesCredentialsStr).AesInstance();
var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
return new CryptoStream(stream, decryptor, CryptoStreamMode.Read);
}
return stream;
}
private Task<FileEntity> GetFileEntityAsync(Guid id)
{
return _filesRepository
.Value
.GetAll()
.AsNoTracking()
.SingleAsync(v => v.Id == id);
}
public FileBucketDto GetFileBucketDto(FileBucketBase bucket, TimeSpan? validity = null)
{
if (bucket == null)
return null;
var bucketDto = new FileBucketDto()
{
Name = bucket.Name,
CreationTime = bucket.CreationTime,
Details = bucket.Details,
Id = bucket.Id,
Files = new List<FileEntityDto>()
};
var domain = _settingManager.Value.GetSettingValue(AppSettingsNames.App.Domain);
if (!validity.HasValue)
validity = TimeSpan.FromHours(1);
var expires = validity.Value == TimeSpan.MaxValue ? DateTime.MaxValue : Clock.Now + validity.Value;
var hash = MakeExpiryHash(bucket.Id, expires);
var qExp = expires.ToString("s");
if (!bucket.Files.IsNullOrEmpty())
{
foreach (var file in bucket.Files.OrderBy(v => v.CreationTime))
{
var query = new QueryBuilder
{
{ "id", file.Id.ToString() },
{ "exp", qExp },
{ "key", hash }
};
var fileDto = new FileEntityDto()
{
ContentType = file.ContentType,
CreationTime = file.CreationTime,
FileName = file.FileName,
Id = file.Id,
Length = file.Length,
IsEncrypted = file.AesCredentials != null,
Url = file.StorageType == StorageType.Azure
? _azureBlobStorageAdapter.Value.GetSasLink(file, validity).OrThrow().ToString()
: $"{domain}/api/Files/Get{query.ToQueryString()}"
};
bucketDto.Files.Add(fileDto);
}
}
return bucketDto;
}
public FileBucketDto GetFileBucketDto(IMayHaveFiles entity, TimeSpan? validity = null)
{
if (!entity.FileBucketId.HasValue)
return null;
var bucket = entity.FileBucket;
if (entity.FileBucket == null || entity.FileBucket.Files == null)
{
bucket = _bucketRepository
.Value
.GetAll()
.OfType<FileBucket>()
.AsNoTracking()
.Where(v => v.Id == entity.FileBucketId.Value)
.Include(v => v.Files)
.SingleOrDefault();
}
return GetFileBucketDto(bucket);
}
public virtual async Task<FileBucketDto> GetFileBucketDto(Guid bucketId, TimeSpan? validity = null)
{
var bucket = await _bucketRepository
.Value
.GetAll()
.AsNoTracking()
.Where(v => v.Id == bucketId)
.Include(v => v.Files)
.SingleOrDefaultAsync();
if (bucket == null)
return null;
return GetFileBucketDto(bucket, validity);
}
private static string MakeExpiryHash(Guid bucketId, DateTime expiry)
{
return Base64UrlTextEncoder.Encode(SHA1.HashData(
Encoding.UTF8.GetBytes($"{bucketId}:{expiry:s}:{bucketId}")));
}
public virtual async Task AssignFileToEntity(IMayHaveFiles entity, Guid? id)
{
//TODO is it a bug? (entity.FileBucketId == id)
if (entity.FileBucketId == id || !id.HasValue)
return;
if (entity.FileBucketId.HasValue)
{
var bucket = await _bucketRepository
.Value
.GetAll()
.AsNoTracking()
.SingleAsync(v => v.Id == entity.FileBucketId.Value);
var tempBucket = await _bucketRepository
.Value
.GetAll()
.Include(v => v.Files)
.SingleAsync(v => v.Id == id.Value);
foreach (var file in tempBucket.Files)
{
file.FileBucketId = bucket.Id;
}
tempBucket.Orphaned = true;
}
else if (id.HasValue)
{
entity.FileBucketId = id;
await _bucketRepository
.Value
.GetAll()
.Where(v => v.Id == id.Value)
.ForEachAsync(v => v.Orphaned = false);
}
}
public async Task SetOrphanedAsync(Guid? fileBucketId, bool orphaned)
{
await _bucketRepository
.Value
.GetAll()
.Where(v => v.Id == fileBucketId.Value)
.ForEachAsync(v => v.Orphaned = orphaned);
}
public async Task<FileEntityDto> SetTemporaryFileAsync(byte[] bytes, string contentType, int validityTimeSeconds)
{
var guid = Guid.NewGuid();
var domain = _settingManager.Value.GetSettingValue(AppSettingsNames.App.Domain);
var creationTime = Clock.Now;
var dto = new FileEntityDto()
{
Id = guid,
ContentType = contentType,
CreationTime = creationTime,
Length = bytes.Length,
Url = $"{domain}/api/Files/GetTemporary?id={guid}",
FileName = $"{creationTime:yyyyMMddHHmmss}_{guid}.{ContentTypeToExtension(contentType)}",
};
await _tempCache.Value.SetAsync(guid, (bytes, dto), absoluteExpireTime: new DateTimeOffset(Clock.Now.AddSeconds(validityTimeSeconds)));
return dto;
}
private class InlineFileContentResult : FileContentResult
{
public InlineFileContentResult(byte[] fileContents, string contentType)
: base(fileContents, contentType)
{
}
public override Task ExecuteResultAsync(ActionContext context)
{
var contentDispositionHeader = new ContentDispositionHeaderValue("inline");
contentDispositionHeader.SetHttpFileName(FileDownloadName);
context.HttpContext.Response.Headers.Add(HeaderNames.ContentDisposition, contentDispositionHeader.ToString());
FileDownloadName = string.Empty;
return base.ExecuteResultAsync(context);
}
}
public async Task<FileContentResult> GetTemporaryFileAsync(Guid guid, bool inline)
{
var found = await _tempCache.Value.GetOrDefaultAsync(guid);
if (found == default)
throw new KeyNotFoundException(guid.ToString());
var dto = found.Item2;
return inline
? new InlineFileContentResult(found.Item1, dto.ContentType)
: new FileContentResult(found.Item1, dto.ContentType)
{
FileDownloadName = dto.FileName,
LastModified = dto.CreationTime
};
}
private static string GetFilePath(FileEntity file)
{
return Path.Combine(GetBucketDirectoryPath(file.FileBucketId), file.Id.ToString());
}
private static string GetBucketDirectoryPath(Guid bucketId)
{
return Path.Combine(Directory.GetCurrentDirectory(), "files", bucketId.ToString());
}
private static string ContentTypeToExtension(string contentType)
{
return contentType switch
{
ContentTypes.Pdf => "pdf",
ContentTypes.Png => "",
ContentTypes.Jpg => "jpg",
ContentTypes.Doc => "doc",
ContentTypes.Docx => "docx",
ContentTypes.Xls => "xls",
ContentTypes.Xlsx => "xlsx",
ContentTypes.Csv => "csv",
ContentTypes.Rtf => "rtf",
ContentTypes.Txt => "txt",
ContentTypes.Odt => "odt",
ContentTypes.Ods => "ods",
_ => "download",
};
}
public async Task<Either<T>> SetBucketForNewEntity<T>(T targetEntity) where T : IMayHaveFiles
{
try
{
var bucketId = targetEntity.FileBucketId;
targetEntity.FileBucketId = null;
await AssignFileToEntity(targetEntity, bucketId);
return Either.Success(targetEntity);
}
catch (Exception e)
{
return Either<T>.InternalError(e);
}
}
public async Task<Either<T>> SetBucketUponUpdate<T>(T targetEntity, Guid? id, bool allowDelete = false) where T : IMayHaveFiles
{
if (targetEntity.FileBucketId == id)
{
return targetEntity.AsSuccess();
}
if (targetEntity.FileBucketId != null && id != null)
{
return Either<T>.InternalError($"Attempt to change bucket id {targetEntity.FileBucketId} -> {id}. {typeof(T)}");
}
try
{
if (targetEntity.FileBucketId != null && id == null)
{
if (!allowDelete)
return Either<T>.InternalError($"Attempt to delete bucket id {targetEntity.FileBucketId}. {typeof(T)}");
var bucketEntity = await _bucketRepository
.Value
.GetAll()
.Include(v => v.Files)
.Where(v => v.Id == targetEntity.FileBucketId)
.SingleAsync();
await DeleteFileBucketAsync(bucketEntity);
targetEntity.FileBucketId = null;
return Either.Success(targetEntity);
}
await AssignFileToEntity(targetEntity, id);
return Either.Success(targetEntity);
}
catch (Exception e)
{
return Either<T>.InternalError(e);
}
}
}
/// AzureBlobStorageAdapter.cs
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using Abp.Configuration;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
using Azure.Storage.Sas;
using Medica.Configuration;
using ServiceStack;
namespace Medica.Files;
public class AzureBlobStorageAdapter : IAzureBlobStorageAdapter
{
private readonly ISettingManager _settingManager;
private readonly BlobServiceClient _blobServiceClient;
code
public AzureBlobStorageAdapter(ISettingManager settingManager, BlobServiceClient blobServiceClient)
{
_settingManager = settingManager;
_blobServiceClient = blobServiceClient;
}
public async Task<Either> SaveFileAsync(Stream stream, Guid id, bool isHot)
{
try
{
var blobClient = GetBlobClient(id);
await using (stream)
{
await blobClient.UploadAsync(stream, new BlobUploadOptions()
{
AccessTier = isHot ? AccessTier.Hot : AccessTier.Cold,
// https://gist.github.com/xiaomi7732/ab1d403ef497047fcb4d419e1c64f5cb
// By default, there will be condition to prevent overwrite.
// Set the conditions to null so that overwrite will be allowed.
Conditions = null,
});
}
return Either.Success();
}
catch (Exception e)
{
return Either.InternalError(e);
}
}
public async Task DownloadAsync(Guid id, Stream target)
{
var blobClient = GetBlobClient(id);
await blobClient.DownloadToAsync(target);
}
public async Task<Either> CopyAsync(Guid sourceId, Guid targetId)
{
var sourceBlobClient = GetBlobClient(sourceId);
var targetBlobClient = GetBlobClient(targetId);
var operation = await targetBlobClient.StartCopyFromUriAsync(sourceBlobClient.Uri);
var response = await operation.WaitForCompletionResponseAsync();
if (response.Status != (int)HttpStatusCode.OK)
{
return Either.InternalError("Copying failed: " + response.Status);
}
return Either.Success();
}
public async Task<Either> DeleteFileAsync(Guid id)
{
try
{
var blobClient = GetBlobClient(id);
await blobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots);
return Either.Success();
}
catch (Exception e)
{
return Either.InternalError(e);
}
}
private BlobClient GetBlobClient(Guid id)
{
var containerName = GetContainerName();
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
var blobClient = containerClient.GetBlobClient(id.ToString());
return blobClient;
}
private string GetContainerName()
{
return _settingManager.GetSettingValue(AppSettingsNames.FileStorage.CloudStorageContainerName);
}
public Either<Uri> GetSasLink(FileEntity fileEntity, TimeSpan? validity = null)
{
try
{
var validitySeconds = validity?.TotalSeconds ?? 600;
var blobClient = GetBlobClient(fileEntity.Id);
if (blobClient.CanGenerateSasUri)
{
var sanitizedFileName = fileEntity.ContentType == ContentTypes.Pdf &&
fileEntity.FileName is { } rawFileName &&
!rawFileName.EndsWithIgnoreCase(".pdf")
? $"{rawFileName}.pdf"
: fileEntity.FileName;
var sasBuilder = new BlobSasBuilder
{
BlobContainerName = blobClient.GetParentBlobContainerClient().Name,
BlobName = blobClient.Name,
Resource = "b",
ContentDisposition = "inline; filename=" + HttpUtility.UrlEncode(sanitizedFileName),
ContentType = fileEntity.ContentType,
ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(validitySeconds),
};
sasBuilder.SetPermissions(BlobSasPermissions.Read);
return blobClient.GenerateSasUri(sasBuilder).AsSuccess();
}
return Either<Uri>.InternalError("BlobClient must be authorized with Shared Key credentials to create a service SAS.");
}
catch (Exception e)
{
return Either<Uri>.InternalError(e);
}
}
}
Aby zmodyfikować aplikację w C# zgodnie z Twoimi wymaganiami, będziemy musieli przeprowadzić kilka kroków:
Zmodyfikować AzureBlobStorageAdapter::GetSasLink, aby akceptował parametr określający Content-Disposition.
Rozszerzyć FileService, aby generował dwa linki SAS z różnymi ustawieniami Content-Disposition.
Aktualizować DTO (Data Transfer Objects), aby przechowywały oba linki SAS.
Dostosować kontrolery API, jeśli to konieczne, aby udostępniały oba linki SAS klientowi.
Poniżej przedstawiam szczegółowe kroki wraz z odpowiednimi fragmentami kodu.
Pierwszym krokiem jest modyfikacja metody GetSasLink w klasie AzureBlobStorageAdapter, aby akceptowała dodatkowy parametr contentDisposition. Dzięki temu będziemy mogli generować linki SAS z różnymi wartościami Content-Disposition (inline i attachment).
Zmiana Interfejsu IAzureBlobStorageAdapter
Najpierw upewnij się, że interfejs IAzureBlobStorageAdapter jest odpowiednio zmodyfikowany, aby odzwierciedlał zmieniony podpis metody GetSasLink.
Następnie zaktualizujemy samą implementację metody GetSasLink, aby używała przekazanego Content-Disposition.
csharp
// AzureBlobStorageAdapter.cs
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using Abp.Configuration;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Sas;
using Medica.Configuration;
using ServiceStack;
namespace Medica.Files
{
public class AzureBlobStorageAdapter : IAzureBlobStorageAdapter
{
private readonly ISettingManager _settingManager;
private readonly BlobServiceClient _blobServiceClient;
public AzureBlobStorageAdapter(ISettingManager settingManager, BlobServiceClient blobServiceClient)
{
_settingManager = settingManager;
_blobServiceClient = blobServiceClient;
}
// Zmieniony podpis metody GetSasLink
public Either<Uri> GetSasLink(FileEntity fileEntity, TimeSpan? validity = null, string contentDisposition = "inline")
{
try
{
var validitySeconds = validity?.TotalSeconds ?? 600; // domyślnie 10 minut
var blobClient = GetBlobClient(fileEntity.Id);
if (blobClient.CanGenerateSasUri)
{
var sanitizedFileName = fileEntity.ContentType == ContentTypes.Pdf &&
!fileEntity.FileName.EndsWithIgnoreCase(".pdf")
? $"{fileEntity.FileName}.pdf"
: fileEntity.FileName;
var sasBuilder = new BlobSasBuilder
{
BlobContainerName = blobClient.GetParentBlobContainerClient().Name,
BlobName = blobClient.Name,
Resource = "b",
ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(validitySeconds),
ContentType = fileEntity.ContentType,
ContentDisposition = $"{contentDisposition}; filename=\"{HttpUtility.UrlEncode(sanitizedFileName)}\""
};
sasBuilder.SetPermissions(BlobSasPermissions.Read);
var sasUri = blobClient.GenerateSasUri(sasBuilder);
return sasUri.AsSuccess();
}
return Either<Uri>.InternalError("BlobClient must be authorized with Shared Key credentials to create a service SAS.");
}
catch (Exception e)
{
return Either<Uri>.InternalError(e);
}
}
// ... pozostałe metody pozostają bez zmian ...
}
}
Wyjaśnienie:
Parametr contentDisposition: Dodaliśmy parametr contentDisposition, który domyślnie jest ustawiony na "inline". Możemy go zmienić na "attachment" podczas generowania linku SAS do pobierania pliku.
Ustawienie Content-Disposition: W BlobSasBuilder ustawiamy ContentDisposition zgodnie z przekazanym parametrem.
2. Rozszerzenie FileService o generowanie dwóch linków SAS
Teraz rozszerzymy FileService o metodę, która będzie generować oba linki SAS: jeden do wyświetlania (inline), a drugi do pobierania (attachment).
Aktualizacja DTO FileEntityDto
Najpierw zaktualizujemy istniejące DTO, aby przechowywały oba linki.
csharp
// FileEntityDto.cs (jeśli istnieje, inaczej należy go utworzyć lub zaktualizować)
using System;
namespace Medica.Files
{
public class FileEntityDto
{
public Guid Id { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public long Length { get; set; }
public DateTime CreationTime { get; set; }
public bool IsEncrypted { get; set; }
// Dodane właściwości dla linków SAS
public Uri InlineUrl { get; set; }
public Uri AttachmentUrl { get; set; }
}
}
Dodanie Metody Generującej Dwa Linki SAS
Dodamy nową metodę w FileService, która zwróci zarówno link do wyświetlania, jak i do pobierania.
csharp
Wyjaśnienie:
Nowa Metoda GetFileSasLinksAsync: Ta metoda przyjmuje Guid id pliku i opcjonalnie TimeSpan validity, który określa, jak długo linki SAS będą ważne.
Generowanie Linków: Metoda wykorzystuje zmodyfikowaną metodę GetSasLink, aby wygenerować dwa linki SAS z różnymi ustawieniami Content-Disposition:
Inline: Ustawione na "inline", co umożliwia wyświetlenie pliku bezpośrednio w przeglądarce.
Attachment: Ustawione na "attachment", co powoduje pobranie pliku.
Obsługa Błędów: Jeśli któreś z generowanych linków SAS się nie powiodą, metoda zwróci błąd.
Aktualizacja GetFileBucketDto: W tej metodzie teraz dla każdego pliku generowane są oba linki SAS i przypisywane do InlineUrl oraz AttachmentUrl w FileEntityDto.
3. Aktualizacja Kontrolera API
Zakładając, że masz kontroler API, który udostępnia informacje o plikach, musisz zaktualizować ten kontroler, aby zwracał oba linki SAS.
Przykładowy Kontroler API
Poniżej przedstawiam przykładowy kontroler API, który używa FileService do zwracania obu linków SAS.
csharp
// FilesController.cs
using System;
using System.Threading.Tasks;
using Medica.Files;
using Microsoft.AspNetCore.Mvc;
namespace Medica.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class FilesController : ControllerBase
{
private readonly IFileService _fileService;
public FilesController(IFileService fileService)
{
_fileService = fileService;
}
// Endpoint do pobierania obu linków SAS dla konkretnego pliku
[HttpGet("sas-links/{id}")]
public async Task<IActionResult> GetSasLinks(Guid id, [FromQuery] int validitySeconds = 600)
{
var validity = TimeSpan.FromSeconds(validitySeconds);
var sasLinksResult = await _fileService.GetFileSasLinksAsync(id, validity);
if (!sasLinksResult.IsSuccess)
{
return BadRequest(sasLinksResult.Error);
}
return Ok(sasLinksResult.Value);
}
}
}
Wyjaśnienie:
Endpoint GetSasLinks: Ten endpoint przyjmuje id pliku oraz opcjonalny parametr validitySeconds, który określa, jak długo linki SAS będą ważne (domyślnie 600 sekund).
Zwracanie Linków: Metoda wykorzystuje FileService.GetFileSasLinksAsync do generowania linków i zwraca je jako odpowiedź JSON.
4. Aktualizacja Vue Component
Chociaż głównie poprosiłeś o zmiany w C#, warto również zaktualizować Vue component, aby korzystał z nowych linków SAS do pobierania plików.
Zmiana Metody downloadImage
Obecnie metoda downloadImage pobiera obraz przez API i ręcznie tworzy plik do pobrania. Teraz możemy uprościć ten proces, używając linku SAS z Content-Disposition: attachment.
javascript
// edit-medical-staff-profile.vue
<script lang="ts">
export default {
// ... istniejące właściwości i metody ...
methods: {
async downloadImage() {
try {
// Zakładamy, że masz dostęp do ID pliku. Możesz to uzyskać z modelu.
const fileId = this.model.avatarId; // Zakładając, że przechowujesz ID avatara
const response = await axios.get(`/api/files/sas-links/${fileId}`, {
params: {
validitySeconds: 3600 // Opcjonalnie, czas ważności linku
}
});
const { attachmentUrl } = response.data;
// Tworzenie tymczasowego elementu <a> do pobrania pliku
const link = document.createElement('a');
link.href = attachmentUrl;
link.setAttribute('download', this.model.avatarName || 'avatar.jpg'); // Ustawienie nazwy pliku
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.error("Błąd podczas pobierania zdjęcia:", error);
this.notifier.errorToast("Wystąpił błąd podczas pobierania zdjęcia.");
}
}
}
};
</script>
Wyjaśnienie:
Pobieranie Linku SAS: Metoda downloadImage teraz wysyła żądanie GET do endpointu /api/files/sas-links/{id}, aby otrzymać link SAS z Content-Disposition: attachment.
Automatyczne Pobieranie: Po otrzymaniu linku, tworzymy tymczasowy element <a>, ustawiamy jego href na link SAS i wywołujemy kliknięcie, co inicjuje pobieranie pliku.
5. Podsumowanie
Poniżej podsumowujemy wszystkie zmiany:
Rozszerzenie IAzureBlobStorageAdapter: Dodanie parametru contentDisposition do metody GetSasLink.
Modyfikacja AzureBlobStorageAdapter: Ustawienie Content-Disposition zgodnie z przekazanym parametrem.
Rozszerzenie FileService: Dodanie metody GetFileSasLinksAsync oraz aktualizacja istniejących metod do obsługi dwóch linków SAS.
Aktualizacja DTO: Dodanie właściwości InlineUrl i AttachmentUrl w FileEntityDto.
Zmiana Kontrolera API: Utworzenie endpointu, który zwraca oba linki SAS.
Aktualizacja Vue Component: Dostosowanie metody downloadImage do korzystania z nowego linku SAS do pobierania pliku.
6. Finalny Kod
AzureBlobStorageAdapter.cs
csharp
FileService.cs
csharp
FileEntityDto.cs
csharp
// FileEntityDto.cs
using System;
namespace Medica.Files
{
public class FileEntityDto
{
public Guid Id { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public long Length { get; set; }
public DateTime CreationTime { get; set; }
public bool IsEncrypted { get; set; }
// Dodane właściwości dla linków SAS
public Uri InlineUrl { get; set; }
public Uri AttachmentUrl { get; set; }
}
}
FileSasLinksDto.cs
csharp
// FileSasLinksDto.cs
using System;
namespace Medica.Files
{
public class FileSasLinksDto
{
public Uri InlineUrl { get; set; }
public Uri AttachmentUrl { get; set; }
}
}
FilesController.cs
csharp
// FilesController.cs
using System;
using System.Threading.Tasks;
using Medica.Files;
using Microsoft.AspNetCore.Mvc;
namespace Medica.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class FilesController : ControllerBase
{
private readonly IFileService _fileService;
public FilesController(IFileService fileService)
{
_fileService = fileService;
}
// Endpoint do pobierania obu linków SAS dla konkretnego pliku
[HttpGet("sas-links/{id}")]
public async Task<IActionResult> GetSasLinks(Guid id, [FromQuery] int validitySeconds = 600)
{
var validity = TimeSpan.FromSeconds(validitySeconds);
var sasLinksResult = await _fileService.GetFileSasLinksAsync(id, validity);
if (!sasLinksResult.IsSuccess)
{
return BadRequest(sasLinksResult.Error);
}
return Ok(sasLinksResult.Value);
}
}
}
<template>
<!-- ... istniejący kod ... -->
<v-btn
v-if="model.avatarUrl"
color="primary"
class="mt-4"
@click="downloadImage">
Pobierz
</v-btn>
<!-- ... istniejący kod ... -->
</template>
<script lang="ts">
import axios from "@/lib/axios";
import { defineComponent, ref, inject } from "@vue/composition-api";
import Notifier from "@/views/main-wrap/notifier";
export default defineComponent({
// ... istniejące komponeny i props ...
setup(props, context) {
const notifier = inject(Notifier.Key) as Notifier;
// ... istniejące referencje i zmienne ...
const downloadImage = async () => {
if (model.value.avatarId) { // Zakładamy, że przechowujesz ID avatara
try {
const response = await axios.get(`/api/files/sas-links/${model.value.avatarId}`, {
params: {
validitySeconds: 3600 // Opcjonalnie, czas ważności linku
}
});
const { attachmentUrl } = response.data;
// Tworzenie tymczasowego elementu <a> do pobrania pliku
const link = document.createElement('a');
link.href = attachmentUrl;
link.setAttribute('download', model.value.avatarName || 'avatar.jpg'); // Ustawienie nazwy pliku
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.error("Błąd podczas pobierania zdjęcia:", error);
notifier.errorToast("Wystąpił błąd podczas pobierania zdjęcia.");
}
} else {
notifier.errorToast("Brak dostępnego avatara do pobrania.");
}
};
return {
// ... istniejące metody i zmienne ...
downloadImage
};
}
});
</script>
<style scoped>
/* ... istniejące style ... */
</style>
Wyjaśnienie:
Korzystanie z Nowego Endpointu: Metoda downloadImage teraz wysyła żądanie GET do endpointu /api/files/sas-links/{id} i otrzymuje oba linki SAS, z których wykorzystujemy attachmentUrl do pobierania pliku.
Automatyczne Pobieranie: Tworzymy tymczasowy element <a>, ustawiamy jego href na attachmentUrl i wywołujemy kliknięcie, co powoduje pobranie pliku.
Bezpieczeństwo: Upewnij się, że tylko uprawnieni użytkownicy mają dostęp do endpointu generującego linki SAS, aby uniknąć nieautoryzowanego dostępu do plików.
7. Testowanie
Po wprowadzeniu powyższych zmian, przeprowadź następujące kroki testowe:
Prześlij Nowy Plik: Upewnij się, że przesyłanie plików działa poprawnie i plik jest przechowywany w Azure Blob Storage.
Generowanie Linków SAS: Użyj endpointu API /api/files/sas-links/{id}, aby otrzymać oba linki SAS dla określonego pliku.
Pobieranie Pliku: Kliknij przycisk "Pobierz" w interfejsie użytkownika i upewnij się, że plik jest prawidłowo pobierany z ustawionym Content-Disposition: attachment.
Wyświetlanie Pliku Inline: Jeśli chcesz umożliwić wyświetlanie pliku inline, możesz również dodać odpowiedni link w interfejsie użytkownika korzystający z InlineUrl.
8. Uwagi Końcowe
Bezpieczeństwo Linków SAS: Zawsze kontroluj czas ważności linków SAS oraz kto ma do nich dostęp, aby zapewnić bezpieczeństwo przechowywanych plików.
Rozszerzalność: Możesz łatwo rozszerzyć tę funkcjonalność, dodając kolejne opcje dostępu do plików lub różne typy Content-Disposition w zależności od potrzeb.
Obsługa Błędów: Upewnij się, że odpowiednio obsługujesz wszelkie możliwe błędy zarówno po stronie serwera, jak i klienta, aby zapewnić poprawne działanie aplikacji nawet w przypadku problemów.
Jeśli napotkasz jakiekolwiek problemy podczas implementacji, daj znać, a chętnie pomogę!
// FileService.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Medica.Commerce.DateTimeEnumerator;
using Medica.Common.Extensions;
using Medica.Communication;
using Medica.Configuration;
using Medica.Extensions;
using Medica.Files.Notification;
using Medica.Helpers.Cache;
using Medica.ImageProcessing;
using Medica.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
namespace Medica.Files
{
public class FileService : BaseMedicaService, IFileService
{
// ... istniejące pola i konstruktor ...
// Nowa metoda do generowania dwóch linków SAS
public async Task<Either<FileSasLinksDto>> GetFileSasLinksAsync(Guid id, TimeSpan? validity = null)
{
try
{
var file = await GetFileEntityAsync(id);
if (file.StorageType != StorageType.Azure)
return Either<FileSasLinksDto>.InternalError("Requested file is not stored in Azure.");
// Generowanie linku do wyświetlania (inline)
var inlineLinkResult = _azureBlobStorageAdapter.Value.GetSasLink(
file,
validity,
"inline"
);
// Generowanie linku do pobierania (attachment)
var attachmentLinkResult = _azureBlobStorageAdapter.Value.GetSasLink(
file,
validity,
$"attachment; filename=\"{file.FileName}\""
);
if (!inlineLinkResult.IsSuccess || !attachmentLinkResult.IsSuccess)
{
return Either<FileSasLinksDto>.InternalError("Failed to generate SAS links.");
}
var sasLinks = new FileSasLinksDto
{
InlineUrl = inlineLinkResult.Value,
AttachmentUrl = attachmentLinkResult.Value
};
return sasLinks.AsSuccess();
}
catch (Exception e)
{
return Either<FileSasLinksDto>.InternalError(e);
}
}
// ... istniejące metody ...
// Aktualizacja metody GetFileBucketDto, aby uwzględniała oba linki
public FileBucketDto GetFileBucketDto(FileBucketBase bucket, TimeSpan? validity = null)
{
if (bucket == null)
return null;
var bucketDto = new FileBucketDto
{
Name = bucket.Name,
CreationTime = bucket.CreationTime,
Details = bucket.Details,
Id = bucket.Id,
Files = new List<FileEntityDto>()
};
var domain = _settingManager.Value.GetSettingValue(AppSettingsNames.App.Domain);
if (!validity.HasValue)
validity = TimeSpan.FromHours(1);
var expires = validity.Value == TimeSpan.MaxValue ? DateTime.MaxValue : Clock.Now + validity.Value;
var hash = MakeExpiryHash(bucket.Id, expires);
var qExp = expires.ToString("s");
if (!bucket.Files.IsNullOrEmpty())
{
foreach (var file in bucket.Files.OrderBy(v => v.CreationTime))
{
// Generowanie obu linków SAS
var inlineLink = _azureBlobStorageAdapter.Value.GetSasLink(
file,
validity,
"inline; filename=\"" + Uri.EscapeDataString(file.FileName) + "\""
).OrThrow();
var attachmentLink = _azureBlobStorageAdapter.Value.GetSasLink(
file,
validity,
$"attachment; filename=\"{Uri.EscapeDataString(file.FileName)}\""
).OrThrow();
var fileDto = new FileEntityDto
{
ContentType = file.ContentType,
CreationTime = file.CreationTime,
FileName = file.FileName,
Id = file.Id,
Length = file.Length,
IsEncrypted = file.AesCredentials != null,
InlineUrl = inlineLink,
AttachmentUrl = attachmentLink
};
bucketDto.Files.Add(fileDto);
}
}
return bucketDto;
}
// ... reszta klasy pozostaje bez zmian ...
}
// DTO do przechowywania dwóch linków SAS
public class FileSasLinksDto
{
public Uri InlineUrl { get; set; }
public Uri AttachmentUrl { get; set; }
}
// ... inne klasy i metody ...
}
// AzureBlobStorageAdapter.cs
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using Abp.Configuration;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Sas;
using Medica.Configuration;
using ServiceStack;
namespace Medica.Files
{
public class AzureBlobStorageAdapter : IAzureBlobStorageAdapter
{
private readonly ISettingManager _settingManager;
private readonly BlobServiceClient _blobServiceClient;
public AzureBlobStorageAdapter(ISettingManager settingManager, BlobServiceClient blobServiceClient)
{
_settingManager = settingManager;
_blobServiceClient = blobServiceClient;
}
public async Task<Either> SaveFileAsync(Stream stream, Guid id, bool isHot)
{
try
{
var blobClient = GetBlobClient(id);
await using (stream)
{
await blobClient.UploadAsync(stream, new BlobUploadOptions()
{
AccessTier = isHot ? AccessTier.Hot : AccessTier.Cold,
Conditions = null,
});
}
return Either.Success();
}
catch (Exception e)
{
return Either.InternalError(e);
}
}
public async Task DownloadAsync(Guid id, Stream target)
{
var blobClient = GetBlobClient(id);
await blobClient.DownloadToAsync(target);
}
public async Task<Either> CopyAsync(Guid sourceId, Guid targetId)
{
var sourceBlobClient = GetBlobClient(sourceId);
var targetBlobClient = GetBlobClient(targetId);
var operation = await targetBlobClient.StartCopyFromUriAsync(sourceBlobClient.Uri);
var response = await operation.WaitForCompletionResponseAsync();
if (response.Status != (int)HttpStatusCode.OK)
{
return Either.InternalError("Copying failed: " + response.Status);
}
return Either.Success();
}
public async Task<Either> DeleteFileAsync(Guid id)
{
try
{
var blobClient = GetBlobClient(id);
await blobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots);
return Either.Success();
}
catch (Exception e)
{
return Either.InternalError(e);
}
}
private BlobClient GetBlobClient(Guid id)
{
var containerName = GetContainerName();
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
var blobClient = containerClient.GetBlobClient(id.ToString());
return blobClient;
}
private string GetContainerName()
{
return _settingManager.GetSettingValue(AppSettingsNames.FileStorage.CloudStorageContainerName);
}
// Zmieniony podpis metody GetSasLink
public Either<Uri> GetSasLink(FileEntity fileEntity, TimeSpan? validity = null, string contentDisposition = "inline")
{
try
{
var validitySeconds = validity?.TotalSeconds ?? 600; // domyślnie 10 minut
var blobClient = GetBlobClient(fileEntity.Id);
if (blobClient.CanGenerateSasUri)
{
var sanitizedFileName = fileEntity.ContentType == ContentTypes.Pdf &&
!fileEntity.FileName.EndsWithIgnoreCase(".pdf")
? $"{fileEntity.FileName}.pdf"
: fileEntity.FileName;
var sasBuilder = new BlobSasBuilder
{
BlobContainerName = blobClient.GetParentBlobContainerClient().Name,
BlobName = blobClient.Name,
Resource = "b",
ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(validitySeconds),
ContentType = fileEntity.ContentType,
ContentDisposition = $"{contentDisposition}; filename=\"{HttpUtility.UrlEncode(sanitizedFileName)}\""
};
sasBuilder.SetPermissions(BlobSasPermissions.Read);
var sasUri = blobClient.GenerateSasUri(sasBuilder);
return sasUri.AsSuccess();
}
return Either<Uri>.InternalError("BlobClient must be authorized with Shared Key credentials to create a service SAS.");
}
catch (Exception e)
{
return Either<Uri>.InternalError(e);
}
}
}
}
// FileService.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Medica.Commerce.DateTimeEnumerator;
using Medica.Common.Extensions;
using Medica.Communication;
using Medica.Configuration;
using Medica.Extensions;
using Medica.Files.Notification;
using Medica.Helpers.Cache;
using Medica.ImageProcessing;
using Medica.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
namespace Medica.Files
{
public class FileService : BaseMedicaService, IFileService
{
// ... istniejące pola i konstruktor ...
// Nowa metoda do generowania dwóch linków SAS
public async Task<Either<FileSasLinksDto>> GetFileSasLinksAsync(Guid id, TimeSpan? validity = null)
{
try
{
var file = await GetFileEntityAsync(id);
if (file.StorageType != StorageType.Azure)
return Either<FileSasLinksDto>.InternalError("Requested file is not stored in Azure.");
// Generowanie linku do wyświetlania (inline)
var inlineLinkResult = _azureBlobStorageAdapter.Value.GetSasLink(
file,
validity,
"inline"
);
// Generowanie linku do pobierania (attachment)
var attachmentLinkResult = _azureBlobStorageAdapter.Value.GetSasLink(
file,
validity,
$"attachment; filename=\"{file.FileName}\""
);
if (!inlineLinkResult.IsSuccess || !attachmentLinkResult.IsSuccess)
{
return Either<FileSasLinksDto>.InternalError("Failed to generate SAS links.");
}
var sasLinks = new FileSasLinksDto
{
InlineUrl = inlineLinkResult.Value,
AttachmentUrl = attachmentLinkResult.Value
};
return sasLinks.AsSuccess();
}
catch (Exception e)
{
return Either<FileSasLinksDto>.InternalError(e);
}
}
// Aktualizacja metody GetFileBucketDto, aby uwzględniała oba linki SAS
public FileBucketDto GetFileBucketDto(FileBucketBase bucket, TimeSpan? validity = null)
{
if (bucket == null)
return null;
var bucketDto = new FileBucketDto
{
Name = bucket.Name,
CreationTime = bucket.CreationTime,
Details = bucket.Details,
Id = bucket.Id,
Files = new List<FileEntityDto>()
};
var domain = _settingManager.Value.GetSettingValue(AppSettingsNames.App.Domain);
if (!validity.HasValue)
validity = TimeSpan.FromHours(1);
var expires = validity.Value == TimeSpan.MaxValue ? DateTime.MaxValue : Clock.Now + validity.Value;
var hash = MakeExpiryHash(bucket.Id, expires);
var qExp = expires.ToString("s");
if (!bucket.Files.IsNullOrEmpty())
{
foreach (var file in bucket.Files.OrderBy(v => v.CreationTime))
{
// Generowanie obu linków SAS
var inlineLink = _azureBlobStorageAdapter.Value.GetSasLink(
file,
validity,
"inline; filename=\"" + Uri.EscapeDataString(file.FileName) + "\""
).OrThrow();
var attachmentLink = _azureBlobStorageAdapter.Value.GetSasLink(
file,
validity,
$"attachment; filename=\"{Uri.EscapeDataString(file.FileName)}\""
).OrThrow();
var fileDto = new FileEntityDto
{
ContentType = file.ContentType,
CreationTime = file.CreationTime,
FileName = file.FileName,
Id = file.Id,
Length = file.Length,
IsEncrypted = file.AesCredentials != null,
InlineUrl = inlineLink,
AttachmentUrl = attachmentLink
};
bucketDto.Files.Add(fileDto);
}
}
return bucketDto;
}
// ... pozostałe metody pozostają bez zmian ...
}
// DTO do przechowywania dwóch linków SAS
public class FileSasLinksDto
{
public Uri InlineUrl { get; set; }
public Uri AttachmentUrl { get; set; }
}
// ... inne klasy i metody ...
}