ustc-sdk 0.1.0__tar.gz
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.
- ustc_sdk-0.1.0/LICENSE +21 -0
- ustc_sdk-0.1.0/NOTICE +11 -0
- ustc_sdk-0.1.0/PKG-INFO +70 -0
- ustc_sdk-0.1.0/README.md +54 -0
- ustc_sdk-0.1.0/pyproject.toml +25 -0
- ustc_sdk-0.1.0/pyproject.toml.orig +17 -0
- ustc_sdk-0.1.0/src/ustc_sdk/__init__.py +38 -0
- ustc_sdk-0.1.0/src/ustc_sdk/auth.py +208 -0
- ustc_sdk-0.1.0/src/ustc_sdk/eams/__init__.py +40 -0
- ustc_sdk-0.1.0/src/ustc_sdk/eams/_http.py +70 -0
- ustc_sdk-0.1.0/src/ustc_sdk/eams/adjustment.py +161 -0
- ustc_sdk-0.1.0/src/ustc_sdk/eams/client.py +229 -0
- ustc_sdk-0.1.0/src/ustc_sdk/eams/grades.py +69 -0
- ustc_sdk-0.1.0/src/ustc_sdk/eams/models.py +411 -0
- ustc_sdk-0.1.0/src/ustc_sdk/eams/selection.py +150 -0
- ustc_sdk-0.1.0/src/ustc_sdk/errors.py +25 -0
- ustc_sdk-0.1.0/src/ustc_sdk/py.typed +0 -0
- ustc_sdk-0.1.0/src/ustc_sdk/spaces.py +1054 -0
- ustc_sdk-0.1.0/src/ustc_sdk/venue_booking/__init__.py +63 -0
- ustc_sdk-0.1.0/src/ustc_sdk/venue_booking/auth.py +116 -0
- ustc_sdk-0.1.0/src/ustc_sdk/venue_booking/booking.py +66 -0
- ustc_sdk-0.1.0/src/ustc_sdk/venue_booking/client.py +156 -0
- ustc_sdk-0.1.0/src/ustc_sdk/venue_booking/models.py +55 -0
- ustc_sdk-0.1.0/src/ustc_sdk/venue_booking/personal.py +146 -0
- ustc_sdk-0.1.0/src/ustc_sdk/venue_booking/query.py +58 -0
- ustc_sdk-0.1.0/src/ustc_sdk/venue_booking/sign.py +46 -0
- ustc_sdk-0.1.0/src/ustc_sdk/young.py +480 -0
ustc_sdk-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 XeF2
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
ustc_sdk-0.1.0/NOTICE
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
ustc-sdk
|
|
2
|
+
|
|
3
|
+
CAS, EAMS, second-class and sports venue protocols and implementation derived from:
|
|
4
|
+
pyustc 1.2.1 (tag v1.2.1), https://github.com/USTC-XeF2/pyustc/tree/v1.2.1
|
|
5
|
+
Copyright (c) 2026 XeF2. MIT license retained in LICENSE.
|
|
6
|
+
Modified for explicit per-user async clients, Pydantic data models and transport seams.
|
|
7
|
+
|
|
8
|
+
Learning-space protocol and booking rules derived from xtcli / wlib-booking:
|
|
9
|
+
https://git.ustc.edu.cn/yu-z.h/xtcli/-/tree/e8c0116f7b95970300e6db1af5b03547166184d5
|
|
10
|
+
README identifies MIT licensing; upstream repository copyright/attribution retained here.
|
|
11
|
+
No CLI/TUI, local credentials or personal data are included.
|
ustc_sdk-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ustc-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Asynchronous user-scoped clients for USTC campus systems
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
License-File: NOTICE
|
|
8
|
+
Requires-Dist: httpx>=0.28.1,<0.29
|
|
9
|
+
Requires-Dist: pydantic>=2.11,<3
|
|
10
|
+
Requires-Dist: pycryptodome>=3.23,<4
|
|
11
|
+
Requires-Dist: ua-generator>=2.1.4,<3
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Project-URL: Repository, https://github.com/RaymondzyLei/tools-at-USTC
|
|
14
|
+
Project-URL: Issues, https://github.com/RaymondzyLei/tools-at-USTC/issues
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# ustc-sdk
|
|
18
|
+
|
|
19
|
+
中国科大校园系统的异步 Python SDK,要求 Python 3.11+。
|
|
20
|
+
|
|
21
|
+
提供显式账号、独立会话的统一认证、第二课堂、教务、学习空间和体育场馆客户端。
|
|
22
|
+
公开数据模型使用 Pydantic,支持 JSON 序列化与 JSON Schema。
|
|
23
|
+
|
|
24
|
+
## 安装(发布后)
|
|
25
|
+
|
|
26
|
+
```text
|
|
27
|
+
uv add ustc-sdk
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## 读取第二课堂活动
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import asyncio
|
|
34
|
+
import os
|
|
35
|
+
|
|
36
|
+
from ustc_sdk import CASClient, YoungClient
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def main():
|
|
40
|
+
async with CASClient(os.environ["USTC_USERNAME"], os.environ["USTC_PASSWORD"]) as cas:
|
|
41
|
+
async with YoungClient(cas) as young:
|
|
42
|
+
for activity in await young.list_activities(limit=5):
|
|
43
|
+
print(activity.model_dump_json())
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
asyncio.run(main())
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
账号配置由应用负责;客户端不会自动查找其他工具的配置或共享全局账号状态。
|
|
50
|
+
CAS Cookie 保留原始域名、路径和 Secure 属性;各校园系统分别持有自己的应用会话。
|
|
51
|
+
|
|
52
|
+
## 模块
|
|
53
|
+
|
|
54
|
+
- `ustc_sdk.auth`:CAS 认证与服务票据。
|
|
55
|
+
- `ustc_sdk.young`:第二课堂列表、详情、已参与活动、报名与取消。
|
|
56
|
+
- `ustc_sdk.eams`:课表、成绩、选退课与课程调整。
|
|
57
|
+
- `ustc_sdk.spaces`:学习空间房间、成员、预约查询及写操作。
|
|
58
|
+
- `ustc_sdk.venue_booking`:体育场馆查询与已有订单操作;创建预约所需的小程序设备验证字段未提供。
|
|
59
|
+
|
|
60
|
+
业务流程、存储和定时扫描由独立的 `ustc-tools` 包提供。
|
|
61
|
+
学习空间上游使用明文 HTTP;CAS 密码仅提交到 HTTPS 认证站点。
|
|
62
|
+
写操作出现 `SubmissionUnknown` 时需先查询服务器状态,不能直接重发。
|
|
63
|
+
|
|
64
|
+
## 来源与许可
|
|
65
|
+
|
|
66
|
+
MIT。认证、教务、二课与体育协议基于 [pyustc v1.2.1](https://github.com/USTC-XeF2/pyustc/tree/v1.2.1),
|
|
67
|
+
学习空间协议基于 [xtcli 固定快照](https://git.ustc.edu.cn/yu-z.h/xtcli/-/tree/e8c0116f7b95970300e6db1af5b03547166184d5)。
|
|
68
|
+
原始许可和来源说明随包附带。
|
|
69
|
+
|
|
70
|
+
[源码与完整文档](https://github.com/RaymondzyLei/tools-at-USTC)
|
ustc_sdk-0.1.0/README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# ustc-sdk
|
|
2
|
+
|
|
3
|
+
中国科大校园系统的异步 Python SDK,要求 Python 3.11+。
|
|
4
|
+
|
|
5
|
+
提供显式账号、独立会话的统一认证、第二课堂、教务、学习空间和体育场馆客户端。
|
|
6
|
+
公开数据模型使用 Pydantic,支持 JSON 序列化与 JSON Schema。
|
|
7
|
+
|
|
8
|
+
## 安装(发布后)
|
|
9
|
+
|
|
10
|
+
```text
|
|
11
|
+
uv add ustc-sdk
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## 读取第二课堂活动
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
import asyncio
|
|
18
|
+
import os
|
|
19
|
+
|
|
20
|
+
from ustc_sdk import CASClient, YoungClient
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def main():
|
|
24
|
+
async with CASClient(os.environ["USTC_USERNAME"], os.environ["USTC_PASSWORD"]) as cas:
|
|
25
|
+
async with YoungClient(cas) as young:
|
|
26
|
+
for activity in await young.list_activities(limit=5):
|
|
27
|
+
print(activity.model_dump_json())
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
asyncio.run(main())
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
账号配置由应用负责;客户端不会自动查找其他工具的配置或共享全局账号状态。
|
|
34
|
+
CAS Cookie 保留原始域名、路径和 Secure 属性;各校园系统分别持有自己的应用会话。
|
|
35
|
+
|
|
36
|
+
## 模块
|
|
37
|
+
|
|
38
|
+
- `ustc_sdk.auth`:CAS 认证与服务票据。
|
|
39
|
+
- `ustc_sdk.young`:第二课堂列表、详情、已参与活动、报名与取消。
|
|
40
|
+
- `ustc_sdk.eams`:课表、成绩、选退课与课程调整。
|
|
41
|
+
- `ustc_sdk.spaces`:学习空间房间、成员、预约查询及写操作。
|
|
42
|
+
- `ustc_sdk.venue_booking`:体育场馆查询与已有订单操作;创建预约所需的小程序设备验证字段未提供。
|
|
43
|
+
|
|
44
|
+
业务流程、存储和定时扫描由独立的 `ustc-tools` 包提供。
|
|
45
|
+
学习空间上游使用明文 HTTP;CAS 密码仅提交到 HTTPS 认证站点。
|
|
46
|
+
写操作出现 `SubmissionUnknown` 时需先查询服务器状态,不能直接重发。
|
|
47
|
+
|
|
48
|
+
## 来源与许可
|
|
49
|
+
|
|
50
|
+
MIT。认证、教务、二课与体育协议基于 [pyustc v1.2.1](https://github.com/USTC-XeF2/pyustc/tree/v1.2.1),
|
|
51
|
+
学习空间协议基于 [xtcli 固定快照](https://git.ustc.edu.cn/yu-z.h/xtcli/-/tree/e8c0116f7b95970300e6db1af5b03547166184d5)。
|
|
52
|
+
原始许可和来源说明随包附带。
|
|
53
|
+
|
|
54
|
+
[源码与完整文档](https://github.com/RaymondzyLei/tools-at-USTC)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ustc-sdk"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Asynchronous user-scoped clients for USTC campus systems"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = [
|
|
9
|
+
"LICENSE",
|
|
10
|
+
"NOTICE",
|
|
11
|
+
]
|
|
12
|
+
dependencies = [
|
|
13
|
+
"httpx>=0.28.1,<0.29",
|
|
14
|
+
"pydantic>=2.11,<3",
|
|
15
|
+
"pycryptodome>=3.23,<4",
|
|
16
|
+
"ua-generator>=2.1.4,<3",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Repository = "https://github.com/RaymondzyLei/tools-at-USTC"
|
|
21
|
+
Issues = "https://github.com/RaymondzyLei/tools-at-USTC/issues"
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["uv_build>=0.13.9,<0.14"]
|
|
25
|
+
build-backend = "uv_build"
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ustc-sdk"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Asynchronous user-scoped clients for USTC campus systems"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
9
|
+
dependencies = ["httpx>=0.28.1,<0.29", "pydantic>=2.11,<3", "pycryptodome>=3.23,<4", "ua-generator>=2.1.4,<3"]
|
|
10
|
+
|
|
11
|
+
[project.urls]
|
|
12
|
+
Repository = "https://github.com/RaymondzyLei/tools-at-USTC"
|
|
13
|
+
Issues = "https://github.com/RaymondzyLei/tools-at-USTC/issues"
|
|
14
|
+
|
|
15
|
+
[build-system]
|
|
16
|
+
requires = ["uv_build>=0.13.9,<0.14"]
|
|
17
|
+
build-backend = "uv_build"
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Asynchronous, user scoped clients for the USTC campus systems.
|
|
2
|
+
|
|
3
|
+
Every client of this package owns its HTTPX connection, takes its credentials
|
|
4
|
+
explicitly and keeps its state in its own instance: there is no global session,
|
|
5
|
+
no environment variable lookup and no shared model cache.
|
|
6
|
+
|
|
7
|
+
The campus protocols are ported from ``pyustc`` v1.2.1 (MIT,
|
|
8
|
+
Copyright (c) 2026 XeF2); see the module docstrings for the details.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from .auth import CAS_BASE_URL, CASClient
|
|
12
|
+
from .errors import (
|
|
13
|
+
AuthenticationError,
|
|
14
|
+
ProtocolError,
|
|
15
|
+
ServiceError,
|
|
16
|
+
SubmissionUnknown,
|
|
17
|
+
USTCError,
|
|
18
|
+
)
|
|
19
|
+
from .spaces import RoomKind, SpaceClient
|
|
20
|
+
from .young import Activity, MutationResult, SignInfo, YoungClient
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"Activity",
|
|
24
|
+
"AuthenticationError",
|
|
25
|
+
"CAS_BASE_URL",
|
|
26
|
+
"CASClient",
|
|
27
|
+
"MutationResult",
|
|
28
|
+
"ProtocolError",
|
|
29
|
+
"RoomKind",
|
|
30
|
+
"ServiceError",
|
|
31
|
+
"SignInfo",
|
|
32
|
+
"SpaceClient",
|
|
33
|
+
"SubmissionUnknown",
|
|
34
|
+
"USTCError",
|
|
35
|
+
"YoungClient",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Central Authentication Service (CAS) client for USTC campus systems.
|
|
2
|
+
|
|
3
|
+
The client owns its HTTPX connection and performs the password login when it is
|
|
4
|
+
entered as an asynchronous context manager. Credentials are explicit: there is
|
|
5
|
+
no environment variable lookup and no global session state.
|
|
6
|
+
|
|
7
|
+
Provenance: the CAS login handshake (RSA-free AES/ECB password encryption with
|
|
8
|
+
the ``login-croypto`` key and the ``login-page-flowkey`` execution token) is
|
|
9
|
+
ported from ``pyustc`` v1.2.1 (MIT, Copyright (c) 2026 XeF2).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import base64
|
|
15
|
+
import copy
|
|
16
|
+
import re
|
|
17
|
+
from types import TracebackType
|
|
18
|
+
from urllib.parse import parse_qs, urlparse
|
|
19
|
+
|
|
20
|
+
import httpx
|
|
21
|
+
|
|
22
|
+
from .errors import AuthenticationError, ProtocolError, ServiceError, USTCError
|
|
23
|
+
|
|
24
|
+
__all__ = ["CAS_BASE_URL", "CASClient", "DEFAULT_TIMEOUT"]
|
|
25
|
+
|
|
26
|
+
CAS_BASE_URL = "https://id.ustc.edu.cn"
|
|
27
|
+
"""Root URL of the USTC identity provider."""
|
|
28
|
+
|
|
29
|
+
DEFAULT_TIMEOUT = httpx.Timeout(30.0, connect=10.0)
|
|
30
|
+
"""Bounded timeout used by every client of this SDK."""
|
|
31
|
+
|
|
32
|
+
_LOGIN_CRYPTO_RE = re.compile(r'<p id="login-croypto">([^<]+)</p>')
|
|
33
|
+
_LOGIN_FLOW_KEY_RE = re.compile(r'<p id="login-page-flowkey">([^<]+)</p>')
|
|
34
|
+
_LOGIN_ERROR_RE = re.compile(
|
|
35
|
+
r'<div\s+class="alert alert-danger"\s+id="login-error-msg">\s*<span>([^<]+)</span>\s*</div>'
|
|
36
|
+
)
|
|
37
|
+
_REDIRECT_CODES = frozenset({301, 302, 303, 307, 308})
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _aes_ecb_encrypt(data: str, key: bytes) -> str:
|
|
41
|
+
"""Encrypt ``data`` with AES/ECB and PKCS#7 padding, base64 encoded.
|
|
42
|
+
|
|
43
|
+
The CAS login form expects this exact encoding of the password.
|
|
44
|
+
"""
|
|
45
|
+
try:
|
|
46
|
+
from Crypto.Cipher import AES
|
|
47
|
+
from Crypto.Util.Padding import pad
|
|
48
|
+
except ImportError as exc: # pragma: no cover - dependency is declared
|
|
49
|
+
raise USTCError(
|
|
50
|
+
"pycryptodome is required for CAS password encryption"
|
|
51
|
+
) from exc
|
|
52
|
+
cipher = AES.new(key, AES.MODE_ECB)
|
|
53
|
+
return base64.b64encode(cipher.encrypt(pad(data.encode(), AES.block_size))).decode()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class CASClient:
|
|
57
|
+
"""Log in to USTC campus systems through the CAS identity provider.
|
|
58
|
+
|
|
59
|
+
``username`` and ``password`` are always explicit; nothing is read from the
|
|
60
|
+
environment. The client is an asynchronous context manager that logs in when
|
|
61
|
+
entered and closes its HTTPX connection when left.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def __init__(
|
|
65
|
+
self,
|
|
66
|
+
username: str,
|
|
67
|
+
password: str,
|
|
68
|
+
*,
|
|
69
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
70
|
+
) -> None:
|
|
71
|
+
if not username or not password:
|
|
72
|
+
raise ValueError("username and password are required")
|
|
73
|
+
self._username = username
|
|
74
|
+
self._password = password
|
|
75
|
+
self._transport = transport
|
|
76
|
+
self._client: httpx.AsyncClient | None = None
|
|
77
|
+
|
|
78
|
+
# -- context management -------------------------------------------------
|
|
79
|
+
|
|
80
|
+
async def __aenter__(self) -> CASClient:
|
|
81
|
+
if self._client is not None:
|
|
82
|
+
raise USTCError("CAS client is already open")
|
|
83
|
+
client = httpx.AsyncClient(
|
|
84
|
+
base_url=CAS_BASE_URL,
|
|
85
|
+
transport=self._transport,
|
|
86
|
+
timeout=DEFAULT_TIMEOUT,
|
|
87
|
+
follow_redirects=False,
|
|
88
|
+
)
|
|
89
|
+
try:
|
|
90
|
+
await self._login(client)
|
|
91
|
+
except BaseException:
|
|
92
|
+
await client.aclose()
|
|
93
|
+
raise
|
|
94
|
+
self._client = client
|
|
95
|
+
return self
|
|
96
|
+
|
|
97
|
+
async def __aexit__(
|
|
98
|
+
self,
|
|
99
|
+
exc_type: type[BaseException] | None = None,
|
|
100
|
+
exc_value: BaseException | None = None,
|
|
101
|
+
traceback: TracebackType | None = None,
|
|
102
|
+
) -> None:
|
|
103
|
+
client, self._client = self._client, None
|
|
104
|
+
if client is not None:
|
|
105
|
+
await client.aclose()
|
|
106
|
+
|
|
107
|
+
# -- properties ---------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def is_open(self) -> bool:
|
|
111
|
+
"""Whether the client completed its login and is usable."""
|
|
112
|
+
return self._client is not None
|
|
113
|
+
|
|
114
|
+
# -- public API ---------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
async def get_ticket(self, service: str) -> str:
|
|
117
|
+
"""Return a one-shot CAS service ticket for ``service``.
|
|
118
|
+
|
|
119
|
+
:param service: Absolute URL of the service that will consume the ticket.
|
|
120
|
+
"""
|
|
121
|
+
client = self._require_client()
|
|
122
|
+
response = await client.get("/cas/login", params={"service": service})
|
|
123
|
+
location = response.headers.get("location")
|
|
124
|
+
if location:
|
|
125
|
+
ticket = parse_qs(urlparse(location).query).get("ticket")
|
|
126
|
+
if ticket:
|
|
127
|
+
return ticket[0]
|
|
128
|
+
raise AuthenticationError("Failed to obtain a CAS ticket")
|
|
129
|
+
|
|
130
|
+
def create_service_client(
|
|
131
|
+
self,
|
|
132
|
+
*,
|
|
133
|
+
base_url: str,
|
|
134
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
135
|
+
follow_redirects: bool = True,
|
|
136
|
+
) -> httpx.AsyncClient:
|
|
137
|
+
"""Create a new application client that carries a copy of the CAS cookies.
|
|
138
|
+
|
|
139
|
+
The returned client is owned by the caller: close it with ``aclose()`` or
|
|
140
|
+
use it as an asynchronous context manager. The CAS client keeps its own
|
|
141
|
+
cookie jar; later CAS mutations never leak into the copy.
|
|
142
|
+
|
|
143
|
+
The cookies are copied verbatim - domain, path, secure flag and expiry
|
|
144
|
+
are preserved. A host-only CAS cookie therefore stays scoped to the CAS
|
|
145
|
+
host: it authenticates the CAS redirect of the application and is never
|
|
146
|
+
sent to the application host itself.
|
|
147
|
+
"""
|
|
148
|
+
client = self._require_client()
|
|
149
|
+
service_client = httpx.AsyncClient(
|
|
150
|
+
base_url=base_url,
|
|
151
|
+
transport=transport,
|
|
152
|
+
timeout=DEFAULT_TIMEOUT,
|
|
153
|
+
follow_redirects=follow_redirects,
|
|
154
|
+
)
|
|
155
|
+
for cookie in client.cookies.jar:
|
|
156
|
+
service_client.cookies.jar.set_cookie(copy.copy(cookie))
|
|
157
|
+
return service_client
|
|
158
|
+
|
|
159
|
+
async def logout(self) -> None:
|
|
160
|
+
"""Invalidate the CAS session on the server."""
|
|
161
|
+
client = self._require_client()
|
|
162
|
+
await client.get("/gate/logout")
|
|
163
|
+
|
|
164
|
+
# -- internals ----------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
def _require_client(self) -> httpx.AsyncClient:
|
|
167
|
+
if self._client is None:
|
|
168
|
+
raise USTCError(
|
|
169
|
+
"CAS client is not open; use `async with CASClient(...)` before calling it"
|
|
170
|
+
)
|
|
171
|
+
return self._client
|
|
172
|
+
|
|
173
|
+
async def _login(self, client: httpx.AsyncClient) -> None:
|
|
174
|
+
page = await client.get("/cas/login")
|
|
175
|
+
crypto = _LOGIN_CRYPTO_RE.search(page.text)
|
|
176
|
+
flow_key = _LOGIN_FLOW_KEY_RE.search(page.text)
|
|
177
|
+
if not (crypto and flow_key):
|
|
178
|
+
raise AuthenticationError("Failed to read the CAS login parameters")
|
|
179
|
+
|
|
180
|
+
crypto_value = crypto.group(1)
|
|
181
|
+
try:
|
|
182
|
+
key = base64.b64decode(crypto_value)
|
|
183
|
+
except Exception as exc:
|
|
184
|
+
raise ProtocolError("The CAS login parameters are malformed") from exc
|
|
185
|
+
if len(key) not in (16, 24, 32):
|
|
186
|
+
raise ProtocolError("The CAS login parameters are malformed")
|
|
187
|
+
|
|
188
|
+
data = {
|
|
189
|
+
"type": "UsernamePassword",
|
|
190
|
+
"_eventId": "submit",
|
|
191
|
+
"croypto": crypto_value,
|
|
192
|
+
"username": self._username,
|
|
193
|
+
"password": _aes_ecb_encrypt(self._password, key),
|
|
194
|
+
"captcha_payload": _aes_ecb_encrypt("{}", key),
|
|
195
|
+
"execution": flow_key.group(1),
|
|
196
|
+
}
|
|
197
|
+
response = await client.post("/cas/login", data=data)
|
|
198
|
+
if response.status_code >= 500:
|
|
199
|
+
raise ServiceError(f"CAS server returned HTTP {response.status_code}")
|
|
200
|
+
if response.status_code not in _REDIRECT_CODES:
|
|
201
|
+
message = _LOGIN_ERROR_RE.search(response.text)
|
|
202
|
+
raise AuthenticationError(
|
|
203
|
+
message.group(1).strip() if message else "CAS login failed"
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
def __repr__(self) -> str:
|
|
207
|
+
state = "open" if self.is_open else "closed"
|
|
208
|
+
return f"CASClient(username=<redacted>, password=<redacted>, {state})"
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Educational administration system (EAMS) client for USTC."""
|
|
2
|
+
|
|
3
|
+
from .adjustment import CourseAdjustmentSystem
|
|
4
|
+
from .client import EAMS_BASE_URL, EAMSClient
|
|
5
|
+
from .grades import GradeManager
|
|
6
|
+
from .models import (
|
|
7
|
+
AddDropResponse,
|
|
8
|
+
Course,
|
|
9
|
+
CourseRef,
|
|
10
|
+
CourseTable,
|
|
11
|
+
GradeSheet,
|
|
12
|
+
GradeSheetCourse,
|
|
13
|
+
Lesson,
|
|
14
|
+
Place,
|
|
15
|
+
Season,
|
|
16
|
+
Semester,
|
|
17
|
+
Teacher,
|
|
18
|
+
Turn,
|
|
19
|
+
)
|
|
20
|
+
from .selection import CourseSelectionSystem
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"AddDropResponse",
|
|
24
|
+
"Course",
|
|
25
|
+
"CourseAdjustmentSystem",
|
|
26
|
+
"CourseRef",
|
|
27
|
+
"CourseSelectionSystem",
|
|
28
|
+
"CourseTable",
|
|
29
|
+
"EAMS_BASE_URL",
|
|
30
|
+
"EAMSClient",
|
|
31
|
+
"GradeManager",
|
|
32
|
+
"GradeSheet",
|
|
33
|
+
"GradeSheetCourse",
|
|
34
|
+
"Lesson",
|
|
35
|
+
"Place",
|
|
36
|
+
"Season",
|
|
37
|
+
"Semester",
|
|
38
|
+
"Teacher",
|
|
39
|
+
"Turn",
|
|
40
|
+
]
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Shared HTTP helpers of the EAMS client.
|
|
2
|
+
|
|
3
|
+
Provenance: the endpoint paths and payloads are ported from ``pyustc`` v1.2.1
|
|
4
|
+
(MIT, Copyright (c) 2026 XeF2).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from ..errors import AuthenticationError, ProtocolError, ServiceError
|
|
14
|
+
|
|
15
|
+
__all__ = ["get_json", "post_json", "post_text"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _decode(response: httpx.Response) -> Any:
|
|
19
|
+
if response.status_code in (401, 403):
|
|
20
|
+
raise AuthenticationError(
|
|
21
|
+
f"The educational system rejected the session (HTTP {response.status_code})"
|
|
22
|
+
)
|
|
23
|
+
if response.status_code >= 500:
|
|
24
|
+
raise ServiceError(
|
|
25
|
+
f"The educational system returned HTTP {response.status_code}"
|
|
26
|
+
)
|
|
27
|
+
try:
|
|
28
|
+
return response.json()
|
|
29
|
+
except ValueError as exc:
|
|
30
|
+
raise ProtocolError("The educational system returned a non-JSON response") from exc
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def get_json(
|
|
34
|
+
client: httpx.AsyncClient,
|
|
35
|
+
url: str,
|
|
36
|
+
*,
|
|
37
|
+
params: dict[str, Any] | None = None,
|
|
38
|
+
) -> Any:
|
|
39
|
+
"""Perform a GET request and decode the JSON payload."""
|
|
40
|
+
return _decode(await client.get(url, params=params))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def post_text(
|
|
44
|
+
client: httpx.AsyncClient,
|
|
45
|
+
url: str,
|
|
46
|
+
*,
|
|
47
|
+
data: dict[str, Any] | None = None,
|
|
48
|
+
) -> str:
|
|
49
|
+
"""Perform a POST request and return the raw response body."""
|
|
50
|
+
response = await client.post(url, data=data)
|
|
51
|
+
if response.status_code in (401, 403):
|
|
52
|
+
raise AuthenticationError(
|
|
53
|
+
f"The educational system rejected the session (HTTP {response.status_code})"
|
|
54
|
+
)
|
|
55
|
+
if response.status_code >= 500:
|
|
56
|
+
raise ServiceError(
|
|
57
|
+
f"The educational system returned HTTP {response.status_code}"
|
|
58
|
+
)
|
|
59
|
+
return response.text
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
async def post_json(
|
|
63
|
+
client: httpx.AsyncClient,
|
|
64
|
+
url: str,
|
|
65
|
+
*,
|
|
66
|
+
data: dict[str, Any] | None = None,
|
|
67
|
+
json: dict[str, Any] | None = None,
|
|
68
|
+
) -> Any:
|
|
69
|
+
"""Perform a POST request and decode the JSON payload."""
|
|
70
|
+
return _decode(await client.post(url, data=data, json=json))
|