Skip to content

Commit

Permalink
feat: support custom backup names on Home Assistant Core
Browse files Browse the repository at this point in the history
  • Loading branch information
jcwillox committed Aug 11, 2022
1 parent cc4dcd8 commit 198fa29
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 7 deletions.
6 changes: 5 additions & 1 deletion custom_components/auto_backup/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
CONF_AUTO_PURGE,
CONF_BACKUP_TIMEOUT,
DEFAULT_BACKUP_TIMEOUT,
PATCH_NAME,
)
from .handlers import SupervisorHandler, HassioAPIError, BackupHandler, HandlerBase

Expand Down Expand Up @@ -291,7 +292,7 @@ def generate_backup_name(self) -> str:
def validate_backup_config(self, config: Dict):
"""Validate the backup config."""
if not self._supervised:
disallowed_options = [ATTR_NAME, ATTR_PASSWORD]
disallowed_options = [ATTR_PASSWORD]
for option in disallowed_options:
if config.get(option):
raise HomeAssistantError(
Expand All @@ -312,6 +313,9 @@ def validate_backup_config(self, config: Dict):
f"Partial backups (e.g. include/exclude) are not supported on non-supervised installations."
)

if config.get(ATTR_NAME):
config[PATCH_NAME] = True

if not config.get(ATTR_NAME):
config[ATTR_NAME] = self.generate_backup_name()

Expand Down
2 changes: 2 additions & 0 deletions custom_components/auto_backup/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@
EVENT_BACKUP_FAILED = f"{DOMAIN}.backup_failed"
EVENT_BACKUPS_PURGED = f"{DOMAIN}.purged_backups"

PATCH_NAME = "patch.name"

PLATFORMS = [Platform.SENSOR]
42 changes: 36 additions & 6 deletions custom_components/auto_backup/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
import async_timeout
from aiohttp.hdrs import AUTHORIZATION
from homeassistant.components.backup import BackupManager
from homeassistant.const import ATTR_NAME
from homeassistant.exceptions import HomeAssistantError

from .const import DEFAULT_BACKUP_TIMEOUT_SECONDS
from .const import DEFAULT_BACKUP_TIMEOUT_SECONDS, PATCH_NAME

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -39,9 +41,9 @@ async def get_addons(self) -> List[Dict]:
"""Returns a list of the installed addons."""
raise NotImplementedError

def create_backup(
async def create_backup(
self, data: Dict, partial: bool = False, timeout: Optional[int] = None
):
) -> Dict:
"""Create a full or partial backup.
This method return a coroutine.
Expand Down Expand Up @@ -172,10 +174,38 @@ def __init__(self, manager: BackupManager):
async def get_addons(self):
raise NotImplementedError("This should be unreachable")

# noinspection PyProtectedMember
async def create_backup(
self, data: Dict, partial: bool = False, timeout: Optional[int] = None
):
return (await self._manager.generate_backup()).as_dict()
self, config: Dict, partial: bool = False, timeout: Optional[int] = None
) -> Dict:
if not config.get(PATCH_NAME):
backup = await self._manager.generate_backup()
else:
_LOGGER.debug("Support name is set: %s", config)
if not hasattr(self._manager, "_generate_backup_contents"):
raise HomeAssistantError(
"Unable to patch '_generate_backup_contents' function."
)

def wrapper(*args, **kwargs):
if len(args) != 2 or kwargs or not isinstance(args[1], dict):
raise HomeAssistantError(
"Wrapper of '_generate_backup_contents' called with wrong arguments"
)

args[1]["name"] = config[ATTR_NAME]
old_function(*args, **kwargs)

old_function = self._manager._generate_backup_contents

try:
self._manager._generate_backup_contents = wrapper
backup = await self._manager.generate_backup()
backup.name = config[ATTR_NAME]
finally:
self._manager._generate_backup_contents = old_function

return backup.as_dict()

async def remove_backup(self, slug):
await self._manager.remove_backup(slug)
Expand Down

0 comments on commit 198fa29

Please sign in to comment.