From f2e6a6ff06d3855eb17d0d7b17912a3ae662a6a3 Mon Sep 17 00:00:00 2001 From: tropicoo Date: Sun, 17 Apr 2022 22:52:28 +0300 Subject: [PATCH] More logging --- hikcamerabot/callbacks.py | 10 ++- hikcamerabot/clients/hikvision/api_client.py | 5 +- hikcamerabot/decorators.py | 3 +- hikcamerabot/handlers/event_result.py | 68 +++++++++++++------- 4 files changed, 55 insertions(+), 31 deletions(-) diff --git a/hikcamerabot/callbacks.py b/hikcamerabot/callbacks.py index e3c0cbc..9f9fb4b 100644 --- a/hikcamerabot/callbacks.py +++ b/hikcamerabot/callbacks.py @@ -8,7 +8,7 @@ from hikcamerabot.clients.hikvision.constants import IrcutFilterType from hikcamerabot.constants import Alarm, Detection, Event, ServiceType, Stream from hikcamerabot.decorators import authorization_check, camera_selection -from hikcamerabot.utils.utils import build_command_presentation, make_bold +from hikcamerabot.utils.utils import make_bold log = logging.getLogger(__name__) @@ -20,6 +20,7 @@ async def cmds(bot: CameraBot, message: Message, cam: HikvisionCam) -> None: presentation = bot.cam_registry.get_commands_presentation(cam.id) await message.reply_text( f'Available commands\n\n{presentation}\n\n/list_cams', + reply_to_message_id=message.message_id, parse_mode='HTML') @@ -111,7 +112,9 @@ async def cmd_list_cams(bot: CameraBot, message: Message) -> None: f'Description: {meta["cam"].description}\n' f'Commands: /cmds_{cam_id}') - await message.reply_text('\n\n'.join(msg), parse_mode='HTML') + await message.reply_text('\n\n'.join(msg), + reply_to_message_id=message.message_id, + parse_mode='HTML') log.info('Camera list has been sent') @@ -271,5 +274,6 @@ async def cmd_help(bot: CameraBot, message: Message, append: bool = False, """Send help message to telegram chat.""" log.info('Help message has been requested') await message.reply_text( - 'Use /list_cams command to show available cameras and commands') + 'Use /list_cams command to show available cameras and commands', + reply_to_message_id=message.message_id, ) log.debug('Help message has been sent') diff --git a/hikcamerabot/clients/hikvision/api_client.py b/hikcamerabot/clients/hikvision/api_client.py index 1afa520..765aada 100644 --- a/hikcamerabot/clients/hikvision/api_client.py +++ b/hikcamerabot/clients/hikvision/api_client.py @@ -54,7 +54,7 @@ async def request(self, timeout: float = CONN_TIMEOUT, ) -> httpx.Response: url = urljoin(self.host, endpoint) - self._log.debug(data) + self._log.debug('Request: %s - %s - %s', method, endpoint, data) try: response = await self.session.request( method, @@ -64,7 +64,8 @@ async def request(self, timeout=timeout, ) except Exception as err: - err_msg = 'API encountered an unknown error.' + err_msg = f'API encountered an unknown error for method {method}, ' \ + f'endpoint {endpoint}, data {data}' self._log.exception(err_msg) raise APIRequestError(f'{err_msg}: {err}') from err self._verify_status_code(response.status_code) diff --git a/hikcamerabot/decorators.py b/hikcamerabot/decorators.py index a543b5e..8420043 100644 --- a/hikcamerabot/decorators.py +++ b/hikcamerabot/decorators.py @@ -62,7 +62,8 @@ async def wrapper(*args, **kwargs): return await func(*args, **kwargs) bot._log.error('User authorization error: %s', message.chat.id) # noqa - await message.reply_text('Not authorized') + await message.reply_text('Not authorized', + reply_to_message_id=message.message_id) return wrapper diff --git a/hikcamerabot/handlers/event_result.py b/hikcamerabot/handlers/event_result.py index 86bdfaa..99b736d 100644 --- a/hikcamerabot/handlers/event_result.py +++ b/hikcamerabot/handlers/event_result.py @@ -7,7 +7,7 @@ from typing import Optional, TYPE_CHECKING, Union from pyrogram.types import Message -from tenacity import retry, wait_fixed +from tenacity import retry, stop_after_attempt, wait_fixed from hikcamerabot.constants import ( Alarm, DETECTION_SWITCH_MAP, Detection, Stream, @@ -59,14 +59,20 @@ async def __handle(self, event: dict) -> None: finally: os.remove(video_path) - @retry(wait=wait_fixed(0.5)) + @retry(wait=wait_fixed(0.5), stop=stop_after_attempt(10)) async def _send_video(self, uid: int, video_path: str, caption: str, bot: 'CameraBot') -> None: - file_, is_cached = self._get_file(video_path) - await bot.send_chat_action(chat_id=uid, action='upload_video') - message = await bot.send_video(chat_id=uid, video=file_, caption=caption) - if not is_cached: - self._video_file_cache[video_path] = message.video.file_id + try: + file_, is_cached = self._get_file(video_path) + await bot.send_chat_action(chat_id=uid, action='upload_video') + message = await bot.send_video(chat_id=uid, video=file_, + caption=caption) + if not is_cached: + self._video_file_cache[video_path] = message.video.file_id + except Exception: + self._log.exception('Failed to send video in %s. Retrying', + self.__class__.__name__) + raise def _get_file(self, video_path: str) -> tuple[str, bool]: """Get str file id from cache or `InputFile` from video path. @@ -89,20 +95,24 @@ async def _handle(self, event: dict) -> None: finally: os.remove(video_path) - @retry(wait=wait_fixed(0.5)) + @retry(wait=wait_fixed(0.5), stop=stop_after_attempt(10)) async def _upload_video(self, event): - cam: 'HikvisionCam' = event['cam'] - message: Message = event['message'] # Stale context, can't `reply`. - video_path: str = event['video_path'] - caption = f'Video from {cam.description} {cam.hashtag}\n/cmds_{cam.id}, ' \ - f'/list_cams' - await self._bot.send_chat_action(message.chat.id, action='upload_video') - await self._bot.send_video( - message.chat.id, - video=video_path, - caption=caption, - reply_to_message_id=message.message_id, - ) + try: + cam: 'HikvisionCam' = event['cam'] + message: Message = event['message'] # Stale context, can't `reply`. + video_path: str = event['video_path'] + caption = f'Video from {cam.description} {cam.hashtag}\n/cmds_{cam.id}, ' \ + f'/list_cams' + await self._bot.send_chat_action(message.chat.id, action='upload_video') + await self._bot.send_video( + message.chat.id, + video=video_path, + caption=caption, + reply_to_message_id=message.message_id, + ) + except Exception: + self._log.exception('Failed to upload video gif. Retrying') + raise class ResultAlertSnapshotHandler(AbstractResultEventHandler): @@ -152,7 +162,9 @@ async def _handle(self, event: dict) -> None: switch: bool = event['params']['switch'] text: str = event.get('text') or '{0} stream successfully {1}'.format( name.value.capitalize(), 'enabled' if switch else 'disabled') - await message.reply(make_bold(text), parse_mode='HTML') + await message.reply(make_bold(text), + reply_to_message_id=message.message_id, + parse_mode='HTML') self._log.info(text) @@ -182,7 +194,9 @@ async def _handle(self, event: dict) -> None: text: str = event.get('text') or '{0} successfully {1}'.format( name.value.capitalize(), 'enabled' if switch else 'disabled') - await message.reply(make_bold(text), parse_mode='HTML') + await message.reply(make_bold(text), + reply_to_message_id=message.message_id, + parse_mode='HTML') self._log.info(text) # err_msg = 'Failed to {0} {1}: {2}'.format( # 'enable' if switch else 'disable', name, err) @@ -197,7 +211,9 @@ async def _handle(self, event: dict) -> None: text = event.get('text') or '{0} successfully {1}'.format( name, 'enabled' if switch else 'disabled') - await message.reply(make_bold(text), parse_mode='HTML') + await message.reply(make_bold(text), + reply_to_message_id=message.message_id, + parse_mode='HTML') self._log.info(text) # err_msg = 'Failed to {0} {1}: {2}'.format( # 'enable' if switch else 'disable', name, err) @@ -221,8 +237,9 @@ async def _send_resized_photo(self, event: dict) -> None: self._log.info('Sending resized cam snapshot') await self._bot.send_chat_action(chat_id=message.chat.id, - action='upload_photo') - await message.reply_photo(event['img'], caption=caption) + action='upload_photo', ) + await message.reply_photo(event['img'], caption=caption, + reply_to_message_id=message.message_id) self._log.info('Resized snapshot sent') async def _send_full_photo(self, event: dict) -> None: @@ -239,5 +256,6 @@ async def _send_full_photo(self, event: dict) -> None: await self._bot.send_chat_action(chat_id=message.chat.id, action='upload_photo') await message.reply_document(document=event['img'], caption=caption, + reply_to_message_id=message.message_id, file_name=filename) self._log.info('Full snapshot "%s" sent', filename)