2024-04-02 21:05:05 +00:00
|
|
|
"""Coordinator for imap integration."""
|
2024-03-08 13:52:48 +00:00
|
|
|
|
2023-01-09 10:41:47 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
from collections.abc import Mapping
|
2023-03-28 20:50:25 +00:00
|
|
|
from datetime import datetime, timedelta
|
2023-03-28 19:02:43 +00:00
|
|
|
import email
|
2023-05-28 11:28:11 +00:00
|
|
|
from email.header import decode_header, make_header
|
2023-11-19 19:15:02 +00:00
|
|
|
from email.message import Message
|
2023-05-28 11:28:11 +00:00
|
|
|
from email.utils import parseaddr, parsedate_to_datetime
|
2023-01-09 10:41:47 +00:00
|
|
|
import logging
|
2024-02-04 20:25:14 +00:00
|
|
|
from typing import TYPE_CHECKING, Any
|
2023-01-09 10:41:47 +00:00
|
|
|
|
2023-04-04 10:59:57 +00:00
|
|
|
from aioimaplib import AUTH, IMAP4_SSL, NONAUTH, SELECTED, AioImapException
|
2023-01-09 10:41:47 +00:00
|
|
|
|
2023-07-17 07:44:47 +00:00
|
|
|
from homeassistant.config_entries import ConfigEntry
|
2023-03-28 19:02:43 +00:00
|
|
|
from homeassistant.const import (
|
|
|
|
CONF_PASSWORD,
|
|
|
|
CONF_PORT,
|
|
|
|
CONF_USERNAME,
|
2023-05-30 17:48:47 +00:00
|
|
|
CONF_VERIFY_SSL,
|
2023-03-28 19:02:43 +00:00
|
|
|
CONTENT_TYPE_TEXT_PLAIN,
|
|
|
|
)
|
2023-01-09 10:41:47 +00:00
|
|
|
from homeassistant.core import HomeAssistant
|
2023-05-25 09:05:25 +00:00
|
|
|
from homeassistant.exceptions import (
|
|
|
|
ConfigEntryAuthFailed,
|
|
|
|
ConfigEntryError,
|
|
|
|
TemplateError,
|
|
|
|
)
|
2023-05-22 10:14:06 +00:00
|
|
|
from homeassistant.helpers.json import json_bytes
|
2023-05-25 09:05:25 +00:00
|
|
|
from homeassistant.helpers.template import Template
|
2023-01-09 10:41:47 +00:00
|
|
|
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
2024-02-09 10:30:27 +00:00
|
|
|
from homeassistant.util import dt as dt_util
|
2023-05-30 17:48:47 +00:00
|
|
|
from homeassistant.util.ssl import (
|
|
|
|
SSLCipherList,
|
|
|
|
client_context,
|
|
|
|
create_no_verify_ssl_context,
|
|
|
|
)
|
2023-01-09 10:41:47 +00:00
|
|
|
|
2023-04-24 13:37:21 +00:00
|
|
|
from .const import (
|
|
|
|
CONF_CHARSET,
|
2023-05-25 09:05:25 +00:00
|
|
|
CONF_CUSTOM_EVENT_DATA_TEMPLATE,
|
2023-04-24 13:37:21 +00:00
|
|
|
CONF_FOLDER,
|
2023-05-22 10:14:06 +00:00
|
|
|
CONF_MAX_MESSAGE_SIZE,
|
2023-04-24 13:37:21 +00:00
|
|
|
CONF_SEARCH,
|
|
|
|
CONF_SERVER,
|
|
|
|
CONF_SSL_CIPHER_LIST,
|
2023-05-22 10:14:06 +00:00
|
|
|
DEFAULT_MAX_MESSAGE_SIZE,
|
2023-04-24 13:37:21 +00:00
|
|
|
DOMAIN,
|
|
|
|
)
|
2023-01-09 10:41:47 +00:00
|
|
|
from .errors import InvalidAuth, InvalidFolder
|
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2023-03-17 21:45:15 +00:00
|
|
|
BACKOFF_TIME = 10
|
|
|
|
|
2023-03-28 19:02:43 +00:00
|
|
|
EVENT_IMAP = "imap_content"
|
2023-07-17 07:44:47 +00:00
|
|
|
MAX_ERRORS = 3
|
2023-05-22 10:14:06 +00:00
|
|
|
MAX_EVENT_DATA_BYTES = 32168
|
2023-03-28 19:02:43 +00:00
|
|
|
|
2024-02-09 10:30:27 +00:00
|
|
|
DIAGNOSTICS_ATTRIBUTES = ["date", "initial"]
|
|
|
|
|
2023-01-09 10:41:47 +00:00
|
|
|
|
|
|
|
async def connect_to_server(data: Mapping[str, Any]) -> IMAP4_SSL:
|
|
|
|
"""Connect to imap server and return client."""
|
2023-05-30 17:48:47 +00:00
|
|
|
ssl_cipher_list: str = data.get(CONF_SSL_CIPHER_LIST, SSLCipherList.PYTHON_DEFAULT)
|
|
|
|
if data.get(CONF_VERIFY_SSL, True):
|
2023-12-09 07:34:01 +00:00
|
|
|
ssl_context = client_context(ssl_cipher_list=SSLCipherList(ssl_cipher_list))
|
2023-05-30 17:48:47 +00:00
|
|
|
else:
|
|
|
|
ssl_context = create_no_verify_ssl_context()
|
2023-04-24 13:37:21 +00:00
|
|
|
client = IMAP4_SSL(data[CONF_SERVER], data[CONF_PORT], ssl_context=ssl_context)
|
2023-08-23 23:02:52 +00:00
|
|
|
_LOGGER.debug(
|
|
|
|
"Wait for hello message from server %s on port %s, verify_ssl: %s",
|
|
|
|
data[CONF_SERVER],
|
|
|
|
data[CONF_PORT],
|
|
|
|
data.get(CONF_VERIFY_SSL, True),
|
|
|
|
)
|
2023-01-09 10:41:47 +00:00
|
|
|
await client.wait_hello_from_server()
|
2023-04-04 10:59:57 +00:00
|
|
|
if client.protocol.state == NONAUTH:
|
2023-08-23 23:02:52 +00:00
|
|
|
_LOGGER.debug(
|
|
|
|
"Authenticating with %s on server %s",
|
|
|
|
data[CONF_USERNAME],
|
|
|
|
data[CONF_SERVER],
|
|
|
|
)
|
2023-04-04 10:59:57 +00:00
|
|
|
await client.login(data[CONF_USERNAME], data[CONF_PASSWORD])
|
|
|
|
if client.protocol.state not in {AUTH, SELECTED}:
|
2023-03-17 21:45:15 +00:00
|
|
|
raise InvalidAuth("Invalid username or password")
|
2023-04-04 10:59:57 +00:00
|
|
|
if client.protocol.state == AUTH:
|
2023-08-23 23:02:52 +00:00
|
|
|
_LOGGER.debug(
|
|
|
|
"Selecting mail folder %s on server %s",
|
|
|
|
data[CONF_FOLDER],
|
|
|
|
data[CONF_SERVER],
|
|
|
|
)
|
2023-04-04 10:59:57 +00:00
|
|
|
await client.select(data[CONF_FOLDER])
|
2023-01-09 10:41:47 +00:00
|
|
|
if client.protocol.state != SELECTED:
|
2023-03-17 21:45:15 +00:00
|
|
|
raise InvalidFolder(f"Folder {data[CONF_FOLDER]} is invalid")
|
2023-01-09 10:41:47 +00:00
|
|
|
return client
|
|
|
|
|
|
|
|
|
2023-03-28 19:02:43 +00:00
|
|
|
class ImapMessage:
|
|
|
|
"""Class to parse an RFC822 email message."""
|
|
|
|
|
2024-02-04 20:25:14 +00:00
|
|
|
def __init__(self, raw_message: bytes) -> None:
|
2023-03-28 19:02:43 +00:00
|
|
|
"""Initialize IMAP message."""
|
|
|
|
self.email_message = email.message_from_bytes(raw_message)
|
|
|
|
|
2024-02-05 07:59:03 +00:00
|
|
|
@staticmethod
|
|
|
|
def _decode_payload(part: Message) -> str:
|
|
|
|
"""Try to decode text payloads.
|
|
|
|
|
|
|
|
Common text encodings are quoted-printable or base64.
|
|
|
|
Falls back to the raw content part if decoding fails.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
decoded_payload: Any = part.get_payload(decode=True)
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
assert isinstance(decoded_payload, bytes)
|
|
|
|
content_charset = part.get_content_charset() or "utf-8"
|
|
|
|
return decoded_payload.decode(content_charset)
|
|
|
|
except ValueError:
|
|
|
|
# return undecoded payload
|
|
|
|
return str(part.get_payload())
|
|
|
|
|
2023-03-28 19:02:43 +00:00
|
|
|
@property
|
|
|
|
def headers(self) -> dict[str, tuple[str,]]:
|
|
|
|
"""Get the email headers."""
|
|
|
|
header_base: dict[str, tuple[str,]] = {}
|
|
|
|
for key, value in self.email_message.items():
|
2023-05-28 11:28:11 +00:00
|
|
|
header_instances: tuple[str,] = (str(value),)
|
|
|
|
if header_base.setdefault(key, header_instances) != header_instances:
|
|
|
|
header_base[key] += header_instances # type: ignore[assignment]
|
2023-03-28 19:02:43 +00:00
|
|
|
return header_base
|
|
|
|
|
2023-09-12 16:54:32 +00:00
|
|
|
@property
|
|
|
|
def message_id(self) -> str | None:
|
|
|
|
"""Get the message ID."""
|
|
|
|
value: str
|
|
|
|
for header, value in self.email_message.items():
|
|
|
|
if header == "Message-ID":
|
|
|
|
return value
|
|
|
|
return None
|
|
|
|
|
2023-03-28 20:50:25 +00:00
|
|
|
@property
|
|
|
|
def date(self) -> datetime | None:
|
|
|
|
"""Get the date the email was sent."""
|
|
|
|
# See https://www.rfc-editor.org/rfc/rfc2822#section-3.3
|
|
|
|
date_str: str | None
|
|
|
|
if (date_str := self.email_message["Date"]) is None:
|
|
|
|
return None
|
2023-05-28 11:28:11 +00:00
|
|
|
try:
|
|
|
|
mail_dt_tm = parsedate_to_datetime(date_str)
|
|
|
|
except ValueError:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Parsed date %s is not compliant with rfc2822#section-3.3", date_str
|
|
|
|
)
|
|
|
|
return None
|
|
|
|
return mail_dt_tm
|
2023-03-28 20:50:25 +00:00
|
|
|
|
2023-03-28 19:02:43 +00:00
|
|
|
@property
|
|
|
|
def sender(self) -> str:
|
|
|
|
"""Get the parsed message sender from the email."""
|
2023-05-28 11:28:11 +00:00
|
|
|
return str(parseaddr(self.email_message["From"])[1])
|
2023-03-28 19:02:43 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def subject(self) -> str:
|
|
|
|
"""Decode the message subject."""
|
2023-06-08 09:11:12 +00:00
|
|
|
decoded_header = decode_header(self.email_message["Subject"] or "")
|
2023-05-28 11:28:11 +00:00
|
|
|
subject_header = make_header(decoded_header)
|
|
|
|
return str(subject_header)
|
2023-03-28 19:02:43 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def text(self) -> str:
|
|
|
|
"""Get the message text from the email.
|
|
|
|
|
2024-02-04 20:25:14 +00:00
|
|
|
Will look for text/plain or use/ text/html if not found.
|
2023-03-28 19:02:43 +00:00
|
|
|
"""
|
2023-05-05 17:21:57 +00:00
|
|
|
message_text: str | None = None
|
|
|
|
message_html: str | None = None
|
|
|
|
message_untyped_text: str | None = None
|
2023-03-28 19:02:43 +00:00
|
|
|
|
2023-11-19 19:15:02 +00:00
|
|
|
part: Message
|
2023-03-28 19:02:43 +00:00
|
|
|
for part in self.email_message.walk():
|
|
|
|
if part.get_content_type() == CONTENT_TYPE_TEXT_PLAIN:
|
|
|
|
if message_text is None:
|
2024-02-05 07:59:03 +00:00
|
|
|
message_text = self._decode_payload(part)
|
2023-03-28 19:02:43 +00:00
|
|
|
elif part.get_content_type() == "text/html":
|
|
|
|
if message_html is None:
|
2024-02-05 07:59:03 +00:00
|
|
|
message_html = self._decode_payload(part)
|
2023-03-28 19:02:43 +00:00
|
|
|
elif (
|
|
|
|
part.get_content_type().startswith("text")
|
|
|
|
and message_untyped_text is None
|
|
|
|
):
|
2023-11-19 19:15:02 +00:00
|
|
|
message_untyped_text = str(part.get_payload())
|
2023-03-28 19:02:43 +00:00
|
|
|
|
|
|
|
if message_text is not None:
|
|
|
|
return message_text
|
|
|
|
|
|
|
|
if message_html is not None:
|
|
|
|
return message_html
|
|
|
|
|
|
|
|
if message_untyped_text is not None:
|
|
|
|
return message_untyped_text
|
|
|
|
|
2023-05-05 17:21:57 +00:00
|
|
|
return str(self.email_message.get_payload())
|
2023-03-28 19:02:43 +00:00
|
|
|
|
|
|
|
|
2023-03-17 21:45:15 +00:00
|
|
|
class ImapDataUpdateCoordinator(DataUpdateCoordinator[int | None]):
|
|
|
|
"""Base class for imap client."""
|
2023-01-09 10:41:47 +00:00
|
|
|
|
|
|
|
config_entry: ConfigEntry
|
2023-05-25 09:05:25 +00:00
|
|
|
custom_event_template: Template | None
|
2023-01-09 10:41:47 +00:00
|
|
|
|
2023-03-17 21:45:15 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
hass: HomeAssistant,
|
|
|
|
imap_client: IMAP4_SSL,
|
2023-05-25 09:05:25 +00:00
|
|
|
entry: ConfigEntry,
|
2023-03-17 21:45:15 +00:00
|
|
|
update_interval: timedelta | None,
|
|
|
|
) -> None:
|
2023-01-09 10:41:47 +00:00
|
|
|
"""Initiate imap client."""
|
|
|
|
self.imap_client = imap_client
|
2023-07-17 07:44:47 +00:00
|
|
|
self.auth_errors: int = 0
|
2023-09-12 16:54:32 +00:00
|
|
|
self._last_message_uid: str | None = None
|
2023-03-28 19:02:43 +00:00
|
|
|
self._last_message_id: str | None = None
|
2023-05-25 09:05:25 +00:00
|
|
|
self.custom_event_template = None
|
2024-02-09 10:30:27 +00:00
|
|
|
self._diagnostics_data: dict[str, Any] = {}
|
2023-05-25 09:05:25 +00:00
|
|
|
_custom_event_template = entry.data.get(CONF_CUSTOM_EVENT_DATA_TEMPLATE)
|
|
|
|
if _custom_event_template is not None:
|
|
|
|
self.custom_event_template = Template(_custom_event_template, hass=hass)
|
2023-01-09 10:41:47 +00:00
|
|
|
super().__init__(
|
|
|
|
hass,
|
|
|
|
_LOGGER,
|
|
|
|
name=DOMAIN,
|
2023-03-17 21:45:15 +00:00
|
|
|
update_interval=update_interval,
|
2023-01-09 10:41:47 +00:00
|
|
|
)
|
|
|
|
|
2023-03-17 21:45:15 +00:00
|
|
|
async def async_start(self) -> None:
|
|
|
|
"""Start coordinator."""
|
|
|
|
|
|
|
|
async def _async_reconnect_if_needed(self) -> None:
|
|
|
|
"""Connect to imap server."""
|
|
|
|
if self.imap_client is None:
|
|
|
|
self.imap_client = await connect_to_server(self.config_entry.data)
|
|
|
|
|
2023-09-12 16:54:32 +00:00
|
|
|
async def _async_process_event(self, last_message_uid: str) -> None:
|
2023-03-28 19:02:43 +00:00
|
|
|
"""Send a event for the last message if the last message was changed."""
|
2023-09-12 16:54:32 +00:00
|
|
|
response = await self.imap_client.fetch(last_message_uid, "BODY.PEEK[]")
|
2023-03-28 19:02:43 +00:00
|
|
|
if response.result == "OK":
|
2024-02-04 20:25:14 +00:00
|
|
|
message = ImapMessage(response.lines[1])
|
2023-09-12 16:54:32 +00:00
|
|
|
# Set `initial` to `False` if the last message is triggered again
|
|
|
|
initial: bool = True
|
|
|
|
if (message_id := message.message_id) == self._last_message_id:
|
|
|
|
initial = False
|
|
|
|
self._last_message_id = message_id
|
2023-03-28 19:02:43 +00:00
|
|
|
data = {
|
2024-04-02 21:05:05 +00:00
|
|
|
"entry_id": self.config_entry.entry_id,
|
2023-03-28 19:02:43 +00:00
|
|
|
"server": self.config_entry.data[CONF_SERVER],
|
|
|
|
"username": self.config_entry.data[CONF_USERNAME],
|
|
|
|
"search": self.config_entry.data[CONF_SEARCH],
|
|
|
|
"folder": self.config_entry.data[CONF_FOLDER],
|
2023-09-12 16:54:32 +00:00
|
|
|
"initial": initial,
|
2023-03-28 20:50:25 +00:00
|
|
|
"date": message.date,
|
2023-05-25 09:05:25 +00:00
|
|
|
"text": message.text,
|
2023-03-28 19:02:43 +00:00
|
|
|
"sender": message.sender,
|
|
|
|
"subject": message.subject,
|
|
|
|
"headers": message.headers,
|
2024-03-29 14:04:24 +00:00
|
|
|
"uid": last_message_uid,
|
2023-03-28 19:02:43 +00:00
|
|
|
}
|
2023-05-25 09:05:25 +00:00
|
|
|
if self.custom_event_template is not None:
|
|
|
|
try:
|
|
|
|
data["custom"] = self.custom_event_template.async_render(
|
|
|
|
data, parse_result=True
|
|
|
|
)
|
|
|
|
_LOGGER.debug(
|
2023-09-12 16:54:32 +00:00
|
|
|
"IMAP custom template (%s) for msguid %s (%s) rendered to: %s, initial: %s",
|
2023-05-25 09:05:25 +00:00
|
|
|
self.custom_event_template,
|
2023-09-12 16:54:32 +00:00
|
|
|
last_message_uid,
|
|
|
|
message_id,
|
2023-05-25 09:05:25 +00:00
|
|
|
data["custom"],
|
2023-09-12 16:54:32 +00:00
|
|
|
initial,
|
2023-05-25 09:05:25 +00:00
|
|
|
)
|
|
|
|
except TemplateError as err:
|
|
|
|
data["custom"] = None
|
|
|
|
_LOGGER.error(
|
2023-09-12 16:54:32 +00:00
|
|
|
"Error rendering IMAP custom template (%s) for msguid %s "
|
2023-05-25 09:05:25 +00:00
|
|
|
"failed with message: %s",
|
|
|
|
self.custom_event_template,
|
2023-09-12 16:54:32 +00:00
|
|
|
last_message_uid,
|
2023-05-25 09:05:25 +00:00
|
|
|
err,
|
|
|
|
)
|
|
|
|
data["text"] = message.text[
|
|
|
|
: self.config_entry.data.get(
|
|
|
|
CONF_MAX_MESSAGE_SIZE, DEFAULT_MAX_MESSAGE_SIZE
|
|
|
|
)
|
|
|
|
]
|
2024-02-09 10:30:27 +00:00
|
|
|
self._update_diagnostics(data)
|
2023-05-22 10:14:06 +00:00
|
|
|
if (size := len(json_bytes(data))) > MAX_EVENT_DATA_BYTES:
|
|
|
|
_LOGGER.warning(
|
|
|
|
"Custom imap_content event skipped, size (%s) exceeds "
|
|
|
|
"the maximal event size (%s), sender: %s, subject: %s",
|
|
|
|
size,
|
|
|
|
MAX_EVENT_DATA_BYTES,
|
|
|
|
message.sender,
|
|
|
|
message.subject,
|
|
|
|
)
|
|
|
|
return
|
|
|
|
|
2023-03-28 19:02:43 +00:00
|
|
|
self.hass.bus.fire(EVENT_IMAP, data)
|
|
|
|
_LOGGER.debug(
|
2023-09-12 16:54:32 +00:00
|
|
|
"Message with id %s (%s) processed, sender: %s, subject: %s, initial: %s",
|
|
|
|
last_message_uid,
|
|
|
|
message_id,
|
2023-03-28 19:02:43 +00:00
|
|
|
message.sender,
|
|
|
|
message.subject,
|
2023-09-12 16:54:32 +00:00
|
|
|
initial,
|
2023-03-28 19:02:43 +00:00
|
|
|
)
|
|
|
|
|
2023-03-17 21:45:15 +00:00
|
|
|
async def _async_fetch_number_of_messages(self) -> int | None:
|
2023-03-28 19:02:43 +00:00
|
|
|
"""Fetch last message and messages count."""
|
2023-03-17 21:45:15 +00:00
|
|
|
await self._async_reconnect_if_needed()
|
|
|
|
await self.imap_client.noop()
|
|
|
|
result, lines = await self.imap_client.search(
|
|
|
|
self.config_entry.data[CONF_SEARCH],
|
|
|
|
charset=self.config_entry.data[CONF_CHARSET],
|
|
|
|
)
|
2023-01-09 10:41:47 +00:00
|
|
|
if result != "OK":
|
|
|
|
raise UpdateFailed(
|
|
|
|
f"Invalid response for search '{self.config_entry.data[CONF_SEARCH]}': {result} / {lines[0]}"
|
|
|
|
)
|
2023-05-15 19:15:10 +00:00
|
|
|
if not (count := len(message_ids := lines[0].split())):
|
2023-09-12 16:54:32 +00:00
|
|
|
self._last_message_uid = None
|
2023-05-15 19:15:10 +00:00
|
|
|
return 0
|
2023-09-12 16:54:32 +00:00
|
|
|
last_message_uid = (
|
2023-03-28 19:02:43 +00:00
|
|
|
str(message_ids[-1:][0], encoding=self.config_entry.data[CONF_CHARSET])
|
|
|
|
if count
|
|
|
|
else None
|
|
|
|
)
|
2023-04-06 20:46:32 +00:00
|
|
|
if (
|
|
|
|
count
|
2023-09-12 16:54:32 +00:00
|
|
|
and last_message_uid is not None
|
|
|
|
and self._last_message_uid != last_message_uid
|
2023-04-06 20:46:32 +00:00
|
|
|
):
|
2023-09-12 16:54:32 +00:00
|
|
|
self._last_message_uid = last_message_uid
|
|
|
|
await self._async_process_event(last_message_uid)
|
2023-03-28 19:02:43 +00:00
|
|
|
|
|
|
|
return count
|
2023-01-09 10:41:47 +00:00
|
|
|
|
2023-03-17 21:45:15 +00:00
|
|
|
async def _cleanup(self, log_error: bool = False) -> None:
|
|
|
|
"""Close resources."""
|
|
|
|
if self.imap_client:
|
|
|
|
try:
|
|
|
|
if self.imap_client.has_pending_idle():
|
|
|
|
self.imap_client.idle_done()
|
|
|
|
await self.imap_client.stop_wait_server_push()
|
|
|
|
await self.imap_client.close()
|
|
|
|
await self.imap_client.logout()
|
2024-02-05 11:00:37 +00:00
|
|
|
except (AioImapException, TimeoutError):
|
2023-03-17 21:45:15 +00:00
|
|
|
if log_error:
|
2023-04-05 10:18:16 +00:00
|
|
|
_LOGGER.debug("Error while cleaning up imap connection")
|
2023-07-23 18:30:15 +00:00
|
|
|
finally:
|
|
|
|
self.imap_client = None
|
2023-01-09 10:41:47 +00:00
|
|
|
|
2023-05-05 17:21:57 +00:00
|
|
|
async def shutdown(self, *_: Any) -> None:
|
2023-01-09 10:41:47 +00:00
|
|
|
"""Close resources."""
|
2023-03-17 21:45:15 +00:00
|
|
|
await self._cleanup(log_error=True)
|
|
|
|
|
2024-02-09 10:30:27 +00:00
|
|
|
def _update_diagnostics(self, data: dict[str, Any]) -> None:
|
|
|
|
"""Update the diagnostics."""
|
|
|
|
self._diagnostics_data.update(
|
|
|
|
{key: value for key, value in data.items() if key in DIAGNOSTICS_ATTRIBUTES}
|
|
|
|
)
|
|
|
|
custom: Any | None = data.get("custom")
|
|
|
|
self._diagnostics_data["custom_template_data_type"] = str(type(custom))
|
|
|
|
self._diagnostics_data["custom_template_result_length"] = (
|
|
|
|
None if custom is None else len(f"{custom}")
|
|
|
|
)
|
|
|
|
self._diagnostics_data["event_time"] = dt_util.now().isoformat()
|
|
|
|
|
|
|
|
@property
|
|
|
|
def diagnostics_data(self) -> dict[str, Any]:
|
|
|
|
"""Return diagnostics info."""
|
|
|
|
return self._diagnostics_data
|
|
|
|
|
2023-03-17 21:45:15 +00:00
|
|
|
|
|
|
|
class ImapPollingDataUpdateCoordinator(ImapDataUpdateCoordinator):
|
|
|
|
"""Class for imap client."""
|
|
|
|
|
2023-05-25 09:05:25 +00:00
|
|
|
def __init__(
|
|
|
|
self, hass: HomeAssistant, imap_client: IMAP4_SSL, entry: ConfigEntry
|
|
|
|
) -> None:
|
2023-03-17 21:45:15 +00:00
|
|
|
"""Initiate imap client."""
|
2023-08-23 23:02:52 +00:00
|
|
|
_LOGGER.debug(
|
|
|
|
"Connected to server %s using IMAP polling", entry.data[CONF_SERVER]
|
|
|
|
)
|
2023-05-25 09:05:25 +00:00
|
|
|
super().__init__(hass, imap_client, entry, timedelta(seconds=10))
|
2023-03-17 21:45:15 +00:00
|
|
|
|
|
|
|
async def _async_update_data(self) -> int | None:
|
|
|
|
"""Update the number of unread emails."""
|
|
|
|
try:
|
2023-07-17 07:44:47 +00:00
|
|
|
messages = await self._async_fetch_number_of_messages()
|
2023-03-17 21:45:15 +00:00
|
|
|
except (
|
|
|
|
AioImapException,
|
|
|
|
UpdateFailed,
|
2024-02-05 11:00:37 +00:00
|
|
|
TimeoutError,
|
2023-03-17 21:45:15 +00:00
|
|
|
) as ex:
|
|
|
|
await self._cleanup()
|
2023-04-06 20:46:32 +00:00
|
|
|
self.async_set_update_error(ex)
|
2024-03-17 23:40:38 +00:00
|
|
|
raise UpdateFailed from ex
|
2023-03-17 21:45:15 +00:00
|
|
|
except InvalidFolder as ex:
|
|
|
|
_LOGGER.warning("Selected mailbox folder is invalid")
|
|
|
|
await self._cleanup()
|
2023-04-06 20:46:32 +00:00
|
|
|
self.async_set_update_error(ex)
|
2023-03-17 21:45:15 +00:00
|
|
|
raise ConfigEntryError("Selected mailbox folder is invalid.") from ex
|
|
|
|
except InvalidAuth as ex:
|
|
|
|
await self._cleanup()
|
2023-07-17 07:44:47 +00:00
|
|
|
self.auth_errors += 1
|
|
|
|
if self.auth_errors <= MAX_ERRORS:
|
|
|
|
_LOGGER.warning("Authentication failed, retrying")
|
|
|
|
else:
|
|
|
|
_LOGGER.warning(
|
|
|
|
"Username or password incorrect, starting reauthentication"
|
|
|
|
)
|
|
|
|
self.config_entry.async_start_reauth(self.hass)
|
2023-04-06 20:46:32 +00:00
|
|
|
self.async_set_update_error(ex)
|
2024-03-17 23:40:38 +00:00
|
|
|
raise ConfigEntryAuthFailed from ex
|
2023-03-17 21:45:15 +00:00
|
|
|
|
2024-03-30 09:37:59 +00:00
|
|
|
self.auth_errors = 0
|
|
|
|
return messages
|
|
|
|
|
2023-03-17 21:45:15 +00:00
|
|
|
|
|
|
|
class ImapPushDataUpdateCoordinator(ImapDataUpdateCoordinator):
|
|
|
|
"""Class for imap client."""
|
|
|
|
|
2023-05-25 09:05:25 +00:00
|
|
|
def __init__(
|
|
|
|
self, hass: HomeAssistant, imap_client: IMAP4_SSL, entry: ConfigEntry
|
|
|
|
) -> None:
|
2023-03-17 21:45:15 +00:00
|
|
|
"""Initiate imap client."""
|
2023-08-23 23:02:52 +00:00
|
|
|
_LOGGER.debug("Connected to server %s using IMAP push", entry.data[CONF_SERVER])
|
2023-05-25 09:05:25 +00:00
|
|
|
super().__init__(hass, imap_client, entry, None)
|
2023-03-17 21:45:15 +00:00
|
|
|
self._push_wait_task: asyncio.Task[None] | None = None
|
|
|
|
|
|
|
|
async def _async_update_data(self) -> int | None:
|
|
|
|
"""Update the number of unread emails."""
|
|
|
|
await self.async_start()
|
|
|
|
return None
|
|
|
|
|
|
|
|
async def async_start(self) -> None:
|
|
|
|
"""Start coordinator."""
|
|
|
|
self._push_wait_task = self.hass.async_create_background_task(
|
|
|
|
self._async_wait_push_loop(), "Wait for IMAP data push"
|
|
|
|
)
|
|
|
|
|
|
|
|
async def _async_wait_push_loop(self) -> None:
|
|
|
|
"""Wait for data push from server."""
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
number_of_messages = await self._async_fetch_number_of_messages()
|
|
|
|
except InvalidAuth as ex:
|
2023-07-17 07:44:47 +00:00
|
|
|
self.auth_errors += 1
|
2023-04-05 10:18:16 +00:00
|
|
|
await self._cleanup()
|
2023-07-17 07:44:47 +00:00
|
|
|
if self.auth_errors <= MAX_ERRORS:
|
|
|
|
_LOGGER.warning("Authentication failed, retrying")
|
|
|
|
else:
|
|
|
|
_LOGGER.warning(
|
|
|
|
"Username or password incorrect, starting reauthentication"
|
|
|
|
)
|
|
|
|
self.config_entry.async_start_reauth(self.hass)
|
2023-03-17 21:45:15 +00:00
|
|
|
self.async_set_update_error(ex)
|
|
|
|
await asyncio.sleep(BACKOFF_TIME)
|
|
|
|
except InvalidFolder as ex:
|
|
|
|
_LOGGER.warning("Selected mailbox folder is invalid")
|
2023-04-05 10:18:16 +00:00
|
|
|
await self._cleanup()
|
2023-03-17 21:45:15 +00:00
|
|
|
self.async_set_update_error(ex)
|
|
|
|
await asyncio.sleep(BACKOFF_TIME)
|
2023-07-17 07:44:47 +00:00
|
|
|
continue
|
2023-03-17 21:45:15 +00:00
|
|
|
except (
|
|
|
|
UpdateFailed,
|
|
|
|
AioImapException,
|
2024-02-05 11:00:37 +00:00
|
|
|
TimeoutError,
|
2023-03-17 21:45:15 +00:00
|
|
|
) as ex:
|
|
|
|
await self._cleanup()
|
2023-04-05 10:18:16 +00:00
|
|
|
self.async_set_update_error(ex)
|
2023-03-17 21:45:15 +00:00
|
|
|
await asyncio.sleep(BACKOFF_TIME)
|
|
|
|
continue
|
|
|
|
else:
|
2023-07-17 07:44:47 +00:00
|
|
|
self.auth_errors = 0
|
2023-03-17 21:45:15 +00:00
|
|
|
self.async_set_updated_data(number_of_messages)
|
|
|
|
try:
|
|
|
|
idle: asyncio.Future = await self.imap_client.idle_start()
|
|
|
|
await self.imap_client.wait_server_push()
|
2023-03-15 20:22:13 +00:00
|
|
|
self.imap_client.idle_done()
|
2023-08-15 12:32:15 +00:00
|
|
|
async with asyncio.timeout(10):
|
2023-03-17 21:45:15 +00:00
|
|
|
await idle
|
|
|
|
|
2024-02-05 11:00:37 +00:00
|
|
|
except (AioImapException, TimeoutError):
|
2023-04-05 10:18:16 +00:00
|
|
|
_LOGGER.debug(
|
2023-03-17 21:45:15 +00:00
|
|
|
"Lost %s (will attempt to reconnect after %s s)",
|
|
|
|
self.config_entry.data[CONF_SERVER],
|
|
|
|
BACKOFF_TIME,
|
|
|
|
)
|
2023-04-06 20:46:32 +00:00
|
|
|
await self._cleanup()
|
2023-03-17 21:45:15 +00:00
|
|
|
await asyncio.sleep(BACKOFF_TIME)
|
|
|
|
|
2023-05-05 17:21:57 +00:00
|
|
|
async def shutdown(self, *_: Any) -> None:
|
2023-03-17 21:45:15 +00:00
|
|
|
"""Close resources."""
|
|
|
|
if self._push_wait_task:
|
|
|
|
self._push_wait_task.cancel()
|
|
|
|
await super().shutdown()
|