Move login

This commit is contained in:
Fabian Affolter
2018-03-27 22:29:22 +02:00
parent 7caa702bf0
commit 2c8446f629

View File

@@ -33,38 +33,41 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def get_service(hass, config, discovery_info=None): def get_service(hass, config, discovery_info=None):
"""Get the Mastodon notification service.""" """Get the Mastodon notification service."""
from mastodon import Mastodon
from mastodon.Mastodon import MastodonUnauthorizedError
client_id = config.get(CONF_CLIENT_ID) client_id = config.get(CONF_CLIENT_ID)
client_secret = config.get(CONF_CLIENT_SECRET) client_secret = config.get(CONF_CLIENT_SECRET)
access_token = config.get(CONF_ACCESS_TOKEN) access_token = config.get(CONF_ACCESS_TOKEN)
base_url = config.get(CONF_BASE_URL) base_url = config.get(CONF_BASE_URL)
try: return MastodonNotificationService(
mastodon = Mastodon( client_id, client_secret, access_token, base_url)
client_id=client_id, client_secret=client_secret,
access_token=access_token, api_base_url=base_url)
mastodon.account_verify_credentials()
except MastodonUnauthorizedError:
_LOGGER.warning("Authentication failed")
return None
return MastodonNotificationService(mastodon)
class MastodonNotificationService(BaseNotificationService): class MastodonNotificationService(BaseNotificationService):
"""Implement the notification service for Mastodon.""" """Implement the notification service for Mastodon."""
def __init__(self, api): def __init__(self, client_id, client_secret, access_token, base_url):
"""Initialize the service.""" """Initialize the service."""
self._api = api from mastodon import Mastodon
from mastodon.Mastodon import MastodonUnauthorizedError
self._client_id = client_id
self._client_secret = client_secret
self._access_token = access_token
self._base_url = base_url
try:
self._mastodon = Mastodon(
client_id=self._client_id, client_secret=self._client_secret,
access_token=self._access_token, api_base_url=self._base_url)
self._mastodon.account_verify_credentials()
except MastodonUnauthorizedError:
_LOGGER.error("Authentication failed")
def send_message(self, message="", **kwargs): def send_message(self, message="", **kwargs):
"""Send a message to a user.""" """Send a message to a user."""
from mastodon.Mastodon import MastodonAPIError from mastodon.Mastodon import MastodonAPIError
try: try:
self._api.toot(message) self._mastodon.toot(message)
except MastodonAPIError: except MastodonAPIError:
_LOGGER.error("Unable to send message") _LOGGER.error("Unable to send message")