ewsgraph 0.1.0__py3-none-any.whl

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.
Files changed (123) hide show
  1. ewsgraph/__init__.py +152 -0
  2. ewsgraph/_availability.py +283 -0
  3. ewsgraph/_bulk.py +702 -0
  4. ewsgraph/_directory.py +321 -0
  5. ewsgraph/_exchangelib_errors.py +186 -0
  6. ewsgraph/_ids.py +54 -0
  7. ewsgraph/_planned.py +190 -0
  8. ewsgraph/_redaction.py +50 -0
  9. ewsgraph/_spec/fields/calendar_item.json +424 -0
  10. ewsgraph/_spec/fields/contact.json +388 -0
  11. ewsgraph/_spec/fields/message.json +319 -0
  12. ewsgraph/_spec/fields/task.json +53 -0
  13. ewsgraph/_spec/fixtures/inbox.unread.newest20.json +10 -0
  14. ewsgraph/_spec/fixtures/query.author.json +36 -0
  15. ewsgraph/_spec/fixtures/query.contains.json +55 -0
  16. ewsgraph/_spec/fixtures/query.count.json +37 -0
  17. ewsgraph/_spec/fixtures/query.exclude.json +37 -0
  18. ewsgraph/_spec/fixtures/query.exists.json +33 -0
  19. ewsgraph/_spec/fixtures/query.in.json +39 -0
  20. ewsgraph/_spec/fixtures/query.negate.json +46 -0
  21. ewsgraph/_spec/fixtures/query.only.json +30 -0
  22. ewsgraph/_spec/fixtures/query.or.json +43 -0
  23. ewsgraph/_spec/fixtures/query.range.json +43 -0
  24. ewsgraph/_spec/fixtures/query.search.json +62 -0
  25. ewsgraph/_spec/fixtures/query.sender.json +36 -0
  26. ewsgraph/_spec/fixtures/query.slice.json +33 -0
  27. ewsgraph/_spec/responses/inbox_page1.json +286 -0
  28. ewsgraph/_spec/schemas/fields.schema.json +112 -0
  29. ewsgraph/_spec/schemas/fixture.schema.json +262 -0
  30. ewsgraph/_spec/schemas/operation.schema.json +41 -0
  31. ewsgraph/_sync.py +361 -0
  32. ewsgraph/account.py +250 -0
  33. ewsgraph/attachments/__init__.py +45 -0
  34. ewsgraph/attachments/_api.py +160 -0
  35. ewsgraph/attachments/_models.py +541 -0
  36. ewsgraph/attachments/_upload.py +601 -0
  37. ewsgraph/auth/__init__.py +43 -0
  38. ewsgraph/auth/_pages.py +74 -0
  39. ewsgraph/auth/certificate.py +126 -0
  40. ewsgraph/auth/credentials.py +431 -0
  41. ewsgraph/auth/delegated.py +498 -0
  42. ewsgraph/auth/identity.py +17 -0
  43. ewsgraph/auth/jwt.py +62 -0
  44. ewsgraph/auth/token_errors.py +242 -0
  45. ewsgraph/autodiscover/__init__.py +9 -0
  46. ewsgraph/autodiscover/discovery.py +7 -0
  47. ewsgraph/cli/__init__.py +44 -0
  48. ewsgraph/cli/__main__.py +11 -0
  49. ewsgraph/cli/doctor.py +760 -0
  50. ewsgraph/configuration.py +113 -0
  51. ewsgraph/constants.py +47 -0
  52. ewsgraph/contracts.py +212 -0
  53. ewsgraph/credentials.py +34 -0
  54. ewsgraph/errors.py +380 -0
  55. ewsgraph/ewsdatetime.py +19 -0
  56. ewsgraph/extended_properties.py +336 -0
  57. ewsgraph/fields/__init__.py +535 -0
  58. ewsgraph/fields/_contacts.py +199 -0
  59. ewsgraph/fields/_timezones.py +146 -0
  60. ewsgraph/folders/__init__.py +899 -0
  61. ewsgraph/folders/_hierarchy.py +142 -0
  62. ewsgraph/folders/base.py +8 -0
  63. ewsgraph/folders/calendar.py +411 -0
  64. ewsgraph/folders/collections.py +8 -0
  65. ewsgraph/folders/contacts.py +349 -0
  66. ewsgraph/folders/known.py +280 -0
  67. ewsgraph/folders/queryset.py +220 -0
  68. ewsgraph/folders/roots.py +8 -0
  69. ewsgraph/folders/tasks.py +299 -0
  70. ewsgraph/indexed_properties.py +87 -0
  71. ewsgraph/items/__init__.py +406 -0
  72. ewsgraph/items/_actions.py +382 -0
  73. ewsgraph/items/_attachments.py +351 -0
  74. ewsgraph/items/_calendar.py +662 -0
  75. ewsgraph/items/_contact.py +194 -0
  76. ewsgraph/items/_extended.py +201 -0
  77. ewsgraph/items/_meeting.py +131 -0
  78. ewsgraph/items/_mime.py +66 -0
  79. ewsgraph/items/_on_access.py +285 -0
  80. ewsgraph/items/_permissions.py +41 -0
  81. ewsgraph/items/_responses.py +154 -0
  82. ewsgraph/items/_send.py +206 -0
  83. ewsgraph/items/_series.py +215 -0
  84. ewsgraph/items/_task.py +328 -0
  85. ewsgraph/items/calendar_item.py +43 -0
  86. ewsgraph/items/contact.py +7 -0
  87. ewsgraph/items/item.py +7 -0
  88. ewsgraph/items/message.py +7 -0
  89. ewsgraph/items/post.py +7 -0
  90. ewsgraph/items/task.py +7 -0
  91. ewsgraph/licensing/__init__.py +225 -0
  92. ewsgraph/licensing/_api.py +68 -0
  93. ewsgraph/licensing/_file.py +68 -0
  94. ewsgraph/licensing/cli.py +83 -0
  95. ewsgraph/paths.py +21 -0
  96. ewsgraph/properties.py +219 -0
  97. ewsgraph/protocol.py +73 -0
  98. ewsgraph/query/__init__.py +938 -0
  99. ewsgraph/query/ir.py +63 -0
  100. ewsgraph/queryset.py +8 -0
  101. ewsgraph/recurrence.py +550 -0
  102. ewsgraph/restriction.py +7 -0
  103. ewsgraph/rules.py +463 -0
  104. ewsgraph/settings.py +160 -0
  105. ewsgraph/spec_data.py +28 -0
  106. ewsgraph/testing/__init__.py +5 -0
  107. ewsgraph/testing/fixtures.py +155 -0
  108. ewsgraph/testing/live.py +170 -0
  109. ewsgraph/testing/mock.py +46 -0
  110. ewsgraph/transport/__init__.py +29 -0
  111. ewsgraph/transport/http.py +563 -0
  112. ewsgraph/transport/limits.py +327 -0
  113. ewsgraph/transport/retry.py +94 -0
  114. ewsgraph/util.py +17 -0
  115. ewsgraph/version.py +54 -0
  116. ewsgraph/winzone.py +17 -0
  117. ewsgraph-0.1.0.dist-info/METADATA +176 -0
  118. ewsgraph-0.1.0.dist-info/RECORD +123 -0
  119. ewsgraph-0.1.0.dist-info/WHEEL +4 -0
  120. ewsgraph-0.1.0.dist-info/entry_points.txt +2 -0
  121. ewsgraph-0.1.0.dist-info/licenses/LICENSE-EXCEPTION.md +40 -0
  122. ewsgraph-0.1.0.dist-info/licenses/LICENSE.md +76 -0
  123. ewsgraph-0.1.0.dist-info/licenses/NOTICE +69 -0
ewsgraph/__init__.py ADDED
@@ -0,0 +1,152 @@
1
+ """ewsgraph: exchangelib-compatible API on Microsoft Graph.
2
+
3
+ Integrator-owned: streams never edit this file; the integrator adds exports after each wave.
4
+ """
5
+
6
+ import logging as _logging
7
+
8
+ from ._planned import (
9
+ DistributionList,
10
+ DLMailbox,
11
+ PostItem,
12
+ PostReplyItem,
13
+ Room,
14
+ RoomList,
15
+ discover,
16
+ )
17
+ from ._redaction import install_httpx_filter as _install_httpx_filter
18
+ from .account import Account
19
+ from .attachments import FileAttachment, ItemAttachment
20
+ from .auth import (
21
+ Credentials,
22
+ Identity,
23
+ OAuth2AuthorizationCodeCredentials,
24
+ OAuth2Credentials,
25
+ OAuth2LegacyCredentials,
26
+ )
27
+ from .configuration import Configuration, O365InteractiveConfiguration, close_connections
28
+ from .constants import (
29
+ BASIC,
30
+ CBA,
31
+ DEEP,
32
+ DELEGATE,
33
+ DIGEST,
34
+ GSSAPI,
35
+ IMPERSONATION,
36
+ NOAUTH,
37
+ NTLM,
38
+ OAUTH2,
39
+ SHALLOW,
40
+ SSPI,
41
+ )
42
+ from .errors import * # noqa: F403
43
+ from .extended_properties import ExtendedProperty
44
+ from .fields import (
45
+ UTC,
46
+ UTC_NOW,
47
+ Attendee,
48
+ Body,
49
+ EWSDate,
50
+ EWSDateTime,
51
+ EWSTimeZone,
52
+ HTMLBody,
53
+ Mailbox,
54
+ )
55
+ from .folders import Folder, FolderCollection, RootOfHierarchy
56
+ from .items import (
57
+ AcceptItem,
58
+ CalendarItem,
59
+ CancelCalendarItem,
60
+ Contact,
61
+ DeclineItem,
62
+ Message,
63
+ Task,
64
+ TentativelyAcceptItem,
65
+ )
66
+ from .items._actions import ForwardItem, ReplyAllToItem, ReplyToItem
67
+ from .licensing import LicenseWarning
68
+ from .properties import UID, ItemId
69
+ from .protocol import BaseProtocol, NoVerifyHTTPAdapter, TLSClientAuth
70
+ from .query import Q
71
+ from .settings import OofSettings
72
+ from .transport import FailFast, FaultTolerance
73
+ from .version import Build, Version
74
+
75
+ __version__ = "0.1.0"
76
+
77
+ # Library logging stays silent unless the application configures logging.
78
+ _logging.getLogger(__name__).addHandler(_logging.NullHandler())
79
+ _install_httpx_filter()
80
+
81
+ __all__ = [
82
+ "Account",
83
+ "Attendee",
84
+ "Body",
85
+ "EWSDate",
86
+ "EWSDateTime",
87
+ "EWSTimeZone",
88
+ "FileAttachment",
89
+ "Folder",
90
+ "FolderCollection",
91
+ "HTMLBody",
92
+ "Mailbox",
93
+ "UTC",
94
+ "UTC_NOW",
95
+ "CalendarItem",
96
+ "Configuration",
97
+ "Credentials",
98
+ "DELEGATE",
99
+ "FailFast",
100
+ "FaultTolerance",
101
+ "IMPERSONATION",
102
+ "ItemAttachment",
103
+ "Message",
104
+ "O365InteractiveConfiguration",
105
+ "OAuth2AuthorizationCodeCredentials",
106
+ "OAuth2Credentials",
107
+ "OAuth2LegacyCredentials",
108
+ "Q",
109
+ # exchangelib auth types and Identity: accepted so exchangelib scripts import unchanged
110
+ "BASIC",
111
+ "CBA",
112
+ "DIGEST",
113
+ "GSSAPI",
114
+ "Identity",
115
+ "NOAUTH",
116
+ "NTLM",
117
+ "OAUTH2",
118
+ "SSPI",
119
+ # exchangelib names that work
120
+ "AcceptItem",
121
+ "CancelCalendarItem",
122
+ "DeclineItem",
123
+ "TentativelyAcceptItem",
124
+ "Build",
125
+ "close_connections",
126
+ "DEEP",
127
+ "ForwardItem",
128
+ "ItemId",
129
+ "ReplyAllToItem",
130
+ "ReplyToItem",
131
+ "RootOfHierarchy",
132
+ "SHALLOW",
133
+ "UID",
134
+ "Version",
135
+ # exchangelib names that raise an explaining error until ewsgraph supports them (_planned)
136
+ "Contact",
137
+ "DLMailbox",
138
+ "ExtendedProperty",
139
+ "LicenseWarning",
140
+ "OofSettings",
141
+ "Room",
142
+ "RoomList",
143
+ "Task",
144
+ # exchangelib names Microsoft Graph cannot support: an explaining error or a warning
145
+ "BaseProtocol",
146
+ "discover",
147
+ "DistributionList",
148
+ "NoVerifyHTTPAdapter",
149
+ "PostItem",
150
+ "PostReplyItem",
151
+ "TLSClientAuth",
152
+ ]
@@ -0,0 +1,283 @@
1
+ """account.protocol.get_free_busy_info(): exchangelib's GetUserAvailability on Graph's getSchedule.
2
+
3
+ POST /users/{mailbox}/calendar/getSchedule takes the addresses, a time window and an interval, and
4
+ answers per address with its schedule items, a merged availability string and its working hours.
5
+ Checked against exchangelib over EWS on a tenant 14.11.2026, for UTC and Europe/Berlin windows:
6
+ - the merged string is the same, digit for digit (0 free, 1 tentative, 2 busy, 3 OOF; an event
7
+ shown as working elsewhere is 0 in both);
8
+ - the events are the same: start and end in the zone of the request (exchangelib gives them in
9
+ start.tzinfo), busy type, subject and the is_* flags. Graph gives no id for them (EWS does);
10
+ - an address without a mailbox is responseCode 5009 with EWS's own message; exchangelib puts
11
+ ErrorMailRecipientNotFound in its place, and so does ewsgraph;
12
+ - Graph's getSchedule can lag a few seconds behind an event that was just created.
13
+ Working hours (WorkingPeriod and its TimeZone) are mapped from Graph's workingHours; the test
14
+ mailbox has none set, in Graph and in EWS alike, so that part is checked offline only.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import datetime as dt
20
+ from typing import Any
21
+
22
+ from . import errors
23
+ from .contracts import GraphRequest
24
+
25
+ REQUESTED_VIEWS = ("MergedOnly", "FreeBusy", "FreeBusyMerged", "Detailed", "DetailedMerged")
26
+ ATTENDEE_TYPES = ("Optional", "Organizer", "Required", "Resource", "Room")
27
+ SCHEDULES_PER_REQUEST = 20
28
+ BUSY_TYPES = {
29
+ "free": "Free",
30
+ "tentative": "Tentative",
31
+ "busy": "Busy",
32
+ "oof": "OOF",
33
+ "workingElsewhere": "WorkingElsewhere",
34
+ "unknown": "NoData",
35
+ }
36
+ WEEKDAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
37
+ PERMISSION = "Calendars.Read"
38
+
39
+
40
+ def get_free_busy_info(
41
+ account, accounts, start, end, merged_free_busy_interval=30, requested_view="DetailedMerged"
42
+ ):
43
+ """A generator of FreeBusyView objects (or the exception for an address), in the order asked."""
44
+ for name, value in (("start", start), ("end", end)):
45
+ if not isinstance(value, dt.datetime) or value.utcoffset() is None:
46
+ raise ValueError(f"'{name}' must be a timezone-aware datetime, not {value!r}")
47
+ if start >= end:
48
+ raise ValueError(f"'start' must be less than 'end' ({start} -> {end})")
49
+ if type(merged_free_busy_interval) is not int or not 5 <= merged_free_busy_interval <= 1440:
50
+ raise ValueError(
51
+ f"'merged_free_busy_interval' must be an integer from 5 to 1440, not "
52
+ f"{merged_free_busy_interval!r}"
53
+ )
54
+ if requested_view not in REQUESTED_VIEWS:
55
+ raise ValueError(f"'requested_view' must be one of {REQUESTED_VIEWS}, not {requested_view!r}")
56
+ addresses = [_address(entry) for entry in accounts]
57
+ zone_name = _windows_zone(start.tzinfo)
58
+ results: list[Any] = []
59
+ for first in range(0, len(addresses), SCHEDULES_PER_REQUEST):
60
+ chunk = addresses[first : first + SCHEDULES_PER_REQUEST]
61
+ body = {
62
+ "schedules": chunk,
63
+ "startTime": {"dateTime": _local(start, start.tzinfo), "timeZone": zone_name},
64
+ "endTime": {"dateTime": _local(end, start.tzinfo), "timeZone": zone_name},
65
+ "availabilityViewInterval": merged_free_busy_interval,
66
+ }
67
+ request = GraphRequest(
68
+ "POST",
69
+ f"{account.mailbox_path}/calendar/getSchedule",
70
+ json=body,
71
+ headers={"Prefer": f'outlook.timezone="{zone_name}"'},
72
+ mailbox=account.primary_smtp_address,
73
+ idempotent=True, # it only reads
74
+ )
75
+ try:
76
+ answer = account.transport.send(request).json or {}
77
+ except errors.ErrorAccessDenied as exc:
78
+ from .items._permissions import missing_permission
79
+
80
+ raise missing_permission(exc, PERMISSION, account) from exc
81
+ rows = list(answer.get("value") or [])
82
+ for n, address in enumerate(chunk):
83
+ row = rows[n] if n < len(rows) else None
84
+ if row is None or (row.get("scheduleId") or "").casefold() != address.casefold():
85
+ row = next(
86
+ (r for r in rows if (r.get("scheduleId") or "").casefold() == address.casefold()), None
87
+ )
88
+ results.append(_view(row, address, requested_view, start.tzinfo))
89
+ yield from results
90
+
91
+
92
+ def _address(entry: Any) -> str:
93
+ try:
94
+ who, attendee_type, exclude_conflicts = entry
95
+ except (TypeError, ValueError):
96
+ raise ValueError(
97
+ f"Expected an (account, attendee_type, exclude_conflicts) tuple, not {entry!r:.80}"
98
+ ) from None
99
+ if attendee_type not in ATTENDEE_TYPES:
100
+ raise ValueError(f"attendee_type must be one of {ATTENDEE_TYPES}, not {attendee_type!r}")
101
+ address = who if isinstance(who, str) else getattr(who, "primary_smtp_address", None)
102
+ if not isinstance(address, str) or "@" not in address:
103
+ raise ValueError(f"Expected an Account or an e-mail address, not {who!r:.80}")
104
+ return address
105
+
106
+
107
+ def _windows_zone(tzinfo: Any) -> str:
108
+ """The Windows zone name Graph takes (and answers in) for this tzinfo."""
109
+ from .fields import EWSTimeZone
110
+
111
+ if tzinfo is dt.timezone.utc or getattr(tzinfo, "key", None) in ("UTC", "Etc/UTC"):
112
+ return "UTC"
113
+ try:
114
+ return EWSTimeZone.from_timezone(tzinfo).ms_id
115
+ except ValueError as exc:
116
+ raise ValueError(
117
+ f"get_free_busy_info() needs a named time zone (zoneinfo or EWSTimeZone), not {tzinfo!r}"
118
+ ) from exc
119
+
120
+
121
+ def _local(value: dt.datetime, tzinfo: Any) -> str:
122
+ return value.astimezone(tzinfo).replace(tzinfo=None).isoformat()
123
+
124
+
125
+ def _view(row: Any, address: str, requested_view: str, tzinfo: Any) -> Any:
126
+ from .properties import CalendarEvent, CalendarEventDetails, FreeBusyView
127
+
128
+ if row is None:
129
+ return errors.EWSError(f"Graph's getSchedule answer has nothing for {address}")
130
+ if row.get("error"):
131
+ problem = row["error"]
132
+ message = problem.get("message") or f"Graph could not read the schedule of {address}"
133
+ if str(problem.get("responseCode")) == "5009":
134
+ return errors.ErrorMailRecipientNotFound(message)
135
+ return errors.EWSError(f"{message} (responseCode {problem.get('responseCode')})")
136
+ events = None
137
+ if requested_view != "MergedOnly":
138
+ events = []
139
+ for item in row.get("scheduleItems") or []:
140
+ details = None
141
+ if requested_view.startswith("Detailed"):
142
+ details = CalendarEventDetails(
143
+ id=None,
144
+ subject=item.get("subject") or None,
145
+ location=item.get("location") or None,
146
+ is_meeting=item.get("isMeeting"),
147
+ is_recurring=item.get("isRecurring"),
148
+ is_exception=item.get("isException"),
149
+ is_reminder_set=item.get("isReminderSet"),
150
+ is_private=item.get("isPrivate"),
151
+ )
152
+ events.append(
153
+ CalendarEvent(
154
+ start=_when(item.get("start"), tzinfo),
155
+ end=_when(item.get("end"), tzinfo),
156
+ busy_type=BUSY_TYPES.get(item.get("status"), "Busy"),
157
+ details=details,
158
+ )
159
+ )
160
+ events = events or None # exchangelib: no CalendarEventArray is None
161
+ working_hours, zone = _working_hours(row.get("workingHours"))
162
+ return FreeBusyView(
163
+ view_type=requested_view,
164
+ merged=row.get("availabilityView")
165
+ if requested_view.endswith("Merged") or requested_view == "MergedOnly"
166
+ else None,
167
+ calendar_events=events,
168
+ working_hours=working_hours,
169
+ working_hours_timezone=zone,
170
+ )
171
+
172
+
173
+ def _when(value: Any, tzinfo: Any) -> Any:
174
+ from .fields import EWSDateTime, _parse_datetime
175
+
176
+ if not value or not value.get("dateTime"):
177
+ return None
178
+ local = _parse_datetime(value["dateTime"]).replace(tzinfo=None) # in the zone asked for (Prefer header)
179
+ return EWSDateTime.from_datetime(local.replace(tzinfo=tzinfo))
180
+
181
+
182
+ # --- working hours --------------------------------------------------------------------------------
183
+
184
+
185
+ def _working_hours(value: Any) -> tuple[list | None, Any]:
186
+ from .properties import WorkingPeriod
187
+
188
+ if not value or not value.get("daysOfWeek"):
189
+ return None, None
190
+ names = [d.capitalize() for d in value.get("daysOfWeek") or []]
191
+ days = sorted(WEEKDAYS.index(d) + 1 for d in names if d in WEEKDAYS) # exchangelib: 1 is Monday
192
+ period = WorkingPeriod(
193
+ weekdays=days, start=_clock(value.get("startTime")), end=_clock(value.get("endTime"))
194
+ )
195
+ return [period], _time_zone(value.get("timeZone") or {})
196
+
197
+
198
+ def _clock(value: Any) -> dt.time | None:
199
+ if not isinstance(value, str) or not value:
200
+ return None
201
+ hours, minutes, *_ = value.split(":")
202
+ return dt.time(int(hours), int(minutes))
203
+
204
+
205
+ def _time_zone(value: dict) -> Any:
206
+ """Graph's timeZone of the working hours as EWS's TimeZone: a customTimeZone carries the rules,
207
+ a named one (Windows or IANA name) is computed from the tz database."""
208
+ from .properties import TimeZone
209
+
210
+ if value.get("@odata.type") == "#microsoft.graph.customTimeZone" or "standardOffset" in value:
211
+ return TimeZone(
212
+ bias=value.get("bias"),
213
+ standard_time=_custom_transition(value.get("standardOffset"), 0, standard=True),
214
+ daylight_time=_custom_transition(
215
+ value.get("daylightOffset"),
216
+ (value.get("daylightOffset") or {}).get("daylightBias", 0) or 0,
217
+ standard=False,
218
+ ),
219
+ )
220
+ name = value.get("name")
221
+ if not name:
222
+ return None
223
+ return rules_for(name, dt.date.today().year)
224
+
225
+
226
+ def _custom_transition(value: Any, bias: int, *, standard: bool) -> Any:
227
+ from .properties import DaylightTime, StandardTime
228
+
229
+ if not value:
230
+ return None
231
+ cls = StandardTime if standard else DaylightTime
232
+ day = value.get("dayOfWeek")
233
+ return cls(
234
+ bias=bias,
235
+ time=_clock(value.get("time")),
236
+ occurrence=value.get("dayOccurrence"),
237
+ iso_month=value.get("month"),
238
+ weekday=WEEKDAYS.index(day.capitalize()) + 1 if isinstance(day, str) else None,
239
+ )
240
+
241
+
242
+ def rules_for(name: str, year: int) -> Any:
243
+ """EWS's TimeZone for a zone name in `year`: bias, and the standard/daylight rules from the
244
+ transitions the tz database has that year (None for a zone without daylight saving time)."""
245
+ from .fields import EWSTimeZone
246
+ from .properties import DaylightTime, StandardTime, TimeZone
247
+
248
+ try:
249
+ zone = EWSTimeZone.from_ms_id(name)
250
+ except (KeyError, ValueError):
251
+ return None
252
+ changes = []
253
+ moment = dt.datetime(year, 1, 1, tzinfo=dt.timezone.utc)
254
+ previous = moment.astimezone(zone).utcoffset()
255
+ while moment.year == year:
256
+ moment += dt.timedelta(minutes=30)
257
+ offset = moment.astimezone(zone).utcoffset()
258
+ if offset != previous:
259
+ changes.append((moment, previous, offset))
260
+ previous = offset
261
+ offsets = [moment.astimezone(zone).utcoffset()] + [c[2] for c in changes]
262
+ standard = min(offsets) if changes else offsets[0]
263
+ bias = -int(standard.total_seconds() // 60)
264
+ if not changes:
265
+ return TimeZone(bias=bias)
266
+ rules: dict[str, Any] = {}
267
+ for when, before, after in changes:
268
+ local = (when + before).replace(tzinfo=None) # the clock, still in the old offset
269
+ weekday_count = (local.day - 1) // 7 + 1
270
+ last = (local + dt.timedelta(days=7)).month != local.month
271
+ cls, key, rule_bias = (
272
+ (DaylightTime, "daylight", -int((after - standard).total_seconds() // 60))
273
+ if after > standard
274
+ else (StandardTime, "standard", 0)
275
+ )
276
+ rules[key] = cls(
277
+ bias=rule_bias,
278
+ time=local.time(),
279
+ occurrence=5 if last else weekday_count,
280
+ iso_month=local.month,
281
+ weekday=local.isoweekday(),
282
+ )
283
+ return TimeZone(bias=bias, standard_time=rules.get("standard"), daylight_time=rules.get("daylight"))