usos-api 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.
Potentially problematic release.
This version of usos-api might be problematic. Click here for more details.
- usos_api-0.1.0/PKG-INFO +16 -0
- usos_api-0.1.0/README.md +1 -0
- usos_api-0.1.0/pyproject.toml +31 -0
- usos_api-0.1.0/usos_api/__init__.py +5 -0
- usos_api-0.1.0/usos_api/auth.py +197 -0
- usos_api-0.1.0/usos_api/client.py +176 -0
- usos_api-0.1.0/usos_api/connection.py +137 -0
- usos_api-0.1.0/usos_api/exceptions.py +2 -0
- usos_api-0.1.0/usos_api/logger.py +20 -0
- usos_api-0.1.0/usos_api/models/__init__.py +53 -0
- usos_api-0.1.0/usos_api/models/consumer.py +17 -0
- usos_api-0.1.0/usos_api/models/course.py +77 -0
- usos_api-0.1.0/usos_api/models/grade.py +27 -0
- usos_api-0.1.0/usos_api/models/group.py +33 -0
- usos_api-0.1.0/usos_api/models/lang_dict.py +10 -0
- usos_api-0.1.0/usos_api/models/programme.py +34 -0
- usos_api-0.1.0/usos_api/models/term.py +14 -0
- usos_api-0.1.0/usos_api/models/user.py +159 -0
- usos_api-0.1.0/usos_api/services/__init__.py +5 -0
- usos_api-0.1.0/usos_api/services/api_server.py +40 -0
- usos_api-0.1.0/usos_api/services/groups.py +204 -0
- usos_api-0.1.0/usos_api/services/users.py +49 -0
- usos_api-0.1.0/usos_api/utils/__init__.py +0 -0
usos_api-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: usos-api
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Asynchronous USOS API for Python
|
|
5
|
+
Author: Antoni-Czaplicki
|
|
6
|
+
Author-email: 56671347+Antoni-Czaplicki@users.noreply.github.com
|
|
7
|
+
Requires-Python: >=3.12,<4.0
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Requires-Dist: aiohttp (>=3.9.5,<4.0.0)
|
|
11
|
+
Requires-Dist: oauthlib (>=3.2.2,<4.0.0)
|
|
12
|
+
Requires-Dist: pydantic (>=2.8.2,<3.0.0)
|
|
13
|
+
Requires-Dist: python-dotenv (>=1.0.1,<2.0.0)
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# USOS API for python, in development
|
usos_api-0.1.0/README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# USOS API for python, in development
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "usos-api"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Asynchronous USOS API for Python"
|
|
5
|
+
authors = ["Antoni-Czaplicki <56671347+Antoni-Czaplicki@users.noreply.github.com>"]
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
|
|
8
|
+
[tool.poetry.dependencies]
|
|
9
|
+
python = "^3.12"
|
|
10
|
+
aiohttp = "^3.9.5"
|
|
11
|
+
pydantic = "^2.8.2"
|
|
12
|
+
oauthlib = "^3.2.2"
|
|
13
|
+
python-dotenv = "^1.0.1"
|
|
14
|
+
|
|
15
|
+
[tool.poetry.group.dev.dependencies]
|
|
16
|
+
black = "*"
|
|
17
|
+
isort = "*"
|
|
18
|
+
ruff = "*"
|
|
19
|
+
|
|
20
|
+
[tool.poetry.group.docs]
|
|
21
|
+
optional = true
|
|
22
|
+
|
|
23
|
+
[tool.poetry.group.docs.dependencies]
|
|
24
|
+
sphinx = "*"
|
|
25
|
+
sphinx_rtd_theme = "*"
|
|
26
|
+
readthedocs-sphinx-search = "*"
|
|
27
|
+
sphinx-autodoc-typehints = "*"
|
|
28
|
+
|
|
29
|
+
[build-system]
|
|
30
|
+
requires = ["poetry-core"]
|
|
31
|
+
build-backend = "poetry.core.masonry.api"
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import urllib
|
|
2
|
+
|
|
3
|
+
import aiohttp
|
|
4
|
+
from oauthlib.oauth1 import Client
|
|
5
|
+
|
|
6
|
+
from .exceptions import USOSAPIException
|
|
7
|
+
from .logger import get_logger
|
|
8
|
+
|
|
9
|
+
_LOGGER = get_logger("AuthManager")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AuthManager:
|
|
13
|
+
"""
|
|
14
|
+
A manager for the USOS API authentication.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
REQUEST_TOKEN_SUFFIX = "services/oauth/request_token"
|
|
18
|
+
AUTHORIZE_SUFFIX = "services/oauth/authorize"
|
|
19
|
+
ACCESS_TOKEN_SUFFIX = "services/oauth/access_token"
|
|
20
|
+
REVOKE_TOKEN_SUFFIX = "services/oauth/revoke_token"
|
|
21
|
+
SCOPES = "|".join(["offline_access", "studies"])
|
|
22
|
+
|
|
23
|
+
def __init__(self, api_base_address: str, consumer_key: str, consumer_secret: str):
|
|
24
|
+
"""
|
|
25
|
+
Initialize the authentication manager.
|
|
26
|
+
|
|
27
|
+
:param api_base_address: The base address of the USOS API.
|
|
28
|
+
:param consumer_key: Consumer key obtained from the USOS API.
|
|
29
|
+
:param consumer_secret: Consumer secret obtained from the USOS API.
|
|
30
|
+
"""
|
|
31
|
+
self.base_address = api_base_address.rstrip("/") + "/"
|
|
32
|
+
self.consumer_key = consumer_key
|
|
33
|
+
self.consumer_secret = consumer_secret
|
|
34
|
+
self.access_token = None
|
|
35
|
+
self.access_token_secret = None
|
|
36
|
+
self._session = None
|
|
37
|
+
self._oauth_client = Client(consumer_key, consumer_secret)
|
|
38
|
+
|
|
39
|
+
async def __aenter__(self) -> "AuthManager":
|
|
40
|
+
"""
|
|
41
|
+
Enter the manager.
|
|
42
|
+
|
|
43
|
+
:return: The manager.
|
|
44
|
+
"""
|
|
45
|
+
await self.open()
|
|
46
|
+
return self
|
|
47
|
+
|
|
48
|
+
async def __aexit__(self, exc_type, exc_value, traceback):
|
|
49
|
+
"""
|
|
50
|
+
Exit the manager.
|
|
51
|
+
|
|
52
|
+
:param exc_type: The exception type.
|
|
53
|
+
:param exc_value: The exception value.
|
|
54
|
+
:param traceback: The traceback.
|
|
55
|
+
"""
|
|
56
|
+
await self.close()
|
|
57
|
+
|
|
58
|
+
async def open(self):
|
|
59
|
+
"""
|
|
60
|
+
Open the manager.
|
|
61
|
+
"""
|
|
62
|
+
self._session = aiohttp.ClientSession()
|
|
63
|
+
|
|
64
|
+
async def close(self):
|
|
65
|
+
"""
|
|
66
|
+
Close the manager.
|
|
67
|
+
"""
|
|
68
|
+
if self._session:
|
|
69
|
+
await self._session.close()
|
|
70
|
+
|
|
71
|
+
async def _generate_request_token(self, callback_url: str) -> None:
|
|
72
|
+
"""
|
|
73
|
+
Generate a new request token.
|
|
74
|
+
|
|
75
|
+
:param callback_url:
|
|
76
|
+
"""
|
|
77
|
+
url = f"{self.base_address}{self.REQUEST_TOKEN_SUFFIX}"
|
|
78
|
+
params = {
|
|
79
|
+
"oauth_callback": callback_url,
|
|
80
|
+
"scopes": self.SCOPES,
|
|
81
|
+
}
|
|
82
|
+
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
|
83
|
+
url, headers, body = Client(
|
|
84
|
+
self.consumer_key, client_secret=self.consumer_secret
|
|
85
|
+
).sign(
|
|
86
|
+
url, http_method="POST", body=params, headers=headers
|
|
87
|
+
) # Use a new client to avoid using the access token if it's set
|
|
88
|
+
async with self._session.post(url, data=body, headers=headers) as response:
|
|
89
|
+
await self._handle_response_errors(response)
|
|
90
|
+
data = dict(urllib.parse.parse_qsl(await response.text()))
|
|
91
|
+
self._request_token = data["oauth_token"]
|
|
92
|
+
self._request_token_secret = data["oauth_token_secret"]
|
|
93
|
+
self._oauth_client.resource_owner_key = self._request_token
|
|
94
|
+
self._oauth_client.resource_owner_secret = self._request_token_secret
|
|
95
|
+
_LOGGER.info(f"New request token generated: {self._request_token}")
|
|
96
|
+
|
|
97
|
+
async def get_authorization_url(self, callback_url: str) -> str:
|
|
98
|
+
"""
|
|
99
|
+
Get the authorization URL.
|
|
100
|
+
|
|
101
|
+
:param callback_url: The callback URL.
|
|
102
|
+
"""
|
|
103
|
+
await self._generate_request_token(callback_url)
|
|
104
|
+
return f"{self.base_address}{self.AUTHORIZE_SUFFIX}?oauth_token={self._request_token}"
|
|
105
|
+
|
|
106
|
+
async def authorize_with_token(self, token: str) -> tuple[str, str]:
|
|
107
|
+
"""
|
|
108
|
+
Authorize the client with a token.
|
|
109
|
+
|
|
110
|
+
:param token: The token to authorize the client with.
|
|
111
|
+
:return: The access token and secret.
|
|
112
|
+
"""
|
|
113
|
+
self._oauth_client.verifier = token
|
|
114
|
+
url = f"{self.base_address}{self.ACCESS_TOKEN_SUFFIX}"
|
|
115
|
+
url, headers, body = self._oauth_client.sign(url, http_method="POST")
|
|
116
|
+
async with self._session.post(url, data=body, headers=headers) as response:
|
|
117
|
+
await self._handle_response_errors(response)
|
|
118
|
+
data = dict(urllib.parse.parse_qsl(await response.text()))
|
|
119
|
+
self.load_access_token(data["oauth_token"], data["oauth_token_secret"])
|
|
120
|
+
_LOGGER.info(
|
|
121
|
+
f"Authorization successful, received access token: {self.access_token}"
|
|
122
|
+
)
|
|
123
|
+
return self.access_token, self.access_token_secret
|
|
124
|
+
|
|
125
|
+
def load_access_token(self, access_token: str, access_token_secret: str):
|
|
126
|
+
"""
|
|
127
|
+
Load the access token and secret into the manager.
|
|
128
|
+
|
|
129
|
+
:param access_token: The access token.
|
|
130
|
+
:param access_token_secret: The access token secret.
|
|
131
|
+
"""
|
|
132
|
+
self.access_token = access_token
|
|
133
|
+
self.access_token_secret = access_token_secret
|
|
134
|
+
self._oauth_client = Client(
|
|
135
|
+
self.consumer_key,
|
|
136
|
+
client_secret=self.consumer_secret,
|
|
137
|
+
resource_owner_key=self.access_token,
|
|
138
|
+
resource_owner_secret=self.access_token_secret,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
def sign_request(
|
|
142
|
+
self, url: str, http_method: str = "GET", **kwargs
|
|
143
|
+
) -> tuple[str, dict, dict]:
|
|
144
|
+
"""
|
|
145
|
+
Sign a request with the OAuth client.
|
|
146
|
+
|
|
147
|
+
:param url: The URL to sign.
|
|
148
|
+
:param http_method: The HTTP method to use.
|
|
149
|
+
:param kwargs: Additional parameters to pass.
|
|
150
|
+
:return: The signed URL, headers, and body.
|
|
151
|
+
"""
|
|
152
|
+
if not self.access_token:
|
|
153
|
+
raise USOSAPIException("Access token not set. Did you forget to authorize?")
|
|
154
|
+
url, headers, body = self._oauth_client.sign(
|
|
155
|
+
url, http_method=http_method, **kwargs
|
|
156
|
+
)
|
|
157
|
+
return url, headers, body
|
|
158
|
+
|
|
159
|
+
async def _handle_response_errors(self, response: aiohttp.ClientResponse):
|
|
160
|
+
"""
|
|
161
|
+
Handle errors in the response.
|
|
162
|
+
|
|
163
|
+
:param response: The response to handle.
|
|
164
|
+
:raises USOSAPIException: If an error occurred.
|
|
165
|
+
"""
|
|
166
|
+
if response.status != 200:
|
|
167
|
+
text = await response.text()
|
|
168
|
+
if response.status == 401:
|
|
169
|
+
_LOGGER.error(
|
|
170
|
+
f"HTTP 401: Unauthorized. Your access key probably expired. Response: {text}"
|
|
171
|
+
)
|
|
172
|
+
raise USOSAPIException(
|
|
173
|
+
"HTTP 401: Unauthorized. Your access key probably expired."
|
|
174
|
+
)
|
|
175
|
+
elif response.status == 400:
|
|
176
|
+
raise USOSAPIException(f"HTTP 400: Bad request: {text}")
|
|
177
|
+
else:
|
|
178
|
+
raise USOSAPIException(f"HTTP {response.status}: {text}")
|
|
179
|
+
|
|
180
|
+
async def _revoke_token(self):
|
|
181
|
+
"""
|
|
182
|
+
Revoke the current access token.
|
|
183
|
+
"""
|
|
184
|
+
url = f"{self.base_address}{self.REVOKE_TOKEN_SUFFIX}"
|
|
185
|
+
url, headers, body = self._oauth_client.sign(url, http_method="POST")
|
|
186
|
+
async with self._session.post(url, data=body, headers=headers) as response:
|
|
187
|
+
await self._handle_response_errors(response)
|
|
188
|
+
_LOGGER.info("Token revoked successfully.")
|
|
189
|
+
|
|
190
|
+
async def logout(self):
|
|
191
|
+
"""
|
|
192
|
+
Log out the user.
|
|
193
|
+
"""
|
|
194
|
+
if not self.access_token:
|
|
195
|
+
return
|
|
196
|
+
await self._revoke_token()
|
|
197
|
+
self.access_token = None
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from .connection import USOSAPIConnection
|
|
4
|
+
from .logger import get_logger
|
|
5
|
+
from .services import UserService
|
|
6
|
+
from .services.api_server import APIServerService
|
|
7
|
+
from .services.groups import GroupService
|
|
8
|
+
|
|
9
|
+
_LOGGER = get_logger("USOSClient")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class USOSClient:
|
|
13
|
+
"""
|
|
14
|
+
A client for the USOS API.
|
|
15
|
+
|
|
16
|
+
:var UserService user_service: The user service.
|
|
17
|
+
:var GroupService group_service: The group service.
|
|
18
|
+
:var APIServerService api_server_service: The API server service.
|
|
19
|
+
|
|
20
|
+
:ivar USOSAPIConnection connection: The connection to the USOS API, used for making requests.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self, api_base_address: str, consumer_key: str, consumer_secret: str
|
|
25
|
+
) -> None:
|
|
26
|
+
"""
|
|
27
|
+
Initialize the USOS API client.
|
|
28
|
+
|
|
29
|
+
:param api_base_address: The base address of the USOS API.
|
|
30
|
+
:param consumer_key: Consumer key obtained from the USOS API.
|
|
31
|
+
:param consumer_secret: Consumer secret obtained from the USOS API.
|
|
32
|
+
"""
|
|
33
|
+
self.connection = USOSAPIConnection(
|
|
34
|
+
api_base_address, consumer_key, consumer_secret
|
|
35
|
+
)
|
|
36
|
+
self.user_service = UserService(self.connection)
|
|
37
|
+
self.group_service = GroupService(self.connection)
|
|
38
|
+
self.api_server_service = APIServerService(self.connection)
|
|
39
|
+
|
|
40
|
+
async def __aenter__(self) -> "USOSClient":
|
|
41
|
+
"""
|
|
42
|
+
Enter the client.
|
|
43
|
+
|
|
44
|
+
:return: The client.
|
|
45
|
+
"""
|
|
46
|
+
await self.open()
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
async def __aexit__(self, exc_type, exc_value, traceback):
|
|
50
|
+
"""
|
|
51
|
+
Exit the client.
|
|
52
|
+
|
|
53
|
+
:param exc_type: The exception type.
|
|
54
|
+
:param exc_value: The exception value.
|
|
55
|
+
:param traceback: The traceback.
|
|
56
|
+
"""
|
|
57
|
+
await self.close()
|
|
58
|
+
|
|
59
|
+
async def close(self) -> None:
|
|
60
|
+
"""
|
|
61
|
+
Close the client.
|
|
62
|
+
"""
|
|
63
|
+
await self.connection.close()
|
|
64
|
+
|
|
65
|
+
async def open(self) -> None:
|
|
66
|
+
"""
|
|
67
|
+
Open the client.
|
|
68
|
+
"""
|
|
69
|
+
await self.connection.open()
|
|
70
|
+
|
|
71
|
+
def set_scopes(self, scopes: list[str]) -> None:
|
|
72
|
+
"""
|
|
73
|
+
Set the scopes for the client.
|
|
74
|
+
|
|
75
|
+
:param scopes: The scopes to set.
|
|
76
|
+
"""
|
|
77
|
+
self.connection.auth_manager.SCOPES = "|".join(scopes)
|
|
78
|
+
|
|
79
|
+
def add_scope(self, scope: str) -> None:
|
|
80
|
+
"""
|
|
81
|
+
Add a scope to the client.
|
|
82
|
+
|
|
83
|
+
:param scope: The scope to add.
|
|
84
|
+
"""
|
|
85
|
+
self.connection.auth_manager.SCOPES += f"|{scope}"
|
|
86
|
+
|
|
87
|
+
def remove_scope(self, scope: str) -> None:
|
|
88
|
+
"""
|
|
89
|
+
Remove a scope from the client.
|
|
90
|
+
|
|
91
|
+
:param scope: The scope to remove.
|
|
92
|
+
"""
|
|
93
|
+
self.connection.auth_manager.SCOPES = "|".join(
|
|
94
|
+
[s for s in self.connection.auth_manager.SCOPES.split("|") if s != scope]
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
async def authorize(self, token: str) -> tuple[str, str]:
|
|
98
|
+
"""
|
|
99
|
+
Authorize the client with a token.
|
|
100
|
+
|
|
101
|
+
:param token: The token to authorize the client with.
|
|
102
|
+
:return: The access token and secret.
|
|
103
|
+
"""
|
|
104
|
+
return await self.connection.auth_manager.authorize_with_token(token)
|
|
105
|
+
|
|
106
|
+
async def get_authorization_url(self, callback_url: str = "oob"):
|
|
107
|
+
"""
|
|
108
|
+
Get the URL to authorize the client.
|
|
109
|
+
|
|
110
|
+
:param callback_url: The URL to redirect to after authorization, leave as "oob" for pin-based authorization.
|
|
111
|
+
:return: The URL to authorize the client.
|
|
112
|
+
"""
|
|
113
|
+
return await self.connection.auth_manager.get_authorization_url(callback_url)
|
|
114
|
+
|
|
115
|
+
def load_access_token(self, access_token: str, access_token_secret: str):
|
|
116
|
+
"""
|
|
117
|
+
Load the access token and secret into the client.
|
|
118
|
+
|
|
119
|
+
:param access_token: The access token.
|
|
120
|
+
:param access_token_secret: The access token secret.
|
|
121
|
+
"""
|
|
122
|
+
self.connection.auth_manager.load_access_token(
|
|
123
|
+
access_token, access_token_secret
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
def load_access_token_from_json(self, json_data: dict):
|
|
127
|
+
"""
|
|
128
|
+
Load the access token and secret from a JSON object.
|
|
129
|
+
|
|
130
|
+
:param json_data: The JSON object containing the access token and secret.
|
|
131
|
+
"""
|
|
132
|
+
try:
|
|
133
|
+
access_token = json_data["access_token"]
|
|
134
|
+
access_token_secret = json_data["access_token_secret"]
|
|
135
|
+
except KeyError:
|
|
136
|
+
raise ValueError("Invalid JSON data.")
|
|
137
|
+
self.load_access_token(access_token, access_token_secret)
|
|
138
|
+
|
|
139
|
+
async def load_access_token_from_file(
|
|
140
|
+
self, file_path: str = "usos_api_access_token.json"
|
|
141
|
+
) -> None:
|
|
142
|
+
"""
|
|
143
|
+
Load the access token and secret from a JSON file.
|
|
144
|
+
|
|
145
|
+
:param file_path: The path to the JSON file.
|
|
146
|
+
"""
|
|
147
|
+
if not file_path.endswith(".json"):
|
|
148
|
+
raise ValueError("File must be a JSON file.")
|
|
149
|
+
with open(file_path, "r") as file:
|
|
150
|
+
json_data = json.load(file)
|
|
151
|
+
self.load_access_token_from_json(json_data)
|
|
152
|
+
|
|
153
|
+
async def save_access_token_to_file(
|
|
154
|
+
self, file_path: str = "usos_api_access_token.json"
|
|
155
|
+
) -> None:
|
|
156
|
+
"""
|
|
157
|
+
Save the access token and secret to a JSON file.
|
|
158
|
+
|
|
159
|
+
:param file_path: The path to the JSON file.
|
|
160
|
+
"""
|
|
161
|
+
if not file_path.endswith(".json"):
|
|
162
|
+
raise ValueError("File must be a JSON file.")
|
|
163
|
+
json_data = {
|
|
164
|
+
"access_token": self.connection.auth_manager.access_token,
|
|
165
|
+
"access_token_secret": self.connection.auth_manager.access_token_secret,
|
|
166
|
+
}
|
|
167
|
+
with open(file_path, "w") as file:
|
|
168
|
+
json.dump(json_data, file)
|
|
169
|
+
|
|
170
|
+
async def test_connection(self) -> bool:
|
|
171
|
+
"""
|
|
172
|
+
Test the connection to the USOS API.
|
|
173
|
+
|
|
174
|
+
:return: True if the connection is successful, False otherwise.
|
|
175
|
+
"""
|
|
176
|
+
return await self.connection.test_connection()
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
from urllib.parse import urlencode, urlparse
|
|
2
|
+
|
|
3
|
+
import aiohttp
|
|
4
|
+
|
|
5
|
+
from .auth import AuthManager
|
|
6
|
+
from .exceptions import USOSAPIException
|
|
7
|
+
from .logger import get_logger
|
|
8
|
+
|
|
9
|
+
_LOGGER = get_logger("usos-api")
|
|
10
|
+
_DOWNLOAD_LOGGER = get_logger("usos-api-download")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class USOSAPIConnection:
|
|
14
|
+
"""
|
|
15
|
+
A connection to the USOS API.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, api_base_address: str, consumer_key: str, consumer_secret: str):
|
|
19
|
+
"""
|
|
20
|
+
Initialize the USOS API connection.
|
|
21
|
+
|
|
22
|
+
:param api_base_address: The base address of the USOS API.
|
|
23
|
+
:param consumer_key: Consumer key obtained from the USOS API.
|
|
24
|
+
:param consumer_secret: Consumer secret obtained from the USOS API.
|
|
25
|
+
"""
|
|
26
|
+
self.base_address = api_base_address.rstrip("/") + "/"
|
|
27
|
+
self.auth_manager = AuthManager(
|
|
28
|
+
self.base_address, consumer_key, consumer_secret
|
|
29
|
+
)
|
|
30
|
+
self._session = None
|
|
31
|
+
|
|
32
|
+
async def __aenter__(self) -> "USOSAPIConnection":
|
|
33
|
+
"""
|
|
34
|
+
Enter the connection.
|
|
35
|
+
|
|
36
|
+
:return: The connection.
|
|
37
|
+
"""
|
|
38
|
+
await self.open()
|
|
39
|
+
return self
|
|
40
|
+
|
|
41
|
+
async def __aexit__(self, exc_type, exc_value, traceback):
|
|
42
|
+
"""
|
|
43
|
+
Exit the connection.
|
|
44
|
+
|
|
45
|
+
:param exc_type: The exception type.
|
|
46
|
+
:param exc_value: The exception value.
|
|
47
|
+
:param traceback: The traceback.
|
|
48
|
+
"""
|
|
49
|
+
await self.close()
|
|
50
|
+
|
|
51
|
+
async def open(self):
|
|
52
|
+
"""
|
|
53
|
+
Open the connection.
|
|
54
|
+
"""
|
|
55
|
+
self._session = aiohttp.ClientSession()
|
|
56
|
+
await self.auth_manager.open()
|
|
57
|
+
|
|
58
|
+
async def close(self):
|
|
59
|
+
"""
|
|
60
|
+
Close the connection.
|
|
61
|
+
"""
|
|
62
|
+
if self._session:
|
|
63
|
+
await self._session.close()
|
|
64
|
+
await self.auth_manager.close()
|
|
65
|
+
|
|
66
|
+
async def test_connection(self) -> bool:
|
|
67
|
+
"""
|
|
68
|
+
Test the connection to the USOS API.
|
|
69
|
+
:return: True if the connection is successful, False otherwise.
|
|
70
|
+
"""
|
|
71
|
+
url = f"{self.base_address}services/apisrv/now"
|
|
72
|
+
async with self._session.get(url) as response:
|
|
73
|
+
return response.status == 200
|
|
74
|
+
|
|
75
|
+
async def get(self, service: str, **kwargs) -> dict:
|
|
76
|
+
"""
|
|
77
|
+
Perform a GET request to the USOS API.
|
|
78
|
+
|
|
79
|
+
From the USOS API documentation:
|
|
80
|
+
You may call all the services with GET or POST methods (POST preferred).
|
|
81
|
+
|
|
82
|
+
:param service: The service to call.
|
|
83
|
+
:param kwargs: The parameters to pass.
|
|
84
|
+
:return: The response data.
|
|
85
|
+
"""
|
|
86
|
+
kwargs = {k: str(v) for k, v in kwargs.items() if v is not None}
|
|
87
|
+
headers = {}
|
|
88
|
+
url_parts = [f"{self.base_address}{service}"]
|
|
89
|
+
query_string = urlparse(url_parts[0]).query
|
|
90
|
+
url_parts.append("&" if query_string else "?")
|
|
91
|
+
url_parts.append(urlencode(kwargs))
|
|
92
|
+
url, headers, body = self.auth_manager.sign_request(
|
|
93
|
+
"".join(url_parts), headers=headers
|
|
94
|
+
)
|
|
95
|
+
print(url, headers, body)
|
|
96
|
+
async with self._session.get(url, params=kwargs, headers=headers) as response:
|
|
97
|
+
await self._handle_response_errors(response)
|
|
98
|
+
return await response.json()
|
|
99
|
+
|
|
100
|
+
async def post(self, service: str, **kwargs) -> dict:
|
|
101
|
+
"""
|
|
102
|
+
Perform a POST request to the USOS API.
|
|
103
|
+
|
|
104
|
+
From the USOS API documentation:
|
|
105
|
+
You may call all the services with GET or POST methods (POST preferred).
|
|
106
|
+
|
|
107
|
+
:param service: The service to call.
|
|
108
|
+
:param kwargs: The parameters to pass.
|
|
109
|
+
:return: The response data.
|
|
110
|
+
"""
|
|
111
|
+
kwargs = {k: str(v) for k, v in kwargs.items() if v is not None}
|
|
112
|
+
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
|
113
|
+
url = f"{self.base_address}{service}"
|
|
114
|
+
url, headers, body = self.auth_manager.sign_request(
|
|
115
|
+
url, http_method="POST", body=kwargs, headers=headers
|
|
116
|
+
)
|
|
117
|
+
async with self._session.post(url, data=body, headers=headers) as response:
|
|
118
|
+
await self._handle_response_errors(response)
|
|
119
|
+
return await response.json()
|
|
120
|
+
|
|
121
|
+
async def _handle_response_errors(self, response: aiohttp.ClientResponse):
|
|
122
|
+
"""
|
|
123
|
+
Handle errors in the response.
|
|
124
|
+
|
|
125
|
+
:param response: The response to handle.
|
|
126
|
+
:raises USOSAPIException: If an error occurred.
|
|
127
|
+
"""
|
|
128
|
+
if response.status != 200:
|
|
129
|
+
text = await response.text()
|
|
130
|
+
if response.status == 401:
|
|
131
|
+
raise USOSAPIException(
|
|
132
|
+
f"HTTP 401: Unauthorized. Your access key probably expired. {text}"
|
|
133
|
+
)
|
|
134
|
+
elif response.status == 400:
|
|
135
|
+
raise USOSAPIException(f"HTTP 400: Bad request: {text}")
|
|
136
|
+
else:
|
|
137
|
+
raise USOSAPIException(f"HTTP {response.status}: {text}")
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def get_logger(name: str) -> logging.Logger:
|
|
5
|
+
"""
|
|
6
|
+
Get a logger with the specified name.
|
|
7
|
+
|
|
8
|
+
:param name: The name of the logger.
|
|
9
|
+
:return: The logger.
|
|
10
|
+
"""
|
|
11
|
+
logger = logging.getLogger(name)
|
|
12
|
+
if not logger.handlers:
|
|
13
|
+
handler = logging.StreamHandler()
|
|
14
|
+
formatter = logging.Formatter(
|
|
15
|
+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
16
|
+
)
|
|
17
|
+
handler.setFormatter(formatter)
|
|
18
|
+
logger.addHandler(handler)
|
|
19
|
+
logger.setLevel(logging.INFO)
|
|
20
|
+
return logger
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from .consumer import Consumer
|
|
2
|
+
from .course import Course, CourseAttribute, CourseEdition, CourseEditionConducted
|
|
3
|
+
from .grade import Grade
|
|
4
|
+
from .group import Group
|
|
5
|
+
from .lang_dict import LangDict
|
|
6
|
+
from .programme import Programme, StudentProgramme
|
|
7
|
+
from .term import Term
|
|
8
|
+
from .user import (
|
|
9
|
+
EmailAccess,
|
|
10
|
+
EmploymentFunction,
|
|
11
|
+
EmploymentPosition,
|
|
12
|
+
ExternalIds,
|
|
13
|
+
Position,
|
|
14
|
+
PostalAddress,
|
|
15
|
+
PreviousName,
|
|
16
|
+
Sex,
|
|
17
|
+
StaffStatus,
|
|
18
|
+
StudentStatus,
|
|
19
|
+
Title,
|
|
20
|
+
User,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
# Fix for circular imports
|
|
24
|
+
CourseAttribute.model_rebuild()
|
|
25
|
+
CourseEdition.model_rebuild()
|
|
26
|
+
Grade.model_rebuild()
|
|
27
|
+
Group.model_rebuild()
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"User",
|
|
31
|
+
"PreviousName",
|
|
32
|
+
"Title",
|
|
33
|
+
"Position",
|
|
34
|
+
"EmploymentPosition",
|
|
35
|
+
"EmailAccess",
|
|
36
|
+
"StaffStatus",
|
|
37
|
+
"StudentStatus",
|
|
38
|
+
"EmploymentFunction",
|
|
39
|
+
"PostalAddress",
|
|
40
|
+
"ExternalIds",
|
|
41
|
+
"StudentProgramme",
|
|
42
|
+
"Programme",
|
|
43
|
+
"Sex",
|
|
44
|
+
"LangDict",
|
|
45
|
+
"CourseAttribute",
|
|
46
|
+
"CourseEdition",
|
|
47
|
+
"Group",
|
|
48
|
+
"Grade",
|
|
49
|
+
"Course",
|
|
50
|
+
"CourseEditionConducted",
|
|
51
|
+
"Term",
|
|
52
|
+
"Consumer",
|
|
53
|
+
]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from typing import List
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Consumer(BaseModel):
|
|
8
|
+
"""
|
|
9
|
+
Class representing a consumer.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
name: str | None = None
|
|
13
|
+
url: str | None = None
|
|
14
|
+
email: str | None = None
|
|
15
|
+
date_registered: datetime | None = None
|
|
16
|
+
administrative_methods: List[str] | None = None
|
|
17
|
+
token_scopes: List[str] | None = None
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING, List
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
from .group import Group
|
|
6
|
+
from .term import Term
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from .user import User
|
|
10
|
+
|
|
11
|
+
from .grade import Grade
|
|
12
|
+
from .lang_dict import LangDict
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CourseAttribute(BaseModel):
|
|
16
|
+
"""
|
|
17
|
+
Class representing a course attribute.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
name: LangDict | None = None
|
|
21
|
+
values: List[LangDict] | None = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Course(BaseModel):
|
|
25
|
+
"""
|
|
26
|
+
Class representing a course.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
id: str | None = None
|
|
30
|
+
name: LangDict | None = None
|
|
31
|
+
homepage_url: str | None = None
|
|
32
|
+
profile_url: str | None = None
|
|
33
|
+
is_currently_conducted: bool | None = None
|
|
34
|
+
terms: List[Term] | None = None
|
|
35
|
+
fac_id: str | None = None
|
|
36
|
+
lang_id: str | None = None
|
|
37
|
+
ects_credits_simplified: float | None = None
|
|
38
|
+
description: LangDict | None = None
|
|
39
|
+
bibliography: LangDict | None = None
|
|
40
|
+
learning_outcomes: LangDict | None = None
|
|
41
|
+
assessment_criteria: LangDict | None = None
|
|
42
|
+
practical_placement: LangDict | None = None
|
|
43
|
+
attributes: List[CourseAttribute] | None = None
|
|
44
|
+
attributes2: List[CourseAttribute] | None = None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class CourseEdition(BaseModel):
|
|
48
|
+
"""
|
|
49
|
+
Class representing a course edition.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
course_id: str | None = None
|
|
53
|
+
course_name: LangDict | None = None
|
|
54
|
+
term_id: str | None = None
|
|
55
|
+
homepage_url: str | None = None
|
|
56
|
+
profile_url: str | None = None
|
|
57
|
+
coordinators: List["User"] | None = None
|
|
58
|
+
lecturers: List["User"] | None = None
|
|
59
|
+
passing_status: str | None = None
|
|
60
|
+
user_groups: List[Group] | None = None
|
|
61
|
+
description: LangDict | None = None
|
|
62
|
+
bibliography: LangDict | None = None
|
|
63
|
+
notes: LangDict | None = None
|
|
64
|
+
course_units_ids: List[str] | None = None
|
|
65
|
+
participants: List["User"] | None = None
|
|
66
|
+
grades: List[Grade] | None = None
|
|
67
|
+
attributes: List[CourseAttribute] | None = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class CourseEditionConducted(BaseModel):
|
|
71
|
+
"""
|
|
72
|
+
Class representing a conducted course edition.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
id: str | None = None
|
|
76
|
+
course: Course | None = None
|
|
77
|
+
term: Term | None = None
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING, Any, Dict, Optional
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from .user import User
|
|
7
|
+
|
|
8
|
+
from .lang_dict import LangDict
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Grade(BaseModel):
|
|
12
|
+
value_symbol: str | None = None
|
|
13
|
+
passes: bool | None = None
|
|
14
|
+
value_description: LangDict | None = None
|
|
15
|
+
exam_id: str | None = None
|
|
16
|
+
exam_session_number: str | None = None
|
|
17
|
+
counts_into_average: bool | None = None
|
|
18
|
+
comment: str | None = None
|
|
19
|
+
private_comment: str | None = None
|
|
20
|
+
grade_type_id: str | None = None
|
|
21
|
+
date_modified: str | None = None
|
|
22
|
+
date_acquisition: str | None = None
|
|
23
|
+
modification_author: str | None = None
|
|
24
|
+
course_edition: Dict[str, Any] | None = None
|
|
25
|
+
unit: Dict[str, Any] | None = None
|
|
26
|
+
exam_report: Dict[str, Any] | None = None
|
|
27
|
+
user: Optional["User"] = None
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING, List
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
from .lang_dict import LangDict
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from .user import User
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Group(BaseModel):
|
|
12
|
+
course_unit_id: str | None = None
|
|
13
|
+
group_number: int | None = None
|
|
14
|
+
class_type: LangDict | None = None
|
|
15
|
+
class_type_id: str | None = None
|
|
16
|
+
group_url: str | None = None
|
|
17
|
+
course_id: str | None = None
|
|
18
|
+
course_name: LangDict | None = None
|
|
19
|
+
course_homepage_url: str | None = None
|
|
20
|
+
course_profile_url: str | None = None
|
|
21
|
+
course_is_currently_conducted: bool | None = None
|
|
22
|
+
course_fac_id: str | None = None
|
|
23
|
+
course_lang_id: str | None = None
|
|
24
|
+
term_id: str | None = None
|
|
25
|
+
lecturers: List["User"] | None = None
|
|
26
|
+
participants: List["User"] | None = None
|
|
27
|
+
group_description: LangDict | None = None
|
|
28
|
+
group_literature: LangDict | None = None
|
|
29
|
+
course_learning_outcomes: LangDict | None = None
|
|
30
|
+
course_description: LangDict | None = None
|
|
31
|
+
course_bibliography: LangDict | None = None
|
|
32
|
+
course_assessment_criteria: LangDict | None = None
|
|
33
|
+
course_practical_placement: LangDict | None = None
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from datetime import date
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Programme(BaseModel):
|
|
7
|
+
"""
|
|
8
|
+
Class representing a study programme.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
id: str | None = None
|
|
12
|
+
name: dict | None = None
|
|
13
|
+
description: dict | None = None
|
|
14
|
+
faculty: dict | None = None
|
|
15
|
+
all_faculties: list | None = None
|
|
16
|
+
mode_of_studies: dict | None = None
|
|
17
|
+
level_of_studies: dict | None = None
|
|
18
|
+
duration: dict | None = None
|
|
19
|
+
professional_status: dict | None = None
|
|
20
|
+
level: str | None = None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class StudentProgramme(BaseModel):
|
|
24
|
+
"""
|
|
25
|
+
Class representing a student programme a user is enrolled in.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
id: str | None = None
|
|
29
|
+
user: dict | None = None
|
|
30
|
+
programme: Programme | None = None
|
|
31
|
+
status: str | None = None
|
|
32
|
+
admission_date: date | None = None
|
|
33
|
+
stages: list = []
|
|
34
|
+
is_primary: bool | None = None
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from datetime import date
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
from .lang_dict import LangDict
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Term(BaseModel):
|
|
9
|
+
id: str | None = None
|
|
10
|
+
name: LangDict | None = None
|
|
11
|
+
start_date: date | None = None
|
|
12
|
+
end_date: date | None = None
|
|
13
|
+
finish_date: date | None = None
|
|
14
|
+
is_active: bool | None = None
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
from datetime import date
|
|
2
|
+
from enum import Enum
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel
|
|
5
|
+
|
|
6
|
+
from .course import CourseEditionConducted
|
|
7
|
+
from .lang_dict import LangDict
|
|
8
|
+
from .programme import StudentProgramme
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PreviousName(BaseModel):
|
|
12
|
+
"""
|
|
13
|
+
Class representing a user's previous name along with the date until which it was used.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
first_name: str | None = None
|
|
17
|
+
last_name: str | None = None
|
|
18
|
+
until: date | None = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Title(BaseModel):
|
|
22
|
+
"""
|
|
23
|
+
Class representing a user's academic titles.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
before: str | None = None
|
|
27
|
+
after: str | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class EmailAccess(Enum):
|
|
31
|
+
"""
|
|
32
|
+
Enum representing the access level to a user's email.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
NO_EMAIL = "no_email"
|
|
36
|
+
NO_ACCESS = "no_access"
|
|
37
|
+
REQUIRE_CAPTCHA = "require_captcha"
|
|
38
|
+
PLAINTEXT = "plaintext"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class EmploymentFunction(BaseModel):
|
|
42
|
+
"""
|
|
43
|
+
Class representing an employment function of a user.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
function: LangDict | None = None
|
|
47
|
+
faculty: dict | None = None
|
|
48
|
+
is_official: bool | None = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Position(BaseModel):
|
|
52
|
+
"""
|
|
53
|
+
Class representing an employment position.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
id: str | None = None
|
|
57
|
+
name: LangDict | None = None
|
|
58
|
+
employment_group: dict | None = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class EmploymentPosition(BaseModel):
|
|
62
|
+
"""
|
|
63
|
+
Class representing an employment position of a user.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
position: Position | None = None
|
|
67
|
+
faculty: LangDict | None = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class PostalAddress(BaseModel):
|
|
71
|
+
"""
|
|
72
|
+
Class representing a postal address of a user.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
type: str | None = None
|
|
76
|
+
type_name: str | None = None
|
|
77
|
+
address: str | None = None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class ExternalIds(BaseModel):
|
|
81
|
+
"""
|
|
82
|
+
Class representing external IDs of a user.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
orcid: str | None = None
|
|
86
|
+
pbn_id: str | None = None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class StaffStatus(Enum):
|
|
90
|
+
"""
|
|
91
|
+
Enum representing the staff status of a user.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
NOT_STAFF = 0
|
|
95
|
+
NON_ACADEMIC_STAFF = 1
|
|
96
|
+
ACADEMIC_TEACHER = 2
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class StudentStatus(Enum):
|
|
100
|
+
"""
|
|
101
|
+
Enum representing the student status of a user.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
NOT_STUDENT = 0
|
|
105
|
+
INACTIVE_STUDENT = 1
|
|
106
|
+
ACTIVE_STUDENT = 2
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Sex(Enum):
|
|
110
|
+
"""
|
|
111
|
+
Enum representing the gender of a user.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
MALE = "M"
|
|
115
|
+
FEMALE = "F"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class User(BaseModel):
|
|
119
|
+
"""
|
|
120
|
+
Class representing a User with various attributes.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
id: int | None = None
|
|
124
|
+
first_name: str | None = None
|
|
125
|
+
middle_names: str | None = None
|
|
126
|
+
last_name: str | None = None
|
|
127
|
+
previous_names: list[PreviousName] = []
|
|
128
|
+
sex: Sex | None = None
|
|
129
|
+
titles: Title | None = None
|
|
130
|
+
student_status: StudentStatus | None = None
|
|
131
|
+
staff_status: StaffStatus | None = None
|
|
132
|
+
email_access: EmailAccess | None = None
|
|
133
|
+
email: str | None = None
|
|
134
|
+
email_url: str | None = None
|
|
135
|
+
has_email: bool | None = None
|
|
136
|
+
homepage_url: str | None = None
|
|
137
|
+
profile_url: str | None = None
|
|
138
|
+
phone_numbers: list[str] = []
|
|
139
|
+
mobile_numbers: list[str] = []
|
|
140
|
+
office_hours: LangDict | None = None
|
|
141
|
+
interests: LangDict | None = None
|
|
142
|
+
has_photo: bool | None = None
|
|
143
|
+
photo_urls: dict[str, str] = {}
|
|
144
|
+
student_number: str | None = None
|
|
145
|
+
pesel: str | None = None
|
|
146
|
+
birth_date: date | None = None
|
|
147
|
+
revenue_office_id: str | None = None
|
|
148
|
+
citizenship: str | None = None
|
|
149
|
+
room: str | None = None
|
|
150
|
+
student_programmes: list[StudentProgramme] = []
|
|
151
|
+
employment_functions: list[EmploymentFunction] = []
|
|
152
|
+
employment_positions: list[EmploymentPosition] = []
|
|
153
|
+
course_editions_conducted: list[CourseEditionConducted] = []
|
|
154
|
+
postal_addresses: list[PostalAddress] = []
|
|
155
|
+
alt_email: str | None = None
|
|
156
|
+
can_i_debug: bool = False
|
|
157
|
+
external_ids: ExternalIds | None = None
|
|
158
|
+
phd_student_status: int | None = None
|
|
159
|
+
library_card_id: str | None = None
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
|
|
3
|
+
from usos_api.models.consumer import Consumer
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class APIServerService:
|
|
7
|
+
"""
|
|
8
|
+
A service for APIServer-related operations.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
def __init__(self, connection):
|
|
12
|
+
"""
|
|
13
|
+
Initialize the APIServerService.
|
|
14
|
+
|
|
15
|
+
:param connection: The connection to use.
|
|
16
|
+
"""
|
|
17
|
+
self.connection = connection
|
|
18
|
+
|
|
19
|
+
async def get_consumer_info(self, fields: List[str] | None = None) -> Consumer:
|
|
20
|
+
"""
|
|
21
|
+
Get information on the Consumer.
|
|
22
|
+
|
|
23
|
+
:param fields: The fields to include in the response.
|
|
24
|
+
:return: A dictionary of fields you have asked for.
|
|
25
|
+
"""
|
|
26
|
+
if not fields:
|
|
27
|
+
fields = [
|
|
28
|
+
"name",
|
|
29
|
+
"url",
|
|
30
|
+
"email",
|
|
31
|
+
"date_registered",
|
|
32
|
+
"administrative_methods",
|
|
33
|
+
"token_scopes",
|
|
34
|
+
]
|
|
35
|
+
fields = "|".join(fields)
|
|
36
|
+
response = await self.connection.post("services/apisrv/consumer", fields=fields)
|
|
37
|
+
return self._deserialize_consumer(response)
|
|
38
|
+
|
|
39
|
+
def _deserialize_consumer(self, data: dict) -> Consumer:
|
|
40
|
+
return Consumer(**data)
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
|
|
3
|
+
from ..connection import USOSAPIConnection
|
|
4
|
+
from ..logger import get_logger
|
|
5
|
+
from ..models import Group, Term
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _filter_ongoing_terms(terms: list[Term]) -> list[Term]:
|
|
9
|
+
"""
|
|
10
|
+
Filter out terms that are not ongoing.
|
|
11
|
+
|
|
12
|
+
:param terms: The terms to filter.
|
|
13
|
+
:return: The ongoing terms.
|
|
14
|
+
"""
|
|
15
|
+
return [
|
|
16
|
+
term
|
|
17
|
+
for term in terms
|
|
18
|
+
if term.start_date <= datetime.today().date() <= term.finish_date
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _deserialize_term(data: dict) -> Term:
|
|
23
|
+
return Term(**data)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _deserialize_group(data: dict, **kwargs) -> Group:
|
|
27
|
+
data.update(kwargs)
|
|
28
|
+
return Group(**data)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class GroupService:
|
|
32
|
+
"""
|
|
33
|
+
A service for group-related operations.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(self, connection: USOSAPIConnection):
|
|
37
|
+
"""
|
|
38
|
+
Initialize the group
|
|
39
|
+
|
|
40
|
+
:param connection: The connection to use.
|
|
41
|
+
"""
|
|
42
|
+
self.connection = connection
|
|
43
|
+
self.logger = get_logger("GroupService")
|
|
44
|
+
|
|
45
|
+
async def get_groups_by_ids(
|
|
46
|
+
self, group_ids: list[tuple[str, int]], fields: list[str] = None
|
|
47
|
+
) -> list[Group]:
|
|
48
|
+
"""
|
|
49
|
+
Get groups by their IDs.
|
|
50
|
+
|
|
51
|
+
:param group_ids: The IDs of the groups to get. Each ID should be a tuple of course unit ID and group number.
|
|
52
|
+
:param fields: The fields to include in the response.
|
|
53
|
+
:return: A dictionary of group IDs to groups.
|
|
54
|
+
"""
|
|
55
|
+
if not group_ids:
|
|
56
|
+
return []
|
|
57
|
+
if not fields:
|
|
58
|
+
fields = ["course_unit_id", "group_number", "course_name"]
|
|
59
|
+
if "course_unit_id" not in fields:
|
|
60
|
+
fields.append("course_unit_id")
|
|
61
|
+
if "group_number" not in fields:
|
|
62
|
+
fields.append("group_number")
|
|
63
|
+
fields = "|".join(fields)
|
|
64
|
+
response = await self.connection.post(
|
|
65
|
+
"services/groups/groups", group_id=group_ids, fields=fields
|
|
66
|
+
)
|
|
67
|
+
return [_deserialize_group(group) for group in response.values()]
|
|
68
|
+
|
|
69
|
+
async def get_groups_for_lecturer(
|
|
70
|
+
self,
|
|
71
|
+
user_id: int | None = None,
|
|
72
|
+
active_terms_only: bool = False,
|
|
73
|
+
ongoing_terms_only: bool = False,
|
|
74
|
+
fields: list[str] = None,
|
|
75
|
+
lang: str = "en",
|
|
76
|
+
) -> list[Group]:
|
|
77
|
+
"""
|
|
78
|
+
Get groups for a lecturer.
|
|
79
|
+
|
|
80
|
+
:param user_id: The ID of the lecturer to get groups for, or None to get groups for the current user.
|
|
81
|
+
:param active_terms_only: Whether to only get groups from active terms. Apparently, this parameter does not always work as expected, so you can use `ongoing_terms_only` instead.
|
|
82
|
+
:param ongoing_terms_only: Whether to only get groups from ongoing terms (filtered locally based on start and finish dates).
|
|
83
|
+
:param fields: The fields to include in the response.
|
|
84
|
+
:param lang: Either pl or en - resulting list of groups will be sorted by the course name in the specified language.
|
|
85
|
+
:return: A dictionary with the following fields: 'groups' (list of groups) and 'terms' (list of terms).
|
|
86
|
+
"""
|
|
87
|
+
if not fields:
|
|
88
|
+
fields = ["course_unit_id", "group_number", "course_name"]
|
|
89
|
+
if "term_id" not in fields:
|
|
90
|
+
fields.append("term_id")
|
|
91
|
+
if active_terms_only and ongoing_terms_only:
|
|
92
|
+
self.logger.warning(
|
|
93
|
+
"Both active_terms_only and ongoing_terms_only are set to True. It is recommended to use only one of them."
|
|
94
|
+
)
|
|
95
|
+
fields = "|".join(fields)
|
|
96
|
+
response = await self.connection.post(
|
|
97
|
+
"services/groups/lecturer",
|
|
98
|
+
user_id=user_id,
|
|
99
|
+
active_terms=active_terms_only,
|
|
100
|
+
fields=fields,
|
|
101
|
+
lang=lang,
|
|
102
|
+
)
|
|
103
|
+
terms = [_deserialize_term(term) for term in response["terms"]]
|
|
104
|
+
if ongoing_terms_only:
|
|
105
|
+
terms = _filter_ongoing_terms(terms)
|
|
106
|
+
term_ids = set(term.id for term in terms)
|
|
107
|
+
return [
|
|
108
|
+
_deserialize_group(group)
|
|
109
|
+
for term_id, groups in response["groups"].items()
|
|
110
|
+
if term_id in term_ids
|
|
111
|
+
for group in groups
|
|
112
|
+
]
|
|
113
|
+
|
|
114
|
+
async def get_groups_for_participant(
|
|
115
|
+
self,
|
|
116
|
+
user_id: int | None = None,
|
|
117
|
+
active_terms_only: bool = False,
|
|
118
|
+
ongoing_terms_only: bool = False,
|
|
119
|
+
fields: list[str] = None,
|
|
120
|
+
lang: str = "en",
|
|
121
|
+
) -> list[Group]:
|
|
122
|
+
"""
|
|
123
|
+
Get groups for a participant.
|
|
124
|
+
|
|
125
|
+
:param user_id: The ID of the participant to get groups for, or None to get groups for the current user.
|
|
126
|
+
:param active_terms_only: Whether to only get groups from active terms. Apparently, this parameter does not always work as expected, so you can use `ongoing_terms_only` instead.
|
|
127
|
+
:param ongoing_terms_only: Whether to only get groups from ongoing terms (filtered locally based on start and finish dates).
|
|
128
|
+
:param fields: The fields to include in the response.
|
|
129
|
+
:param lang: Either pl or en - resulting list of groups will be sorted by the course name in the specified language.
|
|
130
|
+
:return: A dictionary with the following fields: 'groups' (list of groups) and 'terms' (list of terms).
|
|
131
|
+
"""
|
|
132
|
+
if not fields:
|
|
133
|
+
fields = ["course_unit_id", "group_number", "course_name", "term_id"]
|
|
134
|
+
if "term_id" not in fields:
|
|
135
|
+
fields.append("term_id")
|
|
136
|
+
if active_terms_only and ongoing_terms_only:
|
|
137
|
+
self.logger.warning(
|
|
138
|
+
"Both active_terms_only and ongoing_terms_only are set to True. It is recommended to use only one of them."
|
|
139
|
+
)
|
|
140
|
+
fields = "|".join(fields)
|
|
141
|
+
response = await self.connection.post(
|
|
142
|
+
"services/groups/participant",
|
|
143
|
+
user_id=user_id,
|
|
144
|
+
active_terms=active_terms_only,
|
|
145
|
+
fields=fields,
|
|
146
|
+
lang=lang,
|
|
147
|
+
)
|
|
148
|
+
terms = [_deserialize_term(term) for term in response["terms"]]
|
|
149
|
+
if ongoing_terms_only:
|
|
150
|
+
terms = _filter_ongoing_terms(terms)
|
|
151
|
+
term_ids = set(term.id for term in terms)
|
|
152
|
+
return [
|
|
153
|
+
_deserialize_group(group, term_id=term_id)
|
|
154
|
+
for term_id, groups in response["groups"].items()
|
|
155
|
+
if term_id in term_ids
|
|
156
|
+
for group in groups
|
|
157
|
+
]
|
|
158
|
+
|
|
159
|
+
async def get_groups_for_user(
|
|
160
|
+
self,
|
|
161
|
+
user_id: int | None = None,
|
|
162
|
+
active_terms_only: bool = False,
|
|
163
|
+
ongoing_terms_only: bool = False,
|
|
164
|
+
fields: list[str] = None,
|
|
165
|
+
lang: str = "en",
|
|
166
|
+
) -> list[Group]:
|
|
167
|
+
"""
|
|
168
|
+
Get groups for a user.
|
|
169
|
+
|
|
170
|
+
:param user_id: The ID of the user to get groups for, or None to get groups for the current user.
|
|
171
|
+
:param active_terms_only: Whether to only get groups from active terms. Apparently, this parameter does not always work as expected, so you can use `ongoing_terms_only` instead.
|
|
172
|
+
:param ongoing_terms_only: Whether to only get groups from ongoing terms (filtered locally based on start and finish dates).
|
|
173
|
+
:param fields: The fields to include in the response.
|
|
174
|
+
:param lang: Either pl or en - resulting list of groups will be sorted by the course name in the specified language.
|
|
175
|
+
:return: A dictionary with the following fields: 'groups' (list of groups) and 'terms' (list of terms).
|
|
176
|
+
"""
|
|
177
|
+
if not fields:
|
|
178
|
+
fields = ["course_unit_id", "group_number", "course_name", "term_id"]
|
|
179
|
+
if "term_id" not in fields:
|
|
180
|
+
fields.append(
|
|
181
|
+
"term_id"
|
|
182
|
+
) # We need term_id to filter out groups from terms that are not ongoing.
|
|
183
|
+
if active_terms_only and ongoing_terms_only:
|
|
184
|
+
self.logger.warning(
|
|
185
|
+
"Both active_terms_only and ongoing_terms_only are set to True. It is recommended to use only one of them."
|
|
186
|
+
)
|
|
187
|
+
fields = "|".join(fields)
|
|
188
|
+
response = await self.connection.post(
|
|
189
|
+
"services/groups/user",
|
|
190
|
+
user_id=user_id,
|
|
191
|
+
active_terms=active_terms_only,
|
|
192
|
+
fields=fields,
|
|
193
|
+
lang=lang,
|
|
194
|
+
)
|
|
195
|
+
terms = [_deserialize_term(term) for term in response["terms"]]
|
|
196
|
+
if ongoing_terms_only:
|
|
197
|
+
terms = _filter_ongoing_terms(terms)
|
|
198
|
+
term_ids = set(term.id for term in terms)
|
|
199
|
+
return [
|
|
200
|
+
_deserialize_group(group, term_id=term_id)
|
|
201
|
+
for term_id, groups in response["groups"].items()
|
|
202
|
+
if term_id in term_ids
|
|
203
|
+
for group in groups
|
|
204
|
+
]
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from ..connection import USOSAPIConnection
|
|
2
|
+
from ..models.user import User
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class UserService:
|
|
6
|
+
"""
|
|
7
|
+
A service for user-related operations.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
def __init__(self, connection: USOSAPIConnection):
|
|
11
|
+
"""
|
|
12
|
+
Initialize the user service.
|
|
13
|
+
|
|
14
|
+
:param connection: The connection to use.
|
|
15
|
+
"""
|
|
16
|
+
self.connection = connection
|
|
17
|
+
|
|
18
|
+
async def get_user(
|
|
19
|
+
self, user_id: int | None = None, fields: list[str] | None = None
|
|
20
|
+
) -> User:
|
|
21
|
+
"""
|
|
22
|
+
Get a user by their ID or the currently authorized user.
|
|
23
|
+
|
|
24
|
+
:param user_id: The ID of the user to get. If None, the currently authorized user will be returned.
|
|
25
|
+
:param fields: The fields to include in the response. Whole list of fields can be found `here <https://apps.usos.pwr.edu.pl/developers/api/services/users/#user>`_.
|
|
26
|
+
:return: The user.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
if fields is None:
|
|
30
|
+
fields = [
|
|
31
|
+
"id",
|
|
32
|
+
"first_name",
|
|
33
|
+
"last_name",
|
|
34
|
+
"email",
|
|
35
|
+
"student_number",
|
|
36
|
+
"student_programmes",
|
|
37
|
+
"student_status",
|
|
38
|
+
"staff_status",
|
|
39
|
+
"has_photo",
|
|
40
|
+
"photo_urls[original]",
|
|
41
|
+
] # Default fields
|
|
42
|
+
fields = "|".join(fields)
|
|
43
|
+
response = await self.connection.post(
|
|
44
|
+
"services/users/user", user_id=user_id, fields=fields
|
|
45
|
+
)
|
|
46
|
+
return self._deserialize_user(response)
|
|
47
|
+
|
|
48
|
+
def _deserialize_user(self, data: dict) -> User:
|
|
49
|
+
return User(**data)
|
|
File without changes
|