| | | 1 | | using Azure; |
| | | 2 | | using Azure.Storage.Blobs; |
| | | 3 | | using Azure.Storage.Blobs.Models; |
| | | 4 | | using Azure.Storage.Sas; |
| | | 5 | | using Chronicis.Shared.Extensions; |
| | | 6 | | |
| | | 7 | | namespace Chronicis.Api.Services; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Azure Blob Storage service for managing world document files. |
| | | 11 | | /// </summary> |
| | | 12 | | public class BlobStorageService : IBlobStorageService |
| | | 13 | | { |
| | | 14 | | private readonly BlobServiceClient _blobServiceClient; |
| | | 15 | | private readonly IConfiguration _configuration; |
| | | 16 | | private readonly ILogger<BlobStorageService> _logger; |
| | | 17 | | private readonly string _containerName; |
| | | 18 | | private readonly string? _customDomain; |
| | | 19 | | |
| | 0 | 20 | | public BlobStorageService( |
| | 0 | 21 | | IConfiguration configuration, |
| | 0 | 22 | | ILogger<BlobStorageService> logger) |
| | | 23 | | { |
| | 0 | 24 | | _configuration = configuration; |
| | 0 | 25 | | _logger = logger; |
| | | 26 | | |
| | 0 | 27 | | var connectionString = configuration["BlobStorage:ConnectionString"] |
| | 0 | 28 | | ?? configuration["BlobStorage__ConnectionString"]; // Try double underscore format |
| | | 29 | | |
| | 0 | 30 | | if (string.IsNullOrEmpty(connectionString)) |
| | | 31 | | { |
| | 0 | 32 | | _logger.LogError("BlobStorage:ConnectionString not configured. Check Azure app settings."); |
| | 0 | 33 | | throw new InvalidOperationException("BlobStorage:ConnectionString not configured. Please add BlobStorage__Co |
| | | 34 | | } |
| | | 35 | | |
| | 0 | 36 | | _containerName = configuration["BlobStorage:ContainerName"] |
| | 0 | 37 | | ?? configuration["BlobStorage__ContainerName"] |
| | 0 | 38 | | ?? "chronicis-documents"; |
| | | 39 | | |
| | | 40 | | // Optional custom domain (e.g., "http://docs.chronicis.app" or "https://docs.chronicis.app") |
| | 0 | 41 | | _customDomain = configuration["BlobStorage:CustomDomain"] |
| | 0 | 42 | | ?? configuration["BlobStorage__CustomDomain"]; |
| | | 43 | | |
| | 0 | 44 | | if (!string.IsNullOrEmpty(_customDomain)) |
| | | 45 | | { |
| | 0 | 46 | | _logger.LogDebug("Using custom domain for blob URLs: {CustomDomain}", _customDomain); |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | try |
| | | 50 | | { |
| | 0 | 51 | | _blobServiceClient = new BlobServiceClient(connectionString); |
| | | 52 | | |
| | | 53 | | // Ensure container exists (idempotent) |
| | 0 | 54 | | var containerClient = _blobServiceClient.GetBlobContainerClient(_containerName); |
| | 0 | 55 | | containerClient.CreateIfNotExists(PublicAccessType.None); |
| | | 56 | | |
| | 0 | 57 | | _logger.LogDebug("BlobStorageService initialized with container: {ContainerName}", _containerName); |
| | 0 | 58 | | } |
| | 0 | 59 | | catch (Exception ex) |
| | | 60 | | { |
| | 0 | 61 | | _logger.LogError(ex, "Failed to initialize BlobStorageService. Connection string may be invalid."); |
| | 0 | 62 | | throw; |
| | | 63 | | } |
| | 0 | 64 | | } |
| | | 65 | | |
| | | 66 | | /// <inheritdoc/> |
| | | 67 | | public string BuildBlobPath(Guid worldId, Guid documentId, string fileName) |
| | | 68 | | { |
| | | 69 | | // Sanitize filename: remove path separators, keep only safe chars |
| | 0 | 70 | | var sanitized = SanitizeFileName(fileName); |
| | 0 | 71 | | return $"worlds/{worldId}/documents/{documentId}/{sanitized}"; |
| | | 72 | | } |
| | | 73 | | |
| | | 74 | | /// <inheritdoc/> |
| | | 75 | | public Task<string> GenerateUploadSasUrlAsync( |
| | | 76 | | Guid worldId, |
| | | 77 | | Guid documentId, |
| | | 78 | | string fileName, |
| | | 79 | | string contentType) |
| | | 80 | | { |
| | 0 | 81 | | var blobPath = BuildBlobPath(worldId, documentId, fileName); |
| | 0 | 82 | | var containerClient = _blobServiceClient.GetBlobContainerClient(_containerName); |
| | 0 | 83 | | var blobClient = containerClient.GetBlobClient(blobPath); |
| | | 84 | | |
| | | 85 | | // Generate SAS token with write permissions, 15-minute expiry |
| | 0 | 86 | | var sasBuilder = new BlobSasBuilder |
| | 0 | 87 | | { |
| | 0 | 88 | | BlobContainerName = _containerName, |
| | 0 | 89 | | BlobName = blobPath, |
| | 0 | 90 | | Resource = "b", // blob |
| | 0 | 91 | | StartsOn = DateTimeOffset.UtcNow.AddMinutes(-5), // Allow for clock skew |
| | 0 | 92 | | ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(15), |
| | 0 | 93 | | }; |
| | | 94 | | |
| | 0 | 95 | | sasBuilder.SetPermissions(BlobSasPermissions.Create | BlobSasPermissions.Write); |
| | | 96 | | |
| | 0 | 97 | | var sasUrl = BuildSasUrl(blobClient, sasBuilder); |
| | | 98 | | |
| | 0 | 99 | | _logger.LogDebugSanitized("Generated upload SAS URL for blob: {BlobPath}", blobPath); |
| | | 100 | | |
| | 0 | 101 | | return Task.FromResult(sasUrl); |
| | | 102 | | } |
| | | 103 | | |
| | | 104 | | /// <inheritdoc/> |
| | | 105 | | public async Task<BlobMetadata?> GetBlobMetadataAsync(string blobPath) |
| | | 106 | | { |
| | | 107 | | try |
| | | 108 | | { |
| | 0 | 109 | | var containerClient = _blobServiceClient.GetBlobContainerClient(_containerName); |
| | 0 | 110 | | var blobClient = containerClient.GetBlobClient(blobPath); |
| | | 111 | | |
| | 0 | 112 | | if (!await blobClient.ExistsAsync()) |
| | | 113 | | { |
| | 0 | 114 | | _logger.LogWarningSanitized("Blob not found: {BlobPath}", blobPath); |
| | 0 | 115 | | return null; |
| | | 116 | | } |
| | | 117 | | |
| | 0 | 118 | | var properties = await blobClient.GetPropertiesAsync(); |
| | | 119 | | |
| | 0 | 120 | | return new BlobMetadata |
| | 0 | 121 | | { |
| | 0 | 122 | | SizeBytes = properties.Value.ContentLength, |
| | 0 | 123 | | ContentType = properties.Value.ContentType |
| | 0 | 124 | | }; |
| | | 125 | | } |
| | 0 | 126 | | catch (RequestFailedException ex) |
| | | 127 | | { |
| | 0 | 128 | | _logger.LogErrorSanitized(ex, "Error getting blob metadata for: {BlobPath}", blobPath); |
| | 0 | 129 | | return null; |
| | | 130 | | } |
| | 0 | 131 | | } |
| | | 132 | | |
| | | 133 | | /// <inheritdoc/> |
| | | 134 | | public async Task<Stream> OpenReadAsync(string blobPath) |
| | | 135 | | { |
| | 0 | 136 | | var containerClient = _blobServiceClient.GetBlobContainerClient(_containerName); |
| | 0 | 137 | | var blobClient = containerClient.GetBlobClient(blobPath); |
| | | 138 | | |
| | 0 | 139 | | if (!await blobClient.ExistsAsync()) |
| | | 140 | | { |
| | 0 | 141 | | throw new FileNotFoundException($"Blob not found: {blobPath}"); |
| | | 142 | | } |
| | | 143 | | |
| | 0 | 144 | | return await blobClient.OpenReadAsync(); |
| | 0 | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <inheritdoc/> |
| | | 148 | | public async Task DeleteBlobAsync(string blobPath) |
| | | 149 | | { |
| | | 150 | | try |
| | | 151 | | { |
| | 0 | 152 | | var containerClient = _blobServiceClient.GetBlobContainerClient(_containerName); |
| | 0 | 153 | | var blobClient = containerClient.GetBlobClient(blobPath); |
| | | 154 | | |
| | 0 | 155 | | await blobClient.DeleteIfExistsAsync(); |
| | | 156 | | |
| | 0 | 157 | | _logger.LogDebugSanitized("Deleted blob: {BlobPath}", blobPath); |
| | 0 | 158 | | } |
| | 0 | 159 | | catch (RequestFailedException ex) |
| | | 160 | | { |
| | 0 | 161 | | _logger.LogErrorSanitized(ex, "Error deleting blob: {BlobPath}", blobPath); |
| | 0 | 162 | | throw; |
| | | 163 | | } |
| | 0 | 164 | | } |
| | | 165 | | |
| | | 166 | | /// <inheritdoc/> |
| | | 167 | | public Task<string> GenerateDownloadSasUrlAsync(string blobPath) |
| | | 168 | | { |
| | 0 | 169 | | var containerClient = _blobServiceClient.GetBlobContainerClient(_containerName); |
| | 0 | 170 | | var blobClient = containerClient.GetBlobClient(blobPath); |
| | | 171 | | |
| | | 172 | | // Generate SAS token with read permissions, 15-minute expiry |
| | 0 | 173 | | var sasBuilder = new BlobSasBuilder |
| | 0 | 174 | | { |
| | 0 | 175 | | BlobContainerName = _containerName, |
| | 0 | 176 | | BlobName = blobPath, |
| | 0 | 177 | | Resource = "b", // blob |
| | 0 | 178 | | StartsOn = DateTimeOffset.UtcNow.AddMinutes(-5), // Allow for clock skew |
| | 0 | 179 | | ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(15), |
| | 0 | 180 | | }; |
| | | 181 | | |
| | 0 | 182 | | sasBuilder.SetPermissions(BlobSasPermissions.Read); |
| | | 183 | | |
| | 0 | 184 | | var sasUrl = BuildSasUrl(blobClient, sasBuilder); |
| | | 185 | | |
| | 0 | 186 | | _logger.LogDebugSanitized("Generated download SAS URL for blob: {BlobPath}", blobPath); |
| | | 187 | | |
| | 0 | 188 | | return Task.FromResult(sasUrl); |
| | | 189 | | } |
| | | 190 | | |
| | | 191 | | private static string SanitizeFileName(string fileName) |
| | | 192 | | { |
| | | 193 | | // Remove path separators and keep only safe characters |
| | 0 | 194 | | var invalidChars = Path.GetInvalidFileNameChars(); |
| | 0 | 195 | | var sanitized = string.Join("_", fileName.Split(invalidChars, StringSplitOptions.RemoveEmptyEntries)); |
| | | 196 | | |
| | | 197 | | // Limit length |
| | 0 | 198 | | if (sanitized.Length > 200) |
| | | 199 | | { |
| | 0 | 200 | | var extension = Path.GetExtension(sanitized); |
| | 0 | 201 | | var nameWithoutExt = Path.GetFileNameWithoutExtension(sanitized); |
| | 0 | 202 | | sanitized = nameWithoutExt[..(200 - extension.Length)] + extension; |
| | | 203 | | } |
| | | 204 | | |
| | 0 | 205 | | return sanitized; |
| | | 206 | | } |
| | | 207 | | |
| | | 208 | | /// <summary> |
| | | 209 | | /// Build a SAS URL using either the custom domain or the default blob endpoint. |
| | | 210 | | /// </summary> |
| | | 211 | | private string BuildSasUrl(BlobClient blobClient, BlobSasBuilder sasBuilder) |
| | | 212 | | { |
| | 0 | 213 | | if (!string.IsNullOrEmpty(_customDomain)) |
| | | 214 | | { |
| | | 215 | | // Generate SAS token only (query string) |
| | 0 | 216 | | var sasToken = blobClient.GenerateSasUri(sasBuilder).Query; |
| | | 217 | | |
| | | 218 | | // Build custom URL: {customDomain}/{container}/{blobPath}?{sasToken} |
| | 0 | 219 | | var customUrl = $"{_customDomain.TrimEnd('/')}/{_containerName}/{blobClient.Name}{sasToken}"; |
| | | 220 | | |
| | 0 | 221 | | return customUrl; |
| | | 222 | | } |
| | | 223 | | else |
| | | 224 | | { |
| | | 225 | | // Use default blob endpoint with SAS |
| | 0 | 226 | | return blobClient.GenerateSasUri(sasBuilder).ToString(); |
| | | 227 | | } |
| | | 228 | | } |
| | | 229 | | } |