@hfyjq/crannia 1.0.0 → 1.1.0
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.
- package/LICENSE +201 -201
- package/NOTICE +45 -45
- package/THIRD-PARTY-FRONTEND.md +5266 -5266
- package/THIRD-PARTY-PYTHON.md +162 -153
- package/THIRD-PARTY.md +316 -316
- package/apps/desktop/quotes.txt +56 -56
- package/bus/core.py +671 -671
- package/bus/loaders/channel_loader.py +64 -64
- package/bus/loaders/skill_md.py +676 -676
- package/bus/skill_state.py +124 -124
- package/channels/cli_channel/manifest.yaml +5 -5
- package/channels/dingtalk_channel/manifest.yaml +12 -12
- package/channels/feishu_channel/manifest.yaml +12 -12
- package/channels/qq_bot_channel/__init__.py +1 -1
- package/channels/qq_bot_channel/handler.py +881 -881
- package/channels/qq_bot_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/__init__.py +1 -1
- package/channels/telegram_channel/handler.py +813 -813
- package/channels/telegram_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/media.py +231 -231
- package/channels/textfmt.py +58 -58
- package/channels/wechat_channel/__init__.py +1 -1
- package/channels/wechat_channel/auth.py +23 -5
- package/channels/wechat_channel/manifest.yaml +5 -5
- package/channels/wechat_channel/media.py +178 -178
- package/config.yaml +2 -2
- package/core/activity.py +3 -0
- package/core/agent_loop.py +390 -55
- package/core/approval.py +17 -6
- package/core/artifacts.py +7 -0
- package/core/auto_review.py +23 -5
- package/core/channel_configs.py +34 -2
- package/core/channel_turns.py +759 -759
- package/core/child_approval.py +150 -0
- package/core/config_requirements.py +205 -0
- package/core/cron/runner.py +118 -6
- package/core/cron/store.py +14 -5
- package/core/cron/tools.py +17 -5
- package/core/endpoint.py +141 -0
- package/core/events.py +23 -0
- package/core/i18n.py +329 -329
- package/core/ice/store.py +191 -191
- package/core/inbound.py +193 -193
- package/core/jobs.py +19 -3
- package/core/last_good.py +150 -150
- package/core/llm_errors.py +227 -227
- package/core/llm_retry.py +230 -230
- package/core/memory/compressor.py +1214 -1214
- package/core/memory/manager.py +14 -0
- package/core/model_configs.py +80 -0
- package/core/pipeline/scheduler.py +2 -2
- package/core/pipeline/stages/agent_loop.py +24 -4
- package/core/pipeline/stages/pre_process.py +58 -7
- package/core/prompt_assembler.py +680 -680
- package/core/rg.py +255 -255
- package/core/security.py +1544 -1544
- package/core/settings_baseline.py +70 -1
- package/core/shell.py +5 -17
- package/core/skill_settings.py +7 -2
- package/core/state_registry.py +19 -0
- package/core/subagent.py +64 -3
- package/core/task_tool.py +1 -1
- package/core/tasks_notify.py +69 -4
- package/core/tiers.py +9 -3
- package/core/tool_outcome.py +108 -0
- package/core/update_tui.py +158 -0
- package/core/version.py +2 -2
- package/core/web_cache.py +152 -0
- package/crannia_tray.py +278 -278
- package/creators/models.json +4 -4
- package/data/settings.example.json +67 -0
- package/licenses/GPL-3.0.txt +619 -619
- package/licenses/LGPL-2.1.txt +502 -502
- package/licenses/LGPL-3.0.txt +165 -165
- package/licenses/MIT-chat-on-wechat.txt +18 -18
- package/licenses/MIT-deepseek-harness.txt +21 -21
- package/licenses/Molio-LICENSE.txt +44 -44
- package/locales/en.json +9 -4
- package/main.py +154 -154
- package/mcpx/manager.py +522 -522
- package/mcpx/servers/__init__.py +22 -22
- package/mcpx/servers/web_search.py +321 -33
- package/package.json +14 -9
- package/providers/anthropic/client.py +772 -772
- package/providers/cost_table.json +3779 -3779
- package/providers/deepseek/client.py +20 -20
- package/providers/deepseek/manifest.yaml +2 -2
- package/providers/factory.py +136 -136
- package/providers/lmstudio/client.py +2 -2
- package/providers/metadata.py +80 -80
- package/providers/model_capabilities.json +6665 -6665
- package/providers/moonshot/client.py +12 -12
- package/providers/ollama/client.py +2 -2
- package/providers/openai/client.py +13 -13
- package/providers/openrouter/client.py +2 -2
- package/providers/qwen/__init__.py +1 -1
- package/providers/qwen/client.py +2 -2
- package/providers/qwen/manifest.yaml +16 -16
- package/providers/rate_limiter.py +144 -144
- package/providers/siliconflow/client.py +2 -2
- package/providers/validation.py +171 -171
- package/providers/window_table.json +8909 -8909
- package/sbom.json +4413 -4296
- package/skills/entertainment/SKILL.md +35 -35
- package/skills/entertainment/__init__.py +1 -1
- package/skills/entertainment/handler.py +91 -91
- package/skills/entertainment/manifest.yaml +26 -26
- package/skills/file_parser/GUIDANCE.md +10 -10
- package/skills/file_parser/handler.py +177 -4
- package/skills/file_parser/manifest.yaml +22 -1
- package/skills/github/SKILL.md +32 -32
- package/skills/github/__init__.py +1 -1
- package/skills/github/manifest.yaml +5 -0
- package/skills/mail_parser/SKILL.md +68 -68
- package/skills/mail_parser/__init__.py +1 -1
- package/skills/mail_parser/handler.py +806 -806
- package/skills/mail_parser/manifest.yaml +5 -0
- package/skills/media_gen/GUIDANCE.md +19 -19
- package/skills/media_gen/SKILL.md +43 -43
- package/skills/media_gen/__init__.py +1 -1
- package/skills/media_gen/handler.py +430 -430
- package/skills/media_gen/manifest.yaml +93 -88
- package/skills/office_parser/cell_validation.py +127 -127
- package/skills/office_parser/excel_transform.py +936 -936
- package/skills/office_parser/layout_spec.py +243 -243
- package/skills/office_parser/pptx_export/console_encoding.py +27 -27
- package/skills/office_parser/pptx_export/resource_paths.py +88 -88
- package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
- package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
- package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
- package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
- package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
- package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
- package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
- package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
- package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
- package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
- package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
- package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
- package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
- package/skills/office_parser/references/layout_library.md +816 -816
- package/skills/office_parser/references/ppt-master/LICENSE +21 -21
- package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
- package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
- package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
- package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
- package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
- package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
- package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
- package/skills/office_parser/references/spec_lock.md +235 -235
- package/skills/office_parser/soffice.py +68 -68
- package/skills/office_parser/word_tools.py +2909 -2909
- package/tui/crannia.cmd +134 -0
- package/tui/crannia_tui/__init__.py +1 -0
- package/tui/crannia_tui/__main__.py +223 -0
- package/tui/crannia_tui/app.py +1318 -0
- package/tui/crannia_tui/app.tcss +153 -0
- package/tui/crannia_tui/approval.py +85 -0
- package/tui/crannia_tui/backend.py +279 -0
- package/tui/crannia_tui/channel.py +472 -0
- package/tui/crannia_tui/client.py +125 -0
- package/tui/crannia_tui/clipboard.py +62 -0
- package/tui/crannia_tui/commands.py +65 -0
- package/tui/crannia_tui/doctor.py +304 -0
- package/tui/crannia_tui/events.py +84 -0
- package/tui/crannia_tui/headless.py +152 -0
- package/tui/crannia_tui/i18n.py +164 -0
- package/tui/crannia_tui/locales/en.json +263 -0
- package/tui/crannia_tui/outcome.py +62 -0
- package/tui/crannia_tui/paths.py +181 -0
- package/tui/crannia_tui/probe.py +53 -0
- package/tui/crannia_tui/profile.py +169 -0
- package/tui/crannia_tui/render.py +209 -0
- package/tui/crannia_tui/settings.py +134 -0
- package/tui/crannia_tui/setup.py +380 -0
- package/tui/crannia_tui/term.py +116 -0
- package/tui/crannia_tui/ui.py +1236 -0
- package/tui/crannia_tui/update.py +389 -0
- package/vendor/ripgrep/COPYING.txt +3 -3
- package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
- package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
- package/vendor/ripgrep/README.md +51 -51
- package/vendor/ripgrep/UNLICENSE.txt +24 -24
- package/vendor/ripgrep/package-source.json +19 -19
- package/web/__main__.py +15 -0
- package/web/server.py +168 -19
- package/web/static/img/channel-telegram.svg +1 -1
- package/web/static/img/channel-wechat.svg +1 -1
- package/web/templates/logs.html +49 -49
- package/web/templates/models.html +46 -46
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
"""`crannia channel`:通道账本的列表 / 增删改 / 默认,以及启停与扫码。
|
|
2
|
+
|
|
3
|
+
账本操作不 import `core`:两个安装各自更新,TUI 里没有那个包 ——
|
|
4
|
+
所以一律走一次子进程(与 `profile` 同一条路)。启停与扫码要求后端在跑,
|
|
5
|
+
它们是进程内的长活,命令行这边只递一句请求。
|
|
6
|
+
|
|
7
|
+
私聊与桌面是同一条会话(`workspace:private`),所以这里不建第二个对话视图;
|
|
8
|
+
通道跑起来的消息会进 TUI 正在用的那一段。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import getpass
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
import urllib.error
|
|
18
|
+
import urllib.request
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from .doctor import PREPARE, query
|
|
22
|
+
from .i18n import t
|
|
23
|
+
from .profile import endpoint
|
|
24
|
+
|
|
25
|
+
#: 平台名到通道 id。通道 id 是 `bus` 里的注册名,五个各有各的一段;
|
|
26
|
+
#: 映射只在这里写一次(界面那边的表各自独立,见 `packages/ui/src/channels-model.js`)。
|
|
27
|
+
CHANNEL_IDS: dict[str, str] = {
|
|
28
|
+
"wechat": "wechat_channel",
|
|
29
|
+
"feishu": "feishu_channel",
|
|
30
|
+
"dingtalk": "dingtalk_channel",
|
|
31
|
+
"telegram": "telegram_channel",
|
|
32
|
+
"qq_bot": "qq_bot_channel",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
#: 列表读的是账本 + 字段表 + 警告(警告文案由后端给,界面不另存一份)。
|
|
36
|
+
_LIST_CODE = PREPARE + (
|
|
37
|
+
"import json\n"
|
|
38
|
+
"from core import channel_configs as cc\n"
|
|
39
|
+
"out = {p: {'fields': list(s['fields']), 'secret': list(s['secret']),\n"
|
|
40
|
+
" 'default': cc.default_id(p), 'notice': cc.notice_for(p),\n"
|
|
41
|
+
" 'entries': cc.entries_for(p)}\n"
|
|
42
|
+
" for p, s in cc.PLATFORMS.items()}\n"
|
|
43
|
+
"print(json.dumps(out, ensure_ascii=False))\n"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
_CREATE_CODE = PREPARE + (
|
|
47
|
+
"import json\n"
|
|
48
|
+
"from core import channel_configs as cc\n"
|
|
49
|
+
"try:\n"
|
|
50
|
+
" out = cc.create(%r, %r, json.loads(%r))\n"
|
|
51
|
+
"except Exception as exc:\n"
|
|
52
|
+
" out = {'error': str(exc)}\n"
|
|
53
|
+
"print(json.dumps(out, ensure_ascii=False))\n"
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
_UPDATE_CODE = PREPARE + (
|
|
57
|
+
"import json\n"
|
|
58
|
+
"from core import channel_configs as cc\n"
|
|
59
|
+
"try:\n"
|
|
60
|
+
" out = cc.update(%r, name=(%r or None), fields=json.loads(%r))\n"
|
|
61
|
+
"except Exception as exc:\n"
|
|
62
|
+
" out = {'error': str(exc)}\n"
|
|
63
|
+
"print(json.dumps(out, ensure_ascii=False))\n"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
_DELETE_CODE = PREPARE + (
|
|
67
|
+
"import json\n"
|
|
68
|
+
"from core import channel_configs as cc\n"
|
|
69
|
+
"try:\n"
|
|
70
|
+
" out = {'ok': cc.delete(%r)}\n"
|
|
71
|
+
"except Exception as exc:\n"
|
|
72
|
+
" out = {'error': str(exc)}\n"
|
|
73
|
+
"print(json.dumps(out, ensure_ascii=False))\n"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
_DEFAULT_CODE = PREPARE + (
|
|
77
|
+
"import json\n"
|
|
78
|
+
"from core import channel_configs as cc\n"
|
|
79
|
+
"try:\n"
|
|
80
|
+
" e = cc.entry_of(%r)\n"
|
|
81
|
+
" out = {'ok': False, 'missing': True}\n"
|
|
82
|
+
" if e:\n"
|
|
83
|
+
" cc.set_default(e['platform'], %r)\n"
|
|
84
|
+
" out = {'ok': True, 'platform': e['platform']}\n"
|
|
85
|
+
"except Exception as exc:\n"
|
|
86
|
+
" out = {'ok': False, 'error': str(exc)}\n"
|
|
87
|
+
"print(json.dumps(out, ensure_ascii=False))\n"
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
91
|
+
|
|
92
|
+
_USAGE = """用法:
|
|
93
|
+
crannia channel list 列出各通道的配置条目与警告
|
|
94
|
+
crannia channel add <平台> [名字] 新建(凭据逐格输入)
|
|
95
|
+
crannia channel config <名字|id> 更改条目(回车以取消更改)
|
|
96
|
+
crannia channel remove <名字|id> 删除条目(若目标为默认条目,则应优先更换默认)
|
|
97
|
+
crannia channel default <名字|id> 设为该平台的默认条目
|
|
98
|
+
crannia channel start <平台> 启动一个通道
|
|
99
|
+
crannia channel stop <平台> 停止一个通道
|
|
100
|
+
crannia channel login wechat 微信扫码登录
|
|
101
|
+
|
|
102
|
+
平台:feishu / dingtalk / telegram / qq_bot(需要凭据)· wechat(扫码登录)
|
|
103
|
+
选项:--yes 直接确认已读接入警告(脚本用)"""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def read_ledger(python: Path, home: Path, *, query_fn=None) -> dict:
|
|
107
|
+
"""平台 -> 字段表 / 默认 id / 警告 / 条目。子进程读,不 import core。"""
|
|
108
|
+
run = query_fn or (lambda code: query(python, home, code))
|
|
109
|
+
return json.loads(run(_LIST_CODE))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _entries(data: dict):
|
|
113
|
+
for platform, spec in data.items():
|
|
114
|
+
for entry in spec.get("entries") or []:
|
|
115
|
+
yield platform, entry
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _resolve(data: dict, ref: str) -> tuple[tuple[str, dict] | None, str]:
|
|
119
|
+
"""按 id 或名字在全部平台里找一条。返回 `(平台, 条目)` 或 `(None, 一句话)`。"""
|
|
120
|
+
key = ref.strip().lower()
|
|
121
|
+
if not key:
|
|
122
|
+
return None, t("请提供名字或 id")
|
|
123
|
+
by_id = [(p, e) for p, e in _entries(data) if str(e.get("id") or "").lower() == key]
|
|
124
|
+
if by_id:
|
|
125
|
+
return by_id[0], ""
|
|
126
|
+
same = [(p, e) for p, e in _entries(data) if str(e.get("name") or "").lower() == key]
|
|
127
|
+
if len(same) == 1:
|
|
128
|
+
return same[0], ""
|
|
129
|
+
if len(same) > 1:
|
|
130
|
+
return None, t("「%s」撞名了,用 id 指定:%s") % (
|
|
131
|
+
ref, " · ".join("%s(%s)" % (e.get("name"), e.get("id"))
|
|
132
|
+
for _p, e in same))
|
|
133
|
+
return None, t("没有「%s」。尝试运行 `crannia channel list`") % ref
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _masked_hint(entry: dict) -> str:
|
|
137
|
+
fields = entry.get("fields") or {}
|
|
138
|
+
for value in fields.values():
|
|
139
|
+
if value:
|
|
140
|
+
return str(value)
|
|
141
|
+
return ""
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def render(data: dict, running: dict | None = None) -> list[str]:
|
|
145
|
+
"""人看的列表。每条一行;平台那行挂接入警告的短标记。"""
|
|
146
|
+
running = running or {}
|
|
147
|
+
lines: list[str] = []
|
|
148
|
+
for platform, spec in data.items():
|
|
149
|
+
cid = CHANNEL_IDS.get(platform)
|
|
150
|
+
state = t(" · 运行中") if cid and running.get(cid) else ""
|
|
151
|
+
marker = (t(" [群聊未完善]")
|
|
152
|
+
if (spec.get("notice") or {}).get("key") else "")
|
|
153
|
+
lines.append(t("%s(%s)%s%s")
|
|
154
|
+
% (platform, spec.get("default") or t("无默认"),
|
|
155
|
+
state, marker))
|
|
156
|
+
rows = spec.get("entries") or []
|
|
157
|
+
if not rows:
|
|
158
|
+
lines.append(" " + t("(未配置)"))
|
|
159
|
+
continue
|
|
160
|
+
for entry in rows:
|
|
161
|
+
mark = "*" if entry.get("is_default") else " "
|
|
162
|
+
hint = _masked_hint(entry)
|
|
163
|
+
lines.append(" %s %-16s %-12s (%s)"
|
|
164
|
+
% (mark, entry.get("name") or t("(未命名)"),
|
|
165
|
+
hint or t("(无凭据)"), entry.get("id") or ""))
|
|
166
|
+
return lines
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _notice_of(data: dict, platform: str) -> dict:
|
|
170
|
+
return (data.get(platform) or {}).get("notice") or {}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _confirm_notice(notice: dict, assume_yes: bool) -> bool:
|
|
174
|
+
"""配置通道前把接入警告摆出来并要一句确认。"""
|
|
175
|
+
if not notice:
|
|
176
|
+
return True
|
|
177
|
+
print(t("注意:") + str(notice.get("text") or ""))
|
|
178
|
+
if assume_yes:
|
|
179
|
+
return True
|
|
180
|
+
if not sys.stdin.isatty():
|
|
181
|
+
print(t("非交互环境:加 --yes 表示已读并继续。"))
|
|
182
|
+
return False
|
|
183
|
+
answer = _ask(t("是否继续?[y/N] "))
|
|
184
|
+
return str(answer or "").strip().lower() in ("y", "yes", "是")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _ask(prompt: str) -> str | None:
|
|
188
|
+
"""`input` 的一层薄壳:读到 EOF 给 `None` —— 管道里没有输入不是崩溃的事。"""
|
|
189
|
+
try:
|
|
190
|
+
return input(prompt)
|
|
191
|
+
except EOFError:
|
|
192
|
+
print()
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _ask_fields(spec: dict, *, keep: bool) -> dict | None:
|
|
197
|
+
"""逐格问凭据。密钥格不回显;回车 = 不填 / 不改。
|
|
198
|
+
|
|
199
|
+
读不到输入给 `None`(与"一格都没填"分开 —— 后者是一份空 dict,
|
|
200
|
+
调用方要说的话不一样)。
|
|
201
|
+
"""
|
|
202
|
+
out: dict = {}
|
|
203
|
+
for key in spec.get("fields") or []:
|
|
204
|
+
prompt = (t("%s(回车不改): ") if keep else "%s: ") % key
|
|
205
|
+
if key in (spec.get("secret") or []):
|
|
206
|
+
if not sys.stdin.isatty():
|
|
207
|
+
print(t("密钥应在终端里输入。"))
|
|
208
|
+
return None
|
|
209
|
+
try:
|
|
210
|
+
value = getpass.getpass(prompt)
|
|
211
|
+
except EOFError:
|
|
212
|
+
print()
|
|
213
|
+
return None
|
|
214
|
+
else:
|
|
215
|
+
value = _ask(prompt)
|
|
216
|
+
if value is None:
|
|
217
|
+
return None
|
|
218
|
+
value = value.strip()
|
|
219
|
+
if value:
|
|
220
|
+
out[key] = value
|
|
221
|
+
return out
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _post(ep: dict, path: str, payload: dict) -> tuple[bool, str, dict]:
|
|
225
|
+
"""向端点 POST 一份 JSON。返回 `(成功, 一句话, 响应体)`。"""
|
|
226
|
+
req = urllib.request.Request(
|
|
227
|
+
"http://127.0.0.1:%d%s" % (ep["port"], path),
|
|
228
|
+
data=json.dumps(payload).encode("utf-8"), method="POST",
|
|
229
|
+
headers={"X-Crannia-Token": ep["token"],
|
|
230
|
+
"Content-Type": "application/json"})
|
|
231
|
+
try:
|
|
232
|
+
with _OPENER.open(req, timeout=10) as resp:
|
|
233
|
+
body = json.loads(resp.read().decode("utf-8"))
|
|
234
|
+
except urllib.error.HTTPError as exc:
|
|
235
|
+
try:
|
|
236
|
+
body = json.loads(exc.read().decode("utf-8"))
|
|
237
|
+
except (ValueError, OSError):
|
|
238
|
+
body = {}
|
|
239
|
+
return False, str(body.get("error") or "HTTP %s" % exc.code), body
|
|
240
|
+
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
241
|
+
return False, t("后端无应答(%s)") % type(exc).__name__, {}
|
|
242
|
+
if not isinstance(body, dict):
|
|
243
|
+
return False, t("后端回复了未知内容"), {}
|
|
244
|
+
if body.get("error"):
|
|
245
|
+
return False, str(body["error"]), body
|
|
246
|
+
return True, str(body.get("message") or ""), body
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _get(ep: dict, path: str) -> dict:
|
|
250
|
+
req = urllib.request.Request(
|
|
251
|
+
"http://127.0.0.1:%d%s" % (ep["port"], path),
|
|
252
|
+
headers={"X-Crannia-Token": ep["token"]})
|
|
253
|
+
try:
|
|
254
|
+
with _OPENER.open(req, timeout=10) as resp:
|
|
255
|
+
body = json.loads(resp.read().decode("utf-8"))
|
|
256
|
+
except (urllib.error.URLError, OSError, ValueError):
|
|
257
|
+
return {}
|
|
258
|
+
return body if isinstance(body, dict) else {}
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _need_backend(ep) -> dict | None:
|
|
262
|
+
if isinstance(ep, dict):
|
|
263
|
+
return ep
|
|
264
|
+
print(t("后端未启动"))
|
|
265
|
+
return None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _login_wechat(ep: dict, *, timeout_s: float = 180.0) -> int:
|
|
269
|
+
ok, why, _body = _post(ep, "/api/wechat/start-login", {})
|
|
270
|
+
if not ok:
|
|
271
|
+
print(why or t("启动微信登录失败"))
|
|
272
|
+
return 1
|
|
273
|
+
printed = False
|
|
274
|
+
deadline = time.time() + timeout_s
|
|
275
|
+
while time.time() < deadline:
|
|
276
|
+
state = _get(ep, "/api/wechat/qrcode")
|
|
277
|
+
phase = str(state.get("phase") or "")
|
|
278
|
+
if phase == "qr_ready":
|
|
279
|
+
if not printed:
|
|
280
|
+
art = str(state.get("ascii") or "")
|
|
281
|
+
if art:
|
|
282
|
+
print(art, end="" if art.endswith("\n") else "\n")
|
|
283
|
+
print(t("请使用手机微信扫码继续…"))
|
|
284
|
+
printed = True
|
|
285
|
+
elif phase == "scanned":
|
|
286
|
+
print(t("已扫码,请在手机上确认…"))
|
|
287
|
+
printed = True
|
|
288
|
+
elif phase == "confirmed":
|
|
289
|
+
print(t("微信已登录。"))
|
|
290
|
+
return 0
|
|
291
|
+
elif phase == "expired":
|
|
292
|
+
print(t("二维码过期,请再次运行 `crannia channel login wechat`。"))
|
|
293
|
+
return 1
|
|
294
|
+
elif phase == "error":
|
|
295
|
+
print(t("登录失败:%s")
|
|
296
|
+
% (state.get("error_msg") or t("原因未知")))
|
|
297
|
+
return 1
|
|
298
|
+
time.sleep(1.0)
|
|
299
|
+
print(t("等超时了(%s 秒)—— 再执行一次。") % int(timeout_s))
|
|
300
|
+
return 1
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
#: `channel_command` 的默认端点参数:"没传"与"明说没有后端"是两件事 ——
|
|
304
|
+
#: 前者才去探一次,后者按"后端没在跑"处理(测试要能钉后一种)。
|
|
305
|
+
_UNSET = object()
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def channel_command(argv: list[str], *, python: Path, home: Path,
|
|
309
|
+
query_fn=None, ep=_UNSET) -> int:
|
|
310
|
+
"""`crannia channel ...` 的入口。返回退出码。"""
|
|
311
|
+
if not argv:
|
|
312
|
+
print(t(_USAGE))
|
|
313
|
+
return 0
|
|
314
|
+
args = list(argv)
|
|
315
|
+
assume_yes = "--yes" in args
|
|
316
|
+
args = [a for a in args if a != "--yes"]
|
|
317
|
+
action = args[0]
|
|
318
|
+
rest = args[1:]
|
|
319
|
+
|
|
320
|
+
if action in ("-h", "--help", "help"):
|
|
321
|
+
print(t(_USAGE))
|
|
322
|
+
return 0
|
|
323
|
+
|
|
324
|
+
if action == "list":
|
|
325
|
+
data = read_ledger(python, home, query_fn=query_fn)
|
|
326
|
+
running: dict = {}
|
|
327
|
+
ep = endpoint(python, home) if ep is _UNSET else ep
|
|
328
|
+
if isinstance(ep, dict):
|
|
329
|
+
running = (_get(ep, "/api/channel/status") or {}).get("running") or {}
|
|
330
|
+
for line in render(data, running):
|
|
331
|
+
print(line)
|
|
332
|
+
return 0
|
|
333
|
+
|
|
334
|
+
if action == "add":
|
|
335
|
+
if not rest:
|
|
336
|
+
print(t("需要平台名:") + " / ".join(sorted(
|
|
337
|
+
list(CHANNEL_IDS) + ["qq_bot"])))
|
|
338
|
+
return 2
|
|
339
|
+
platform = rest[0]
|
|
340
|
+
name = rest[1] if len(rest) > 1 else t("默认")
|
|
341
|
+
data = read_ledger(python, home, query_fn=query_fn)
|
|
342
|
+
spec = data.get(platform)
|
|
343
|
+
if spec is None:
|
|
344
|
+
print(t("未知平台:%s(有:%s)")
|
|
345
|
+
% (platform, " / ".join(sorted(data))))
|
|
346
|
+
return 2
|
|
347
|
+
if not _confirm_notice(spec.get("notice") or {}, assume_yes):
|
|
348
|
+
print(t("已取消。"))
|
|
349
|
+
return 1
|
|
350
|
+
fields = _ask_fields(spec, keep=False)
|
|
351
|
+
if not fields:
|
|
352
|
+
print(t("未更改"))
|
|
353
|
+
return 1
|
|
354
|
+
run = query_fn or (lambda code: query(python, home, code))
|
|
355
|
+
row = json.loads(run(_CREATE_CODE % (
|
|
356
|
+
platform, name, json.dumps(fields, ensure_ascii=False))))
|
|
357
|
+
if row.get("error"):
|
|
358
|
+
print(row["error"])
|
|
359
|
+
return 1
|
|
360
|
+
print(t("已新建:「%s」(%s)")
|
|
361
|
+
% (row.get("name") or name, row.get("id") or ""))
|
|
362
|
+
return 0
|
|
363
|
+
|
|
364
|
+
if action == "config":
|
|
365
|
+
if not rest:
|
|
366
|
+
print(t("请提供一个名字或 id"))
|
|
367
|
+
return 2
|
|
368
|
+
data = read_ledger(python, home, query_fn=query_fn)
|
|
369
|
+
hit, why = _resolve(data, rest[0])
|
|
370
|
+
if hit is None:
|
|
371
|
+
print(why)
|
|
372
|
+
return 1
|
|
373
|
+
platform, entry = hit
|
|
374
|
+
if not _confirm_notice(_notice_of(data, platform), assume_yes):
|
|
375
|
+
print(t("已取消。"))
|
|
376
|
+
return 1
|
|
377
|
+
fields = _ask_fields(data[platform], keep=True)
|
|
378
|
+
run = query_fn or (lambda code: query(python, home, code))
|
|
379
|
+
row = json.loads(run(_UPDATE_CODE % (
|
|
380
|
+
entry["id"], "", json.dumps(fields, ensure_ascii=False))))
|
|
381
|
+
if row.get("error"):
|
|
382
|
+
print(row["error"])
|
|
383
|
+
return 1
|
|
384
|
+
print(t("已更新:「%s」(%s)")
|
|
385
|
+
% (row.get("name") or entry.get("name"),
|
|
386
|
+
entry.get("id") or ""))
|
|
387
|
+
return 0
|
|
388
|
+
|
|
389
|
+
if action == "remove":
|
|
390
|
+
if not rest:
|
|
391
|
+
print(t("请提供一个名字或 id"))
|
|
392
|
+
return 2
|
|
393
|
+
data = read_ledger(python, home, query_fn=query_fn)
|
|
394
|
+
hit, why = _resolve(data, rest[0])
|
|
395
|
+
if hit is None:
|
|
396
|
+
print(why)
|
|
397
|
+
return 1
|
|
398
|
+
_platform, entry = hit
|
|
399
|
+
if not assume_yes:
|
|
400
|
+
if not sys.stdin.isatty():
|
|
401
|
+
print(t("非交互环境:加 --yes 确认删除。"))
|
|
402
|
+
return 1
|
|
403
|
+
prompt = t("删除「%s」?[y/N] ") % (
|
|
404
|
+
entry.get("name") or entry.get("id"))
|
|
405
|
+
if input(prompt).strip().lower() not in ("y", "yes", "是"):
|
|
406
|
+
print(t("已取消。"))
|
|
407
|
+
return 1
|
|
408
|
+
run = query_fn or (lambda code: query(python, home, code))
|
|
409
|
+
row = json.loads(run(_DELETE_CODE % (entry["id"],)))
|
|
410
|
+
if row.get("error"):
|
|
411
|
+
print(row["error"])
|
|
412
|
+
return 1
|
|
413
|
+
print(t("已删除:%s") % (entry.get("name") or entry.get("id")))
|
|
414
|
+
return 0
|
|
415
|
+
|
|
416
|
+
if action == "default":
|
|
417
|
+
if not rest:
|
|
418
|
+
print(t("请提供一个名字或 id"))
|
|
419
|
+
return 2
|
|
420
|
+
data = read_ledger(python, home, query_fn=query_fn)
|
|
421
|
+
hit, why = _resolve(data, rest[0])
|
|
422
|
+
if hit is None:
|
|
423
|
+
print(why)
|
|
424
|
+
return 1
|
|
425
|
+
_platform, entry = hit
|
|
426
|
+
run = query_fn or (lambda code: query(python, home, code))
|
|
427
|
+
row = json.loads(run(_DEFAULT_CODE % (entry["id"], entry["id"])))
|
|
428
|
+
if not row.get("ok"):
|
|
429
|
+
print(t("配置丢失") if row.get("missing")
|
|
430
|
+
else (row.get("error") or t("失败")))
|
|
431
|
+
return 1
|
|
432
|
+
print(t("已设为默认:「%s」。重启以更换运行中的通道。")
|
|
433
|
+
% (entry.get("name") or entry.get("id")))
|
|
434
|
+
return 0
|
|
435
|
+
|
|
436
|
+
if action in ("start", "stop"):
|
|
437
|
+
if not rest:
|
|
438
|
+
print(t("需要平台名:") + " / ".join(sorted(CHANNEL_IDS)))
|
|
439
|
+
return 2
|
|
440
|
+
channel_id = CHANNEL_IDS.get(rest[0])
|
|
441
|
+
if channel_id is None:
|
|
442
|
+
print(t("未知平台:%s(有:%s)")
|
|
443
|
+
% (rest[0], " / ".join(sorted(CHANNEL_IDS))))
|
|
444
|
+
return 2
|
|
445
|
+
if ep is _UNSET:
|
|
446
|
+
ep = endpoint(python, home)
|
|
447
|
+
ep = _need_backend(ep)
|
|
448
|
+
if ep is None:
|
|
449
|
+
return 2
|
|
450
|
+
path = "/api/channel/%s" % ("start" if action == "start" else "stop")
|
|
451
|
+
ok, why, body = _post(ep, path, {"channel_id": channel_id})
|
|
452
|
+
if not ok:
|
|
453
|
+
print(why or (t("启动失败") if action == "start"
|
|
454
|
+
else t("停止失败")))
|
|
455
|
+
return 1
|
|
456
|
+
print(str(body.get("message") or body.get("status")
|
|
457
|
+
or (t("已启动") if action == "start" else t("已停止"))))
|
|
458
|
+
return 0
|
|
459
|
+
|
|
460
|
+
if action == "login":
|
|
461
|
+
if not rest or rest[0] != "wechat":
|
|
462
|
+
print(t("目前只有 `crannia channel login wechat`。"))
|
|
463
|
+
return 2
|
|
464
|
+
if ep is _UNSET:
|
|
465
|
+
ep = endpoint(python, home)
|
|
466
|
+
ep = _need_backend(ep)
|
|
467
|
+
if ep is None:
|
|
468
|
+
return 2
|
|
469
|
+
return _login_wechat(ep)
|
|
470
|
+
|
|
471
|
+
print(t(_USAGE))
|
|
472
|
+
return 2
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""事件流客户端。
|
|
2
|
+
|
|
3
|
+
为什么用线程而不是 asyncio:crannia 的管线是同步的(`provider.chat()` 阻塞),
|
|
4
|
+
TUI 也保持同步模型。两套并发模型混在一起时,出问题的地方永远在交界处,
|
|
5
|
+
而这里唯一的并发需求就是"一边等输入、一边收事件"——一个线程足够。
|
|
6
|
+
|
|
7
|
+
断线要自己重连:浏览器的 `EventSource` 自带这条(断了 3 秒一次地试),
|
|
8
|
+
手写的 `urllib` 没有这份运气 —— 不重连的话,界面就是"卡死"本身:
|
|
9
|
+
横幅继续转、卡片停在 `running`,而实际上一条事件都收不到了。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import threading
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import urllib.request
|
|
17
|
+
from typing import Callable
|
|
18
|
+
|
|
19
|
+
from . import events as E
|
|
20
|
+
from .i18n import t
|
|
21
|
+
|
|
22
|
+
#: 重连的退避:1s、2s、4s…封顶 10s。连接恢复后从头计。
|
|
23
|
+
_BACKOFF_CAP = 10.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class EventStream:
|
|
27
|
+
"""订阅 `/api/events`,把每条事件交给回调;断了自动重连。
|
|
28
|
+
|
|
29
|
+
回调在读取线程里执行 —— 调用方自己保证线程安全(往终端写要加锁,
|
|
30
|
+
因为输入行随时可能在被重绘)。
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, base: str, token: str,
|
|
34
|
+
on_event: Callable[[E.Event], None],
|
|
35
|
+
on_state: Callable[[str], None] | None = None,
|
|
36
|
+
session: str = "") -> None:
|
|
37
|
+
self.base = base
|
|
38
|
+
self.token = token
|
|
39
|
+
#: 只订阅这一条会话的事件。空 = 全部会话 —— 那会把 IM 群聊与
|
|
40
|
+
#: 别的地方的一轮也画进这个界面。
|
|
41
|
+
self.session = str(session or "")
|
|
42
|
+
self.on_event = on_event
|
|
43
|
+
#: 连接状态变化:"connected" / "disconnected" / 一句人话的失败原因。
|
|
44
|
+
#: TUI 用它更新状态栏,也用它决定"还要不要相信屏幕上那个绿灯"。
|
|
45
|
+
self.on_state = on_state or (lambda _s: None)
|
|
46
|
+
self._stop = threading.Event()
|
|
47
|
+
self._resp = None
|
|
48
|
+
self._thread: threading.Thread | None = None
|
|
49
|
+
#: 收到的最后一条事件的 seq。重连时作为 `last_id` 传回去,
|
|
50
|
+
#: 服务端会把错过的事件里可重放的那部分补发(与浏览器的
|
|
51
|
+
#: `Last-Event-ID` 同一行为)。
|
|
52
|
+
self._last_seq = 0
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def last_seq(self) -> int:
|
|
56
|
+
return self._last_seq
|
|
57
|
+
|
|
58
|
+
def start(self) -> None:
|
|
59
|
+
self._thread = threading.Thread(target=self._run, daemon=True,
|
|
60
|
+
name="crannia-sse")
|
|
61
|
+
self._thread.start()
|
|
62
|
+
|
|
63
|
+
def stop(self) -> None:
|
|
64
|
+
"""停止订阅。
|
|
65
|
+
|
|
66
|
+
先关响应对象再等线程:读取循环阻塞在 socket 上,只设标志位的话
|
|
67
|
+
它要等到下一个心跳才会返回 —— 退出时卡十几秒,用户会以为挂了。
|
|
68
|
+
"""
|
|
69
|
+
self._stop.set()
|
|
70
|
+
resp, self._resp = self._resp, None
|
|
71
|
+
if resp is not None:
|
|
72
|
+
try:
|
|
73
|
+
resp.close()
|
|
74
|
+
except Exception:
|
|
75
|
+
pass
|
|
76
|
+
if self._thread is not None:
|
|
77
|
+
self._thread.join(timeout=2.0)
|
|
78
|
+
self._thread = None
|
|
79
|
+
|
|
80
|
+
def _run(self) -> None:
|
|
81
|
+
attempt = 0
|
|
82
|
+
while not self._stop.is_set():
|
|
83
|
+
url = f"{self.base}/api/events?token={self.token}"
|
|
84
|
+
if self.session:
|
|
85
|
+
url += "&session=" + urllib.parse.quote(self.session)
|
|
86
|
+
if self._last_seq:
|
|
87
|
+
url += f"&last_id={self._last_seq}"
|
|
88
|
+
reason = "disconnected"
|
|
89
|
+
try:
|
|
90
|
+
req = urllib.request.Request(
|
|
91
|
+
url, headers={"Accept": "text/event-stream"})
|
|
92
|
+
# 不设短超时:SSE 是长连接,短超时会把正常的静默当成断线。
|
|
93
|
+
resp = urllib.request.urlopen(req, timeout=None)
|
|
94
|
+
self._resp = resp
|
|
95
|
+
if getattr(resp, "status", 200) != 200:
|
|
96
|
+
reason = t("事件流被拒绝(HTTP %s)") % resp.status
|
|
97
|
+
else:
|
|
98
|
+
self.on_state("connected")
|
|
99
|
+
attempt = 0
|
|
100
|
+
for raw in resp:
|
|
101
|
+
if self._stop.is_set():
|
|
102
|
+
return
|
|
103
|
+
line = raw.decode("utf-8", "ignore").rstrip("\r\n")
|
|
104
|
+
if not line or line.startswith(":"):
|
|
105
|
+
# 心跳或 connected 注释帧。它们的存在本身是信息:
|
|
106
|
+
# 读到这里说明连接还活着。
|
|
107
|
+
continue
|
|
108
|
+
if not line.startswith("data:"):
|
|
109
|
+
continue
|
|
110
|
+
ev = E.parse(line[5:].strip())
|
|
111
|
+
if ev is None:
|
|
112
|
+
continue
|
|
113
|
+
if ev.seq:
|
|
114
|
+
self._last_seq = ev.seq
|
|
115
|
+
self.on_event(ev)
|
|
116
|
+
except Exception as exc:
|
|
117
|
+
if self._stop.is_set():
|
|
118
|
+
return
|
|
119
|
+
reason = t("事件流已断开:%s") % type(exc).__name__
|
|
120
|
+
if self._stop.is_set():
|
|
121
|
+
return
|
|
122
|
+
attempt += 1
|
|
123
|
+
self.on_state(reason)
|
|
124
|
+
# 退避放在"报过状态"之后:用户先看到"断了",再等下一次尝试。
|
|
125
|
+
self._stop.wait(min(2.0 ** (attempt - 1), _BACKOFF_CAP))
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""剪贴板里的图:取一张,转成 data URL。
|
|
2
|
+
|
|
3
|
+
为什么要有子进程:终端应用拿不到剪贴板的位图 —— 剪贴板是操作系统那一层的,
|
|
4
|
+
不是终端的。`Get-Clipboard -Format Image` 是系统自带、不用装依赖的那条路;
|
|
5
|
+
一次冷启动约 0.4 秒,所以只在按键时才调,不轮询。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from .i18n import t
|
|
14
|
+
|
|
15
|
+
#: 取图并转 base64 的脚本。一次调用做完全部转换 —— 不落临时文件:落盘要么
|
|
16
|
+
#: 留在用户目录里,要么还得负责删,两个都是尾巴。
|
|
17
|
+
_SCRIPT = (
|
|
18
|
+
"$i = Get-Clipboard -Format Image; "
|
|
19
|
+
"if ($null -eq $i) { exit 3 }; "
|
|
20
|
+
"$ms = New-Object IO.MemoryStream; "
|
|
21
|
+
"$i.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); "
|
|
22
|
+
"[Convert]::ToBase64String($ms.ToArray())"
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
#: 脚本用这个退出码说"剪贴板里没有图"。它不是错误。
|
|
26
|
+
_NO_IMAGE = 3
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ClipboardError(RuntimeError):
|
|
30
|
+
"""读剪贴板失败:没有 powershell、超时、或者脚本自己报错。"""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def read_image() -> str | None:
|
|
34
|
+
"""剪贴板里的图 → `data:image/png;base64,…`;没有图返回 None。
|
|
35
|
+
|
|
36
|
+
`-Sta` 不能省:.NET 的 `Clipboard` 要求 STA 线程,MTA 下直接抛异常。
|
|
37
|
+
"""
|
|
38
|
+
if sys.platform != "win32":
|
|
39
|
+
raise ClipboardError(t("剪贴板图片读取仅在windows下支持"))
|
|
40
|
+
|
|
41
|
+
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
42
|
+
try:
|
|
43
|
+
proc = subprocess.run(
|
|
44
|
+
["powershell", "-NoProfile", "-NonInteractive", "-Sta",
|
|
45
|
+
"-Command", _SCRIPT],
|
|
46
|
+
capture_output=True, timeout=20, check=False, creationflags=flags,
|
|
47
|
+
)
|
|
48
|
+
except FileNotFoundError as exc:
|
|
49
|
+
raise ClipboardError(t("未找到 powershell")) from exc
|
|
50
|
+
except subprocess.TimeoutExpired as exc:
|
|
51
|
+
raise ClipboardError(t("剪贴板读取超时(20 秒)")) from exc
|
|
52
|
+
|
|
53
|
+
if proc.returncode == _NO_IMAGE:
|
|
54
|
+
return None
|
|
55
|
+
if proc.returncode != 0:
|
|
56
|
+
stderr = proc.stderr.decode("utf-8", "ignore").strip()
|
|
57
|
+
raise ClipboardError(stderr.splitlines()[-1] if stderr
|
|
58
|
+
else t("powershell 退出码 %s")
|
|
59
|
+
% proc.returncode)
|
|
60
|
+
|
|
61
|
+
b64 = proc.stdout.decode("ascii", "ignore").strip()
|
|
62
|
+
return f"data:image/png;base64,{b64}" if b64 else None
|