Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Google Drive integration for backup #134576

Open
wants to merge 25 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .strict-typing
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ homeassistant.components.goalzero.*
homeassistant.components.google.*
homeassistant.components.google_assistant_sdk.*
homeassistant.components.google_cloud.*
homeassistant.components.google_drive.*
homeassistant.components.google_photos.*
homeassistant.components.google_sheets.*
homeassistant.components.govee_ble.*
Expand Down
2 changes: 2 additions & 0 deletions CODEOWNERS

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions homeassistant/brands/google.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"google_assistant",
"google_assistant_sdk",
"google_cloud",
"google_drive",
"google_generative_ai_conversation",
"google_mail",
"google_maps",
Expand Down
66 changes: 66 additions & 0 deletions homeassistant/components/google_drive/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""The Google Drive integration."""

from __future__ import annotations

from collections.abc import Callable

from aiohttp.client_exceptions import ClientError, ClientResponseError

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryError, ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.config_entry_oauth2_flow import (
OAuth2Session,
async_get_config_entry_implementation,
)
from homeassistant.util.hass_dict import HassKey

from .api import AsyncConfigEntryAuth, create_headers
from .const import DOMAIN, DRIVE_API_FILES

DATA_BACKUP_AGENT_LISTENERS: HassKey[list[Callable[[], None]]] = HassKey(
f"{DOMAIN}.backup_agent_listeners"
)

type GoogleDriveConfigEntry = ConfigEntry[AsyncConfigEntryAuth]


async def async_setup_entry(hass: HomeAssistant, entry: GoogleDriveConfigEntry) -> bool:
"""Set up Google Drive from a config entry."""
implementation = await async_get_config_entry_implementation(hass, entry)
session = OAuth2Session(hass, entry, implementation)
auth = AsyncConfigEntryAuth(hass, session)
access_token = await auth.check_and_refresh_token()
try:
resp = await async_get_clientsession(hass).get(
f"{DRIVE_API_FILES}/{entry.unique_id}",
tronikos marked this conversation as resolved.
Show resolved Hide resolved
params={"fields": ""},
headers=create_headers(access_token),
)
resp.raise_for_status()
except ClientError as err:
if isinstance(err, ClientResponseError) and 400 <= err.status < 500:
if err.status == 404:
raise ConfigEntryError(
translation_key="config_entry_error_folder_not_found"
) from err
raise ConfigEntryError(
translation_key="config_entry_error_folder_4xx"
) from err
raise ConfigEntryNotReady from err
zweckj marked this conversation as resolved.
Show resolved Hide resolved
entry.runtime_data = auth
return True


async def async_unload_entry(
hass: HomeAssistant, entry: GoogleDriveConfigEntry
) -> bool:
"""Unload a config entry."""
hass.async_create_task(_notify_backup_listeners(hass), eager_start=False)
return True


async def _notify_backup_listeners(hass: HomeAssistant) -> None:
for listener in hass.data.get(DATA_BACKUP_AGENT_LISTENERS, []):
listener()
66 changes: 66 additions & 0 deletions homeassistant/components/google_drive/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""API for Google Drive bound to Home Assistant OAuth."""

from __future__ import annotations

from aiohttp.client_exceptions import ClientError, ClientResponseError
from google.auth.exceptions import RefreshError

from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_ACCESS_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
HomeAssistantError,
)
from homeassistant.helpers import config_entry_oauth2_flow


def create_headers(access_token: str) -> dict[str, str]:
"""Create headers with the provided access token."""
return {
"Authorization": f"Bearer {access_token}",
}


class AsyncConfigEntryAuth:
"""Provide Google Drive authentication tied to an OAuth2 based config entry."""

def __init__(
self,
hass: HomeAssistant,
oauth2_session: config_entry_oauth2_flow.OAuth2Session,
) -> None:
"""Initialize Google Drive Auth."""
self._hass = hass
self.oauth_session = oauth2_session

@property
def access_token(self) -> str:
"""Return the access token."""
return str(self.oauth_session.token[CONF_ACCESS_TOKEN])

async def check_and_refresh_token(self) -> str:
"""Check the token."""
try:
await self.oauth_session.async_ensure_token_valid()
except (RefreshError, ClientResponseError, ClientError) as ex:
if (
self.oauth_session.config_entry.state
is ConfigEntryState.SETUP_IN_PROGRESS
):
if isinstance(ex, ClientResponseError) and 400 <= ex.status < 500:
raise ConfigEntryAuthFailed(
"OAuth session is not valid, reauth required"
) from ex
raise ConfigEntryNotReady from ex
if (
isinstance(ex, RefreshError)
or hasattr(ex, "status")
and ex.status == 400
):
self.oauth_session.config_entry.async_start_reauth(
self.oauth_session.hass
)
raise HomeAssistantError(ex) from ex
return self.access_token
21 changes: 21 additions & 0 deletions homeassistant/components/google_drive/application_credentials.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""application_credentials platform for Google Drive."""

from homeassistant.components.application_credentials import AuthorizationServer
from homeassistant.core import HomeAssistant


async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationServer:
"""Return authorization server."""
return AuthorizationServer(
"https://accounts.google.com/o/oauth2/v2/auth",
"https://oauth2.googleapis.com/token",
)


async def async_get_description_placeholders(hass: HomeAssistant) -> dict[str, str]:
"""Return description placeholders for the credentials dialog."""
return {
"oauth_consent_url": "https://console.cloud.google.com/apis/credentials/consent",
"more_info_url": "https://www.home-assistant.io/integrations/google_drive/",
"oauth_creds_url": "https://console.cloud.google.com/apis/credentials",
}
Loading
Loading