| | | 1 | | using Chronicis.Api.Data; |
| | | 2 | | using Chronicis.Shared.DTOs; |
| | | 3 | | using Chronicis.Shared.Extensions; |
| | | 4 | | using Chronicis.Shared.Models; |
| | | 5 | | using Microsoft.EntityFrameworkCore; |
| | | 6 | | |
| | | 7 | | namespace Chronicis.Api.Services; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Service for managing world documents with blob storage integration. |
| | | 11 | | /// </summary> |
| | | 12 | | public class WorldDocumentService : IWorldDocumentService |
| | | 13 | | { |
| | | 14 | | private readonly ChronicisDbContext _db; |
| | | 15 | | private readonly IBlobStorageService _blobStorage; |
| | | 16 | | private readonly IConfiguration _configuration; |
| | | 17 | | private readonly ILogger<WorldDocumentService> _logger; |
| | | 18 | | |
| | | 19 | | // File validation constants |
| | | 20 | | private const long MaxFileSizeBytes = 209_715_200; // 200 MB |
| | 0 | 21 | | private static readonly HashSet<string> AllowedExtensions = new(StringComparer.OrdinalIgnoreCase) |
| | 0 | 22 | | { |
| | 0 | 23 | | ".pdf", ".docx", ".xlsx", ".pptx", ".txt", ".md", |
| | 0 | 24 | | ".png", ".jpg", ".jpeg", ".gif", ".webp" |
| | 0 | 25 | | }; |
| | | 26 | | |
| | 0 | 27 | | private static readonly Dictionary<string, string> ExtensionToMimeType = new(StringComparer.OrdinalIgnoreCase) |
| | 0 | 28 | | { |
| | 0 | 29 | | { ".pdf", "application/pdf" }, |
| | 0 | 30 | | { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }, |
| | 0 | 31 | | { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, |
| | 0 | 32 | | { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }, |
| | 0 | 33 | | { ".txt", "text/plain" }, |
| | 0 | 34 | | { ".md", "text/markdown" }, |
| | 0 | 35 | | { ".png", "image/png" }, |
| | 0 | 36 | | { ".jpg", "image/jpeg" }, |
| | 0 | 37 | | { ".jpeg", "image/jpeg" }, |
| | 0 | 38 | | { ".gif", "image/gif" }, |
| | 0 | 39 | | { ".webp", "image/webp" } |
| | 0 | 40 | | }; |
| | | 41 | | |
| | 0 | 42 | | public WorldDocumentService( |
| | 0 | 43 | | ChronicisDbContext db, |
| | 0 | 44 | | IBlobStorageService blobStorage, |
| | 0 | 45 | | IConfiguration configuration, |
| | 0 | 46 | | ILogger<WorldDocumentService> logger) |
| | | 47 | | { |
| | 0 | 48 | | _db = db; |
| | 0 | 49 | | _blobStorage = blobStorage; |
| | 0 | 50 | | _configuration = configuration; |
| | 0 | 51 | | _logger = logger; |
| | 0 | 52 | | } |
| | | 53 | | |
| | | 54 | | public async Task<WorldDocumentUploadResponseDto> RequestUploadAsync( |
| | | 55 | | Guid worldId, |
| | | 56 | | Guid userId, |
| | | 57 | | WorldDocumentUploadRequestDto request) |
| | | 58 | | { |
| | 0 | 59 | | _logger.LogDebugSanitized("User {UserId} requesting upload for world {WorldId}: {FileName}", |
| | 0 | 60 | | userId, worldId, request.FileName); |
| | | 61 | | |
| | | 62 | | // Verify user owns the world |
| | 0 | 63 | | var world = await _db.Worlds |
| | 0 | 64 | | .AsNoTracking() |
| | 0 | 65 | | .FirstOrDefaultAsync(w => w.Id == worldId && w.OwnerId == userId); |
| | | 66 | | |
| | 0 | 67 | | if (world == null) |
| | | 68 | | { |
| | 0 | 69 | | throw new UnauthorizedAccessException("World not found or access denied"); |
| | | 70 | | } |
| | | 71 | | |
| | | 72 | | // Validate file |
| | 0 | 73 | | ValidateFileUpload(request); |
| | | 74 | | |
| | | 75 | | // Generate unique title (handle duplicates) |
| | 0 | 76 | | var title = await GenerateUniqueTitleAsync(worldId, request.FileName); |
| | | 77 | | |
| | | 78 | | // Create pending document record |
| | 0 | 79 | | var document = new WorldDocument |
| | 0 | 80 | | { |
| | 0 | 81 | | Id = Guid.NewGuid(), |
| | 0 | 82 | | WorldId = worldId, |
| | 0 | 83 | | ArticleId = request.ArticleId, |
| | 0 | 84 | | FileName = request.FileName, |
| | 0 | 85 | | Title = title, |
| | 0 | 86 | | ContentType = request.ContentType, |
| | 0 | 87 | | FileSizeBytes = request.FileSizeBytes, |
| | 0 | 88 | | Description = request.Description, |
| | 0 | 89 | | UploadedById = userId, |
| | 0 | 90 | | UploadedAt = DateTime.UtcNow, |
| | 0 | 91 | | BlobPath = "" // Will be set after blob path is generated |
| | 0 | 92 | | }; |
| | | 93 | | |
| | | 94 | | // Generate blob path and SAS URL |
| | 0 | 95 | | var blobPath = _blobStorage.BuildBlobPath(worldId, document.Id, request.FileName); |
| | 0 | 96 | | document.BlobPath = blobPath; |
| | | 97 | | |
| | 0 | 98 | | var sasUrl = await _blobStorage.GenerateUploadSasUrlAsync( |
| | 0 | 99 | | worldId, |
| | 0 | 100 | | document.Id, |
| | 0 | 101 | | request.FileName, |
| | 0 | 102 | | request.ContentType); |
| | | 103 | | |
| | | 104 | | // Save pending document (blob doesn't exist yet) |
| | 0 | 105 | | _db.WorldDocuments.Add(document); |
| | 0 | 106 | | await _db.SaveChangesAsync(); |
| | | 107 | | |
| | 0 | 108 | | _logger.LogDebug("Created pending document {DocumentId} for world {WorldId}", |
| | 0 | 109 | | document.Id, worldId); |
| | | 110 | | |
| | 0 | 111 | | return new WorldDocumentUploadResponseDto |
| | 0 | 112 | | { |
| | 0 | 113 | | DocumentId = document.Id, |
| | 0 | 114 | | UploadUrl = sasUrl, |
| | 0 | 115 | | Title = title |
| | 0 | 116 | | }; |
| | 0 | 117 | | } |
| | | 118 | | |
| | | 119 | | public async Task<WorldDocumentDto> ConfirmUploadAsync( |
| | | 120 | | Guid worldId, |
| | | 121 | | Guid documentId, |
| | | 122 | | Guid userId) |
| | | 123 | | { |
| | 0 | 124 | | _logger.LogDebug("User {UserId} confirming upload for document {DocumentId}", |
| | 0 | 125 | | userId, documentId); |
| | | 126 | | |
| | | 127 | | // Get the pending document |
| | 0 | 128 | | var document = await _db.WorldDocuments |
| | 0 | 129 | | .Include(d => d.World) |
| | 0 | 130 | | .FirstOrDefaultAsync(d => d.Id == documentId && d.WorldId == worldId); |
| | | 131 | | |
| | 0 | 132 | | if (document == null) |
| | | 133 | | { |
| | 0 | 134 | | throw new InvalidOperationException("Document not found"); |
| | | 135 | | } |
| | | 136 | | |
| | | 137 | | // Verify user owns the world |
| | 0 | 138 | | if (document.World.OwnerId != userId) |
| | | 139 | | { |
| | 0 | 140 | | throw new UnauthorizedAccessException("Only world owner can upload documents"); |
| | | 141 | | } |
| | | 142 | | |
| | | 143 | | // Verify blob exists in storage |
| | 0 | 144 | | var metadata = await _blobStorage.GetBlobMetadataAsync(document.BlobPath); |
| | | 145 | | |
| | 0 | 146 | | if (metadata == null) |
| | | 147 | | { |
| | | 148 | | // Blob upload failed or didn't complete |
| | 0 | 149 | | _logger.LogWarningSanitized("Blob not found for document {DocumentId}: {BlobPath}", |
| | 0 | 150 | | documentId, document.BlobPath); |
| | 0 | 151 | | throw new InvalidOperationException("File upload did not complete. Please try again."); |
| | | 152 | | } |
| | | 153 | | |
| | | 154 | | // Update document with actual blob metadata |
| | 0 | 155 | | document.FileSizeBytes = metadata.SizeBytes; |
| | 0 | 156 | | document.ContentType = metadata.ContentType; |
| | | 157 | | |
| | 0 | 158 | | await _db.SaveChangesAsync(); |
| | | 159 | | |
| | 0 | 160 | | _logger.LogDebug("Confirmed upload for document {DocumentId}, size: {SizeBytes} bytes", |
| | 0 | 161 | | documentId, metadata.SizeBytes); |
| | | 162 | | |
| | 0 | 163 | | return MapToDto(document); |
| | 0 | 164 | | } |
| | | 165 | | |
| | | 166 | | public async Task<List<WorldDocumentDto>> GetWorldDocumentsAsync(Guid worldId, Guid userId) |
| | | 167 | | { |
| | 0 | 168 | | _logger.LogDebug("User {UserId} getting documents for world {WorldId}", |
| | 0 | 169 | | userId, worldId); |
| | | 170 | | |
| | | 171 | | // Verify user has access to the world (owner or member) |
| | 0 | 172 | | var hasAccess = await _db.Worlds |
| | 0 | 173 | | .AsNoTracking() |
| | 0 | 174 | | .AnyAsync(w => w.Id == worldId && |
| | 0 | 175 | | (w.OwnerId == userId || w.Members.Any(m => m.UserId == userId))); |
| | | 176 | | |
| | 0 | 177 | | if (!hasAccess) |
| | | 178 | | { |
| | 0 | 179 | | throw new UnauthorizedAccessException("World not found or access denied"); |
| | | 180 | | } |
| | | 181 | | |
| | 0 | 182 | | var documents = await _db.WorldDocuments |
| | 0 | 183 | | .AsNoTracking() |
| | 0 | 184 | | .Where(d => d.WorldId == worldId) |
| | 0 | 185 | | .OrderByDescending(d => d.UploadedAt) |
| | 0 | 186 | | .ToListAsync(); |
| | | 187 | | |
| | 0 | 188 | | return documents.Select(MapToDto).ToList(); |
| | 0 | 189 | | } |
| | | 190 | | |
| | | 191 | | public async Task<DocumentContentResult> GetDocumentContentAsync(Guid documentId, Guid userId) |
| | | 192 | | { |
| | 0 | 193 | | _logger.LogDebug("User {UserId} requesting document download URL for {DocumentId}", |
| | 0 | 194 | | userId, documentId); |
| | | 195 | | |
| | 0 | 196 | | var document = await GetAuthorizedDocumentAsync(documentId, userId); |
| | 0 | 197 | | var contentType = string.IsNullOrWhiteSpace(document.ContentType) |
| | 0 | 198 | | ? "application/octet-stream" |
| | 0 | 199 | | : document.ContentType; |
| | | 200 | | |
| | | 201 | | // Generate read-only SAS URL for direct download from blob storage |
| | 0 | 202 | | var downloadUrl = await _blobStorage.GenerateDownloadSasUrlAsync(document.BlobPath); |
| | | 203 | | |
| | 0 | 204 | | return new DocumentContentResult( |
| | 0 | 205 | | downloadUrl, |
| | 0 | 206 | | document.FileName, |
| | 0 | 207 | | contentType, |
| | 0 | 208 | | document.FileSizeBytes); |
| | 0 | 209 | | } |
| | | 210 | | |
| | | 211 | | public async Task<WorldDocumentDto> UpdateDocumentAsync( |
| | | 212 | | Guid worldId, |
| | | 213 | | Guid documentId, |
| | | 214 | | Guid userId, |
| | | 215 | | WorldDocumentUpdateDto update) |
| | | 216 | | { |
| | 0 | 217 | | _logger.LogDebug("User {UserId} updating document {DocumentId}", |
| | 0 | 218 | | userId, documentId); |
| | | 219 | | |
| | 0 | 220 | | var document = await _db.WorldDocuments |
| | 0 | 221 | | .Include(d => d.World) |
| | 0 | 222 | | .FirstOrDefaultAsync(d => d.Id == documentId && d.WorldId == worldId); |
| | | 223 | | |
| | 0 | 224 | | if (document == null) |
| | | 225 | | { |
| | 0 | 226 | | throw new InvalidOperationException("Document not found"); |
| | | 227 | | } |
| | | 228 | | |
| | | 229 | | // Only owner can update |
| | 0 | 230 | | if (document.World.OwnerId != userId) |
| | | 231 | | { |
| | 0 | 232 | | throw new UnauthorizedAccessException("Only world owner can update documents"); |
| | | 233 | | } |
| | | 234 | | |
| | | 235 | | // Update metadata |
| | 0 | 236 | | if (!string.IsNullOrWhiteSpace(update.Title)) |
| | | 237 | | { |
| | 0 | 238 | | document.Title = update.Title.Trim(); |
| | | 239 | | } |
| | | 240 | | |
| | 0 | 241 | | document.Description = string.IsNullOrWhiteSpace(update.Description) |
| | 0 | 242 | | ? null |
| | 0 | 243 | | : update.Description.Trim(); |
| | | 244 | | |
| | 0 | 245 | | await _db.SaveChangesAsync(); |
| | | 246 | | |
| | 0 | 247 | | _logger.LogDebug("Updated document {DocumentId}", documentId); |
| | | 248 | | |
| | 0 | 249 | | return MapToDto(document); |
| | 0 | 250 | | } |
| | | 251 | | |
| | | 252 | | public async Task DeleteDocumentAsync(Guid worldId, Guid documentId, Guid userId) |
| | | 253 | | { |
| | 0 | 254 | | _logger.LogDebug("User {UserId} deleting document {DocumentId}", |
| | 0 | 255 | | userId, documentId); |
| | | 256 | | |
| | 0 | 257 | | var document = await _db.WorldDocuments |
| | 0 | 258 | | .Include(d => d.World) |
| | 0 | 259 | | .FirstOrDefaultAsync(d => d.Id == documentId && d.WorldId == worldId); |
| | | 260 | | |
| | 0 | 261 | | if (document == null) |
| | | 262 | | { |
| | 0 | 263 | | throw new InvalidOperationException("Document not found"); |
| | | 264 | | } |
| | | 265 | | |
| | | 266 | | // Only owner can delete |
| | 0 | 267 | | if (document.World.OwnerId != userId) |
| | | 268 | | { |
| | 0 | 269 | | throw new UnauthorizedAccessException("Only world owner can delete documents"); |
| | | 270 | | } |
| | | 271 | | |
| | | 272 | | // Delete blob from storage |
| | | 273 | | try |
| | | 274 | | { |
| | 0 | 275 | | await _blobStorage.DeleteBlobAsync(document.BlobPath); |
| | 0 | 276 | | } |
| | 0 | 277 | | catch (Exception ex) |
| | | 278 | | { |
| | 0 | 279 | | _logger.LogErrorSanitized(ex, "Failed to delete blob for document {DocumentId}: {BlobPath}", |
| | 0 | 280 | | documentId, document.BlobPath); |
| | | 281 | | // Continue with database deletion even if blob deletion fails |
| | 0 | 282 | | } |
| | | 283 | | |
| | | 284 | | // Delete from database |
| | 0 | 285 | | _db.WorldDocuments.Remove(document); |
| | 0 | 286 | | await _db.SaveChangesAsync(); |
| | | 287 | | |
| | 0 | 288 | | _logger.LogDebug("Deleted document {DocumentId}", documentId); |
| | 0 | 289 | | } |
| | | 290 | | |
| | | 291 | | /// <inheritdoc /> |
| | | 292 | | public async Task DeleteArticleImagesAsync(Guid articleId) |
| | | 293 | | { |
| | 0 | 294 | | var documents = await _db.WorldDocuments |
| | 0 | 295 | | .Where(d => d.ArticleId == articleId) |
| | 0 | 296 | | .ToListAsync(); |
| | | 297 | | |
| | 0 | 298 | | if (documents.Count == 0) |
| | 0 | 299 | | return; |
| | | 300 | | |
| | 0 | 301 | | _logger.LogDebug("Deleting {Count} images for article {ArticleId}", documents.Count, articleId); |
| | | 302 | | |
| | 0 | 303 | | foreach (var document in documents) |
| | | 304 | | { |
| | | 305 | | try |
| | | 306 | | { |
| | 0 | 307 | | await _blobStorage.DeleteBlobAsync(document.BlobPath); |
| | 0 | 308 | | } |
| | 0 | 309 | | catch (Exception ex) |
| | | 310 | | { |
| | 0 | 311 | | _logger.LogWarning(ex, "Failed to delete blob {BlobPath} for document {DocumentId}", |
| | 0 | 312 | | document.BlobPath, document.Id); |
| | 0 | 313 | | } |
| | 0 | 314 | | } |
| | | 315 | | |
| | 0 | 316 | | _db.WorldDocuments.RemoveRange(documents); |
| | 0 | 317 | | await _db.SaveChangesAsync(); |
| | | 318 | | |
| | 0 | 319 | | _logger.LogDebug("Deleted {Count} images for article {ArticleId}", documents.Count, articleId); |
| | 0 | 320 | | } |
| | | 321 | | |
| | | 322 | | // ===== Private Helper Methods ===== |
| | | 323 | | |
| | | 324 | | private void ValidateFileUpload(WorldDocumentUploadRequestDto request) |
| | | 325 | | { |
| | | 326 | | // Validate file size |
| | 0 | 327 | | if (request.FileSizeBytes <= 0) |
| | | 328 | | { |
| | 0 | 329 | | throw new ArgumentException("File size must be greater than zero"); |
| | | 330 | | } |
| | | 331 | | |
| | 0 | 332 | | if (request.FileSizeBytes > MaxFileSizeBytes) |
| | | 333 | | { |
| | 0 | 334 | | throw new ArgumentException($"File size exceeds maximum allowed size of {MaxFileSizeBytes / 1024 / 1024} MB" |
| | | 335 | | } |
| | | 336 | | |
| | | 337 | | // Validate filename |
| | 0 | 338 | | if (string.IsNullOrWhiteSpace(request.FileName)) |
| | | 339 | | { |
| | 0 | 340 | | throw new ArgumentException("Filename is required"); |
| | | 341 | | } |
| | | 342 | | |
| | 0 | 343 | | var extension = Path.GetExtension(request.FileName); |
| | 0 | 344 | | if (string.IsNullOrEmpty(extension) || !AllowedExtensions.Contains(extension)) |
| | | 345 | | { |
| | 0 | 346 | | var allowed = string.Join(", ", AllowedExtensions); |
| | 0 | 347 | | throw new ArgumentException($"File type '{extension}' is not allowed. Allowed types: {allowed}"); |
| | | 348 | | } |
| | | 349 | | |
| | | 350 | | // Validate content type matches extension |
| | 0 | 351 | | if (!string.IsNullOrWhiteSpace(request.ContentType)) |
| | | 352 | | { |
| | 0 | 353 | | if (ExtensionToMimeType.TryGetValue(extension, out var expectedMimeType)) |
| | | 354 | | { |
| | 0 | 355 | | if (!request.ContentType.Equals(expectedMimeType, StringComparison.OrdinalIgnoreCase)) |
| | | 356 | | { |
| | 0 | 357 | | _logger.LogWarningSanitized("Content type mismatch for {FileName}: expected {Expected}, got {Actual} |
| | 0 | 358 | | request.FileName, expectedMimeType, request.ContentType); |
| | | 359 | | } |
| | | 360 | | } |
| | | 361 | | } |
| | 0 | 362 | | } |
| | | 363 | | |
| | | 364 | | private async Task<string> GenerateUniqueTitleAsync(Guid worldId, string fileName) |
| | | 365 | | { |
| | | 366 | | // Start with filename without extension as title |
| | 0 | 367 | | var baseTitle = Path.GetFileNameWithoutExtension(fileName); |
| | 0 | 368 | | var extension = Path.GetExtension(fileName); |
| | 0 | 369 | | var title = baseTitle; |
| | | 370 | | |
| | | 371 | | // Check for existing documents with same title |
| | 0 | 372 | | var existingTitles = await _db.WorldDocuments |
| | 0 | 373 | | .AsNoTracking() |
| | 0 | 374 | | .Where(d => d.WorldId == worldId && d.Title.StartsWith(baseTitle)) |
| | 0 | 375 | | .Select(d => d.Title) |
| | 0 | 376 | | .ToListAsync(); |
| | | 377 | | |
| | 0 | 378 | | if (!existingTitles.Contains(title)) |
| | | 379 | | { |
| | 0 | 380 | | return title; // Title is unique, use as-is |
| | | 381 | | } |
| | | 382 | | |
| | | 383 | | // Title exists, find next available number |
| | 0 | 384 | | var counter = 2; |
| | 0 | 385 | | while (existingTitles.Contains(title)) |
| | | 386 | | { |
| | 0 | 387 | | title = $"{baseTitle} ({counter})"; |
| | 0 | 388 | | counter++; |
| | | 389 | | |
| | | 390 | | // Safety check to prevent infinite loop |
| | 0 | 391 | | if (counter > 1000) |
| | | 392 | | { |
| | 0 | 393 | | throw new InvalidOperationException("Too many documents with similar names"); |
| | | 394 | | } |
| | | 395 | | } |
| | | 396 | | |
| | 0 | 397 | | _logger.LogDebugSanitized("Generated unique title for {FileName}: {Title}", fileName, title); |
| | 0 | 398 | | return title; |
| | 0 | 399 | | } |
| | | 400 | | |
| | | 401 | | private static WorldDocumentDto MapToDto(WorldDocument document) |
| | | 402 | | { |
| | 0 | 403 | | return new WorldDocumentDto |
| | 0 | 404 | | { |
| | 0 | 405 | | Id = document.Id, |
| | 0 | 406 | | WorldId = document.WorldId, |
| | 0 | 407 | | ArticleId = document.ArticleId, |
| | 0 | 408 | | FileName = document.FileName, |
| | 0 | 409 | | Title = document.Title, |
| | 0 | 410 | | ContentType = document.ContentType, |
| | 0 | 411 | | FileSizeBytes = document.FileSizeBytes, |
| | 0 | 412 | | Description = document.Description, |
| | 0 | 413 | | UploadedAt = document.UploadedAt, |
| | 0 | 414 | | UploadedById = document.UploadedById |
| | 0 | 415 | | }; |
| | | 416 | | } |
| | | 417 | | |
| | | 418 | | private async Task<WorldDocument> GetAuthorizedDocumentAsync( |
| | | 419 | | Guid documentId, |
| | | 420 | | Guid userId, |
| | | 421 | | Guid? worldId = null) |
| | | 422 | | { |
| | 0 | 423 | | var query = _db.WorldDocuments |
| | 0 | 424 | | .Include(d => d.World) |
| | 0 | 425 | | .AsQueryable(); |
| | | 426 | | |
| | 0 | 427 | | if (worldId.HasValue) |
| | | 428 | | { |
| | 0 | 429 | | query = query.Where(d => d.WorldId == worldId.Value); |
| | | 430 | | } |
| | | 431 | | |
| | 0 | 432 | | var document = await query.FirstOrDefaultAsync(d => d.Id == documentId); |
| | | 433 | | |
| | 0 | 434 | | if (document == null) |
| | | 435 | | { |
| | 0 | 436 | | throw new InvalidOperationException("Document not found"); |
| | | 437 | | } |
| | | 438 | | |
| | 0 | 439 | | var hasAccess = document.World.OwnerId == userId || |
| | 0 | 440 | | await _db.WorldMembers.AnyAsync(m => m.WorldId == document.WorldId && m.UserId == userId); |
| | | 441 | | |
| | 0 | 442 | | if (!hasAccess) |
| | | 443 | | { |
| | 0 | 444 | | throw new UnauthorizedAccessException("Access denied"); |
| | | 445 | | } |
| | | 446 | | |
| | 0 | 447 | | return document; |
| | 0 | 448 | | } |
| | | 449 | | } |