ChaoXingAutoClass
【WinUI】基于 XFEstudio 的 XFEWinUIApplication 模板重建的 WinUI 3 课程工作台。二维码和账号密码登录、课程 GridView、章节、播放进度、学习笔记及日志均使用原生 WinUI 控件。网页播放器运行在独立后台进程中,界面不显示课程网站。
关注
0
Fork
0
Star
0
using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.RegularExpressions;
using ChaoXingAutoClass.Core;
using Microsoft.Playwright;
namespace ChaoXingAutoClass.Browser;
public sealed partial class ChaoxingBrowser : ICourseBrowser, IHomeworkBrowser, ILessonDocumentBrowser, IMediaDownloader, IAsyncDisposable
{
private readonly IBrowserContext _context;
private readonly IPage _page;
private readonly Dictionary<IFrame, string> _frames = new(ReferenceEqualityComparer.Instance);
private readonly Dictionary<string, IFrame> _frameByKey = new();
private readonly Dictionary<string, (IFrame Frame, int Index)> _questions = new();
private readonly ConcurrentQueue<string> _network = new();
private readonly CancellationTokenSource _networkStop = new();
private readonly Task _networkWriter;
private int _frameSequence;
private string? _lastDialog;
private const string QuestionSelector = ".TiMu:not(:has(.questionLi)), .questionLi, [data-cx-question]";
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { PropertyNameCaseInsensitive = true };
public IPage Page => _page;
public string NetworkFile { get; }
public ChaoxingBrowser(IBrowserContext context, IPage page, string networkFile)
{
_context = context; _page = page; NetworkFile = networkFile;
Directory.CreateDirectory(Path.GetDirectoryName(networkFile)!);
context.Response += OnResponse;
context.RequestFailed += OnRequestFailed;
page.Dialog += OnDialog;
_networkWriter = WriteNetworkAsync();
}
private string FrameKey(IFrame frame)
{
if (!_frames.TryGetValue(frame, out var key))
{ key = $"frame-{++_frameSequence:D5}"; _frames.Add(frame, key); _frameByKey[key] = frame; }
return key;
}
private IFrame RequireFrame(string key) => _frameByKey.TryGetValue(key, out var frame) && !frame.IsDetached
? frame : throw new InvalidOperationException("页面已导航,原播放器或题目已失效,请重新扫描。");
private IFrame[] CurrentFrames() => _page.Frames.Where(frame => !frame.IsDetached).ToArray();
public async Task<IReadOnlyList<CourseInfo>> GetCoursesAsync(CancellationToken cancellationToken)
{
var result = new List<CourseInfo>();
foreach (var frame in CurrentFrames())
{
try
{
var raw = await frame.EvaluateAsync<JsonElement>("""
() => Array.from(document.querySelectorAll('a[href*="stucoursemiddle"],a[href*="/mycourse/stu?"],a[data-cx-course]'))
.map(a => ({id:new URL(a.href).searchParams.get('courseid')||a.dataset.cxCourse||a.href,
title:(a.querySelector('[title]')?.getAttribute('title')||a.textContent||a.title||'').trim(),url:a.href}))
.filter(a=>a.title&&a.url.startsWith('http'))
""").WaitAsync(cancellationToken);
var items = raw.Deserialize<CourseDto[]>(Json) ?? [];
result.AddRange(items.Where(item => IsAllowedUrl(item.Url)).Select(item => new CourseInfo(item.Id, item.Title, item.Url)));
}
catch (PlaywrightException) when (!_page.IsClosed) { }
}
return result.DistinctBy(course => course.Url).ToArray();
}
public async Task OpenCourseAsync(CourseInfo course, CancellationToken cancellationToken)
{
_lastDialog = null;
_appliedChoices.Clear();
if (!IsAllowedUrl(course.Url)) throw new InvalidOperationException("课程链接不属于学习通或本地演示站点。");
await _page.GotoAsync(course.Url, new() { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 45000 }).WaitAsync(cancellationToken);
await WaitForAsync(async () => (await GetChaptersAsync(cancellationToken)).Count > 0 ||
await _page.GetByText("章节", new() { Exact = true }).CountAsync() > 0, 20000, cancellationToken);
if ((await GetChaptersAsync(cancellationToken)).Count == 0)
{
var menu = _page.GetByText("章节", new() { Exact = true });
if (await menu.CountAsync() == 1) await menu.ClickAsync().WaitAsync(cancellationToken);
await WaitForAsync(async () => (await GetChaptersAsync(cancellationToken)).Count > 0, 15000, cancellationToken, false);
}
}
public async Task<IReadOnlyList<ChapterInfo>> GetChaptersAsync(CancellationToken cancellationToken)
{
var result = new List<ChapterInfo>();
foreach (var frame in CurrentFrames())
{
try
{
var raw = await frame.EvaluateAsync<JsonElement>("""
() => Array.from(document.querySelectorAll('.chapter_item[id^="cur"],.posCatalog_select[id^="cur"],[data-cx-chapter]'))
.map(e=>({id:e.dataset.cxChapter||e.id.replace(/^cur/,''),
title:(e.querySelector('.catalog_name,.posCatalog_name')?.textContent||e.getAttribute('title')||e.textContent||'').trim().replace(/\s+/g,' '),
completed:e.dataset.completed==='true'||e.classList.contains('cx-completed')||
Array.from(e.querySelectorAll('.bntHoverTips')).some(s=>s.textContent.trim()==='已完成')||
(!!e.querySelector('.catalog_points_yi,.catalog_jindu,.orangeNew')&&/^\s*0\s*$/.test(e.querySelector('.catalog_points_yi,.catalog_jindu,.orangeNew').textContent))}))
""").WaitAsync(cancellationToken);
var chapters = raw.Deserialize<ChapterDto[]>(Json) ?? [];
result.AddRange(chapters.Select(chapter => new ChapterInfo(chapter.Id, chapter.Title, chapter.Completed)));
}
catch (PlaywrightException) when (!_page.IsClosed) { }
}
return result.DistinctBy(chapter => chapter.Id).ToArray();
}
public async Task OpenChapterAsync(ChapterInfo chapter, CancellationToken cancellationToken)
{
_lastDialog = null;
_questions.Clear();
_appliedChoices.Clear();
foreach (var frame in CurrentFrames())
{
var selector = $"#cur{CssEscape(chapter.Id)},[data-cx-chapter=\"{CssEscape(chapter.Id)}\"]";
var item = frame.Locator(selector).First;
try
{
if (await item.CountAsync() == 0) continue;
// The new catalog's own toOld() defines a signed navigation URL. Derive
// it from this live page rather than persisting an account-specific URL.
var navigation = await item.EvaluateAsync<string?>("""
el => {
const call=(el.getAttribute('onclick')||el.querySelector('[onclick*="toOld"]')?.getAttribute('onclick')||'').match(/toOld\('([^']+)',\s*'([^']+)',\s*'([^']+)'/);
if(!call)return null;
const scripts=Array.from(document.scripts).map(s=>s.textContent||'').join('\n');
const enc=scripts.match(/var\s+enc\s*=\s*"([^"]+)"/);
const cpi=scripts.match(/var\s+cpi\s*=\s*(\d+)/);
const host=window.ServerHost?.mooc1Domain;
if(!host||!enc||!cpi)return null;
const refer=new URL('/mycourse/studentstudy',host);
Object.entries({chapterId:call[2],courseId:call[1],clazzid:call[3],cpi:cpi[1],enc:enc[1],mooc2:'1',hidetype:'0',fanyaVersion:'0'}).forEach(([k,v])=>refer.searchParams.set(k,v));
const url=new URL('/mycourse/transfer',host);
Object.entries({moocId:call[1],clazzid:call[3],linkTime:String(Date.now()),ut:'s',refer:refer.href}).forEach(([k,v])=>url.searchParams.set(k,v));
return url.href;
}
""").WaitAsync(cancellationToken);
if (navigation is not null && IsAllowedUrl(navigation))
await _page.GotoAsync(navigation, new() { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 45000 }).WaitAsync(cancellationToken);
else
{
var title = item.Locator(".clicktitle,.posCatalog_name").First;
await (await title.CountAsync() > 0 ? title : item).ClickAsync(new() { Timeout = 10000 }).WaitAsync(cancellationToken);
}
await WaitForAsync(async () =>
{
var frames = CurrentFrames();
var cards = frames.Where(current => Uri.TryCreate(current.Url, UriKind.Absolute, out var url) &&
url.AbsolutePath.EndsWith("/knowledge/cards", StringComparison.OrdinalIgnoreCase)).ToArray();
// Old chapter media can remain visible during the asynchronous iframe swap.
// Require the selected chapter's actual task document before accepting it.
if (cards.Length > 0)
{
if (cards.Any(current => QueryValue(current.Url, "knowledgeid") != chapter.Id)) return false;
}
else if (QueryValue(_page.Url, "chapterId") != chapter.Id) return false;
foreach (var current in CurrentFrames())
if (await current.Locator("video,audio," + QuestionSelector).CountAsync() > 0) return true;
return (await GetDocumentsAsync(cancellationToken)).Count > 0;
}, 30000, cancellationToken);
return;
}
catch (PlaywrightException error) when (error.Message.Contains("detached", StringComparison.OrdinalIgnoreCase)) { }
}
throw new InvalidOperationException("当前页面没有找到所选章节,请返回课程并重新加载章节目录。");
}
private static string? QueryValue(string value, string name)
{
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) return null;
foreach (var pair in uri.Query.TrimStart('?').Split('&'))
{
var parts = pair.Split('=', 2);
if (Uri.UnescapeDataString(parts[0]).Equals(name, StringComparison.OrdinalIgnoreCase))
return parts.Length > 1 ? Uri.UnescapeDataString(parts[1]) : "";
}
return null;
}
public async Task<IReadOnlyList<VideoState>> GetVideosAsync(CancellationToken cancellationToken)
{
var result = new List<VideoState>();
foreach (var frame in CurrentFrames())
{
try
{
var key = FrameKey(frame);
var raw = await frame.Locator("video,audio").EvaluateAllAsync<JsonElement>("""
vs=>vs.map((v,index)=>({index,title:v.getAttribute('title')||document.title||'课程视频',
time:Number.isFinite(v.currentTime)?v.currentTime:0,duration:Number.isFinite(v.duration)?v.duration:0,
paused:v.paused,ended:v.ended,
meaningful:v.tagName==='VIDEO'||!!((v.getAttribute('src')||'').trim()||Array.from(v.querySelectorAll('source')).some(s=>(s.getAttribute('src')||'').trim()))}))
.filter(v=>v.meaningful)
""").WaitAsync(cancellationToken);
var videos = raw.Deserialize<VideoDto[]>(Json) ?? [];
var serverCompleted = false;
var objectId = QueryValue(frame.Url, "objectid");
if (frame.ParentFrame is { } parent)
{
var owner = await frame.FrameElementAsync().WaitAsync(cancellationToken);
try
{
var attribute = await owner.GetAttributeAsync("objectid").WaitAsync(cancellationToken);
if (!string.IsNullOrWhiteSpace(attribute)) objectId = attribute;
}
finally { await owner.DisposeAsync(); }
if (objectId is not null) serverCompleted = await parent.EvaluateAsync<bool>("""
id => typeof mArg !== 'undefined' && Array.isArray(mArg.attachments) &&
mArg.attachments.some(a=>a.type==='video' && a.isPassed===true &&
String(a.objectId||a.property?.objectid||'')===id)
""", objectId).WaitAsync(cancellationToken);
}
result.AddRange(videos.Select(video => new VideoState($"{key}-{video.Index}", video.Title, video.Time, video.Duration, video.Paused, video.Ended, key, video.Index, serverCompleted)));
}
catch (PlaywrightException) when (!_page.IsClosed) { }
}
return result;
}
public async Task PlayAsync(VideoState video, bool muted, CancellationToken cancellationToken)
{
var frame = RequireFrame(video.FrameKey);
var element = frame.Locator("video,audio").Nth(video.Index);
var attempt = await element.EvaluateAsync<JsonElement>("""
async (v,muted)=>{v.muted=muted;try{await v.play();return {ok:!v.paused,error:''}}catch(e){return {ok:false,error:e.name+': '+e.message}}}
""", muted).WaitAsync(cancellationToken);
if (!attempt.GetProperty("ok").GetBoolean())
{
var buttons = frame.Locator(".vjs-big-play-button,.vjs-play-control:not(.vjs-playing)")
.Or(frame.GetByRole(AriaRole.Button, new() { NameRegex = new Regex("^(播放视频|播放|Play Video|Play)$", RegexOptions.IgnoreCase) }));
var clicked = false;
for (var index = 0; index < await buttons.CountAsync(); index++)
if (await buttons.Nth(index).IsVisibleAsync())
{ await buttons.Nth(index).ClickAsync(new() { Timeout = 10000 }).WaitAsync(cancellationToken); clicked = true; break; }
if (!clicked) throw new InvalidOperationException("播放器尚未就绪且未找到可见播放按钮:" + attempt.GetProperty("error").GetString());
}
var before = video.CurrentTime;
await frame.WaitForFunctionAsync("""
({index,before})=>{const v=document.querySelectorAll('video,audio')[index];return v&&(v.ended||(!v.paused&&v.readyState>=2&&v.currentTime>before+.1))}
""", new { index = video.Index, before }, new() { Timeout = 20000 }).WaitAsync(cancellationToken);
}
public async Task<string> DownloadMediaAsync(VideoState video, string directory, CancellationToken cancellationToken)
{
var frame = RequireFrame(video.FrameKey);
var element = frame.Locator("video,audio").Nth(video.Index);
await frame.WaitForFunctionAsync("""
index=>{const v=document.querySelectorAll('video,audio')[index];return !!(v?.currentSrc||(v?.getAttribute('src')||'').trim())}
""", video.Index, new() { Timeout = 20000 }).WaitAsync(cancellationToken);
var source = await element.EvaluateAsync<string>("v=>v.currentSrc||v.src").WaitAsync(cancellationToken);
if (!Uri.TryCreate(source, UriKind.Absolute, out var sourceUri) ||
(sourceUri.Scheme != "https" && !(sourceUri.IsLoopback && sourceUri.Scheme == "http")))
throw new InvalidOperationException("当前媒体使用 blob/流式来源,不能通过直接媒体下载提取音轨。");
Directory.CreateDirectory(directory);
var suffix = Path.GetExtension(sourceUri.AbsolutePath).ToLowerInvariant();
if (suffix is not (".mp4" or ".mp3" or ".m4a" or ".wav" or ".webm")) suffix = ".mp4";
var file = Path.Combine(directory, $"media-{Guid.NewGuid():N}{suffix}");
var jar = new System.Net.CookieContainer();
foreach (var cookie in await _context.CookiesAsync([source]))
try { jar.Add(new System.Net.Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain) { Secure = cookie.Secure }); }
catch (System.Net.CookieException) { }
using var handler = new HttpClientHandler { CookieContainer = jar };
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromMinutes(10) };
using var request = new HttpRequestMessage(HttpMethod.Get, sourceUri);
request.Headers.Referrer = new Uri(frame.Url);
request.Headers.TryAddWithoutValidation("User-Agent", await frame.EvaluateAsync<string>("()=>navigator.userAgent"));
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"课程媒体下载失败(HTTP {(int)response.StatusCode})。");
const long maximum = 1024L * 1024 * 1024;
if (response.Content.Headers.ContentLength > maximum) throw new InvalidOperationException("单个课程媒体超过 1 GiB,已停止下载。");
await using var input = await response.Content.ReadAsStreamAsync(cancellationToken);
await using var output = new FileStream(file, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536, true);
var buffer = new byte[65536]; long total = 0; int read;
while ((read = await input.ReadAsync(buffer, cancellationToken)) > 0)
{
total += read; if (total > maximum) throw new InvalidOperationException("课程媒体超过下载上限。");
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
}
if (total < 44) throw new InvalidOperationException("课程媒体为空或不完整。");
return file;
}
public async Task PauseAllAsync(CancellationToken cancellationToken)
{
foreach (var frame in CurrentFrames())
try { await frame.Locator("video,audio").EvaluateAllAsync<object?>("vs=>{vs.forEach(v=>v.pause());return null}").WaitAsync(cancellationToken); }
catch (PlaywrightException) { }
}
public async Task<EvidenceFrame?> CaptureVideoAsync(VideoState video, string directory, CancellationToken cancellationToken)
{
var element = RequireFrame(video.FrameKey).Locator("video,audio").Nth(video.Index);
if (await element.EvaluateAsync<string>("e=>e.tagName") == "AUDIO") return null;
Directory.CreateDirectory(directory);
var file = Path.Combine(directory, $"frame-{DateTime.UtcNow:HHmmssfff}-{Guid.NewGuid():N}.jpg");
await element.ScreenshotAsync(new() { Path = file, Type = ScreenshotType.Jpeg, Quality = 75, Timeout = 12000 }).WaitAsync(cancellationToken);
return new(file, video.CurrentTime);
}
public async Task<string> ReadCaptionsAsync(CancellationToken cancellationToken)
{
var text = new List<string>();
foreach (var frame in CurrentFrames())
try
{
var captions = await frame.EvaluateAsync<string>("""
() => {
const cues=Array.from(document.querySelectorAll('video,audio')).flatMap(v=>Array.from(v.textTracks||[]).flatMap(t=>Array.from(t.activeCues||[]).map(c=>c.text||'')));
const visible=Array.from(document.querySelectorAll('.vjs-text-track-cue,.subtitle,.captions,[data-cx-caption]'))
.filter(e=>e.getBoundingClientRect().height>0).map(e=>e.innerText||e.textContent||'');
return [...new Set([...cues,...visible])].join('\n');
}
""").WaitAsync(cancellationToken);
if (!string.IsNullOrWhiteSpace(captions)) text.Add(captions);
}
catch (PlaywrightException) when (!_page.IsClosed) { }
return string.Join('\n', text.Distinct());
}
public async Task<string?> GetBlockerAsync(CancellationToken cancellationToken)
{
if (_lastDialog is { } dialog) return "站点提示:" + dialog;
if (_page.IsClosed) return "浏览器窗口已关闭。";
if (new Uri(_page.Url).Host.Contains("passport", StringComparison.OrdinalIgnoreCase)) return "登录已失效,请在内置浏览器中重新登录。";
foreach (var frame in CurrentFrames())
try
{
var blocker = await frame.EvaluateAsync<string?>("""
() => {
const visible=e=>e.getBoundingClientRect().width>0&&e.getBoundingClientRect().height>0&&getComputedStyle(e).visibility!=='hidden';
const captcha=Array.from(document.querySelectorAll('.yidun_popup,.yidun_panel,.geetest_panel,[id*="captcha"],[class*="captcha"]')).find(visible);
if(captcha)return '页面需要验证码,请在浏览器中完成后继续。';
const dialogs=Array.from(document.querySelectorAll('[role="dialog"],.layui-layer')).filter(visible);
return dialogs.find(e=>/人脸识别|身份验证|访问受限|账号异常/.test(e.innerText))?.innerText||null;
}
""").WaitAsync(cancellationToken);
if (blocker is not null) return blocker;
}
catch (PlaywrightException) when (!_page.IsClosed) { }
return null;
}
public async Task<IReadOnlyList<QuestionSnapshot>> GetQuestionsAsync(string directory, bool inlineOnly, CancellationToken cancellationToken)
{
var result = new List<QuestionSnapshot>();
Directory.CreateDirectory(directory);
foreach (var frame in CurrentFrames())
{
try
{
var inline = frame.Url.Contains("/modules/video/", StringComparison.OrdinalIgnoreCase) ||
await frame.Locator("[data-cx-inline]").CountAsync() > 0;
if (inlineOnly != inline) continue;
// Already-submitted chapter tests display questions too. Do not answer them again.
var submitted = await frame.EvaluateAsync<bool>("""
() => !!document.querySelector('[data-cx-submitted="true"]') ||
(!document.querySelector('.ZY_sub,.completeBtn,[data-cx-submit]') && /已提交|已完成|待批阅|批阅中/.test(document.body?.innerText||''))
""").WaitAsync(cancellationToken);
if (submitted) continue;
var roots = frame.Locator(QuestionSelector);
var count = await roots.CountAsync();
for (var index = 0; index < count; index++)
{
var root = roots.Nth(index);
if (!await root.IsVisibleAsync()) continue;
var raw = await root.EvaluateAsync<JsonElement>("""
e=>{
let options=Array.from(e.querySelectorAll('.Zy_ulTop>li'));
if(!options.length)options=Array.from(e.querySelectorAll('[data-cx-option],[role="radio"],[role="checkbox"],input[type="radio"],input[type="checkbox"]'));
const kind=e.getAttribute('typename')||e.querySelector('.newZy_TItle')?.textContent||e.dataset.kind||e.querySelector('[qtype]')?.getAttribute('qtype')||e.getAttribute('data')||'';
const id=e.dataset.cxQuestion||e.querySelector('[qid]')?.getAttribute('qid')||e.id||'';
return {id,kind,stem:(e.querySelector('.mark_name,.Zy_TItle,.fontLabel,[data-cx-stem]')?.textContent||e.textContent||'').trim(),
options:options.map((o,i)=>({key:o.dataset.cxOption||String.fromCharCode(65+i),
text:(o.querySelector('.answer_p,a')?.textContent||o.textContent||o.getAttribute('aria-label')||'').trim()})),
obfuscated:!!e.querySelector('.font-cxsecret')||e.classList.contains('font-cxsecret')};
}
""").WaitAsync(cancellationToken);
var data = raw.Deserialize<QuestionDto>(Json) ?? throw new InvalidOperationException("题目结构无法读取。");
var key = FrameKey(frame);
var id = $"{key}:{(data.Id.Length > 0 ? data.Id : index.ToString())}";
var image = Path.Combine(directory, $"question-{Guid.NewGuid():N}.png");
await root.ScreenshotAsync(new() { Path = image, Timeout = 15000 }).WaitAsync(cancellationToken);
result.Add(new(id, ParseKind(data.Kind), data.Stem, data.Options, key, index, image, data.Obfuscated, inline));
_questions[id] = (frame, index);
}
}
catch (PlaywrightException error) when (!_page.IsClosed && (error.Message.Contains("detached", StringComparison.OrdinalIgnoreCase) || error.Message.Contains("destroyed", StringComparison.OrdinalIgnoreCase))) { }
}
return result;
}
public async Task ApplyAnswersAsync(IReadOnlyList<QuestionSnapshot> questions, IReadOnlyList<AnswerProposal> answers, CancellationToken cancellationToken)
{
foreach (var question in questions)
{
cancellationToken.ThrowIfCancellationRequested();
if (!_questions.TryGetValue(question.Id, out var handle) || handle.Frame.IsDetached)
throw new InvalidOperationException("题目已经变化,请重新分析。");
var root = handle.Frame.Locator(QuestionSelector).Nth(handle.Index);
var answer = answers.Single(answer => answer.QuestionId == question.Id);
if (question.Kind is QuestionKind.Single or QuestionKind.Multiple or QuestionKind.TrueFalse)
{
var primary = root.Locator(".Zy_ulTop>li");
var options = await primary.CountAsync() > 0 ? primary : root.Locator("[data-cx-option],[role=radio],[role=checkbox],input[type=radio],input[type=checkbox]");
if (await options.CountAsync() != question.Options.Count) throw new InvalidOperationException("题目选项数量已改变,尚未执行答案。");
for (var index = 0; index < question.Options.Count; index++)
{
var option = options.Nth(index);
var key = question.Options[index].Key;
var desired = answer.Choices.Contains(key, StringComparer.OrdinalIgnoreCase);
var chosen = await option.EvaluateAsync<bool>(ChoiceSelectedScript, key).WaitAsync(cancellationToken);
if (desired != chosen)
{
await option.ClickAsync(new() { Timeout = 10000 }).WaitAsync(cancellationToken);
await WaitForAsync(async () => await option.EvaluateAsync<bool>(ChoiceSelectedScript, key) == desired, 5000, cancellationToken);
}
}
await VerifyChoicesAsync(question, answer.Choices, cancellationToken);
_appliedChoices[question.Id] = answer.Choices.ToArray();
}
else
{
var inputs = root.Locator("textarea,input[type=text],[contenteditable=true]");
var count = await inputs.CountAsync();
var parts = answer.Text.Split("||", StringSplitOptions.TrimEntries);
if (count == 0 || (count > 1 && parts.Length != count)) throw new InvalidOperationException("文本答题控件或填空数量不匹配,请手动检查。");
for (var index = 0; index < count; index++) await inputs.Nth(index).FillAsync(parts[index]).WaitAsync(cancellationToken);
}
}
}
private const string ChoiceSelectedScript = """
(e,key)=>{
if(typeof e.checked==='boolean')return e.checked;
const aria=e.getAttribute('aria-checked');if(aria==='true'||aria==='false')return aria==='true';
const selected=e.getAttribute('data-selected');if(selected==='true'||selected==='false')return selected==='true';
const root=e.closest('.questionLi,.TiMu,[data-cx-question]');
const actual=e.querySelector('.num_option[data],.num_option_dx[data]')?.getAttribute('data')||key;
const hidden=Array.from(root.querySelectorAll('input[type="hidden"][name^="answer"]')).map(i=>i.value).join(',');
return hidden.split(/[,;\s]+/).flatMap(s=>/^[A-Z]+$/.test(s)?s.split(''):[s]).includes(actual)||
!!e.querySelector('.check_answer,.check_answer_dx,.checked');
}
""";
private readonly Dictionary<string, string[]> _appliedChoices = new();
private async Task VerifyChoicesAsync(QuestionSnapshot question, IReadOnlyList<string> expected, CancellationToken token)
{
if (!_questions.TryGetValue(question.Id, out var handle) || handle.Frame.IsDetached)
throw new InvalidOperationException("题目已经变化,本任务未提交。");
var root = handle.Frame.Locator(QuestionSelector).Nth(handle.Index);
var primary = root.Locator(".Zy_ulTop>li");
var options = await primary.CountAsync() > 0 ? primary : root.Locator("[data-cx-option],[role=radio],[role=checkbox],input[type=radio],input[type=checkbox]");
if (await options.CountAsync() != question.Options.Count) throw new InvalidOperationException("选项数量已改变,本任务未提交。");
for (var index = 0; index < question.Options.Count; index++)
{
var key = question.Options[index].Key;
var actual = await options.Nth(index).EvaluateAsync<bool>(ChoiceSelectedScript, key).WaitAsync(token);
if (actual != expected.Contains(key, StringComparer.OrdinalIgnoreCase))
throw new InvalidOperationException($"题目 {question.Id} 的实际勾选状态与 Agent 答案不一致,本任务未提交。");
}
}
public async Task<QuizSubmission> SubmitAsync(IReadOnlyList<QuestionSnapshot> questions, CancellationToken cancellationToken)
{
double? score = null;
foreach (var group in questions.GroupBy(question => question.FrameKey))
{
var frame = RequireFrame(group.Key);
foreach (var question in group)
if (_appliedChoices.TryGetValue(question.Id, out var expected)) await VerifyChoicesAsync(question, expected, cancellationToken);
var submit = frame.GetByRole(AriaRole.Button, new() { NameRegex = new Regex("^(提交|提交答案|确认|确定|Submit)$", RegexOptions.IgnoreCase) }).First;
if (await submit.CountAsync() == 0) return new(false, false, "未找到当前题目的提交按钮,答案已填入,请手动检查。");
await submit.ClickAsync().WaitAsync(cancellationToken);
var confirmationClicked = false;
var confirmed = await WaitForAsync(async () =>
{
if (frame.IsDetached) return false;
if (!confirmationClicked)
{
foreach (var current in CurrentFrames())
{
var dialogs = current.Locator("[role=dialog],.layui-layer,.popDiv,.popbox");
for (var index = 0; index < await dialogs.CountAsync(); index++)
{
var dialog = dialogs.Nth(index);
if (!await dialog.IsVisibleAsync() || !(await dialog.InnerTextAsync()).Contains("提交")) continue;
var confirm = dialog.GetByRole(AriaRole.Button, new() { NameRegex = new Regex("^(确认提交|确定提交|确定|确认|提交)$") }).First;
if (await confirm.CountAsync() > 0 && await confirm.IsVisibleAsync())
{ await confirm.ClickAsync().WaitAsync(cancellationToken); confirmationClicked = true; break; }
}
if (confirmationClicked) break;
}
}
return await frame.EvaluateAsync<bool>("""
() => !!document.querySelector('[data-cx-submitted="true"]') ||
(location.pathname.endsWith('/mooc2/work/prompt') && /提交时间\s*[::]/.test(document.body?.innerText||'') &&
/(^|[\n\r])\s*\d+(?:\.\d+)?\s*分\s*($|[\n\r])|待批阅|待批改|批阅中/m.test(document.body?.innerText||'')) ||
/(^|[\n\r::·])\s*(提交成功|已提交|待批阅|待批改|批阅中|本次得分|本次成绩|已完成)(?=\s|[::·,。]|$)/m.test(document.querySelector('.newTestTitle,.TestTitle_name,[data-cx-result]')?.innerText||document.body?.innerText||'')
""") || (group.All(question => question.IsInline) && await frame.Locator(QuestionSelector).CountAsync() == 0);
}, 15000, cancellationToken, false);
if (!confirmed) return new(true, false, "已点击提交,但尚未收到明确的提交结果,本轮不再重复提交。");
await WaitForAsync(async () =>
{
if (frame.IsDetached) return true;
var resultText = await frame.Locator("body").InnerTextAsync(new() { Timeout = 3000 });
score = ParseScore(resultText);
return score is not null || resultText.Contains("待批阅") || resultText.Contains("批阅中");
}, 3000, cancellationToken, false);
}
return new(true, true, "页面已确认题目提交结果。" + (score is not null ? $" 本次成绩 {score:0.##} 分。" : ""), score);
}
public static double? ParseScore(string text)
{
var match = Regex.Match(text, @"本次(?:成绩|得分)\s*([\d]+(?:\.[\d]+)?)\s*分?");
if (!match.Success && Regex.IsMatch(text, @"提交时间\s*[::]")) match = Regex.Match(text, @"(?m)^\s*([\d]+(?:\.[\d]+)?)\s*分\s*$");
return match.Success && double.TryParse(match.Groups[1].Value, System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out var score) ? score : null;
}
public static QuestionKind ParseKind(string value) => value switch
{
"0" or "single" => QuestionKind.Single,
"1" or "multiple" => QuestionKind.Multiple,
"2" or "fill" => QuestionKind.FillBlank,
"3" or "judge" => QuestionKind.TrueFalse,
"4" or "short" => QuestionKind.ShortAnswer,
_ when value.Contains("多选") => QuestionKind.Multiple,
_ when value.Contains("单选") => QuestionKind.Single,
_ when value.Contains("判断") => QuestionKind.TrueFalse,
_ when value.Contains("填空") => QuestionKind.FillBlank,
_ when value.Contains("简答") => QuestionKind.ShortAnswer,
_ => QuestionKind.Unknown,
};
public static bool IsAllowedUrl(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) &&
((uri.Scheme == "https" && (uri.Host.Equals("chaoxing.com", StringComparison.OrdinalIgnoreCase) || uri.Host.EndsWith(".chaoxing.com", StringComparison.OrdinalIgnoreCase))) ||
(uri.IsLoopback && uri.Scheme is "http" or "https"));
private static string CssEscape(string value) => Regex.Replace(value, "[^a-zA-Z0-9_-]", "");
private static async Task<bool> WaitForAsync(Func<Task<bool>> condition, int timeout, CancellationToken token, bool throwOnTimeout = true)
{
var until = DateTime.UtcNow.AddMilliseconds(timeout);
while (DateTime.UtcNow < until)
{
token.ThrowIfCancellationRequested();
try { if (await condition()) return true; } catch (PlaywrightException) { }
await Task.Delay(250, token);
}
if (throwOnTimeout) throw new TimeoutException("页面在规定时间内未出现预期状态,请检查登录和页面内容。");
return false;
}
private void OnResponse(object? sender, IResponse response) { if (!Owns(response.Request)) return; _network.Enqueue(JsonSerializer.Serialize(new
{ time = DateTimeOffset.Now, method = response.Request.Method, url = RedactUrl(response.Url), status = response.Status, type = response.Request.ResourceType })); }
private void OnRequestFailed(object? sender, IRequest request) { if (!Owns(request)) return; _network.Enqueue(JsonSerializer.Serialize(new
{ time = DateTimeOffset.Now, method = request.Method, url = RedactUrl(request.Url), failure = request.Failure, type = request.ResourceType })); }
private bool Owns(IRequest request) { try { return ReferenceEquals(request.Frame.Page, _page); } catch (PlaywrightException) { return false; } }
private async void OnDialog(object? sender, IDialog dialog)
{
_lastDialog = dialog.Message;
try { await dialog.DismissAsync(); } catch (PlaywrightException) { }
}
public static string RedactUrl(string value)
{
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) return "[invalid URL]";
var path = uri.GetLeftPart(UriPartial.Path);
if (uri.Query.Length == 0) return path;
return path + "?" + string.Join('&', uri.Query.TrimStart('?').Split('&').Select(pair => pair.Split('=')[0] + "=[hidden]"));
}
private async Task WriteNetworkAsync()
{
await using var stream = new StreamWriter(NetworkFile, append: true) { AutoFlush = true };
while (!_networkStop.IsCancellationRequested || !_network.IsEmpty)
{
while (_network.TryDequeue(out var entry)) await stream.WriteLineAsync(entry);
if (!_networkStop.IsCancellationRequested) await Task.Delay(300);
}
}
public async ValueTask DisposeAsync()
{
_context.Response -= OnResponse; _context.RequestFailed -= OnRequestFailed;
_page.Dialog -= OnDialog;
_networkStop.Cancel(); await _networkWriter; _networkStop.Dispose();
}
private sealed record CourseDto(string Id, string Title, string Url);
private sealed record ChapterDto(string Id, string Title, bool Completed);
private sealed record VideoDto(int Index, string Title, double Time, double Duration, bool Paused, bool Ended);
private sealed record QuestionDto(string Id, string Kind, string Stem, QuestionOption[] Options, bool Obfuscated);
}
using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.RegularExpressions;
using ChaoXingAutoClass.Core;
using Microsoft.Playwright;
namespace ChaoXingAutoClass.Browser;
public sealed partial class ChaoxingBrowser : ICourseBrowser, IHomeworkBrowser, ILessonDocumentBrowser, IMediaDownloader, IAsyncDisposable
{
private readonly IBrowserContext _context;
private readonly IPage _page;
private readonly Dictionary<IFrame, string> _frames = new(ReferenceEqualityComparer.Instance);
private readonly Dictionary<string, IFrame> _frameByKey = new();
private readonly Dictionary<string, (IFrame Frame, int Index)> _questions = new();
private readonly ConcurrentQueue<string> _network = new();
private readonly CancellationTokenSource _networkStop = new();
private readonly Task _networkWriter;
private int _frameSequence;
private string? _lastDialog;
private const string QuestionSelector = ".TiMu:not(:has(.questionLi)), .questionLi, [data-cx-question]";
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { PropertyNameCaseInsensitive = true };
public IPage Page => _page;
public string NetworkFile { get; }
public ChaoxingBrowser(IBrowserContext context, IPage page, string networkFile)
{
_context = context; _page = page; NetworkFile = networkFile;
Directory.CreateDirectory(Path.GetDirectoryName(networkFile)!);
context.Response += OnResponse;
context.RequestFailed += OnRequestFailed;
page.Dialog += OnDialog;
_networkWriter = WriteNetworkAsync();
}
private string FrameKey(IFrame frame)
{
if (!_frames.TryGetValue(frame, out var key))
{ key = $"frame-{++_frameSequence:D5}"; _frames.Add(frame, key); _frameByKey[key] = frame; }
return key;
}
private IFrame RequireFrame(string key) => _frameByKey.TryGetValue(key, out var frame) && !frame.IsDetached
? frame : throw new InvalidOperationException("页面已导航,原播放器或题目已失效,请重新扫描。");
private IFrame[] CurrentFrames() => _page.Frames.Where(frame => !frame.IsDetached).ToArray();
public async Task<IReadOnlyList<CourseInfo>> GetCoursesAsync(CancellationToken cancellationToken)
{
var result = new List<CourseInfo>();
foreach (var frame in CurrentFrames())
{
try
{
var raw = await frame.EvaluateAsync<JsonElement>("""
() => Array.from(document.querySelectorAll('a[href*="stucoursemiddle"],a[href*="/mycourse/stu?"],a[data-cx-course]'))
.map(a => ({id:new URL(a.href).searchParams.get('courseid')||a.dataset.cxCourse||a.href,
title:(a.querySelector('[title]')?.getAttribute('title')||a.textContent||a.title||'').trim(),url:a.href}))
.filter(a=>a.title&&a.url.startsWith('http'))
""").WaitAsync(cancellationToken);
var items = raw.Deserialize<CourseDto[]>(Json) ?? [];
result.AddRange(items.Where(item => IsAllowedUrl(item.Url)).Select(item => new CourseInfo(item.Id, item.Title, item.Url)));
}
catch (PlaywrightException) when (!_page.IsClosed) { }
}
return result.DistinctBy(course => course.Url).ToArray();
}
public async Task OpenCourseAsync(CourseInfo course, CancellationToken cancellationToken)
{
_lastDialog = null;
_appliedChoices.Clear();
if (!IsAllowedUrl(course.Url)) throw new InvalidOperationException("课程链接不属于学习通或本地演示站点。");
await _page.GotoAsync(course.Url, new() { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 45000 }).WaitAsync(cancellationToken);
await WaitForAsync(async () => (await GetChaptersAsync(cancellationToken)).Count > 0 ||
await _page.GetByText("章节", new() { Exact = true }).CountAsync() > 0, 20000, cancellationToken);
if ((await GetChaptersAsync(cancellationToken)).Count == 0)
{
var menu = _page.GetByText("章节", new() { Exact = true });
if (await menu.CountAsync() == 1) await menu.ClickAsync().WaitAsync(cancellationToken);
await WaitForAsync(async () => (await GetChaptersAsync(cancellationToken)).Count > 0, 15000, cancellationToken, false);
}
}
public async Task<IReadOnlyList<ChapterInfo>> GetChaptersAsync(CancellationToken cancellationToken)
{
var result = new List<ChapterInfo>();
foreach (var frame in CurrentFrames())
{
try
{
var raw = await frame.EvaluateAsync<JsonElement>("""
() => Array.from(document.querySelectorAll('.chapter_item[id^="cur"],.posCatalog_select[id^="cur"],[data-cx-chapter]'))
.map(e=>({id:e.dataset.cxChapter||e.id.replace(/^cur/,''),
title:(e.querySelector('.catalog_name,.posCatalog_name')?.textContent||e.getAttribute('title')||e.textContent||'').trim().replace(/\s+/g,' '),
completed:e.dataset.completed==='true'||e.classList.contains('cx-completed')||
Array.from(e.querySelectorAll('.bntHoverTips')).some(s=>s.textContent.trim()==='已完成')||
(!!e.querySelector('.catalog_points_yi,.catalog_jindu,.orangeNew')&&/^\s*0\s*$/.test(e.querySelector('.catalog_points_yi,.catalog_jindu,.orangeNew').textContent))}))
""").WaitAsync(cancellationToken);
var chapters = raw.Deserialize<ChapterDto[]>(Json) ?? [];
result.AddRange(chapters.Select(chapter => new ChapterInfo(chapter.Id, chapter.Title, chapter.Completed)));
}
catch (PlaywrightException) when (!_page.IsClosed) { }
}
return result.DistinctBy(chapter => chapter.Id).ToArray();
}
public async Task OpenChapterAsync(ChapterInfo chapter, CancellationToken cancellationToken)
{
_lastDialog = null;
_questions.Clear();
_appliedChoices.Clear();
foreach (var frame in CurrentFrames())
{
var selector = $"#cur{CssEscape(chapter.Id)},[data-cx-chapter=\"{CssEscape(chapter.Id)}\"]";
var item = frame.Locator(selector).First;
try
{
if (await item.CountAsync() == 0) continue;
// The new catalog's own toOld() defines a signed navigation URL. Derive
// it from this live page rather than persisting an account-specific URL.
var navigation = await item.EvaluateAsync<string?>("""
el => {
const call=(el.getAttribute('onclick')||el.querySelector('[onclick*="toOld"]')?.getAttribute('onclick')||'').match(/toOld\('([^']+)',\s*'([^']+)',\s*'([^']+)'/);
if(!call)return null;
const scripts=Array.from(document.scripts).map(s=>s.textContent||'').join('\n');
const enc=scripts.match(/var\s+enc\s*=\s*"([^"]+)"/);
const cpi=scripts.match(/var\s+cpi\s*=\s*(\d+)/);
const host=window.ServerHost?.mooc1Domain;
if(!host||!enc||!cpi)return null;
const refer=new URL('/mycourse/studentstudy',host);
Object.entries({chapterId:call[2],courseId:call[1],clazzid:call[3],cpi:cpi[1],enc:enc[1],mooc2:'1',hidetype:'0',fanyaVersion:'0'}).forEach(([k,v])=>refer.searchParams.set(k,v));
const url=new URL('/mycourse/transfer',host);
Object.entries({moocId:call[1],clazzid:call[3],linkTime:String(Date.now()),ut:'s',refer:refer.href}).forEach(([k,v])=>url.searchParams.set(k,v));
return url.href;
}
""").WaitAsync(cancellationToken);
if (navigation is not null && IsAllowedUrl(navigation))
await _page.GotoAsync(navigation, new() { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 45000 }).WaitAsync(cancellationToken);
else
{
var title = item.Locator(".clicktitle,.posCatalog_name").First;
await (await title.CountAsync() > 0 ? title : item).ClickAsync(new() { Timeout = 10000 }).WaitAsync(cancellationToken);
}
await WaitForAsync(async () =>
{
var frames = CurrentFrames();
var cards = frames.Where(current => Uri.TryCreate(current.Url, UriKind.Absolute, out var url) &&
url.AbsolutePath.EndsWith("/knowledge/cards", StringComparison.OrdinalIgnoreCase)).ToArray();
// Old chapter media can remain visible during the asynchronous iframe swap.
// Require the selected chapter's actual task document before accepting it.
if (cards.Length > 0)
{
if (cards.Any(current => QueryValue(current.Url, "knowledgeid") != chapter.Id)) return false;
}
else if (QueryValue(_page.Url, "chapterId") != chapter.Id) return false;
foreach (var current in CurrentFrames())
if (await current.Locator("video,audio," + QuestionSelector).CountAsync() > 0) return true;
return (await GetDocumentsAsync(cancellationToken)).Count > 0;
}, 30000, cancellationToken);
return;
}
catch (PlaywrightException error) when (error.Message.Contains("detached", StringComparison.OrdinalIgnoreCase)) { }
}
throw new InvalidOperationException("当前页面没有找到所选章节,请返回课程并重新加载章节目录。");
}
private static string? QueryValue(string value, string name)
{
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) return null;
foreach (var pair in uri.Query.TrimStart('?').Split('&'))
{
var parts = pair.Split('=', 2);
if (Uri.UnescapeDataString(parts[0]).Equals(name, StringComparison.OrdinalIgnoreCase))
return parts.Length > 1 ? Uri.UnescapeDataString(parts[1]) : "";
}
return null;
}
public async Task<IReadOnlyList<VideoState>> GetVideosAsync(CancellationToken cancellationToken)
{
var result = new List<VideoState>();
foreach (var frame in CurrentFrames())
{
try
{
var key = FrameKey(frame);
var raw = await frame.Locator("video,audio").EvaluateAllAsync<JsonElement>("""
vs=>vs.map((v,index)=>({index,title:v.getAttribute('title')||document.title||'课程视频',
time:Number.isFinite(v.currentTime)?v.currentTime:0,duration:Number.isFinite(v.duration)?v.duration:0,
paused:v.paused,ended:v.ended,
meaningful:v.tagName==='VIDEO'||!!((v.getAttribute('src')||'').trim()||Array.from(v.querySelectorAll('source')).some(s=>(s.getAttribute('src')||'').trim()))}))
.filter(v=>v.meaningful)
""").WaitAsync(cancellationToken);
var videos = raw.Deserialize<VideoDto[]>(Json) ?? [];
var serverCompleted = false;
var objectId = QueryValue(frame.Url, "objectid");
if (frame.ParentFrame is { } parent)
{
var owner = await frame.FrameElementAsync().WaitAsync(cancellationToken);
try
{
var attribute = await owner.GetAttributeAsync("objectid").WaitAsync(cancellationToken);
if (!string.IsNullOrWhiteSpace(attribute)) objectId = attribute;
}
finally { await owner.DisposeAsync(); }
if (objectId is not null) serverCompleted = await parent.EvaluateAsync<bool>("""
id => typeof mArg !== 'undefined' && Array.isArray(mArg.attachments) &&
mArg.attachments.some(a=>a.type==='video' && a.isPassed===true &&
String(a.objectId||a.property?.objectid||'')===id)
""", objectId).WaitAsync(cancellationToken);
}
result.AddRange(videos.Select(video => new VideoState($"{key}-{video.Index}", video.Title, video.Time, video.Duration, video.Paused, video.Ended, key, video.Index, serverCompleted)));
}
catch (PlaywrightException) when (!_page.IsClosed) { }
}
return result;
}
public async Task PlayAsync(VideoState video, bool muted, CancellationToken cancellationToken)
{
var frame = RequireFrame(video.FrameKey);
var element = frame.Locator("video,audio").Nth(video.Index);
var attempt = await element.EvaluateAsync<JsonElement>("""
async (v,muted)=>{v.muted=muted;try{await v.play();return {ok:!v.paused,error:''}}catch(e){return {ok:false,error:e.name+': '+e.message}}}
""", muted).WaitAsync(cancellationToken);
if (!attempt.GetProperty("ok").GetBoolean())
{
var buttons = frame.Locator(".vjs-big-play-button,.vjs-play-control:not(.vjs-playing)")
.Or(frame.GetByRole(AriaRole.Button, new() { NameRegex = new Regex("^(播放视频|播放|Play Video|Play)$", RegexOptions.IgnoreCase) }));
var clicked = false;
for (var index = 0; index < await buttons.CountAsync(); index++)
if (await buttons.Nth(index).IsVisibleAsync())
{ await buttons.Nth(index).ClickAsync(new() { Timeout = 10000 }).WaitAsync(cancellationToken); clicked = true; break; }
if (!clicked) throw new InvalidOperationException("播放器尚未就绪且未找到可见播放按钮:" + attempt.GetProperty("error").GetString());
}
var before = video.CurrentTime;
await frame.WaitForFunctionAsync("""
({index,before})=>{const v=document.querySelectorAll('video,audio')[index];return v&&(v.ended||(!v.paused&&v.readyState>=2&&v.currentTime>before+.1))}
""", new { index = video.Index, before }, new() { Timeout = 20000 }).WaitAsync(cancellationToken);
}
public async Task<string> DownloadMediaAsync(VideoState video, string directory, CancellationToken cancellationToken)
{
var frame = RequireFrame(video.FrameKey);
var element = frame.Locator("video,audio").Nth(video.Index);
await frame.WaitForFunctionAsync("""
index=>{const v=document.querySelectorAll('video,audio')[index];return !!(v?.currentSrc||(v?.getAttribute('src')||'').trim())}
""", video.Index, new() { Timeout = 20000 }).WaitAsync(cancellationToken);
var source = await element.EvaluateAsync<string>("v=>v.currentSrc||v.src").WaitAsync(cancellationToken);
if (!Uri.TryCreate(source, UriKind.Absolute, out var sourceUri) ||
(sourceUri.Scheme != "https" && !(sourceUri.IsLoopback && sourceUri.Scheme == "http")))
throw new InvalidOperationException("当前媒体使用 blob/流式来源,不能通过直接媒体下载提取音轨。");
Directory.CreateDirectory(directory);
var suffix = Path.GetExtension(sourceUri.AbsolutePath).ToLowerInvariant();
if (suffix is not (".mp4" or ".mp3" or ".m4a" or ".wav" or ".webm")) suffix = ".mp4";
var file = Path.Combine(directory, $"media-{Guid.NewGuid():N}{suffix}");
var jar = new System.Net.CookieContainer();
foreach (var cookie in await _context.CookiesAsync([source]))
try { jar.Add(new System.Net.Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain) { Secure = cookie.Secure }); }
catch (System.Net.CookieException) { }
using var handler = new HttpClientHandler { CookieContainer = jar };
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromMinutes(10) };
using var request = new HttpRequestMessage(HttpMethod.Get, sourceUri);
request.Headers.Referrer = new Uri(frame.Url);
request.Headers.TryAddWithoutValidation("User-Agent", await frame.EvaluateAsync<string>("()=>navigator.userAgent"));
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"课程媒体下载失败(HTTP {(int)response.StatusCode})。");
const long maximum = 1024L * 1024 * 1024;
if (response.Content.Headers.ContentLength > maximum) throw new InvalidOperationException("单个课程媒体超过 1 GiB,已停止下载。");
await using var input = await response.Content.ReadAsStreamAsync(cancellationToken);
await using var output = new FileStream(file, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536, true);
var buffer = new byte[65536]; long total = 0; int read;
while ((read = await input.ReadAsync(buffer, cancellationToken)) > 0)
{
total += read; if (total > maximum) throw new InvalidOperationException("课程媒体超过下载上限。");
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
}
if (total < 44) throw new InvalidOperationException("课程媒体为空或不完整。");
return file;
}
public async Task PauseAllAsync(CancellationToken cancellationToken)
{
foreach (var frame in CurrentFrames())
try { await frame.Locator("video,audio").EvaluateAllAsync<object?>("vs=>{vs.forEach(v=>v.pause());return null}").WaitAsync(cancellationToken); }
catch (PlaywrightException) { }
}
public async Task<EvidenceFrame?> CaptureVideoAsync(VideoState video, string directory, CancellationToken cancellationToken)
{
var element = RequireFrame(video.FrameKey).Locator("video,audio").Nth(video.Index);
if (await element.EvaluateAsync<string>("e=>e.tagName") == "AUDIO") return null;
Directory.CreateDirectory(directory);
var file = Path.Combine(directory, $"frame-{DateTime.UtcNow:HHmmssfff}-{Guid.NewGuid():N}.jpg");
await element.ScreenshotAsync(new() { Path = file, Type = ScreenshotType.Jpeg, Quality = 75, Timeout = 12000 }).WaitAsync(cancellationToken);
return new(file, video.CurrentTime);
}
public async Task<string> ReadCaptionsAsync(CancellationToken cancellationToken)
{
var text = new List<string>();
foreach (var frame in CurrentFrames())
try
{
var captions = await frame.EvaluateAsync<string>("""
() => {
const cues=Array.from(document.querySelectorAll('video,audio')).flatMap(v=>Array.from(v.textTracks||[]).flatMap(t=>Array.from(t.activeCues||[]).map(c=>c.text||'')));
const visible=Array.from(document.querySelectorAll('.vjs-text-track-cue,.subtitle,.captions,[data-cx-caption]'))
.filter(e=>e.getBoundingClientRect().height>0).map(e=>e.innerText||e.textContent||'');
return [...new Set([...cues,...visible])].join('\n');
}
""").WaitAsync(cancellationToken);
if (!string.IsNullOrWhiteSpace(captions)) text.Add(captions);
}
catch (PlaywrightException) when (!_page.IsClosed) { }
return string.Join('\n', text.Distinct());
}
public async Task<string?> GetBlockerAsync(CancellationToken cancellationToken)
{
if (_lastDialog is { } dialog) return "站点提示:" + dialog;
if (_page.IsClosed) return "浏览器窗口已关闭。";
if (new Uri(_page.Url).Host.Contains("passport", StringComparison.OrdinalIgnoreCase)) return "登录已失效,请在内置浏览器中重新登录。";
foreach (var frame in CurrentFrames())
try
{
var blocker = await frame.EvaluateAsync<string?>("""
() => {
const visible=e=>e.getBoundingClientRect().width>0&&e.getBoundingClientRect().height>0&&getComputedStyle(e).visibility!=='hidden';
const captcha=Array.from(document.querySelectorAll('.yidun_popup,.yidun_panel,.geetest_panel,[id*="captcha"],[class*="captcha"]')).find(visible);
if(captcha)return '页面需要验证码,请在浏览器中完成后继续。';
const dialogs=Array.from(document.querySelectorAll('[role="dialog"],.layui-layer')).filter(visible);
return dialogs.find(e=>/人脸识别|身份验证|访问受限|账号异常/.test(e.innerText))?.innerText||null;
}
""").WaitAsync(cancellationToken);
if (blocker is not null) return blocker;
}
catch (PlaywrightException) when (!_page.IsClosed) { }
return null;
}
public async Task<IReadOnlyList<QuestionSnapshot>> GetQuestionsAsync(string directory, bool inlineOnly, CancellationToken cancellationToken)
{
var result = new List<QuestionSnapshot>();
Directory.CreateDirectory(directory);
foreach (var frame in CurrentFrames())
{
try
{
var inline = frame.Url.Contains("/modules/video/", StringComparison.OrdinalIgnoreCase) ||
await frame.Locator("[data-cx-inline]").CountAsync() > 0;
if (inlineOnly != inline) continue;
// Already-submitted chapter tests display questions too. Do not answer them again.
var submitted = await frame.EvaluateAsync<bool>("""
() => !!document.querySelector('[data-cx-submitted="true"]') ||
(!document.querySelector('.ZY_sub,.completeBtn,[data-cx-submit]') && /已提交|已完成|待批阅|批阅中/.test(document.body?.innerText||''))
""").WaitAsync(cancellationToken);
if (submitted) continue;
var roots = frame.Locator(QuestionSelector);
var count = await roots.CountAsync();
for (var index = 0; index < count; index++)
{
var root = roots.Nth(index);
if (!await root.IsVisibleAsync()) continue;
var raw = await root.EvaluateAsync<JsonElement>("""
e=>{
let options=Array.from(e.querySelectorAll('.Zy_ulTop>li'));
if(!options.length)options=Array.from(e.querySelectorAll('[data-cx-option],[role="radio"],[role="checkbox"],input[type="radio"],input[type="checkbox"]'));
const kind=e.getAttribute('typename')||e.querySelector('.newZy_TItle')?.textContent||e.dataset.kind||e.querySelector('[qtype]')?.getAttribute('qtype')||e.getAttribute('data')||'';
const id=e.dataset.cxQuestion||e.querySelector('[qid]')?.getAttribute('qid')||e.id||'';
return {id,kind,stem:(e.querySelector('.mark_name,.Zy_TItle,.fontLabel,[data-cx-stem]')?.textContent||e.textContent||'').trim(),
options:options.map((o,i)=>({key:o.dataset.cxOption||String.fromCharCode(65+i),
text:(o.querySelector('.answer_p,a')?.textContent||o.textContent||o.getAttribute('aria-label')||'').trim()})),
obfuscated:!!e.querySelector('.font-cxsecret')||e.classList.contains('font-cxsecret')};
}
""").WaitAsync(cancellationToken);
var data = raw.Deserialize<QuestionDto>(Json) ?? throw new InvalidOperationException("题目结构无法读取。");
var key = FrameKey(frame);
var id = $"{key}:{(data.Id.Length > 0 ? data.Id : index.ToString())}";
var image = Path.Combine(directory, $"question-{Guid.NewGuid():N}.png");
await root.ScreenshotAsync(new() { Path = image, Timeout = 15000 }).WaitAsync(cancellationToken);
result.Add(new(id, ParseKind(data.Kind), data.Stem, data.Options, key, index, image, data.Obfuscated, inline));
_questions[id] = (frame, index);
}
}
catch (PlaywrightException error) when (!_page.IsClosed && (error.Message.Contains("detached", StringComparison.OrdinalIgnoreCase) || error.Message.Contains("destroyed", StringComparison.OrdinalIgnoreCase))) { }
}
return result;
}
public async Task ApplyAnswersAsync(IReadOnlyList<QuestionSnapshot> questions, IReadOnlyList<AnswerProposal> answers, CancellationToken cancellationToken)
{
foreach (var question in questions)
{
cancellationToken.ThrowIfCancellationRequested();
if (!_questions.TryGetValue(question.Id, out var handle) || handle.Frame.IsDetached)
throw new InvalidOperationException("题目已经变化,请重新分析。");
var root = handle.Frame.Locator(QuestionSelector).Nth(handle.Index);
var answer = answers.Single(answer => answer.QuestionId == question.Id);
if (question.Kind is QuestionKind.Single or QuestionKind.Multiple or QuestionKind.TrueFalse)
{
var primary = root.Locator(".Zy_ulTop>li");
var options = await primary.CountAsync() > 0 ? primary : root.Locator("[data-cx-option],[role=radio],[role=checkbox],input[type=radio],input[type=checkbox]");
if (await options.CountAsync() != question.Options.Count) throw new InvalidOperationException("题目选项数量已改变,尚未执行答案。");
for (var index = 0; index < question.Options.Count; index++)
{
var option = options.Nth(index);
var key = question.Options[index].Key;
var desired = answer.Choices.Contains(key, StringComparer.OrdinalIgnoreCase);
var chosen = await option.EvaluateAsync<bool>(ChoiceSelectedScript, key).WaitAsync(cancellationToken);
if (desired != chosen)
{
await option.ClickAsync(new() { Timeout = 10000 }).WaitAsync(cancellationToken);
await WaitForAsync(async () => await option.EvaluateAsync<bool>(ChoiceSelectedScript, key) == desired, 5000, cancellationToken);
}
}
await VerifyChoicesAsync(question, answer.Choices, cancellationToken);
_appliedChoices[question.Id] = answer.Choices.ToArray();
}
else
{
var inputs = root.Locator("textarea,input[type=text],[contenteditable=true]");
var count = await inputs.CountAsync();
var parts = answer.Text.Split("||", StringSplitOptions.TrimEntries);
if (count == 0 || (count > 1 && parts.Length != count)) throw new InvalidOperationException("文本答题控件或填空数量不匹配,请手动检查。");
for (var index = 0; index < count; index++) await inputs.Nth(index).FillAsync(parts[index]).WaitAsync(cancellationToken);
}
}
}
private const string ChoiceSelectedScript = """
(e,key)=>{
if(typeof e.checked==='boolean')return e.checked;
const aria=e.getAttribute('aria-checked');if(aria==='true'||aria==='false')return aria==='true';
const selected=e.getAttribute('data-selected');if(selected==='true'||selected==='false')return selected==='true';
const root=e.closest('.questionLi,.TiMu,[data-cx-question]');
const actual=e.querySelector('.num_option[data],.num_option_dx[data]')?.getAttribute('data')||key;
const hidden=Array.from(root.querySelectorAll('input[type="hidden"][name^="answer"]')).map(i=>i.value).join(',');
return hidden.split(/[,;\s]+/).flatMap(s=>/^[A-Z]+$/.test(s)?s.split(''):[s]).includes(actual)||
!!e.querySelector('.check_answer,.check_answer_dx,.checked');
}
""";
private readonly Dictionary<string, string[]> _appliedChoices = new();
private async Task VerifyChoicesAsync(QuestionSnapshot question, IReadOnlyList<string> expected, CancellationToken token)
{
if (!_questions.TryGetValue(question.Id, out var handle) || handle.Frame.IsDetached)
throw new InvalidOperationException("题目已经变化,本任务未提交。");
var root = handle.Frame.Locator(QuestionSelector).Nth(handle.Index);
var primary = root.Locator(".Zy_ulTop>li");
var options = await primary.CountAsync() > 0 ? primary : root.Locator("[data-cx-option],[role=radio],[role=checkbox],input[type=radio],input[type=checkbox]");
if (await options.CountAsync() != question.Options.Count) throw new InvalidOperationException("选项数量已改变,本任务未提交。");
for (var index = 0; index < question.Options.Count; index++)
{
var key = question.Options[index].Key;
var actual = await options.Nth(index).EvaluateAsync<bool>(ChoiceSelectedScript, key).WaitAsync(token);
if (actual != expected.Contains(key, StringComparer.OrdinalIgnoreCase))
throw new InvalidOperationException($"题目 {question.Id} 的实际勾选状态与 Agent 答案不一致,本任务未提交。");
}
}
public async Task<QuizSubmission> SubmitAsync(IReadOnlyList<QuestionSnapshot> questions, CancellationToken cancellationToken)
{
double? score = null;
foreach (var group in questions.GroupBy(question => question.FrameKey))
{
var frame = RequireFrame(group.Key);
foreach (var question in group)
if (_appliedChoices.TryGetValue(question.Id, out var expected)) await VerifyChoicesAsync(question, expected, cancellationToken);
var submit = frame.GetByRole(AriaRole.Button, new() { NameRegex = new Regex("^(提交|提交答案|确认|确定|Submit)$", RegexOptions.IgnoreCase) }).First;
if (await submit.CountAsync() == 0) return new(false, false, "未找到当前题目的提交按钮,答案已填入,请手动检查。");
await submit.ClickAsync().WaitAsync(cancellationToken);
var confirmationClicked = false;
var confirmed = await WaitForAsync(async () =>
{
if (frame.IsDetached) return false;
if (!confirmationClicked)
{
foreach (var current in CurrentFrames())
{
var dialogs = current.Locator("[role=dialog],.layui-layer,.popDiv,.popbox");
for (var index = 0; index < await dialogs.CountAsync(); index++)
{
var dialog = dialogs.Nth(index);
if (!await dialog.IsVisibleAsync() || !(await dialog.InnerTextAsync()).Contains("提交")) continue;
var confirm = dialog.GetByRole(AriaRole.Button, new() { NameRegex = new Regex("^(确认提交|确定提交|确定|确认|提交)$") }).First;
if (await confirm.CountAsync() > 0 && await confirm.IsVisibleAsync())
{ await confirm.ClickAsync().WaitAsync(cancellationToken); confirmationClicked = true; break; }
}
if (confirmationClicked) break;
}
}
return await frame.EvaluateAsync<bool>("""
() => !!document.querySelector('[data-cx-submitted="true"]') ||
(location.pathname.endsWith('/mooc2/work/prompt') && /提交时间\s*[::]/.test(document.body?.innerText||'') &&
/(^|[\n\r])\s*\d+(?:\.\d+)?\s*分\s*($|[\n\r])|待批阅|待批改|批阅中/m.test(document.body?.innerText||'')) ||
/(^|[\n\r::·])\s*(提交成功|已提交|待批阅|待批改|批阅中|本次得分|本次成绩|已完成)(?=\s|[::·,。]|$)/m.test(document.querySelector('.newTestTitle,.TestTitle_name,[data-cx-result]')?.innerText||document.body?.innerText||'')
""") || (group.All(question => question.IsInline) && await frame.Locator(QuestionSelector).CountAsync() == 0);
}, 15000, cancellationToken, false);
if (!confirmed) return new(true, false, "已点击提交,但尚未收到明确的提交结果,本轮不再重复提交。");
await WaitForAsync(async () =>
{
if (frame.IsDetached) return true;
var resultText = await frame.Locator("body").InnerTextAsync(new() { Timeout = 3000 });
score = ParseScore(resultText);
return score is not null || resultText.Contains("待批阅") || resultText.Contains("批阅中");
}, 3000, cancellationToken, false);
}
return new(true, true, "页面已确认题目提交结果。" + (score is not null ? $" 本次成绩 {score:0.##} 分。" : ""), score);
}
public static double? ParseScore(string text)
{
var match = Regex.Match(text, @"本次(?:成绩|得分)\s*([\d]+(?:\.[\d]+)?)\s*分?");
if (!match.Success && Regex.IsMatch(text, @"提交时间\s*[::]")) match = Regex.Match(text, @"(?m)^\s*([\d]+(?:\.[\d]+)?)\s*分\s*$");
return match.Success && double.TryParse(match.Groups[1].Value, System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out var score) ? score : null;
}
public static QuestionKind ParseKind(string value) => value switch
{
"0" or "single" => QuestionKind.Single,
"1" or "multiple" => QuestionKind.Multiple,
"2" or "fill" => QuestionKind.FillBlank,
"3" or "judge" => QuestionKind.TrueFalse,
"4" or "short" => QuestionKind.ShortAnswer,
_ when value.Contains("多选") => QuestionKind.Multiple,
_ when value.Contains("单选") => QuestionKind.Single,
_ when value.Contains("判断") => QuestionKind.TrueFalse,
_ when value.Contains("填空") => QuestionKind.FillBlank,
_ when value.Contains("简答") => QuestionKind.ShortAnswer,
_ => QuestionKind.Unknown,
};
public static bool IsAllowedUrl(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) &&
((uri.Scheme == "https" && (uri.Host.Equals("chaoxing.com", StringComparison.OrdinalIgnoreCase) || uri.Host.EndsWith(".chaoxing.com", StringComparison.OrdinalIgnoreCase))) ||
(uri.IsLoopback && uri.Scheme is "http" or "https"));
private static string CssEscape(string value) => Regex.Replace(value, "[^a-zA-Z0-9_-]", "");
private static async Task<bool> WaitForAsync(Func<Task<bool>> condition, int timeout, CancellationToken token, bool throwOnTimeout = true)
{
var until = DateTime.UtcNow.AddMilliseconds(timeout);
while (DateTime.UtcNow < until)
{
token.ThrowIfCancellationRequested();
try { if (await condition()) return true; } catch (PlaywrightException) { }
await Task.Delay(250, token);
}
if (throwOnTimeout) throw new TimeoutException("页面在规定时间内未出现预期状态,请检查登录和页面内容。");
return false;
}
private void OnResponse(object? sender, IResponse response) { if (!Owns(response.Request)) return; _network.Enqueue(JsonSerializer.Serialize(new
{ time = DateTimeOffset.Now, method = response.Request.Method, url = RedactUrl(response.Url), status = response.Status, type = response.Request.ResourceType })); }
private void OnRequestFailed(object? sender, IRequest request) { if (!Owns(request)) return; _network.Enqueue(JsonSerializer.Serialize(new
{ time = DateTimeOffset.Now, method = request.Method, url = RedactUrl(request.Url), failure = request.Failure, type = request.ResourceType })); }
private bool Owns(IRequest request) { try { return ReferenceEquals(request.Frame.Page, _page); } catch (PlaywrightException) { return false; } }
private async void OnDialog(object? sender, IDialog dialog)
{
_lastDialog = dialog.Message;
try { await dialog.DismissAsync(); } catch (PlaywrightException) { }
}
public static string RedactUrl(string value)
{
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) return "[invalid URL]";
var path = uri.GetLeftPart(UriPartial.Path);
if (uri.Query.Length == 0) return path;
return path + "?" + string.Join('&', uri.Query.TrimStart('?').Split('&').Select(pair => pair.Split('=')[0] + "=[hidden]"));
}
private async Task WriteNetworkAsync()
{
await using var stream = new StreamWriter(NetworkFile, append: true) { AutoFlush = true };
while (!_networkStop.IsCancellationRequested || !_network.IsEmpty)
{
while (_network.TryDequeue(out var entry)) await stream.WriteLineAsync(entry);
if (!_networkStop.IsCancellationRequested) await Task.Delay(300);
}
}
public async ValueTask DisposeAsync()
{
_context.Response -= OnResponse; _context.RequestFailed -= OnRequestFailed;
_page.Dialog -= OnDialog;
_networkStop.Cancel(); await _networkWriter; _networkStop.Dispose();
}
private sealed record CourseDto(string Id, string Title, string Url);
private sealed record ChapterDto(string Id, string Title, bool Completed);
private sealed record VideoDto(int Index, string Title, double Time, double Duration, bool Paused, bool Ended);
private sealed record QuestionDto(string Id, string Kind, string Stem, QuestionOption[] Options, bool Obfuscated);
}