Switch OwnTracks HTTP to use webhook component (#17034)
* Update OwnTracks_HTTP to use the webhook component * Update owntracks_http.py * Update owntracks_http.py
This commit is contained in:
1 parent
589764900a
commit
eb385515c8
2 files changed
+150
-59
No files matched your search
@@ -4,52 +4,79 @@ Device tracker platform that adds support for OwnTracks over HTTP.
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/device_tracker.owntracks_http/
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from aiohttp.web_exceptions import HTTPInternalServerError
|
||||
|
||||
from homeassistant.components.http import HomeAssistantView
|
||||
from aiohttp.web import Response
|
||||
import voluptuous as vol
|
||||
|
||||
# pylint: disable=unused-import
|
||||
from .owntracks import ( # NOQA
|
||||
REQUIREMENTS, PLATFORM_SCHEMA, context_from_config, async_handle_message)
|
||||
from homeassistant.components.device_tracker.owntracks import ( # NOQA
|
||||
PLATFORM_SCHEMA, REQUIREMENTS, async_handle_message, context_from_config)
|
||||
from homeassistant.const import CONF_WEBHOOK_ID
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
DEPENDENCIES = ['webhook']
|
||||
|
||||
DEPENDENCIES = ['http']
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
EVENT_RECEIVED = 'owntracks_http_webhook_received'
|
||||
EVENT_RESPONSE = 'owntracks_http_webhook_response_'
|
||||
|
||||
DOMAIN = 'device_tracker.owntracks_http'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_WEBHOOK_ID): cv.string
|
||||
})
|
||||
|
||||
|
||||
async def async_setup_scanner(hass, config, async_see, discovery_info=None):
|
||||
"""Set up an OwnTracks tracker."""
|
||||
"""Set up OwnTracks HTTP component."""
|
||||
context = context_from_config(async_see, config)
|
||||
|
||||
hass.http.register_view(OwnTracksView(context))
|
||||
subscription = context.mqtt_topic
|
||||
topic = re.sub('/#$', '', subscription)
|
||||
|
||||
return True
|
||||
async def handle_webhook(hass, webhook_id, request):
|
||||
"""Handle webhook callback."""
|
||||
headers = request.headers
|
||||
data = dict()
|
||||
|
||||
if 'X-Limit-U' in headers:
|
||||
data['user'] = headers['X-Limit-U']
|
||||
elif 'u' in request.query:
|
||||
data['user'] = request.query['u']
|
||||
else:
|
||||
return Response(
|
||||
body=json.dumps({'error': 'You need to supply username.'}),
|
||||
content_type="application/json"
|
||||
)
|
||||
|
||||
class OwnTracksView(HomeAssistantView):
|
||||
"""View to handle OwnTracks HTTP requests."""
|
||||
|
||||
url = '/api/owntracks/{user}/{device}'
|
||||
name = 'api:owntracks'
|
||||
|
||||
def __init__(self, context):
|
||||
"""Initialize OwnTracks URL endpoints."""
|
||||
self.context = context
|
||||
|
||||
async def post(self, request, user, device):
|
||||
"""Handle an OwnTracks message."""
|
||||
hass = request.app['hass']
|
||||
|
||||
subscription = self.context.mqtt_topic
|
||||
topic = re.sub('/#$', '', subscription)
|
||||
if 'X-Limit-D' in headers:
|
||||
data['device'] = headers['X-Limit-D']
|
||||
elif 'd' in request.query:
|
||||
data['device'] = request.query['d']
|
||||
else:
|
||||
return Response(
|
||||
body=json.dumps({'error': 'You need to supply device name.'}),
|
||||
content_type="application/json"
|
||||
)
|
||||
|
||||
message = await request.json()
|
||||
message['topic'] = '{}/{}/{}'.format(topic, user, device)
|
||||
|
||||
message['topic'] = '{}/{}/{}'.format(topic, data['user'],
|
||||
data['device'])
|
||||
|
||||
try:
|
||||
await async_handle_message(hass, self.context, message)
|
||||
return self.json([])
|
||||
|
||||
await async_handle_message(hass, context, message)
|
||||
return Response(body=json.dumps([]), status=200,
|
||||
content_type="application/json")
|
||||
except ValueError:
|
||||
raise HTTPInternalServerError
|
||||
_LOGGER.error("Received invalid JSON")
|
||||
return None
|
||||
|
||||
hass.components.webhook.async_register(
|
||||
'owntracks', 'OwnTracks', config['webhook_id'], handle_webhook)
|
||||
|
||||
return True
|
||||
Reference in new issue
Block a user