| 1 | """Helper methods to handle the time in Home Assistant.""" |
| 2 | |
| 3 | from __future__scip-python python python-stdlib 3.11 __future__/__init__: import annotationsscip-python python python-stdlib 3.11 __future__/annotations.annotations. |
| 4 | |
| 5 | import asyncioscip-python python python-stdlib 3.11 asyncio/__init__: |
| 6 | from collections.abcscip-python python python-stdlib 3.11 `collections.abc`/__init__: import Awaitablescip-python python python-stdlib 3.11 typing/Awaitable#, Callablescip-python python python-stdlib 3.11 typing/Callable., Mappingscip-python python python-stdlib 3.11 typing/Mapping# |
| 7 | import datetimescip-python python python-stdlib 3.11 datetime/__init__: as dt |
| 8 | from loggingscip-python python python-stdlib 3.11 logging/__init__: import Loggerscip-python python python-stdlib 3.11 logging/Logger# |
| 9 | import randomscip-python python python-stdlib 3.11 random/__init__: |
| 10 | import sslscip-python python python-stdlib 3.11 ssl/__init__: |
| 11 | from typingscip-python python python-stdlib 3.11 typing/__init__: import Anyscip-python python python-stdlib 3.11 typing/Any., TypeVarscip-python python python-stdlib 3.11 typing/TypeVar# |
| 12 | |
| 13 | import ciso8601scip-python python ciso8601 2.3.3 ciso8601/__init__: |
| 14 | import jwt |
| 15 | |
| 16 | CALLABLE_Tscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/CALLABLE_T. = TypeVarscip-python python python-stdlib 3.11 typing/TypeVar#("CALLABLE_T", boundscip-python python python-stdlib 3.11 typing/TypeVar#__init__().(bound)=Callablescip-python python python-stdlib 3.11 typing/Callable.) # pylint: disable=invalid-name |
| 17 | UTCscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/UTC. = dt.UTCscip-python python python-stdlib 3.11 datetime/UTC. |
| 18 | |
| 19 | |
| 20 | def utcnowscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/utcnow().() -> dt.datetimescip-python python python-stdlib 3.11 datetime/datetime#: |
| 21 | """Get now in UTC time.""" |
| 22 | return dt.datetimescip-python python python-stdlib 3.11 datetime/datetime#.nowscip-python python python-stdlib 3.11 datetime/datetime#now().(UTCscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/UTC.) |
| 23 | |
| 24 | |
| 25 | def utc_from_timestampscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/utc_from_timestamp().(timestampscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/utc_from_timestamp().(timestamp): floatscip-python python python-stdlib 3.11 builtins/float#) -> dt.datetimescip-python python python-stdlib 3.11 datetime/datetime#: |
| 26 | """Return a UTC time from a timestamp.""" |
| 27 | return dt.datetimescip-python python python-stdlib 3.11 datetime/datetime#.fromtimestampscip-python python python-stdlib 3.11 datetime/datetime#fromtimestamp().(timestampscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/utc_from_timestamp().(timestamp), UTCscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/UTC.) |
| 28 | |
| 29 | |
| 30 | def parse_datescip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/parse_date().(dt_strscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/parse_date().(dt_str): strscip-python python python-stdlib 3.11 builtins/str#) -> dt.datescip-python python python-stdlib 3.11 datetime/date# | None: |
| 31 | """Convert a date string to a date object.""" |
| 32 | try: |
| 33 | return ciso8601scip-python python ciso8601 2.3.3 ciso8601/__init__:.parse_datetime(dt_strscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/parse_date().(dt_str)).datescip-python python python-stdlib 3.11 datetime/datetime#date().() |
| 34 | except ValueErrorscip-python python python-stdlib 3.11 builtins/ValueError#: # If dt_str did not match our format |
| 35 | return None |
| 36 | |
| 37 | |
| 38 | def seconds_as_dhmsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds): floatscip-python python python-stdlib 3.11 builtins/float#) -> strscip-python python python-stdlib 3.11 builtins/str#: |
| 39 | """Convert seconds to a DDd:HHh:MMm:SSs string.""" |
| 40 | days, secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds) = divmodscip-python python python-stdlib 3.11 builtins/divmod().(intscip-python python python-stdlib 3.11 builtins/int#(secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds)), 86400) |
| 41 | hours, secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds) = divmodscip-python python python-stdlib 3.11 builtins/divmod().(secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds), 3600) |
| 42 | minutes, secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds) = divmodscip-python python python-stdlib 3.11 builtins/divmod().(secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds), 60) |
| 43 | |
| 44 | parts = [] |
| 45 | if days > 0: |
| 46 | parts.appendscip-python python python-stdlib 3.11 builtins/list#append().(f"{days}d") |
| 47 | if hours > 0 or (parts and (minutes > 0 or secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds) > 0)): |
| 48 | parts.appendscip-python python python-stdlib 3.11 builtins/list#append().(f"{hours}h") |
| 49 | if minutes > 0 or (parts and secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds) > 0): |
| 50 | parts.appendscip-python python python-stdlib 3.11 builtins/list#append().(f"{minutes}m") |
| 51 | if secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds) > 0 or not parts: |
| 52 | parts.appendscip-python python python-stdlib 3.11 builtins/list#append().(f"{secondsscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/seconds_as_dhms().(seconds)}s") |
| 53 | return ":".joinscip-python python python-stdlib 3.11 builtins/str#join().(parts) |
| 54 | |
| 55 | |
| 56 | def expiration_from_tokenscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/expiration_from_token().(tokenscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/expiration_from_token().(token): strscip-python python python-stdlib 3.11 builtins/str# | None) -> intscip-python python python-stdlib 3.11 builtins/int# | None: |
| 57 | """Return the expiration time from a token.""" |
| 58 | if not tokenscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/expiration_from_token().(token): |
| 59 | return None |
| 60 | |
| 61 | try: |
| 62 | decoded_token: Mappingscip-python python python-stdlib 3.11 typing/Mapping#[strscip-python python python-stdlib 3.11 builtins/str#, Anyscip-python python python-stdlib 3.11 typing/Any.] = jwt.decode( |
| 63 | tokenscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/expiration_from_token().(token), |
| 64 | options={"verify_signature": False}, |
| 65 | ) |
| 66 | return intscip-python python python-stdlib 3.11 builtins/int#(decoded_token["exp"]) |
| 67 | except (jwt.DecodeErrorscip-python python hass-nabucasa 0.0.0 `jwt.exceptions`/DecodeError#, KeyErrorscip-python python python-stdlib 3.11 builtins/KeyError#): |
| 68 | return None |
| 69 | |
| 70 | |
| 71 | def server_context_modernscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/server_context_modern().() -> sslscip-python python python-stdlib 3.11 ssl/__init__:.SSLContextscip-python python python-stdlib 3.11 ssl/SSLContext#: |
| 72 | """ |
| 73 | Return an SSL context following the Mozilla recommendations. |
| 74 | |
| 75 | TLS configuration follows the best-practice guidelines specified here: |
| 76 | https://wiki.mozilla.org/Security/Server_Side_TLS |
| 77 | Modern guidelines are followed. |
| 78 | """ |
| 79 | context = sslscip-python python python-stdlib 3.11 ssl/__init__:.SSLContextscip-python python python-stdlib 3.11 ssl/SSLContext#(sslscip-python python python-stdlib 3.11 ssl/__init__:.PROTOCOL_TLSscip-python python python-stdlib 3.11 ssl/PROTOCOL_TLS.PROTOCOL_TLS.) # pylint: disable=no-member |
| 80 | |
| 81 | context.optionsscip-python python python-stdlib 3.11 ssl/SSLContext#options. |= ( |
| 82 | sslscip-python python python-stdlib 3.11 ssl/__init__:.OP_NO_SSLv2scip-python python python-stdlib 3.11 ssl/OP_NO_SSLv2.OP_NO_SSLv2. |
| 83 | | sslscip-python python python-stdlib 3.11 ssl/__init__:.OP_NO_SSLv3scip-python python python-stdlib 3.11 ssl/OP_NO_SSLv3.OP_NO_SSLv3. |
| 84 | | sslscip-python python python-stdlib 3.11 ssl/__init__:.OP_NO_TLSv1scip-python python python-stdlib 3.11 ssl/OP_NO_TLSv1.OP_NO_TLSv1. |
| 85 | | sslscip-python python python-stdlib 3.11 ssl/__init__:.OP_NO_TLSv1_1scip-python python python-stdlib 3.11 ssl/OP_NO_TLSv1_1.OP_NO_TLSv1_1. |
| 86 | | sslscip-python python python-stdlib 3.11 ssl/__init__:.OP_CIPHER_SERVER_PREFERENCEscip-python python python-stdlib 3.11 ssl/OP_CIPHER_SERVER_PREFERENCE.OP_CIPHER_SERVER_PREFERENCE. |
| 87 | ) |
| 88 | if hasattr(sslscip-python python python-stdlib 3.11 ssl/__init__:, "OP_NO_COMPRESSION"): |
| 89 | context.optionsscip-python python python-stdlib 3.11 ssl/SSLContext#options. |= sslscip-python python python-stdlib 3.11 ssl/__init__:.OP_NO_COMPRESSIONscip-python python python-stdlib 3.11 ssl/OP_NO_COMPRESSION.OP_NO_COMPRESSION. |
| 90 | |
| 91 | context.set_ciphersscip-python python python-stdlib 3.11 ssl/SSLContext#set_ciphers().( |
| 92 | "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:" |
| 93 | "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:" |
| 94 | "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:" |
| 95 | "ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:" |
| 96 | "ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256", |
| 97 | ) |
| 98 | |
| 99 | return context |
| 100 | |
| 101 | |
| 102 | def next_midnightscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/next_midnight().() -> floatscip-python python python-stdlib 3.11 builtins/float#: |
| 103 | """Return the seconds till next local midnight.""" |
| 104 | midnight = dt.datetimescip-python python python-stdlib 3.11 datetime/datetime#.nowscip-python python python-stdlib 3.11 datetime/datetime#now().().replacescip-python python python-stdlib 3.11 datetime/datetime#replace().( |
| 105 | hourscip-python python python-stdlib 3.11 datetime/datetime#replace().(hour)=0, |
| 106 | minutescip-python python python-stdlib 3.11 datetime/datetime#replace().(minute)=0, |
| 107 | secondscip-python python python-stdlib 3.11 datetime/datetime#replace().(second)=0, |
| 108 | microsecondscip-python python python-stdlib 3.11 datetime/datetime#replace().(microsecond)=0, |
| 109 | ) + dt.timedeltascip-python python python-stdlib 3.11 datetime/timedelta#(days=1) |
| 110 | return (midnight - dt.datetimescip-python python python-stdlib 3.11 datetime/datetime#.nowscip-python python python-stdlib 3.11 datetime/datetime#now().()).total_secondsscip-python python python-stdlib 3.11 datetime/timedelta#total_seconds().() |
| 111 | |
| 112 | |
| 113 | def jitterscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/jitter().(minimumscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/jitter().(minimum): floatscip-python python python-stdlib 3.11 builtins/float#, maximumscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/jitter().(maximum): floatscip-python python python-stdlib 3.11 builtins/float#) -> floatscip-python python python-stdlib 3.11 builtins/float#: |
| 114 | """Return a random float between minimum and maximum for backoff jitter.""" |
| 115 | return randomscip-python python python-stdlib 3.11 random/__init__:.uniformscip-python python python-stdlib 3.11 random/uniform.(minimumscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/jitter().(minimum), maximumscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/jitter().(maximum)) |
| 116 | |
| 117 | |
| 118 | async def gather_callbacksscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/gather_callbacks().( |
| 119 | loggerscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/gather_callbacks().(logger): Loggerscip-python python python-stdlib 3.11 logging/Logger#, |
| 120 | namescip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/gather_callbacks().(name): strscip-python python python-stdlib 3.11 builtins/str#, |
| 121 | callbacksscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/gather_callbacks().(callbacks): listscip-python python python-stdlib 3.11 builtins/list#[Callablescip-python python python-stdlib 3.11 typing/Callable.[[], Awaitablescip-python python python-stdlib 3.11 typing/Awaitable#[None]]], |
| 122 | ) -> None: |
| 123 | """Gather callbacks and log exceptions.""" |
| 124 | results = await asyncioscip-python python python-stdlib 3.11 asyncio/__init__:.gatherscip-python python hass-nabucasa 0.0.0 `asyncio.tasks`/Task#(*[cb() for cb in callbacksscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/gather_callbacks().(callbacks)], return_exceptions=True) |
| 125 | for result, callback in zipscip-python python python-stdlib 3.11 builtins/zip#(results, callbacksscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/gather_callbacks().(callbacks), strict=False): |
| 126 | if not isinstance(result, Exceptionscip-python python python-stdlib 3.11 builtins/Exception#): |
| 127 | continue |
| 128 | loggerscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/gather_callbacks().(logger).errorscip-python python python-stdlib 3.11 logging/Logger#error().( |
| 129 | "Unexpected error in %s callback %s", namescip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/gather_callbacks().(name), callback, exc_infoscip-python python python-stdlib 3.11 logging/Logger#error().(exc_info)=result |
| 130 | ) |
| 131 | |
| 132 | |
| 133 | class Registryscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#(dictscip-python python python-stdlib 3.11 builtins/dict#): |
| 134 | """Registry of items.""" |
| 135 | |
| 136 | def registerscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#register().(selfscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#register().(self), namescip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#register().(name): strscip-python python python-stdlib 3.11 builtins/str#) -> Callablescip-python python python-stdlib 3.11 typing/Callable.[[CALLABLE_Tscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/CALLABLE_T.], CALLABLE_Tscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/CALLABLE_T.]: |
| 137 | """Return decorator to register item with a specific name.""" |
| 138 | |
| 139 | def decoratorscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#decorator().(funcscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#decorator().(func): CALLABLE_Tscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/CALLABLE_T.) -> CALLABLE_Tscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/CALLABLE_T.: |
| 140 | """Register decorated function.""" |
| 141 | selfscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#register().(self)[namescip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#register().(name)] = funcscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#decorator().(func) |
| 142 | return funcscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#decorator().(func) |
| 143 | |
| 144 | return decoratorscip-python python hass-nabucasa 0.0.0 `hass_nabucasa.utils`/Registry#decorator(). |