Skip to content

Commit

Permalink
More logging
Browse files Browse the repository at this point in the history
  • Loading branch information
tropicoo committed Apr 17, 2022
1 parent 7443f01 commit f2e6a6f
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 31 deletions.
10 changes: 7 additions & 3 deletions hikcamerabot/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand All @@ -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'<b>Available commands</b>\n\n{presentation}\n\n/list_cams',
reply_to_message_id=message.message_id,
parse_mode='HTML')


Expand Down Expand Up @@ -111,7 +112,9 @@ async def cmd_list_cams(bot: CameraBot, message: Message) -> None:
f'<b>Description:</b> {meta["cam"].description}\n'
f'<b>Commands</b>: /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')


Expand Down Expand Up @@ -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')
5 changes: 3 additions & 2 deletions hikcamerabot/clients/hikvision/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion hikcamerabot/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
68 changes: 43 additions & 25 deletions hikcamerabot/handlers/event_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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):
Expand Down Expand Up @@ -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)


Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -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)

0 comments on commit f2e6a6f

Please sign in to comment.