Cleanup api code

This commit is contained in:
pvizeli 2017-03-31 12:28:30 +02:00
parent d8ab85986d
commit 0236611676
6 changed files with 54 additions and 59 deletions

View File

@ -28,11 +28,16 @@ level:
- 4: host update - 4: host update
- 8: network functions - 8: network functions
- Answer Answer:
``` ```
{}|OK|ERROR {}|OK|ERROR|WRONG
``` ```
- {}: json
- OK: call was successfully
- ERROR: error on call
- WRONG: not supported
## HassIO REST API ## HassIO REST API
Interface for HomeAssistant to controll things from supervisor. Interface for HomeAssistant to controll things from supervisor.

View File

@ -1,10 +1,7 @@
"""Init file for HassIO host rest api.""" """Init file for HassIO host rest api."""
import logging import logging
from aiohttp import web from .util import api_process_hostcontroll
from aiohttp.web_exceptions import HTTPServiceUnavailable
from .util import api_return_ok, api_return_not_supported
from ..const import ATTR_VERSION from ..const import ATTR_VERSION
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -19,54 +16,33 @@ class APIHost(object):
self.loop = loop self.loop = loop
self.host_controll = host_controll self.host_controll = host_controll
async def info(self, request): @api_process_hostcontroll
def info(self, request):
"""Return host information.""" """Return host information."""
if not self.host_controll.active: return self.host_controll.info()
raise HTTPServiceUnavailable()
host_info = await self.host_controll.info() @api_process_hostcontroll
if host_info: def reboot(self, request):
return web.json_response(host_info)
return api_return_not_supported()
async def reboot(self, request):
"""Reboot host.""" """Reboot host."""
if not self.host_controll.active: return self.host_controll.reboot():
raise HTTPServiceUnavailable()
if await self.host_controll.reboot(): @api_process_hostcontroll
return api_return_ok() def shutdown(self, request):
return api_return_not_supported()
async def shutdown(self, request):
"""Poweroff host.""" """Poweroff host."""
if not self.host_controll.active: return self.host_controll.shutdown():
raise HTTPServiceUnavailable()
if await self.host_controll.shutdown(): @api_process_hostcontroll
return api_return_ok() def network_info(self, request):
return api_return_not_supported()
async def network_info(self, request):
"""Edit network settings.""" """Edit network settings."""
if not self.host_controll.active: pass
raise HTTPServiceUnavailable()
return api_return_not_supported() @api_process_hostcontroll
def network_update(self, request):
async def network_update(self, request):
"""Edit network settings.""" """Edit network settings."""
if not self.host_controll.active: pass
raise HTTPServiceUnavailable()
return api_return_not_supported()
@api_process_hostcontroll
async def update(self, request): async def update(self, request):
"""Update host OS.""" """Update host OS."""
if not self.host_controll.active:
raise HTTPServiceUnavailable()
body = await request.json() or {} body = await request.json() or {}
if await self.host_controll.host_update(body.get(ATTR_VERSION)): return await self.host_controll.host_update(body.get(ATTR_VERSION))
return api_return_ok()
return api_return_not_supported()

View File

@ -1,9 +1,7 @@
"""Init file for HassIO supervisor rest api.""" """Init file for HassIO supervisor rest api."""
import logging import logging
from aiohttp.web_exceptions import HTTPServiceUnavailable from .util import api_return_ok, api_process_hostcontroll
from .util import api_return_ok, api_return_not_supported
from ..const import ATTR_VERSION, HASSIO_VERSION from ..const import ATTR_VERSION, HASSIO_VERSION
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -24,12 +22,9 @@ class APISupervisor(object):
ATTR_VERSION: HASSIO_VERSION, ATTR_VERSION: HASSIO_VERSION,
}) })
@api_process_hostcontroll
async def update(self, request): async def update(self, request):
"""Update host OS.""" """Update host OS."""
if not self.host_controll.active:
raise HTTPServiceUnavailable()
body = await request.json() or {} body = await request.json() or {}
if await self.host_controll.supervisor_update(body.get(ATTR_VERSION)): return await self.host_controll.supervisor_update(
return api_return_ok() body.get(ATTR_VERSION))
return api_return_not_supported()

View File

@ -2,6 +2,7 @@
import logging import logging
from aiohttp import web from aiohttp import web
from aiohttp.web_exceptions import HTTPServiceUnavailable
from ..const import ( from ..const import (
JSON_RESULT, JSON_DATA, JSON_MESSAGE, RESULT_OK, RESULT_ERROR) JSON_RESULT, JSON_DATA, JSON_MESSAGE, RESULT_OK, RESULT_ERROR)
@ -9,6 +10,24 @@ from ..const import (
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
def api_process_hostcontroll(method):
async def wrap_hostcontroll(api, *args, **kwargs):
"""Return host information."""
if not api.host_controll.active:
raise HTTPServiceUnavailable()
answer = await method(api, *args, **kwargs)
if isinstance(answer, dict):
return web.json_response(answer)
elif answer is None:
return api_not_supported()
elif answer:
return api_return_ok()
return api_return_error()
return wrap_hostcontroll
def api_return_error(message=None): def api_return_error(message=None):
"""Return a API error message.""" """Return a API error message."""
return web.json_response({ return web.json_response({
@ -25,6 +44,6 @@ def api_return_ok(data=None):
}) })
def api_return_not_supported(): def api_not_supported():
"""Return a api error with not supported.""" """Return a api error with not supported."""
return api_return_error("Function is not supported") return api_return_error("Function is not supported")

View File

@ -57,6 +57,8 @@ class HostControll(object):
return True return True
elif response == "ERROR": elif response == "ERROR":
return False return False
elif response == "WRONG":
return None
else: else:
try: try:
return json.loads(response) return json.loads(response)

View File

@ -21,13 +21,11 @@ do
continue continue
fi fi
if [ ${parse[0]} == "reboot" ]; then if [ ${parse[0]} == "reboot" ]; then
systemctl reboot || true systemctl reboot && echo "OK" || echo "ERROR"
echo "OK"
continue continue
fi fi
if [ ${parse[0]} == "shutdown" ]; then if [ ${parse[0]} == "shutdown" ]; then
systemctl poweroff || true systemctl poweroff && echo "OK" || echo "ERROR"
echo "OK"
continue continue
fi fi
if [ ${parse[0]} == "host-update" ]; then if [ ${parse[0]} == "host-update" ]; then
@ -49,5 +47,5 @@ do
continue continue
fi fi
echo "ERROR" echo "WRONG"
done done