using FileShare_EFCore.Database;
using FileShare_EFCore.Models;
using FileShare_Services.Core;
using Microsoft.EntityFrameworkCore;
namespace FileShare_Services.Services.FileLibrary
{
///
/// 文件流服务接口,根据文件记录 ID 返回物理文件流信息。
///
public interface IFileStreamService
{
///
/// 获取指定文件的流式传输响应,包含文件路径、名称、Content-Type 和修改时间。
///
/// 文件记录 ID。
/// 取消令牌。
/// 文件流响应,文件不存在时返回 null。
Task GetFileStreamAsync(int id, CancellationToken cancellationToken = default);
}
///
/// 文件流服务实现,从数据库查询文件记录并构建 。
///
public sealed class FileStreamService(AppDataContext db) : IFileStreamService
{
///
public async Task 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);
}
}
}