2026-05-22 14:29:22 +08:00
|
|
|
|
using FileShare_EFCore.Database;
|
|
|
|
|
|
using FileShare_EFCore.Models;
|
|
|
|
|
|
using FileShare_Services.Core;
|
2026-05-22 11:18:47 +08:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
|
|
2026-05-22 14:29:22 +08:00
|
|
|
|
namespace FileShare_Services.Services.FileLibrary
|
2026-05-22 11:18:47 +08:00
|
|
|
|
{
|
2026-05-22 14:45:07 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 文件流服务接口,根据文件记录 ID 返回物理文件流信息。
|
|
|
|
|
|
/// </summary>
|
2026-05-22 11:18:47 +08:00
|
|
|
|
public interface IFileStreamService
|
|
|
|
|
|
{
|
2026-05-22 14:45:07 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 获取指定文件的流式传输响应,包含文件路径、名称、Content-Type 和修改时间。
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="id">文件记录 ID。</param>
|
|
|
|
|
|
/// <param name="cancellationToken">取消令牌。</param>
|
|
|
|
|
|
/// <returns>文件流响应,文件不存在时返回 null。</returns>
|
2026-05-22 11:18:47 +08:00
|
|
|
|
Task<FileStreamResponse?> GetFileStreamAsync(int id, CancellationToken cancellationToken = default);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-22 14:45:07 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 文件流服务实现,从数据库查询文件记录并构建 <see cref="FileStreamResponse"/>。
|
|
|
|
|
|
/// </summary>
|
2026-05-22 11:18:47 +08:00
|
|
|
|
public sealed class FileStreamService(AppDataContext db) : IFileStreamService
|
|
|
|
|
|
{
|
2026-05-22 14:45:07 +08:00
|
|
|
|
/// <inheritdoc />
|
2026-05-22 11:18:47 +08:00
|
|
|
|
public async Task<FileStreamResponse?> GetFileStreamAsync(int id, CancellationToken cancellationToken = default)
|
|
|
|
|
|
{
|
|
|
|
|
|
var file = await db.ManagedFileRecords
|
|
|
|
|
|
.AsNoTracking()
|
|
|
|
|
|
.Include(item => item.LibraryRoot)
|
|
|
|
|
|
.FirstOrDefaultAsync(item =>
|
|
|
|
|
|
item.Id == id
|
|
|
|
|
|
&& item.Exists
|
|
|
|
|
|
&& item.LibraryRoot != null
|
|
|
|
|
|
&& item.LibraryRoot.IsAvailable,
|
|
|
|
|
|
cancellationToken);
|
|
|
|
|
|
|
|
|
|
|
|
if (file is null || !System.IO.File.Exists(file.AbsolutePath))
|
|
|
|
|
|
return null;
|
|
|
|
|
|
|
|
|
|
|
|
return new FileStreamResponse(
|
|
|
|
|
|
file.AbsolutePath,
|
|
|
|
|
|
file.FileName,
|
|
|
|
|
|
file.ContentType,
|
|
|
|
|
|
file.LastWriteTimeUtc);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|