using System.Diagnostics; using System.Collections.Concurrent; using System.Text.Json; using ChaoXingAutoClass.Browser; using ChaoXingAutoClass.Core; using ChaoXingAutoClass.Interface.Services; using ChaoXingAutoClass.Speech; using Microsoft.Playwright; namespace ChaoXingAutoClass.Implements.Services; public sealed partial class LearningService : ILearningService { private readonly SettingsStore _store = new(); private readonly HttpClient _http = new() { Timeout = TimeSpan.FromMinutes(5) }; private readonly HttpClient _referenceHttp = new() { Timeout = TimeSpan.FromSeconds(25) }; private readonly SemaphoreSlim _initialize = new(1, 1); private readonly CancellationTokenSource _lifetime = new(); private Process? _worker; private IPlaywright? _playwright; private IBrowser? _browser; private ChaoxingBrowser? _adapter; private ChaoxingApiClient? _api; private string _session = ""; public AppSettings Settings { get; } = new SettingsStore().Load(); public IReadOnlyList Courses { get; private set; } = []; public IReadOnlyList Chapters => CurrentCourse is { } c && _jobs.TryGetValue(CourseIdentity.Key(c), out var job) ? job.Chapters : []; public CourseInfo? CurrentCourse { get; private set; } public LearningController? Controller => CurrentCourse is { } c && _jobs.TryGetValue(CourseIdentity.Key(c), out var job) ? job.Controller : null; public event Action? Notice; public async Task InitializeAsync(CancellationToken token) { await _initialize.WaitAsync(token); try { if (_api is not null) return; Directory.CreateDirectory(SettingsStore.DataDirectory); var endpointFile = Path.Combine(SettingsStore.DataDirectory, "Runtime", Guid.NewGuid().ToString("N") + ".endpoint"); Directory.CreateDirectory(Path.GetDirectoryName(endpointFile)!); var executable = LocateWorker(); var start = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; start.ArgumentList.Add(Path.Combine(SettingsStore.DataDirectory, "BrowserProfile")); start.ArgumentList.Add(endpointFile); _worker = Process.Start(start) ?? throw new InvalidOperationException("无法启动后台浏览器。"); _worker.ErrorDataReceived += (_, e) => { if (e.Data is { Length: > 0 }) Log("error", e.Data); }; _worker.BeginErrorReadLine(); _worker.OutputDataReceived += OnWorkerOutput; _worker.BeginOutputReadLine(); for (var attempt = 0; !File.Exists(endpointFile); attempt++) { if (_worker.HasExited) throw new InvalidOperationException("后台浏览器初始化失败,请检查日志。"); if (attempt >= 160) throw new TimeoutException("后台浏览器初始化超时。"); await Task.Delay(250, token); } var endpoint = await File.ReadAllTextAsync(endpointFile, token); File.Delete(endpointFile); _playwright = await Playwright.CreateAsync(); _browser = await _playwright.Chromium.ConnectOverCDPAsync(endpoint, new() { Timeout = 20000 }); var context = _browser.Contexts.First(); var page = context.Pages.First(); _session = Path.Combine(SettingsStore.DataDirectory, "Sessions", "WinUI-" + DateTime.Now.ToString("yyyyMMdd-HHmmss")); _adapter = new(context, page, Path.Combine(_session, "network.jsonl")); _api = new(context); await File.WriteAllTextAsync(Path.Combine(SettingsStore.DataDirectory, "hidden-browser-endpoint.txt"), endpoint, token); Log("info", "后台浏览器与课程 API 已就绪。"); } finally { _initialize.Release(); } } private static string LocateWorker() { var packaged = Path.Combine(AppContext.BaseDirectory, "BrowserHost", "ChaoXingAutoClass.BrowserHost.exe"); if (File.Exists(packaged)) return packaged; for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent) { var project = Path.Combine(directory.FullName, "src", "ChaoXingAutoClass.BrowserHost", "bin"); if (!Directory.Exists(project)) continue; return Directory.EnumerateFiles(project, "ChaoXingAutoClass.BrowserHost.exe", SearchOption.AllDirectories) .OrderByDescending(File.GetLastWriteTimeUtc).FirstOrDefault() ?? throw new FileNotFoundException("请先生成 BrowserHost 项目。"); } throw new FileNotFoundException("缺少 BrowserHost,请重新解压完整发行包。"); } public async Task> RefreshCoursesAsync(CancellationToken token) { await InitializeAsync(token); Courses = await _api!.GetCoursesAsync(token); Log("success", $"课程 API 已返回 {Courses.Count} 门课程。"); return Courses; } public async Task GetQrAsync(CancellationToken token) { await InitializeAsync(token); return await _api!.GetQrAsync(token); } public Task PollQrAsync(LoginQr qr, CancellationToken token) => _api!.PollQrAsync(qr, token); public Task PasswordLoginAsync(string account, string password, CancellationToken token) => _api!.PasswordLoginAsync(_adapter!.Page, account, password, token); }