ustc-sdk 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.
- ustc_sdk/__init__.py +38 -0
- ustc_sdk/auth.py +208 -0
- ustc_sdk/eams/__init__.py +40 -0
- ustc_sdk/eams/_http.py +70 -0
- ustc_sdk/eams/adjustment.py +161 -0
- ustc_sdk/eams/client.py +229 -0
- ustc_sdk/eams/grades.py +69 -0
- ustc_sdk/eams/models.py +411 -0
- ustc_sdk/eams/selection.py +150 -0
- ustc_sdk/errors.py +25 -0
- ustc_sdk/py.typed +0 -0
- ustc_sdk/spaces.py +1054 -0
- ustc_sdk/venue_booking/__init__.py +63 -0
- ustc_sdk/venue_booking/auth.py +116 -0
- ustc_sdk/venue_booking/booking.py +66 -0
- ustc_sdk/venue_booking/client.py +156 -0
- ustc_sdk/venue_booking/models.py +55 -0
- ustc_sdk/venue_booking/personal.py +146 -0
- ustc_sdk/venue_booking/query.py +58 -0
- ustc_sdk/venue_booking/sign.py +46 -0
- ustc_sdk/young.py +480 -0
- ustc_sdk-0.1.0.dist-info/METADATA +70 -0
- ustc_sdk-0.1.0.dist-info/RECORD +26 -0
- ustc_sdk-0.1.0.dist-info/WHEEL +4 -0
- ustc_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
- ustc_sdk-0.1.0.dist-info/licenses/NOTICE +11 -0
ustc_sdk/__init__.py
ADDED
|
@@ -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"
|
ustc_sdk/auth.py
ADDED
|
@@ -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
|
+
]
|
ustc_sdk/eams/_http.py
ADDED
|
@@ -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))
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Course adjustment (调课) of the USTC educational system.
|
|
2
|
+
|
|
3
|
+
Provenance: the endpoints and payloads are ported from ``pyustc`` v1.2.1
|
|
4
|
+
(MIT, Copyright (c) 2026 XeF2).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from ..errors import ProtocolError, ServiceError, SubmissionUnknown
|
|
15
|
+
from ._http import get_json, post_json
|
|
16
|
+
from .models import AddDropResponse, Lesson
|
|
17
|
+
|
|
18
|
+
__all__ = ["CourseAdjustmentSystem"]
|
|
19
|
+
|
|
20
|
+
_POLL_INTERVAL = 1.0
|
|
21
|
+
_POLL_ATTEMPTS = 30
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CourseAdjustmentSystem:
|
|
25
|
+
"""Course adjustment inside one selection turn."""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
turn_id: int,
|
|
30
|
+
semester_id: int,
|
|
31
|
+
student_id: int,
|
|
32
|
+
client: httpx.AsyncClient,
|
|
33
|
+
) -> None:
|
|
34
|
+
self._turn_id = turn_id
|
|
35
|
+
self._semester_id = semester_id
|
|
36
|
+
self._student_id = student_id
|
|
37
|
+
self._client = client
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def turn_id(self) -> int:
|
|
41
|
+
"""Id of the selection turn."""
|
|
42
|
+
return self._turn_id
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def semester_id(self) -> int:
|
|
46
|
+
"""Id of the semester the adjustment applies to."""
|
|
47
|
+
return self._semester_id
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def student_id(self) -> int:
|
|
51
|
+
"""Id of the student."""
|
|
52
|
+
return self._student_id
|
|
53
|
+
|
|
54
|
+
async def add(self, lesson: Lesson, reason: str, confirm_retake: bool = False) -> AddDropResponse:
|
|
55
|
+
"""Apply for a retake of ``lesson``.
|
|
56
|
+
|
|
57
|
+
:param lesson: The lesson to retake.
|
|
58
|
+
:param reason: The reason shown to the reviewer.
|
|
59
|
+
:param confirm_retake: Whether to confirm a detected retake.
|
|
60
|
+
"""
|
|
61
|
+
data: dict[str, Any] = {
|
|
62
|
+
"newLessonAssoc": lesson.id,
|
|
63
|
+
"studentAssoc": self._student_id,
|
|
64
|
+
"semesterAssoc": self._semester_id,
|
|
65
|
+
"bizTypeAssoc": 2,
|
|
66
|
+
"applyTypeAssoc": 1,
|
|
67
|
+
"applyReason": reason,
|
|
68
|
+
"retake": False,
|
|
69
|
+
"scheduleGroupAssoc": None,
|
|
70
|
+
}
|
|
71
|
+
precheck = await post_json(
|
|
72
|
+
self._client, "/for-std/course-adjustment-apply/preCheck", json=[data]
|
|
73
|
+
)
|
|
74
|
+
error = _first_error(precheck)
|
|
75
|
+
if error:
|
|
76
|
+
raise ServiceError(error)
|
|
77
|
+
retake = await get_json(
|
|
78
|
+
self._client,
|
|
79
|
+
"/for-std/course-adjustment-apply/getRetake",
|
|
80
|
+
params={
|
|
81
|
+
"lessonIds": lesson.id,
|
|
82
|
+
"studentId": self._student_id,
|
|
83
|
+
"bizTypeId": 2,
|
|
84
|
+
},
|
|
85
|
+
)
|
|
86
|
+
if isinstance(retake, list) and retake and not confirm_retake:
|
|
87
|
+
raise ServiceError("A retake was detected; confirm it with confirm_retake=True")
|
|
88
|
+
result = await post_json(
|
|
89
|
+
self._client, "/for-std/course-adjustment-apply/selection-apply/save", json=data
|
|
90
|
+
)
|
|
91
|
+
error = _first_error(result)
|
|
92
|
+
if error:
|
|
93
|
+
raise ServiceError(error)
|
|
94
|
+
return AddDropResponse(type="add", success=True)
|
|
95
|
+
|
|
96
|
+
async def change_class(
|
|
97
|
+
self,
|
|
98
|
+
old_lesson: Lesson,
|
|
99
|
+
new_lesson: Lesson,
|
|
100
|
+
reason: str,
|
|
101
|
+
) -> AddDropResponse:
|
|
102
|
+
"""Apply for a change of the teaching group of a course."""
|
|
103
|
+
data: dict[str, Any] = {
|
|
104
|
+
"studentAssoc": self._student_id,
|
|
105
|
+
"semesterAssoc": self._semester_id,
|
|
106
|
+
"bizTypeAssoc": 2,
|
|
107
|
+
"applyTypeAssoc": 5,
|
|
108
|
+
}
|
|
109
|
+
result = await post_json(
|
|
110
|
+
self._client,
|
|
111
|
+
"/for-std/course-adjustment-apply/change-class-request",
|
|
112
|
+
json={
|
|
113
|
+
**data,
|
|
114
|
+
"courseSelectTurnAssoc": self._turn_id,
|
|
115
|
+
"saveCmds": [
|
|
116
|
+
{
|
|
117
|
+
"oldLessonAssoc": old_lesson.id,
|
|
118
|
+
"newLessonAssoc": new_lesson.id,
|
|
119
|
+
"applyReason": reason,
|
|
120
|
+
**data,
|
|
121
|
+
"scheduleGroupAssoc": None,
|
|
122
|
+
}
|
|
123
|
+
],
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
if not isinstance(result, dict):
|
|
127
|
+
raise ProtocolError("The educational system returned a malformed adjustment response")
|
|
128
|
+
error = _first_error(result)
|
|
129
|
+
if error:
|
|
130
|
+
return AddDropResponse(type="change-class", success=False, error=error)
|
|
131
|
+
if result.get("saveApply"):
|
|
132
|
+
return AddDropResponse(type="change-class", success=True)
|
|
133
|
+
request_id = result.get("requestId")
|
|
134
|
+
if not request_id:
|
|
135
|
+
raise ProtocolError("The educational system did not return a request id")
|
|
136
|
+
for _ in range(_POLL_ATTEMPTS):
|
|
137
|
+
response = await post_json(
|
|
138
|
+
self._client,
|
|
139
|
+
"/for-std/course-adjustment-apply/add-drop-response",
|
|
140
|
+
data={"studentId": self._student_id, "requestId": request_id},
|
|
141
|
+
)
|
|
142
|
+
if response:
|
|
143
|
+
return AddDropResponse.from_record("change-class", response)
|
|
144
|
+
await asyncio.sleep(_POLL_INTERVAL)
|
|
145
|
+
raise SubmissionUnknown(
|
|
146
|
+
f"The change class request {request_id!r} has an unknown outcome; query the adjustment again"
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _first_error(payload: Any) -> str | None:
|
|
151
|
+
"""Extract the first error message of an adjustment payload."""
|
|
152
|
+
if not isinstance(payload, dict):
|
|
153
|
+
return None
|
|
154
|
+
errors = payload.get("errors")
|
|
155
|
+
if not isinstance(errors, dict):
|
|
156
|
+
return None
|
|
157
|
+
all_errors = errors.get("allErrors")
|
|
158
|
+
if isinstance(all_errors, list) and all_errors:
|
|
159
|
+
first = all_errors[0]
|
|
160
|
+
return str(first.get("message") if isinstance(first, dict) else first)
|
|
161
|
+
return None
|