< Summary

Information
Class: Anichron.Core.Data.Repository.EfMediaAssetRepository
Assembly: Anichron.Core
File(s): /home/runner/work/anichron/anichron/src/Anichron.Core/Data/Repository/MediaAssetRepository.cs
Tag: 19_45211875487
Line coverage
84%
Covered lines: 55
Uncovered lines: 10
Coverable lines: 65
Total lines: 198
Line coverage: 84.6%
Branch coverage
50%
Covered branches: 2
Total branches: 4
Branch coverage: 50%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

File(s)

/home/runner/work/anichron/anichron/src/Anichron.Core/Data/Repository/MediaAssetRepository.cs

#LineLine coverage
 1using Anichron.Core.Domain;
 2using Microsoft.EntityFrameworkCore;
 3
 4namespace Anichron.Core.Data.Repository;
 5
 6public sealed record ContentLocation(Guid UserId, string ContentHash, Guid StorageConfigId, string FilePath);
 7
 8/// <summary>An active row's path, with what the missing-file sweep needs to soft-delete a Live Photo as one.</summary>
 9/// <param name="Id">The row.</param>
 10/// <param name="FilePath">Its path, relative to the config's root.</param>
 11/// <param name="PairedAssetId">The video the row points at, when it is a Live Photo's photo.</param>
 12public sealed record AssetPath(Guid Id, string FilePath, Guid? PairedAssetId = null);
 13
 14public interface IMediaAssetRepository
 15{
 16    Task<MediaAsset?> FindByHashAsync(string contentHash, Guid storageConfigId, CancellationToken ct);
 17
 18    /// <summary>The config's rows that match, tracked, each with its proxy rows.</summary>
 19    /// <param name="storageConfigId">The config whose rows are searched.</param>
 20    /// <param name="contentHashes">Matches active and soft-deleted rows.</param>
 21    /// <param name="filePaths">Matches active and soft-deleted rows, as the unique path index does.</param>
 22    /// <param name="ct">Cancels the query.</param>
 23    Task<IReadOnlyList<MediaAsset>> FindByHashesOrPathsAsync(
 24        Guid storageConfigId,
 25        IReadOnlyCollection<string> contentHashes,
 26        IReadOnlyCollection<string> filePaths,
 27        CancellationToken ct);
 28
 29    /// <summary>Active rows whose content is also stored in another of the same user's configs.</summary>
 30    /// <param name="storageConfigIds">Only rows in these configs are compared.</param>
 31    /// <param name="ct">Cancels the query.</param>
 32    Task<IReadOnlyList<ContentLocation>> FindSharedContentAsync(IReadOnlyCollection<Guid> storageConfigIds, Cancellation
 33
 34    Task<IReadOnlyList<AssetPath>> GetActivePathsAsync(Guid storageConfigId, CancellationToken ct);
 35
 36    /// <summary>The tracked row with the id, else the active stored one.</summary>
 37    /// <param name="id">The row.</param>
 38    /// <param name="ct">Cancels the query.</param>
 39    /// <returns>The row, tracked; null when it is neither tracked nor active.</returns>
 40    Task<MediaAsset?> FindAsync(Guid id, CancellationToken ct);
 41
 42    /// <summary>The stored rows, active or soft-deleted, that point at the video.</summary>
 43    /// <param name="videoId">The video.</param>
 44    /// <param name="ct">Cancels the query.</param>
 45    /// <returns>The rows, tracked: a row already tracked comes back as that instance, with its current values.</returns
 46    Task<IReadOnlyList<MediaAsset>> FindPhotosOfAsync(Guid videoId, CancellationToken ct);
 47
 48    /// <summary>Soft-deletes the rows among <paramref name="ids"/> that are still active.</summary>
 49    /// <param name="ids">The rows to soft-delete.</param>
 50    /// <param name="ct">Cancels the update.</param>
 51    /// <returns>The number of rows soft-deleted.</returns>
 52    Task<int> SoftDeleteAsync(IReadOnlyCollection<Guid> ids, CancellationToken ct);
 53
 54    /// <summary>Loads the asset's metadata row, even when the asset is soft-deleted.</summary>
 55    /// <param name="asset">A tracked asset.</param>
 56    /// <param name="ct">Cancels the query.</param>
 57    Task LoadMetadataAsync(MediaAsset asset, CancellationToken ct);
 58
 59    /// <summary>
 60    /// The config's active assets with a <see cref="ProxyType.FullPreview"/> but no
 61    /// <see cref="ProxyType.CompactPreview"/>, tracked with their proxy rows, by id.
 62    /// </summary>
 63    /// <param name="storageConfigId">The config whose assets are loaded.</param>
 64    /// <param name="after">Only assets whose id comes after this one; null starts at the first.</param>
 65    /// <param name="count">At most this many.</param>
 66    /// <param name="ct">Cancels the query.</param>
 67    Task<IReadOnlyList<MediaAsset>> GetWithoutCompactPreviewAsync(Guid storageConfigId, Guid? after, int count, Cancella
 68
 69    /// <summary>How many assets <see cref="GetWithoutCompactPreviewAsync"/> would find with no limit.</summary>
 70    /// <param name="storageConfigId">The config whose assets are counted.</param>
 71    /// <param name="after">Only assets whose id comes after this one; null counts from the first.</param>
 72    /// <param name="ct">Cancels the query.</param>
 73    Task<int> CountWithoutCompactPreviewAsync(Guid storageConfigId, Guid? after, CancellationToken ct);
 74
 75    void Add(MediaAsset asset);
 76    void AddProxyFiles(IEnumerable<ProxyFile> proxyFiles);
 77    void RemoveProxyFile(ProxyFile proxyFile);
 78}
 79
 4480public sealed class EfMediaAssetRepository(AnichronDbContext db) : IMediaAssetRepository
 81{
 82    public Task<MediaAsset?> FindByHashAsync(string contentHash, Guid storageConfigId, CancellationToken ct)
 583        => ActiveByHashQuery(db, contentHash, storageConfigId).FirstOrDefaultAsync(ct);
 84
 85    internal static IQueryable<MediaAsset> ActiveByHashQuery(AnichronDbContext db, string contentHash, Guid storageConfi
 686        => db.MediaAssets
 687            .IgnoreQueryFilters()
 688            .Where(a => a.ContentHash == contentHash && a.StorageConfigId == storageConfigId && !a.IsSoftDeleted);
 89
 90    public async Task<IReadOnlyList<MediaAsset>> FindByHashesOrPathsAsync(
 91        Guid storageConfigId,
 92        IReadOnlyCollection<string> contentHashes,
 93        IReadOnlyCollection<string> filePaths,
 94        CancellationToken ct)
 895        => await HashesOrPathsQuery(db, storageConfigId, contentHashes, filePaths).ToListAsync(ct);
 96
 97    internal static IQueryable<MediaAsset> HashesOrPathsQuery(
 98        AnichronDbContext db,
 99        Guid storageConfigId,
 100        IReadOnlyCollection<string> contentHashes,
 101        IReadOnlyCollection<string> filePaths)
 10102        => db.MediaAssets
 10103            .IgnoreQueryFilters()
 10104            .Include(a => a.ProxyFiles)
 10105            .Where(a => a.StorageConfigId == storageConfigId
 10106                && ((!a.IsSoftDeleted && contentHashes.Contains(a.ContentHash))
 10107                    || (a.IsSoftDeleted && contentHashes.Contains(a.ContentHash))
 10108                    || filePaths.Contains(a.FilePath)));
 109
 110    public async Task<IReadOnlyList<ContentLocation>> FindSharedContentAsync(
 111        IReadOnlyCollection<Guid> storageConfigIds, CancellationToken ct)
 4112        => await SharedContentQuery(db, storageConfigIds).ToListAsync(ct);
 113
 114    internal static IQueryable<ContentLocation> SharedContentQuery(
 115        AnichronDbContext db, IReadOnlyCollection<Guid> storageConfigIds)
 5116    {
 5117        var inScope = db.MediaAssets
 5118            .IgnoreQueryFilters()
 5119            .Where(a => storageConfigIds.Contains(a.StorageConfigId) && !a.IsSoftDeleted);
 5120        var shared = inScope
 5121            .GroupBy(a => new { a.StorageConfig.UserId, a.ContentHash })
 5122            .Where(g => g.Count() > 1)
 5123            .Select(g => g.Key);
 5124        return inScope
 5125            .Where(a => shared.Any(k => k.UserId == a.StorageConfig.UserId && k.ContentHash == a.ContentHash))
 5126            .Select(a => new ContentLocation(a.StorageConfig.UserId, a.ContentHash, a.StorageConfigId, a.FilePath));
 5127    }
 128
 129    public async Task<IReadOnlyList<AssetPath>> GetActivePathsAsync(Guid storageConfigId, CancellationToken ct)
 2130        => await ActivePathsQuery(db, storageConfigId).ToListAsync(ct);
 131
 132    internal static IQueryable<AssetPath> ActivePathsQuery(AnichronDbContext db, Guid storageConfigId)
 3133        => db.MediaAssets
 3134            .AsNoTracking()
 3135            .IgnoreQueryFilters()
 3136            .Where(a => a.StorageConfigId == storageConfigId && !a.IsSoftDeleted)
 3137            .Select(a => new AssetPath(a.Id, a.FilePath, a.PairedAssetId));
 138
 139    public async Task<MediaAsset?> FindAsync(Guid id, CancellationToken ct)
 3140        => await db.MediaAssets.FindAsync([id], ct);
 141
 142    public async Task<IReadOnlyList<MediaAsset>> FindPhotosOfAsync(Guid videoId, CancellationToken ct)
 2143        => await db.MediaAssets.IgnoreQueryFilters().Where(a => a.PairedAssetId == videoId).ToListAsync(ct);
 144
 145    public Task LoadMetadataAsync(MediaAsset asset, CancellationToken ct)
 3146        => db.Entry(asset).Reference(a => a.Metadata).Query().IgnoreQueryFilters().LoadAsync(ct);
 147
 148    public async Task<IReadOnlyList<MediaAsset>> GetWithoutCompactPreviewAsync(
 149        Guid storageConfigId, Guid? after, int count, CancellationToken ct)
 12150        => await WithoutCompactPreviewQuery(db, storageConfigId, after)
 12151            .Include(a => a.ProxyFiles)
 12152            .OrderBy(a => a.Id)
 12153            .Take(count)
 12154            .ToListAsync(ct);
 155
 156    public Task<int> CountWithoutCompactPreviewAsync(Guid storageConfigId, Guid? after, CancellationToken ct)
 11157        => WithoutCompactPreviewQuery(db, storageConfigId, after).CountAsync(ct);
 158
 159    internal static IQueryable<MediaAsset> WithoutCompactPreviewQuery(AnichronDbContext db, Guid storageConfigId, Guid? 
 24160    {
 24161        var pending = db.MediaAssets
 24162            .IgnoreQueryFilters()
 24163            .Where(a => a.StorageConfigId == storageConfigId && !a.IsSoftDeleted
 24164                && a.ProxyFiles.Any(p => p.ProxyType == ProxyType.FullPreview)
 24165                && !a.ProxyFiles.Any(p => p.ProxyType == ProxyType.CompactPreview));
 24166        return after is { } id ? pending.Where(a => a.Id.CompareTo(id) > 0) : pending;
 24167    }
 168
 169    public void Add(MediaAsset asset)
 1170        => db.MediaAssets.Add(asset);
 171
 172    public void AddProxyFiles(IEnumerable<ProxyFile> proxyFiles)
 10173        => db.ProxyFiles.AddRange(proxyFiles);
 174
 175    public void RemoveProxyFile(ProxyFile proxyFile)
 1176        => db.ProxyFiles.Remove(proxyFile);
 177
 178    public Task<int> SoftDeleteAsync(IReadOnlyCollection<Guid> ids, CancellationToken ct)
 0179        => SoftDeleteAsync(ids, batchSize: 1000, ct);
 180
 181    internal static IQueryable<MediaAsset> StillActiveQuery(AnichronDbContext db, IReadOnlyCollection<Guid> ids)
 1182        => db.MediaAssets
 1183            .IgnoreQueryFilters()
 1184            .Where(a => ids.Contains(a.Id) && !a.IsSoftDeleted);
 185
 186    // Stryker disable all
 187    internal async Task<int> SoftDeleteAsync(IReadOnlyCollection<Guid> ids, int batchSize, CancellationToken ct)
 0188    {
 0189        var softDeleted = 0;
 0190        foreach (var batch in ids.Chunk(batchSize))
 0191        {
 0192            softDeleted += await StillActiveQuery(db, batch)
 0193                .ExecuteUpdateAsync(set => set.SetProperty(a => a.IsSoftDeleted, true), ct);
 0194        }
 195
 0196        return softDeleted;
 0197    }
 198}