Peach: Local-first video metadata scraper and media manager.
fix(taste): 完善浏览器历史格式与目录兼容
longmeidao7cf62507ce61
diff --git a/README.en.md b/README.en.mdindex 1ce40a9e9..d0a650bdd 100644--- a/README.en.md+++ b/README.en.md@@ -96,7 +96,7 @@ The original screenshots are lossless 3840×2160 PNGs; click to view them. You c- **Cloud download**: open Find resources from JAV or a quality goal, search a video code or paste a magnet link, then submit the selected resource to 115 or PikPak. Once it lands, Peach selects the main video, isolates promotional attachments that meet the automatic threshold, collects metadata and applies that source's organization template. Progress and failed-step retries show up in Activity.- **Find a release**: direct cloud downloads search `manko.fun → JavDB → Sukebei` first and stop when manko.fun has a 1080p or 2160p match; without one, they continue through your configured Prowlarr or Jackett indexers. Wanted titles collect candidates from multiple sources so you can compare versions. Available covers and title details appear with the resource candidates.- **Statistics**: which drive holds what, how much you have watched and which tags dominate, on one page.-- **Taste**: combines viewing, feedback, accumulated library titles, browsing history and followed accounts. Read local 115, Aside, Chrome, Edge or Firefox profiles, or add another browser's profile directory. Stopping sync and deleting imported records are separate controls. Social visits are associated with registered accounts and known identities.+- **Taste**: combines viewing, feedback, accumulated library titles, browsing history and followed accounts. Read local 115, QQ, 360, Aside, Chrome, Edge or Firefox profiles, or add another browser's profile directory; see [browser history support](docs/BROWSER_HISTORY.md) for supported locations and formats. Stopping sync and deleting imported records are separate controls. Social visits are associated with registered accounts and known identities.- **Settings**: the dialog groups appearance and navigation, browsing and playback, JAV and new releases, search and recommendations, and content display. Peach configuration groups media intake, sources and subscriptions, download channels, network access, and application maintenance.- **Any screen**: works in the browser on desktop, tablet and phone.diff --git a/README.md b/README.mdindex bf8ec8743..32ba07740 100644--- a/README.md+++ b/README.md@@ -95,7 +95,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 索引器。「想要」的待找清单继续汇集多个来源,方便比较版本。取得的封面和作品资料与候选资源一起展示。- **统计**:片子存在哪块盘、看过多少、标签分布,一页看完。-- **口味**:综合观看、反馈、馆藏积累、浏览记录及关注关系。可读取 115、Aside、Chrome、Edge、Firefox 等本机浏览器,也可添加其他浏览器的资料目录;停止同步与删除已导入记录分别管理。社媒访问按已登记账号和人物身份判断。+- **口味**:综合观看、反馈、馆藏积累、浏览记录及关注关系。可读取 115、QQ、360、Aside、Chrome、Edge、Firefox 等本机浏览器,也可添加资料目录;目录与格式范围见[浏览器历史导入](docs/BROWSER_HISTORY.md)。停止同步与删除已导入记录分别管理。社媒访问按已登记账号和人物身份判断。- **设置**:弹窗按外观与导航、浏览与播放、JAV 与新作、搜索与推荐、内容显示分类;「Peach 配置」集中管理媒体入库、来源订阅、下载渠道、网络访问与应用维护。- **多端**:电脑、平板、手机的浏览器都能用。diff --git a/docs/BROWSER_HISTORY.md b/docs/BROWSER_HISTORY.mdnew file mode 100644index 000000000..81dc9d9f7--- /dev/null+++ b/docs/BROWSER_HISTORY.md@@ -0,0 +1,34 @@+# 浏览器历史导入++「口味」读取网页访问记录。自动发现覆盖默认资料目录;便携版、自定义安装和自定义 Firefox 资料可在「浏览器」中添加资料目录或历史文件。文件格式按 SQLite 表结构识别,不由浏览器名称或文件名决定。++## 目录范围++| 平台 | 自动发现 |+| --- | --- |+| Windows | Chrome、Chromium、Edge、Firefox、Zen、Aside、Brave、Vivaldi、Opera、Opera GX、115、QQ、360 安全、360 极速、360 极速 X、搜狗新版、2345、Maxthon |+| 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`,网页历史可存于 `HistoryEx`。本机实际文件同时含 `urls`、`visits` 与下载表,自动发现、选择文件、选择 `Default` 或 `User Data` 目录均已验收。[115 官方下载故障说明](https://115.com/115115/T344887.html)也引用此文件,但不能据此将整个文件视为仅有下载记录。只有不含可识别网页访问表的文件才会被拒绝;下载表本身不计入口味。+- **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)记录的表结构与标准网页访问表不同;完整时间字段语义未取得。+- **2345**:`%LOCALAPPDATA%\2345Explorer\User Data`,依据[官方帮助](https://ie.2345.cc/help/v7/help_scj.htm)确认资料目录;历史文件仍需满足受支持的 SQLite 表结构。+- **Maxthon**:同时查找 `%LOCALAPPDATA%\Maxthon\User Data` 与 `%LOCALAPPDATA%\Maxthon\Application\User Data`。前者见 [Winapp2 维护源码](https://github.com/MoscaDotTo/Winapp2/blob/master/Non-CCleaner/Winapp2.ini),后者见[官方社区实际目录](https://forum.maxthon.com/d/6744-aimax--cant-turn-off/5);[官方答复](https://forum.maxthon.com/d/3314-restore-last-visit-page-after-update-)确认 `History` 为资料中的历史文件。旧版专有 `.dat` 不在标准 SQLite 解析范围内。+- **Opera**:具体资料目录可从 `opera:about/` 查看,见[官方帮助](https://help.opera.com/en/latest/crashes-and-issues/)。++Chrome、Chromium 的资料路径以[官方说明](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md)和 `chrome://version` 的 `Profile Path` 为准;`--user-data-dir` 指定的任意位置需手动添加。++Firefox 自定义资料可以从 `about:profiles` 找到根目录后手动添加。官方源码中,[`profiles.ini`](https://github.com/mozilla-firefox/firefox/blob/main/toolkit/profile/nsToolkitProfileService.cpp) 的相对路径基于 Firefox 根目录;新版 [Profile Groups](https://github.com/mozilla-firefox/firefox/blob/main/toolkit/profile/ProfilesDatastoreService.sys.mjs) 记录在独立 SQLite 配置里。Peach 自动查找默认资料位置,不解析这两类配置中的外置位置。UC 的 [Autopsy 目录规则](https://github.com/sleuthkit/autopsy/blob/develop/RecentActivity/src/org/sleuthkit/autopsy/recentactivity/Chromium.java)包含 `UCBrowser/User Data%`,存在资料目录与文件名后缀差异,未列入自动发现承诺;可手动选择历史文件,按实际格式校验。++## 验证与限制++浏览器数据库先经 SQLite backup 取得一致快照,再由固定的 `browserexport==0.4.4` 转换访问时间与记录。Chrome 的可选停留时长、Firefox 的可选描述与预览图缺失时仍可读取;一份资料损坏不阻断其他资料。原始 URL 与标题只保存在私有历史库,不进入 ledger。++临时 SQLite 回归覆盖目录发现、手动添加、停止与恢复、增量去重、可选列、错误格式、特殊路径字符及本机单份失败隔离。本机 115 的真实文件已在临时私有库完成读取与重复导入验收,源文件哈希保持一致;记录仅保留计数和通过状态,没有 URL 或标题。其他浏览器的目录支持不表示已对其当前版本完成实机验收。issue [#65](https://github.com/peach-mitao/peach/issues/65) 报告者环境仍待修复版本发布后复测。++桌面与手机页面沿用现有浏览器来源管理,本次没有布局或交互改动。diff --git a/src/peach/taste_browsers.py b/src/peach/taste_browsers.pyindex ef9524196..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", "HistoryEx", "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,9 +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", "HistoryEx": "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 4484a7a6b..8ce77ad6c 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,26 +120,43 @@ 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")+ use_environment = home is Nonehome = 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") or home / "AppData" / "Roaming")+ if use_environment else home / "AppData" / "Roaming")+ localappdata = localappdata or (Path(os.environ.get("LOCALAPPDATA") or home / "AppData" / "Local")+ if use_environment else home / "AppData" / "Local")candidates.extend([("firefox", appdata / "Mozilla" / "Firefox" / "Profiles"),("zen", appdata / "zen" / "Profiles"),("chrome", localappdata / "Google" / "Chrome" / "User Data"),- ("115", localappdata / "115Chrome" / "User Data"),("aside", localappdata / "Aside" / "User Data"),("edge", localappdata / "Microsoft" / "Edge" / "User Data"),("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"),+ ("2345", localappdata / "2345Explorer" / "User Data"),+ ("maxthon", localappdata / "Maxthon" / "Application" / "User Data"),+ ("maxthon", localappdata / "Maxthon" / "User Data"),+ ("chromium", localappdata / "Chromium" / "User Data"),])- else:+ elif platform_name == "macos":candidates.extend([("firefox", home / "Library" / "Application Support" / "Firefox" / "Profiles"),@@ -145,16 +166,31 @@ 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") or home / ".config")+ if use_environment else 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 "HistoryEx" if browser == "115" 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"))@@ -166,7 +202,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:@@ -195,7 +231,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:@@ -302,7 +368,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 f6db69862..5a3de26c5 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,41 @@ 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",+ "2345": local / "2345Explorer/User Data/Default/History",+ "maxthon": local / "Maxthon/Application/User Data/Default/History",+ "chromium": local / "Chromium/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_discovers_windows_115_historyex_profiles(self):home = self.root.resolve()@@ -163,6 +191,86 @@ class TasteHistoryTests(unittest.TestCase):self.assertEqual(refresh_history(sources, store, host="test")[0]["added"], 1)self.assertEqual(refresh_history(sources, store, host="test")[0]["added"], 0)+ 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)}), \+ mock.patch("pathlib.Path.home", return_value=self.root):+ sources = discover_history_sources(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)}), \+ mock.patch("pathlib.Path.home", return_value=self.root):+ sources = discover_history_sources(platform_name="linux")+ self.assertEqual({source.path for source in sources}, set(paths))+def test_the_history_store_has_one_entry_point(self):"""打开私有历史库的前导只许有一份。