feat: 同步 LightCore 应用后台 CLI
This commit is contained in:
+37
-19
@@ -2,6 +2,7 @@
|
||||
import contextlib
|
||||
import errno
|
||||
import getpass
|
||||
from hashlib import sha256
|
||||
from http.client import IncompleteRead
|
||||
import ipaddress
|
||||
import json
|
||||
@@ -9,6 +10,7 @@ import mimetypes
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -20,7 +22,7 @@ from uuid import uuid4
|
||||
|
||||
DEFAULT_BASE_URL = 'https://api.zhecent.com'
|
||||
DEFAULT_BASE_URLS = {'shop': DEFAULT_BASE_URL, 'media': DEFAULT_BASE_URL,
|
||||
'gysmart': 'https://am.gysmart.shop'}
|
||||
'gysmart': 'https://am.gysmart.shop', 'fangyus': '', 'hengde': ''}
|
||||
APP_KEY = 'LIGHTCORE_API_APP'
|
||||
KEYS = ('LIGHTCORE_API_BASE_URL', 'LIGHTCORE_ACCESS_TOKEN', 'LIGHTCORE_REFRESH_TOKEN',
|
||||
'LIGHTCORE_ACCESS_TOKEN_EXPIRES_AT', 'LIGHTCORE_REFRESH_TOKEN_EXPIRES_AT')
|
||||
@@ -163,13 +165,14 @@ def reject_constant(_):
|
||||
|
||||
class MultipartBody:
|
||||
"""可重复打开的有长度流;仅认证失效允许一次重发。"""
|
||||
def __init__(self, file, fields):
|
||||
self.file = Path(file).resolve()
|
||||
def __init__(self, file, fields, *, reject_symlink=False):
|
||||
self.file = Path(file).absolute() if reject_symlink else Path(file).resolve()
|
||||
self.reject_symlink = reject_symlink
|
||||
if not isinstance(fields, dict) or any(not isinstance(k, str) or not isinstance(v, (str, int, float, bool)) for k, v in fields.items()):
|
||||
raise ClientError('上传表单必须是 JSON 对象,字段值为字符串、数字或布尔值。')
|
||||
if not self.file.is_file():
|
||||
raise ClientError('上传文件不存在。')
|
||||
self.stat = self.file.stat()
|
||||
self.stat = self.file.lstat() if self.reject_symlink else self.file.stat()
|
||||
if not stat.S_ISREG(self.stat.st_mode):
|
||||
raise ClientError('上传路径必须是普通文件。')
|
||||
boundary = 'lightcore-' + uuid4().hex
|
||||
self.content_type = 'multipart/form-data; boundary=' + boundary
|
||||
parts = []
|
||||
@@ -187,11 +190,13 @@ class MultipartBody:
|
||||
self.size = len(self.prefix) + self.stat.st_size + len(self.suffix)
|
||||
|
||||
def __iter__(self):
|
||||
current = self.file.stat()
|
||||
if (current.st_size, current.st_mtime_ns) != (self.stat.st_size, self.stat.st_mtime_ns):
|
||||
raise ClientError('上传文件已变化,未继续发送。')
|
||||
yield self.prefix
|
||||
with self.file.open('rb') as stream:
|
||||
current = os.fstat(stream.fileno())
|
||||
if (not os.path.samestat(current, self.stat)
|
||||
or current.st_size != self.stat.st_size or current.st_mtime_ns != self.stat.st_mtime_ns
|
||||
or self.reject_symlink and self.file.is_symlink()):
|
||||
raise ClientError('上传文件已变化,未继续发送。')
|
||||
yield self.prefix
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
yield chunk
|
||||
yield self.suffix
|
||||
@@ -203,7 +208,7 @@ class Client:
|
||||
def __init__(self, app, env_file, timeout=30):
|
||||
self.app = app
|
||||
self.timeout = timeout
|
||||
self.refreshable = self.app in ('shop', 'media')
|
||||
self.refreshable = self.app in ('shop', 'media', 'fangyus', 'hengde')
|
||||
self.auth_fields = {key: field for key, field in AUTH_FIELDS.items()
|
||||
if self.refreshable or key in (KEYS[1], KEYS[3])}
|
||||
self.admin_path = admin_path(app)
|
||||
@@ -250,7 +255,10 @@ class Client:
|
||||
|
||||
def configured_base(self, settings, explicit=None):
|
||||
candidates = (explicit, os.environ.get(KEYS[0]), settings.get(KEYS[0]))
|
||||
return base_url(next((value for value in candidates if value and value.strip()), DEFAULT_BASE_URLS[self.app]), self.app)
|
||||
address = next((value for value in candidates if value and value.strip()), DEFAULT_BASE_URLS[self.app])
|
||||
if not address:
|
||||
raise ClientError('首次登录请通过 --base-url 指定目标后端地址。')
|
||||
return base_url(address, self.app)
|
||||
|
||||
def read_session(self):
|
||||
if not self.env.is_file():
|
||||
@@ -284,16 +292,19 @@ class Client:
|
||||
details = {'httpStatus': response.status, 'code': 200,
|
||||
'traceId': response.headers.get('X-Request-ID')}
|
||||
target = Path(output).absolute()
|
||||
digest = sha256()
|
||||
try:
|
||||
size = 0
|
||||
with private_output(target) as stream:
|
||||
while chunk := response.read(1024 * 1024):
|
||||
stream.write(chunk)
|
||||
digest.update(chunk)
|
||||
size += len(chunk)
|
||||
expected = response.headers.get('Content-Length')
|
||||
if expected is not None and size != int(expected):
|
||||
raise ClientError('下载长度不完整,未保存目标文件。', **details)
|
||||
return {'ok': True, **details, 'downloaded': True, 'outputFile': str(target), 'bytes': size}
|
||||
return {'ok': True, **details, 'downloaded': True, 'outputFile': str(target),
|
||||
'bytes': size, 'sha256': digest.hexdigest()}
|
||||
except (OSError, ValueError, IncompleteRead, subprocess.SubprocessError) as error:
|
||||
raise ClientError('下载未完成或目标文件已存在;未覆盖目标文件。', **details) from error
|
||||
|
||||
@@ -306,21 +317,23 @@ class Client:
|
||||
headers['Content-Type'] = payload.content_type
|
||||
headers['Content-Length'] = str(payload.size)
|
||||
request = Request(base + self.admin_path + path, data=payload, headers=headers, method=method)
|
||||
trace_id = None
|
||||
try:
|
||||
try:
|
||||
response = self.http.open(request, timeout=self.timeout)
|
||||
except HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
trace_id = response.headers.get('X-Request-ID')
|
||||
if (output is not None and 200 <= response.status < 300
|
||||
and response.headers.get('Content-Disposition', '').lower().startswith('attachment')
|
||||
and (self.app != 'system' or response.headers.get_content_type() == 'application/zip')):
|
||||
return self.save_download(response, output)
|
||||
raw = response.read().decode(response.headers.get_content_charset() or 'utf-8')
|
||||
trace_id = response.headers.get('X-Request-ID')
|
||||
status = response.status
|
||||
except (URLError, OSError, TimeoutError, IncompleteRead, ValueError):
|
||||
raise ClientError('HTTP 请求未获得完整响应,结果未知;写操作请先核对业务结果,不要盲目重试。') from None
|
||||
details = {'traceId': trace_id} if trace_id else {}
|
||||
raise ClientError('HTTP 请求未获得完整响应,结果未知;写操作请先核对业务结果,不要盲目重试。', **details) from None
|
||||
parsed = None
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
@@ -397,14 +410,18 @@ class Client:
|
||||
except (OSError, subprocess.SubprocessError, ClientError) as error:
|
||||
raise ClientError('服务端已退出,但清理本机会话失败。', **details) from error
|
||||
|
||||
def login_base(self, explicit_base):
|
||||
def login_base(self, explicit_base, isolate_target=False):
|
||||
previous = self.read_settings()
|
||||
if previous.get(APP_KEY) not in (None, self.app) or (previous.get(APP_KEY) is None and any(previous.get(k) for k in KEYS[1:])):
|
||||
raise ClientError('目标文件已有其他或未标明应用的会话,拒绝覆盖,请使用独立会话文件。')
|
||||
return self.configured_base(previous, explicit_base)
|
||||
base = self.configured_base(previous, explicit_base)
|
||||
if (isolate_target and previous.get(KEYS[0]) and previous.get(KEYS[1])
|
||||
and base_url(previous[KEYS[0]], self.app) != base):
|
||||
raise ClientError('会话文件属于其他目标后端,请通过 --env-file 指定独立文件。')
|
||||
return base
|
||||
|
||||
def login(self, explicit_base=None):
|
||||
base = self.login_base(explicit_base)
|
||||
def login(self, explicit_base=None, *, isolate_target=False):
|
||||
base = self.login_base(explicit_base, isolate_target)
|
||||
account_field = 'identifier' if self.app == 'shop' else 'username'
|
||||
while True:
|
||||
identifier = input('后台账号或登录手机号: ')
|
||||
@@ -421,6 +438,7 @@ class Client:
|
||||
break
|
||||
session = self.auth_session(base, response)
|
||||
with session_lock(self.env, self.timeout):
|
||||
self.login_base(base, isolate_target)
|
||||
self.write_session(session)
|
||||
return {'ok': True, 'traceId': response['traceId'], 'message': '登录成功,会话已保存在本机。'}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user