"""通用后台 HTTP 命令。""" import json from pathlib import Path import subprocess from uuid import uuid4 from . import transport from .transport import ClientError, compact, private_write class RawClient(transport.Client): def __init__(self, args, response_dir): super().__init__(args.app, args.env_file, args.timeout) self.args = args self.response_dir = response_dir def request(self): payload = (Path(self.args.body_file).read_bytes() if self.args.body_file else (self.args.body if self.args.body is not None else '{}').encode('utf-8')) try: body = json.loads(payload.decode('utf-8-sig'), parse_constant=transport.reject_constant) except (ValueError, UnicodeError): raise ClientError('请求正文必须是有效 JSON。') from None self.remember_secrets(body) if self.args.action == 'upload': payload = transport.MultipartBody(self.args.file, body) response = self.exchange(self.args.path, payload, self.args.method, self.args.output) return format_response(self, response, self.response_dir, self.args.max_chars) def format_response(client, response, response_dir, max_chars=6000): if response.get('downloaded'): return response raw = client.redact(response['raw']) try: body = json.loads(raw) except ValueError: body = raw result = {'ok': client.success(response), 'httpStatus': response['httpStatus'], 'code': response['code'], 'traceId': response['traceId'], 'truncated': False, 'body': body} if len(compact(result)) > max_chars: file = response_dir / (uuid4().hex + '.json') try: private_write(file, raw) except (OSError, subprocess.SubprocessError, ClientError): raise ClientError('已收到服务端响应,但完整响应保存失败;请按 traceId 核对结果,不要重复写入。', **{key: response[key] for key in ('httpStatus', 'code', 'traceId')}) from None del result['body'] result.update(truncated=True, responseFile=str(file), preview='') low, high = 0, min(len(raw), max_chars) while low < high: middle = (low + high + 1) // 2 result['preview'] = raw[:middle] if len(compact(result)) <= max_chars: low = middle else: high = middle - 1 result['preview'] = raw[:low] return result def add_arguments(parser): parser.add_argument('action', choices=('login', 'request', 'upload', 'download')) parser.add_argument('--base-url', help='仅登录使用;GYSmart 默认 https://am.gysmart.shop,Shop/Media 默认 https://api.zhecent.com') parser.add_argument('--app', required=True, choices=tuple(transport.DEFAULT_BASE_URLS)) parser.add_argument('--path') parser.add_argument('--file', help='上传的本机文件') parser.add_argument('--output', help='下载目标文件,拒绝覆盖') body = parser.add_mutually_exclusive_group() body.add_argument('--body') body.add_argument('--body-file') parser.add_argument('--method', default='POST', choices=('GET', 'POST', 'PUT', 'PATCH', 'DELETE')) parser.add_argument('--env-file') parser.add_argument('--max-chars', type=int, default=6000) parser.add_argument('--timeout', type=int, default=30) def run(args, parser, response_dir): if not 1024 <= args.max_chars <= 1000000 or not 1 <= args.timeout <= 120: parser.error('max-chars 范围为 1024—1000000,timeout 范围为 1—120 秒。') if args.action == 'login' and (args.path or args.body is not None or args.body_file): parser.error('login 不接受业务路径或正文。') if args.action != 'login' and (not args.path or args.base_url): parser.error('request 需要 --path;服务地址来自已登录会话。') if args.action == 'upload' and not args.file: parser.error('upload 需要 --file。') if args.action == 'download' and not args.output: parser.error('download 需要 --output。') if args.action != 'upload' and args.file: parser.error('--file 仅供 upload 使用。') if args.action != 'download' and args.output: parser.error('--output 仅供 download 使用。') client = RawClient(args, response_dir) try: result = client.login(args.base_url) if args.action == 'login' else client.request() except ClientError as error: result = {'ok': False, 'message': str(error), **error.details} except (OSError, subprocess.SubprocessError, UnicodeError, EOFError, ValueError): result = {'ok': False, 'message': '本机文件、权限或会话数据处理失败;若请求已发出,先核对结果,不要盲目重试。'} except KeyboardInterrupt: result = {'ok': False, 'message': '操作已取消;若请求已经发出,先核对业务结果。'} print(client.redact(compact(result))) return 0 if result['ok'] else 1