feat(media): content-hash dedup for uploads + media-library endpoint

Uploads previously wrote every file to disk with a fresh GUID name, so the
same image uploaded twice produced two identical files. Now:

- New MediaAsset table records each stored upload (SHA-256 hash, size, type,
  url, kind, scope) + migration. Indexed on (CafeId, ContentHash).
- MediaStorageService computes the content hash on upload; if an identical file
  already exists for that café it returns the existing URL instead of writing a
  duplicate (covers images, videos, 3D models). Dedup lookup/record run via a
  scoped DbContext (the service is a singleton) and never block an upload on
  failure.
- GET /api/cafes/{cafeId}/media lists the café's library (newest first, optional
  ?kind=) so the UI can let users pick an existing file instead of re-uploading.

86 API tests pass.
This commit is contained in:
soroush.asadi
2026-06-02 22:16:11 +03:30
parent eb165db182
commit 97a9481627
7 changed files with 3686 additions and 7 deletions
@@ -1,7 +1,9 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Meezi.API.Services;
using Meezi.Core.Enums;
using Meezi.Core.Interfaces;
using Meezi.Infrastructure.Data;
using Meezi.Infrastructure.Services.Platform;
using Meezi.Shared;
@@ -81,6 +83,33 @@ public class MediaController : CafeApiControllerBase
string cafeId, IFormFile file, ITenantContext tenant, CancellationToken cancellationToken)
=> Upload(cafeId, file, tenant, _media.SaveCafeCoverAsync, "INVALID_FILE", "Use JPEG/PNG/WebP up to 5MB.", cancellationToken);
/// <summary>Media library for this café — previously uploaded files so the UI can
/// reuse one instead of re-uploading. Deduplication means each distinct file appears once.</summary>
[HttpGet]
public async Task<IActionResult> ListMedia(
string cafeId,
ITenantContext tenant,
[FromServices] AppDbContext db,
CancellationToken cancellationToken,
[FromQuery] string? kind = null,
[FromQuery] int limit = 60)
{
if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
var query = db.MediaAssets.AsNoTracking().Where(m => m.CafeId == cafeId);
if (!string.IsNullOrWhiteSpace(kind))
query = query.Where(m => m.Kind == kind);
var items = await query
.OrderByDescending(m => m.CreatedAt)
.Take(Math.Clamp(limit, 1, 200))
.Select(m => new MediaAssetDto(
m.Id, m.Url, m.Kind, m.ContentType, m.SizeBytes, m.OriginalFileName, m.CreatedAt))
.ToListAsync(cancellationToken);
return Ok(new ApiResponse<List<MediaAssetDto>>(true, items));
}
private async Task<IActionResult> Upload(
string cafeId,
IFormFile file,
@@ -103,3 +132,12 @@ public class MediaController : CafeApiControllerBase
}
public record UploadResultDto(string Url);
public record MediaAssetDto(
string Id,
string Url,
string Kind,
string ContentType,
long SizeBytes,
string? OriginalFileName,
DateTime CreatedAt);