Add config flow for cloudflare (#41167)
* add config flow for cloudflare * Create const.py * work on flow. * remove const. * lint. * Apply suggestions from code review Co-authored-by: J. Nick Koston <nick@koston.org> * Update config_flows.py * Update homeassistant/components/cloudflare/strings.json * Apply suggestions from code review * Apply suggestions from code review * Apply suggestions from code review * Update strings.json * Apply suggestions from code review * Update __init__.py * Update __init__.py Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
1 parent
e203896638
commit
d8577a1550
14 files changed
+692
-49
No files matched your search
@@ -1,74 +1,130 @@
|
||||
"""Update the IP addresses of your Cloudflare DNS records."""
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
from typing import Dict
|
||||
|
||||
from pycfdns import CloudflareUpdater
|
||||
from pycfdns.exceptions import (
|
||||
CloudflareAuthenticationException,
|
||||
CloudflareConnectionException,
|
||||
CloudflareException,
|
||||
)
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.const import CONF_API_KEY, CONF_EMAIL, CONF_ZONE
|
||||
from homeassistant.components import persistent_notification
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_API_KEY, CONF_API_TOKEN, CONF_EMAIL, CONF_ZONE
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.event import track_time_interval
|
||||
from homeassistant.helpers.event import async_track_time_interval
|
||||
|
||||
from .const import (
|
||||
CONF_RECORDS,
|
||||
DATA_UNDO_UPDATE_INTERVAL,
|
||||
DEFAULT_UPDATE_INTERVAL,
|
||||
DOMAIN,
|
||||
SERVICE_UPDATE_RECORDS,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONF_RECORDS = "records"
|
||||
|
||||
DOMAIN = "cloudflare"
|
||||
|
||||
INTERVAL = timedelta(minutes=60)
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{
|
||||
DOMAIN: vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_EMAIL): cv.string,
|
||||
vol.Required(CONF_API_KEY): cv.string,
|
||||
vol.Required(CONF_ZONE): cv.string,
|
||||
vol.Required(CONF_RECORDS): vol.All(cv.ensure_list, [cv.string]),
|
||||
}
|
||||
DOMAIN: vol.All(
|
||||
cv.deprecated(CONF_EMAIL, invalidation_version="0.119"),
|
||||
cv.deprecated(CONF_API_KEY, invalidation_version="0.119"),
|
||||
cv.deprecated(CONF_ZONE, invalidation_version="0.119"),
|
||||
cv.deprecated(CONF_RECORDS, invalidation_version="0.119"),
|
||||
vol.Schema(
|
||||
{
|
||||
vol.Optional(CONF_EMAIL): cv.string,
|
||||
vol.Optional(CONF_API_KEY): cv.string,
|
||||
vol.Optional(CONF_ZONE): cv.string,
|
||||
vol.Optional(CONF_RECORDS): vol.All(cv.ensure_list, [cv.string]),
|
||||
}
|
||||
),
|
||||
)
|
||||
},
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
|
||||
|
||||
def setup(hass, config):
|
||||
"""Set up the Cloudflare component."""
|
||||
async def async_setup(hass: HomeAssistant, config: Dict) -> bool:
|
||||
"""Set up the component."""
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
|
||||
cfupdate = CloudflareUpdater()
|
||||
email = config[DOMAIN][CONF_EMAIL]
|
||||
key = config[DOMAIN][CONF_API_KEY]
|
||||
zone = config[DOMAIN][CONF_ZONE]
|
||||
records = config[DOMAIN][CONF_RECORDS]
|
||||
if len(hass.config_entries.async_entries(DOMAIN)) > 0:
|
||||
return True
|
||||
|
||||
def update_records_interval(now):
|
||||
"""Set up recurring update."""
|
||||
_update_cloudflare(cfupdate, email, key, zone, records)
|
||||
if DOMAIN in config and CONF_API_KEY in config[DOMAIN]:
|
||||
persistent_notification.async_create(
|
||||
hass,
|
||||
"Cloudflare integration now requires an API Token. Please go to the integrations page to setup.",
|
||||
"Cloudflare Setup",
|
||||
"cloudflare_setup",
|
||||
)
|
||||
|
||||
def update_records_service(now):
|
||||
"""Set up service for manual trigger."""
|
||||
_update_cloudflare(cfupdate, email, key, zone, records)
|
||||
|
||||
track_time_interval(hass, update_records_interval, INTERVAL)
|
||||
hass.services.register(DOMAIN, "update_records", update_records_service)
|
||||
return True
|
||||
|
||||
|
||||
def _update_cloudflare(cfupdate, email, key, zone, records):
|
||||
"""Update DNS records for a given zone."""
|
||||
_LOGGER.debug("Starting update for zone %s", zone)
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Set up Cloudflare from a config entry."""
|
||||
cfupdate = CloudflareUpdater(
|
||||
async_get_clientsession(hass),
|
||||
entry.data[CONF_API_TOKEN],
|
||||
entry.data[CONF_ZONE],
|
||||
entry.data[CONF_RECORDS],
|
||||
)
|
||||
|
||||
headers = cfupdate.set_header(email, key)
|
||||
_LOGGER.debug("Header data defined as: %s", headers)
|
||||
try:
|
||||
zone_id = await cfupdate.get_zone_id()
|
||||
except CloudflareAuthenticationException:
|
||||
_LOGGER.error("API access forbidden. Please reauthenticate")
|
||||
return False
|
||||
except CloudflareConnectionException as error:
|
||||
raise ConfigEntryNotReady from error
|
||||
|
||||
zoneid = cfupdate.get_zoneID(headers, zone)
|
||||
_LOGGER.debug("Zone ID is set to: %s", zoneid)
|
||||
async def update_records(now):
|
||||
"""Set up recurring update."""
|
||||
try:
|
||||
await _async_update_cloudflare(cfupdate, zone_id)
|
||||
except CloudflareException as error:
|
||||
_LOGGER.error("Error updating zone %s: %s", entry.data[CONF_ZONE], error)
|
||||
|
||||
update_records = cfupdate.get_recordInfo(headers, zoneid, zone, records)
|
||||
_LOGGER.debug("Records: %s", update_records)
|
||||
async def update_records_service(call):
|
||||
"""Set up service for manual trigger."""
|
||||
try:
|
||||
await _async_update_cloudflare(cfupdate, zone_id)
|
||||
except CloudflareException as error:
|
||||
_LOGGER.error("Error updating zone %s: %s", entry.data[CONF_ZONE], error)
|
||||
|
||||
result = cfupdate.update_records(headers, zoneid, update_records)
|
||||
_LOGGER.debug("Update for zone %s is complete", zone)
|
||||
update_interval = timedelta(minutes=DEFAULT_UPDATE_INTERVAL)
|
||||
undo_interval = async_track_time_interval(hass, update_records, update_interval)
|
||||
|
||||
if result is not True:
|
||||
_LOGGER.warning(result)
|
||||
hass.data[DOMAIN][entry.entry_id] = {
|
||||
DATA_UNDO_UPDATE_INTERVAL: undo_interval,
|
||||
}
|
||||
|
||||
hass.services.async_register(DOMAIN, SERVICE_UPDATE_RECORDS, update_records_service)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Unload Cloudflare config entry."""
|
||||
hass.data[DOMAIN][entry.entry_id][DATA_UNDO_UPDATE_INTERVAL]()
|
||||
hass.data[DOMAIN].pop(entry.entry_id)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def _async_update_cloudflare(cfupdate: CloudflareUpdater, zone_id: str):
|
||||
_LOGGER.debug("Starting update for zone %s", cfupdate.zone)
|
||||
|
||||
records = await cfupdate.get_record_info(zone_id)
|
||||
_LOGGER.debug("Records: %s", records)
|
||||
|
||||
await cfupdate.update_records(zone_id, records)
|
||||
_LOGGER.debug("Update for zone %s is complete", cfupdate.zone)
|
||||
Reference in new issue
Block a user