using Avalonia_Common.Core; using Avalonia_Services.Core; using System.Text.Json; namespace Avalonia_Services.Services.FileLibrary { public sealed class FileLibraryEndpointService(IFileLibraryService fileLibrary) : IFileLibraryEndpointService { private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true, }; public async Task GetDrivesAsync(ServiceEndpointContext ctx) { return ResponseHelper.Ok(await fileLibrary.GetDrivesAsync()); } public async Task GetDirectoriesAsync(ServiceEndpointContext ctx) { var path = ctx.Query.GetValueOrDefault("path"); return ResponseHelper.Ok(await fileLibrary.GetDirectoriesAsync(path)); } public async Task GetRootsAsync(ServiceEndpointContext ctx) { return ResponseHelper.Ok(await fileLibrary.GetRootsAsync()); } public async Task AddRootAsync(ServiceEndpointContext ctx) { var request = ReadBody(ctx); return ResponseHelper.Ok(await fileLibrary.AddRootAsync(request), "文件库目录已添加并完成扫描。"); } public async Task SetRootEnabledAsync(ServiceEndpointContext ctx) { var request = ReadBody(ctx); return ResponseHelper.Ok(await fileLibrary.SetRootEnabledAsync(request), "文件库目录状态已更新。"); } public async Task DeleteRootAsync(ServiceEndpointContext ctx) { var request = ReadBody(ctx); await fileLibrary.DeleteRootAsync(request); return ResponseHelper.Succeed("文件库目录已删除。"); } public async Task ScanRootAsync(ServiceEndpointContext ctx) { var request = ReadBody(ctx); return ResponseHelper.Ok(await fileLibrary.ScanRootAsync(request.Id), "文件库目录扫描完成。"); } public async Task SearchFilesAsync(ServiceEndpointContext ctx) { return await fileLibrary.SearchFilesAsync(ctx); } public async Task GetFileAsync(ServiceEndpointContext ctx) { var id = ReadId(ctx); var file = await fileLibrary.GetFileAsync(id); return file is null ? ResponseHelper.Failure(404, "文件不存在或尚未扫描入库。") : ResponseHelper.Ok(file); } public async Task GetTextPreviewAsync(ServiceEndpointContext ctx) { var id = ReadId(ctx); var preview = await fileLibrary.GetTextPreviewAsync(id); return preview is null ? ResponseHelper.Failure(404, "文本文件不存在或无法预览。") : ResponseHelper.Ok(preview); } private static T ReadBody(ServiceEndpointContext ctx) { if (string.IsNullOrWhiteSpace(ctx.Body)) { throw new InvalidOperationException("请求体不能为空。"); } var body = JsonSerializer.Deserialize(ctx.Body, JsonOptions); return body ?? throw new InvalidOperationException("请求体格式错误。"); } private static int ReadId(ServiceEndpointContext ctx) { if (int.TryParse(ctx.Query.GetValueOrDefault("id"), out var id) && id > 0) { return id; } throw new InvalidOperationException("id 参数无效。"); } } }