XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

ChaoXingAutoClass

【WinUI】基于 XFEstudio 的 XFEWinUIApplication 模板重建的 WinUI 3 课程工作台。二维码和账号密码登录、课程 GridView、章节、播放进度、学习笔记及日志均使用原生 WinUI 控件。网页播放器运行在独立后台进程中,界面不显示课程网站。

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Net;
using System.Text;
using System.Text.Json;
using AngleSharp.Html.Parser;
using ChaoXingAutoClass.Core;

namespace ChaoXingAutoClass.Browser;

/// <summary>Collects linked public teaching material automatically; search snippets are not treated as source evidence.</summary>
public sealed class PublicReferenceProvider(HttpClient http,
    Func<string, string, IReadOnlyList<QuestionSnapshot>, CancellationToken, Task<string[]>> plan,
    string directory, Action<string>? notice = null) : ILessonReferenceProvider
{
    private readonly HtmlParser _parser = new();
    private readonly Dictionary<string, ReferenceSource[]> _cache = new(StringComparer.Ordinal);
    private readonly Dictionary<string, ReferenceSource> _documents = new(StringComparer.Ordinal);
    private readonly Dictionary<string, int> _attempts = new(StringComparer.Ordinal);

    public async Task<IReadOnlyList<ReferenceSource>> GatherAsync(string chapter, string knowledge,
        IReadOnlyList<QuestionSnapshot> questions, CancellationToken token)
    {
        notice?.Invoke("正在根据课程和题目自动检索补充讲义…");
        string[] queries;
        try { queries = await plan(chapter, knowledge, questions, token); }
        catch (Exception error) when (!token.IsCancellationRequested && error is HttpRequestException or InvalidOperationException or JsonException)
        {
            notice?.Invoke("检索规划暂时不可用,将按当前章节主题检索。");
            queries = [System.Text.RegularExpressions.Regex.Replace(chapter, @"^\s*\d+(?:\.\d+)*\s*", "")];
        }
        var referenceQuery = string.Join(' ', queries) + " " + string.Join(' ', questions.Select(q => q.Stem + " " + string.Join(' ', q.Options.Select(o => o.Text))));
        var transactionTopic = System.Text.RegularExpressions.Regex.IsMatch(chapter + referenceQuery, "transaction|事务|隔离|传播|ACID", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        var concurrencyTopic = transactionTopic && System.Text.RegularExpressions.Regex.IsMatch(referenceQuery, "并发|脏读|幻读|丢失|隔离|isolation", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        var springTransactionTypes = new Dictionary<string, string>
        {
            ["TransactionDefinition"] = "TransactionDefinition.html", ["PlatformTransactionManager"] = "PlatformTransactionManager.html",
            ["TransactionTemplate"] = "support/TransactionTemplate.html", ["TransactionStatus"] = "TransactionStatus.html"
        };
        var collected = new List<ReferenceSource>();
        foreach (var query in queries)
        {
            if (_cache.TryGetValue(query, out var cached)) { collected.AddRange(cached); continue; }
            var sources = new List<ReferenceSource>();
            var topic = query.Trim('"', '“', '”');
            topic = System.Text.RegularExpressions.Regex.Replace(topic, "(的)?(核心|定义|概念|选择|含义)$", "");
            if (topic.Length < 2) topic = query;
            var technical = System.Text.RegularExpressions.Regex.IsMatch(query, @"[A-Za-z][A-Za-z0-9_.]{2,}");
            // Framework documentation is public source material, never a stored answer key.
            if (transactionTopic && (chapter + referenceQuery).Contains("Spring", StringComparison.OrdinalIgnoreCase))
                foreach (var type in springTransactionTypes.Where(t => referenceQuery.Contains(t.Key, StringComparison.Ordinal) ||
                    t.Key == "TransactionDefinition" && referenceQuery.Contains("timeout", StringComparison.OrdinalIgnoreCase)))
                    if (await FetchAsync(new Uri("https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/" + type.Value), token, referenceQuery) is { } declaration) sources.Add(declaration);
            if (concurrencyTopic)
            {
                if (await FetchAsync(new Uri("https://learn.microsoft.com/zh-cn/sql/relational-databases/sql-server-transaction-locking-and-row-versioning-guide?view=sql-server-ver17"), token, referenceQuery) is { } concurrency) sources.Add(concurrency);
                if (referenceQuery.Contains("MySQL", StringComparison.OrdinalIgnoreCase) &&
                    await FetchAsync(new Uri("https://dev.mysql.com/doc/refman/8.4/en/innodb-transaction-isolation-levels.html"), token, referenceQuery) is { } isolation) sources.Add(isolation);
            }
            if ((chapter + query).Contains("MyBatis", StringComparison.OrdinalIgnoreCase))
            {
                var paths = new List<string> { "configuration.html", "sqlmap-xml.html" };
                if ((query + string.Join(' ', questions.Select(q => q.Stem))).Contains("别名") || query.Contains("typeAlias", StringComparison.OrdinalIgnoreCase))
                    paths.Insert(0, "xref/org/apache/ibatis/type/TypeAliasRegistry.html");
                if (referenceQuery.Contains("POOLED", StringComparison.OrdinalIgnoreCase) || referenceQuery.Contains("连接池"))
                    paths.Insert(0, "xref/org/apache/ibatis/datasource/pooled/PooledConnection.html");
                foreach (var path in paths)
                    if (await FetchAsync(new Uri("https://mybatis.org/mybatis-3/" + path), token, referenceQuery) is { } official) sources.Add(official);
            }
            if ((chapter + query).Contains("Spring", StringComparison.OrdinalIgnoreCase))
            {
                var paths = transactionTopic ? new List<string>() : new List<string> { "core/beans/java/basic-concepts.html", "core/beans/classpath-scanning.html" };
                if (System.Text.RegularExpressions.Regex.IsMatch(query, "AOP|Aspect|切面|增强|拦截", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    paths.InsertRange(0, ["core/aop/introduction-defn.html", "core/aop/proxying.html", "core/aop/ataspectj/aspectj-support.html"]);
                if (System.Text.RegularExpressions.Regex.IsMatch(query, "scope|prototype|singleton|作用域|生命周期|创建|销毁", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    paths.Insert(0, "core/beans/factory-scopes.html");
                if (transactionTopic)
                    paths.InsertRange(0, ["data-access/transaction/declarative/annotations.html", "data-access/transaction/declarative/tx-propagation.html", "data-access/transaction.html"]);
                foreach (var path in paths)
                    if (await FetchAsync(new Uri("https://docs.spring.io/spring-framework/reference/" + path), token, referenceQuery) is { } official) sources.Add(official);
            }
            if (sources.Count < 2) try
            {
                var searchUrl = "https://www.bing.com/search?q=" + Uri.EscapeDataString(technical ? topic + " 官方文档" : '"' + topic + '"' + " (site:chaoxing.com OR site:edu.cn)") + "&count=10";
                using var request = new HttpRequestMessage(HttpMethod.Get, searchUrl);
                request.Headers.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/155.0.0.0 Safari/537.36");
                using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);
                response.EnsureSuccessStatusCode();
                var document = await _parser.ParseDocumentAsync(await ReadLimitedAsync(response, 1500000, token), token);
                Directory.CreateDirectory(directory);
                await File.WriteAllTextAsync(Path.Combine(directory, "search-diagnostics.json"), JsonSerializer.Serialize(new { query, searchTitle = document.Title, shownQuery = document.QuerySelector("input[name=q]")?.GetAttribute("value"), results = document.QuerySelectorAll("li.b_algo h2").Select(e => e.TextContent).ToArray() }), token);
                var links = document.QuerySelectorAll("li.b_algo h2 a[href]").Select(a => DecodeSearchLink(a.GetAttribute("href")!))
                    .Where(u => u is not null && IsPublicHttps(u)).Select(u => u!).DistinctBy(u => u.AbsoluteUri)
                    .OrderByDescending(u => IsOfficialDocumentation(u) ? 2 : u.Host.EndsWith(".edu.cn") || u.Host.EndsWith(".edu") || u.Host.EndsWith(".chaoxing.com") ? 1 : 0)
                    .Take(5).ToArray();
                foreach (var url in links)
                {
                    if (sources.Count >= 3) break;
                    var source = await FetchAsync(url, token, topic);
                    var terms = topic.Split(' ', StringSplitOptions.RemoveEmptyEntries);
                    if (source is not null && terms.Any(t => source.Title.Contains(t, StringComparison.OrdinalIgnoreCase) || source.Content.Contains(t, StringComparison.OrdinalIgnoreCase))) sources.Add(source);
                }
            }
            catch (Exception error) when (!token.IsCancellationRequested && error is HttpRequestException or IOException or TaskCanceledException or System.Net.Sockets.SocketException)
            { notice?.Invoke("部分公开资料暂时无法读取,将保留已有课程依据。"); }
            // An independently linked encyclopedia page is a fallback when public search
            // yields rankings, inaccessible pages, or no full-text teaching references.
            if (sources.Count < 2 && !technical)
            {
                var encyclopedia = await FetchAsync(new Uri("https://wiki.mbalib.com/wiki/" + Uri.EscapeDataString(topic)), token);
                if (encyclopedia is not null && encyclopedia.Title.Contains(topic, StringComparison.OrdinalIgnoreCase)) sources.Add(encyclopedia);
                if (sources.Count < 2 && (chapter + query).Contains("品牌") &&
                    await FetchAsync(new Uri("https://wiki.mbalib.com/wiki/" + Uri.EscapeDataString("品牌")), token, referenceQuery) is { } concept)
                    sources.Add(concept);
            }
            _cache[query] = sources.ToArray();
            collected.AddRange(sources);
        }
        // A URL can serve several queries. Re-extract from the full cached document for
        // this entire batch instead of keeping only its first query's excerpt.
        var unique = collected.DistinctBy(s => s.Url).Take(6).ToArray();
        var budget = Math.Clamp(18000 / Math.Max(1, unique.Length), 2000, 6000);
        var result = unique.Select(source =>
            _documents.TryGetValue(source.Url, out var full) ? full with { Content = ExtractRelevantText(full.Content, referenceQuery, budget) } :
                source with { Content = ExtractRelevantText(source.Content, referenceQuery, budget) }).ToArray();
        Directory.CreateDirectory(directory);
        await File.WriteAllTextAsync(Path.Combine(directory, $"references-{DateTime.Now:yyyyMMdd-HHmmssfff}.json"),
            JsonSerializer.Serialize(new { chapter, queries, sources = result }, new JsonSerializerOptions { WriteIndented = true }), token);
        notice?.Invoke($"自动取得 {result.Length} 份公开资料,来源和摘录已保存。" );
        return result;
    }

    private static bool IsOfficialDocumentation(Uri uri) => new[] { "mybatis.org", "spring.io", "microsoft.com", "oracle.com", "python.org", "pytorch.org", "tensorflow.org", "apache.org" }
        .Any(host => uri.Host == host || uri.Host.EndsWith('.' + host, StringComparison.OrdinalIgnoreCase));

    public static string ExtractRelevantText(string content, string query, int maximum = 9000)
    {
        if (content.Length <= maximum) return content;
        if (maximum < 1) return "";
        var introduction = Math.Min(600, maximum);
        var terms = System.Text.RegularExpressions.Regex.Matches(query, @"[A-Za-z_][A-Za-z0-9_.]{2,}|[\u4e00-\u9fff]{2,}")
            .SelectMany(m => m.Value.Length > 4 && m.Value.All(c => c is >= '\u4e00' and <= '\u9fff')
                ? new[] { m.Value }.Concat(Enumerable.Range(0, m.Value.Length - 1).Select(i => m.Value.Substring(i, 2)))
                : new[] { m.Value }).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
        var occurrences = terms.Select(term =>
        {
            var positions = new List<int>(); var offset = 0;
            while (positions.Count < 100 && offset < content.Length)
            {
                var index = content.IndexOf(term, offset, StringComparison.OrdinalIgnoreCase); if (index < 0) break;
                positions.Add(index); offset = index + term.Length;
            }
            return (Term: term, Positions: positions, Weight: Math.Log(2 + content.Length / (double)(1 + positions.Count * term.Length)));
        }).Where(t => t.Positions.Count > 0).ToArray();
        var window = Math.Min(1600, maximum - introduction);
        if (window < 1 || occurrences.Length == 0) return content[..maximum];
        var candidates = occurrences.SelectMany(t => t.Positions).Select(index =>
            Math.Clamp(index - 350, introduction, Math.Max(introduction, content.Length - window))).Distinct().Select(start =>
            (Start: start, End: Math.Min(content.Length, start + window), Terms: occurrences.Where(t =>
                t.Positions.Any(p => p >= start && p < start + window)).ToArray())).ToList();
        var selected = new List<(int Start, int End)> { (0, introduction) };
        var covered = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        var remaining = maximum - introduction;
        while (remaining > 80 && candidates.Count > 0)
        {
            var best = candidates.MaxBy(c => c.Terms.Sum(t => t.Weight * (covered.Contains(t.Term) ? .08 : 1)))!;
            candidates.Remove(best);
            if (selected.Any(r => best.Start < r.End && best.End > r.Start)) continue;
            var end = Math.Min(best.End, best.Start + remaining - 12);
            selected.Add((best.Start, end)); remaining -= end - best.Start + 12;
            foreach (var term in best.Terms) covered.Add(term.Term);
        }
        var text = new StringBuilder();
        foreach (var range in selected.OrderBy(r => r.Start))
        { if (text.Length > 0) text.Append("\n[相关正文摘录]\n"); text.Append(content.AsSpan(range.Start, range.End - range.Start)); }
        return text.Length > maximum ? text.ToString(0, maximum) : text.ToString();
    }
    private async Task<ReferenceSource?> FetchAsync(Uri url, CancellationToken token, string query = "")
    {
        if (_documents.TryGetValue(url.AbsoluteUri, out var cached)) return cached with { Content = ExtractRelevantText(cached.Content, query) };
        var attempts = _attempts.GetValueOrDefault(url.AbsoluteUri);
        if (attempts >= 2) return null;
        _attempts[url.AbsoluteUri] = attempts + 1;
        using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
        timeout.CancelAfter(TimeSpan.FromSeconds(10));
        var readToken = timeout.Token;
        try
        {
            if (!await HasPublicAddressAsync(url, readToken)) return null;
            using var response = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, readToken);
            if (!response.IsSuccessStatusCode || response.RequestMessage?.RequestUri is not { } final || !IsPublicHttps(final) ||
                !await HasPublicAddressAsync(final, readToken)) return null;
            if (response.Content.Headers.ContentType?.MediaType is not ("text/html" or "text/plain" or "application/xhtml+xml")) return null;
            var html = await ReadLimitedAsync(response, 1500000, readToken);
            var document = await _parser.ParseDocumentAsync(html, readToken);
            foreach (var element in document.QuerySelectorAll("script,style,nav,header,footer,noscript,form")) element.Remove();
            var title = document.Title?.Trim() ?? "";
            if (string.IsNullOrEmpty(title)) title = Path.GetFileName(final.AbsolutePath);
            if (title.Contains("题库") || title.Contains("答案") || title.Contains("验证码") || title.Contains("排行榜") || title.Contains("百强") || final.AbsolutePath == "/") return null;
            var content = (document.QuerySelector(".mw-parser-output,#mw-content-text,article,main,.article-content,.article,.content") ?? document.Body)?.TextContent ?? "";
            content = System.Text.RegularExpressions.Regex.Replace(content, @"\s+", " ").Trim();
            if (content.Length < 120) return null;
            var source = new ReferenceSource(title, final.AbsoluteUri, content, DateTimeOffset.Now);
            _documents[url.AbsoluteUri] = source;
            _documents[final.AbsoluteUri] = source;
            return source with { Content = ExtractRelevantText(content, query) };
        }
        catch (Exception error) when (!token.IsCancellationRequested && error is HttpRequestException or IOException or TaskCanceledException or System.Net.Sockets.SocketException)
        { return null; }
    }

    private static Uri? DecodeSearchLink(string href)
    {
        if (!Uri.TryCreate(href, UriKind.Absolute, out var uri)) return null;
        if (uri.Host.EndsWith("bing.com", StringComparison.OrdinalIgnoreCase))
        {
            var encoded = uri.Query.TrimStart('?').Split('&').Select(p => p.Split('=', 2)).FirstOrDefault(p => p[0] == "u")?.ElementAtOrDefault(1);
            if (encoded?.StartsWith("a1", StringComparison.Ordinal) != true) return null;
            try
            {
                encoded = Uri.UnescapeDataString(encoded[2..]).Replace('-', '+').Replace('_', '/');
                encoded = encoded.PadRight((encoded.Length + 3) / 4 * 4, '=');
                return Uri.TryCreate(Encoding.UTF8.GetString(Convert.FromBase64String(encoded)), UriKind.Absolute, out var decoded) ? decoded : null;
            }
            catch (FormatException) { return null; }
        }
        return uri;
    }

    private static bool IsPublicHttps(Uri uri) => uri.Scheme == "https" && string.IsNullOrEmpty(uri.UserInfo) &&
        !uri.IsLoopback && Uri.CheckHostName(uri.Host) == UriHostNameType.Dns && uri.Port == 443;
    private static async Task<bool> HasPublicAddressAsync(Uri uri, CancellationToken token)
    {
        var addresses = await Dns.GetHostAddressesAsync(uri.Host, token);
        return addresses.Length > 0 && addresses.All(address =>
        {
            if (IPAddress.IsLoopback(address)) return false;
            if (address.IsIPv4MappedToIPv6) address = address.MapToIPv4();
            var b = address.GetAddressBytes();
            return b.Length == 4 ? b[0] is not (0 or 10 or 127) && !(b[0] == 169 && b[1] == 254) &&
                !(b[0] == 172 && b[1] is >= 16 and <= 31) && !(b[0] == 192 && b[1] == 168) && b[0] < 224 :
                !address.IsIPv6LinkLocal && !address.IsIPv6Multicast && (b[0] & 0xfe) != 0xfc && !address.Equals(IPAddress.IPv6Any);
        });
    }
    private static async Task<string> ReadLimitedAsync(HttpResponseMessage response, int maximum, CancellationToken token)
    {
        await using var stream = await response.Content.ReadAsStreamAsync(token);
        using var memory = new MemoryStream();
        var buffer = new byte[16384];
        while (await stream.ReadAsync(buffer, token) is var read && read > 0)
        {
            if (memory.Length + read > maximum) throw new IOException("资料响应超过读取上限。");
            await memory.WriteAsync(buffer.AsMemory(0, read), token);
        }
        return Encoding.UTF8.GetString(memory.ToArray());
    }
}