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

Make Send Check ID Optional #45

Closed
Closed
Show file tree
Hide file tree
Changes from all 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
86 changes: 58 additions & 28 deletions custom_components/healthchecksio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,24 @@
For more details about this component, please refer to
https://github.com/custom-components/healthchecksio
"""
import os
import async_timeout
import asyncio
import json
import os
from datetime import timedelta

import aiohttp
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import voluptuous as vol
from homeassistant import config_entries
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import discovery
from homeassistant.util import Throttle

from integrationhelper.const import CC_STARTUP_VERSION
from integrationhelper import Logger
from integrationhelper.const import CC_STARTUP_VERSION

from .const import (
DOMAIN_DATA,
DOMAIN,
ISSUE_URL,
REQUIRED_FILES,
DOMAIN_DATA,
INTEGRATION_VERSION,
ISSUE_URL,
OFFICIAL_SITE_ROOT,
REQUIRED_FILES,
)

MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=300)
Expand Down Expand Up @@ -95,28 +92,61 @@ def __init__(self, hass, api_key, check, self_hosted, site_root, ping_endpoint):
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def update_data(self):
"""Update data."""
Logger("custom_components.healthchecksio").debug("Running update")
Logger("custom_components.healthchecksio").debug("Running Update")
# This is where the main logic to update platform data goes.
try:
verify_ssl = not self.self_hosted or self.site_root.startswith("https")
session = async_get_clientsession(self.hass, verify_ssl)
headers = {"X-Api-Key": self.api_key}
async with async_timeout.timeout(10):
data = await session.get(
f"{self.site_root}/api/v1/checks/", headers=headers
verify_ssl = not self.self_hosted or self.site_root.startswith("https")
session = async_get_clientsession(self.hass, verify_ssl)
timeout10 = aiohttp.ClientTimeout(total=10)
headers = {"X-Api-Key": self.api_key}
if self.check is not None:
if self.self_hosted:
check_url = f"{self.site_root}/{self.ping_endpoint}/{self.check}"
else:
check_url = f"https://hc-ping.com/{self.check}"
await asyncio.sleep(1) # needed for self-hosted instances
try:
check_response = await session.get(check_url, timeout=timeout10)
except (aiohttp.ClientError, asyncio.TimeoutError) as error:
Logger("custom_components.healthchecksio").error(
f"Could Not Send Check: {error}"
)
self.hass.data[DOMAIN_DATA]["data"] = await data.json()

if self.self_hosted:
check_url = f"{self.site_root}/{self.ping_endpoint}/{self.check}"
else:
if check_response.ok:
Logger("custom_components.healthchecksio").debug(
f"Send Check HTTP Status Code: {check_response.status}"
)
else:
check_url = f"https://hc-ping.com/{self.check}"
await asyncio.sleep(1) # needed for self-hosted instances
await session.get(check_url)
except Exception as error: # pylint: disable=broad-except
Logger("custom_components.healthchecksio").error(
f"Error: Send Check HTTP Status Code: {check_response.status}"
)
else:
Logger("custom_components.healthchecksio").debug(
"Send Check is not defined."
)
try:
async with session.get(
f"{self.site_root}/api/v1/checks/",
headers=headers,
timeout=timeout10,
) as data:
self.hass.data[DOMAIN_DATA]["data"] = await data.json()
except (aiohttp.ClientError, asyncio.TimeoutError) as error:
Logger("custom_components.healthchecksio").error(
f"Could Not Update Data: {error}"
)
except (ValueError, json.decoder.JSONDecodeError) as error:
Logger("custom_components.healthchecksio").error(
f"Could not update data - {error}"
f"Data JSON Decode Error: {error}"
)
else:
if data.ok:
Logger("custom_components.healthchecksio").debug(
f"Get Data HTTP Status Code: {data.status}"
)
else:
Logger("custom_components.healthchecksio").error(
f"Error: Get Data HTTP Status Code: {data.status}"
)


async def check_files(hass):
Expand Down
86 changes: 64 additions & 22 deletions custom_components/healthchecksio/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
"""Adds config flow for Blueprint."""
import async_timeout
import asyncio
import json
from collections import OrderedDict

import aiohttp
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from integrationhelper import Logger
from homeassistant import config_entries

from .const import DOMAIN, DOMAIN_DATA, OFFICIAL_SITE_ROOT

Expand Down Expand Up @@ -72,7 +74,7 @@ async def _show_initial_config_form(self, user_input):

data_schema = OrderedDict()
data_schema[vol.Required("api_key", default=api_key)] = str
data_schema[vol.Required("check", default=check)] = str
data_schema[vol.Optional("check", default=check)] = str
data_schema[vol.Required("self_hosted", default=self_hosted)] = bool
return self.async_show_form(
step_id="user", data_schema=vol.Schema(data_schema), errors=self._errors
Expand Down Expand Up @@ -123,23 +125,63 @@ async def _test_credentials(
self, api_key, check, self_hosted, site_root, ping_endpoint
):
"""Return true if credentials is valid."""
try:
verify_ssl = not self_hosted or site_root.startswith("https")
session = async_get_clientsession(self.hass, verify_ssl)
headers = {"X-Api-Key": api_key}
async with async_timeout.timeout(10):
Logger("custom_components.healthchecksio").info("Checking API Key")
data = await session.get(f"{site_root}/api/v1/checks/", headers=headers)
self.hass.data[DOMAIN_DATA] = {"data": await data.json()}

Logger("custom_components.healthchecksio").info("Checking Check ID")
if self_hosted:
check_url = f"{site_root}/{ping_endpoint}/{check}"
Logger("custom_components.healthchecksio").debug("Testing Credentials")
verify_ssl = not self.self_hosted or self.site_root.startswith("https")
session = async_get_clientsession(self.hass, verify_ssl)
timeout10 = aiohttp.ClientTimeout(total=10)
headers = {"X-Api-Key": self.api_key}
if self.check is not None:
if self.self_hosted:
check_url = f"{self.site_root}/{self.ping_endpoint}/{self.check}"
else:
check_url = f"https://hc-ping.com/{self.check}"
await asyncio.sleep(1) # needed for self-hosted instances
try:
check_response = await session.get(check_url, timeout=timeout10)
except (aiohttp.ClientError, asyncio.TimeoutError) as error:
Logger("custom_components.healthchecksio").error(
f"Could Not Send Check: {error}"
)
return False
else:
if check_response.ok:
Logger("custom_components.healthchecksio").debug(
f"Send Check HTTP Status Code: {check_response.status}"
)
else:
check_url = f"https://hc-ping.com/{check}"
await asyncio.sleep(1) # needed for self-hosted instances
await session.get(check_url)
return True
except Exception as exception: # pylint: disable=broad-except
Logger("custom_components.healthchecksio").error(exception)
return False
Logger("custom_components.healthchecksio").error(
f"Error: Send Check HTTP Status Code: {check_response.status}"
)
return False
else:
Logger("custom_components.healthchecksio").debug(
"Send Check is not defined."
)
try:
async with session.get(
f"{self.site_root}/api/v1/checks/",
headers=headers,
timeout=timeout10,
) as data:
self.hass.data[DOMAIN_DATA]["data"] = await data.json()
except (aiohttp.ClientError, asyncio.TimeoutError) as error:
Logger("custom_components.healthchecksio").error(
f"Could Not Update Data: {error}"
)
return False
except (ValueError, json.decoder.JSONDecodeError) as error:
Logger("custom_components.healthchecksio").error(
f"Data JSON Decode Error: {error}"
)
return False
else:
if data.ok:
Logger("custom_components.healthchecksio").debug(
f"Get Data HTTP Status Code: {data.status}"
)
return True
else:
Logger("custom_components.healthchecksio").error(
f"Error: Get Data HTTP Status Code: {data.status}"
)
return False
4 changes: 2 additions & 2 deletions custom_components/healthchecksio/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"auth": "API Key, Check ID, Site root or Ping endpoint is wrong."
},
"abort": {
"single_instance_allowed": "Only a single configuration of Blueprint is allowed."
"single_instance_allowed": "Only a single configuration of Healthchecks.io is allowed."
}
}
}
}