-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
311 lines (240 loc) · 9.31 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import threading
import requests
import urllib.parse
from datetime import datetime
import logger
class Appointment:
def __init__(self, raw: dict):
# TODO: be able to choose from optional classes
self.valid = True
if 'subjects' not in raw:
self.valid = False
return
else:
self.subjects = raw['subjects']
# groups, locations, teachers, cancelled, online, start, end
if 'groups' not in raw:
self.valid = False
return
else:
self.groups = raw['groups']
if 'locations' not in raw:
self.valid = False
return
else:
self.locations = raw['locations']
if 'teachers' not in raw:
self.valid = False
return
else:
self.teachers = raw['teachers']
if 'cancelled' not in raw:
self.valid = False
return
else:
self.cancelled = raw['cancelled']
if 'online' not in raw:
self.valid = False
return
else:
self.online = raw['online']
if self.online:
logger.warn('Online classes are not supported!')
if 'start' not in raw:
self.valid = False
return
else:
# time = datetime.fromtimestamp(int(raw['start'])).strftime('%j %H:%M:%S').split(' ')
# self.start = (int(time[0]), [int(t) for t in time[1].split(':')])
self.start = datetime.fromtimestamp(raw['start'])
if 'end' not in raw:
self.valid = False
return
else:
# time = datetime.fromtimestamp(int(raw['end'])).strftime('%j %H:%M:%S').split(' ')
# self.end = (int(time[0]), [int(t) for t in time[1].split(':')])
self.end = datetime.fromtimestamp(raw['end'])
if 'optional' not in raw:
self.valid = False
return
else:
self.optional = raw['optional']
if 'actions' not in raw:
return
else:
if len(raw['actions']) > 0:
self.optional = True # TODO
self.options = []
for option in raw['actions']:
self.options.append(Appointment(option['appointment']))
# if 'attendanceOverruled' not in raw:
# self.valid = False
# return
# else:
# self.attendance_overruled = raw['attendanceOverruled']
# plannedAttendance
# studentEnrolled
# post
# TODO: make subject be schedulerRemark if 'nd' in subjects
class Week:
def __init__(self, raw: dict, week: int):
self.week = week
self.raw = raw
self.valid = True
self.appointments = []
if 'response' not in self.raw:
logger.warn('No response?')
self.valid = False
return
if 'data' not in self.raw['response']:
logger.warn('No response data?')
self.valid = False # TODO: still renders if not valid
if len(self.raw['response']['data']) != 1:
raise NotImplementedError('Multiple weeks in one week')
week = self.raw['response']['data'][0]
if 'appointments' not in week:
logger.warn('No appointments in this week found!')
self.valid = False
return
for appointment in week['appointments']:
self.appointments.append(Appointment(appointment))
class Api:
def __init__(self, username, password, tenant):
self.username = username
self.password = password
self.tenant = tenant
self.zportal_url = f'https://{self.tenant}.zportal.nl'
self.api_url = f'{self.zportal_url}/api/v3/'
self.state = 0
self.max_state = 3
self.successfull = True
self.credentials_correct = True
self.queue = []
self.busy = False
self.weeks = {}
self.t = threading.Thread(target=self._bootstrap)
self.t.start()
def _bootstrap(self):
r = requests.get(self.api_url + 'oauth')
# print(r.status_code)
if r.status_code != 200:
self.successfull = False
logger.error(f"Invalid response code {r.status_code}: {r.content.decode('utf-8')}")
return
self.jar = r.cookies
content = r.content.decode('utf-8')
redirect_search = '<input name="redirect_uri" type="hidden" value='
redirect_index = content.find(redirect_search)
redirect = ''
i = redirect_index + len(redirect_search) + 1
while content[i] != '"':
redirect += content[i]
i += 1
state_search = '<input name="state" type="hidden" value='
state_index = content.find(state_search)
state = ''
i = state_index + len(state_search) + 1
while content[i] != '"':
state += content[i]
i += 1
self.state += 1
r = requests.post(self.api_url + 'oauth', data={
'username': self.username,
'password': self.password,
'client_id': 'OAuthPage',
'redirect_uri': redirect,
'scope': '',
'state': state,
'response_type': 'code',
'tenant': 'ig'
}, cookies=self.jar)
# print(r.status_code)
if r.status_code != 200:
self.successfull = False
logger.error(f"Invalid response code {r.status_code}: {r.content.decode('utf-8')}")
return
content = r.content.decode('utf-8')
path_search = '<a href='
path_index = content.find(path_search)
path = ''
i = path_index + len(path_search) + 1
while content[i] != '"':
path += content[i]
i += 1
parsed_path = urllib.parse.parse_qs(urllib.parse.urlparse(path).query)
if 'code' not in parsed_path:
self.credentials_correct = False
self.successfull = False
return
if len(parsed_path['code']) != 1:
raise NotImplementedError('Multiple codes are not supported.')
code = parsed_path['code'][0]
if len(parsed_path['interfaceVersion']) != 1:
logger.warn('Multiple versions found! This is not a good thing')
if parsed_path['interfaceVersion'][0] != '23.03j57':
logger.warn(f"Unsupported interfaceVersion {parsed_path['interfaceVersion'][0]} found. Only version 23.03j57 is currently supported.")
if len(parsed_path['tenant']) != 1:
logger.warn('Multiple tenants???')
if parsed_path['tenant'][0] != self.tenant:
logger.warn(f'Tenant {self.tenant} not {parsed_path["tenant"][0]}')
self.state += 1
r = requests.post(self.api_url + 'oauth/token', cookies=self.jar, data={
'code': code,
'client_id': 'ZermeloPortal',
'client_secret': 42, # TODO: ??
'grant_type': 'authorization_code',
'rememberMe': 'false'
})
# print(r.status_code)
if r.status_code != 200:
self.successfull = False
logger.error(f"Invalid response code {r.status_code}: {r.content.decode('utf-8')}")
return
token_raw = r.json()
self.token = token_raw['access_token']
if token_raw['token_type'] != 'bearer':
logger.warn(f"Unsupported token type: {token_raw['token_raw']}")
self.state += 1
self.busy = False
def update(self):
if self.t.is_alive():
return
if not self.busy:
self.t.join()
if len(self.queue) > 0:
self.t = threading.Thread(target=self._get, args=[self.queue.pop(0)])
self.t.start()
self.busy = True
def get(self, week):
# print(f'get {week} in? {week in self.weeks} busy? {self.busy}')
if week in self.weeks:
return self.weeks[week]
if self.busy or self.t.is_alive():
if week in self.queue or week in self.weeks:
return
self.queue.append(week)
return None # TODO: store empty week
self.t = threading.Thread(target=self._get, args=[week])
self.t.start()
return None
def _get(self, week):
self.busy = True
url = self.api_url + 'liveschedule?' + urllib.parse.urlencode({
'student': self.username,
'week': str(week),
'fields': 'appointmentInstance,start,end,startTimeSlotName,endTimeSlotName,subjects,groups,locations,teachers,cancelled,changeDescription,schedulerRemark,content,appointmentType,creator'
})
r = requests.get(url, cookies=self.jar, auth=('Bearer', self.token))
# print(r.status_code)
if r.status_code != 200:
self.busy = False
logger.error(f"Invalid response code {r.status_code}: requesting week {int(week)} {url} -> {r.content.decode('utf-8')}")
return
try:
self.weeks[week] = Week(r.json(), week)
# print(r.json())
except requests.exceptions.JSONDecodeError as e:
logger.error(str(e))
logger.error(url)
self.busy = False
return