-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuntis_sync_improved.py
More file actions
705 lines (581 loc) · 29 KB
/
untis_sync_improved.py
File metadata and controls
705 lines (581 loc) · 29 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
#!/usr/bin/env python3
"""
Verbessertes WebUntis zu Google Calendar Sync
- Unterstützt mehrere Wochen
- Automatische Extraktion direkt aus dem Browser
- Duplikat-Erkennung
"""
import json
import re
from datetime import datetime, timedelta
from typing import List, Dict, Optional
import os
import pickle
import holidays
from pathlib import Path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import hashlib
SCOPES = ['https://www.googleapis.com/auth/calendar']
class UntisLesson:
"""Repräsentiert eine einzelne Unterrichtsstunde"""
def __init__(self, start_time: str, end_time: str, subject: str,
teacher: str, room: str, date: str):
self.start_time = start_time
self.end_time = end_time
self.subject = subject
self.teacher = teacher
self.room = room
self.date = date
# Erstelle eine eindeutige ID für Duplikat-Erkennung
self.uid = self._generate_uid()
def _generate_uid(self) -> str:
"""Generiert eine eindeutige ID für diese Lesson"""
# Normalisiere Raum: entferne Raumänderungen aber behalte Hauptraum
# "+O1101, O1104" -> "O1104" (nimm zweiten wenn erster mit + beginnt)
# "O1027, +O1101, +O1102" -> "O1027" (nimm ersten)
# "N/A" -> "N/A"
room_parts = [r.strip() for r in self.room.split(',')]
# Filter: Nimm ersten Raum der NICHT mit + beginnt
room_normalized = None
for part in room_parts:
clean_part = part.lstrip('+').strip()
if clean_part and clean_part != 'N/A':
room_normalized = clean_part
break
# Fallback auf originalen Raum wenn nichts gefunden
if not room_normalized:
room_normalized = room_parts[0].lstrip('+').strip() if room_parts else self.room
data = f"{self.date}_{self.start_time}_{self.end_time}_{self.subject}_{room_normalized}"
return hashlib.md5(data.encode()).hexdigest()[:16]
def __repr__(self):
return f"Lesson({self.date} {self.start_time}-{self.end_time}: {self.subject} @ {self.room})"
def to_dict(self):
result = {
'uid': self.uid,
'date': self.date,
'start_time': self.start_time,
'end_time': self.end_time,
'subject': self.subject,
'teacher': self.teacher,
'room': self.room
}
# Füge Notiz hinzu falls vorhanden
if hasattr(self, 'note') and self.note:
result['note'] = self.note
return result
class ImprovedUntisParser:
"""Verbesserter Parser der mehrere Tage/Wochen unterstützt"""
def __init__(self, json_file: str, bundesland: str = 'BY'):
with open(json_file, 'r', encoding='utf-8') as f:
self.data = json.load(f)
self.base_date = self._extract_date_from_url()
# Initialisiere deutsche Feiertage für das entsprechende Bundesland
year = int(self.base_date[:4])
self.holidays = holidays.Germany(years=year, prov=bundesland)
# Lade manuelle schulfreie Tage
custom_holidays_file = Path(__file__).parent / 'school_holidays.json'
if custom_holidays_file.exists():
with open(custom_holidays_file, 'r', encoding='utf-8') as f:
custom_data = json.load(f)
for date_str in custom_data.get('custom_holidays', []):
date_obj = datetime.strptime(date_str, '%Y-%m-%d').date()
self.holidays[date_obj] = 'Schulfrei (manuell konfiguriert)'
print(f" → {len(custom_data.get('custom_holidays', []))} manuelle schulfreie Tage geladen")
print(f" → Feiertage geladen für {bundesland} {year} + manuelle Einträge")
def _extract_date_from_url(self) -> str:
"""Extrahiert das Datum aus der URL"""
url = self.data['timetable']['url']
match = re.search(r'date=(\d{4}-\d{2}-\d{2})', url)
if match:
return match.group(1)
return datetime.now().strftime('%Y-%m-%d')
def parse_lessons(self) -> List[UntisLesson]:
"""Parst alle Lessons - erkennt Wochentage durch Zeit-Resets"""
lessons = []
raw_lessons = self.data['timetable']['lessons']
print(f"Analysiere {len(raw_lessons)} Einträge...")
print(f"Basis-Datum aus URL: {self.base_date}")
# Versuche die Wochenstruktur zu erkennen
# Montag des base_date ermitteln (Wochenanfang)
base = datetime.strptime(self.base_date, '%Y-%m-%d')
# Finde den Montag dieser Woche
days_since_monday = base.weekday() # 0=Monday, 6=Sunday
week_start = base - timedelta(days=days_since_monday)
# NEUE STRATEGIE: Gruppiere Lessons nach Tagen
# Sammle erst alle Lessons mit ihrer Zeit
lesson_groups = [] # [(index, start_time), ...]
for i, lesson in enumerate(raw_lessons):
class_name = lesson.get('className', '')
text = lesson.get('text', '').strip()
if 'lesson-card ' in class_name or class_name.startswith('lesson-card '):
time_match = re.search(r'(\d{2}):(\d{2})', text)
if time_match:
start_time = f"{time_match.group(1)}:{time_match.group(2)}"
lesson_groups.append((i, start_time))
# Erkenne Tagwechsel durch Zeit-Rücksprünge
day_boundaries = [0] # Erste Lesson ist immer Start von Tag 0
for idx, (i, time) in enumerate(lesson_groups[1:], start=1):
prev_time = lesson_groups[idx-1][1]
if time < prev_time: # Zeit springt zurück = neuer Tag
day_boundaries.append(idx)
print(f" → Erkannte Tagesgrenzen bei Lesson-Indices: {day_boundaries}")
print(f" → Das entspricht {len(day_boundaries)} Tagen in den Daten")
# Zähle Lessons pro Tag-Block um fehlende Tage zu erkennen
day_lesson_counts = []
for day_idx, boundary_start in enumerate(day_boundaries):
if day_idx < len(day_boundaries) - 1:
boundary_end = day_boundaries[day_idx + 1]
else:
boundary_end = len(lesson_groups)
lesson_count = boundary_end - boundary_start
day_lesson_counts.append(lesson_count)
print(f" → Lessons pro Tag: {day_lesson_counts}")
# INTELLIGENTE FEIERTAGS-ERKENNUNG
# Prüfe welche Wochentage in dieser Woche Feiertage sind
num_days_detected = len(day_boundaries)
# Erstelle Liste aller Wochentage (Mo-Fr = 0-4)
all_weekdays = list(range(5)) # [0, 1, 2, 3, 4]
# Prüfe welche Tage Feiertage sind
holiday_weekdays = []
for weekday in range(5): # Mo-Fr
date = week_start + timedelta(days=weekday)
if date in self.holidays:
holiday_name = self.holidays.get(date)
print(f" 🎊 Feiertag erkannt: {date.strftime('%Y-%m-%d')} ({['Mo','Di','Mi','Do','Fr'][weekday]}) = {holiday_name}")
holiday_weekdays.append(weekday)
# Berechne welche Tage Schultage sind (ohne Feiertage)
school_days = [d for d in all_weekdays if d not in holiday_weekdays]
expected_days = len(school_days)
print(f" → Erwartete Schultage: {expected_days} (ohne {len(holiday_weekdays)} Feiertage)")
# Mapping: Welcher Tag-Index gehört zu welchem Wochentag?
if num_days_detected == expected_days:
# Perfekt: Anzahl passt
weekday_mapping = school_days
print(f" ✓ Mapping: {num_days_detected} Tage → {[['Mo','Di','Mi','Do','Fr'][w] for w in weekday_mapping]}")
elif num_days_detected < expected_days:
# Weniger Tage als erwartet - nimm die ersten N Schultage
weekday_mapping = school_days[:num_days_detected]
print(f" ⚠ Nur {num_days_detected} Tage erkannt, erwartet {expected_days}")
print(f" → Mapping: {[['Mo','Di','Mi','Do','Fr'][w] for w in weekday_mapping]}")
else:
# Mehr Tage als erwartet - sollte nicht passieren, aber fallback
print(f" ⚠ Mehr Tage ({num_days_detected}) als erwartet ({expected_days})!")
weekday_mapping = list(range(num_days_detected))
# Weise jedem Lesson-Index den richtigen Wochentag zu
lesson_to_weekday = {}
for day_idx, boundary_start in enumerate(day_boundaries):
if day_idx < len(day_boundaries) - 1:
boundary_end = day_boundaries[day_idx + 1]
else:
boundary_end = len(lesson_groups)
lesson_count = boundary_end - boundary_start
actual_weekday = weekday_mapping[day_idx]
weekday_name = ['Mo','Di','Mi','Do','Fr','Sa','So'][actual_weekday]
# Weise alle Lessons in diesem Block zum richtigen Wochentag zu
for lesson_idx in range(boundary_start, boundary_end):
actual_index = lesson_groups[lesson_idx][0]
lesson_to_weekday[actual_index] = actual_weekday
print(f" → Tag-Block {day_idx} ({lesson_count} Lessons) → Wochentag {actual_weekday} ({weekday_name})")
# Parse alle Lessons mit dem richtigen Wochentag
i = 0
while i < len(raw_lessons):
lesson = raw_lessons[i]
class_name = lesson.get('className', '')
if 'lesson-card ' in class_name or class_name.startswith('lesson-card '):
if i in lesson_to_weekday:
weekday = lesson_to_weekday[i]
parsed = self._parse_lesson_card(raw_lessons, i, week_start, weekday)
if parsed:
lessons.append(parsed)
print(f" ✓ {parsed.date} ({datetime.strptime(parsed.date, '%Y-%m-%d').strftime('%A')}): {parsed.start_time}-{parsed.end_time} {parsed.subject} @ {parsed.room}")
i += 1
# Sortiere nach Datum und Zeit
lessons.sort(key=lambda l: (l.date, l.start_time))
# Zähle eindeutige Tage
unique_days = len(set(l.date for l in lessons))
print(f"\n✓ {len(lessons)} Lessons über {unique_days} Tage gefunden")
return lessons
def _parse_lesson_card(self, lessons_list: List[Dict], start_index: int, week_start: datetime, weekday: int) -> Optional[UntisLesson]:
"""Parst eine einzelne Lesson-Card"""
try:
# Berechne das echte Datum basierend auf Wochentag
# week_start ist Montag, weekday 0=Mo, 1=Di, 2=Mi, ...
lesson_date = week_start + timedelta(days=weekday)
lesson_date_str = lesson_date.strftime('%Y-%m-%d')
main_text = lessons_list[start_index].get('text', '').strip()
# Extrahiere Zeiten
time_pattern = r'(\d{2}):(\d{2})'
times = re.findall(time_pattern, main_text)
if len(times) < 2:
return None
start_time = f"{times[0][0]}:{times[0][1]}"
end_time = f"{times[1][0]}:{times[1][1]}"
# Extrahiere Komponenten
teacher = None
subject = None
room = None
note = None # Für Hinweise wie "Klassenarbeit"
for i in range(start_index, min(start_index + 35, len(lessons_list))):
item = lessons_list[i]
text = item.get('text', '').strip()
dataset = item.get('dataset', {})
testid = dataset.get('testid', '')
# Lehrer
if 'lesson-card-resources-with-change-teachers' in testid:
if not teacher: # Nur setzen wenn noch nicht gesetzt
for j in range(i, min(i + 3, len(lessons_list))):
next_text = lessons_list[j].get('text', '').strip()
if next_text and len(next_text) < 20 and not ':' in next_text:
teacher = next_text
break
# Fach
elif 'lesson-card-subject' in testid or testid == 'lesson-card-subjects':
if not subject: # Nur setzen wenn noch nicht gesetzt
for j in range(i, min(i + 3, len(lessons_list))):
next_text = lessons_list[j].get('text', '').strip()
if next_text and len(next_text) < 20 and not ':' in next_text:
subject = next_text
break
# Raum (WICHTIG: hat Priorität vor Notizen)
elif 'lesson-card-resources-with-change-rooms' in testid:
if not room: # Nur setzen wenn noch nicht gesetzt
for j in range(i, min(i + 3, len(lessons_list))):
next_text = lessons_list[j].get('text', '').strip()
# Prüfe ob es wie ein Raum aussieht (O + Zahlen)
if next_text and re.match(r'O\d{3,4}', next_text):
room = next_text
break
# Hinweis/Notiz (z.B. "Klassenarbeit Lit") - NACH Raum-Check!
elif 'lesson-card-text-content-container' in testid:
if not note: # Nur setzen wenn noch nicht gesetzt
for j in range(i, min(i + 3, len(lessons_list))):
next_text = lessons_list[j].get('text', '').strip()
# Nur als Notiz nehmen wenn es NICHT wie ein Raum aussieht
if next_text and len(next_text) < 50 and not ':' in next_text:
if not re.match(r'O\d{3,4}', next_text):
note = next_text
break
# Stop bei nächster lesson-card
class_name = item.get('className', '')
if i > start_index and 'lesson-card' in class_name and 'lesson-card-' not in class_name:
break
# Fallback: Versuche Raum aus main_text zu extrahieren wenn nicht gefunden
if not room or room == 'N/A':
# Pattern: Nach Lehrername und Fach kommt Raumnummer
# "12:5014:20FayKLitO1027, +O1101, +O1102+2"
# Entferne Zeiten und suche nach O + Zahlen
room_match = re.search(r'(O\d{3,4}(?:,\s*\+O\d{3,4})*)', main_text)
if room_match:
room = room_match.group(1)
if start_time and end_time:
# Wenn wir einen Hinweis haben, füge ihn zur Beschreibung hinzu aber nicht zum Raum
final_room = room or 'N/A'
# Erstelle Lesson mit optionalem Hinweis
lesson = UntisLesson(
start_time=start_time,
end_time=end_time,
subject=subject or 'Unbekannt',
teacher=teacher or 'N/A',
room=final_room,
date=lesson_date_str
)
# Füge Hinweis als Attribut hinzu (für spätere Nutzung)
if note:
lesson.note = note
return lesson
except Exception as e:
print(f" ⚠ Fehler: {e}")
return None
class GoogleCalendarSync:
"""Synchronisiert mit Google Calendar - mit Duplikat-Erkennung"""
def __init__(self, calendar_id: str = 'primary'):
self.calendar_id = calendar_id
self.service = self._authenticate()
self.existing_events = self._load_existing_events()
def _authenticate(self):
"""Authentifiziere mit Google Calendar API"""
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return build('calendar', 'v3', credentials=creds)
def _load_existing_events(self) -> Dict[str, str]:
"""Lade existierende Events um Duplikate zu vermeiden"""
existing_by_uid = {}
existing_by_signature = {}
try:
# Hole Events - erweitere den Zeitraum und erhöhe das Limit
now = datetime.utcnow()
# Gehe 7 Tage zurück (falls alte Events vorhanden)
time_min = (now - timedelta(days=7)).isoformat() + 'Z'
time_max = (now + timedelta(days=90)).isoformat() + 'Z'
print(" 🔍 Lade existierende Events...")
all_events = []
page_token = None
# Paginate durch ALLE Events (nicht nur erste 1000)
while True:
events_result = self.service.events().list(
calendarId=self.calendar_id,
timeMin=time_min,
timeMax=time_max,
maxResults=2500, # Maximum pro Request
singleEvents=True,
orderBy='startTime',
pageToken=page_token
).execute()
events = events_result.get('items', [])
all_events.extend(events)
page_token = events_result.get('nextPageToken')
if not page_token:
break
print(f" 📊 {len(all_events)} Events im Zeitraum gefunden")
# Filtere nur Events die wie Untis-Events aussehen
untis_count = 0
for event in all_events:
summary = event.get('summary', '')
location = event.get('location', '')
# Prüfe ob es ein Untis-Event sein könnte
# Kriterien: Kurzer Name (< 10 Zeichen) UND Raum-Pattern (O + Zahlen)
is_short_name = len(summary) <= 10
has_room_pattern = location and (
location.startswith('O') and any(c.isdigit() for c in location)
)
# Nur Events die beides haben sind wahrscheinlich Untis-Events
if not (is_short_name and has_room_pattern):
continue
untis_count += 1
# Methode 1: Per untis_uid
extended = event.get('extendedProperties', {}).get('private', {})
uid = extended.get('untis_uid')
if uid:
existing_by_uid[uid] = event['id']
# Methode 2: Per Signatur
try:
start = event['start'].get('dateTime', event['start'].get('date'))
if 'T' in start:
# Parse als datetime
if start.endswith('Z'):
dt = datetime.fromisoformat(start.replace('Z', '+00:00'))
else:
dt = datetime.fromisoformat(start)
date_str = dt.strftime('%Y-%m-%d')
time_str = dt.strftime('%H:%M')
# Erstelle Signatur: Datum_Zeit_Fach_Raum
signature = f"{date_str}_{time_str}_{summary}_{location}"
existing_by_signature[signature] = event['id']
except Exception as e:
print(f" ⚠ Fehler beim Parsen von Event: {e}")
print(f" ✓ {untis_count} Untis-Events erkannt")
print(f" - {len(existing_by_uid)} mit UID")
print(f" - {len(existing_by_signature)} mit Signatur")
except Exception as e:
print(f" ⚠ Fehler beim Laden: {e}")
import traceback
traceback.print_exc()
return {
'by_uid': existing_by_uid,
'by_signature': existing_by_signature
}
def create_event(self, lesson: UntisLesson, skip_duplicates: bool = True) -> Optional[str]:
"""Erstellt ein Event - mit verbesserter Duplikat-Prüfung"""
try:
# Prüfe auf Duplikate - Methode 1: Per UID
if skip_duplicates and lesson.uid in self.existing_events['by_uid']:
return 'DUPLICATE_UID'
start_datetime = datetime.strptime(
f"{lesson.date} {lesson.start_time}",
"%Y-%m-%d %H:%M"
)
end_datetime = datetime.strptime(
f"{lesson.date} {lesson.end_time}",
"%Y-%m-%d %H:%M"
)
# Prüfe auf Duplikate - Methode 2: Per Signatur
# Normalisiere Raum genauso wie für UID
room_parts = [r.strip() for r in lesson.room.split(',')]
room_normalized = None
for part in room_parts:
clean_part = part.lstrip('+').strip()
if clean_part and clean_part != 'N/A':
room_normalized = clean_part
break
if not room_normalized:
room_normalized = room_parts[0].lstrip('+').strip() if room_parts else lesson.room
signature = f"{lesson.date}_{lesson.start_time}_{lesson.subject}_{room_normalized}"
if skip_duplicates and signature in self.existing_events['by_signature']:
return 'DUPLICATE_SIG'
# Erstelle Beschreibung mit optionaler Notiz
description_parts = [f'Lehrer: {lesson.teacher}', f'Raum: {lesson.room}']
if hasattr(lesson, 'note') and lesson.note:
description_parts.append(f'📝 {lesson.note}')
description = '\n'.join(description_parts)
event = {
'summary': lesson.subject,
'location': lesson.room,
'description': description,
'start': {
'dateTime': start_datetime.isoformat(),
'timeZone': 'Europe/Berlin',
},
'end': {
'dateTime': end_datetime.isoformat(),
'timeZone': 'Europe/Berlin',
},
'colorId': '6', # Orange (passend zu Untis)
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'popup', 'minutes': 10},
],
},
'extendedProperties': {
'private': {
'untis_uid': lesson.uid,
'untis_source': 'automated_sync'
}
}
}
event_result = self.service.events().insert(
calendarId=self.calendar_id,
body=event
).execute()
# Speichere in existierenden Events (WICHTIG!)
event_id = event_result.get('id')
self.existing_events['by_uid'][lesson.uid] = event_id
self.existing_events['by_signature'][signature] = event_id
return event_id
except HttpError as error:
print(f' ✗ HTTP Error: {error}')
return None
def sync_lessons(self, lessons: List[UntisLesson], dry_run: bool = False):
"""Synchronisiert alle Lessons"""
print(f"\n{'='*60}")
print(f"Synchronisiere {len(lessons)} Lessons...")
print(f"{'='*60}\n")
created = 0
duplicates = 0
failed = 0
for i, lesson in enumerate(lessons, 1):
print(f"[{i}/{len(lessons)}] {lesson.date} {lesson.subject} ({lesson.start_time}-{lesson.end_time}) @ {lesson.room}", end='')
if dry_run:
print(" ✓ (Dry-Run)")
created += 1
else:
result = self.create_event(lesson)
if result in ['DUPLICATE_UID', 'DUPLICATE_SIG']:
print(" ⊘ (Duplikat)")
duplicates += 1
elif result:
print(" ✓")
created += 1
else:
print(" ✗")
failed += 1
print(f"\n{'='*60}")
print(f"✓ Neu erstellt: {created}")
if duplicates > 0:
print(f"⊘ Übersprungen (Duplikate): {duplicates}")
if failed > 0:
print(f"✗ Fehlgeschlagen: {failed}")
print(f"{'='*60}\n")
def sync_lessons_silent(self, lessons: List[UntisLesson]) -> tuple:
"""Synchronisiert Lessons ohne viel Output (für Automatisierung)"""
created = 0
duplicates = 0
failed = 0
for lesson in lessons:
result = self.create_event(lesson)
if result in ['DUPLICATE_UID', 'DUPLICATE_SIG']:
duplicates += 1
elif result:
created += 1
else:
failed += 1
return (created, duplicates, failed)
def main():
"""Hauptprogramm"""
print("="*60)
print("📅 WebUntis zu Google Calendar Sync (Verbessert)")
print("="*60 + "\n")
json_file = 'manual_data.json'
if not os.path.exists(json_file):
print(f"❌ {json_file} nicht gefunden!\n")
print("📋 ANLEITUNG: Daten aus WebUntis extrahieren\n")
print("1. Öffne WebUntis und gehe zu einer WOCHE deines Stundenplans")
print("2. Drücke F12 → Console")
print("3. Kopiere diesen Code:\n")
print("""
const data = {localStorage: {}, timetable: {url: window.location.href, lessons: []}};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
data.localStorage[key] = localStorage.getItem(key);
}
const selectors = ['div[class*="lesson"]'];
for (const selector of selectors) {
const elements = document.querySelectorAll(selector);
if (elements.length > 0) {
elements.forEach((el, i) => {
data.timetable.lessons.push({
index: i, text: el.textContent.trim(),
html: el.innerHTML.substring(0, 300),
className: el.className, dataset: {...el.dataset}
});
});
break;
}
}
copy(JSON.stringify(data, null, 2));
console.log('✓ Kopiert! Füge in manual_data.json ein');
""")
print("\n4. Füge die kopierten Daten in 'manual_data.json' ein")
print("5. Führe das Script erneut aus\n")
return
print(f"📖 Lese {json_file}...")
parser = ImprovedUntisParser(json_file)
print("🔍 Parse Lessons...\n")
lessons = parser.parse_lessons()
print(f"\n✓ {len(lessons)} Lessons gefunden!")
# Gruppiere nach Datum
by_date = {}
for lesson in lessons:
if lesson.date not in by_date:
by_date[lesson.date] = []
by_date[lesson.date].append(lesson)
print(f"📅 Über {len(by_date)} Tage verteilt:\n")
for date in sorted(by_date.keys()):
count = len(by_date[date])
weekday = datetime.strptime(date, '%Y-%m-%d').strftime('%A')
print(f" {date} ({weekday}): {count} Lessons")
# Speichere
with open('parsed_lessons.json', 'w', encoding='utf-8') as f:
json.dump([l.to_dict() for l in lessons], f, indent=2, ensure_ascii=False)
print(f"\n💾 Gespeichert: parsed_lessons.json\n")
print("="*60)
response = input("Zu Google Calendar hinzufügen? (j/n/d für dry-run): ").lower()
if response in ['j', 'y', 'd']:
dry_run = (response == 'd')
try:
syncer = GoogleCalendarSync()
syncer.sync_lessons(lessons, dry_run=dry_run)
if not dry_run:
print("✅ Synchronisation abgeschlossen!")
print("🌐 Öffne Google Calendar!\n")
except Exception as e:
print(f"\n❌ Fehler: {e}\n")
else:
print("\n✋ Abgebrochen.\n")
if __name__ == "__main__":
main()