Peach: Local-first video metadata scraper and media manager.
feat(processing): 断网时跳过外部采集,联网恢复后自动重试
longmeidao728a84a78229
diff --git a/docs/SOURCING.md b/docs/SOURCING.mdindex 493d48a1b..2a9fc3c1c 100644--- a/docs/SOURCING.md+++ b/docs/SOURCING.md@@ -32,6 +32,15 @@连不上外网时,每个页面顶部出现一条横幅,指向「网络与访问 → Peach 代理」。判定来自服务端:有页面读取 `/api/network-status` 后,后台按 Peach 代理设置访问 `www.msftconnecttest.com` 与 `captive.apple.com` 两个系统联网检测地址,任一个返回预期正文就算联网;正常十分钟、断网时一分钟复查一次,保存代理设置后立即重探。+资料处理在「采集外部资料与封面」开始前用同一判定当场探一次。判为断网时不再逐个尝试来源:要联网的作品记为可重试的「外部资料未取得:连不上外网」,补人物资料跳过,后继照常派发,任务以部分完成收尾。全新实例第一次处理时没有网络,结果如下:++- 扫描文件、读取媒体属性与检查垃圾、检查配套文件、生成视频预览四步照常完成。+- 有 NFO 的作品按 NFO 写入标题、演员、厂牌等资料,本地海报照常装上;文件名读得出番号的仍留在重试集合里,联网后再与外部来源核对。+- 没有 NFO 的作品只有文件名、番号和九宫格预览。+- 外网判定从断网变回联网时,Peach 自动对最近一趟发起一次「重试未完成项」,补齐外部资料与封面。同一次恢复只触发一次;只读端不自动发起,重试仍失败时在处理卡片上手动重试。++命令行 `peach process` 不做断网判定,照旧逐个尝试来源。补厂牌官网与标识的后继在候选官网一个都连不上时,只把这家挡一天,之后存量补派会再派到它。+跟随环境时,HTTP 客户端读取进程代理环境变量,浏览器使用系统代理;两者不保证采用相同出口。应用直连不能排除操作系统 TUN。设置对新建客户端生效,已经运行的任务或长连接沿用创建时的设置。浏览器直接加载的外站图片与用户打开的外链由浏览器自身网络设置决定。本机健康检查、浏览器控制接口、writer 镜像、用户自配 Torznab 索引器和 CloudDrive 挂载连接使用各自的网络边界。CloudDrive 的 API/数据代理仍在媒体库设置中管理;Git、glab、rclone、cloudflared 与构建工具的联网由各工具配置负责。可独立构建的 FFmpeg 对应源码归档不包含 Peach 应用,归档内下载脚本使用系统环境代理。diff --git a/src/peach/api.py b/src/peach/api.pyindex d1bebc0f9..dae0be0d6 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -382,7 +382,15 @@ def create_app(from .mount_reachability import source_rootsmount_reachability = MountReachability(source_roots())from .network_reachability import NetworkReachability- network_reachability = NetworkReachability()+ from .web_library_processing import retry_after_network_recovery++ def network_recovered():+ # 只读端不发起处理:路由层会拒的写入,从探测线程绕进来也不该做。+ if sync is None or not sync.read_only:+ retry_after_network_recovery(contract)+ network_reachability = NetworkReachability(on_recovered=network_recovered)+ # 处理任务在外部采集前按它判断网(`library_processing._network_gate`)。+ contract.network_reachability = network_reachabilityresolver = FFmpegResolver(settings.ffmpeg_root)http_transport = HttpxTransport()follow_media_resolver = FollowMediaResolver(http_transport).with_credential_loader(diff --git a/src/peach/library_processing.py b/src/peach/library_processing.pyindex 769bc2f74..61e2b9fce 100644--- a/src/peach/library_processing.py+++ b/src/peach/library_processing.py@@ -256,6 +256,8 @@ MISS_MESSAGES = {'querying_metadata': '外部来源没有这部片的资料,7'fetching_cover': '外部来源没有这部片的封面,7 天内不再问'}#: 日志里的写法反查回上面的键,界面按键取自己的短标签。NOTE_KEYS = {message: key for key, message in MISS_MESSAGES.items()}+#: 外网不通时要出网的那些行不去问,直接记这一句;联网之后可以重试(`network_reachability`)。+OFFLINE_MESSAGE = '外部资料未取得:连不上外网'#: 状态文件与候选 CSV 的落盘节流。页面轮询读的是内存里的任务快照,文件只为进程没了#: 之后还能看到最后状态;候选 CSV 随处理进度越写越大,每条资产都重写一遍是平方级开销。@@ -1531,10 +1533,7 @@ class _RemoteSession:if not _scrapes_as_jav(row, code):return entries, coverschain = self._chain(code, *_studio_evidence(row))- # 链上剩下的站都给过候选或说过没有、且至少有一家给过候选:这一行不是「没取到」,- # 只是没有新的可问,不进告知项。- if missing and chain and (self._askable(chain, code, answered)- or not set(answered).intersection(chain)):+ if self._asks_metadata(chain, code, missing, answered):entries = self._metadata(row, code, missing, update=update, issue=issue, answered=answered,received=received)if fetch_cover and _asks_cover(code, *_studio_evidence(row)) and not cover_settled(cover_root / (code + '.jpg')):@@ -1543,6 +1542,21 @@ class _RemoteSession:snapshots=snapshots, absent=absent)return entries, covers+ def asks(self, row, code, missing, cover_root, *, answered=(), fetch_cover=True):+ """`collect` 这一行会不会去问外部来源,判据与它逐条相同。断网时只把要问的行记成未取得。"""+ if not _scrapes_as_jav(row, code):+ return False+ chain = self._chain(code, *_studio_evidence(row))+ return (self._asks_metadata(chain, code, missing, answered)+ or bool(fetch_cover and _asks_cover(code, *_studio_evidence(row))+ and not cover_settled(cover_root / (code + '.jpg'))))++ def _asks_metadata(self, chain, code, missing, answered):+ # 链上剩下的站都给过候选或说过没有、且至少有一家给过候选:这一行不是「没取到」,+ # 只是没有新的可问,不进告知项。+ return bool(missing and chain and (self._askable(chain, code, answered)+ or not set(answered).intersection(chain)))+def _cover_inputs(self, code, chain, entries):"""封面那一步不必再问的:手上已有的快照 `[(来源, 资料)]`,与说过没有或不在链上的站。@@ -2095,6 +2109,21 @@ def _people_allowed(config):return any('people' in stages for stages in media_identity.stages_by_root(config).values())+def _network_gate(network, update):+ """外部采集开始前当场探一次外网,返回之后每一行用的判定:读探测器最近的快照。++ 只有两次探测都连不上(`offline`)才算断网;代理设置待选(`unknown`)照常采集,判不准的+ 结论不拦。快照可能是十分钟前的,所以开头不读旧快照而是同步探一次,断网时最多等约 20 秒。+ 探测线程顺带拉起:断网首扫之后没人打开页面,联网恢复也要有人发现。+ """+ if network is None:+ return lambda: False+ update(stage='检查外网连接', current_action='', current_started_at=None, current_deadline_at=None)+ network.tick()+ network.start()+ return lambda: network.summary().get('state') == 'offline'++def _collect_allowed(remote, traffic, row, code, missing, allowed, cover_root, covered, *,update, issue, answered, received, succeeded):"""按这一行所属媒体库的处理方式问外部来源(ADR-0116),返回 (证据条目, 新落盘的封面数)。@@ -2201,14 +2230,16 @@ def _candidate_scope(groups, asset_ids):def _finish_collection(config, database, candidate_root, cover_root, groups, remote, *,- asset_ids, active, update, issue, watermark, covered, people=True):+ asset_ids, active, update, issue, watermark, covered, people=True, offline=False):"""结算本趟候选并补人物资料,全库任务同时推进存量后继。- `people` 为假(没有哪个媒体库的处理方式联网补人物图片)时不补人物资料,也不派实体后继。"""+ `people` 为假(没有哪个媒体库的处理方式联网补人物图片)时不补人物资料,也不派实体后继。+ `offline` 为真时只跳过补人物资料:后继照派,这一趟登记的实体过了这一趟就不再算新登记,+ 恢复后的重试趟派不到它们。"""auto_apply = _apply_finished_candidates(database, candidate_root, active, asset_ids)profiles = (_enrich_finished_performers(database, _candidate_scope(groups, asset_ids), config, candidate_root, remote, active, update, issue)- if people else dict(aliases=0, avatars=0, conflicts=0, failed=0))+ if people and not offline else dict(aliases=0, avatars=0, conflicts=0, failed=0))followups = [] if asset_ids is not None else sample_followup.plan(database, config, cover_root)if people:followups += _entity_followups(database, config, watermark, covered, include_stock=asset_ids is None)@@ -2587,7 +2618,8 @@ def _restore_processing_counts(state, previous):"""同一处理任务沿用累计数、问题清单和已保存证据索引。"""previous = previous or {}for key in ('started_at', 'identified', 'covers', 'previews', 'probed', 'issue_count', 'paused_count',- 'issue_preview', 'issues_truncated', 'notes', 'retryable_asset_ids', 'junk_isolated', 'junk_review'):+ 'issue_preview', 'issues_truncated', 'notes', 'retryable_asset_ids', 'junk_isolated', 'junk_review',+ 'offline_skipped'):if key in previous:state[key] = previous[key]for key in ('scan_checkpoints', 'local_metadata'):@@ -2690,7 +2722,7 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='coretry_ids=None, active=lambda: True, stage=ALL_STAGES,database=None, route_overrides=None, state_file=None, asset_ids=None,resume_state=None, speed_mode=None, protected_ids=(), recheck_existing=False,- incremental=False):+ incremental=False, network=None):"""登记文件与确定的番号,外部资料保留为可复核候选。`retry_ids` 为 `None` 时处理整个馆藏;给定时只处理这些项目(上一任务记录的@@ -2707,6 +2739,9 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co`route_overrides` 覆盖某几种内容类型的来源链,形状与判据见`metadata_routes.parse_route_overrides`;不给就用内建那张表。`state_file` 给后台定向任务保存独立进度,共享候选写入仍使用全库处理锁。+ `network` 是 `NetworkReachability`:外部采集开始前当场探一次,判成断网时要出网的行记为+ 可重试的「外部资料未取得」、补人物资料整段跳过,本地那几步照常做完;之后每一行读它的快照。+ 不给就不判,命令行走这条。"""selected_ids = _validate_processing_request(config, db_path, stage, asset_ids, retry_ids, database)from .repository import LedgerDatabase@@ -2743,7 +2778,7 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='colast_progress_at=time.time(), progress_seq=0,current_asset_id=None, current_asset_name='', current_action='',current_started_at=None, current_deadline_at=None,- followups=[],+ followups=[], offline_skipped=0,junk_isolated=0, junk_review=0,started_at=time.time(), error='')state.update(initial_estimate(config, db_path, stage, initial_ids, speed_mode))@@ -2934,9 +2969,11 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co_check_processing_junk(judgement_database, locations, sources.online_roots,scope_ids, protected_ids, state, update)prepared = _active_prepared(judgement_database, prepared)+ offline = _network_gate(network, update)from .metadata_amane import PreparationErrortry:- remote.prepare(prepared, stages_of, update, cover_root=cover_root, groups=groups)+ if not offline():+ remote.prepare(prepared, stages_of, update, cover_root=cover_root, groups=groups)except PreparationError as error:message = f'采集工具准备失败:{error}'issue(None, message, action='preparing_sources')@@ -2954,10 +2991,18 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='cocurrent_asset_name=Path(str(row['name'] or '')).name)target_key = f"asset:{row['id']}"missing = list(COLLECTED_FIELDS) if verify_existing else _missing_fields(row, local_fields)+ answered = () if verify_existing else _answered_sources(groups, target_key, missing)+ allowed = stages_of(row['path'])+ if offline() and remote.asks(row, code, missing if 'metadata' in allowed else [], cover_root,+ answered=answered, fetch_cover='cover' in allowed):+ # 不进断点:这一行这一趟没做完,末尾也不从待补全集合里摘掉。+ issue(row, OFFLINE_MESSAGE, action='network_offline', retryable=True)+ update(offline_skipped=state['offline_skipped'] + 1, checked=completed_count + position + 1,+ current_asset_id=None, current_asset_name='', current_action='')+ continuefound, covers = _collect_allowed(- remote, traffic, row, code, missing, stages_of(row['path']), cover_root, covered,- update=update, issue=issue,- answered=() if verify_existing else _answered_sources(groups, target_key, missing),+ remote, traffic, row, code, missing, allowed, cover_root, covered,+ update=update, issue=issue, answered=answered,received=lambda entries, row=row, code=code, fields=local_fields, verify=verify_existing:publish(row, code, fields, verify, entries),succeeded=lambda before=issues_before: state['issue_count'] == before)@@ -2976,7 +3021,7 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='cosummary = _finish_collection(config, database, candidate_root, cover_root, groups, remote, asset_ids=scope_ids,active=active, update=update, issue=issue, watermark=entity_watermark, covered=covered,- people=_people_allowed(config))+ people=_people_allowed(config), offline=offline())finish_step('collect')_settle_collection_state(state, summary, rows, update)except Exception:diff --git a/src/peach/network_reachability.py b/src/peach/network_reachability.pyindex 277d79805..db0bd1193 100644--- a/src/peach/network_reachability.py+++ b/src/peach/network_reachability.py@@ -40,11 +40,17 @@ def probe(timeout: float = PROBE_TIMEOUT) -> bool | None:class NetworkReachability:- """后台线程按节律探测;`refresh()` 让下一轮立即开始,用于代理设置刚保存时。"""+ """后台线程按节律探测;`refresh()` 让下一轮立即开始,用于代理设置刚保存时。- def __init__(self, *, check=probe, wall_clock=time.time, retry_delay=1.0):+ `on_recovered` 在判过 `offline` 之后第一次判回 `online` 时调一次,在探测所在的线程里跑;+ 中间夹着的 `unknown` 不算恢复也不算断开。+ """++ def __init__(self, *, check=probe, wall_clock=time.time, retry_delay=1.0, on_recovered=None):self.check, self.wall_clock, self.retry_delay = check, wall_clock, retry_delay+ self.on_recovered = on_recoveredself._state, self._checked_at = "checking", None+ self._down = Falseself._lock = threading.Lock()self._stop = threading.Event()self._wake = threading.Event()@@ -84,6 +90,12 @@ class NetworkReachability:state = {True: "online", False: "offline"}.get(result, "unknown")with self._lock:self._state, self._checked_at = state, self.wall_clock()+ recovered = self._down and state == "online"+ if state != "unknown":+ self._down = state == "offline"+ # 回调在锁外:它多半要回头读 `summary()`。+ if recovered and self.on_recovered is not None:+ self.on_recovered()return statedef summary(self) -> dict:diff --git a/src/peach/web_library_processing.py b/src/peach/web_library_processing.pyindex 3ff9d874f..dc50e750f 100644--- a/src/peach/web_library_processing.py+++ b/src/peach/web_library_processing.py@@ -1,6 +1,7 @@"""统一处理任务的启动、只读状态查询与失败项重试。"""import jsonimport hashlib+import loggingfrom . import settings_filefrom .library_processing import (ALL_STAGES, COLLECT_STAGE, SCAN_STAGE, STAGES,@@ -9,6 +10,7 @@ from .library_processing import (ALL_STAGES, COLLECT_STAGE, SCAN_STAGE, STAGES,from .processing_control import control_for, initial_estimate, valid_mode, mode_ratioACTIVE = ('running', 'pausing', 'paused', 'stopping')+LOGGER = logging.getLogger(__name__)#: 回给页面的状态字段:`frontend/src/react/library-processing/library-processing.ts` 的#: `LibraryProcessingData`,加上对应任务中心那一行的 `run_id` 与发起方式 `trigger`。状态文件里另有续跑用的 `local_metadata`(带完整媒体路径)、@@ -356,6 +358,24 @@ def _processing_request(contract, config, previous, body):return retry_ids, asset_ids, stage+def retry_after_network_recovery(contract):+ """外网判回联网时,上一趟因断网跳过的外部资料自动补一次,等于替人点「立即重试」。++ 只认最近一趟以失败收尾、记过断网跳过(`offline_skipped`)且还有可重试项的;在跑的、+ 只是别的原因失败的都不碰。由 `NetworkReachability.on_recovered` 在探测线程里调,+ 这里的任何异常都只记日志:只读端会被拒,探测线程不能因此停掉。+ """+ try:+ previous = _current(contract)+ if (previous.get('status') != 'failed' or not previous.get('offline_skipped')+ or not previous.get('retryable_asset_ids')):+ return None+ return w_library_processing(contract, {'job_id': previous.get('job_id'), 'retry': []})+ except Exception:+ LOGGER.warning('联网恢复后自动重试未完成项失败', exc_info=True)+ return None++def w_library_processing(contract, body, *, resume=False):config = settings_file.active()if (body or {}).get('action'):@@ -384,7 +404,8 @@ def w_library_processing(contract, body, *, resume=False):database=contract.database,resume_state=previous if resume else None,speed_mode=control_for(config).mode,- active=lambda: (contract.library_processing_job.snapshot() or {}).get('job_id') == job_id,+ network=getattr(contract, 'network_reachability', None),+ active=lambda:(contract.library_processing_job.snapshot() or {}).get('job_id') == job_id,report=lambda state: contract.library_processing_job.update(job_id, **{key: value for key, value in state.items() if key != 'job_id'}))contract.library_processing_job.update(job_id, **{key: value for key, value in result.items() if key != 'job_id'})diff --git a/tests/test_metadata_library.py b/tests/test_metadata_library.pyindex b188e75b1..5c035f5f0 100644--- a/tests/test_metadata_library.py+++ b/tests/test_metadata_library.py@@ -866,6 +866,28 @@ class LibraryNfoTests(unittest.TestCase):self.assertEqual(q_library_processing(contract, {})['job_id'], 'one')worker.assert_not_called()+ def test_network_recovery_retries_only_a_run_that_skipped_rows_offline(self):+ from peach.web_library_processing import retry_after_network_recovery+ cases = {+ 'skipped offline': ({'status': 'failed', 'offline_skipped': 2, 'retryable_asset_ids': [1, 2]}, True),+ 'failed for other reasons': ({'status': 'failed', 'offline_skipped': 0, 'retryable_asset_ids': [1]}, False),+ 'still running': ({'status': 'running', 'offline_skipped': 2, 'retryable_asset_ids': [1]}, False),+ 'nothing left': ({'status': 'failed', 'offline_skipped': 2, 'retryable_asset_ids': []}, False),+ }+ for name, (live, expected) in cases.items():+ with self.subTest(name):+ contract = Mock()+ contract.library_processing_job.thread = None+ contract.library_processing_job.snapshot.return_value = {**live, 'job_id': 'one', 'started_at': 1}+ with patch('peach.web_library_processing.settings_file.active'), \+ patch('peach.web_library_processing.snapshot', return_value={}), \+ patch('peach.web_library_processing.w_library_processing') as start:+ retry_after_network_recovery(contract)+ if expected:+ start.assert_called_once_with(contract, {'job_id': 'one', 'retry': []})+ else:+ start.assert_not_called()+@windows_ledger_rootsdef test_processing_auto_applies_safe_nfo_fields_before_it_finishes(self):media = self.root / 'media'@@ -1115,6 +1137,59 @@ class LibraryNfoTests(unittest.TestCase):self.assertEqual((provider.query.call_count, provider.community.call_count, provider.amane.call_count),asked)+ @windows_ledger_roots+ def test_offline_scan_finishes_locally_and_leaves_only_remote_rows_for_retry(self):+ """断网首扫:NFO 资料照落,要出网的行记成可重试,一个来源都不问;联网后重试补齐。++ 有 NFO 的作品联网时也要拿外部来源核对一遍,所以它同样留给重试;不出网的行不记。"""+ from PIL import Image+ from peach.library_processing import OFFLINE_MESSAGE+ from peach.network_reachability import NetworkReachability+ media = self.root / 'media'+ media.mkdir()+ (media / 'ABW-358.mp4').write_bytes(b'video')+ (media / 'ABW-358.nfo').write_text(+ '<movie><title>Local title</title><sorttitle>ABW-358</sorttitle><studio>Studio</studio>'+ '<premiered>2023-05-26</premiered><actor><name>涼森れむ</name></actor><tag>自定义标签</tag></movie>',+ encoding='utf-8')+ Image.new('RGB', (600, 900), 'blue').save(media / 'ABW-358-poster.jpg')+ (media / 'SSIS-057.mp4').write_bytes(b'video')+ # 文件名读不出番号的本地作品:有 NFO 也不问外部来源,断网时不进重试。+ (media / 'holiday.mp4').write_bytes(b'video')+ (media / 'holiday.nfo').write_text('<movie><title>假期</title></movie>', encoding='utf-8')+ db = fresh_ledger(self.root)+ config = PeachConfig(self.root, self.root / 'config.toml', present=True, locations={'local': (str(media),)})+ provider = stub_provider()+ provider.query.return_value = {'id': 'SSIS-057', 'title': '作品资料'}+ provider.cover.return_value = False+ factory = Mock(return_value=provider)+ generated, covers = self.root / 'generated', self.root / 'covers'+ offline = NetworkReachability(check=lambda: False, retry_delay=0)+ self.addCleanup(offline.stop)++ # 只看资料:测试里的假视频生成不了预览,那一步的失败会混进重试集合。+ process_library(config, db, generated, covers, stage='scan')+ result = process_library(config, db, generated, covers, provider_factory=factory, stage='metadata',+ database=LedgerDatabase(db), network=offline)++ self.assertEqual(provider.method_calls, [])+ self.assertEqual((result['status'], result['offline_skipped']), ('failed', 2))+ with closing(sqlite3.connect(db)) as connection:+ ids = dict(connection.execute('SELECT name,id FROM asset'))+ title = connection.execute("SELECT catalog_title FROM asset WHERE code='ABW-358'").fetchone()[0]+ self.assertEqual(title, 'Local title')+ self.assertEqual(sorted(result['retryable_asset_ids']), sorted([ids['ABW-358.mp4'], ids['SSIS-057.mp4']]))+ self.assertIn('holiday.mp4', ids)+ self.assertEqual({issue['message'] for issue in result['issue_preview']}, {OFFLINE_MESSAGE})++ online = NetworkReachability(check=lambda: True, retry_delay=0)+ self.addCleanup(online.stop)+ retried = process_library(config, db, generated, covers, provider_factory=factory,+ database=LedgerDatabase(db), network=online,+ retry_ids=result['retryable_asset_ids'])+ self.assertEqual(retried['offline_skipped'], 0)+ self.assertEqual({call.args[0] for call in provider.query.call_args_list}, {'ABW-358', 'SSIS-057'})+@windows_ledger_rootsdef test_local_nfo_fields_keep_remote_differences_for_review(self):"""本地字段优先补空,在线不同值保留为覆盖复核候选。"""diff --git a/tests/test_network_reachability.py b/tests/test_network_reachability.pyindex 9e8694953..ca0928731 100644--- a/tests/test_network_reachability.py+++ b/tests/test_network_reachability.py@@ -38,6 +38,19 @@ class NetworkReachabilityTests(unittest.TestCase):monitor, _ = self.monitor(False, False)self.assertEqual(monitor.tick(), "offline")+ def test_recovery_from_offline_fires_once(self):+ monitor, calls = self.monitor(True, False, False, None, True, True)+ recovered = []+ monitor.on_recovered = lambda: recovered.append(monitor.summary()["state"])+ self.assertEqual(monitor.tick(), "online")+ self.assertEqual(monitor.tick(), "offline")+ self.assertEqual(monitor.tick(), "unknown")+ self.assertEqual(recovered, [])+ self.assertEqual(monitor.tick(), "online")+ self.assertEqual(monitor.tick(), "online")+ self.assertEqual(recovered, ["online"])+ self.assertEqual(calls, [])+def test_undecidable_settings_and_errors_are_unknown(self):monitor, _ = self.monitor(None)self.assertEqual(monitor.tick(), "unknown")