using ChaoXingAutoClass.Core; using Microsoft.Playwright; namespace ChaoXingAutoClass.Browser; public sealed partial class ChaoxingBrowser { private const string DocumentPageSelector = "li[id^='anchor']"; public async Task> GetDocumentsAsync(CancellationToken cancellationToken) { var documents = new List(); foreach (var frame in CurrentFrames()) { // Only the course's actual PDF/PPT reader is a supported document task. var owner = frame.ParentFrame; while (owner is not null && !owner.Url.Contains("/modules/pdf/", StringComparison.OrdinalIgnoreCase)) owner = owner.ParentFrame; if (owner is null) continue; try { var pages = frame.Locator(DocumentPageSelector); var count = await pages.CountAsync().WaitAsync(cancellationToken); if (count == 0 || await pages.Locator("img").CountAsync() != count) continue; var title = await frame.Locator("#fileInfoNameInput").CountAsync() == 1 ? await frame.Locator("#fileInfoNameInput").InputValueAsync().WaitAsync(cancellationToken) : "课程课件"; documents.Add(new(FrameKey(frame), title, count)); } catch (PlaywrightException) when (!_page.IsClosed) { } } return documents; } public async Task ReadDocumentPageAsync(LessonDocument document, int pageNumber, string directory, CancellationToken cancellationToken) { if (pageNumber < 1 || pageNumber > document.PageCount) throw new ArgumentOutOfRangeException(nameof(pageNumber)); var frame = RequireFrame(document.FrameKey); var pages = frame.Locator(DocumentPageSelector); if (await pages.CountAsync() != document.PageCount) throw new InvalidOperationException("课件已发生变化,请重新加载本章。"); var page = pages.Nth(pageNumber - 1); await page.ScrollIntoViewIfNeededAsync().WaitAsync(cancellationToken); await WaitForAsync(async () => await page.Locator("img").EvaluateAsync("e=>e.complete&&e.naturalWidth>0&&e.naturalHeight>0"), 30000, cancellationToken); Directory.CreateDirectory(directory); var path = Path.Combine(directory, $"document-{document.FrameKey}-page-{pageNumber:D3}.png"); await page.Locator("img").ScreenshotAsync(new() { Path = path, Timeout = 15000 }).WaitAsync(cancellationToken); // Scrolling the real reader lets its normal scroll listener report progress. // Never invoke site completion functions or replay a progress endpoint here. return new(path, 0, $"课件《{document.Title}》第 {pageNumber} / {document.PageCount} 页"); } }