File: ewsdatetime.py

package info (click to toggle)
python-exchangelib 5.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 12,084 kB
  • sloc: python: 25,351; sh: 6; makefile: 5
file content (309 lines) | stat: -rw-r--r-- 11,414 bytes parent folder | download
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
import datetime
import logging
import zoneinfo

import tzlocal

from .errors import InvalidTypeError, NaiveDateTimeNotAllowed, UnknownTimeZone
from .winzone import IANA_TO_MS_TIMEZONE_MAP, MS_TIMEZONE_TO_IANA_MAP

log = logging.getLogger(__name__)


class EWSDate(datetime.date):
    """Extends the normal date implementation to satisfy EWS."""

    __slots__ = "_year", "_month", "_day", "_hashcode"

    def ewsformat(self):
        """ISO 8601 format to satisfy xs:date as interpreted by EWS. Example: 2009-01-15."""
        return self.isoformat()

    def __add__(self, other):
        dt = super().__add__(other)
        if isinstance(dt, self.__class__):
            return dt
        return self.from_date(dt)  # We want to return EWSDate objects

    def __iadd__(self, other):
        return self + other

    def __sub__(self, other):
        dt = super().__sub__(other)
        if isinstance(dt, datetime.timedelta):
            return dt
        if isinstance(dt, self.__class__):
            return dt
        return self.from_date(dt)  # We want to return EWSDate objects

    def __isub__(self, other):
        return self - other

    @classmethod
    def fromordinal(cls, n):
        dt = super().fromordinal(n)
        if isinstance(dt, cls):
            return dt
        return cls.from_date(dt)  # We want to return EWSDate objects

    @classmethod
    def from_date(cls, d):
        if type(d) is not datetime.date:
            raise InvalidTypeError("d", d, datetime.date)
        return cls(d.year, d.month, d.day)

    @classmethod
    def from_string(cls, date_string):
        # Sometimes, we'll receive a date string with time zone information. Not very useful.
        if date_string.endswith("Z"):
            date_fmt = "%Y-%m-%dZ"
        elif ":" in date_string:
            if "+" in date_string:
                date_fmt = "%Y-%m-%d+%H:%M"
            else:
                date_fmt = "%Y-%m-%d-%H:%M"
        else:
            date_fmt = "%Y-%m-%d"
        d = datetime.datetime.strptime(date_string, date_fmt).date()
        if isinstance(d, cls):
            return d
        return cls.from_date(d)  # We want to return EWSDate objects


class EWSDateTime(datetime.datetime):
    """Extends the normal datetime implementation to satisfy EWS."""

    __slots__ = "_year", "_month", "_day", "_hour", "_minute", "_second", "_microsecond", "_tzinfo", "_hashcode"

    def __new__(cls, *args, **kwargs):
        # pylint: disable=arguments-differ

        if len(args) == 8:
            tzinfo = args[7]
        else:
            tzinfo = kwargs.get("tzinfo")
        if isinstance(tzinfo, zoneinfo.ZoneInfo):
            # Don't allow pytz or dateutil timezones here. They are not safe to use as direct input for datetime()
            tzinfo = EWSTimeZone.from_timezone(tzinfo)
        if not isinstance(tzinfo, (EWSTimeZone, type(None))):
            raise InvalidTypeError("tzinfo", tzinfo, EWSTimeZone)
        if len(args) == 8:
            args = args[:7] + (tzinfo,)
        else:
            kwargs["tzinfo"] = tzinfo
        return super().__new__(cls, *args, **kwargs)

    def ewsformat(self):
        """ISO 8601 format to satisfy xs:datetime as interpreted by EWS. Examples:
        * 2009-01-15T13:45:56Z
        * 2009-01-15T13:45:56+01:00
        """
        if not self.tzinfo:
            raise ValueError(f"{self!r} must be timezone-aware")
        if self.tzinfo.key == "UTC":
            if self.microsecond:
                return self.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
            return self.strftime("%Y-%m-%dT%H:%M:%SZ")
        return self.isoformat()

    @classmethod
    def from_datetime(cls, d):
        if type(d) is not datetime.datetime:
            raise InvalidTypeError("d", d, datetime.datetime)
        if d.tzinfo is None:
            tz = None
        elif isinstance(d.tzinfo, EWSTimeZone):
            tz = d.tzinfo
        else:
            tz = EWSTimeZone.from_timezone(d.tzinfo)
        return cls(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, tzinfo=tz)

    def astimezone(self, tz=None):
        if tz is None:
            tz = EWSTimeZone.localzone()
        t = super().astimezone(tz=tz).replace(tzinfo=tz)
        if isinstance(t, self.__class__):
            return t
        return self.from_datetime(t)  # We want to return EWSDateTime objects

    @classmethod
    def fromisoformat(cls, date_string):
        return cls.from_string(date_string)

    def __add__(self, other):
        t = super().__add__(other)
        if isinstance(t, self.__class__):
            return t
        return self.from_datetime(t)  # We want to return EWSDateTime objects

    def __iadd__(self, other):
        return self + other

    def __sub__(self, other):
        t = super().__sub__(other)
        if isinstance(t, datetime.timedelta):
            return t
        if isinstance(t, self.__class__):
            return t
        return self.from_datetime(t)  # We want to return EWSDateTime objects

    def __isub__(self, other):
        return self - other

    @classmethod
    def from_string(cls, date_string):
        # Parses several common datetime formats and returns time zone aware EWSDateTime objects
        if date_string.endswith("Z"):
            # UTC datetime
            return super().strptime(date_string, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)
        if len(date_string) == 19:
            # This is probably a naive datetime. Don't allow this, but signal caller with an appropriate error
            local_dt = super().strptime(date_string, "%Y-%m-%dT%H:%M:%S")
            raise NaiveDateTimeNotAllowed(local_dt)
        # This is probably a datetime value with time zone information. This comes in the form '+/-HH:MM'.
        aware_dt = datetime.datetime.fromisoformat(date_string).astimezone(UTC).replace(tzinfo=UTC)
        if isinstance(aware_dt, cls):
            return aware_dt
        return cls.from_datetime(aware_dt)

    @classmethod
    def fromtimestamp(cls, t, tz=None):
        dt = super().fromtimestamp(t, tz=tz)
        if isinstance(dt, cls):
            return dt
        return cls.from_datetime(dt)  # We want to return EWSDateTime objects

    @classmethod
    def utcfromtimestamp(cls, t):
        dt = super().utcfromtimestamp(t)
        if isinstance(dt, cls):
            return dt
        return cls.from_datetime(dt)  # We want to return EWSDateTime objects

    @classmethod
    def now(cls, tz=None):
        t = super().now(tz=tz)
        if isinstance(t, cls):
            return t
        return cls.from_datetime(t)  # We want to return EWSDateTime objects

    @classmethod
    def utcnow(cls):
        t = super().utcnow()
        if isinstance(t, cls):
            return t
        return cls.from_datetime(t)  # We want to return EWSDateTime objects

    def date(self):
        d = super().date()
        if isinstance(d, EWSDate):
            return d
        return EWSDate.from_date(d)  # We want to return EWSDate objects


class EWSTimeZone(zoneinfo.ZoneInfo):
    """Represents a time zone as expected by the EWS TimezoneContext / TimezoneDefinition XML element, and returned by
    services.GetServerTimeZones.
    """

    IANA_TO_MS_MAP = IANA_TO_MS_TIMEZONE_MAP
    MS_TO_IANA_MAP = MS_TIMEZONE_TO_IANA_MAP

    def __new__(cls, *args, **kwargs):
        try:
            instance = super().__new__(cls, *args, **kwargs)
        except zoneinfo.ZoneInfoNotFoundError as e:
            raise UnknownTimeZone(e.args[0])
        try:
            instance.ms_id = cls.IANA_TO_MS_MAP[instance.key][0]
        except KeyError:
            raise UnknownTimeZone(f"No Windows timezone name found for timezone {instance.key!r}")

        # We don't need the Windows long-format time zone name in long format. It's used in time zone XML elements, but
        # EWS happily accepts empty strings. For a full list of time zones supported by the target server, including
        # long-format names, see output of services.GetServerTimeZones(account.protocol).call()
        instance.ms_name = ""
        return instance

    def __hash__(self):
        return hash(self.key)

    def __eq__(self, other):
        # Microsoft time zones are less granular than IANA, so an EWSTimeZone created from 'Europe/Copenhagen' may
        # return from the server as 'Europe/Copenhagen'. We're catering for Microsoft here, so base equality on the
        # Microsoft time zone ID.
        if not isinstance(other, self.__class__):
            return NotImplemented
        return self.ms_id == other.ms_id

    @classmethod
    def from_ms_id(cls, ms_id):
        # Create a time zone instance from a Microsoft time zone ID. This is lossy because there is not a 1:1
        # translation from MS time zone ID to IANA time zone.
        try:
            return cls(cls.MS_TO_IANA_MAP[ms_id])
        except KeyError:
            if "/" in ms_id:
                # EWS sometimes returns an ID that has a region/location format, e.g. 'Europe/Copenhagen'. Try the
                # string unaltered.
                return cls(ms_id)
            raise UnknownTimeZone(f"Windows timezone ID {ms_id!r} is unknown by CLDR")

    @classmethod
    def from_pytz(cls, tz):
        return cls(tz.zone)

    @classmethod
    def from_datetime(cls, tz):
        """Convert from a standard library `datetime.timezone` instance."""
        return cls(tz.tzname(None))

    @classmethod
    def from_dateutil(cls, tz):
        # Objects returned by dateutil.tz.tzlocal() and dateutil.tz.gettz() are not supported. They
        # don't contain enough information to reliably match them with a CLDR time zone.
        if hasattr(tz, "_filename"):
            key = "/".join(tz._filename.split("/")[-2:])
            return cls(key)
        return cls(tz.tzname(datetime.datetime.now()))

    @classmethod
    def from_zoneinfo(cls, tz):
        return cls(tz.key)

    @classmethod
    def from_timezone(cls, tz):
        # Support multiple tzinfo implementations. We could use isinstance(), but then we'd have to have pytz
        # and dateutil as dependencies for this package.
        tz_module = tz.__class__.__module__.split(".")[0]
        try:
            return {
                cls.__module__.split(".")[0]: lambda z: z,
                "datetime": cls.from_datetime,
                "dateutil": cls.from_dateutil,
                "pytz": cls.from_pytz,
                "zoneinfo": cls.from_zoneinfo,
                "pytz_deprecation_shim": lambda z: cls.from_timezone(z.unwrap_shim()),
            }[tz_module](tz)
        except KeyError:
            raise TypeError(f"Unsupported tzinfo type: {tz!r}")

    @classmethod
    def localzone(cls):
        try:
            tz = tzlocal.get_localzone()
        except zoneinfo.ZoneInfoNotFoundError:
            # Older versions of tzlocal will raise a pytz exception. Let's not depend on pytz just for that.
            raise UnknownTimeZone("Failed to guess local timezone")
        # Handle both old and new versions of tzlocal that may return pytz or zoneinfo objects, respectively
        return cls.from_timezone(tz)

    def fromutc(self, dt):
        t = super().fromutc(dt)
        if isinstance(t, EWSDateTime):
            return t
        return EWSDateTime.from_datetime(t)  # We want to return EWSDateTime objects


UTC = EWSTimeZone("UTC")
UTC_NOW = lambda: EWSDateTime.now(tz=UTC)  # noqa: E731