feat: 新增文件库功能,支持局域网文件浏览与媒体播放
后端: - 新增 ManagedLibraryRoot / ManagedFileRecord 数据模型及 SQLite 迁移 - 新增文件库服务、端点服务及定时扫描后台任务 - 新增 REST API: drives、directories、roots CRUD、files 分页搜索、文本预览 - 新增文件流端点支持视频/音频流式传输 - 数据库切换为 SQLite,Kestrel 绑定 0.0.0.0 支持局域网访问 前端: - 管理端:磁盘浏览、目录选择、根目录添加/启用/删除/扫描 - 客户端:根目录选择、文件搜索/筛选/分页、音视频播放、文本预览 - 全新响应式 UI(桌面+移动端),CSS 变量设计系统 - HTTP 客户端支持 Vite 开发代理与生产同源自动切换 - 移除 HTTPS 强制重定向以提升移动端视频流兼容性
This commit is contained in:
@@ -28,4 +28,23 @@
|
||||
<Folder Include="Controllers\" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="RestoreFrontendPackages" BeforeTargets="Build" Condition="'$(SkipFrontendBuild)' != 'true' And Exists('..\Avalonia-Web-VUE\package.json') And !Exists('..\Avalonia-Web-VUE\node_modules')">
|
||||
<Message Importance="high" Text="Restoring Avalonia-Web-VUE npm packages..." />
|
||||
<Exec WorkingDirectory="..\Avalonia-Web-VUE" Command="npm.cmd install" />
|
||||
</Target>
|
||||
|
||||
<Target Name="BuildFrontend" BeforeTargets="Build" DependsOnTargets="RestoreFrontendPackages" Condition="'$(SkipFrontendBuild)' != 'true' And Exists('..\Avalonia-Web-VUE\package.json')">
|
||||
<Message Importance="high" Text="Building Avalonia-Web-VUE into Avalonia-API/wwwroot..." />
|
||||
<Exec WorkingDirectory="..\Avalonia-Web-VUE" Command="npm.cmd run build-only" />
|
||||
<RemoveDir Directories="wwwroot" />
|
||||
<MakeDir Directories="wwwroot" />
|
||||
<ItemGroup>
|
||||
<FrontendDist Include="..\Avalonia-Web-VUE\dist\**\*.*" />
|
||||
</ItemGroup>
|
||||
<Copy
|
||||
SourceFiles="@(FrontendDist)"
|
||||
DestinationFiles="@(FrontendDist->'wwwroot\%(RecursiveDir)%(Filename)%(Extension)')"
|
||||
SkipUnchangedFiles="false" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
using Avalonia_API.Authentication;
|
||||
using Avalonia_API.Services;
|
||||
using Avalonia_EFCore.Database;
|
||||
using Avalonia_Services.Core;
|
||||
using Avalonia_Services.Endpoints;
|
||||
using Avalonia_Services.Services;
|
||||
using Avalonia_Services.Services.AuthService;
|
||||
using Avalonia_Services.Services.FileLibrary;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
@@ -36,6 +39,11 @@ namespace Avalonia_API.Configuration
|
||||
|
||||
// ---- 业务服务 ----
|
||||
services.AddScoped<WeatherForecastService>();
|
||||
services.AddScoped<IFileLibraryService, FileLibraryService>();
|
||||
services.AddScoped<IFileLibraryEndpointService, FileLibraryEndpointService>();
|
||||
services.AddHostedService<FileLibraryScanHostedService>();
|
||||
services.AddDataProtection()
|
||||
.PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, "data-protection-keys")));
|
||||
|
||||
// ---- API 鉴权 ----
|
||||
var jwtSection = configuration.GetSection("Jwt");
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
using Avalonia_EFCore.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Avalonia_API.Extensions
|
||||
{
|
||||
public static class FileStreamEndpointExtensions
|
||||
{
|
||||
public static IEndpointRouteBuilder MapFileStreamEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapMethods("/api/files/{id:int}/stream", ["GET", "HEAD"], async (int id, AppDataContext db, HttpContext httpContext) =>
|
||||
{
|
||||
// Browsers cancel in-flight range requests aggressively while seeking.
|
||||
// Keep this small metadata lookup independent from RequestAborted so
|
||||
// EF does not throw TaskCanceledException before the file is opened.
|
||||
var file = await db.ManagedFileRecords
|
||||
.AsNoTracking()
|
||||
.Include(item => item.LibraryRoot)
|
||||
.FirstOrDefaultAsync(item =>
|
||||
item.Id == id
|
||||
&& item.Exists
|
||||
&& item.LibraryRoot != null
|
||||
&& item.LibraryRoot.IsAvailable);
|
||||
|
||||
if (file is null || !System.IO.File.Exists(file.AbsolutePath))
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
var stream = System.IO.File.Open(file.AbsolutePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
httpContext.Response.Headers.ContentDisposition = $"inline; filename=\"{Uri.EscapeDataString(file.FileName)}\"";
|
||||
httpContext.Response.Headers.AcceptRanges = "bytes";
|
||||
httpContext.Response.Headers.CacheControl = "public, max-age=3600";
|
||||
|
||||
return Results.File(
|
||||
stream,
|
||||
contentType: file.ContentType,
|
||||
fileDownloadName: null,
|
||||
lastModified: file.LastWriteTimeUtc,
|
||||
enableRangeProcessing: true);
|
||||
})
|
||||
.WithName("StreamManagedFile")
|
||||
.WithTags("FileLibrary");
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,9 +131,11 @@ namespace Avalonia_API.Extensions
|
||||
{
|
||||
return async (HttpContext httpContext) =>
|
||||
{
|
||||
var ctx = await BuildContextFromHttpContext(httpContext);
|
||||
var ctx = httpContext.Items["UnifiedContext"] as ServiceEndpointContext
|
||||
?? await BuildContextFromHttpContext(httpContext);
|
||||
ctx.Items["ServiceProvider"] = serviceProvider;
|
||||
ctx.Items["User"] = httpContext.User;
|
||||
httpContext.Items["UnifiedContext"] = ctx;
|
||||
|
||||
var result = await unifiedHandler(ctx);
|
||||
|
||||
@@ -204,6 +206,7 @@ namespace Avalonia_API.Extensions
|
||||
|
||||
httpContext.Items["UnifiedContext"] = ctx;
|
||||
|
||||
object? nextResult = null;
|
||||
await unifiedFilter.InvokeAsync(ctx, async (c) =>
|
||||
{
|
||||
httpContext.Response.StatusCode = c.StatusCode;
|
||||
@@ -211,7 +214,7 @@ namespace Avalonia_API.Extensions
|
||||
{
|
||||
httpContext.Response.Headers[kvp.Key] = kvp.Value;
|
||||
}
|
||||
await aspNext(aspContext);
|
||||
nextResult = await aspNext(aspContext);
|
||||
});
|
||||
|
||||
if (ctx.ResponseBody is not null)
|
||||
@@ -219,7 +222,7 @@ namespace Avalonia_API.Extensions
|
||||
return Results.Json(ctx.ResponseBody, statusCode: ctx.StatusCode);
|
||||
}
|
||||
|
||||
return null!;
|
||||
return nextResult;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+16
-1
@@ -13,12 +13,22 @@ try
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// 配置 Kestrel 监听所有本机 IP
|
||||
builder.WebHost.UseUrls("http://0.0.0.0:5206", "https://0.0.0.0:7165");
|
||||
|
||||
// 使用 Serilog 作为日志提供程序
|
||||
builder.Host.UseSerilog();
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddOpenApi();
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("LanFileViewer", policy =>
|
||||
policy.AllowAnyOrigin()
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod());
|
||||
});
|
||||
|
||||
// 注册统一端点及业务服务(入口在 Avalonia-Services/Endpoints/AppEndpoints.cs)
|
||||
builder.Services.AddUnifiedApiServices(builder.Configuration);
|
||||
@@ -41,12 +51,17 @@ try
|
||||
});
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseDefaultFiles();
|
||||
app.UseStaticFiles();
|
||||
// 局域网文件播放优先使用 HTTP,避免手机浏览器对自签 HTTPS/HTTP2 视频流的兼容问题。
|
||||
app.UseCors("LanFileViewer");
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
// 将统一端点映射到 ASP.NET Core 路由
|
||||
app.MapUnifiedEndpoints(endpoints, app.Services);
|
||||
app.MapFileStreamEndpoints();
|
||||
app.MapFallbackToFile("index.html");
|
||||
|
||||
app.Run();
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5206",
|
||||
"applicationUrl": "http://0.0.0.0:5206",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7165;http://localhost:5206",
|
||||
"applicationUrl": "https://0.0.0.0:7165;http://0.0.0.0:5206",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using Avalonia_Services.Services.FileLibrary;
|
||||
|
||||
namespace Avalonia_API.Services
|
||||
{
|
||||
public sealed class FileLibraryScanHostedService(IServiceScopeFactory scopeFactory, ILogger<FileLibraryScanHostedService> logger)
|
||||
: BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(1);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
await ScanAsync(stoppingToken);
|
||||
|
||||
using var timer = new PeriodicTimer(Interval);
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
await ScanAsync(stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ScanAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var scope = scopeFactory.CreateAsyncScope();
|
||||
var scanner = scope.ServiceProvider.GetRequiredService<IFileLibraryService>();
|
||||
await scanner.ScanDueRootsAsync(cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "文件库定时扫描失败。");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,8 @@
|
||||
"RefreshTokenDays": 30
|
||||
},
|
||||
"DatabaseConfiguration": {
|
||||
"Provider": "MySQL",
|
||||
"ConnectionString": "Server=127.0.0.1;Port=3306;Database=avalonia-api;Uid=root;Pwd=123456;Max Pool Size=100;Min Pool Size=5;AllowZeroDateTime=True;AllowLoadLocalInfile=true;SslMode=Required",
|
||||
"Provider": "SQLite",
|
||||
"ConnectionString": "Data Source=app.db",
|
||||
"AutoMigrate": true,
|
||||
"RecreateDatabase": false,
|
||||
"EnableDetailedLog": false,
|
||||
|
||||
Reference in New Issue
Block a user