|
1 | 1 | #!/usr/bin/env python3 |
2 | 2 | import json |
3 | | -from os import environ as env |
4 | 3 |
|
5 | | -import caldav |
| 4 | +## Code contributed by Крылов Александр. Minor changes and quite some |
| 5 | +## comments by Tobias Brox. |
6 | 6 |
|
7 | | -username = env["CALDAV_USERNAME"] |
8 | | -password = env["CALDAV_PASSWORD"] |
9 | | -url = env["CALDAV_URL"] |
10 | | -caldav_url = f"https://{url}/{username}/" |
11 | | -headers = {} |
| 7 | +## Set CALDAV_USERNAME, CALDAV_URL and CALDAV_PASSWORD through |
| 8 | +## environment variables before running this example |
12 | 9 |
|
| 10 | +from caldav.davclient import get_davclient |
13 | 11 |
|
14 | 12 | def fetch_and_print(): |
15 | | - with caldav.DAVClient( |
16 | | - url=caldav_url, |
17 | | - username=username, |
18 | | - password=password, |
19 | | - # Optional parameter to set HTTP headers on each request if needed |
20 | | - headers=headers, |
21 | | - ) as client: |
| 13 | + with get_davclient() as client: |
22 | 14 | print_calendars_demo(client.principal().calendars()) |
23 | 15 |
|
24 | | - |
25 | 16 | def print_calendars_demo(calendars): |
26 | 17 | if not calendars: |
27 | 18 | return |
28 | 19 | events = [] |
29 | 20 | for calendar in calendars: |
30 | 21 | for event in calendar.events(): |
| 22 | + ## Most calendar events will have only one component, |
| 23 | + ## and it can be accessed simply as event.component |
| 24 | + ## The exception is special recurrences, to handle those |
| 25 | + ## we may need to do the walk: |
31 | 26 | for component in event.icalendar_instance.walk(): |
32 | 27 | if component.name != "VEVENT": |
33 | 28 | continue |
34 | 29 | events.append(fill_event(component, calendar)) |
35 | 30 | print(json.dumps(events, indent=2, ensure_ascii=False)) |
36 | 31 |
|
37 | | - |
38 | 32 | def fill_event(component, calendar) -> dict[str, str]: |
| 33 | + ## quite some data is tossed away here - like, the recurring rule. |
39 | 34 | cur = {} |
40 | 35 | cur["calendar"] = f"{calendar}" |
41 | 36 | cur["summary"] = component.get("summary") |
42 | 37 | cur["description"] = component.get("description") |
43 | | - cur["start"] = component.get("dtstart").dt.strftime("%m/%d/%Y %H:%M") |
44 | | - endDate = component.get("dtend") |
45 | | - if endDate and endDate.dt: |
46 | | - cur["end"] = endDate.dt.strftime("%m/%d/%Y %H:%M") |
| 38 | + cur["start"] = component.start.strftime("%m/%d/%Y %H:%M") |
| 39 | + endDate = component.end |
| 40 | + if endDate: |
| 41 | + cur["end"] = endDate.strftime("%m/%d/%Y %H:%M") |
| 42 | + ## For me the following line breaks because some imported calendar events |
| 43 | + ## came without dtstamp. But dtstamp is mandatory according to the RFC |
47 | 44 | cur["datestamp"] = component.get("dtstamp").dt.strftime("%m/%d/%Y %H:%M") |
48 | 45 | return cur |
49 | 46 |
|
50 | | - |
51 | 47 | if __name__ == "__main__": |
52 | 48 | fetch_and_print() |
0 commit comments