goofish-cli 0.6.0__tar.gz → 0.6.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/.claude-plugin/marketplace.json +1 -1
  2. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/CHANGELOG.md +14 -0
  3. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/PKG-INFO +2 -2
  4. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/README.md +1 -1
  5. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/pyproject.toml +1 -1
  6. goofish_cli-0.6.2/src/goofish_cli/commands/item/view.py +117 -0
  7. goofish_cli-0.6.2/src/goofish_cli/core/item_page.py +183 -0
  8. goofish_cli-0.6.0/src/goofish_cli/commands/item/view.py +0 -241
  9. goofish_cli-0.6.0/src/goofish_cli/core/item_page.py +0 -141
  10. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/.gitignore +0 -0
  11. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/LICENSE +0 -0
  12. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/NOTICE +0 -0
  13. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/examples/README.md +0 -0
  14. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-overview/SKILL.md +0 -0
  15. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-overview/references/accounts.md +0 -0
  16. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-overview/references/mcp-tools-index.md +0 -0
  17. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-overview/references/xianyu-concepts.md +0 -0
  18. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-publish-item/SKILL.md +0 -0
  19. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-publish-item/references/category-selection.md +0 -0
  20. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-publish-item/references/common-pitfalls.md +0 -0
  21. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-publish-item/references/image-checklist.md +0 -0
  22. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-publish-item/references/title-formula.md +0 -0
  23. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-reply-buyer/SKILL.md +0 -0
  24. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-reply-buyer/references/bargain-ladder.md +0 -0
  25. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-reply-buyer/references/intent-classification.md +0 -0
  26. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-reply-buyer/references/tone-guide.md +0 -0
  27. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-risk-guard/SKILL.md +0 -0
  28. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-risk-guard/references/external-contact-keywords.md +0 -0
  29. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-risk-guard/references/forbidden-words.md +0 -0
  30. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-risk-guard/references/publish-red-lines.md +0 -0
  31. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-risk-guard/references/x5sec-recovery.md +0 -0
  32. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-shop-diagnosis/SKILL.md +0 -0
  33. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-shop-diagnosis/references/diagnosis-workflow.md +0 -0
  34. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-shop-diagnosis/references/rank-factors.md +0 -0
  35. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/skills/goofish-shop-diagnosis/references/traffic-drop-causes.md +0 -0
  36. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/__init__.py +0 -0
  37. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/cli.py +0 -0
  38. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/__init__.py +0 -0
  39. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/auth/__init__.py +0 -0
  40. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/auth/login.py +0 -0
  41. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/auth/reset_guard.py +0 -0
  42. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/auth/status.py +0 -0
  43. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/category/__init__.py +0 -0
  44. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/category/recommend.py +0 -0
  45. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/item/__init__.py +0 -0
  46. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/item/delete.py +0 -0
  47. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/item/get.py +0 -0
  48. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/item/list.py +0 -0
  49. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/item/publish.py +0 -0
  50. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/location/__init__.py +0 -0
  51. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/location/default.py +0 -0
  52. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/media/__init__.py +0 -0
  53. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/media/upload.py +0 -0
  54. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/message/__init__.py +0 -0
  55. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/message/history.py +0 -0
  56. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/message/list_chats.py +0 -0
  57. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/message/send.py +0 -0
  58. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/message/watch.py +0 -0
  59. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/search/__init__.py +0 -0
  60. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/search/search.py +0 -0
  61. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/skills/__init__.py +0 -0
  62. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/commands/skills/install.py +0 -0
  63. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/__init__.py +0 -0
  64. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/browser.py +0 -0
  65. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/browser_cookie.py +0 -0
  66. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/cookie_types.py +0 -0
  67. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/crypto.py +0 -0
  68. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/errors.py +0 -0
  69. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/guard.py +0 -0
  70. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/item_data.py +0 -0
  71. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/limiter.py +0 -0
  72. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/local_state.py +0 -0
  73. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/message_history.py +0 -0
  74. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/mtop.py +0 -0
  75. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/output.py +0 -0
  76. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/qr_login.py +0 -0
  77. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/refresh.py +0 -0
  78. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/registry.py +0 -0
  79. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/sandbox_browser.py +0 -0
  80. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/search_data.py +0 -0
  81. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/session.py +0 -0
  82. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/sign.py +0 -0
  83. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/strategy.py +0 -0
  84. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/token.py +0 -0
  85. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/write_operation.py +0 -0
  86. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/core/ws.py +0 -0
  87. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/mcp_server.py +0 -0
  88. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/sandbox/__init__.py +0 -0
  89. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/sandbox/assets/Dockerfile +0 -0
  90. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/sandbox/assets/entrypoint.sh +0 -0
  91. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/sandbox/cli.py +0 -0
  92. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/sandbox/interactive.py +0 -0
  93. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/sandbox/runtime.py +0 -0
  94. {goofish_cli-0.6.0 → goofish_cli-0.6.2}/src/goofish_cli/static/goofish_js_version_2.js +0 -0
@@ -3,7 +3,7 @@
3
3
  "name": "goofish-cli-skills",
4
4
  "displayName": "goofish-cli Skills",
5
5
  "description": "闲鱼(goofish.com)自动化运营的 Claude Skills 套件。配合 goofish-cli MCP server 使用,让 Agent 在发布商品 / 回复买家 / 风控预检 / 店铺诊断这些场景里上手即会。",
6
- "version": "0.6.0",
6
+ "version": "0.6.2",
7
7
  "author": {
8
8
  "name": "fancy",
9
9
  "url": "https://github.com/fancyboi999"
@@ -4,6 +4,20 @@ All notable changes to this project will be documented in this file.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
5
  and this project adheres to [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [0.6.2](https://github.com/fancyboi999/goofish-cli/compare/v0.6.1...v0.6.2) (2026-10-26)
8
+
9
+
10
+ ### Bug Fixes
11
+
12
+ * **item:** read detail responses across page navigation ([#51](https://github.com/fancyboi999/goofish-cli/issues/51)) ([19830e0](https://github.com/fancyboi999/goofish-cli/commit/19830e030594ccd7aee4a2f1665e07d1af936cd7))
13
+
14
+ ## [0.6.1](https://github.com/fancyboi999/goofish-cli/compare/v0.6.0...v0.6.1) (2026-10-26)
15
+
16
+
17
+ ### Bug Fixes
18
+
19
+ * **item:** retry evaluate when the detail page navigates mid-read ([#48](https://github.com/fancyboi999/goofish-cli/issues/48)) ([f0299f8](https://github.com/fancyboi999/goofish-cli/commit/f0299f8533a253c661c5b21d9a3f061adf6f85e0))
20
+
7
21
  ## [0.6.0](https://github.com/fancyboi999/goofish-cli/compare/v0.5.3...v0.6.0) (2026-10-19)
8
22
 
9
23
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: goofish-cli
3
- Version: 0.6.0
3
+ Version: 0.6.2
4
4
  Summary: 闲鱼 CLI — 支持 MCP,未来支持 Claude Skills。为 AI Agent 提供闲鱼自动化基础能力。
5
5
  Project-URL: Homepage, https://github.com/fancyboi999/goofish-cli
6
6
  Project-URL: Repository, https://github.com/fancyboi999/goofish-cli
@@ -203,7 +203,7 @@ OpenClaw `2026.6.1` 及以上可把本仓库作为 compatible bundle 加载。
203
203
  openclaw plugins install clawhub:openclaw-goofish
204
204
 
205
205
  # 登录态由用户在终端初始化,不交给 Agent 覆盖
206
- uvx --from goofish-cli==0.6.0 goofish auth login --qr
206
+ uvx --from goofish-cli==0.6.2 goofish auth login --qr
207
207
 
208
208
  openclaw plugins inspect goofish --json
209
209
  openclaw gateway restart
@@ -162,7 +162,7 @@ OpenClaw `2026.6.1` 及以上可把本仓库作为 compatible bundle 加载。
162
162
  openclaw plugins install clawhub:openclaw-goofish
163
163
 
164
164
  # 登录态由用户在终端初始化,不交给 Agent 覆盖
165
- uvx --from goofish-cli==0.6.0 goofish auth login --qr
165
+ uvx --from goofish-cli==0.6.2 goofish auth login --qr
166
166
 
167
167
  openclaw plugins inspect goofish --json
168
168
  openclaw gateway restart
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "goofish-cli"
7
- version = "0.6.0"
7
+ version = "0.6.2"
8
8
  description = "闲鱼 CLI — 支持 MCP,未来支持 Claude Skills。为 AI Agent 提供闲鱼自动化基础能力。"
9
9
  readme = "README.md"
10
10
  license = { text = "Apache-2.0" }
@@ -0,0 +1,117 @@
1
+ """item view — 读取商品页自身的响应并校验身份。
2
+
3
+ 本机与沙箱共用页面响应读取器;取数不依赖页面 JavaScript 上下文。
4
+ 平台要求验证时明确报错并保留沙箱页面,由用户亲自处理。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import json
11
+ import os
12
+ import re
13
+ from typing import Any
14
+
15
+ from goofish_cli.core import Strategy, command
16
+ from goofish_cli.core.browser import goofish_page
17
+ from goofish_cli.core.errors import AuthRequiredError, GoofishError
18
+ from goofish_cli.core.item_data import normalize_item
19
+ from goofish_cli.core.item_page import read_item_page
20
+
21
+
22
+ def _normalize_item_id(value: Any) -> str:
23
+ s = str(value or "").strip()
24
+ if not re.fullmatch(r"\d+", s):
25
+ raise GoofishError(f"item_id 必须是数字,收到:{value!r}")
26
+ return s
27
+
28
+
29
+ def _view_result(raw: dict[str, Any], item_id: str) -> dict[str, Any]:
30
+ base = normalize_item(raw, item_id)
31
+ data = raw["data"]
32
+ item, seller = data["itemDO"], data.get("sellerDO") or {}
33
+
34
+ def clean(value):
35
+ return re.sub(r"\s+", " ", str(value if value is not None else "")).strip()
36
+
37
+ images = [
38
+ image["url"]
39
+ for image in item.get("imageInfos") or []
40
+ if isinstance(image, dict) and image.get("url")
41
+ ]
42
+ result = {key: value for key, value in base.items() if key not in {"raw", "seller_nick"}}
43
+ result.update(
44
+ title=clean(base["title"]),
45
+ description=clean(base["description"]),
46
+ price="¥" + clean(base["price"]) if base["price"] is not None else None,
47
+ original_price=clean(base["original_price"]),
48
+ seller_name=clean(base["seller_nick"]),
49
+ seller_id=clean(base["seller_id"]),
50
+ status=clean(base["status"]),
51
+ location=clean(base["location"]),
52
+ condition=clean(base["condition"]),
53
+ brand=clean(base["brand"]),
54
+ category=clean(base["category"]),
55
+ want_count=clean(item.get("wantCnt")),
56
+ collect_count=clean(item.get("collectCnt")),
57
+ browse_count=clean(item.get("browseCnt")),
58
+ seller_score=clean(seller.get("xianyuSummary")),
59
+ reply_ratio_24h=clean(seller.get("replyRatio24h")),
60
+ reply_interval=clean(seller.get("replyInterval")),
61
+ seller_url="https://www.goofish.com/personal?userId=" + clean(base["seller_id"])
62
+ if base["seller_id"] is not None
63
+ else "",
64
+ image_count=str(len(images)),
65
+ image_urls=images,
66
+ )
67
+ return result
68
+
69
+
70
+ async def _run(item_id: str) -> dict[str, Any]:
71
+ try:
72
+ async with goofish_page() as page:
73
+ raw = await read_item_page(page, item_id)
74
+ except GoofishError as exc:
75
+ # 沙箱沿用响应读取器的类型;本机保留原有 CLI 退出码和 MCP 错误类型。
76
+ ret = (exc.raw or {}).get("ret")
77
+ if os.environ.get("GOOFISH_DESKTOP_SANDBOX") == "1" or not ret:
78
+ raise
79
+ message = " | ".join(ret)
80
+ code = ret[0].partition("::")[0]
81
+ if "SESSION_EXPIRED" in message:
82
+ raise AuthRequiredError("mtop 返回 session 过期:" + message, raw=exc.raw) from exc
83
+ raise GoofishError(f"mtop 调用失败 [{code}]: {message}", raw=exc.raw) from exc
84
+ result = _view_result(raw, item_id)
85
+ if not result.get("title"):
86
+ raise GoofishError(f"未拿到商品 {item_id} 的标题,接口返回为空")
87
+ return result
88
+
89
+
90
+ @command(
91
+ namespace="item",
92
+ name="view",
93
+ description="浏览器视角查看商品详情(读取页面响应,含图片和卖家字段)",
94
+ strategy=Strategy.COOKIE,
95
+ columns=[
96
+ "item_id",
97
+ "title",
98
+ "price",
99
+ "condition",
100
+ "brand",
101
+ "location",
102
+ "seller_name",
103
+ "want_count",
104
+ "browse_count",
105
+ ],
106
+ )
107
+ def view(item_id: str) -> dict[str, Any]:
108
+ normalized = _normalize_item_id(item_id)
109
+ # MCP / table 渲染依赖 dict;image_urls 是列表(JSON 里保留,table 里压成长度)
110
+ result = asyncio.run(_run(normalized))
111
+ result["_image_urls_json"] = json.dumps(result.get("image_urls", []), ensure_ascii=False)
112
+ return result
113
+
114
+
115
+ __test__ = {
116
+ "_normalize_item_id": _normalize_item_id,
117
+ }
@@ -0,0 +1,183 @@
1
+ """读取详情页自身发出的响应,校验请求和返回的商品身份。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import math
8
+ import re
9
+ from typing import Any
10
+ from urllib.parse import parse_qs, urlsplit
11
+
12
+ from playwright.async_api import Error as PlaywrightError
13
+
14
+ from .errors import AuthRequiredError, GoofishError, RiskControlError
15
+ from .item_data import normalize_item
16
+ from .mtop import _classify_error
17
+
18
+ DETAIL_PATH = "/h5/mtop.taobao.idle.pc.detail/1.0/"
19
+ _TOKEN_REFRESH_CODES = {"FAIL_SYS_TOKEN_EMPTY", "FAIL_SYS_TOKEN_EXOIRED", "FAIL_SYS_TOKEN_EXPIRED"}
20
+
21
+
22
+ def _matches_request(request, item_id: str) -> bool:
23
+ url = urlsplit(request.url)
24
+ if url.hostname not in {"h5api.m.goofish.com", "h5api.m.taobao.com"} or url.path != DETAIL_PATH:
25
+ return False
26
+ try:
27
+ fields = parse_qs(request.post_data or "")
28
+ if "data" not in fields:
29
+ fields = parse_qs(url.query)
30
+ return str(json.loads(fields["data"][0]).get("itemId")) == item_id
31
+ except (ValueError, KeyError, TypeError, AttributeError):
32
+ return False
33
+
34
+
35
+ def _decode_response(text: str, item_id: str) -> dict:
36
+ if not text.lstrip().startswith("{"):
37
+ match = re.fullmatch(r"\s*[\w.$]+\s*\((.*)\)\s*;?\s*", text, re.S)
38
+ if not match:
39
+ raise GoofishError("详情响应不是可确认的 JSON/JSONP")
40
+ text = match[1]
41
+ try:
42
+ raw = json.loads(text)
43
+ except ValueError as exc:
44
+ raise GoofishError("详情响应无法解析") from exc
45
+ if not isinstance(raw, dict) or not isinstance(raw.get("ret"), list) or not raw["ret"]:
46
+ raise GoofishError("详情响应缺少明确的业务状态")
47
+ if not all(isinstance(value, str) for value in raw["ret"]):
48
+ raise GoofishError("详情响应业务状态格式无效")
49
+ try:
50
+ _classify_error(raw, "mtop.taobao.idle.pc.detail")
51
+ except RiskControlError as exc:
52
+ raise RiskControlError(
53
+ "闲鱼详情需要人工验证;请在浏览器完成验证后重试,不会自动绕过或重发请求",
54
+ raw=raw,
55
+ ) from exc
56
+ if any(value.partition("::")[0] != "SUCCESS" for value in raw["ret"]):
57
+ raise GoofishError("详情响应不是明确成功状态")
58
+ data = raw.get("data")
59
+ if not isinstance(data, dict) or not isinstance(data.get("itemDO"), dict):
60
+ raise GoofishError("详情响应缺少商品数据")
61
+ if data.get("sellerDO") is not None and not isinstance(data["sellerDO"], dict):
62
+ raise GoofishError("详情响应卖家数据格式无效")
63
+ for field in ("itemLabelExtList", "imageInfos"):
64
+ if data["itemDO"].get(field) is not None and not isinstance(data["itemDO"][field], list):
65
+ raise GoofishError(f"详情响应 {field} 格式无效")
66
+ normalize_item(raw, item_id)
67
+ return raw
68
+
69
+
70
+ class ItemResponse:
71
+ """只消费本次观察到的匹配请求,忽略推荐、验证端点和迟到的旧请求。"""
72
+
73
+ def __init__(self, page, item_id: str):
74
+ self.page = page
75
+ self.item_id = item_id
76
+ self.results: asyncio.Queue[dict | GoofishError] = asyncio.Queue()
77
+ self.last_error: GoofishError | None = None
78
+ self.requests: set[Any] = set()
79
+ self.tasks: set[asyncio.Task] = set()
80
+ self.request_handler = self._request
81
+ self.response_handler = self._schedule
82
+ self.failure_handler = self._failed
83
+ self.close_handler = lambda: self.results.put_nowait(GoofishError("商品详情页已关闭"))
84
+ page.on("request", self.request_handler)
85
+ page.on("response", self.response_handler)
86
+ page.on("requestfailed", self.failure_handler)
87
+ page.on("close", self.close_handler)
88
+
89
+ def _request(self, request) -> None:
90
+ if _matches_request(request, self.item_id):
91
+ self.requests.add(request)
92
+
93
+ def _failed(self, request) -> None:
94
+ self.requests.discard(request)
95
+
96
+ def _schedule(self, response) -> None:
97
+ if response.request not in self.requests:
98
+ return
99
+ self.requests.discard(response.request)
100
+ task = asyncio.create_task(self._capture(response))
101
+ self.tasks.add(task)
102
+ task.add_done_callback(self.tasks.discard)
103
+
104
+ async def _capture(self, response) -> None:
105
+ if response.status != 200:
106
+ self.results.put_nowait(GoofishError(f"详情服务返回 HTTP {response.status}"))
107
+ return
108
+ # 导航可能取消响应体读取;只等待页面后续的自然响应,不主动补发请求。
109
+ try:
110
+ text = await response.text()
111
+ except PlaywrightError:
112
+ self.last_error = GoofishError("详情响应读取中断,未收到后续成功响应")
113
+ return
114
+ try:
115
+ result: dict | GoofishError = _decode_response(text, self.item_id)
116
+ except GoofishError as exc:
117
+ ret = (exc.raw or {}).get("ret", [])
118
+ if ret and all(value.partition("::")[0] in _TOKEN_REFRESH_CODES for value in ret):
119
+ # SDK 会自行刷新 token 并重发;中间态不代表用户会话已失效。
120
+ self.last_error = AuthRequiredError("页面令牌刷新未完成", raw=exc.raw)
121
+ return
122
+ result = exc
123
+ self.results.put_nowait(result)
124
+
125
+ async def wait(self, timeout: float = 20, *, allow_verification: bool = False) -> dict:
126
+ deadline = asyncio.get_running_loop().time() + timeout
127
+ while True:
128
+ try:
129
+ remaining = deadline - asyncio.get_running_loop().time()
130
+ if remaining <= 0:
131
+ raise TimeoutError
132
+ result = await asyncio.wait_for(
133
+ self.results.get(), remaining
134
+ )
135
+ except TimeoutError as exc:
136
+ if self.last_error is not None:
137
+ raise self.last_error from exc
138
+ raise GoofishError(
139
+ "等待超时,未收到目标商品的成功详情响应;请检查网络及页面是否需要登录或人工验证"
140
+ ) from exc
141
+ if isinstance(result, GoofishError):
142
+ if allow_verification and isinstance(result, RiskControlError):
143
+ self.last_error = result
144
+ continue
145
+ raise result
146
+ return result
147
+
148
+ async def close(self) -> None:
149
+ self.page.remove_listener("request", self.request_handler)
150
+ self.page.remove_listener("response", self.response_handler)
151
+ self.page.remove_listener("requestfailed", self.failure_handler)
152
+ self.page.remove_listener("close", self.close_handler)
153
+ tasks = tuple(self.tasks)
154
+ for task in tasks:
155
+ task.cancel()
156
+ await asyncio.gather(*tasks, return_exceptions=True)
157
+ self.requests.clear()
158
+
159
+
160
+ async def read_item_page(page, item_id: str, *, timeout: float = 20) -> dict:
161
+ """导航与取数共享同一截止时间;页面上下文被替换不影响响应观察。"""
162
+ if not math.isfinite(timeout) or timeout <= 0:
163
+ raise GoofishError("详情读取超时必须为有限正数")
164
+ observer = ItemResponse(page, item_id)
165
+ deadline = asyncio.get_running_loop().time() + timeout
166
+ try:
167
+ await page.goto(
168
+ f"https://www.goofish.com/item?id={item_id}",
169
+ wait_until="commit",
170
+ timeout=timeout * 1000,
171
+ )
172
+ return await observer.wait(deadline - asyncio.get_running_loop().time())
173
+ except PlaywrightError as exc:
174
+ raise GoofishError("商品详情页加载失败或超时,请检查网络及浏览器状态") from exc
175
+ finally:
176
+ await observer.close()
177
+
178
+
179
+ async def fetch_item_page(item_id: str) -> dict:
180
+ from .browser import goofish_page
181
+
182
+ async with goofish_page() as page:
183
+ return await read_item_page(page, item_id)
@@ -1,241 +0,0 @@
1
- """item view — 浏览器商品详情。沙箱读取页面自身的响应并校验身份。
2
-
3
- 本机保留原有页面 SDK 调用;沙箱 item get 与 view 共用常驻浏览器路径。
4
- 平台要求验证时明确报错并保留沙箱页面,由用户亲自处理。
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import asyncio
10
- import json
11
- import os
12
- import re
13
- from typing import Any
14
-
15
- from goofish_cli.core import Strategy, command
16
- from goofish_cli.core.browser import goofish_page
17
- from goofish_cli.core.errors import AuthRequiredError, GoofishError
18
- from goofish_cli.core.item_data import normalize_item
19
- from goofish_cli.core.item_page import read_item_page
20
-
21
-
22
- def _normalize_item_id(value: Any) -> str:
23
- s = str(value or "").strip()
24
- if not re.fullmatch(r"\d+", s):
25
- raise GoofishError(f"item_id 必须是数字,收到:{value!r}")
26
- return s
27
-
28
-
29
- def _build_item_url(item_id: str) -> str:
30
- return f"https://www.goofish.com/item?id={item_id}"
31
-
32
-
33
- def _view_result(raw: dict[str, Any], item_id: str) -> dict[str, Any]:
34
- base = normalize_item(raw, item_id)
35
- data = raw["data"]
36
- item, seller = data["itemDO"], data.get("sellerDO") or {}
37
-
38
- def clean(value):
39
- return re.sub(r"\s+", " ", str(value if value is not None else "")).strip()
40
-
41
- images = [
42
- image["url"]
43
- for image in item.get("imageInfos") or []
44
- if isinstance(image, dict) and image.get("url")
45
- ]
46
- result = {key: value for key, value in base.items() if key not in {"raw", "seller_nick"}}
47
- result.update(
48
- title=clean(base["title"]),
49
- description=clean(base["description"]),
50
- price="¥" + clean(base["price"]) if base["price"] is not None else None,
51
- original_price=clean(base["original_price"]),
52
- seller_name=clean(base["seller_nick"]),
53
- seller_id=clean(base["seller_id"]),
54
- status=clean(base["status"]),
55
- location=clean(base["location"]),
56
- condition=clean(base["condition"]),
57
- brand=clean(base["brand"]),
58
- category=clean(base["category"]),
59
- want_count=clean(item.get("wantCnt")),
60
- collect_count=clean(item.get("collectCnt")),
61
- browse_count=clean(item.get("browseCnt")),
62
- seller_score=clean(seller.get("xianyuSummary")),
63
- reply_ratio_24h=clean(seller.get("replyRatio24h")),
64
- reply_interval=clean(seller.get("replyInterval")),
65
- seller_url="https://www.goofish.com/personal?userId=" + clean(base["seller_id"])
66
- if base["seller_id"] is not None
67
- else "",
68
- image_count=str(len(images)),
69
- image_urls=images,
70
- )
71
- return result
72
-
73
-
74
- # 页面上下文里运行的抽取脚本。直接复用 OpenCLI 的提取逻辑(DOM 文案检查 + mtop 调用)。
75
- _FETCH_JS = r"""
76
- (itemId) => (async () => {
77
- const clean = (v) => String(v ?? '').replace(/\s+/g, ' ').trim();
78
- const extractRetCode = (ret) => {
79
- const first = Array.isArray(ret) ? ret[0] : '';
80
- return clean(first).split('::')[0] || '';
81
- };
82
- const waitFor = async (predicate, timeoutMs = 5000) => {
83
- const start = Date.now();
84
- while (Date.now() - start < timeoutMs) {
85
- if (predicate()) return true;
86
- await new Promise((r) => setTimeout(r, 150));
87
- }
88
- return false;
89
- };
90
-
91
- const bodyText = document.body?.innerText || '';
92
- // 注意:「登录后」在页脚也会出现,不能作为 auth 判定;真正的未登录靠 mtop 返回的
93
- // FAIL_SYS_SESSION_EXPIRED 来判,这里只拦显式验证码/风控页。
94
- if (/验证码|安全验证|异常访问/.test(bodyText)) return { error: 'blocked' };
95
-
96
- await waitFor(() => window.lib?.mtop?.request);
97
- if (!window.lib || !window.lib.mtop || typeof window.lib.mtop.request !== 'function') {
98
- return { error: 'mtop-not-ready' };
99
- }
100
-
101
- let response;
102
- try {
103
- response = await window.lib.mtop.request({
104
- api: 'mtop.taobao.idle.pc.detail',
105
- data: { itemId: String(itemId) },
106
- type: 'POST',
107
- v: '1.0',
108
- dataType: 'json',
109
- needLogin: false,
110
- needLoginPC: false,
111
- sessionOption: 'AutoLoginOnly',
112
- ecode: 0,
113
- });
114
- } catch (error) {
115
- const ret = error?.ret || [];
116
- return {
117
- error: 'mtop-request-failed',
118
- error_code: extractRetCode(ret),
119
- error_message: clean(Array.isArray(ret) ? ret.join(' | ') : error?.message || String(error)),
120
- };
121
- }
122
-
123
- const retCode = extractRetCode(response?.ret || []);
124
- if (retCode && retCode !== 'SUCCESS') {
125
- return {
126
- error: 'mtop-response-error',
127
- error_code: retCode,
128
- error_message: clean((response?.ret || []).join(' | ')),
129
- };
130
- }
131
-
132
- const data = response?.data || {};
133
- const item = data.itemDO || {};
134
- const seller = data.sellerDO || {};
135
- const labels = Array.isArray(item.itemLabelExtList) ? item.itemLabelExtList : [];
136
- const findLabel = (name) => labels.find((l) => clean(l.propertyText) === name)?.text || '';
137
- const images = Array.isArray(item.imageInfos)
138
- ? item.imageInfos.map((e) => e?.url).filter(Boolean)
139
- : [];
140
-
141
- return {
142
- item_id: clean(item.itemId || itemId),
143
- title: clean(item.title || ''),
144
- description: clean(item.desc || ''),
145
- price: item.soldPrice == null || typeof item.soldPrice === 'boolean' || item.soldPrice === ''
146
- ? null : '¥' + clean(item.soldPrice),
147
- price_kind: item.defaultPrice === true ? 'negotiable' : 'fixed',
148
- original_price: clean(item.originalPrice || ''),
149
- want_count: String(item.wantCnt ?? ''),
150
- collect_count: String(item.collectCnt ?? ''),
151
- browse_count: String(item.browseCnt ?? ''),
152
- status: clean(item.itemStatusStr || ''),
153
- status_code: item.itemStatus ?? null,
154
- condition: clean(findLabel('成色')),
155
- brand: clean(findLabel('品牌')),
156
- category: clean(findLabel('分类')),
157
- location: clean(seller.publishCity || seller.city || ''),
158
- seller_name: clean(seller.nick || seller.uniqueName || ''),
159
- seller_id: String(seller.sellerId || ''),
160
- seller_score: clean(seller.xianyuSummary || ''),
161
- reply_ratio_24h: clean(seller.replyRatio24h || ''),
162
- reply_interval: clean(seller.replyInterval || ''),
163
- seller_url: seller.sellerId ? 'https://www.goofish.com/personal?userId=' + seller.sellerId : '',
164
- image_count: String(images.length),
165
- image_urls: images,
166
- };
167
- })()
168
- """
169
-
170
-
171
- async def _run_native(item_id: str) -> dict[str, Any]:
172
- url = _build_item_url(item_id)
173
- async with goofish_page() as page:
174
- await page.goto(url, wait_until="domcontentloaded")
175
- await page.wait_for_timeout(2000)
176
- result = await page.evaluate(_FETCH_JS, item_id)
177
-
178
- if not isinstance(result, dict):
179
- raise GoofishError("商品详情页返回结构非预期")
180
-
181
- err = result.get("error")
182
- if err == "blocked":
183
- raise GoofishError("商品详情页被验证码/安全验证拦截,触发风控")
184
- if err == "mtop-not-ready":
185
- raise GoofishError("页面 window.lib.mtop 未就绪(等待超时),页面加载异常")
186
-
187
- # auth 判定统一走 mtop 返回的 error_code/error_message 里的 SESSION_EXPIRED,
188
- # 不再依赖 body 文案正则("登录后" 在页脚也会出现,误报多)。
189
- err_code = str(result.get("error_code") or "")
190
- err_msg = str(result.get("error_message") or "")
191
- if re.search(r"FAIL_SYS_SESSION_EXPIRED|SESSION_EXPIRED", err_code + " " + err_msg):
192
- raise AuthRequiredError("mtop 返回 session 过期:" + (err_msg or err_code))
193
- if err:
194
- raise GoofishError(f"mtop 调用失败 [{err_code or err}]: {err_msg or '无详情'}")
195
- if not result.get("title"):
196
- raise GoofishError(f"未拿到商品 {item_id} 的标题,接口返回为空")
197
-
198
- return result
199
-
200
-
201
-
202
- async def _run(item_id: str) -> dict[str, Any]:
203
- if os.environ.get("GOOFISH_DESKTOP_SANDBOX") != "1":
204
- return await _run_native(item_id)
205
- async with goofish_page() as page:
206
- raw = await read_item_page(page, item_id)
207
- result = _view_result(raw, item_id)
208
- if not result.get("title"):
209
- raise GoofishError(f"未拿到商品 {item_id} 的标题,接口返回为空")
210
- return result
211
-
212
-
213
- @command(
214
- namespace="item",
215
- name="view",
216
- description="浏览器视角查看商品详情(读取页面响应,含图片和卖家字段)",
217
- strategy=Strategy.COOKIE,
218
- columns=[
219
- "item_id",
220
- "title",
221
- "price",
222
- "condition",
223
- "brand",
224
- "location",
225
- "seller_name",
226
- "want_count",
227
- "browse_count",
228
- ],
229
- )
230
- def view(item_id: str) -> dict[str, Any]:
231
- normalized = _normalize_item_id(item_id)
232
- # MCP / table 渲染依赖 dict;image_urls 是列表(JSON 里保留,table 里压成长度)
233
- result = asyncio.run(_run(normalized))
234
- result["_image_urls_json"] = json.dumps(result.get("image_urls", []), ensure_ascii=False)
235
- return result
236
-
237
-
238
- __test__ = {
239
- "_normalize_item_id": _normalize_item_id,
240
- "_build_item_url": _build_item_url,
241
- }
@@ -1,141 +0,0 @@
1
- """读取详情页自身发出的响应,校验请求和返回的商品身份。"""
2
-
3
- from __future__ import annotations
4
-
5
- import asyncio
6
- import json
7
- import re
8
- from typing import Any
9
- from urllib.parse import parse_qs, urlsplit
10
-
11
- from .errors import GoofishError, RiskControlError
12
- from .item_data import normalize_item
13
- from .mtop import _classify_error
14
-
15
- DETAIL_PATH = "/h5/mtop.taobao.idle.pc.detail/1.0/"
16
-
17
-
18
- def _matches_request(request, item_id: str) -> bool:
19
- url = urlsplit(request.url)
20
- if url.hostname not in {"h5api.m.goofish.com", "h5api.m.taobao.com"} or url.path != DETAIL_PATH:
21
- return False
22
- try:
23
- fields = parse_qs(request.post_data or "")
24
- if "data" not in fields:
25
- fields = parse_qs(url.query)
26
- return str(json.loads(fields["data"][0]).get("itemId")) == item_id
27
- except (ValueError, KeyError, TypeError, AttributeError):
28
- return False
29
-
30
-
31
- def _decode_response(text: str, item_id: str) -> dict:
32
- if not text.lstrip().startswith("{"):
33
- match = re.fullmatch(r"\s*[\w.$]+\s*\((.*)\)\s*;?\s*", text, re.S)
34
- if not match:
35
- raise GoofishError("详情响应不是可确认的 JSON/JSONP")
36
- text = match[1]
37
- try:
38
- raw = json.loads(text)
39
- except ValueError as exc:
40
- raise GoofishError("详情响应无法解析") from exc
41
- if not isinstance(raw, dict) or not isinstance(raw.get("ret"), list) or not raw["ret"]:
42
- raise GoofishError("详情响应缺少明确的业务状态")
43
- if not all(isinstance(value, str) for value in raw["ret"]):
44
- raise GoofishError("详情响应业务状态格式无效")
45
- try:
46
- _classify_error(raw, "mtop.taobao.idle.pc.detail")
47
- except RiskControlError as exc:
48
- raise RiskControlError(
49
- "闲鱼详情需要人工验证;请在沙箱浏览器完成验证后重试,不会自动绕过或重发请求",
50
- raw=raw,
51
- ) from exc
52
- if any(value.partition("::")[0] != "SUCCESS" for value in raw["ret"]):
53
- raise GoofishError("详情响应不是明确成功状态")
54
- normalize_item(raw, item_id)
55
- return raw
56
-
57
-
58
- class ItemResponse:
59
- """只消费本次观察到的匹配请求,忽略推荐、验证端点和迟到的旧请求。"""
60
-
61
- def __init__(self, page, item_id: str):
62
- self.page = page
63
- self.item_id = item_id
64
- self.raw: dict | None = None
65
- self.error: GoofishError | None = None
66
- self.ready = asyncio.Event()
67
- self.requests: set[Any] = set()
68
- self.tasks: set[asyncio.Task] = set()
69
- self.request_handler = self._request
70
- self.response_handler = self._schedule
71
- page.on("request", self.request_handler)
72
- page.on("response", self.response_handler)
73
-
74
- def _request(self, request) -> None:
75
- if _matches_request(request, self.item_id):
76
- self.requests.add(request)
77
-
78
- def _schedule(self, response) -> None:
79
- if response.request not in self.requests:
80
- return
81
- self.requests.discard(response.request)
82
- task = asyncio.create_task(self._capture(response))
83
- self.tasks.add(task)
84
- task.add_done_callback(self.tasks.discard)
85
-
86
- async def _capture(self, response) -> None:
87
- try:
88
- if response.status != 200:
89
- raise GoofishError(f"详情服务返回 HTTP {response.status}")
90
- self.raw = _decode_response(await response.text(), self.item_id)
91
- self.error = None
92
- except GoofishError as exc:
93
- self.raw = None
94
- self.error = exc
95
- except Exception:
96
- self.raw = None
97
- self.error = GoofishError("详情响应读取失败")
98
- self.ready.set()
99
-
100
- async def wait(self, timeout: float = 20, *, allow_verification: bool = False) -> dict:
101
- deadline = asyncio.get_running_loop().time() + timeout
102
- while True:
103
- try:
104
- await asyncio.wait_for(
105
- self.ready.wait(), max(0.01, deadline - asyncio.get_running_loop().time())
106
- )
107
- except TimeoutError as exc:
108
- raise GoofishError(
109
- "未收到目标商品的成功详情响应;沙箱页面保留,可检查当前页面"
110
- ) from exc
111
- self.ready.clear()
112
- if self.raw is not None:
113
- return self.raw
114
- if self.error is not None:
115
- if allow_verification and isinstance(self.error, RiskControlError):
116
- self.error = None
117
- continue
118
- raise self.error
119
-
120
- async def close(self) -> None:
121
- self.page.remove_listener("request", self.request_handler)
122
- self.page.remove_listener("response", self.response_handler)
123
- for task in self.tasks:
124
- task.cancel()
125
- await asyncio.gather(*self.tasks, return_exceptions=True)
126
-
127
-
128
- async def read_item_page(page, item_id: str) -> dict:
129
- observer = ItemResponse(page, item_id)
130
- try:
131
- await page.goto(f"https://www.goofish.com/item?id={item_id}", wait_until="domcontentloaded")
132
- return await observer.wait()
133
- finally:
134
- await observer.close()
135
-
136
-
137
- async def fetch_item_page(item_id: str) -> dict:
138
- from .browser import goofish_page
139
-
140
- async with goofish_page() as page:
141
- return await read_item_page(page, item_id)
File without changes
File without changes
File without changes