Rename projects to FileShare
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
namespace FileShare_Services.Services.AuthService
|
||||
{
|
||||
/// <summary>
|
||||
/// API 登录请求。
|
||||
/// </summary>
|
||||
/// <param name="Account">账号(邮箱或用户名)。</param>
|
||||
/// <param name="Password">密码。</param>
|
||||
/// <param name="Roles">请求的角色列表。</param>
|
||||
public sealed record ApiLoginRequest(string? Account, string? Password, string[]? Roles = null);
|
||||
|
||||
/// <summary>
|
||||
/// API Refresh Token 请求。
|
||||
/// </summary>
|
||||
/// <param name="RefreshToken">刷新令牌。</param>
|
||||
public sealed record ApiRefreshTokenRequest(string? RefreshToken);
|
||||
|
||||
/// <summary>
|
||||
/// API 登出请求。
|
||||
/// </summary>
|
||||
/// <param name="RefreshToken">要撤销的刷新令牌。</param>
|
||||
public sealed record ApiLogoutRequest(string? RefreshToken);
|
||||
|
||||
/// <summary>
|
||||
/// 认证 Token 响应,包含 Access Token 和 Refresh Token 及其过期时间。
|
||||
/// </summary>
|
||||
/// <param name="AccessToken">访问令牌。</param>
|
||||
/// <param name="RefreshToken">刷新令牌。</param>
|
||||
/// <param name="AccessTokenExpiresAt">访问令牌过期时间。</param>
|
||||
/// <param name="RefreshTokenExpiresAt">刷新令牌过期时间。</param>
|
||||
/// <param name="Roles">用户角色列表。</param>
|
||||
public sealed record AuthTokenResponse(
|
||||
string AccessToken,
|
||||
string RefreshToken,
|
||||
DateTime AccessTokenExpiresAt,
|
||||
DateTime RefreshTokenExpiresAt,
|
||||
string[] Roles);
|
||||
|
||||
/// <summary>
|
||||
/// PC 端授权码登录请求。
|
||||
/// </summary>
|
||||
/// <param name="AuthorizationCode">第三方授权码。</param>
|
||||
public sealed record PcAuthorizeRequest(string? AuthorizationCode);
|
||||
|
||||
/// <summary>
|
||||
/// PC 端 Token 刷新请求。
|
||||
/// </summary>
|
||||
/// <param name="Token">当前 Token。</param>
|
||||
public sealed record PcRefreshRequest(string? Token);
|
||||
|
||||
/// <summary>
|
||||
/// PC 端登出请求。
|
||||
/// </summary>
|
||||
/// <param name="Token">要清除的 Token。</param>
|
||||
public sealed record PcLogoutRequest(string? Token);
|
||||
|
||||
/// <summary>
|
||||
/// PC 端 Token 响应。
|
||||
/// </summary>
|
||||
/// <param name="Token">访问令牌。</param>
|
||||
/// <param name="ExpiresAt">过期时间。</param>
|
||||
/// <param name="Roles">用户角色列表。</param>
|
||||
public sealed record PcTokenResponse(string Token, DateTime ExpiresAt, string[] Roles);
|
||||
|
||||
/// <summary>
|
||||
/// 第三方授权检查结果。
|
||||
/// </summary>
|
||||
public enum ThirdPartyAuthCheckResult
|
||||
{
|
||||
/// <summary>授权有效。</summary>
|
||||
Valid,
|
||||
/// <summary>授权已丢失。</summary>
|
||||
AuthorizationLost,
|
||||
/// <summary>暂时性失败。</summary>
|
||||
TemporaryFailure,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 第三方授权客户端接口,用于验证和刷新第三方授权。
|
||||
/// </summary>
|
||||
public interface IPcThirdPartyAuthorizationClient
|
||||
{
|
||||
/// <summary>
|
||||
/// 验证第三方授权码是否有效。
|
||||
/// </summary>
|
||||
/// <param name="authorizationCode">第三方授权码。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
/// <returns>授权检查结果。</returns>
|
||||
Task<ThirdPartyAuthCheckResult> ValidateAuthorizationCodeAsync(string authorizationCode, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 刷新第三方授权。
|
||||
/// </summary>
|
||||
/// <param name="authorizationReference">授权引用标识。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
/// <returns>授权检查结果。</returns>
|
||||
Task<ThirdPartyAuthCheckResult> RefreshAuthorizationAsync(string authorizationReference, CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using FileShare_Common.Core;
|
||||
using FileShare_Services.Core;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FileShare_Services.Services.AuthService
|
||||
{
|
||||
/// <summary>
|
||||
/// API 鉴权端点服务接口,定义登录、刷新 Token 和登出操作。
|
||||
/// </summary>
|
||||
public interface IApiAuthEndpointService
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理用户登录请求。
|
||||
/// </summary>
|
||||
/// <param name="ctx">服务端点上下文。</param>
|
||||
/// <returns>包含 Token 的认证响应。</returns>
|
||||
Task<IApiResponse> LoginAsync(ApiLoginRequest request, ServiceEndpointContext ctx);
|
||||
|
||||
/// <summary>
|
||||
/// 使用 Refresh Token 刷新 Access Token。
|
||||
/// </summary>
|
||||
/// <param name="ctx">服务端点上下文。</param>
|
||||
/// <returns>新的 Token 对。</returns>
|
||||
Task<IApiResponse> RefreshAsync(ApiRefreshTokenRequest request, ServiceEndpointContext ctx);
|
||||
|
||||
/// <summary>
|
||||
/// 处理用户登出请求。
|
||||
/// </summary>
|
||||
/// <param name="ctx">服务端点上下文。</param>
|
||||
/// <returns>登出结果。</returns>
|
||||
Task<IApiResponse> LogoutAsync(ApiLogoutRequest request, ServiceEndpointContext ctx);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PC 端鉴权端点服务接口,定义授权码登录、Token 刷新和登出操作。
|
||||
/// </summary>
|
||||
public interface IPcAuthEndpointService
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用授权码进行登录授权。
|
||||
/// </summary>
|
||||
/// <param name="ctx">服务端点上下文。</param>
|
||||
/// <returns>包含 Token 的认证响应。</returns>
|
||||
Task<IApiResponse> AuthorizeAsync(PcAuthorizeRequest request, ServiceEndpointContext ctx);
|
||||
|
||||
/// <summary>
|
||||
/// 刷新当前 Token。
|
||||
/// </summary>
|
||||
/// <param name="ctx">服务端点上下文。</param>
|
||||
/// <returns>新的 Token 响应。</returns>
|
||||
Task<IApiResponse> RefreshAsync(PcRefreshRequest request, ServiceEndpointContext ctx);
|
||||
|
||||
/// <summary>
|
||||
/// 处理用户登出请求。
|
||||
/// </summary>
|
||||
/// <param name="ctx">服务端点上下文。</param>
|
||||
/// <returns>登出结果。</returns>
|
||||
Task<IApiResponse> LogoutAsync(PcLogoutRequest request, ServiceEndpointContext ctx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace FileShare_Services.Services.FileLibrary
|
||||
{
|
||||
public sealed record AddLibraryRootRequest(
|
||||
[property: JsonPropertyName("path")] string? Path,
|
||||
[property: JsonPropertyName("displayName")] string? DisplayName = null,
|
||||
[property: JsonPropertyName("scanIntervalMinutes")] int? ScanIntervalMinutes = null);
|
||||
|
||||
public sealed record UpdateLibraryRootRequest(
|
||||
[property: JsonPropertyName("id")] int Id,
|
||||
[property: JsonPropertyName("isEnabled")] bool IsEnabled);
|
||||
|
||||
public sealed record ScanLibraryRootRequest(
|
||||
[property: JsonPropertyName("id")] int Id);
|
||||
|
||||
public sealed record DeleteLibraryRootRequest(
|
||||
[property: JsonPropertyName("id")] int Id);
|
||||
|
||||
public sealed record DirectoryQueryRequest(
|
||||
[property: JsonPropertyName("path")] string? Path);
|
||||
|
||||
public sealed record FileQueryRequest(
|
||||
[property: JsonPropertyName("id")] int Id);
|
||||
|
||||
public sealed record SearchFilesRequest(
|
||||
[property: JsonPropertyName("page")] int Page = 1,
|
||||
[property: JsonPropertyName("pageSize")] int PageSize = 24,
|
||||
[property: JsonPropertyName("mediaType")] string? MediaType = null,
|
||||
[property: JsonPropertyName("keyword")] string? Keyword = null,
|
||||
[property: JsonPropertyName("rootId")] int RootId = 0);
|
||||
|
||||
public sealed record DriveDto(
|
||||
string Name,
|
||||
string DisplayName,
|
||||
string RootDirectory,
|
||||
string DriveType,
|
||||
long? TotalSize,
|
||||
long? AvailableFreeSpace,
|
||||
bool IsReady);
|
||||
|
||||
public sealed record DirectoryDto(
|
||||
string Name,
|
||||
string FullPath);
|
||||
|
||||
public sealed record LibraryRootDto(
|
||||
int Id,
|
||||
string Path,
|
||||
string DisplayName,
|
||||
bool IsEnabled,
|
||||
bool IsAvailable,
|
||||
int ScanIntervalMinutes,
|
||||
DateTime? LastScanStartedAt,
|
||||
DateTime? LastScanCompletedAt,
|
||||
string? LastScanError,
|
||||
int FileCount);
|
||||
|
||||
public sealed record FileRecordDto(
|
||||
int Id,
|
||||
int LibraryRootId,
|
||||
string FileName,
|
||||
string RelativePath,
|
||||
string Extension,
|
||||
long SizeBytes,
|
||||
DateTime LastWriteTimeUtc,
|
||||
string MediaType,
|
||||
string ContentType,
|
||||
string StreamUrl,
|
||||
string? TextUrl,
|
||||
bool BrowserPlayable);
|
||||
|
||||
public sealed record BrowseDirectoryRequest(
|
||||
[property: JsonPropertyName("rootId")] int RootId = 0,
|
||||
[property: JsonPropertyName("path")] string? Path = null);
|
||||
|
||||
public sealed record BrowseDirectoryResponse(
|
||||
string CurrentPath,
|
||||
List<string> Subdirectories,
|
||||
List<FileRecordDto> Files);
|
||||
|
||||
public sealed record TextPreviewDto(
|
||||
int Id,
|
||||
string FileName,
|
||||
string Content,
|
||||
bool Truncated);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using FileShare_Common.Core;
|
||||
using FileShare_Services.Core;
|
||||
|
||||
namespace FileShare_Services.Services.FileLibrary
|
||||
{
|
||||
public sealed class FileLibraryEndpointService(IFileLibraryService fileLibrary) : IFileLibraryEndpointService
|
||||
{
|
||||
public async Task<IApiResponse> GetDrivesAsync(ServiceEndpointContext ctx)
|
||||
{
|
||||
return ResponseHelper.Ok(await fileLibrary.GetDrivesAsync());
|
||||
}
|
||||
|
||||
public async Task<IApiResponse> GetDirectoriesAsync(DirectoryQueryRequest request)
|
||||
{
|
||||
return ResponseHelper.Ok(await fileLibrary.GetDirectoriesAsync(request.Path));
|
||||
}
|
||||
|
||||
public async Task<IApiResponse> GetRootsAsync(ServiceEndpointContext ctx)
|
||||
{
|
||||
return ResponseHelper.Ok(await fileLibrary.GetRootsAsync());
|
||||
}
|
||||
|
||||
public async Task<IApiResponse> AddRootAsync(AddLibraryRootRequest request)
|
||||
{
|
||||
return ResponseHelper.Ok(await fileLibrary.AddRootAsync(request), "文件库目录已添加并完成扫描。");
|
||||
}
|
||||
|
||||
public async Task<IApiResponse> SetRootEnabledAsync(UpdateLibraryRootRequest request)
|
||||
{
|
||||
return ResponseHelper.Ok(await fileLibrary.SetRootEnabledAsync(request), "文件库目录状态已更新。");
|
||||
}
|
||||
|
||||
public async Task<IApiResponse> DeleteRootAsync(DeleteLibraryRootRequest request)
|
||||
{
|
||||
await fileLibrary.DeleteRootAsync(request);
|
||||
return ResponseHelper.Succeed("文件库目录已删除。");
|
||||
}
|
||||
|
||||
public async Task<IApiResponse> ScanRootAsync(ScanLibraryRootRequest request)
|
||||
{
|
||||
return ResponseHelper.Ok(await fileLibrary.ScanRootAsync(request.Id), "文件库目录扫描完成。");
|
||||
}
|
||||
|
||||
public async Task<IApiResponse> SearchFilesAsync(SearchFilesRequest request)
|
||||
{
|
||||
return await fileLibrary.SearchFilesAsync(request);
|
||||
}
|
||||
|
||||
public async Task<IApiResponse> GetFileAsync(FileQueryRequest request)
|
||||
{
|
||||
ValidateFileId(request.Id);
|
||||
var file = await fileLibrary.GetFileAsync(request.Id);
|
||||
return file is null
|
||||
? ResponseHelper.Failure(404, "文件不存在或尚未扫描入库。")
|
||||
: ResponseHelper.Ok(file);
|
||||
}
|
||||
|
||||
public async Task<IApiResponse> GetTextPreviewAsync(FileQueryRequest request)
|
||||
{
|
||||
ValidateFileId(request.Id);
|
||||
var preview = await fileLibrary.GetTextPreviewAsync(request.Id);
|
||||
return preview is null
|
||||
? ResponseHelper.Failure(404, "文本文件不存在或无法预览。")
|
||||
: ResponseHelper.Ok(preview);
|
||||
}
|
||||
|
||||
public async Task<IApiResponse> BrowseDirectoryAsync(BrowseDirectoryRequest request)
|
||||
{
|
||||
if (request.RootId <= 0)
|
||||
return ResponseHelper.Failure(400, "rootId 参数无效。");
|
||||
|
||||
var result = await fileLibrary.BrowseDirectoryAsync(request);
|
||||
return ResponseHelper.Ok(result);
|
||||
}
|
||||
|
||||
private static void ValidateFileId(int id)
|
||||
{
|
||||
if (id > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
throw new ArgumentException("id 参数无效。");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
using FileShare_Common.Core;
|
||||
using FileShare_EFCore.Database;
|
||||
using FileShare_EFCore.Models;
|
||||
using FileShare_Services.Core;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Text;
|
||||
|
||||
namespace FileShare_Services.Services.FileLibrary
|
||||
{
|
||||
public sealed class FileLibraryService(AppDataContext db) : IFileLibraryService
|
||||
{
|
||||
private const int DefaultScanIntervalMinutes = 5;
|
||||
private const int MaxTextPreviewBytes = 1024 * 1024;
|
||||
|
||||
public Task<List<DriveDto>> GetDrivesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var drives = DriveInfo.GetDrives()
|
||||
.Select(drive => new DriveDto(
|
||||
drive.Name,
|
||||
drive.IsReady ? $"{drive.Name} ({drive.VolumeLabel})" : drive.Name,
|
||||
drive.RootDirectory.FullName,
|
||||
drive.DriveType.ToString(),
|
||||
SafeDriveValue(drive, d => d.TotalSize),
|
||||
SafeDriveValue(drive, d => d.AvailableFreeSpace),
|
||||
drive.IsReady))
|
||||
.OrderBy(drive => drive.Name)
|
||||
.ToList();
|
||||
|
||||
return Task.FromResult(drives);
|
||||
}
|
||||
|
||||
public Task<List<DirectoryDto>> GetDirectoriesAsync(string? path, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalized = NormalizeExistingDirectory(path);
|
||||
var directories = Directory.EnumerateDirectories(normalized)
|
||||
.Select(directory => new DirectoryInfo(directory))
|
||||
.OrderBy(directory => directory.Name)
|
||||
.Select(directory => new DirectoryDto(directory.Name, directory.FullName))
|
||||
.ToList();
|
||||
|
||||
return Task.FromResult(directories);
|
||||
}
|
||||
|
||||
public async Task<List<LibraryRootDto>> GetRootsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var counts = await db.ManagedFileRecords
|
||||
.Where(file => file.Exists)
|
||||
.GroupBy(file => file.LibraryRootId)
|
||||
.Select(group => new { RootId = group.Key, Count = group.Count() })
|
||||
.ToDictionaryAsync(item => item.RootId, item => item.Count, cancellationToken);
|
||||
|
||||
var roots = await db.ManagedLibraryRoots
|
||||
.OrderBy(root => root.Path)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return roots.Select(root => ToRootDto(root, counts.GetValueOrDefault(root.Id))).ToList();
|
||||
}
|
||||
|
||||
public async Task<LibraryRootDto> AddRootAsync(AddLibraryRootRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalized = NormalizeExistingDirectory(request.Path);
|
||||
var existing = await db.ManagedLibraryRoots.FirstOrDefaultAsync(root => root.Path == normalized, cancellationToken);
|
||||
if (existing is not null)
|
||||
{
|
||||
existing.IsEnabled = true;
|
||||
existing.IsAvailable = true;
|
||||
existing.DisplayName = ResolveDisplayName(normalized, request.DisplayName);
|
||||
existing.ScanIntervalMinutes = NormalizeInterval(request.ScanIntervalMinutes);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return await ScanRootAsync(existing.Id, cancellationToken);
|
||||
}
|
||||
|
||||
var root = new ManagedLibraryRoot
|
||||
{
|
||||
Path = normalized,
|
||||
DisplayName = ResolveDisplayName(normalized, request.DisplayName),
|
||||
ScanIntervalMinutes = NormalizeInterval(request.ScanIntervalMinutes),
|
||||
IsEnabled = true,
|
||||
IsAvailable = true,
|
||||
};
|
||||
|
||||
db.ManagedLibraryRoots.Add(root);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return await ScanRootAsync(root.Id, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<LibraryRootDto> SetRootEnabledAsync(UpdateLibraryRootRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var root = await db.ManagedLibraryRoots.FirstOrDefaultAsync(item => item.Id == request.Id, cancellationToken)
|
||||
?? throw new InvalidOperationException("文件库目录不存在。");
|
||||
|
||||
root.IsEnabled = request.IsEnabled;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
|
||||
var count = await db.ManagedFileRecords.CountAsync(file => file.LibraryRootId == root.Id && file.Exists, cancellationToken);
|
||||
return ToRootDto(root, count);
|
||||
}
|
||||
|
||||
public async Task DeleteRootAsync(DeleteLibraryRootRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var root = await db.ManagedLibraryRoots.FirstOrDefaultAsync(item => item.Id == request.Id, cancellationToken)
|
||||
?? throw new InvalidOperationException("文件库目录不存在。");
|
||||
|
||||
db.ManagedLibraryRoots.Remove(root);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<LibraryRootDto> ScanRootAsync(int rootId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var root = await db.ManagedLibraryRoots.FirstOrDefaultAsync(item => item.Id == rootId, cancellationToken)
|
||||
?? throw new InvalidOperationException("文件库目录不存在。");
|
||||
|
||||
root.LastScanStartedAt = DateTime.UtcNow;
|
||||
root.LastScanError = null;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(root.Path))
|
||||
{
|
||||
throw new DirectoryNotFoundException($"目录不存在:{root.Path}");
|
||||
}
|
||||
|
||||
root.IsAvailable = true;
|
||||
root.IsEnabled = true;
|
||||
|
||||
var existing = await db.ManagedFileRecords
|
||||
.Where(file => file.LibraryRootId == root.Id)
|
||||
.ToDictionaryAsync(file => file.AbsolutePath, StringComparer.OrdinalIgnoreCase, cancellationToken);
|
||||
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var path in EnumerateSupportedFiles(root.Path))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var info = new FileInfo(path);
|
||||
if (!info.Exists || !MediaFileTypes.TryGet(info.Extension.ToLowerInvariant(), out var mediaType, out var contentType, out _))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var absolutePath = info.FullName;
|
||||
seen.Add(absolutePath);
|
||||
|
||||
if (!existing.TryGetValue(absolutePath, out var record))
|
||||
{
|
||||
record = new ManagedFileRecord
|
||||
{
|
||||
LibraryRootId = root.Id,
|
||||
AbsolutePath = absolutePath,
|
||||
};
|
||||
db.ManagedFileRecords.Add(record);
|
||||
}
|
||||
|
||||
record.FileName = info.Name;
|
||||
record.RelativePath = Path.GetRelativePath(root.Path, absolutePath);
|
||||
record.Extension = info.Extension.ToLowerInvariant();
|
||||
record.SizeBytes = info.Length;
|
||||
record.LastWriteTimeUtc = info.LastWriteTimeUtc;
|
||||
record.MediaType = mediaType;
|
||||
record.ContentType = contentType;
|
||||
record.Exists = true;
|
||||
record.LastSeenAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
foreach (var stale in existing.Values.Where(file => !seen.Contains(file.AbsolutePath)))
|
||||
{
|
||||
stale.Exists = false;
|
||||
}
|
||||
|
||||
root.LastScanCompletedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
root.IsAvailable = false;
|
||||
root.IsEnabled = false;
|
||||
root.LastScanError = ex.Message;
|
||||
root.LastScanCompletedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(CancellationToken.None);
|
||||
throw;
|
||||
}
|
||||
|
||||
var count = await db.ManagedFileRecords.CountAsync(file => file.LibraryRootId == root.Id && file.Exists, cancellationToken);
|
||||
return ToRootDto(root, count);
|
||||
}
|
||||
|
||||
public async Task ScanDueRootsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var roots = await db.ManagedLibraryRoots
|
||||
.Where(root => root.IsEnabled && root.IsAvailable)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
foreach (var root in roots)
|
||||
{
|
||||
var interval = Math.Max(1, root.ScanIntervalMinutes);
|
||||
var isDue = root.LastScanCompletedAt is null || root.LastScanCompletedAt.Value.AddMinutes(interval) <= now;
|
||||
if (!isDue)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await ScanRootAsync(root.Id, cancellationToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ScanRootAsync records the error on the root. Continue scanning other roots.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<PagedResponse<FileRecordDto>> SearchFilesAsync(SearchFilesRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var page = Math.Clamp(request.Page, 1, 100000);
|
||||
var pageSize = Math.Clamp(request.PageSize, 1, 100);
|
||||
var mediaType = request.MediaType?.Trim();
|
||||
var keyword = request.Keyword?.Trim();
|
||||
var rootId = Math.Clamp(request.RootId, 0, int.MaxValue);
|
||||
|
||||
var query = db.ManagedFileRecords
|
||||
.AsNoTracking()
|
||||
.Where(file => file.Exists && file.LibraryRoot != null && file.LibraryRoot.IsAvailable);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(mediaType) && !mediaType.Equals("all", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
query = query.Where(file => file.MediaType == mediaType);
|
||||
}
|
||||
|
||||
if (rootId > 0)
|
||||
{
|
||||
query = query.Where(file => file.LibraryRootId == rootId);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(keyword))
|
||||
{
|
||||
query = query.Where(file => file.FileName.Contains(keyword) || file.RelativePath.Contains(keyword));
|
||||
}
|
||||
|
||||
var total = await query.CountAsync(cancellationToken);
|
||||
var items = await query
|
||||
.OrderBy(file => file.MediaType)
|
||||
.ThenBy(file => file.RelativePath)
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.Select(file => ToFileDto(file))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return PagedResponse<FileRecordDto>.From(items, total, page, pageSize);
|
||||
}
|
||||
|
||||
public async Task<FileRecordDto?> GetFileAsync(int id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await db.ManagedFileRecords
|
||||
.AsNoTracking()
|
||||
.Where(file => file.Id == id && file.Exists && file.LibraryRoot != null && file.LibraryRoot.IsAvailable)
|
||||
.Select(file => ToFileDto(file))
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<BrowseDirectoryResponse> BrowseDirectoryAsync(BrowseDirectoryRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var rootId = request.RootId;
|
||||
// URL 友好的正斜杠,用于响应和内存处理
|
||||
var prefix = (request.Path ?? "").Trim().Replace('\\', '/').Trim('/');
|
||||
// Windows 反斜杠,用于数据库查询
|
||||
var dbPrefix = prefix.Replace('/', '\\');
|
||||
|
||||
var query = db.ManagedFileRecords
|
||||
.AsNoTracking()
|
||||
.Where(f => f.LibraryRootId == rootId && f.Exists
|
||||
&& f.LibraryRoot != null && f.LibraryRoot.IsAvailable);
|
||||
|
||||
if (!string.IsNullOrEmpty(dbPrefix))
|
||||
{
|
||||
var dbPrefixWithSlash = dbPrefix + "\\";
|
||||
query = query.Where(f => f.RelativePath.StartsWith(dbPrefixWithSlash));
|
||||
}
|
||||
|
||||
var allFiles = await query.ToListAsync(cancellationToken);
|
||||
|
||||
var subdirs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var currentFiles = new List<FileRecordDto>();
|
||||
|
||||
foreach (var file in allFiles)
|
||||
{
|
||||
var relativePath = file.RelativePath.Replace('\\', '/');
|
||||
var remaining = string.IsNullOrEmpty(prefix)
|
||||
? relativePath
|
||||
: relativePath[(prefix.Length + 1)..];
|
||||
|
||||
var slashIndex = remaining.IndexOf('/');
|
||||
if (slashIndex < 0)
|
||||
{
|
||||
currentFiles.Add(ToFileDto(file));
|
||||
}
|
||||
else
|
||||
{
|
||||
subdirs.Add(remaining[..slashIndex]);
|
||||
}
|
||||
}
|
||||
|
||||
return new BrowseDirectoryResponse(
|
||||
prefix,
|
||||
subdirs.OrderBy(d => d, StringComparer.OrdinalIgnoreCase).ToList(),
|
||||
currentFiles);
|
||||
}
|
||||
|
||||
public async Task<TextPreviewDto?> GetTextPreviewAsync(int id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var file = await db.ManagedFileRecords
|
||||
.AsNoTracking()
|
||||
.Include(item => item.LibraryRoot)
|
||||
.FirstOrDefaultAsync(item =>
|
||||
item.Id == id
|
||||
&& item.Exists
|
||||
&& item.MediaType == "text"
|
||||
&& item.LibraryRoot != null
|
||||
&& item.LibraryRoot.IsAvailable,
|
||||
cancellationToken);
|
||||
|
||||
if (file is null || !File.Exists(file.AbsolutePath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
await using var stream = File.OpenRead(file.AbsolutePath);
|
||||
var limit = (int)Math.Min(stream.Length, MaxTextPreviewBytes);
|
||||
var buffer = new byte[limit];
|
||||
var read = await stream.ReadAsync(buffer.AsMemory(0, limit), cancellationToken);
|
||||
var content = Encoding.UTF8.GetString(buffer, 0, read);
|
||||
return new TextPreviewDto(file.Id, file.FileName, content, stream.Length > MaxTextPreviewBytes);
|
||||
}
|
||||
|
||||
private static IEnumerable<string> EnumerateSupportedFiles(string rootPath)
|
||||
{
|
||||
var pending = new Stack<string>();
|
||||
pending.Push(rootPath);
|
||||
|
||||
while (pending.Count > 0)
|
||||
{
|
||||
var current = pending.Pop();
|
||||
IEnumerable<string> directories;
|
||||
IEnumerable<string> files;
|
||||
|
||||
try
|
||||
{
|
||||
directories = Directory.EnumerateDirectories(current);
|
||||
files = Directory.EnumerateFiles(current);
|
||||
}
|
||||
catch
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var directory in directories)
|
||||
{
|
||||
pending.Push(directory);
|
||||
}
|
||||
|
||||
foreach (var file in files)
|
||||
{
|
||||
if (MediaFileTypes.TryGet(Path.GetExtension(file), out _, out _, out _))
|
||||
{
|
||||
yield return file;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string NormalizeExistingDirectory(string? path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
throw new InvalidOperationException("目录路径不能为空。");
|
||||
}
|
||||
|
||||
var fullPath = Path.GetFullPath(path.Trim());
|
||||
if (!Directory.Exists(fullPath))
|
||||
{
|
||||
throw new DirectoryNotFoundException($"目录不存在:{fullPath}");
|
||||
}
|
||||
|
||||
return new DirectoryInfo(fullPath).FullName;
|
||||
}
|
||||
|
||||
private static string ResolveDisplayName(string path, string? displayName)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(displayName))
|
||||
{
|
||||
return displayName.Trim();
|
||||
}
|
||||
|
||||
var directory = new DirectoryInfo(path);
|
||||
return string.IsNullOrWhiteSpace(directory.Name) ? directory.FullName : directory.Name;
|
||||
}
|
||||
|
||||
private static int NormalizeInterval(int? interval)
|
||||
{
|
||||
return Math.Clamp(interval ?? DefaultScanIntervalMinutes, 1, 1440);
|
||||
}
|
||||
|
||||
private static long? SafeDriveValue(DriveInfo drive, Func<DriveInfo, long> selector)
|
||||
{
|
||||
try
|
||||
{
|
||||
return drive.IsReady ? selector(drive) : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static LibraryRootDto ToRootDto(ManagedLibraryRoot root, int fileCount)
|
||||
{
|
||||
return new LibraryRootDto(
|
||||
root.Id,
|
||||
root.Path,
|
||||
root.DisplayName,
|
||||
root.IsEnabled,
|
||||
root.IsAvailable,
|
||||
root.ScanIntervalMinutes,
|
||||
root.LastScanStartedAt,
|
||||
root.LastScanCompletedAt,
|
||||
root.LastScanError,
|
||||
fileCount);
|
||||
}
|
||||
|
||||
private static FileRecordDto ToFileDto(ManagedFileRecord file)
|
||||
{
|
||||
return new FileRecordDto(
|
||||
file.Id,
|
||||
file.LibraryRootId,
|
||||
file.FileName,
|
||||
file.RelativePath,
|
||||
file.Extension,
|
||||
file.SizeBytes,
|
||||
file.LastWriteTimeUtc,
|
||||
file.MediaType,
|
||||
file.ContentType,
|
||||
$"/api/files/{file.Id}/stream",
|
||||
file.MediaType == "text" ? $"/api/files/text?id={file.Id}" : null,
|
||||
MediaFileTypes.IsBrowserPlayable(file.Extension));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using FileShare_EFCore.Database;
|
||||
using FileShare_EFCore.Models;
|
||||
using FileShare_Services.Core;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FileShare_Services.Services.FileLibrary
|
||||
{
|
||||
public interface IFileStreamService
|
||||
{
|
||||
Task<FileStreamResponse?> GetFileStreamAsync(int id, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class FileStreamService(AppDataContext db) : IFileStreamService
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using FileShare_Common.Core;
|
||||
using FileShare_Services.Core;
|
||||
|
||||
namespace FileShare_Services.Services.FileLibrary
|
||||
{
|
||||
public interface IFileLibraryEndpointService
|
||||
{
|
||||
Task<IApiResponse> GetDrivesAsync(ServiceEndpointContext ctx);
|
||||
|
||||
Task<IApiResponse> GetDirectoriesAsync(DirectoryQueryRequest request);
|
||||
|
||||
Task<IApiResponse> GetRootsAsync(ServiceEndpointContext ctx);
|
||||
|
||||
Task<IApiResponse> AddRootAsync(AddLibraryRootRequest request);
|
||||
|
||||
Task<IApiResponse> SetRootEnabledAsync(UpdateLibraryRootRequest request);
|
||||
|
||||
Task<IApiResponse> DeleteRootAsync(DeleteLibraryRootRequest request);
|
||||
|
||||
Task<IApiResponse> ScanRootAsync(ScanLibraryRootRequest request);
|
||||
|
||||
Task<IApiResponse> SearchFilesAsync(SearchFilesRequest request);
|
||||
|
||||
Task<IApiResponse> GetFileAsync(FileQueryRequest request);
|
||||
|
||||
Task<IApiResponse> GetTextPreviewAsync(FileQueryRequest request);
|
||||
|
||||
Task<IApiResponse> BrowseDirectoryAsync(BrowseDirectoryRequest request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using FileShare_Common.Core;
|
||||
|
||||
namespace FileShare_Services.Services.FileLibrary
|
||||
{
|
||||
public interface IFileLibraryService
|
||||
{
|
||||
Task<List<DriveDto>> GetDrivesAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
Task<List<DirectoryDto>> GetDirectoriesAsync(string? path, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<List<LibraryRootDto>> GetRootsAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
Task<LibraryRootDto> AddRootAsync(AddLibraryRootRequest request, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<LibraryRootDto> SetRootEnabledAsync(UpdateLibraryRootRequest request, CancellationToken cancellationToken = default);
|
||||
|
||||
Task DeleteRootAsync(DeleteLibraryRootRequest request, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<LibraryRootDto> ScanRootAsync(int rootId, CancellationToken cancellationToken = default);
|
||||
|
||||
Task ScanDueRootsAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
Task<PagedResponse<FileRecordDto>> SearchFilesAsync(SearchFilesRequest request, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<FileRecordDto?> GetFileAsync(int id, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<TextPreviewDto?> GetTextPreviewAsync(int id, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<BrowseDirectoryResponse> BrowseDirectoryAsync(BrowseDirectoryRequest request, CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
namespace FileShare_Services.Services.FileLibrary
|
||||
{
|
||||
public static class MediaFileTypes
|
||||
{
|
||||
private static readonly Dictionary<string, (string MediaType, string ContentType, bool BrowserPlayable)> Types =
|
||||
new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[".txt"] = ("text", "text/plain; charset=utf-8", true),
|
||||
[".log"] = ("text", "text/plain; charset=utf-8", true),
|
||||
[".json"] = ("text", "application/json; charset=utf-8", true),
|
||||
[".xml"] = ("text", "application/xml; charset=utf-8", true),
|
||||
[".csv"] = ("text", "text/csv; charset=utf-8", true),
|
||||
[".md"] = ("text", "text/markdown; charset=utf-8", true),
|
||||
[".ini"] = ("text", "text/plain; charset=utf-8", true),
|
||||
[".yml"] = ("text", "text/yaml; charset=utf-8", true),
|
||||
[".yaml"] = ("text", "text/yaml; charset=utf-8", true),
|
||||
[".mp4"] = ("video", "video/mp4", true),
|
||||
[".webm"] = ("video", "video/webm", true),
|
||||
[".ogg"] = ("video", "video/ogg", true),
|
||||
[".ogv"] = ("video", "video/ogg", true),
|
||||
[".mov"] = ("video", "video/quicktime", false),
|
||||
[".mkv"] = ("video", "video/x-matroska", false),
|
||||
[".mp3"] = ("audio", "audio/mpeg", true),
|
||||
[".wav"] = ("audio", "audio/wav", true),
|
||||
[".m4a"] = ("audio", "audio/mp4", true),
|
||||
[".aac"] = ("audio", "audio/aac", true),
|
||||
[".oga"] = ("audio", "audio/ogg", true),
|
||||
};
|
||||
|
||||
public static bool TryGet(string extension, out string mediaType, out string contentType, out bool browserPlayable)
|
||||
{
|
||||
if (Types.TryGetValue(extension, out var value))
|
||||
{
|
||||
mediaType = value.MediaType;
|
||||
contentType = value.ContentType;
|
||||
browserPlayable = value.BrowserPlayable;
|
||||
return true;
|
||||
}
|
||||
|
||||
mediaType = string.Empty;
|
||||
contentType = "application/octet-stream";
|
||||
browserPlayable = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool IsBrowserPlayable(string extension)
|
||||
{
|
||||
return Types.TryGetValue(extension, out var value) && value.BrowserPlayable;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using FileShare_Services.Core;
|
||||
|
||||
namespace FileShare_Services.Services.QrCode
|
||||
{
|
||||
public interface IQrCodeService
|
||||
{
|
||||
Task<object?> GenerateQrCodeAsync(ServiceEndpointContext ctx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace FileShare_Services.Services.QrCode
|
||||
{
|
||||
public sealed record QrCodeResponse(string Url, string QrCodeBase64);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using FileShare_Common.Core;
|
||||
using FileShare_Services.Core;
|
||||
using QRCoder;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace FileShare_Services.Services.QrCode
|
||||
{
|
||||
public sealed class QrCodeService : IQrCodeService
|
||||
{
|
||||
public Task<object?> GenerateQrCodeAsync(ServiceEndpointContext ctx)
|
||||
{
|
||||
var ip = GetLanIpAddress();
|
||||
if (ip is null)
|
||||
throw new InvalidOperationException("无法获取局域网IP地址");
|
||||
|
||||
var url = $"http://{ip}:5206";
|
||||
var base64 = GeneratePngBase64(url);
|
||||
return Task.FromResult<object?>(ResponseHelper.Ok(new QrCodeResponse(url, base64)));
|
||||
}
|
||||
|
||||
private static string GeneratePngBase64(string content)
|
||||
{
|
||||
using var generator = new QRCodeGenerator();
|
||||
using var data = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.Q);
|
||||
using var png = new PngByteQRCode(data);
|
||||
var bytes = png.GetGraphic(20);
|
||||
return $"data:image/png;base64,{Convert.ToBase64String(bytes)}";
|
||||
}
|
||||
|
||||
private static string? GetLanIpAddress()
|
||||
{
|
||||
return NetworkInterface.GetAllNetworkInterfaces()
|
||||
.Where(ni => ni.OperationalStatus == OperationalStatus.Up
|
||||
&& ni.NetworkInterfaceType != NetworkInterfaceType.Loopback)
|
||||
.SelectMany(ni => ni.GetIPProperties().UnicastAddresses)
|
||||
.Select(ua => ua.Address)
|
||||
.FirstOrDefault(ip =>
|
||||
ip.AddressFamily == AddressFamily.InterNetwork
|
||||
&& !IPAddress.IsLoopback(ip)
|
||||
&& !ip.ToString().StartsWith("169.254"))
|
||||
?.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using FileShare_EFCore.Models;
|
||||
|
||||
namespace FileShare_Services.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// 天气预报服务,随机生成未来 5 天的天气预报数据。
|
||||
/// </summary>
|
||||
public class WeatherForecastService
|
||||
{
|
||||
private static readonly string[] Summaries =
|
||||
[
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 生成未来 5 天的随机天气预报数据。
|
||||
/// </summary>
|
||||
/// <returns>天气预报数据集合。</returns>
|
||||
public IEnumerable<WeatherForecast> GetWeatherForecasts()
|
||||
{
|
||||
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
||||
{
|
||||
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
|
||||
TemperatureC = Random.Shared.Next(-20, 55),
|
||||
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user