Webhook component - pass headers to webhook handler (#17091)

* Pass headers to webhook handler

* Refactors webhook component to post Request object instead of data

* Update webhook tests

* Cleanup webhook test and fix a bug in ifttt

* Address code review comments
This commit is contained in:
Georgi Kirichkov 2018-10-04 16:54:51 +03:00 committed by Paulus Schoutsen
parent 0cfbb9ce91
commit b92b24e8a4
3 changed files with 12 additions and 16 deletions

View file

@ -5,6 +5,7 @@ For more details about this component, please refer to the documentation at
https://home-assistant.io/components/ifttt/
"""
from ipaddress import ip_address
import json
import logging
from urllib.parse import urlparse
@ -74,8 +75,14 @@ async def async_setup(hass, config):
return True
async def handle_webhook(hass, webhook_id, data):
async def handle_webhook(hass, webhook_id, request):
"""Handle webhook callback."""
body = await request.text()
try:
data = json.loads(body) if body else {}
except ValueError:
return None
if isinstance(data, dict):
data['webhook_id'] = webhook_id
hass.bus.async_fire(EVENT_RECEIVED, data)

View file

@ -3,7 +3,6 @@
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/webhook/
"""
import json
import logging
from aiohttp.web import Response
@ -76,16 +75,8 @@ class WebhookView(HomeAssistantView):
'Received message for unregistered webhook %s', webhook_id)
return Response(status=200)
body = await request.text()
try:
data = json.loads(body) if body else {}
except ValueError:
_LOGGER.warning(
'Received webhook %s with invalid JSON', webhook_id)
return Response(status=200)
try:
response = await handler(hass, webhook_id, data)
response = await handler(hass, webhook_id, request)
if response is None:
response = Response(status=200)
return response

View file

@ -63,7 +63,7 @@ async def test_posting_webhook_json(hass, mock_client):
async def handle(*args):
"""Handle webhook."""
hooks.append(args)
hooks.append((args[0], args[1], await args[2].text()))
hass.components.webhook.async_register(webhook_id, handle)
@ -74,9 +74,7 @@ async def test_posting_webhook_json(hass, mock_client):
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2] == {
'data': True
}
assert hooks[0][2] == '{"data": true}'
async def test_posting_webhook_no_data(hass, mock_client):
@ -95,4 +93,4 @@ async def test_posting_webhook_no_data(hass, mock_client):
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2] == {}
assert await hooks[0][2].text() == ''