imradv3 / src /EchoDictLib /DictRequestHandler.cs
fasdfsa's picture
加入完整 mdict 查询功能
38cc2e9
using CefSharp;
using CefSharp.Handler;
using System;
using System.Collections.Generic;
using System.IO;
namespace Echodict
{
public class DictRequestHandler : RequestHandler
{
private DictResourceRequestHandler _resourceRequestHandler;
private Action<string> _searchAction;
public DictRequestHandler(List<Dictionary> dicts, Action<string> searchAction = null)
{
_resourceRequestHandler = new DictResourceRequestHandler(dicts);
_searchAction = searchAction;
}
public void SetSearchHtml(string html)
{
_resourceRequestHandler.SearchHtml = html;
}
protected override bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
{
if (request.Url.StartsWith("entry://", StringComparison.OrdinalIgnoreCase))
{
string word = request.Url.Substring(8);
// Remove trailing slash if present
if (word.EndsWith("/")) word = word.Substring(0, word.Length - 1);
word = Uri.UnescapeDataString(word);
_searchAction?.Invoke(word);
return true;
}
return base.OnBeforeBrowse(chromiumWebBrowser, browser, frame, request, userGesture, isRedirect);
}
protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
{
return _resourceRequestHandler;
}
}
public class DictResourceRequestHandler : ResourceRequestHandler
{
private List<Dictionary> _dicts;
public string? SearchHtml { get; set; }
public DictResourceRequestHandler(List<Dictionary> dicts)
{
_dicts = dicts;
}
protected override IResourceHandler GetResourceHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request)
{
if (request.Url.StartsWith("http://custom-rendering/", StringComparison.OrdinalIgnoreCase))
{
// Serve the search result page
if (request.Url.Equals("http://custom-rendering/result.html", StringComparison.OrdinalIgnoreCase) ||
request.Url.Equals("http://custom-rendering/", StringComparison.OrdinalIgnoreCase))
{
if (SearchHtml != null)
{
return ResourceHandler.FromByteArray(System.Text.Encoding.UTF8.GetBytes(SearchHtml), "text/html");
}
}
if (!Uri.TryCreate(request.Url, UriKind.Absolute, out Uri? uri))
{
var handler = ResourceHandler.FromByteArray(System.Text.Encoding.UTF8.GetBytes("Invalid URL"), "text/plain");
return handler;
}
// Parse path to extract dictionary ID if present
// Expected format: /<dictId>/path/to/resource
string path = Uri.UnescapeDataString(uri.AbsolutePath);
string? dictId = null;
string resourcePath = path;
// Check if the first segment is a dictionary ID (32 hex chars)
var segments = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (segments.Length > 0 && segments[0].Length == 32 && System.Text.RegularExpressions.Regex.IsMatch(segments[0], "^[a-fA-F0-9]{32}$"))
{
dictId = segments[0];
// Reconstruct path without the ID
resourcePath = string.Join("/", segments, 1, segments.Length - 1);
}
if (dictId != null)
{
// Search in specific dictionary
var dict = _dicts.Find(d => d.Id.Equals(dictId, StringComparison.OrdinalIgnoreCase));
if (dict != null)
{
var data = dict.GetResource(resourcePath);
if (data != null)
{
string mime = GetMimeType(resourcePath);
return ResourceHandler.FromByteArray(data, mime);
}
}
}
else
{
// Fallback: Search in all dictionaries (legacy/global lookup)
foreach (var dict in _dicts)
{
var data = dict.GetResource(path);
if (data != null)
{
string mime = GetMimeType(path);
return ResourceHandler.FromByteArray(data, mime);
}
}
}
// Resource not found: return 404 to avoid network/DNS lookup which causes "Site can't be reached"
// We return 200 OK with "Not Found" body because setting StatusCode on IResourceHandler is tricky in some versions
var notFoundHandler = ResourceHandler.FromByteArray(System.Text.Encoding.UTF8.GetBytes("Not Found"), "text/plain");
return notFoundHandler;
}
return base.GetResourceHandler(chromiumWebBrowser, browser, frame, request);
}
private string GetMimeType(string path)
{
string ext = Path.GetExtension(path).ToLower();
switch (ext)
{
case ".css": return "text/css";
case ".js": return "text/javascript";
case ".png": return "image/png";
case ".jpg": return "image/jpeg";
case ".jpeg": return "image/jpeg";
case ".gif": return "image/gif";
case ".bmp": return "image/bmp";
case ".svg": return "image/svg+xml";
case ".wav": return "audio/wav";
case ".mp3": return "audio/mpeg";
case ".ttf": return "font/ttf";
case ".woff": return "font/woff";
case ".woff2": return "font/woff2";
default: return "application/octet-stream";
}
}
}
}