diff options
Diffstat (limited to 'bin')
-rw-r--r-- | bin/web_kbn.py | 55 |
1 files changed, 37 insertions, 18 deletions
diff --git a/bin/web_kbn.py b/bin/web_kbn.py index c21269b..5b36d53 100644 --- a/bin/web_kbn.py +++ b/bin/web_kbn.py @@ -6,13 +6,15 @@ import json import re import inverterd import phonenumbers +import time import __py_include from io import StringIO from aiohttp.web import HTTPFound from typing import Optional, Union -from homekit.config import config, AppConfigUnit -from homekit.util import homekit_path, filesize_fmt, seconds_to_human_readable_string +from homekit.config import config, AppConfigUnit, is_development_mode, Translation +from homekit.camera import IpcamConfig +from homekit.util import homekit_path, filesize_fmt, seconds_to_human_readable_string, json_serial from homekit.modem import E3372, ModemsConfig, MacroNetWorkType from homekit.inverter.config import InverterdConfig from homekit.relay.sunxi_h3_client import RelayClient @@ -43,12 +45,16 @@ STATIC_FILES = [ def get_js_link(file, version) -> str: + if is_development_mode(): + version = int(time.time()) if version: file += f'?version={version}' return f'<script src="{config.app_config["assets_public_path"]}/{file}" type="text/javascript"></script>' def get_css_link(file, version) -> str: + if is_development_mode(): + version = int(time.time()) if version: file += f'?version={version}' return f'<link rel="stylesheet" type="text/css" href="{config.app_config["assets_public_path"]}/{file}">' @@ -171,20 +177,22 @@ def get_inverter_data() -> tuple: class WebSite(http.HTTPServer): - _modems_config: ModemsConfig - def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - self._modems_config = ModemsConfig() - aiohttp_jinja2.setup( self.app, loader=jinja2.FileSystemLoader(homekit_path('web', 'kbn_templates')), autoescape=jinja2.select_autoescape(['html', 'xml']), ) env = aiohttp_jinja2.get_env(self.app) - env.filters['tojson'] = lambda obj: json.dumps(obj, separators=(',', ':')) + + def filter_lang(key, unit): + strings = Translation(unit) + return strings.get()[key] + + env.filters['tojson'] = lambda obj: json.dumps(obj, separators=(',', ':'), default=json_serial) + env.filters['lang'] = filter_lang self.app.router.add_static('/assets/', path=homekit_path('web', 'kbn_assets')) @@ -200,6 +208,8 @@ class WebSite(http.HTTPServer): self.get('/sms.cgi', self.sms) self.post('/sms.cgi', self.sms_post) + self.get('/cams.cgi', self.cams) + async def render_page(self, req: http.Request, template_name: str, @@ -220,6 +230,11 @@ class WebSite(http.HTTPServer): ctx = {} for k in 'inverter', 'sensors': ctx[f'{k}_grafana_url'] = config.app_config[f'{k}_grafana_url'] + + cc = IpcamConfig() + ctx['camzones'] = cc['zones'].keys() + ctx['allcams'] = cc.get_all_cam_names() + return await self.render_page(req, 'index', title="Home web site", context=ctx) @@ -227,14 +242,15 @@ class WebSite(http.HTTPServer): async def modems(self, req: http.Request): return await self.render_page(req, 'modems', title='Состояние модемов', - context=dict(modems=self._modems_config)) + context=dict(modems=ModemsConfig())) async def modems_ajx(self, req: http.Request): + mc = ModemsConfig() modem = req.query.get('id', None) - if modem not in self._modems_config.keys(): + if modem not in mc.keys(): raise ValueError('invalid modem id') - modem_cfg = self._modems_config.get(modem) + modem_cfg = mc.get(modem) loop = asyncio.get_event_loop() modem_data = await loop.run_in_executor(None, lambda: get_modem_data(modem_cfg)) @@ -247,10 +263,10 @@ class WebSite(http.HTTPServer): async def modems_verbose(self, req: http.Request): modem = req.query.get('id', None) - if modem not in self._modems_config.keys(): + if modem not in ModemsConfig().keys(): raise ValueError('invalid modem id') - modem_cfg = self._modems_config.get(modem) + modem_cfg = ModemsConfig().get(modem) loop = asyncio.get_event_loop() signal, status, traffic, device, dialup_conn = await loop.run_in_executor(None, lambda: get_modem_data(modem_cfg, True)) data = [ @@ -261,23 +277,23 @@ class WebSite(http.HTTPServer): ['Dialup connection', dialup_conn] ] - modem_name = self._modems_config.getfullname(modem) + modem_name = ModemsConfig().getfullname(modem) return await self.render_page(req, 'modem_verbose', title=f'Подробная информация о модеме "{modem_name}"', context=dict(data=data, modem_name=modem_name)) async def sms(self, req: http.Request): - modem = req.query.get('id', list(self._modems_config.keys())[0]) + modem = req.query.get('id', list(ModemsConfig().keys())[0]) is_outbox = int(req.query.get('outbox', 0)) == 1 error = req.query.get('error', None) sent = int(req.query.get('sent', 0)) == 1 - cl = get_modem_client(self._modems_config[modem]) + cl = get_modem_client(ModemsConfig()[modem]) messages = cl.sms_list(1, 20, is_outbox) return await self.render_page(req, 'sms', title=f"SMS-сообщения ({'исходящие' if is_outbox else 'входящие'}, {modem})", context=dict( - modems=self._modems_config, + modems=ModemsConfig(), selected_modem=modem, is_outbox=is_outbox, error=error, @@ -286,7 +302,7 @@ class WebSite(http.HTTPServer): )) async def sms_post(self, req: http.Request): - modem = req.query.get('id', list(self._modems_config.keys())[0]) + modem = req.query.get('id', list(ModemsConfig().keys())[0]) is_outbox = int(req.query.get('outbox', 0)) == 1 fd = await req.post() @@ -305,7 +321,7 @@ class WebSite(http.HTTPServer): raise HTTPFound(f'{return_url}&error=Неверный+номер') phone = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164) - cl = get_modem_client(self._modems_config[modem]) + cl = get_modem_client(ModemsConfig()[modem]) cl.sms_send(phone, text) raise HTTPFound(return_url) @@ -346,6 +362,9 @@ class WebSite(http.HTTPServer): title='Насос', context=dict(status=status)) + async def cams(self, req: http.Request): + pass + if __name__ == '__main__': config.load_app(WebKbnConfig) |