clean up clicksend (#17723)

This commit is contained in:
Daniel Høyer Iversen 2018-10-23 14:06:42 +02:00 committed by Paulus Schoutsen
parent 398ea40189
commit 37a667c2de
1 changed files with 27 additions and 36 deletions

View File

@ -7,51 +7,41 @@ https://home-assistant.io/components/notify.clicksend/
import json import json
import logging import logging
from aiohttp.hdrs import CONTENT_TYPE
import requests import requests
import voluptuous as vol import voluptuous as vol
from aiohttp.hdrs import CONTENT_TYPE
import homeassistant.helpers.config_validation as cv
from homeassistant.components.notify import ( from homeassistant.components.notify import (
PLATFORM_SCHEMA, BaseNotificationService) PLATFORM_SCHEMA, BaseNotificationService)
from homeassistant.const import ( from homeassistant.const import (
CONF_API_KEY, CONF_RECIPIENT, CONF_SENDER, CONF_USERNAME, CONF_API_KEY, CONF_RECIPIENT, CONF_SENDER, CONF_USERNAME,
CONTENT_TYPE_JSON) CONTENT_TYPE_JSON)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
BASE_API_URL = 'https://rest.clicksend.com/v3' BASE_API_URL = 'https://rest.clicksend.com/v3'
DEFAULT_SENDER = 'hass' DEFAULT_SENDER = 'hass'
TIMEOUT = 5
HEADERS = {CONTENT_TYPE: CONTENT_TYPE_JSON} HEADERS = {CONTENT_TYPE: CONTENT_TYPE_JSON}
def validate_sender(config):
"""Set the optional sender name if sender name is not provided."""
if CONF_SENDER in config:
return config
config[CONF_SENDER] = DEFAULT_SENDER
return config
PLATFORM_SCHEMA = vol.Schema( PLATFORM_SCHEMA = vol.Schema(
vol.All(PLATFORM_SCHEMA.extend({ vol.All(PLATFORM_SCHEMA.extend({
vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_RECIPIENT, default=[]): vol.Required(CONF_RECIPIENT, default=[]):
vol.All(cv.ensure_list, [cv.string]), vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_SENDER): cv.string, vol.Optional(CONF_SENDER, default=DEFAULT_SENDER): cv.string,
}), validate_sender)) }),))
def get_service(hass, config, discovery_info=None): def get_service(hass, config, discovery_info=None):
"""Get the ClickSend notification service.""" """Get the ClickSend notification service."""
print("#### ", config) if not _authenticate(config):
if _authenticate(config) is False: _LOGGER.error("You are not authorized to access ClickSend")
_LOGGER.exception("You are not authorized to access ClickSend")
return None return None
return ClicksendNotificationService(config) return ClicksendNotificationService(config)
@ -60,10 +50,10 @@ class ClicksendNotificationService(BaseNotificationService):
def __init__(self, config): def __init__(self, config):
"""Initialize the service.""" """Initialize the service."""
self.username = config.get(CONF_USERNAME) self.username = config[CONF_USERNAME]
self.api_key = config.get(CONF_API_KEY) self.api_key = config[CONF_API_KEY]
self.recipients = config.get(CONF_RECIPIENT) self.recipients = config[CONF_RECIPIENT]
self.sender = config.get(CONF_SENDER) self.sender = config[CONF_SENDER]
def send_message(self, message="", **kwargs): def send_message(self, message="", **kwargs):
"""Send a message to a user.""" """Send a message to a user."""
@ -77,28 +67,29 @@ class ClicksendNotificationService(BaseNotificationService):
}) })
api_url = "{}/sms/send".format(BASE_API_URL) api_url = "{}/sms/send".format(BASE_API_URL)
resp = requests.post(api_url,
resp = requests.post( data=json.dumps(data),
api_url, data=json.dumps(data), headers=HEADERS, headers=HEADERS,
auth=(self.username, self.api_key), timeout=5) auth=(self.username, self.api_key),
timeout=TIMEOUT)
if resp.status_code == 200:
return
obj = json.loads(resp.text) obj = json.loads(resp.text)
response_msg = obj['response_msg'] response_msg = obj.get('response_msg')
response_code = obj['response_code'] response_code = obj.get('response_code')
_LOGGER.error("Error %s : %s (Code %s)", resp.status_code,
if resp.status_code != 200: response_msg, response_code)
_LOGGER.error("Error %s : %s (Code %s)", resp.status_code,
response_msg, response_code)
def _authenticate(config): def _authenticate(config):
"""Authenticate with ClickSend.""" """Authenticate with ClickSend."""
api_url = '{}/account'.format(BASE_API_URL) api_url = '{}/account'.format(BASE_API_URL)
resp = requests.get( resp = requests.get(api_url,
api_url, headers=HEADERS, auth=(config.get(CONF_USERNAME), headers=HEADERS,
config.get(CONF_API_KEY)), timeout=5) auth=(config[CONF_USERNAME],
config[CONF_API_KEY]),
timeout=TIMEOUT)
if resp.status_code != 200: if resp.status_code != 200:
return False return False
return True return True