Home Assistant Unofficial Reference 2024.12.1
services.py
Go to the documentation of this file.
1 """Services for Google Mail integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import datetime, timedelta
6 from typing import TYPE_CHECKING
7 
8 from googleapiclient.http import HttpRequest
9 import voluptuous as vol
10 
11 from homeassistant.core import HomeAssistant, ServiceCall
12 from homeassistant.helpers import config_validation as cv
13 from homeassistant.helpers.service import async_extract_config_entry_ids
14 
15 from .const import (
16  ATTR_ENABLED,
17  ATTR_END,
18  ATTR_ME,
19  ATTR_MESSAGE,
20  ATTR_PLAIN_TEXT,
21  ATTR_RESTRICT_CONTACTS,
22  ATTR_RESTRICT_DOMAIN,
23  ATTR_START,
24  ATTR_TITLE,
25  DOMAIN,
26 )
27 
28 if TYPE_CHECKING:
29  from . import GoogleMailConfigEntry
30 
31 SERVICE_SET_VACATION = "set_vacation"
32 
33 SERVICE_VACATION_SCHEMA = vol.All(
34  cv.make_entity_service_schema(
35  {
36  vol.Required(ATTR_ENABLED, default=True): cv.boolean,
37  vol.Optional(ATTR_TITLE): cv.string,
38  vol.Required(ATTR_MESSAGE): cv.string,
39  vol.Optional(ATTR_PLAIN_TEXT, default=True): cv.boolean,
40  vol.Optional(ATTR_RESTRICT_CONTACTS): cv.boolean,
41  vol.Optional(ATTR_RESTRICT_DOMAIN): cv.boolean,
42  vol.Optional(ATTR_START): cv.date,
43  vol.Optional(ATTR_END): cv.date,
44  },
45  )
46 )
47 
48 
49 async def async_setup_services(hass: HomeAssistant) -> None:
50  """Set up services for Google Mail integration."""
51 
52  async def extract_gmail_config_entries(
53  call: ServiceCall,
54  ) -> list[GoogleMailConfigEntry]:
55  return [
56  entry
57  for entry_id in await async_extract_config_entry_ids(hass, call)
58  if (entry := hass.config_entries.async_get_entry(entry_id))
59  and entry.domain == DOMAIN
60  ]
61 
62  async def gmail_service(call: ServiceCall) -> None:
63  """Call Google Mail service."""
64  for entry in await extract_gmail_config_entries(call):
65  try:
66  auth = entry.runtime_data
67  except AttributeError as ex:
68  raise ValueError(f"Config entry not loaded: {entry.entry_id}") from ex
69  service = await auth.get_resource()
70 
71  _settings = {
72  "enableAutoReply": call.data[ATTR_ENABLED],
73  "responseSubject": call.data.get(ATTR_TITLE),
74  }
75  if contacts := call.data.get(ATTR_RESTRICT_CONTACTS):
76  _settings["restrictToContacts"] = contacts
77  if domain := call.data.get(ATTR_RESTRICT_DOMAIN):
78  _settings["restrictToDomain"] = domain
79  if _date := call.data.get(ATTR_START):
80  _dt = datetime.combine(_date, datetime.min.time())
81  _settings["startTime"] = _dt.timestamp() * 1000
82  if _date := call.data.get(ATTR_END):
83  _dt = datetime.combine(_date, datetime.min.time())
84  _settings["endTime"] = (_dt + timedelta(days=1)).timestamp() * 1000
85  if call.data[ATTR_PLAIN_TEXT]:
86  _settings["responseBodyPlainText"] = call.data[ATTR_MESSAGE]
87  else:
88  _settings["responseBodyHtml"] = call.data[ATTR_MESSAGE]
89  settings: HttpRequest = (
90  service.users()
91  .settings()
92  .updateVacation(userId=ATTR_ME, body=_settings)
93  )
94  await hass.async_add_executor_job(settings.execute)
95 
96  hass.services.async_register(
97  domain=DOMAIN,
98  service=SERVICE_SET_VACATION,
99  schema=SERVICE_VACATION_SCHEMA,
100  service_func=gmail_service,
101  )
None async_setup_services(HomeAssistant hass)
Definition: services.py:49
set[str] async_extract_config_entry_ids(HomeAssistant hass, ServiceCall service_call, bool expand_group=True)
Definition: service.py:635