using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Sakayaki.Services;
namespace Sakayaki.Pages;
public class IndexModel(SyncService syncService, AppDbContext dbContext, IConfiguration configuration) : PageModel
{
private readonly SyncService _syncService = syncService;
private readonly AppDbContext _dbContext = dbContext;
private readonly string? _rootPath = configuration["Fanbox:RootPath"];
[TempData]
public string? StatusMessage { get; set; }
public sealed class AuthorCard
{
public required string Author { get; init; }
public int FolderCount { get; init; }
public DateTime? LatestDate { get; init; }
}
public IReadOnlyList<AuthorCard> Authors { get; private set; } = Array.Empty<AuthorCard>();
/// <summary>
/// 加载作者列表。
/// </summary>
public async Task OnGetAsync()
{
var authors = await _dbContext.FanboxFolders.AsNoTracking()
.Where(x => x.Author != null && x.Author != string.Empty)
.GroupBy(x => x.Author)
.Select(group => new AuthorCard
{
Author = group.Key!,
FolderCount = group.Count(),
LatestDate = group.Max(x => (DateTime?)x.Date)
})
.OrderByDescending(x => x.LatestDate)
.ThenBy(x => x.Author)
.ToListAsync();
Authors = authors;
}
/// <summary>
/// 触发同步任务,将新的目录写入数据库。
/// </summary>
public async Task<IActionResult> OnPostUpdateAsync()
{
if (string.IsNullOrWhiteSpace(_rootPath))
{
StatusMessage = "Fanbox settings missing (RootPath).";
return Page();
}
var inserted = await _syncService.SyncFanboxFoldersAsync(_rootPath, HttpContext.RequestAborted);
StatusMessage = $"Inserted {inserted} rows.";
return RedirectToPage();
}
}