commit b4a6d1165ac6bb8ecb90e0f3e3a5038c6886ba4b Author: Ari Sosnovsky Date: Wed Jul 3 10:42:15 2024 -0400 first diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3d6b9e1 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.pytest_cache \ No newline at end of file diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..73f60b8 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + "recommendations": [ + "mikestead.dotenv", + "ms-python.python", + "charliermarsh.ruff" + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..9b38853 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "python.testing.pytestArgs": [ + "tests" + ], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..49ad7c3 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# Textbelt API for Homeassistant \ No newline at end of file diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..a5766f2 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,23 @@ + +services: + homeassistant: + image: ghcr.io/home-assistant/home-assistant:stable + restart: unless-stopped + privileged: true + # environment: + # TZ: MY_TIME_ZONE + volumes: + - ./custom_components:/config/custom_components + # network_mode: host + ports: + - 8123:8123 + +# docker run -d \ +# --name homeassistant \ +# --privileged \ +# --restart=unless-stopped \ +# -e TZ=MY_TIME_ZONE \ +# -v /PATH_TO_YOUR_CONFIG:/config \ +# -v /run/dbus:/run/dbus:ro \ +# --network=host \ +# ghcr.io/home-assistant/home-assistant:stable \ No newline at end of file diff --git a/custom_components/__init__.py b/custom_components/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/custom_components/__pycache__/__init__.cpython-312.pyc b/custom_components/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..1e93291 Binary files /dev/null and b/custom_components/__pycache__/__init__.cpython-312.pyc differ diff --git a/custom_components/ha_textbelt/__init__.py b/custom_components/ha_textbelt/__init__.py new file mode 100644 index 0000000..e0070ae --- /dev/null +++ b/custom_components/ha_textbelt/__init__.py @@ -0,0 +1,86 @@ +"""Example of a custom component exposing a service.""" + +from __future__ import annotations + +import logging +from functools import partial +from homeassistant.const import CONF_API_KEY, CONF_URL, Platform, CONF_ENTITY_ID +from homeassistant.core import ( + HomeAssistant, + SupportsResponse, + ServiceCall, + ServiceResponse, + HassJobType, +) +from homeassistant.exceptions import HomeAssistantError +from homeassistant.config_entries import ConfigEntryState +from homeassistant.helpers.entity_component import EntityComponent + +from .const import DOMAIN, SERVICES_SEND_TEXT, PHONE_ENTRY, MESSAGE_ENTRY +from .textbelt_api import TextbeltAPI +from .schemas import SEND_TEXT_SCHEMA +from .types import TextbeltConfigEntry, TextbeltData +from .sensor import CreditBalanceSensor + +log = logging.getLogger(DOMAIN) +PLATFORMS = [Platform.SENSOR, Platform.NOTIFY] + + +async def async_setup(hass: HomeAssistant, config: TextbeltConfigEntry): + hass.data[DOMAIN] = EntityComponent[CreditBalanceSensor](log, DOMAIN, hass) + hass.services.async_register( + DOMAIN, + SERVICES_SEND_TEXT, + partial(send_text, hass=hass), + schema=SEND_TEXT_SCHEMA, + supports_response=SupportsResponse.OPTIONAL, + job_type=HassJobType.Coroutinefunction, + ) + return True + + +async def async_setup_entry(hass: HomeAssistant, config: TextbeltConfigEntry) -> bool: + textbelt = TextbeltAPI(config.data[CONF_API_KEY], config.data[CONF_URL]) + config.runtime_data = TextbeltData(textbelt, config.data[PHONE_ENTRY]) + await hass.config_entries.async_forward_entry_setups(config, PLATFORMS) + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: TextbeltConfigEntry) -> bool: + unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + loaded_entries = [ + entry + for entry in hass.config_entries.async_entries(DOMAIN) + if entry.state == ConfigEntryState.LOADED + ] + if len(loaded_entries) == 1: + hass.services.async_remove(DOMAIN, SERVICES_SEND_TEXT) + + return unload_ok + + +async def send_text(call: ServiceCall, hass: HomeAssistant) -> ServiceResponse: + entity_ids = call.data[CONF_ENTITY_ID] + message = call.data[MESSAGE_ENTRY] + phone = call.data[PHONE_ENTRY] + p: EntityComponent[CreditBalanceSensor] = hass.data[Platform.SENSOR] + resp = {} + success = 0 + for entity_id in entity_ids: + e = p.get_entity(entity_id) + if isinstance(e, CreditBalanceSensor): + err, r = await e.textbelt.send_text(msg=message, phone=phone) + if err is not None: + log.warning(f"Failed to send text to {entity_id} due to {err}") + resp[entity_id] = {"success": False, "error": err} + else: + success += 1 + resp[entity_id] = r + else: + log.warning(f"invalid entity {entity_id} cannot be used for text messages") + if success == 0: + raise HomeAssistantError( + f"Failed to send text due to {resp}", + translation_domain=DOMAIN, + ) + return resp diff --git a/custom_components/ha_textbelt/__pycache__/__init__.cpython-312.pyc b/custom_components/ha_textbelt/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..92f6973 Binary files /dev/null and b/custom_components/ha_textbelt/__pycache__/__init__.cpython-312.pyc differ diff --git a/custom_components/ha_textbelt/__pycache__/config_flow.cpython-312.pyc b/custom_components/ha_textbelt/__pycache__/config_flow.cpython-312.pyc new file mode 100644 index 0000000..b866f11 Binary files /dev/null and b/custom_components/ha_textbelt/__pycache__/config_flow.cpython-312.pyc differ diff --git a/custom_components/ha_textbelt/__pycache__/const.cpython-312.pyc b/custom_components/ha_textbelt/__pycache__/const.cpython-312.pyc new file mode 100644 index 0000000..164b91a Binary files /dev/null and b/custom_components/ha_textbelt/__pycache__/const.cpython-312.pyc differ diff --git a/custom_components/ha_textbelt/__pycache__/notify.cpython-312.pyc b/custom_components/ha_textbelt/__pycache__/notify.cpython-312.pyc new file mode 100644 index 0000000..b930f79 Binary files /dev/null and b/custom_components/ha_textbelt/__pycache__/notify.cpython-312.pyc differ diff --git a/custom_components/ha_textbelt/__pycache__/schemas.cpython-312.pyc b/custom_components/ha_textbelt/__pycache__/schemas.cpython-312.pyc new file mode 100644 index 0000000..5e18e53 Binary files /dev/null and b/custom_components/ha_textbelt/__pycache__/schemas.cpython-312.pyc differ diff --git a/custom_components/ha_textbelt/__pycache__/sensor.cpython-312.pyc b/custom_components/ha_textbelt/__pycache__/sensor.cpython-312.pyc new file mode 100644 index 0000000..5a9d914 Binary files /dev/null and b/custom_components/ha_textbelt/__pycache__/sensor.cpython-312.pyc differ diff --git a/custom_components/ha_textbelt/__pycache__/textbelt_api.cpython-312.pyc b/custom_components/ha_textbelt/__pycache__/textbelt_api.cpython-312.pyc new file mode 100644 index 0000000..82b50ca Binary files /dev/null and b/custom_components/ha_textbelt/__pycache__/textbelt_api.cpython-312.pyc differ diff --git a/custom_components/ha_textbelt/__pycache__/types.cpython-312.pyc b/custom_components/ha_textbelt/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000..725091f Binary files /dev/null and b/custom_components/ha_textbelt/__pycache__/types.cpython-312.pyc differ diff --git a/custom_components/ha_textbelt/config_flow.py b/custom_components/ha_textbelt/config_flow.py new file mode 100644 index 0000000..cbbb736 --- /dev/null +++ b/custom_components/ha_textbelt/config_flow.py @@ -0,0 +1,30 @@ +from typing import Any + +from homeassistant import config_entries +from homeassistant.data_entry_flow import FlowResult +from homeassistant.const import CONF_API_KEY + +from .const import DOMAIN +from .schemas import USER_INPUT_SCHEMA + + +class TextbeltFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): + VERSION = 1 + CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL + + async def async_step_user( + self, + user_input: dict[str, Any] | None = None, + ) -> FlowResult: + errors = {} + if user_input is not None: + self.context["title_placeholders"] = {"name": user_input[CONF_API_KEY]} + return self.async_create_entry(title=DOMAIN, data=user_input) + return self.async_show_form( + step_id="user", + data_schema=USER_INPUT_SCHEMA, + errors=errors, + description_placeholders={ + k.schema: k.description for k in USER_INPUT_SCHEMA.schema.keys() + }, + ) diff --git a/custom_components/ha_textbelt/const.py b/custom_components/ha_textbelt/const.py new file mode 100644 index 0000000..0b6388f --- /dev/null +++ b/custom_components/ha_textbelt/const.py @@ -0,0 +1,4 @@ +DOMAIN = "ha_textbelt" +SERVICES_SEND_TEXT = "send_text" +PHONE_ENTRY = "phone" +MESSAGE_ENTRY = "message" diff --git a/custom_components/ha_textbelt/manifest.json b/custom_components/ha_textbelt/manifest.json new file mode 100644 index 0000000..2148908 --- /dev/null +++ b/custom_components/ha_textbelt/manifest.json @@ -0,0 +1,15 @@ +{ + "domain": "ha_textbelt", + "name": "Textbelt SMS", + "codeowners": [], + "config_flow": true, + "dependencies": [], + "documentation": "", + "integration_type": "service", + "iot_class": "local_polling", + "loggers": [ + "textbelt" + ], + "requirements": [], + "version": "0.1.0" +} \ No newline at end of file diff --git a/custom_components/ha_textbelt/notify.py b/custom_components/ha_textbelt/notify.py new file mode 100644 index 0000000..c950fa0 --- /dev/null +++ b/custom_components/ha_textbelt/notify.py @@ -0,0 +1,63 @@ +import logging + +from homeassistant.components.notify import NotifyEntity, NotifyEntityFeature +from homeassistant.core import ( + HomeAssistant, +) +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.exceptions import HomeAssistantError + +from .const import DOMAIN +from .textbelt_api import TextbeltAPI +from .types import TextbeltConfigEntry + +log = logging.getLogger(DOMAIN) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: TextbeltConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + notifier = SendTextMessage( + name=entry.runtime_data.phone, + phone_number=entry.runtime_data.phone, + textbelt=entry.runtime_data.client, + ) + async_add_entities([notifier]) + + +class SendTextMessage(NotifyEntity): + _attr_supported_features = NotifyEntityFeature.TITLE + _attr_name = "Send Text via Textbelt" + _attr_has_entity_name = True + _attr_icon = "mdi:cellphone-charging" + + def __init__(self, name: str, phone_number: str, textbelt: TextbeltAPI) -> None: + super().__init__() + self.phone_number = phone_number + self.textbelt = textbelt + self._attr_name += f" ({name})" + self._attr_unique_id = "_".join( + [ + DOMAIN, + "notify", + name, + ] + ) + + async def async_send_message(self, message: str, **kwargs) -> None: + """Send a message.""" + resp = await self._send_text(self.phone_number, message=message) + self._attr_state = resp["textId"] + return resp + + async def _send_text(self, phone: str, message: str): + err, resp = await self.textbelt.send_text( + msg=message, + phone=phone, + ) + if err is None: + return resp + else: + raise HomeAssistantError(err, translation_domain=DOMAIN) diff --git a/custom_components/ha_textbelt/schemas.py b/custom_components/ha_textbelt/schemas.py new file mode 100644 index 0000000..ca5be8c --- /dev/null +++ b/custom_components/ha_textbelt/schemas.py @@ -0,0 +1,32 @@ +import voluptuous as vol +import homeassistant.helpers.config_validation as cv + +from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_ENTITY_ID +from .const import PHONE_ENTRY, MESSAGE_ENTRY + +USER_INPUT_SCHEMA = vol.Schema( + { + vol.Optional( + PHONE_ENTRY, + ): cv.string, + vol.Required( + CONF_API_KEY, + ): cv.string, + vol.Optional( + CONF_URL, + default="https://textbelt.com/", + ): cv.string, + } +) + +SEND_TEXT_SCHEMA = vol.Schema( + { + vol.Required( + MESSAGE_ENTRY, + ): cv.string, + vol.Required( + PHONE_ENTRY, + ): cv.string, + }, + extra=vol.ALLOW_EXTRA, +) diff --git a/custom_components/ha_textbelt/sensor.py b/custom_components/ha_textbelt/sensor.py new file mode 100644 index 0000000..4b0c112 --- /dev/null +++ b/custom_components/ha_textbelt/sensor.py @@ -0,0 +1,65 @@ +"""Platform for sensor integration.""" + +from __future__ import annotations + +import logging + +from homeassistant.components.sensor import ( + SensorDeviceClass, + SensorEntity, + SensorStateClass, +) +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from .textbelt_api import TextbeltAPI +from .types import TextbeltConfigEntry +from .const import DOMAIN + +log = logging.getLogger(DOMAIN) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: TextbeltConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + sensor = CreditBalanceSensor( + name=entry.runtime_data.phone, + phone_number=entry.runtime_data.phone, + textbelt=entry.runtime_data.client, + ) + async_add_entities([sensor], True) + + +class CreditBalanceSensor(SensorEntity): + _attr_name = "Credit Balance for API KEY" + _attr_icon = "mdi:credit-card-multiple" + _attr_device_class = SensorDeviceClass.MONETARY + _attr_state_class = SensorStateClass.TOTAL + _attr_unit_of_measurement = "msgs" + _attr_should_poll = True + + def __init__(self, name: str, phone_number: str, textbelt: TextbeltAPI) -> None: + super().__init__() + self.textbelt = textbelt + self.phone_number = phone_number + self._attr_name += f" ({name})" + self._attr_unique_id = "_".join( + [ + DOMAIN, + "credit_balance", + name, + ] + ) + + async def async_update(self) -> None: + err, resp = await self.textbelt.get_balance() + if err is None: + self._attr_available = True + self._attr_native_value = resp + else: + self._attr_available = False + self._attr_native_value = 0 + raise HomeAssistantError(f"Textbelt ERROR {err}", translation_domain=DOMAIN) diff --git a/custom_components/ha_textbelt/services.yaml b/custom_components/ha_textbelt/services.yaml new file mode 100644 index 0000000..0a10768 --- /dev/null +++ b/custom_components/ha_textbelt/services.yaml @@ -0,0 +1,16 @@ +send_text: + target: + entity: + domain: sensor + integration: ha_textbelt + fields: + phone: + required: true + example: "18888888" + selector: + text: + message: + required: true + example: "Hello World" + selector: + text: diff --git a/custom_components/ha_textbelt/strings.json b/custom_components/ha_textbelt/strings.json new file mode 100644 index 0000000..32106c5 --- /dev/null +++ b/custom_components/ha_textbelt/strings.json @@ -0,0 +1,35 @@ +{ + "config": { + "step": { + "user": { + "description": "Setup intergration with textbelt!", + "data": { + "name": "Name", + "api_key": "[%key:common::config_flow::data::api_key%]", + "url": "[%key:common::config_flow::data::url%]" + }, + "data_description": { + "api_key": "The textbelt api key (can be found here https://textbelt.com/)" + } + } + }, + "error": {}, + "abort": {} + }, + "services": { + "send_text": { + "name": "Send Text", + "description": "Send text message with textbelt", + "fields": { + "phone": { + "name": "Phone Number", + "description": "Phone to where we send the text message." + }, + "message": { + "name": "[%key:common::config_flow::data::message%]", + "description": "Text message we want to send." + } + } + } + } +} \ No newline at end of file diff --git a/custom_components/ha_textbelt/textbelt_api.py b/custom_components/ha_textbelt/textbelt_api.py new file mode 100644 index 0000000..29f1db2 --- /dev/null +++ b/custom_components/ha_textbelt/textbelt_api.py @@ -0,0 +1,79 @@ +import httpx + +from datetime import datetime, timedelta +from http import HTTPStatus +from typing import NamedTuple + +ErrorStr = str +ApiKey = str + + +class QuotaState(NamedTuple): + quota: int | None + last_update: datetime + last_error: ErrorStr | None + + +_quotas: dict[ApiKey, QuotaState | None] = {} + + +class TextbeltAPI: + def __init__(self, key: ApiKey, base_url: str = "https://textbelt.com/") -> None: + self.key = key + self.client = httpx.AsyncClient(base_url=base_url) + _quotas[key] = _quotas.get(key, None) + + @property + def quota(self): + return _quotas.get(self.key, None) + + @quota.setter + def quota(self, value: QuotaState): + _quotas[self.key] = value + + async def get_balance(self) -> tuple[ErrorStr, None] | tuple[None, int]: + if self.quota is not None: + if self.quota.quota is not None: + if datetime.now() - self.quota.last_update < timedelta(minutes=30): + return self.quota.last_error, self.quota.quota + elif datetime.now() - self.quota.last_update < timedelta(minutes=10): + return self.quota.last_error, self.quota.quota + err, resp = await self._get_balance() + if err is None: + self.quota = QuotaState(resp, datetime.now(), None) + else: + self.quota = QuotaState(None, datetime.now(), err) + return self.quota.last_error, self.quota.quota + + async def _get_balance(self) -> tuple[ErrorStr, None] | tuple[None, int]: + resp = await self.client.get(f"/quota/{self.key}") + if resp.status_code == HTTPStatus.OK: + data = resp.json() + if data["success"]: + return None, data["quotaRemaining"] + return resp.text, None + return f"Unexpected status code = {resp.status_code} data = {resp.text}", None + + async def send_text( + self, + msg: str, + phone: str, + ) -> tuple[ErrorStr, None] | tuple[None, dict]: + resp = await self.client.post( + "/text", + json={ + "phone": phone, + "message": msg, + "key": self.key, + }, + ) + if resp.status_code == HTTPStatus.OK: + data = resp.json() + if data["success"]: + if data.get("quotaRemaining", None) is not None: + self.quota = QuotaState( + data["quotaRemaining"], datetime.now(), None + ) + return None, data + return data["error"], None + return f"Unexpected status code = {resp.status_code} data = {resp.text}", None diff --git a/custom_components/ha_textbelt/translations/en.json b/custom_components/ha_textbelt/translations/en.json new file mode 100644 index 0000000..4de6315 --- /dev/null +++ b/custom_components/ha_textbelt/translations/en.json @@ -0,0 +1,34 @@ +{ + "config": { + "step": { + "user": { + "title": "Enter you textbelt information", + "data": { + "name": "Name", + "api_key": "API Key", + "url": "URL for Textbelt" + }, + "data_description": { + "name": "Name to remember the API KEY by (defaults to a random string).", + "api_key": "The textbelt api key (can be found here https://textbelt.com/)" + } + } + } + }, + "services": { + "send_text": { + "name": "Send Text", + "description": "Send text message with textbelt", + "fields": { + "phone": { + "name": "Phone Number", + "description": "Phone to where we send the text message." + }, + "message": { + "name": "Text Message", + "description": "Text message we want to send." + } + } + } + } +} \ No newline at end of file diff --git a/custom_components/ha_textbelt/types.py b/custom_components/ha_textbelt/types.py new file mode 100644 index 0000000..f02c8fb --- /dev/null +++ b/custom_components/ha_textbelt/types.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from dataclasses import dataclass + +from homeassistant.config_entries import ConfigEntry + +from .textbelt_api import TextbeltAPI + + +@dataclass +class TextbeltData: + """Adguard data type.""" + + client: TextbeltAPI + phone: str + + +type TextbeltConfigEntry = ConfigEntry[TextbeltData] diff --git a/hacs.json b/hacs.json new file mode 100644 index 0000000..e6234f9 --- /dev/null +++ b/hacs.json @@ -0,0 +1,5 @@ +{ + "name": "Textbelt SMS API", + "homeassistant": "2024.6.4", + "render_readme": true +} \ No newline at end of file diff --git a/info.md b/info.md new file mode 100644 index 0000000..e69de29 diff --git a/requirements.test.txt b/requirements.test.txt new file mode 100644 index 0000000..6c94ed1 --- /dev/null +++ b/requirements.test.txt @@ -0,0 +1,3 @@ +pytest +pytest-cov +pytest-homeassistant-custom-component \ No newline at end of file diff --git a/tests/__pycache__/test_init.cpython-312-pytest-8.2.0.pyc b/tests/__pycache__/test_init.cpython-312-pytest-8.2.0.pyc new file mode 100644 index 0000000..a18a73d Binary files /dev/null and b/tests/__pycache__/test_init.cpython-312-pytest-8.2.0.pyc differ diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..702cc54 --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,10 @@ +"""Test component setup.""" + +from homeassistant.setup import async_setup_component + +from custom_components.ha_textbelt.const import DOMAIN + + +async def test_async_setup(hass): + """Test the component gets setup.""" + assert await async_setup_component(hass, DOMAIN, {}) is True