-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathtermin_api.py
352 lines (285 loc) · 10.6 KB
/
termin_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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import datetime
import json
import re
import requests
import captcha
class Meta(type):
def __repr__(cls):
return cls.get_name()
class Buro(metaclass=Meta):
"""
Base interface-like class for all departments providing appointments on ...muenchen.de/termin/index.php... page
"""
appointment_types = None
appointment_type_date = None
@classmethod
def get_available_appointment_types(cls):
"""
:return: list of available appointment types
"""
# Cache appointment type results for one day
if cls.appointment_types and (datetime.datetime.now() - cls.appointment_type_date).days < 1:
return cls.appointment_types
response = requests.get(cls.get_frame_url())
# Cut not needed content making search more complicated, we need only part in (after) WEB_APPOINT_CASETYPELIST div
inner_div = \
re.findall('WEB_APPOINT_CASETYPELIST.*', response.content.decode("utf-8"), re.MULTILINE | re.DOTALL)[0]
# Search for text CASETYPES. So far the only issue was in "+" sign for CityHall in some service variable,
# that's why exclude it from the name
cls.appointment_types = re.findall('CASETYPES\[([^+]*?)\]', inner_div)
# Get rid of duplicates
cls.appointment_types = list(set(cls.appointment_types))
cls.appointment_type_date = datetime.datetime.now()
return cls.appointment_types
@staticmethod
def get_frame_url():
"""
:return: URL with appointments form
"""
raise NotImplementedError
@staticmethod
def get_info_message():
"""
:return: Optional text message to be printed before the list of termins
"""
return ''
@staticmethod
def _get_base_page():
"""
:return: actual external web-page containing the frame. Not really needed for implementation, but may be useful
for testing or debugging
"""
raise NotImplementedError
@staticmethod
def get_name():
"""
:return: human-readable name of the buro
"""
raise NotImplementedError
@staticmethod
def get_id():
"""
:return: machine-readable unique ID of the buro
"""
return 'baseburo'
@staticmethod
def get_typical_appointments() -> list:
"""
:return: list of tuples (<Name of appointment>, <index>)
"""
return []
@staticmethod
def get_buro_by_id(buro_id):
for buroClass in Buro.__subclasses__():
if buroClass.get_id() == buro_id:
return buroClass()
return None
class DMV(Buro):
@staticmethod
def get_name():
return 'Führerscheinstelle'
@staticmethod
def _get_base_page():
return 'https://www.muenchen.de/rathaus/terminvereinbarung_fs.html'
@staticmethod
def get_frame_url():
return 'https://terminvereinbarung.muenchen.de/fs/termin/index.php?loc=FS'
@staticmethod
def get_typical_appointments() -> list:
try:
res = []
for i, termin in enumerate(DMV.get_available_appointment_types()):
if 'Umschreibung' in termin or 'Abholung' in termin:
res.append((i, termin))
return res
except IndexError:
print('ERROR: cannot return typical appointments for DMV (most probably the indexes have changed)')
return []
@staticmethod
def get_id():
"""
:return: machine-readable unique ID of the buro
"""
return 'fs'
class CityHall(Buro):
@staticmethod
def get_name():
return 'Bürgerbüro'
@staticmethod
def _get_base_page():
return 'https://www.muenchen.de/rathaus/terminvereinbarung_bb.html'
@staticmethod
def get_frame_url():
return 'https://terminvereinbarung.muenchen.de/bba/termin/'
@staticmethod
def get_typical_appointments() -> list:
try:
res = []
for i, termin in enumerate(CityHall.get_available_appointment_types()):
if 'meldung' in termin:
res.append((i, termin))
return res
except IndexError:
print('ERROR: cannot return typical appointments for CityHall (most probably the indexes have changed)')
return []
@staticmethod
def get_id():
"""
:return: machine-readable unique ID of the buro
"""
return 'bb'
class KFZ(Buro):
@staticmethod
def get_name():
return 'Kfz-Zulassung'
@staticmethod
def _get_base_page():
return 'https://www.muenchen.de/rathaus/terminvereinbarung_kfz.html'
@staticmethod
def get_frame_url():
return 'https://terminvereinbarung.muenchen.de/kfz/termin/'
@staticmethod
def get_typical_appointments() -> list:
try:
res = []
# Initial registration and address change
for i, termin in enumerate(KFZ.get_available_appointment_types()):
if 'Umschreibung' in termin or 'Adress' in termin:
res.append((i, termin))
return res
except IndexError:
print('ERROR: cannot return typical appointments for KFZ (most probably the indexes have changed)')
return []
@staticmethod
def get_id():
"""
:return: machine-readable unique ID of the buro
"""
return 'kfz'
class Pension(Buro):
@staticmethod
def get_name():
return 'Versicherungsamt'
@staticmethod
def get_info_message():
return f'ℹ️ Please note for Wartezeitauskunft there are no appointments available, you must apply online at https://service\.muenchen\.de/intelliform/forms/01/02/02/kontaktformularversicherungsamt/index'
@staticmethod
def _get_base_page():
return 'https://www.muenchen.de/rathaus/terminvereinbarung_va.html'
@staticmethod
def get_frame_url():
return 'https://terminvereinbarung.muenchen.de/va/termin/'
@staticmethod
def get_typical_appointments() -> list:
try:
res = []
# Pension information for NE
for i, termin in enumerate(Pension.get_available_appointment_types()):
if 'Wartezeit' in termin:
res.append((i, termin))
return res
except IndexError:
print('ERROR: cannot return typical appointments for Pension (most probably the indexes have changed)')
return []
@staticmethod
def get_id():
"""
:return: machine-readable unique ID of the buro
"""
return 'va'
class KVR(Buro):
@staticmethod
def get_name():
return 'KVR'
@staticmethod
def _get_base_page():
return 'https://www.muenchen.de/rathaus/terminvereinbarung_kvr.html'
@staticmethod
def get_frame_url():
return 'https://terminvereinbarung.muenchen.de/kvr/termin/?cts=1064437'
@staticmethod
def get_typical_appointments() -> list:
try:
res = []
for index in [0]:
res.append((index, KVR.get_available_appointment_types()[index]))
return res
except IndexError:
print('ERROR: cannot return typical appointments for Pension (most probably the indexes have changed)')
return []
@staticmethod
def get_id():
"""
:return: machine-readable unique ID of the buro
"""
return 'kvr'
class ForeignLabor(Buro):
@staticmethod
def get_name():
return '❌ Ausländerbehörde'
@staticmethod
def get_info_message():
return '❌ Please note Ausländerbehörde does not have online Termin bookings any more\. You need to file application online for [Blue Card](https://stadt.muenchen.de/service/info/hauptabteilung-ii-buergerangelegenheiten/1080627/) or for [Niederlassungserlaubnis](https://stadt.muenchen.de/service/info/hauptabteilung-ii-buergerangelegenheiten/1080810/)'
def write_response_to_log(txt):
with open('log.txt', 'w', encoding='utf-8') as f:
f.write(txt)
def get_termins(buro, termin_type):
"""
Get available appointments in the given buro for the given appointment type.
:param buro: Buro to search in
:param termin_type: what type of appointment do you want to find?
:return: dictionary of appointments, keys are possible dates, values are lists of available times
"""
# Session is required to keep cookies between requests
s = requests.Session()
# First request to get and save cookies
first_page = s.post(buro.get_frame_url())
try:
token = re.search('FRM_CASETYPES_token" value="(.*?)"', first_page.text).group(1)
except AttributeError:
token = None
captcha_response = s.get('https://terminvereinbarung.muenchen.de/bba/securimage/securimage_play.php')
code = captcha.solve_captcha(captcha_response.content)
termin_data = {
f'CASETYPES[{termin_type}]': 1,
'step': 'WEB_APPOINT_SEARCH_BY_CASETYPES',
'FRM_CASETYPES_token': token,
'captcha_code': code,
}
response = s.post(buro.get_frame_url(), termin_data)
txt = response.text
try:
json_str = re.search('jsonAppoints = \'(.*?)\'', txt).group(1)
except AttributeError:
print('ERROR: cannot find termins data in server\'s response. See log.txt for raw text')
write_response_to_log(txt)
return None
appointments = json.loads(json_str)
# We expect structure of this JSON should be like this:
# {
# 'Place ID 1': {
# # Address
# 'caption': 'F\u00fchrerscheinstelle Garmischer Str. 19/21',
# # Some internal ID
# 'id': 'a6a84abc3c8666ca80a3655eef15bade',
# # Dictionary containing data about appointments
# 'appoints': {
# '2019-01-25': ['09:05', '09:30'],
# '2019-01-26': []
# # ...
# }
# }
# }
# So there can be several Buros located in different places in the city
return appointments
if __name__ == '__main__':
# Example for exchanging driver license
appointments = get_termins(DMV, 'FS Umschreibung Ausländischer FS')
# # Example for Anmeldung
# appointments = get_termins(CityHall, 'An- oder Ummeldung - Einzelperson')
# # Example for NE with Blue Card
# appointments = get_termins(ForeignLabor, 'Werkverträge')
# # Example for KFZ and car registration
# appointments = get_termins(KFZ, 'ZUL Fabrikneues Fahrzeug')
if appointments:
print(json.dumps(appointments, sort_keys=True, indent=4, separators=(',', ': ')))