codecin 7.22.10__py3-none-win_amd64.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.
- codecin/__init__.py +27 -0
- codecin/aot.py +1057 -0
- codecin/assembler.py +619 -0
- codecin/cbackend.py +3024 -0
- codecin/cin.py +4265 -0
- codecin/cli.py +670 -0
- codecin/codecin_native.dll +0 -0
- codecin/config.py +50 -0
- codecin/console.py +183 -0
- codecin/cpu.py +312 -0
- codecin/crom.py +449 -0
- codecin/cvm.py +708 -0
- codecin/disasm.py +149 -0
- codecin/environment.py +176 -0
- codecin/errors.py +54 -0
- codecin/isa.py +560 -0
- codecin/lib/array/pic.toml +10 -0
- codecin/lib/array/src/array.cin +103 -0
- codecin/lib/bigint/pic.toml +10 -0
- codecin/lib/bigint/src/bigint.cin +589 -0
- codecin/lib/bits/pic.toml +10 -0
- codecin/lib/bits/src/bits.cin +143 -0
- codecin/lib/bitset/pic.toml +10 -0
- codecin/lib/bitset/src/bitset.cin +374 -0
- codecin/lib/codec/pic.toml +10 -0
- codecin/lib/codec/src/codec.cin +563 -0
- codecin/lib/combin/pic.toml +10 -0
- codecin/lib/combin/src/combin.cin +414 -0
- codecin/lib/conv/pic.toml +10 -0
- codecin/lib/conv/src/conv.cin +151 -0
- codecin/lib/cppstd/pic.toml +10 -0
- codecin/lib/cppstd/src/cppstd.cin +418 -0
- codecin/lib/cstd/pic.toml +10 -0
- codecin/lib/cstd/src/cstd.cin +424 -0
- codecin/lib/csv/pic.toml +10 -0
- codecin/lib/csv/src/csv.cin +405 -0
- codecin/lib/dp/pic.toml +10 -0
- codecin/lib/dp/src/dp.cin +325 -0
- codecin/lib/ffi/pic.toml +10 -0
- codecin/lib/ffi/src/ffi.cin +163 -0
- codecin/lib/fmt/pic.toml +10 -0
- codecin/lib/fmt/src/fmt.cin +325 -0
- codecin/lib/frac/pic.toml +10 -0
- codecin/lib/frac/src/frac.cin +252 -0
- codecin/lib/gostd/pic.toml +10 -0
- codecin/lib/gostd/src/gostd.cin +415 -0
- codecin/lib/graph/pic.toml +10 -0
- codecin/lib/graph/src/graph.cin +367 -0
- codecin/lib/gui/pic.toml +10 -0
- codecin/lib/gui/src/gui.cin +218 -0
- codecin/lib/hash/pic.toml +10 -0
- codecin/lib/hash/src/hash.cin +67 -0
- codecin/lib/heap/pic.toml +10 -0
- codecin/lib/heap/src/heap.cin +199 -0
- codecin/lib/io/pic.toml +10 -0
- codecin/lib/io/src/io.cin +141 -0
- codecin/lib/json/pic.toml +10 -0
- codecin/lib/json/src/json.cin +84 -0
- codecin/lib/key/pic.toml +10 -0
- codecin/lib/key/src/key.cin +78 -0
- codecin/lib/math/pic.toml +10 -0
- codecin/lib/math/src/math.cin +50 -0
- codecin/lib/matrix/pic.toml +10 -0
- codecin/lib/matrix/src/matrix.cin +155 -0
- codecin/lib/net/pic.toml +10 -0
- codecin/lib/net/src/net.cin +171 -0
- codecin/lib/path/pic.toml +10 -0
- codecin/lib/path/src/path.cin +372 -0
- codecin/lib/queue/pic.toml +10 -0
- codecin/lib/queue/src/queue.cin +112 -0
- codecin/lib/rand/pic.toml +10 -0
- codecin/lib/rand/src/rand.cin +46 -0
- codecin/lib/set/pic.toml +10 -0
- codecin/lib/set/src/set.cin +269 -0
- codecin/lib/sort/pic.toml +10 -0
- codecin/lib/sort/src/sort.cin +93 -0
- codecin/lib/stat/pic.toml +10 -0
- codecin/lib/stat/src/stat.cin +138 -0
- codecin/lib/str/pic.toml +10 -0
- codecin/lib/str/src/str.cin +54 -0
- codecin/lib/termux/pic.toml +10 -0
- codecin/lib/termux/src/termux.cin +118 -0
- codecin/lib/test/pic.toml +10 -0
- codecin/lib/test/src/test.cin +74 -0
- codecin/lib/text/pic.toml +10 -0
- codecin/lib/text/src/text.cin +323 -0
- codecin/lib/time/pic.toml +10 -0
- codecin/lib/time/src/time.cin +54 -0
- codecin/lib/token/pic.toml +10 -0
- codecin/lib/token/src/token.cin +183 -0
- codecin/lib/tree/pic.toml +10 -0
- codecin/lib/tree/src/tree.cin +256 -0
- codecin/lib/unionfind/pic.toml +10 -0
- codecin/lib/unionfind/src/unionfind.cin +115 -0
- codecin/lib/validate/pic.toml +10 -0
- codecin/lib/validate/src/validate.cin +148 -0
- codecin/lib/vec/pic.toml +10 -0
- codecin/lib/vec/src/vec.cin +88 -0
- codecin/logger.py +145 -0
- codecin/memory.py +306 -0
- codecin/mkn.py +916 -0
- codecin/native/aot/aot.go +114 -0
- codecin/native/aot/stub_main.go.txt +23 -0
- codecin/native/build.ps1 +33 -0
- codecin/native/build.sh +48 -0
- codecin/native/cmd/cincc/main.go +66 -0
- codecin/native/compiler/codegen.go +2238 -0
- codecin/native/compiler/compile_test.go +1069 -0
- codecin/native/compiler/parser.go +1331 -0
- codecin/native/compiler/syscalls.go +166 -0
- codecin/native/compiler/tokenizer.go +394 -0
- codecin/native/compiler/types.go +217 -0
- codecin/native/engine/args.go +37 -0
- codecin/native/engine/audio.go +402 -0
- codecin/native/engine/audio_other.go +105 -0
- codecin/native/engine/audio_test.go +279 -0
- codecin/native/engine/audio_windows.go +190 -0
- codecin/native/engine/canvas.go +271 -0
- codecin/native/engine/console_other.go +9 -0
- codecin/native/engine/console_windows.go +43 -0
- codecin/native/engine/crom.go +86 -0
- codecin/native/engine/encode.go +93 -0
- codecin/native/engine/engine_test.go +198 -0
- codecin/native/engine/ffi_nocgo.go +20 -0
- codecin/native/engine/ffi_registry.go +69 -0
- codecin/native/engine/ffi_unix.go +109 -0
- codecin/native/engine/ffi_windows.go +117 -0
- codecin/native/engine/gui.go +209 -0
- codecin/native/engine/gui_stub.go +13 -0
- codecin/native/engine/gui_test.go +148 -0
- codecin/native/engine/gui_windows.go +604 -0
- codecin/native/engine/gui_x11.go +723 -0
- codecin/native/engine/host_test.go +139 -0
- codecin/native/engine/hostcrypto.go +30 -0
- codecin/native/engine/hostdesktop.go +173 -0
- codecin/native/engine/hostnet.go +127 -0
- codecin/native/engine/isa_gen.go +689 -0
- codecin/native/engine/keyboard.go +432 -0
- codecin/native/engine/keyboard_other.go +94 -0
- codecin/native/engine/keyboard_stub.go +17 -0
- codecin/native/engine/keyboard_termios_darwin.go +9 -0
- codecin/native/engine/keyboard_termios_linux.go +9 -0
- codecin/native/engine/keyboard_test.go +246 -0
- codecin/native/engine/keyboard_windows.go +208 -0
- codecin/native/engine/keyboard_windows_test.go +123 -0
- codecin/native/engine/lineedit.go +262 -0
- codecin/native/engine/lineedit_test.go +105 -0
- codecin/native/engine/lineint_unix.go +17 -0
- codecin/native/engine/lineint_windows.go +19 -0
- codecin/native/engine/mem_other.go +37 -0
- codecin/native/engine/mem_windows.go +33 -0
- codecin/native/engine/native.go +640 -0
- codecin/native/engine/netsock.go +321 -0
- codecin/native/engine/ops_ext.go +515 -0
- codecin/native/engine/stdin.go +72 -0
- codecin/native/engine/stdin_other.go +9 -0
- codecin/native/engine/stdin_windows.go +60 -0
- codecin/native/engine/system.go +313 -0
- codecin/native/engine/termux.go +180 -0
- codecin/native/engine/version_gen.go +7 -0
- codecin/native/engine/vkb_darwin.go +62 -0
- codecin/native/engine/vkb_linux.go +95 -0
- codecin/native/engine/vkb_stub.go +11 -0
- codecin/native/engine/vm.go +1677 -0
- codecin/native/go.mod +3 -0
- codecin/native/ir/ir.go +48 -0
- codecin/native/main.go +448 -0
- codecin/native/mc/aarch64.go +165 -0
- codecin/native/mc/aarch64_test.go +30 -0
- codecin/native/mc/elf.go +88 -0
- codecin/native/mc/print_test.go +52 -0
- codecin/native/mc/x86_64.go +1262 -0
- codecin/native/mc/x86_64_test.go +102 -0
- codecin/native.py +432 -0
- codecin/native_codegen.py +987 -0
- codecin/nativegen.py +786 -0
- codecin/object.py +539 -0
- codecin/optimizer.py +236 -0
- codecin/packaging/__init__.py +46 -0
- codecin/packaging/archive.py +177 -0
- codecin/packaging/model.py +519 -0
- codecin/packaging/spec.py +193 -0
- codecin/packaging/store.py +372 -0
- codecin/packaging/toml.py +541 -0
- codecin/packaging/vcs.py +215 -0
- codecin/pic.py +1917 -0
- codecin/pic_api.py +374 -0
- codecin/pic_login.py +519 -0
- codecin/pic_registry.py +515 -0
- codecin/registers.py +130 -0
- codecin/sdgcc.py +493 -0
- codecin/stats.py +230 -0
- codecin/stdlib.py +138 -0
- codecin/toolchain.py +396 -0
- codecin/toolkit.py +26 -0
- codecin/version.py +260 -0
- codecin-7.22.10.dist-info/METADATA +1077 -0
- codecin-7.22.10.dist-info/RECORD +202 -0
- codecin-7.22.10.dist-info/WHEEL +5 -0
- codecin-7.22.10.dist-info/entry_points.txt +5 -0
- codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
- codecin-7.22.10.dist-info/top_level.txt +1 -0
codecin/pic_api.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""Cdifit 身份服务 API 客户端 (pic v6.2.0+)。
|
|
2
|
+
|
|
3
|
+
Cdifit (``https://www.cdifit.cn``) **只用于登录/Token 校验**; 包记录与
|
|
4
|
+
``.cinpkg`` 制品由 ``package.codecin.org.cn`` 中央注册/分发服务器负责
|
|
5
|
+
(见 :mod:`codecin.pic_registry`)。本模块只负责:
|
|
6
|
+
|
|
7
|
+
* ``POST /api/v4/session/token`` 密码登录 (含 2FA);
|
|
8
|
+
* ``PUT /api/v4/session/token/refresh`` 刷新令牌;
|
|
9
|
+
* ``DELETE /api/v4/session/token`` 退出;
|
|
10
|
+
* ``GET /api/v4/session/oauth/userinfo`` 用户信息。
|
|
11
|
+
|
|
12
|
+
API 文档: https://docs.cdifit.com/zh/api/session
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import tempfile
|
|
19
|
+
import time
|
|
20
|
+
import urllib.error
|
|
21
|
+
import urllib.request
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from datetime import datetime, timezone
|
|
24
|
+
from typing import Any, Dict, Optional
|
|
25
|
+
|
|
26
|
+
DEFAULT_API_BASE = 'https://www.cdifit.cn'
|
|
27
|
+
API_PREFIX = '/api/v4'
|
|
28
|
+
__all__ = [
|
|
29
|
+
'ApiError', 'AuthState', 'AuthStore', 'CdifitClient', 'TwoFactorRequired',
|
|
30
|
+
'DEFAULT_API_BASE', 'auth_path',
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ApiError(RuntimeError):
|
|
35
|
+
"""Cdifit API 返回非 0 code 或 HTTP 错误。"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, message: str, *, status: int = 0, code: int = 0,
|
|
38
|
+
data: Any = None):
|
|
39
|
+
super().__init__(message)
|
|
40
|
+
self.status = status
|
|
41
|
+
self.code = code
|
|
42
|
+
self.data = data
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class TwoFactorRequired(ApiError):
|
|
46
|
+
"""密码登录返回 code=203, 需要 2FA。"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, session: str):
|
|
49
|
+
super().__init__('需要两步验证', code=203, data=session)
|
|
50
|
+
self.session = session
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class AuthState:
|
|
55
|
+
api_base: str = DEFAULT_API_BASE
|
|
56
|
+
access_token: str = ''
|
|
57
|
+
refresh_token: str = ''
|
|
58
|
+
access_expires: Optional[str] = None
|
|
59
|
+
refresh_expires: Optional[str] = None
|
|
60
|
+
user: Dict[str, Any] = field(default_factory=dict)
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def email(self) -> str:
|
|
64
|
+
return str(self.user.get('email') or '')
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def display_name(self) -> str:
|
|
68
|
+
return str(self.user.get('nickname') or self.user.get('name')
|
|
69
|
+
or self.email or self.user.get('id') or 'unknown')
|
|
70
|
+
|
|
71
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
72
|
+
return {
|
|
73
|
+
'api_base': self.api_base,
|
|
74
|
+
'access_token': self.access_token,
|
|
75
|
+
'refresh_token': self.refresh_token,
|
|
76
|
+
'access_expires': self.access_expires,
|
|
77
|
+
'refresh_expires': self.refresh_expires,
|
|
78
|
+
'user': self.user,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
def from_dict(cls, data: Dict[str, Any]) -> 'AuthState':
|
|
83
|
+
return cls(
|
|
84
|
+
api_base=str(data.get('api_base') or DEFAULT_API_BASE),
|
|
85
|
+
access_token=str(data.get('access_token') or ''),
|
|
86
|
+
refresh_token=str(data.get('refresh_token') or ''),
|
|
87
|
+
access_expires=data.get('access_expires'),
|
|
88
|
+
refresh_expires=data.get('refresh_expires'),
|
|
89
|
+
user=dict(data.get('user') or {}),
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _parse_time(value: Any) -> Optional[datetime]:
|
|
94
|
+
if not value:
|
|
95
|
+
return None
|
|
96
|
+
text = str(value).strip()
|
|
97
|
+
try:
|
|
98
|
+
parsed = datetime.fromisoformat(text.replace('Z', '+00:00'))
|
|
99
|
+
except ValueError:
|
|
100
|
+
return None
|
|
101
|
+
if parsed.tzinfo is None:
|
|
102
|
+
parsed = parsed.replace(tzinfo=timezone.utc)
|
|
103
|
+
return parsed
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _expiring(value: Any, skew: int = 60) -> bool:
|
|
107
|
+
parsed = _parse_time(value)
|
|
108
|
+
if parsed is None:
|
|
109
|
+
return False
|
|
110
|
+
return parsed.timestamp() - skew <= time.time()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _pic_home() -> str:
|
|
114
|
+
return os.path.abspath(os.environ.get('PIC_HOME')
|
|
115
|
+
or os.path.join(os.path.expanduser('~'), '.pic'))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def auth_path() -> str:
|
|
119
|
+
return os.path.join(_pic_home(), 'auth.json')
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class AuthStore:
|
|
123
|
+
"""``$PIC_HOME/auth.json`` 的读写 (权限尽量设为 0600)。"""
|
|
124
|
+
|
|
125
|
+
def __init__(self, path: Optional[str] = None):
|
|
126
|
+
self.path = path or auth_path()
|
|
127
|
+
|
|
128
|
+
def load(self) -> Optional[AuthState]:
|
|
129
|
+
if not os.path.isfile(self.path):
|
|
130
|
+
return None
|
|
131
|
+
try:
|
|
132
|
+
with open(self.path, encoding='utf-8') as f:
|
|
133
|
+
data = json.load(f)
|
|
134
|
+
if not isinstance(data, dict):
|
|
135
|
+
return None
|
|
136
|
+
state = AuthState.from_dict(data)
|
|
137
|
+
return state if state.access_token else None
|
|
138
|
+
except (OSError, ValueError, TypeError):
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
def save(self, state: AuthState) -> None:
|
|
142
|
+
os.makedirs(os.path.dirname(self.path), exist_ok=True)
|
|
143
|
+
payload = json.dumps(state.to_dict(), ensure_ascii=False,
|
|
144
|
+
indent=2) + '\n'
|
|
145
|
+
fd, tmp = tempfile.mkstemp(prefix='.auth-', suffix='.json',
|
|
146
|
+
dir=os.path.dirname(self.path))
|
|
147
|
+
try:
|
|
148
|
+
with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as f:
|
|
149
|
+
f.write(payload)
|
|
150
|
+
with contextlib.suppress(OSError):
|
|
151
|
+
os.chmod(tmp, 0o600)
|
|
152
|
+
os.replace(tmp, self.path)
|
|
153
|
+
finally:
|
|
154
|
+
if os.path.exists(tmp):
|
|
155
|
+
with contextlib.suppress(OSError):
|
|
156
|
+
os.remove(tmp)
|
|
157
|
+
|
|
158
|
+
def clear(self) -> None:
|
|
159
|
+
with contextlib.suppress(OSError):
|
|
160
|
+
os.remove(self.path)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class CdifitClient:
|
|
164
|
+
"""轻量 HTTP 客户端 (标准库, 无第三方依赖)。"""
|
|
165
|
+
|
|
166
|
+
def __init__(self, api_base: str = DEFAULT_API_BASE,
|
|
167
|
+
auth: Optional[AuthState] = None,
|
|
168
|
+
store: Optional[AuthStore] = None,
|
|
169
|
+
timeout: int = 25):
|
|
170
|
+
self.api_base = (api_base or DEFAULT_API_BASE).rstrip('/')
|
|
171
|
+
self.auth = auth
|
|
172
|
+
self.store = store
|
|
173
|
+
self.timeout = timeout
|
|
174
|
+
|
|
175
|
+
# ---------------- 底层请求 ----------------
|
|
176
|
+
|
|
177
|
+
def _url(self, path: str) -> str:
|
|
178
|
+
if path.startswith('http://') or path.startswith('https://'):
|
|
179
|
+
return path
|
|
180
|
+
return self.api_base + (path if path.startswith('/') else '/' + path)
|
|
181
|
+
|
|
182
|
+
def _send(self, method: str, path: str, body: Optional[Dict[str, Any]] = None,
|
|
183
|
+
token: Optional[str] = None) -> Any:
|
|
184
|
+
headers = {'Accept': 'application/json',
|
|
185
|
+
'User-Agent': f'pic/{_version()}'}
|
|
186
|
+
data = None
|
|
187
|
+
if body is not None:
|
|
188
|
+
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
|
189
|
+
headers['Content-Type'] = 'application/json'
|
|
190
|
+
if token:
|
|
191
|
+
headers['Authorization'] = 'Bearer ' + token
|
|
192
|
+
request = urllib.request.Request(self._url(path), data=data,
|
|
193
|
+
headers=headers, method=method)
|
|
194
|
+
status = 0
|
|
195
|
+
try:
|
|
196
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as resp:
|
|
197
|
+
status = resp.status
|
|
198
|
+
raw = resp.read()
|
|
199
|
+
except urllib.error.HTTPError as e:
|
|
200
|
+
status = e.code
|
|
201
|
+
raw = e.read()
|
|
202
|
+
except urllib.error.URLError as e:
|
|
203
|
+
raise ApiError(f'无法连接 Cdifit API: {e.reason}') from e
|
|
204
|
+
except OSError as e:
|
|
205
|
+
raise ApiError(f'无法连接 Cdifit API: {e}') from e
|
|
206
|
+
|
|
207
|
+
try:
|
|
208
|
+
payload = json.loads(raw.decode('utf-8')) if raw else {}
|
|
209
|
+
except (ValueError, UnicodeDecodeError):
|
|
210
|
+
text = raw.decode('utf-8', 'replace')[:300]
|
|
211
|
+
raise ApiError(
|
|
212
|
+
f'Cdifit API 返回非 JSON (HTTP {status}): {text}',
|
|
213
|
+
status=status) from None
|
|
214
|
+
|
|
215
|
+
if not isinstance(payload, dict):
|
|
216
|
+
return payload
|
|
217
|
+
code = payload.get('code', 0)
|
|
218
|
+
if code == 203:
|
|
219
|
+
raise TwoFactorRequired(str(payload.get('data') or ''))
|
|
220
|
+
if code not in (0, None):
|
|
221
|
+
# Cdifit 对无效 Token 返回 HTTP 200 + code=401/403,
|
|
222
|
+
# 这里归一为 status, 让 _request 的刷新逻辑生效。
|
|
223
|
+
raise ApiError(str(payload.get('msg') or 'Cdifit API 请求失败'),
|
|
224
|
+
status=int(code) if code in (401, 403) else status,
|
|
225
|
+
code=int(code or 0),
|
|
226
|
+
data=payload.get('data'))
|
|
227
|
+
return payload.get('data', payload)
|
|
228
|
+
|
|
229
|
+
def _token(self) -> Optional[str]:
|
|
230
|
+
return self.auth.access_token if self.auth else None
|
|
231
|
+
|
|
232
|
+
def _refresh_if_needed(self) -> None:
|
|
233
|
+
if not self.auth:
|
|
234
|
+
return
|
|
235
|
+
if self.auth.access_expires and _expiring(self.auth.access_expires):
|
|
236
|
+
self.refresh()
|
|
237
|
+
|
|
238
|
+
def ensure_token(self) -> None:
|
|
239
|
+
"""确保 access token 存在且未过期 (必要时刷新)。"""
|
|
240
|
+
if not self.auth or not self.auth.access_token:
|
|
241
|
+
raise ApiError('未登录: 请先运行 `pic login`', status=401)
|
|
242
|
+
self._refresh_if_needed()
|
|
243
|
+
|
|
244
|
+
def _request(self, method: str, path: str,
|
|
245
|
+
body: Optional[Dict[str, Any]] = None,
|
|
246
|
+
auth: bool = True, retry: bool = True) -> Any:
|
|
247
|
+
if auth:
|
|
248
|
+
if not self.auth or not self.auth.access_token:
|
|
249
|
+
raise ApiError('未登录: 请先运行 `pic login`', status=401)
|
|
250
|
+
self._refresh_if_needed()
|
|
251
|
+
try:
|
|
252
|
+
return self._send(method, path, body, self._token() if auth else None)
|
|
253
|
+
except ApiError as e:
|
|
254
|
+
if auth and e.status in (401, 403) and retry and self.auth \
|
|
255
|
+
and self.auth.refresh_token:
|
|
256
|
+
self.refresh()
|
|
257
|
+
return self._send(method, path, body, self._token())
|
|
258
|
+
raise
|
|
259
|
+
|
|
260
|
+
# ---------------- 会话 ----------------
|
|
261
|
+
|
|
262
|
+
def login(self, email: str, password: str,
|
|
263
|
+
captcha: Optional[str] = None,
|
|
264
|
+
ticket: Optional[str] = None) -> AuthState:
|
|
265
|
+
body: Dict[str, Any] = {'email': email, 'password': password}
|
|
266
|
+
if captcha:
|
|
267
|
+
body['captcha'] = captcha
|
|
268
|
+
if ticket:
|
|
269
|
+
body['ticket'] = ticket
|
|
270
|
+
payload = self._send('POST', API_PREFIX + '/session/token', body)
|
|
271
|
+
data = payload if isinstance(payload, dict) else {}
|
|
272
|
+
token = data.get('token') or {}
|
|
273
|
+
user = data.get('user') or {}
|
|
274
|
+
if not token.get('access_token'):
|
|
275
|
+
raise ApiError('登录响应缺少 access_token', data=data)
|
|
276
|
+
self.auth = AuthState(
|
|
277
|
+
api_base=self.api_base,
|
|
278
|
+
access_token=str(token.get('access_token')),
|
|
279
|
+
refresh_token=str(token.get('refresh_token') or ''),
|
|
280
|
+
access_expires=token.get('access_expires'),
|
|
281
|
+
refresh_expires=token.get('refresh_expires'),
|
|
282
|
+
user=dict(user),
|
|
283
|
+
)
|
|
284
|
+
if self.store:
|
|
285
|
+
self.store.save(self.auth)
|
|
286
|
+
return self.auth
|
|
287
|
+
|
|
288
|
+
def finish_2fa(self, session: str, code: str) -> AuthState:
|
|
289
|
+
payload = self._send('POST', API_PREFIX + '/session/token/2fa',
|
|
290
|
+
{'session': session, 'code': code})
|
|
291
|
+
data = payload if isinstance(payload, dict) else {}
|
|
292
|
+
token = data.get('token') or {}
|
|
293
|
+
user = data.get('user') or {}
|
|
294
|
+
if not token.get('access_token'):
|
|
295
|
+
raise ApiError('2FA 响应缺少 access_token', data=data)
|
|
296
|
+
self.auth = AuthState(
|
|
297
|
+
api_base=self.api_base,
|
|
298
|
+
access_token=str(token.get('access_token')),
|
|
299
|
+
refresh_token=str(token.get('refresh_token') or ''),
|
|
300
|
+
access_expires=token.get('access_expires'),
|
|
301
|
+
refresh_expires=token.get('refresh_expires'),
|
|
302
|
+
user=dict(user) or (self.auth.user if self.auth else {}),
|
|
303
|
+
)
|
|
304
|
+
if self.store:
|
|
305
|
+
self.store.save(self.auth)
|
|
306
|
+
return self.auth
|
|
307
|
+
|
|
308
|
+
def refresh(self) -> AuthState:
|
|
309
|
+
if not self.auth or not self.auth.refresh_token:
|
|
310
|
+
raise ApiError('没有可用的 refresh_token, 请重新登录', status=401)
|
|
311
|
+
payload = self._send(
|
|
312
|
+
'PUT', API_PREFIX + '/session/token/refresh',
|
|
313
|
+
{'refresh_token': self.auth.refresh_token},
|
|
314
|
+
token=self.auth.refresh_token)
|
|
315
|
+
data = payload if isinstance(payload, dict) else {}
|
|
316
|
+
if not data.get('access_token'):
|
|
317
|
+
raise ApiError('刷新令牌响应缺少 access_token', data=data)
|
|
318
|
+
self.auth.access_token = str(data['access_token'])
|
|
319
|
+
if data.get('refresh_token'):
|
|
320
|
+
self.auth.refresh_token = str(data['refresh_token'])
|
|
321
|
+
self.auth.access_expires = data.get('access_expires') \
|
|
322
|
+
or self.auth.access_expires
|
|
323
|
+
self.auth.refresh_expires = data.get('refresh_expires') \
|
|
324
|
+
or self.auth.refresh_expires
|
|
325
|
+
if self.store:
|
|
326
|
+
self.store.save(self.auth)
|
|
327
|
+
return self.auth
|
|
328
|
+
|
|
329
|
+
def logout(self) -> None:
|
|
330
|
+
if self.auth and self.auth.access_token:
|
|
331
|
+
with contextlib.suppress(ApiError):
|
|
332
|
+
self._request('DELETE', API_PREFIX + '/session/token')
|
|
333
|
+
self.auth = None
|
|
334
|
+
if self.store:
|
|
335
|
+
self.store.clear()
|
|
336
|
+
|
|
337
|
+
def userinfo(self) -> Dict[str, Any]:
|
|
338
|
+
payload = self._request('GET',
|
|
339
|
+
API_PREFIX + '/session/oauth/userinfo')
|
|
340
|
+
if isinstance(payload, dict) and payload.get('sub'):
|
|
341
|
+
if self.auth:
|
|
342
|
+
self.auth.user.update(payload)
|
|
343
|
+
if self.store:
|
|
344
|
+
self.store.save(self.auth)
|
|
345
|
+
return payload
|
|
346
|
+
return self.auth.user if self.auth else {}
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _version() -> str:
|
|
350
|
+
try:
|
|
351
|
+
from . import __version__
|
|
352
|
+
return __version__
|
|
353
|
+
except Exception: # pragma: no cover
|
|
354
|
+
return '0'
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def load_auth(api_base: Optional[str] = None) -> Optional[AuthState]:
|
|
358
|
+
state = AuthStore().load()
|
|
359
|
+
if state is None:
|
|
360
|
+
return None
|
|
361
|
+
if api_base and state.api_base.rstrip('/') != api_base.rstrip('/'):
|
|
362
|
+
return None
|
|
363
|
+
return state
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def client_from_store(api_base: Optional[str] = None,
|
|
367
|
+
store: Optional[AuthStore] = None) -> Optional[CdifitClient]:
|
|
368
|
+
store = store or AuthStore()
|
|
369
|
+
state = store.load()
|
|
370
|
+
if state is None:
|
|
371
|
+
return None
|
|
372
|
+
if api_base and state.api_base.rstrip('/') != api_base.rstrip('/'):
|
|
373
|
+
return None
|
|
374
|
+
return CdifitClient(api_base or state.api_base, auth=state, store=store)
|