smartcheck-cli 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,3 @@
1
+ from importlib.metadata import version
2
+
3
+ __version__ = version("smartcheck-cli")
smartcheck_cli/auth.py ADDED
@@ -0,0 +1,263 @@
1
+ import base64
2
+ from contextlib import contextmanager
3
+ from datetime import UTC, datetime, timedelta
4
+ import hashlib
5
+ from http.server import BaseHTTPRequestHandler, HTTPServer
6
+ import json
7
+ from pathlib import Path
8
+ import re
9
+ import secrets
10
+ import socket
11
+ import sys
12
+ import time
13
+ from urllib.parse import parse_qs
14
+ import webbrowser
15
+
16
+ from filelock import FileLock, Timeout
17
+
18
+ from . import __version__
19
+ from .http import Error, LOCAL, note
20
+
21
+ UNCERTAIN = "凭据续期结果无法确认,请重新登录"
22
+ KEYRING_FAILURE = "无法安全保存凭据,请检查系统凭据库"
23
+
24
+
25
+ class Vault:
26
+ def __init__(self, host):
27
+ self.host = host
28
+ self.service = "SmartCheck CLI " + host
29
+ try:
30
+ if sys.platform == "darwin":
31
+ from keyring.backends.macOS import Keyring
32
+ elif sys.platform == "win32":
33
+ from keyring.backends.Windows import WinVaultKeyring as Keyring
34
+ else:
35
+ from keyring.backends.SecretService import Keyring
36
+ self.backend = Keyring()
37
+ except Exception:
38
+ raise Error(KEYRING_FAILURE, 3) from None
39
+
40
+ @contextmanager
41
+ def lock(self):
42
+ directory = Path.home() / ".smartcheck"
43
+ name = "local" if self.host == LOCAL else "production"
44
+ try:
45
+ directory.mkdir(mode=0o700, exist_ok=True)
46
+ lock = FileLock(directory / (name + ".lock"), timeout=310)
47
+ lock.acquire()
48
+ except (Timeout, OSError):
49
+ raise Error("无法锁定本机凭据,请稍后重试", 3) from None
50
+ try:
51
+ yield
52
+ finally:
53
+ lock.release()
54
+
55
+ def load(self):
56
+ try:
57
+ raw = self.backend.get_password(self.service, self.host)
58
+ return json.loads(raw) if raw else {}
59
+ except Exception:
60
+ raise Error(KEYRING_FAILURE, 3) from None
61
+
62
+ def save(self, data):
63
+ try:
64
+ if data:
65
+ self.backend.set_password(self.service, self.host, json.dumps(data, ensure_ascii=False, separators=(",", ":")))
66
+ elif self.backend.get_password(self.service, self.host) is not None:
67
+ self.backend.delete_password(self.service, self.host)
68
+ except Exception:
69
+ raise Error(KEYRING_FAILURE, 3) from None
70
+
71
+
72
+ class Listener(HTTPServer):
73
+ def get_request(self):
74
+ connection, address = super().get_request()
75
+ connection.settimeout(2)
76
+ return connection, address
77
+
78
+ def handle_error(self, request, client_address):
79
+ pass # Never log callback payloads.
80
+
81
+
82
+ def receive(client, device, no_browser):
83
+ state = secrets.token_urlsafe(32)
84
+ verifier = secrets.token_urlsafe(32)
85
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")
86
+ result = []
87
+
88
+ class Callback(BaseHTTPRequestHandler):
89
+ def log_message(self, *args):
90
+ pass
91
+
92
+ def do_POST(self):
93
+ try:
94
+ size = int(self.headers.get("Content-Length", "0"))
95
+ except ValueError:
96
+ size = 0
97
+ if (self.path != "/callback" or self.headers.get("Origin") != client.host
98
+ or self.headers.get("Host") != f"127.0.0.1:{self.server.server_port}"
99
+ or not 0 < size <= 512):
100
+ self.send_error(400)
101
+ return
102
+ fields = parse_qs(self.rfile.read(size).decode("ascii", errors="replace"), keep_blank_values=True)
103
+ code = fields.get("code", [])
104
+ if (fields.get("state") != [state] or len(code) != 1
105
+ or (code[0] and not re.fullmatch(r"[a-zA-Z0-9_-]{43}", code[0]))):
106
+ self.send_error(400)
107
+ return
108
+ result.append(code[0])
109
+ self.send_response(303)
110
+ self.send_header("Location", link + "#complete")
111
+ self.send_header("Cache-Control", "no-store")
112
+ self.send_header("Content-Length", "0")
113
+ self.end_headers()
114
+
115
+ try:
116
+ server = Listener(("127.0.0.1", 0), Callback)
117
+ except OSError:
118
+ raise Error("无法在本机接收授权结果,当前环境不支持浏览器授权", 3) from None
119
+ with server:
120
+ server.timeout = 1
121
+ until = time.monotonic() + 600
122
+ started = client.request("POST", "/cli/requests", body=dict(
123
+ state=state, challenge=challenge, port=server.server_port, device_name=device, cli_version=__version__))
124
+ request = started["request"]
125
+ if not re.fullmatch(r"[A-Za-z0-9_-]{43}", request):
126
+ raise Error("授权请求响应无效", 5)
127
+ link = client.host + "/cli/authorize?request=" + request
128
+ note(link)
129
+ if not no_browser:
130
+ try:
131
+ opened = webbrowser.open(link)
132
+ except (OSError, webbrowser.Error):
133
+ opened = False
134
+ if not opened:
135
+ note("无法自动打开浏览器,请在本机浏览器打开以上链接")
136
+ previous = None
137
+ while not result and time.monotonic() < until:
138
+ left = max(0, round(until - time.monotonic()))
139
+ if previous is None or previous - left >= 30:
140
+ note(f"请在浏览器中登录并授权,正在等待…(剩余 {left//60:02d}:{left%60:02d},Ctrl+C 取消)")
141
+ previous = left
142
+ server.handle_request()
143
+ if not result or not result[0]:
144
+ raise Error("授权未完成,原登录保持不变", 3)
145
+ return client.request("POST", "/cli/exchange", body=dict(request=request, code=result[0], verifier=verifier))
146
+
147
+
148
+ def settle_login(client, vault, data):
149
+ """Recover a saved candidate after interruption. Activation is idempotent."""
150
+ new = data["candidate"]
151
+ old = data.get("current", {})
152
+ try:
153
+ info = client.request("POST", "/cli/activate", body={
154
+ "refresh_token": new["refresh_token"], "previous_refresh_token": old.get("refresh_token"),
155
+ })
156
+ except Error as error:
157
+ if error.status == 401:
158
+ data.pop("candidate")
159
+ vault.save(data)
160
+ raise
161
+ new = {**new, "profile": info}
162
+ try:
163
+ vault.save({"current": new})
164
+ except Error:
165
+ # The candidate was durably saved before activation. A later command can finalize it.
166
+ pass
167
+ return new
168
+
169
+
170
+ def login(client, vault, args):
171
+ device = args.device_name if args.device_name is not None else socket.gethostname()[:100]
172
+ if not 1 <= len(device) <= 100:
173
+ raise Error("设备名须为 1–100 个字符")
174
+ with vault.lock():
175
+ vault.load() # Check availability before launching the browser.
176
+ try:
177
+ new = receive(client, device, args.no_browser)
178
+ except KeyboardInterrupt:
179
+ raise Error("授权未完成,原登录保持不变", 3) from None
180
+ with vault.lock():
181
+ data = vault.load()
182
+ if "candidate" in data:
183
+ try:
184
+ settle_login(client, vault, data)
185
+ except Error as error:
186
+ if error.status != 401:
187
+ raise
188
+ data = vault.load()
189
+ old = data.get("current", {}).get("profile")
190
+ data["candidate"] = {k: v for k, v in new.items() if k != "profile"}
191
+ vault.save(data)
192
+ new = settle_login(client, vault, data)
193
+ info = new["profile"]
194
+ if old and (old["tenant_id"], old["username"]) != (info["tenant_id"], info["username"]):
195
+ note(f"已从 {old['enterprise_name']}/{old['username']} 切换为 {info['enterprise_name']}/{info['username']}")
196
+ role = "管理员" if info["role"] == "admin" else "成员"
197
+ note(f"已登录 {info['enterprise_name']}({info['tenant_id']})/ {info['name']}({info['username']}),身份:{role}")
198
+ return {"host": client.host, **info}
199
+
200
+
201
+ def current(client, vault):
202
+ with vault.lock():
203
+ data = vault.load()
204
+ if "candidate" in data:
205
+ data = {"current": settle_login(client, vault, data)}
206
+ pair = data.get("current")
207
+ if not pair:
208
+ raise Error(f"尚未登录 {client.host},请运行 smartcheck auth login", 3)
209
+ if data.get("refresh_pending"):
210
+ raise Error(UNCERTAIN, 3)
211
+ now = datetime.now(UTC)
212
+ if datetime.fromisoformat(pair["profile"]["expires_at"]) <= now:
213
+ raise Error("登录已失效,请重新运行 smartcheck auth login", 3)
214
+ if datetime.fromisoformat(pair["access_until"]) > now + timedelta(seconds=20):
215
+ return pair
216
+ # Before sending anything, persist uncertainty even across SIGKILL.
217
+ vault.save({**data, "refresh_pending": True})
218
+ try:
219
+ new = client.request("POST", "/cli/refresh", body={"refresh_token": pair["refresh_token"]})
220
+ vault.save({"current": new})
221
+ return new
222
+ except Error as error:
223
+ if error.status == 401:
224
+ vault.save({})
225
+ raise
226
+ raise Error(UNCERTAIN, 3) from None
227
+
228
+
229
+ def status(client, vault):
230
+ try:
231
+ pair = current(client, vault)
232
+ profile = client.request("GET", "/cli/status", token=pair["access_token"])
233
+ return {"host": client.host, **profile}
234
+ except Error as error:
235
+ if error.exit_code != 4:
236
+ raise
237
+ with vault.lock():
238
+ saved = vault.load().get("current")
239
+ if saved:
240
+ note("无法在线校验,以下为本机保存的登录信息(未确认有效)")
241
+ print(json.dumps({"host": client.host, **saved["profile"], "verified": False}, ensure_ascii=False))
242
+ raise
243
+
244
+
245
+ def logout(client, vault):
246
+ with vault.lock():
247
+ data = vault.load()
248
+ if not data:
249
+ raise Error(f"尚未登录 {client.host},请运行 smartcheck auth login", 3)
250
+ unknown = False
251
+ try:
252
+ for key in ("current", "candidate"):
253
+ if pair := data.get(key):
254
+ try:
255
+ client.request("POST", "/cli/revoke", body={"refresh_token": pair["refresh_token"]})
256
+ except Error:
257
+ unknown = True
258
+ finally:
259
+ vault.save({})
260
+ if unknown:
261
+ raise Error("本机已退出,服务端撤销未确认,该授权将在 2 天有效期结束时自动失效", 4)
262
+ note("已退出,授权已撤销")
263
+ return {"host": client.host, "revoked": True}
@@ -0,0 +1,129 @@
1
+ from datetime import date
2
+ import getpass
3
+ import json
4
+ from pathlib import Path
5
+ import secrets
6
+ import string
7
+ import sys
8
+
9
+ from .auth import current
10
+ from .http import Error, note, segment
11
+
12
+
13
+ def read_object(path):
14
+ try:
15
+ body = json.loads(Path(path).read_text(encoding="utf-8"))
16
+ except (OSError, ValueError) as exc:
17
+ raise Error("无法读取 UTF-8 JSON 文件,请检查路径和格式") from exc
18
+ if not isinstance(body, dict):
19
+ raise Error("请求体必须为 JSON 对象")
20
+ return body
21
+
22
+
23
+ def password(args, creating):
24
+ if args.generate_password:
25
+ alphabet = string.ascii_letters + string.digits
26
+ while True:
27
+ value = "".join(secrets.choice(alphabet) for _ in range(16))
28
+ if any(c.isupper() for c in value) and any(c.islower() for c in value) and any(c.isdigit() for c in value):
29
+ return value
30
+ if args.password_stdin:
31
+ value = sys.stdin.readline().rstrip("\r\n")
32
+ if not value:
33
+ raise Error("标准输入中缺少密码")
34
+ return value
35
+ if creating:
36
+ if not sys.stdin.isatty():
37
+ raise Error("请指定 --password-stdin 或 --generate-password")
38
+ value = getpass.getpass("新密码:", stream=sys.stderr)
39
+ if value != getpass.getpass("再次输入:", stream=sys.stderr):
40
+ raise Error("两次输入的密码不一致")
41
+ return value
42
+ return None
43
+
44
+
45
+ def confirm(client, pair, args, body):
46
+ if getattr(args, "yes", False):
47
+ return
48
+ target = getattr(args, "identifier", None)
49
+ if args.group == "accounts":
50
+ info = client.request("GET", "/accounts/" + segment(target), token=pair["access_token"])
51
+ message = f"{info['name']}({target}) 删除后,该成员将无法登录,当前会话也将失效。确定删除?"
52
+ elif args.group == "call-fields":
53
+ info = client.request("GET", "/call-fields/" + segment(target), token=pair["access_token"])
54
+ message = (f"删除后不可恢复,字段键也不能再次使用。如果只是暂时不需要,建议停用。"
55
+ f"确定删除以下字段? {info['label']}({target},{info['field_type']})")
56
+ else:
57
+ message = f"保存话者识别方式 {body.get('mode', '')},仅对之后首次开始转写的录音生效。"
58
+ note(f"{client.host} · {pair['profile']['enterprise_name']}({pair['profile']['tenant_id']})\n{message} 输入 y 继续,默认取消。")
59
+ if sys.stdin.readline().strip() != "y":
60
+ raise Error("已取消", 1)
61
+
62
+
63
+ def run_business(client, vault, args):
64
+ group, action = args.group, args.action
65
+ guarded = action == "delete" or (group, action) == ("speaker-roles", "set")
66
+ path = "/" + group
67
+ if hasattr(args, "identifier"):
68
+ path += "/" + segment(args.identifier)
69
+ methods = {"list": "GET", "get": "GET", "download-recording": "GET", "create": "POST",
70
+ "update": "PUT", "set": "PUT", "enable": "PATCH", "disable": "PATCH",
71
+ "reorder": "PUT", "delete": "DELETE"}
72
+ method = methods[action]
73
+ body, params, output, generated = None, None, None, None
74
+ if hasattr(args, "json_file"):
75
+ body = read_object(args.json_file)
76
+ elif action == "list" and group in ("calls", "accounts"):
77
+ if args.page < 1 or args.per_page < 1 or args.per_page > 50:
78
+ raise Error("页码须大于 0,每页为 1–50 条")
79
+ params = dict(page=args.page, per_page=args.per_page)
80
+ if args.keyword is not None:
81
+ params["search" if group == "accounts" else "keyword"] = args.keyword
82
+ if group == "calls":
83
+ if args.keyword and len(args.keyword) > 128:
84
+ raise Error("搜索词最多 128 字符")
85
+ for key in ("start_date", "end_date"):
86
+ if value := getattr(args, key):
87
+ try:
88
+ if date.fromisoformat(value).isoformat() != value:
89
+ raise ValueError
90
+ except ValueError:
91
+ raise Error("日期须为 YYYY-MM-DD") from None
92
+ params[key] = value
93
+ if args.direction:
94
+ params["direction"] = args.direction
95
+ elif action == "download-recording":
96
+ path += "/recording/" + segment(args.source) + "/audio"
97
+ output = args.output
98
+ if Path(output).exists() and not args.force:
99
+ raise Error("文件已存在,添加 --force 覆盖")
100
+ elif action in ("enable", "disable"):
101
+ body = {"enabled": action == "enable"}
102
+ elif action == "reorder":
103
+ body = {"field_keys": args.field_keys}
104
+ pair = current(client, vault)
105
+ if group != "calls" and pair["profile"]["role"] != "admin":
106
+ raise Error("无权访问系统设置", 3, code="FORBIDDEN", status=403)
107
+ if group == "accounts" and action in ("create", "update"):
108
+ body = {key: getattr(args, key) for key in ("name", "email", "phone") if getattr(args, key) is not None}
109
+ if action == "create":
110
+ body["username"] = args.username
111
+ else:
112
+ method = "PATCH"
113
+ if args.clear_phone:
114
+ body["phone"] = None
115
+ value = password(args, action == "create")
116
+ if value is not None:
117
+ body["password"] = value
118
+ if args.generate_password:
119
+ generated = value
120
+ if not body:
121
+ raise Error("请至少提供一项变更")
122
+ if guarded:
123
+ confirm(client, pair, args, body)
124
+ result = client.request(method, path, token=pair["access_token"], params=params, body=body,
125
+ output=output, force=getattr(args, "force", False))
126
+ if generated:
127
+ result["generated_password"] = generated
128
+ note("请立即保存该密码")
129
+ return result
smartcheck_cli/http.py ADDED
@@ -0,0 +1,104 @@
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+ import sys
5
+ import tempfile
6
+ from urllib.parse import quote
7
+
8
+ import requests
9
+
10
+ PRODUCTION = "https://smartcheck.deepflowagent.com"
11
+ LOCAL = "http://localhost:3003"
12
+ HOSTS = {PRODUCTION: PRODUCTION + "/api/v1", LOCAL: "http://localhost:5003/api/v1"}
13
+
14
+
15
+ class Error(Exception):
16
+ def __init__(self, message, exit_code=2, *, code="CLI_ERROR", status=None, trace=None):
17
+ super().__init__(message)
18
+ self.exit_code = exit_code
19
+ self.code = code
20
+ self.status = status
21
+ self.trace = trace
22
+
23
+ def __str__(self):
24
+ return f"错误:{self.args[0]}(code={self.code},status={self.status or '-'},trace_id={self.trace or '-'})"
25
+
26
+
27
+ def note(message):
28
+ print(message, file=sys.stderr, flush=True)
29
+
30
+
31
+ def segment(value):
32
+ if not value or value in {".", ".."} or any(c in value for c in "/\\"):
33
+ raise Error("路径标识无效")
34
+ return quote(value, safe="")
35
+
36
+
37
+ class Client:
38
+ def __init__(self, host, timeout):
39
+ if host not in HOSTS:
40
+ raise Error(f"不受信任的地址:{host}")
41
+ if not 0 < timeout <= 300:
42
+ raise Error("超时时间须大于 0 且不超过 300 秒")
43
+ self.host = host
44
+ self.base = HOSTS[host]
45
+ self.timeout = timeout
46
+ self.session = requests.Session()
47
+ self.session.trust_env = False
48
+
49
+ def request(self, method, path, *, token=None, params=None, body=None, output=None, force=False):
50
+ reading = method == "GET"
51
+ attempts = 3 if reading else 1
52
+ for attempt in range(attempts):
53
+ try:
54
+ with self.session.request(method, self.base + path, params=params, json=body,
55
+ headers={"Authorization": "Bearer " + token} if token else {},
56
+ timeout=self.timeout, allow_redirects=False,
57
+ stream=output is not None) as response:
58
+ status = response.status_code
59
+ if status in (502, 503, 504) and attempt + 1 < attempts:
60
+ continue
61
+ if not 200 <= status < 300:
62
+ try:
63
+ error = response.json()
64
+ except ValueError:
65
+ error = {}
66
+ if not isinstance(error, dict):
67
+ error = {}
68
+ exit_code = 3 if status in (401, 403) else 5 if status >= 500 else 2
69
+ raise Error(error.get("message") or "服务端请求失败", exit_code,
70
+ code=error.get("code", "HTTP_ERROR"), status=status,
71
+ trace=response.headers.get("X-Trace-Id"))
72
+ if output is not None:
73
+ return save_recording(response, output, force)
74
+ try:
75
+ return response.json()
76
+ except (json.JSONDecodeError, requests.exceptions.JSONDecodeError):
77
+ raise Error("服务端响应格式错误" if reading else "请求结果未知,请先查询确认后再决定是否重试",
78
+ 5 if reading else 4) from None
79
+ except requests.RequestException:
80
+ if attempt + 1 == attempts:
81
+ message = (f"无法连接 {self.host},请稍后重试" if reading else
82
+ "请求结果未知,请先查询确认后再决定是否重试")
83
+ raise Error(message, 4, code="NETWORK_ERROR") from None
84
+
85
+
86
+ def save_recording(response, destination, force):
87
+ path = Path(destination)
88
+ temp = None
89
+ try:
90
+ with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle:
91
+ temp = Path(handle.name)
92
+ for chunk in response.iter_content(128 * 1024):
93
+ handle.write(chunk)
94
+ size = handle.tell()
95
+ if force:
96
+ os.replace(temp, path)
97
+ else:
98
+ os.link(temp, path)
99
+ return {"output": str(path), "bytes": size}
100
+ except FileExistsError:
101
+ raise Error("文件已存在,添加 --force 覆盖") from None
102
+ finally:
103
+ if temp:
104
+ temp.unlink(missing_ok=True)
smartcheck_cli/main.py ADDED
@@ -0,0 +1,197 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ import sys
5
+
6
+ from . import __version__, auth
7
+ from .commands import run_business
8
+ from .http import Client, Error, PRODUCTION, note
9
+
10
+
11
+ class Parser(argparse.ArgumentParser):
12
+ def format_help(self):
13
+ return super().format_help().replace("usage: ", "用法:").replace("options:", "选项:").replace(
14
+ "positional arguments:", "位置参数:")
15
+
16
+ def error(self, message):
17
+ translations = {"the following arguments are required:": "缺少必填参数:",
18
+ "unrecognized arguments:": "无法识别的参数:", "invalid choice:": "无效选项:",
19
+ "not allowed with argument": "不能同时指定", "expected one argument": "需要一个值"}
20
+ for source, target in translations.items():
21
+ message = message.replace(source, target)
22
+ raise Error(message, code="INVALID_ARGUMENT")
23
+
24
+
25
+ def options(parser):
26
+ parser.add_argument("-h", "--help", action="help", help="显示帮助")
27
+ parser.add_argument("--host", default=argparse.SUPPRESS, help="可信网页地址,默认 SMARTCHECK_HOST 或生产地址")
28
+ parser.add_argument("--timeout", type=float, default=argparse.SUPPRESS, help="请求超时秒数,默认 30,最大 300")
29
+ parser.add_argument("--pretty", action="store_true", default=argparse.SUPPRESS, help="缩进输出 JSON")
30
+ parser.add_argument("--version", action="version", version=__version__, help="显示安装版本")
31
+
32
+
33
+ GROUPS = {
34
+ "auth": ("账号授权", [("login", "浏览器登录", ""), ("status", "在线校验登录状态", ""),
35
+ ("logout", "退出并撤销授权", "")]),
36
+ "calls": ("本企业通话", [("list", "分页查询通话", "--page 1"), ("get", "读取通话详情", "CALL001"),
37
+ ("download-recording", "下载一个录音来源", "CALL001 --source SOURCE --output call.wav")]),
38
+ "accounts": ("成员账号", [("list", "分页查询成员", "--page 1"), ("get", "查看成员资料", "zhangsan"),
39
+ ("create", "新建成员账号", "--name 张三 --email a@example.com --username zhangsan --generate-password"),
40
+ ("update", "修改指定资料或密码", "zhangsan --name 张三"), ("delete", "删除成员账号", "zhangsan --yes")]),
41
+ "call-fields": ("通话字段", [("list", "依次列出字段定义", ""), ("get", "读取字段定义", "store"),
42
+ ("create", "新增字段", "--json-file field.json"), ("update", "替换可编辑属性", "store --json-file update.json"),
43
+ ("enable", "启用字段", "store"), ("disable", "停用字段", "store"),
44
+ ("reorder", "提交全部字段的顺序", "store region"), ("delete", "删除字段", "store --yes")]),
45
+ "speaker-roles": ("话者识别", [("get", "查看识别配置", ""), ("set", "保存识别配置", "--json-file roles.json --yes")]),
46
+ }
47
+
48
+
49
+ def arguments(parser, group, action):
50
+ add = parser.add_argument
51
+ if action == "login":
52
+ add("--device-name", help="1–100 字符,默认本机名称")
53
+ add("--no-browser", action="store_true", help="手动在本机浏览器打开链接")
54
+ if action == "list" and group in ("calls", "accounts"):
55
+ add("--keyword", help="搜索词,默认全部")
56
+ add("--page", type=int, default=1, help="页码,默认 1")
57
+ add("--per-page", type=int, default=10, choices=(10, 20, 50) if group == "accounts" else None,
58
+ help="每页条数,默认 10,最大 50")
59
+ if group == "calls":
60
+ add("--start-date", help="开始日期,YYYY-MM-DD,北京时间")
61
+ add("--end-date", help="结束日期,YYYY-MM-DD,北京时间")
62
+ add("--direction", choices=("inbound", "outbound", "unknown"), help="通话方向")
63
+ if action in ("delete", "enable", "disable", "download-recording", "update") or (action == "get" and group != "speaker-roles"):
64
+ label = {"calls": "call_id", "accounts": "username", "call-fields": "field_key"}[group]
65
+ add("identifier", metavar=label, help="目标标识")
66
+ if action == "download-recording":
67
+ add("--source", required=True, help="详情中的 source_id")
68
+ add("--output", required=True, help="本地目标文件")
69
+ add("--force", action="store_true", help="覆盖已有文件")
70
+ if group == "accounts" and action in ("create", "update"):
71
+ creating = action == "create"
72
+ add("--name", required=creating, help="成员姓名")
73
+ add("--email", required=creating, help="成员邮箱")
74
+ phone = parser.add_mutually_exclusive_group()
75
+ phone.add_argument("--phone", help="手机号")
76
+ if creating:
77
+ add("--username", required=True, help="登录用户名")
78
+ else:
79
+ phone.add_argument("--clear-phone", action="store_true", help="清空手机号")
80
+ passwords = parser.add_mutually_exclusive_group()
81
+ passwords.add_argument("--generate-password", action="store_true", help="生成 16 位随机密码")
82
+ passwords.add_argument("--password-stdin", action="store_true", help="从标准输入读取一行密码")
83
+ if (group == "call-fields" and action in ("create", "update")) or action == "set":
84
+ add("--json-file", required=True, help="UTF-8 请求体文件,示例见 guide")
85
+ if action == "reorder":
86
+ add("field_keys", nargs="+", metavar="field_key", help="按新顺序给出全部字段键")
87
+ if action in ("delete", "set"):
88
+ add("--yes", action="store_true", help="确认执行,非交互环境必填")
89
+
90
+
91
+ def parser_tree():
92
+ common = Parser(add_help=False, allow_abbrev=False)
93
+ options(common)
94
+ settings = dict(add_help=False, parents=[common], allow_abbrev=False)
95
+ root = Parser(prog="smartcheck", description="SmartCheck 命令行", epilog="示例:smartcheck guide", **settings)
96
+ groups = root.add_subparsers(dest="group", required=True, title="命令")
97
+ guide = groups.add_parser("guide", help="离线使用指南", epilog="示例:smartcheck guide --format markdown", **settings)
98
+ guide.add_argument("--format", choices=("terminal", "markdown", "json"), default="terminal", help="输出格式,默认 terminal")
99
+ entries = []
100
+ for name, (label, actions) in GROUPS.items():
101
+ group = groups.add_parser(name, help=label, epilog=f"示例:smartcheck {name} {actions[0][0]} --help", **settings)
102
+ children = group.add_subparsers(dest="action", required=True, title="子命令")
103
+ for action, purpose, example in actions:
104
+ command = f"smartcheck {name} {action}"
105
+ sample = (command + " " + example).strip()
106
+ child = children.add_parser(action, help=purpose, description=purpose, epilog="示例:" + sample, **settings)
107
+ arguments(child, name, action)
108
+ entries.append(dict(command=command, purpose=purpose, example=sample,
109
+ role="管理员" if name not in ("auth", "calls") else "管理员或成员",
110
+ confirmation=action in ("delete", "set"),
111
+ parameters=[f"{a.option_strings[-1] if a.option_strings else a.metavar} {a.help}"
112
+ for a in child._actions if a not in common._actions]))
113
+ return root, entries
114
+
115
+
116
+ def guide_content(entries):
117
+ field = dict(label="门店", description="来电门店", config={}, options=[])
118
+ return {
119
+ "product": "企业是数据隔离范围。通话可以包含录音来源、按时间排序的转写话轮和企业定义的业务字段。",
120
+ "permissions": "管理员可管理账号、字段和话者识别。成员只能查看本企业通话及录音。",
121
+ "install": "python -m pip install --upgrade smartcheck-cli 或 pipx install smartcheck-cli",
122
+ "global_options": ["--host > SMARTCHECK_HOST > " + PRODUCTION, "--pretty 缩进 JSON",
123
+ "--timeout 请求超时秒数(默认 30,最大 300)", "--version 版本", "--help 帮助"],
124
+ "guide": "smartcheck guide [--format terminal|markdown|json],默认 terminal,无需登录",
125
+ "commands": entries,
126
+ "examples": {"call-fields create": dict(field_key="store", field_type="text", **field),
127
+ "call-fields update": field, "speaker-roles set": {"mode": "decision", "fallback": False},
128
+ "按声道标注": {"mode": "channel", "channels": [{"source": "CRM", "left": "agent", "right": "customer"}]},
129
+ "LLM": {"mode": "llm", "llm": {"prompt": "请判断每位说话人的角色", "agent": {"key": "role", "value": "agent"},
130
+ "user": {"key": "role", "value": "user"}}}},
131
+ "security": ["凭据只存于系统凭据库。请只在信任的电脑和 AI 助手中授权。",
132
+ "生成的密码只输出一次,请立即保存。写操作结果未知时先查询确认。"],
133
+ "exit_codes": {"0": "成功", "1": "取消或需要 --yes", "2": "参数或校验错误,请检查输入",
134
+ "3": "授权或权限错误,请核实身份、重新登录", "4": "网络错误,先核实操作结果",
135
+ "5": "服务端错误,请携带 trace_id 联系管理员"},
136
+ "workflow": ["smartcheck guide --format markdown", "smartcheck auth status",
137
+ "smartcheck calls list --page 1", "smartcheck calls get CALL001"],
138
+ }
139
+
140
+
141
+ def render_guide(data, mode):
142
+ heading = "## " if mode == "markdown" else ""
143
+ print(("# " if mode == "markdown" else "") + "SmartCheck CLI\n")
144
+ for key, label in [("product", "概念"), ("permissions", "权限"), ("install", "安装"), ("global_options", "全局参数"),
145
+ ("guide", "指南"), ("commands", "命令"), ("examples", "请求体示例"), ("security", "安全"),
146
+ ("exit_codes", "退出状态"), ("workflow", "使用顺序")]:
147
+ print(heading + label)
148
+ value = data[key]
149
+ if key == "commands":
150
+ for entry in value:
151
+ confirm = ",需确认" if entry["confirmation"] else ""
152
+ print(f"- {entry['command']} {entry['purpose']}({entry['role']}{confirm})")
153
+ if entry["parameters"]:
154
+ print(" " + ";".join(entry["parameters"]))
155
+ print(" 示例:" + entry["example"])
156
+ elif isinstance(value, dict):
157
+ for name, item in value.items():
158
+ print(f"{name} {json.dumps(item, ensure_ascii=False) if isinstance(item, dict) else item}")
159
+ else:
160
+ print("\n".join(value) if isinstance(value, list) else value)
161
+ print()
162
+
163
+
164
+ def main():
165
+ try:
166
+ parser, entries = parser_tree()
167
+ args = parser.parse_args()
168
+ client = Client(getattr(args, "host", os.getenv("SMARTCHECK_HOST", PRODUCTION)), getattr(args, "timeout", 30))
169
+ if args.group == "guide":
170
+ result = guide_content(entries)
171
+ if args.format != "json":
172
+ render_guide(result, args.format)
173
+ return 0
174
+ else:
175
+ # Confirmation is required even before touching the system keychain.
176
+ if args.action in ("delete", "set") and not args.yes and not sys.stdin.isatty():
177
+ raise Error("非交互环境需添加 --yes 确认此操作", 1)
178
+ vault = auth.Vault(client.host)
179
+ if args.group != "auth":
180
+ result = run_business(client, vault, args)
181
+ elif args.action == "login":
182
+ result = auth.login(client, vault, args)
183
+ elif args.action == "status":
184
+ result = auth.status(client, vault)
185
+ else:
186
+ result = auth.logout(client, vault)
187
+ print(json.dumps(result, ensure_ascii=False, indent=2 if getattr(args, "pretty", False) else None))
188
+ return 0
189
+ except Error as error:
190
+ note(error)
191
+ return error.exit_code
192
+ except (KeyboardInterrupt, EOFError):
193
+ note("操作已取消")
194
+ return 3 if 'args' in locals() and args.group == "auth" else 1
195
+ except OSError:
196
+ note(Error("本地文件读写失败,请检查目标路径和权限"))
197
+ return 2
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: smartcheck-cli
3
+ Version: 0.1.0
4
+ Summary: SmartCheck 账号授权与通话管理命令行
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: requests<3,>=2.32
7
+ Requires-Dist: filelock<4,>=3.13
8
+ Requires-Dist: keyring<26,>=25
@@ -0,0 +1,10 @@
1
+ smartcheck_cli/__init__.py,sha256=BtMvLAxL9Xvh_37ULEk1R2L9MJon6Mj310zL4YXzWO8,80
2
+ smartcheck_cli/auth.py,sha256=UQ5UFAHxWP8eyD4hVMdfNURkob25AJ-omw5yA3lCeEM,10369
3
+ smartcheck_cli/commands.py,sha256=n7nWociCAVSoQ4HhSNJtk_sdUnrgY17epR5mmkKm9q0,5809
4
+ smartcheck_cli/http.py,sha256=sAC1mFwwNMX4ZshNGQJKtVibrbqt701XVbjFzBdRbxM,4318
5
+ smartcheck_cli/main.py,sha256=N1YUWsGLkoZyIab1pRmuPoPen_tsjNmMix81Gmsk0uA,12369
6
+ smartcheck_cli-0.1.0.dist-info/METADATA,sha256=e0AP0GGIiykpjM0Vxj9h5NZHlMiNTa4ntR-k2l1-vUg,236
7
+ smartcheck_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ smartcheck_cli-0.1.0.dist-info/entry_points.txt,sha256=EKNRylYgDSqKW0QWYdBZ4NrKZcZgE_p92dWaqNiZxt4,56
9
+ smartcheck_cli-0.1.0.dist-info/top_level.txt,sha256=gLPNPG2PS4m-DUOSqlC35TzOV9j49sVwY_09yFTDx64,15
10
+ smartcheck_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ smartcheck = smartcheck_cli.main:main
@@ -0,0 +1 @@
1
+ smartcheck_cli