Peach: Local-first video metadata scraper and media manager.
fix(taste): 补齐浏览器历史目录并按表结构读取访问记录
longmeidao191b1c15e2a6
diff --git a/README.md b/README.mdindex 5eaec335d..797a85f47 100644--- a/README.md+++ b/README.md@@ -96,7 +96,7 @@ https://github.com/user-attachments/assets/a5610874-e611-41bb-be22-7d99f0d64b62- **云下载**:在 JAV 或高清版目标打开「查找资源」,搜索番号或粘贴磁力,选择资源后提交到 115 或 PikPak。落地后自动选择正片、隔离达到自动线的推广附件、采集资料并按该来源模板整理;进度和失败重试都在活动页看。- **按番号找资源**:云下载直接添加先按 `manko.fun → JavDB → Sukebei` 查磁力,`manko.fun` 命中 1080p 或 2160p 就停止;没有高清命中时再接配置的 Prowlarr 或 Jackett 索引器。「想要」的待找清单继续汇集多个来源,方便比较版本。取得的封面和作品资料与候选资源一起展示。- **统计**:片子存在哪块盘、看过多少、标签分布,一页看完。-- **口味**:综合观看、反馈、馆藏积累、浏览记录及关注关系。可读取 Aside、Chrome、Edge、Firefox 等本机浏览器,也可添加其他浏览器的资料目录;停止同步与删除已导入记录分别管理。社媒访问按已登记账号和人物身份判断。+- **口味**:综合观看、反馈、馆藏积累、浏览记录及关注关系。可读取 Aside、Chrome、Edge、Firefox、QQ、360 等本机浏览器,也可添加其他浏览器的资料目录;停止同步与删除已导入记录分别管理。浏览器范围和 115 下载记录限制见[浏览器历史导入](docs/BROWSER_HISTORY.md)。社媒访问按已登记账号和人物身份判断。- **设置**:弹窗按外观与导航、浏览与播放、JAV 与新作、搜索与推荐、内容显示分类;「Peach 配置」集中管理媒体入库、来源订阅、下载渠道、网络访问与应用维护。- **多端**:电脑、平板、手机的浏览器都能用。diff --git a/docs/BROWSER_HISTORY.md b/docs/BROWSER_HISTORY.mdnew file mode 100644index 000000000..e0bbd118b--- /dev/null+++ b/docs/BROWSER_HISTORY.md@@ -0,0 +1,28 @@+# 浏览器历史导入++「口味」读取网页访问记录。自动发现覆盖默认资料目录;便携版、自定义安装和自定义 Firefox 资料可在「浏览器」中添加资料目录或历史文件。文件格式按 SQLite 表结构识别,不由浏览器名称或文件名决定。++## 目录范围++| 平台 | 自动发现 |+| --- | --- |+| Windows | Chrome、Edge、Firefox、Zen、Aside、Brave、Vivaldi、Opera、Opera GX、115、QQ、360 安全、360 极速、360 极速 X、搜狗新版 |+| macOS | Chrome、Edge、Firefox、Zen、Aside、Brave、Vivaldi、Opera、Opera GX、Safari |+| Linux | Chrome、Chromium、Edge、Firefox、Brave、Vivaldi、Opera;另含 Chrome Flatpak、Firefox Flatpak 与 Snap 默认目录 |++Windows 使用当前设备的 `APPDATA`、`LOCALAPPDATA`,Linux 使用 `XDG_CONFIG_HOME`。资料目录可直接包含历史文件,也可包含一层资料子目录。浏览器配置可以停止和恢复读取,已导入记录单独管理。++## 115 与国产浏览器++- **115**:默认资料目录为 `%LOCALAPPDATA%\115Chrome\User Data`。优先使用包含网页访问记录的 `History`。`HistoryEx` 只有包含受支持的网页访问表结构时才可读取;[115 官方将其称为下载历史](https://115.com/115115/T344887.html),只有下载记录的文件会提示选择 `History`,不计入口味。目录中同时有两种文件时,下载记录不妨碍网页历史读取。+- **QQ、360 极速、360 极速 X、搜狗新版**:按 Chromium 网页历史读取。默认目录依据维护项目 [HackBrowserData 的 Windows 浏览器目录](https://github.com/moonD4rk/HackBrowserData/blob/master/browser/browser_windows.go);360 安全目录另有[官方社区说明](https://bbs.360.cn/archiver/tid-15857311.html)。自定义安装路径需手动添加。+- **搜狗旧版**:`HistoryUrl3.db` 的专有格式未支持,不能按 Chromium 格式读取。[取证研究](https://www.huorong.cn/document/tech/vir_report/805)记录的表结构与标准网页访问表不同;完整时间字段语义未取得。+- **Opera**:具体资料目录可从 `opera:about/` 查看,见[官方帮助](https://help.opera.com/en/latest/crashes-and-issues/)。++## 验证与限制++浏览器数据库先经 SQLite backup 取得一致快照,再由固定的 `browserexport==0.4.4` 转换访问时间与记录。Chrome 的可选停留时长、Firefox 的可选描述与预览图缺失时仍可读取;一份资料损坏不阻断其他资料。原始 URL 与标题只保存在私有历史库,不进入 ledger。++临时 SQLite 回归覆盖目录发现、手动添加、停止与恢复、增量去重、可选列、错误格式、特殊路径字符及单份失败隔离。这里的目录支持不表示已对每款浏览器当前版本完成实机验收。issue [#65](https://github.com/peach-mitao/peach/issues/65) 报告者的 `HistoryEx` 表结构与实际导入结果未取得;无需上传含私人历史的完整数据库,可先提供表名与列名确认格式。++桌面与手机页面沿用现有浏览器来源管理,本次没有布局或交互改动。diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.mdindex effa3fc5d..31f16b06e 100644--- a/docs/PRODUCT_BACKLOG.md+++ b/docs/PRODUCT_BACKLOG.md@@ -6,6 +6,8 @@## 功能验收与范围+- [#65 115 历史导入](https://github.com/peach-mitao/peach/issues/65):目录与格式识别有合成 SQLite 回归;报告者的 `HistoryEx` 表结构和实机导入结果未取得。官方将其描述为下载历史,支持范围见[浏览器历史导入](BROWSER_HISTORY.md)。+- #61 的 OneDrive、光鸭与通用挂载来源待真实账号验收;#62 的真实 STRM 上游兼容性待补,合成 HTTP Range 与 HLS 回归在隔离环境验证。- [#63 Emby/Jellyfin 兼容](https://github.com/peach-mitao/peach/issues/63)待明确目标客户端、认证、媒体库查询、播放与进度接口范围。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 09caed5dd..94ad5bb2c 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -530,7 +530,7 @@ A 盘垃圾隔离使用短名称 `peach-purge-<32 位 UUID>.peach-quarantine`,| 115 文件清单 | `p115client==0.0.9.6.5.1`(MIT) | 只在显式 SHA-1 对账脚本中安装,Peach 负责 ledger 事务、备份与写入门槛 || 视频出处/片尾证据 | 现有 FFmpeg 抽帧 + Windows.Media.Ocr WinRT Provider(Windows PowerShell 5.1 固定适配器) | 有界首尾采样、缓存、来源/Full version 分类、健康统计与人工复核 || 参考产品行为 | 当前线上交互 + 有版本的公开 DOM/CSS/JS;取不到源码时用精确截图测量 | 证据登记、无障碍、Peach 差异、回归检查 |-| 浏览器历史解析 | `browserexport`(Chrome/Firefox/Zen/Safari 的 SQLite 解析,`taste_history.py` 不自写解析) | 消费者是 `/taste` 的本机读取与导出导入;Peach 保留 SQLite backup、Takeout、私有原始存储、域名分析和 candidate 生成,在 Windows 自己关只读连接以避开句柄滞留。跨主机同步须显式导出、传输并按来源去重合并 |+| 浏览器历史解析 | `browserexport==0.4.4`(MIT、Python ≥3.9,约 35 KB wheel;Chrome/Firefox/Zen/Safari 的 SQLite 解析) | 消费者是 `/taste` 的本机读取与导出导入;Peach 保留 SQLite backup、Takeout、私有原始存储、域名分析和 candidate 生成,在 Windows 自己关只读连接。按必需列识别格式,以局部 Schema 补可选元数据列,时间与 Visit 转换继续复用上游。国产浏览器目录参考 HackBrowserData,不引入其运行依赖;目录与合成 SQLite 的最小验证、115 下载记录和旧搜狗限制见[浏览器历史导入](BROWSER_HISTORY.md)。跨主机同步须显式导出、传输并按来源去重合并 || Rule34.xxx / Paheal 高清封面 | 固定参考 gallery-dl `86047cf67a12bdb6ff1085774f8ad9fc347e8da9`(GPL-2.0,只作协议行为证据,不引入运行时);运行时复用现有 FFmpeg | booru 按 `sample_url`/`preview_url`/`file_url` 回退,Paheal 只取原始 `file_url` 再抽帧:FFmpeg `blackframe` 的 `lavfi.blackframe.pblack` 在开头 30 秒选第一张黑色像素低于 98% 的帧,版本化缓存键淘汰旧黑帧(不用 GPL、默认取 10% 位置的 ffmpegthumbnailer)。Peach 管 URL 白名单、同源代理、双并发抽帧、缓存与低清回退 || FANBOX 正文解析 | PixivUtil2 `v20251112` / `e537e96` 的公开正文模型(BSD-2-Clause,只复用数据模型,不引入整套下载器) | Peach 的独立规范化 DTO 覆盖 image/text/file/article/video/entry、`fileMap`、`embedMap`、`urlEmbedMap` 和旧 HTML 正文,保留正文顺序、稳定去重、可播放媒体与文件页边界;许可证依据写在实现头部,传输固定 `curl_cffi` || 云下载传输 | `grpcio==1.84.0` 与 `protobuf==7.36.2`(消息代码由 grpcio-tools 1.84.0 生成后提交),首个消费者 `downloads_clouddrive` | CloudDrive2 官方 proto 的七个方法子集、令牌存 CredentialStore、任务表与失败分类(`downloads.py`,ADR-0089) |diff --git a/src/peach/taste_browsers.py b/src/peach/taste_browsers.pyindex d9463eb9e..1629307a2 100644--- a/src/peach/taste_browsers.py+++ b/src/peach/taste_browsers.py@@ -12,30 +12,57 @@ def _key(path: Path) -> str:return hashlib.sha256(f"{socket.gethostname()}\0{str(path.resolve()).casefold()}".encode()).hexdigest()-def _paths(path: Path) -> list[Path]:+def _paths(path: Path, *, browsing_only: bool = False) -> list[Path]:if path.is_file():return [path]if not path.is_dir():return []- return sorted({item for name in ("History", "places.sqlite", "History.db")- for pattern in (name, f"*/{name}") for item in path.glob(pattern)- if item.is_file()})[:200]+ paths = sorted({item for name in ("History", "HistoryEx", "places.sqlite", "History.db")+ for pattern in (name, f"*/{name}") for item in path.glob(pattern)+ if item.is_file()})[:200]+ if not browsing_only:+ return paths+ found = []+ for item in paths:+ if item.name == "HistoryEx":+ try:+ _validate(item)+ except ValueError:+ continue+ found.append(item)+ return found+++def history_engine(db: sqlite3.Connection) -> str:+ """根据访问记录的必需列识别格式,附加元数据由解析器处理。"""+ schemas = {+ "chrome": {"urls": {"id", "url", "title"}, "visits": {"url", "visit_time"}},+ "firefox": {"moz_places": {"id", "url", "title"},+ "moz_historyvisits": {"place_id", "visit_date"}},+ "safari": {"history_items": {"id", "url"},+ "history_visits": {"history_item", "visit_time", "title"}},+ }+ for engine, required in schemas.items():+ if all(columns <= {row[1] for row in db.execute(f'PRAGMA table_info("{table}")')}+ for table, columns in required.items()):+ return engine+ raise ValueError("浏览器历史格式不受支持,请选择包含网页访问记录的历史文件")def _validate(path: Path) -> str:from .taste_history import _readonly_uritry:with closing(sqlite3.connect(_readonly_uri(path), uri=True)) as db:- tables = {row[0] for row in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}- except sqlite3.OperationalError as error:+ try:+ return history_engine(db)+ except ValueError as error:+ if path.name == "HistoryEx":+ raise ValueError("HistoryEx 未包含可识别的网页访问记录;115 下载记录不能用于浏览历史,请选择 History 文件") from error+ raise+ except sqlite3.DatabaseError as error:if "locked" in str(error).casefold():raise ValueError("历史文件正在使用,请退出该浏览器后添加") from errorraise ValueError("浏览器历史文件未取得,请检查资料目录") from error- for engine, required in (("chrome", {"urls", "visits"}), ("firefox", {"moz_places", "moz_historyvisits"}),- ("safari", {"history_items", "history_visits"})):- if required <= tables:- return engine- raise ValueError("请选择浏览器历史文件或包含浏览器资料的目录")def _registered_browsers(store_path):@@ -62,7 +89,7 @@ def browser_sources(store_path: Path) -> list[dict]:entries[key] = {"id": key, "name": name, "path": path, "enabled": bool(enabled),"automatic": key in entries, "engine": engine}for entry in entries.values():- paths = _paths(Path(entry["path"]))+ paths = _paths(Path(entry["path"]), browsing_only=True)entry["profiles"] = len(paths)entry["available"] = bool(paths)return sorted(entries.values(), key=lambda row: (row["name"].casefold(), row["id"]))@@ -80,7 +107,9 @@ def configure_browser(store_path: Path, operation: str, body: dict) -> None:paths = _paths(path)if not paths:raise ValueError("目录中未找到浏览器历史文件")- engines = [_validate(history) for history in paths]+ # 同一资料目录可以同时包含网页历史与下载历史。+ browsing = _paths(path, browsing_only=True)+ engines = [_validate(history) for history in browsing or paths]entry = {"id": _key(path), "name": name, "path": str(path), "enabled": True,"engine": engines[0] if len(set(engines)) == 1 else "auto"}elif operation in ("disable", "enable"):@@ -106,8 +135,7 @@ def enabled_history_sources(store_path: Path):unique = {}for browser in browser_sources(store_path):if browser["enabled"]:- for path in _paths(Path(browser["path"])):- engine = {"History": "chrome", "places.sqlite": "firefox", "History.db": "safari"}.get(path.name, browser["engine"])+ for path in _paths(Path(browser["path"]), browsing_only=True):unique.setdefault(str(path.resolve()).casefold(), HistorySource(- browser["name"].casefold(), path.parent.name, path, engine=engine))+ browser["name"].casefold(), path.parent.name, path, engine=browser["engine"]))return list(unique.values())diff --git a/src/peach/taste_history.py b/src/peach/taste_history.pyindex 3aee4d80e..765de044e 100644--- a/src/peach/taste_history.py+++ b/src/peach/taste_history.py@@ -9,6 +9,8 @@ import sqlite3import tempfileimport zipfileimport math+import os+import sysimport timefrom collections import Counter, defaultdictfrom contextlib import closing, contextmanager@@ -22,6 +24,8 @@ from browserexport.parse import read_visits as read_browser_visitsfrom browserexport.browsers.chrome import Chromefrom browserexport.browsers.firefox import Firefoxfrom browserexport.browsers.safari import Safari+from browserexport.browsers.common import Schema+from browserexport.common import BrowserexportErrorfrom .catalog_rules import LENGTH_TAGS, TECH_TAGSfrom .review_csv import read_rows, write_rows@@ -116,12 +120,14 @@ def discover_history_sources(localappdata: Path | None = None,platform_name: str | None = None,) -> list[HistorySource]:- platform_name = platform_name or ("windows" if __import__("os").name == "nt" else "macos")+ from .taste_browsers import _paths++ platform_name = platform_name or {"win32": "windows", "darwin": "macos"}.get(sys.platform, "linux")home = home or Path.home()candidates: list[tuple[str, Path]] = []if platform_name == "windows":- appdata = appdata or home / "AppData" / "Roaming"- localappdata = localappdata or home / "AppData" / "Local"+ appdata = appdata or Path(os.environ.get("APPDATA", home / "AppData" / "Roaming"))+ localappdata = localappdata or Path(os.environ.get("LOCALAPPDATA", home / "AppData" / "Local"))candidates.extend([("firefox", appdata / "Mozilla" / "Firefox" / "Profiles"),@@ -132,9 +138,18 @@ def discover_history_sources(("brave", localappdata / "BraveSoftware" / "Brave-Browser" / "User Data"),("vivaldi", localappdata / "Vivaldi" / "User Data"),("opera", appdata / "Opera Software" / "Opera Stable"),+ ("opera_gx", appdata / "Opera Software" / "Opera GX Stable"),+ ("115", localappdata / "115Chrome" / "User Data"),+ ("qq", localappdata / "Tencent" / "QQBrowser" / "User Data"),+ ("360chrome", localappdata / "360chrome" / "Chrome" / "User Data"),+ ("360chromex", localappdata / "360ChromeX" / "Chrome" / "User Data"),+ ("360se", appdata / "360se6" / "User Data"),+ ("360se", localappdata / "360se6" / "User Data"),+ ("360se", localappdata / "secoresdk" / "360se6" / "User Data"),+ ("sogou", localappdata / "Sogou" / "SogouExplorer" / "User Data"),])- else:+ elif platform_name == "macos":candidates.extend([("firefox", home / "Library" / "Application Support" / "Firefox" / "Profiles"),@@ -144,15 +159,30 @@ def discover_history_sources(("edge", home / "Library" / "Application Support" / "Microsoft Edge"),("brave", home / "Library" / "Application Support" / "BraveSoftware" / "Brave-Browser"),("vivaldi", home / "Library" / "Application Support" / "Vivaldi"),+ ("opera", home / "Library" / "Application Support" / "com.operasoftware.Opera"),+ ("opera_gx", home / "Library" / "Application Support" / "com.operasoftware.OperaGX"),])+ elif platform_name == "linux":+ config = Path(os.environ.get("XDG_CONFIG_HOME", home / ".config"))+ candidates.extend([+ ("firefox", home / ".mozilla/firefox"),+ ("firefox", home / ".var/app/org.mozilla.firefox/.mozilla/firefox"),+ ("firefox", home / "snap/firefox/common/.mozilla/firefox"),+ ("chrome", config / "google-chrome"),+ ("chrome", home / ".var/app/com.google.Chrome/config/google-chrome"),+ ("chromium", config / "chromium"),+ ("edge", config / "microsoft-edge"),+ ("brave", config / "BraveSoftware/Brave-Browser"),+ ("vivaldi", config / "vivaldi"),+ ("opera", config / "opera"),+ ])found: list[HistorySource] = []for browser, root in candidates:if not root.is_dir():continue- filename = "places.sqlite" if browser in {"firefox", "zen"} else "History"- for path in [root / filename, *root.glob(f"*/{filename}")]:+ for path in _paths(root, browsing_only=True):if path.is_file():found.append(HistorySource(browser, path.parent.name, path, root,"firefox" if browser in {"firefox", "zen"} else "chrome"))@@ -164,7 +194,7 @@ def discover_history_sources(def _readonly_uri(path: Path) -> str:- return f"file:{path.resolve().as_posix()}?mode=ro"+ return f"{path.resolve().as_uri()}?mode=ro"def _consistent_copy(source: Path, destination: Path) -> None:@@ -193,7 +223,37 @@ def _read_visits(snapshot: Path, _browser: str | None = None, *, progress=None)def consume(source, browser: str | None = None) -> None:known = {"chrome": Chrome, "firefox": Firefox, "zen": Firefox, "safari": Safari}- iterator = known[browser].extract_visits(source) if browser in known else read_browser_visits(source)+ if isinstance(source, sqlite3.Connection):+ from .taste_browsers import history_engine+ try:+ browser = history_engine(source)+ except ValueError:+ # 其它格式仍交给 browserexport 自带的格式探测器。+ iterator = read_browser_visits(source)+ return consume_visits(iterator)+ adapter = known[browser]+ # 保留 browserexport 的时间与 DTO 转换,仅补可选元数据列。+ optional = ({"V.visit_duration": ("visits", "visit_duration", "0")}+ if browser == "chrome" else {+ "P.description": ("moz_places", "description", "NULL"),+ "P.preview_image_url": ("moz_places", "preview_image_url", "NULL"),+ } if browser == "firefox" else {})+ columns = list(adapter.schema.cols)+ for expression, (table, column, fallback) in optional.items():+ available = {row[1] for row in source.execute(f'PRAGMA table_info("{table}")')}+ replacement = (f"COALESCE({expression}, {fallback})" if column in available+ else fallback)+ columns = [f"{replacement} AS {column}" if item == expression else item+ for item in columns]+ adapted = type("HistoryAdapter", (adapter,), {+ "schema": Schema(cols=columns, where=adapter.schema.where, order_by=adapter.schema.order_by),+ })+ iterator = adapted.extract_visits(source)+ else:+ iterator = read_browser_visits(source)+ consume_visits(iterator)++ def consume_visits(iterator) -> None:for visit in iterator:visited = visit.dtif visited.tzinfo is None:@@ -300,7 +360,7 @@ def refresh_history(report()visits = _read_visits(snapshot, source.engine or source.browser, progress=report)report(len(visits))- except (sqlite3.DatabaseError, OSError) as error:+ except (sqlite3.DatabaseError, OSError, ValueError, TypeError, OverflowError, BrowserexportError) as error:message = ("历史文件正在使用,请退出该浏览器后重新读取" if "locked" in str(error).casefold()else "浏览器历史未取得,请检查资料目录或退出浏览器后重试")results.append({"browser": source.browser, "profile": source.profile, "visits": 0,diff --git a/tests/test_taste_history.py b/tests/test_taste_history.pyindex 98efaa943..a8749bd78 100644--- a/tests/test_taste_history.py+++ b/tests/test_taste_history.py@@ -26,7 +26,7 @@ from peach.taste_history import (class TasteHistoryTests(unittest.TestCase):def setUp(self):self.temp_dir = tempfile.TemporaryDirectory()- self.root = Path(self.temp_dir.name)+ self.root = Path(self.temp_dir.name).resolve()def tearDown(self):self.temp_dir.cleanup()@@ -116,13 +116,128 @@ class TasteHistoryTests(unittest.TestCase):support / "Firefox" / "Profiles" / "firefox" / "places.sqlite",support / "zen" / "Profiles" / "zen" / "places.sqlite",support / "Google" / "Chrome" / "Default" / "History",+ support / "com.operasoftware.Opera" / "History",+ support / "com.operasoftware.OperaGX" / "Default" / "History",self.root / "Library" / "Safari" / "History.db",]for path in paths:path.parent.mkdir(parents=True, exist_ok=True)path.touch()sources = discover_history_sources(home=self.root, platform_name="macos")- self.assertEqual([source.browser for source in sources], ["chrome", "firefox", "safari", "zen"])+ self.assertEqual([source.browser for source in sources], ["chrome", "firefox", "opera", "opera_gx", "safari", "zen"])++ def test_windows_browser_variants_read_through_registered_sources(self):+ from peach.taste_browsers import browser_sources, enabled_history_sources+ local, roaming = self.root / "Local", self.root / "Roaming"+ layouts = {+ "115": local / "115Chrome/User Data/Default/HistoryEx",+ "qq": local / "Tencent/QQBrowser/User Data/Default/History",+ "360chrome": local / "360chrome/Chrome/User Data/Default/History",+ "360chromex": local / "360ChromeX/Chrome/User Data/Default/History",+ "360se": roaming / "360se6/User Data/Default/History",+ "sogou": local / "Sogou/SogouExplorer/User Data/Default/History",+ "opera_gx": roaming / "Opera Software/Opera GX Stable/Default/History",+ }+ for path in layouts.values():+ self._chrome_db(path)+ sources = discover_history_sources(home=self.root, appdata=roaming, localappdata=local,+ platform_name="windows")+ self.assertEqual({source.browser: source.path for source in sources}, layouts)+ store = self.root / "private.sqlite"+ with mock.patch("peach.taste_history.discover_history_sources", return_value=sources):+ self.assertEqual(len(browser_sources(store)), len(layouts))+ results = refresh_history(enabled_history_sources(store), store)+ self.assertEqual([row["added"] for row in results], [1] * len(layouts))++ def test_historyex_directory_and_file_use_verified_browsing_schema(self):+ from peach.taste_browsers import configure_browser, enabled_history_sources+ path = self.root / "115Chrome/User Data/Default/HistoryEx"+ self._chrome_db(path)+ for selected in (path, path.parent, path.parent.parent):+ with self.subTest(selected=selected), mock.patch("peach.taste_history.discover_history_sources", return_value=[]):+ store = self.root / f"store-{len(selected.parts)}.sqlite"+ configure_browser(store, "add", {"name": "115", "path": str(selected)})+ sources = enabled_history_sources(store)+ self.assertEqual([source.path for source in sources], [path])+ self.assertEqual(refresh_history(sources, store)[0]["added"], 1)++ def test_historyex_download_database_has_actionable_error(self):+ from peach.taste_browsers import configure_browser+ path = self.root / "Default/HistoryEx"+ path.parent.mkdir()+ with closing(sqlite3.connect(path)) as db:+ db.execute("CREATE TABLE downloads(id INTEGER PRIMARY KEY, url TEXT)")+ for selected in (path, path.parent):+ with self.subTest(selected=selected), mock.patch("peach.taste_history.discover_history_sources", return_value=[]):+ with self.assertRaisesRegex(ValueError, "下载记录.*History"):+ configure_browser(self.root / "private.sqlite", "add", {"name": "115", "path": str(selected)})++ def test_sqlite_filename_and_optional_metadata_do_not_control_history_engine(self):+ chrome = self.root / "export #1%/History.db"+ firefox = self.root / "firefox/History"+ self._chrome_db(chrome)+ self._firefox_db(firefox)+ with closing(sqlite3.connect(chrome)) as db:+ db.execute("ALTER TABLE visits DROP COLUMN visit_duration")+ with closing(sqlite3.connect(firefox)) as db:+ db.execute("ALTER TABLE moz_places DROP COLUMN description")+ db.execute("ALTER TABLE moz_places DROP COLUMN preview_image_url")+ sources = [HistorySource("custom", "chrome", chrome, engine="safari"),+ HistorySource("custom", "firefox", firefox, engine="chrome")]+ results = refresh_history(sources, self.root / "private.sqlite")+ self.assertEqual([row["added"] for row in results], [1, 1])+ exported = import_history_exports([chrome], self.root / "exported.sqlite")+ self.assertEqual(exported[0]["added"], 1)++ def test_invalid_history_file_is_rejected_without_sqlite_traceback(self):+ from peach.taste_browsers import configure_browser+ path = self.root / "History"+ path.write_bytes(b"not a sqlite database")+ with mock.patch("peach.taste_history.discover_history_sources", return_value=[]):+ with self.assertRaisesRegex(ValueError, "历史文件未取得"):+ configure_browser(self.root / "private.sqlite", "add", {"name": "custom", "path": str(path)})++ def test_download_history_does_not_hide_web_history_in_same_profile(self):+ from peach.taste_browsers import configure_browser, enabled_history_sources+ path = self.root / "Default/History"+ self._chrome_db(path)+ with closing(sqlite3.connect(path.with_name("HistoryEx"))) as db:+ db.execute("CREATE TABLE downloads(id INTEGER PRIMARY KEY)")+ with mock.patch("peach.taste_history.discover_history_sources", return_value=[]):+ store = self.root / "private.sqlite"+ configure_browser(store, "add", {"name": "115", "path": str(path.parent)})+ self.assertEqual([source.path for source in enabled_history_sources(store)], [path])++ def test_malformed_visit_does_not_interrupt_other_profiles(self):+ invalid, valid = self.root / "invalid/History", self.root / "valid/History"+ self._chrome_db(invalid)+ self._chrome_db(valid)+ with closing(sqlite3.connect(invalid)) as db:+ db.execute("UPDATE visits SET visit_time='not a date'")+ db.commit()+ results = refresh_history([HistorySource("custom", str(index), path)+ for index, path in enumerate((invalid, valid))], self.root / "private.sqlite")+ self.assertEqual(results[0]["status"], "failed")+ self.assertEqual(results[1]["added"], 1)++ def test_windows_uses_redirected_appdata_directories(self):+ local, roaming = self.root / "RedirectedLocal", self.root / "RedirectedRoaming"+ self._chrome_db(local / "Google/Chrome/User Data/Profile 2/History")+ self._firefox_db(roaming / "Mozilla/Firefox/Profiles/custom/places.sqlite")+ with mock.patch.dict("os.environ", {"APPDATA": str(roaming), "LOCALAPPDATA": str(local)}):+ sources = discover_history_sources(home=self.root, platform_name="windows")+ self.assertEqual([source.browser for source in sources], ["chrome", "firefox"])++ def test_linux_uses_native_and_sandboxed_browser_profiles(self):+ config = self.root / "config"+ paths = [config / "google-chrome/Default/History", config / "opera/History",+ self.root / ".mozilla/firefox/default/places.sqlite",+ self.root / "snap/firefox/common/.mozilla/firefox/snap/places.sqlite"]+ for path in paths:+ (self._firefox_db if path.name == "places.sqlite" else self._chrome_db)(path)+ with mock.patch.dict("os.environ", {"XDG_CONFIG_HOME": str(config)}):+ sources = discover_history_sources(home=self.root, platform_name="linux")+ self.assertEqual({source.path for source in sources}, set(paths))def test_the_history_store_has_one_entry_point(self):"""打开私有历史库的前导只许有一份。