Refactoring and cleanup codebase (50%...)
MVP dashboard users page
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
|
||||
db = SQLAlchemy() # Создаем экземпляр SQLAlchemy
|
||||
@@ -0,0 +1,204 @@
|
||||
import logging
|
||||
import os
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta
|
||||
from logging.config import dictConfig
|
||||
from logging.handlers import TimedRotatingFileHandler
|
||||
|
||||
|
||||
class UTF8StreamHandler(logging.StreamHandler):
|
||||
def __init__(self, stream=None):
|
||||
super().__init__(stream)
|
||||
self.setStream(stream)
|
||||
|
||||
def setStream(self, stream):
|
||||
super().setStream(stream)
|
||||
if hasattr(stream, 'reconfigure'):
|
||||
stream.reconfigure(encoding='utf-8')
|
||||
|
||||
|
||||
class FilterByMessage(logging.Filter):
|
||||
def filter(self, record):
|
||||
# Фильтруем сообщения, содержащие 'Received 1 new updates'
|
||||
return 'Received ' not in record.getMessage()
|
||||
|
||||
|
||||
class LogManager:
|
||||
def __init__(self, log_dir='logs', retention_days=30):
|
||||
self.log_dir = log_dir
|
||||
self.retention_days = retention_days
|
||||
self.log_files = {
|
||||
'flask': os.path.join(self.log_dir, 'flask.log'),
|
||||
'flask_error': os.path.join(self.log_dir, 'flask_error.log'),
|
||||
'app': os.path.join(self.log_dir, 'app.log'),
|
||||
'app_error': os.path.join(self.log_dir, 'app_error.log'),
|
||||
'debug': os.path.join(self.log_dir, 'debug.log'),
|
||||
}
|
||||
|
||||
# Ensure the log directory exists
|
||||
if not os.path.exists(self.log_dir):
|
||||
os.makedirs(self.log_dir)
|
||||
|
||||
# Setup logging configuration
|
||||
self.setup_logging()
|
||||
|
||||
def setup_logging(self):
|
||||
dictConfig({
|
||||
'version': 1,
|
||||
'disable_existing_loggers': False,
|
||||
'formatters': {
|
||||
'default': {
|
||||
'format': '[%(asctime)s] %(levelname)s %(module)s: %(message)s',
|
||||
},
|
||||
'error': {
|
||||
'format': '[%(asctime)s] %(levelname)s %(module)s: %(message)s',
|
||||
},
|
||||
'werkzeug': {
|
||||
'format': '[%(asctime)s] %(levelname)s %(message)s'
|
||||
},
|
||||
'debug': {
|
||||
'format': '[%(asctime)s] %(levelname)s %(module)s [%(funcName)s:%(lineno)d]: %(message)s'
|
||||
}
|
||||
},
|
||||
'handlers': {
|
||||
'telebot_console': {
|
||||
'class': 'utilities.log_manager.UTF8StreamHandler',
|
||||
'stream': 'ext://sys.stdout',
|
||||
'formatter': 'default',
|
||||
},
|
||||
'flask_console': {
|
||||
'class': 'utilities.log_manager.UTF8StreamHandler',
|
||||
'stream': 'ext://sys.stdout',
|
||||
'formatter': 'werkzeug',
|
||||
},
|
||||
'flask_file': {
|
||||
'class': 'logging.handlers.TimedRotatingFileHandler',
|
||||
'filename': self.log_files['flask'],
|
||||
'when': 'midnight',
|
||||
'backupCount': self.retention_days,
|
||||
'formatter': 'werkzeug',
|
||||
'encoding': 'utf-8',
|
||||
},
|
||||
'flask_error_file': {
|
||||
'class': 'logging.handlers.TimedRotatingFileHandler',
|
||||
'filename': self.log_files['flask_error'],
|
||||
'when': 'midnight',
|
||||
'backupCount': self.retention_days,
|
||||
'formatter': 'werkzeug',
|
||||
'encoding': 'utf-8',
|
||||
'level': 'ERROR',
|
||||
},
|
||||
'app_file': {
|
||||
'class': 'logging.handlers.TimedRotatingFileHandler',
|
||||
'filename': self.log_files['app'],
|
||||
'when': 'midnight',
|
||||
'backupCount': self.retention_days,
|
||||
'formatter': 'default',
|
||||
'encoding': 'utf-8',
|
||||
},
|
||||
'app_error_file': {
|
||||
'class': 'logging.handlers.TimedRotatingFileHandler',
|
||||
'filename': self.log_files['app_error'],
|
||||
'when': 'midnight',
|
||||
'backupCount': self.retention_days,
|
||||
'formatter': 'error',
|
||||
'encoding': 'utf-8',
|
||||
'level': 'ERROR',
|
||||
},
|
||||
'debug_file': {
|
||||
'class': 'logging.handlers.TimedRotatingFileHandler',
|
||||
'filename': self.log_files['debug'],
|
||||
'when': 'midnight',
|
||||
'backupCount': self.retention_days,
|
||||
'formatter': 'debug',
|
||||
'encoding': 'utf-8',
|
||||
'level': 'DEBUG',
|
||||
},
|
||||
},
|
||||
'loggers': {
|
||||
'flask': {
|
||||
'level': 'INFO',
|
||||
'handlers': ['flask_file', 'flask_error_file', 'flask_console'],
|
||||
'propagate': False,
|
||||
},
|
||||
'telebot': {
|
||||
'level': 'INFO',
|
||||
'handlers': ['app_file', 'app_error_file', 'telebot_console'],
|
||||
'propagate': False,
|
||||
},
|
||||
'werkzeug': {
|
||||
'level': 'INFO',
|
||||
'handlers': ['flask_file', 'flask_error_file', 'flask_console'],
|
||||
'propagate': False,
|
||||
},
|
||||
'debug': {
|
||||
'level': 'DEBUG',
|
||||
'handlers': ['debug_file'],
|
||||
'propagate': False,
|
||||
},
|
||||
}
|
||||
# 'root': {
|
||||
# 'level': 'DEBUG',
|
||||
# 'handlers': ['flask_console', 'telebot_console'],
|
||||
# }
|
||||
})
|
||||
|
||||
def archive_old_logs(self):
|
||||
"""Archives old log files and removes logs older than retention_days."""
|
||||
# Get yesterday's date
|
||||
yesterday_date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
|
||||
|
||||
for log_name, log_file in self.log_files.items():
|
||||
if os.path.exists(log_file):
|
||||
archive_name = f"{log_name}_{yesterday_date}.zip"
|
||||
archive_path = os.path.join(self.log_dir, archive_name)
|
||||
|
||||
# Archive the log file
|
||||
with zipfile.ZipFile(archive_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
||||
zipf.write(log_file, arcname=os.path.basename(log_file))
|
||||
|
||||
# Remove the old log file after archiving
|
||||
os.remove(log_file)
|
||||
|
||||
# Clean up old archives
|
||||
self.cleanup_old_archives()
|
||||
|
||||
def configure_werkzeug_logging(self):
|
||||
"""Отключаем встроенный логгер Werkzeug и задаём собственные настройки логирования."""
|
||||
werkzeug_logger = logging.getLogger('werkzeug')
|
||||
werkzeug_logger.handlers = [] # Удаляем существующие обработчики
|
||||
|
||||
# Добавляем кастомный обработчик для форматирования логов
|
||||
handler = TimedRotatingFileHandler(self.log_files['flask'], when='midnight', backupCount=self.retention_days,
|
||||
encoding='utf-8')
|
||||
handler.setFormatter(logging.Formatter('[%(asctime)s] %(levelname)s %(message)s'))
|
||||
werkzeug_logger.addHandler(handler)
|
||||
|
||||
# Отключаем дублирование логов
|
||||
werkzeug_logger.propagate = False
|
||||
|
||||
def cleanup_old_archives(self):
|
||||
"""Deletes archived logs older than retention_days."""
|
||||
now = datetime.now()
|
||||
cutoff = now - timedelta(days=self.retention_days)
|
||||
|
||||
for file in os.listdir(self.log_dir):
|
||||
if file.endswith('.zip'):
|
||||
file_path = os.path.join(self.log_dir, file)
|
||||
file_time = datetime.fromtimestamp(os.path.getmtime(file_path))
|
||||
if file_time < cutoff:
|
||||
os.remove(file_path)
|
||||
|
||||
def schedule_log_rotation(self):
|
||||
"""Schedules daily log rotation and archiving."""
|
||||
from threading import Timer
|
||||
now = datetime.now()
|
||||
next_midnight = now.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
|
||||
delay = (next_midnight - now).total_seconds()
|
||||
|
||||
Timer(delay, self.rotate_and_archive_logs).start()
|
||||
|
||||
def rotate_and_archive_logs(self):
|
||||
"""Rotates and archives logs."""
|
||||
self.archive_old_logs()
|
||||
self.schedule_log_rotation() # Schedule the next rotation
|
||||
@@ -0,0 +1,156 @@
|
||||
import asyncio
|
||||
import json
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from functools import partial
|
||||
|
||||
import aio_pika
|
||||
import aiohttp
|
||||
import pika
|
||||
import telebot
|
||||
|
||||
import backend_bot
|
||||
from config import RABBITMQ_LOGIN, RABBITMQ_PASS, RABBITMQ_HOST, RABBITMQ_QUEUE, RABBITMQ_URL_FULL
|
||||
|
||||
# Semaphore for rate limiting
|
||||
rate_limit_semaphore = asyncio.Semaphore(25)
|
||||
|
||||
|
||||
def rabbitmq_connection():
|
||||
# Создаем объект учетных данных
|
||||
credentials = pika.PlainCredentials(RABBITMQ_LOGIN, RABBITMQ_PASS)
|
||||
|
||||
# Указываем параметры подключения, включая учетные данные
|
||||
parameters = pika.ConnectionParameters(
|
||||
host=RABBITMQ_HOST,
|
||||
credentials=credentials, # Передаем учетные данные
|
||||
heartbeat=600, # Интервал heartbeat для поддержания соединения
|
||||
blocked_connection_timeout=300 # Таймаут блокировки соединения
|
||||
)
|
||||
|
||||
# Создаем подключение и канал
|
||||
connection = pika.BlockingConnection(parameters)
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=RABBITMQ_QUEUE, durable=True)
|
||||
return connection, channel
|
||||
|
||||
|
||||
def send_to_queue(message):
|
||||
connection, channel = rabbitmq_connection()
|
||||
channel.basic_publish(
|
||||
exchange='',
|
||||
routing_key=RABBITMQ_QUEUE,
|
||||
body=json.dumps(message),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2, # make message persistent
|
||||
))
|
||||
connection.close()
|
||||
|
||||
|
||||
async def consume_from_queue():
|
||||
while True: # Бесконечный цикл для переподключения
|
||||
try:
|
||||
# Подключение к RabbitMQ
|
||||
connection = await aio_pika.connect_robust(RABBITMQ_URL_FULL)
|
||||
async with connection:
|
||||
# Открываем канал
|
||||
channel = await connection.channel()
|
||||
# Объявляем очередь (если нужно)
|
||||
queue = await channel.declare_queue(RABBITMQ_QUEUE, durable=True)
|
||||
|
||||
# Потребляем сообщения
|
||||
# noinspection PyTypeChecker
|
||||
async for message in queue:
|
||||
async with message.process(): # Авто подтверждение сообщения
|
||||
try:
|
||||
# Парсинг сообщения
|
||||
data = json.loads(message.body)
|
||||
|
||||
# Проверка структуры сообщения
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Invalid message format: Expected a dictionary")
|
||||
|
||||
# Извлечение необходимых данных
|
||||
chat_id = data.get("chat_id")
|
||||
username = data.get("username")
|
||||
message_text = data.get("message")
|
||||
|
||||
# Проверка обязательных полей
|
||||
if not all([chat_id, username, message_text]):
|
||||
raise ValueError(f"Missing required fields in message: {data}")
|
||||
|
||||
# Отправляем сообщение
|
||||
await send_notification_message(chat_id, message_text, username)
|
||||
except json.JSONDecodeError:
|
||||
# Логируем некорректный JSON
|
||||
telebot.logger.error(f"Failed to decode message: {message.body}")
|
||||
except ValueError as ve:
|
||||
# Логируем ошибку формата сообщения
|
||||
telebot.logger.error(f"Invalid message: {ve}")
|
||||
except Exception as e:
|
||||
# Логируем общую ошибку при обработке
|
||||
telebot.logger.error(f"Error sending message from queue: {e}")
|
||||
except aio_pika.exceptions.AMQPError as e:
|
||||
# Логируем ошибку RabbitMQ и переподключаемся
|
||||
telebot.logger.error(f"RabbitMQ error: {e}")
|
||||
except Exception as e:
|
||||
# Логируем общую ошибку и ждем перед переподключением
|
||||
telebot.logger.error(f"Critical error in consume_from_queue: {e}")
|
||||
finally:
|
||||
# Задержка перед переподключением
|
||||
await asyncio.sleep(5)
|
||||
|
||||
|
||||
async def send_message(chat_id, message, is_notification=False):
|
||||
try:
|
||||
if is_notification:
|
||||
await rate_limit_semaphore.acquire()
|
||||
parse_mode = 'HTML'
|
||||
|
||||
# Используем partial для передачи именованных аргументов в bot.send_message
|
||||
func_with_args = partial(backend_bot.bot.send_message, chat_id=chat_id, text=message, parse_mode=parse_mode)
|
||||
|
||||
# Передаем подготовленную функцию в run_in_executor
|
||||
await run_in_executor(func_with_args)
|
||||
|
||||
except telebot.apihelper.ApiTelegramException as e:
|
||||
if "429" in str(e):
|
||||
telebot.logger.warning(f"Rate limit exceeded for chat_id {chat_id}. Retrying...")
|
||||
await asyncio.sleep(1)
|
||||
await send_message(chat_id, message, is_notification)
|
||||
elif "403" in str(e):
|
||||
telebot.logger.warning(f"Can't send message to user because bot blocked by user with chat id: {chat_id}")
|
||||
pass
|
||||
else:
|
||||
telebot.logger.error(f"Failed to send message to {chat_id}: {e}")
|
||||
telebot.logger.error(f"Detailed Error: {e}", exc_info=True) # Добавлено логирование исключения
|
||||
except Exception as e:
|
||||
username = f"@{message.from_user.username}" if message.from_user.username else "N/A"
|
||||
telebot.logger.error(f"Unexpected error while sending message to {username} {chat_id}: {e}", exc_info=True)
|
||||
await check_telegram_api()
|
||||
finally:
|
||||
if is_notification:
|
||||
rate_limit_semaphore.release()
|
||||
formatted_message = message.replace('\n', ' ').replace('\r', '')
|
||||
telebot.logger.info(f'Send notification to {chat_id} from RabbitMQ [{formatted_message}]')
|
||||
|
||||
|
||||
async def send_notification_message(chat_id, message, username):
|
||||
await send_message(chat_id, message, is_notification=True)
|
||||
|
||||
|
||||
async def run_in_executor(func, *args):
|
||||
loop = asyncio.get_event_loop()
|
||||
with ThreadPoolExecutor() as pool:
|
||||
return await loop.run_in_executor(pool, func, *args)
|
||||
|
||||
|
||||
async def check_telegram_api():
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get('https://api.telegram.org') as response:
|
||||
if response.status == 200:
|
||||
telebot.logger.info("Telegram API is reachable.")
|
||||
else:
|
||||
telebot.logger.error("Telegram API is not reachable.")
|
||||
except Exception as e:
|
||||
telebot.logger.error(f"Error checking Telegram API: {e}")
|
||||
@@ -0,0 +1,117 @@
|
||||
import re
|
||||
import time
|
||||
|
||||
import telebot
|
||||
|
||||
import backend_bot
|
||||
import backend_flask
|
||||
import bot_database
|
||||
import telezab
|
||||
|
||||
|
||||
def validate_chat_id(chat_id):
|
||||
"""Validate that chat_id is composed only of digits."""
|
||||
return chat_id.isdigit()
|
||||
|
||||
|
||||
def validate_telegram_id(telegram_id):
|
||||
"""Validate that telegram_id starts with '@'."""
|
||||
return telegram_id.startswith('@')
|
||||
|
||||
|
||||
def validate_email(email):
|
||||
"""Validate that email domain is '@rtmis.ru'."""
|
||||
return re.match(r'^[\w.-]+@rtmis\.ru$', email) is not None
|
||||
|
||||
|
||||
def format_message(data):
|
||||
try:
|
||||
priority_map = {
|
||||
'High': '⚠️',
|
||||
'Disaster': '⛔️'
|
||||
}
|
||||
priority = priority_map.get(data['severity'])
|
||||
msg = escape_telegram_chars(data['msg'])
|
||||
if data['status'].upper() == "PROBLEM":
|
||||
message = (
|
||||
f"{priority} {data['host']} ({data['ip']})\n"
|
||||
f"<b>Описание</b>: {msg}\n"
|
||||
f"<b>Критичность</b>: {data['severity']}\n"
|
||||
f"<b>Время возникновения</b>: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(data['date_reception'])))} Мск\n"
|
||||
)
|
||||
if 'link' in data:
|
||||
message += f'<b>URL</b>: <a href="{data['link']}">Ссылка на график</a>'
|
||||
return message
|
||||
else:
|
||||
message = (
|
||||
f"✅ {data['host']} ({data['ip']})\n"
|
||||
f"<b>Описание</b>: {msg}\n"
|
||||
f"<b>Критичность</b>: {data['severity']}\n"
|
||||
f"<b>Проблема устранена!</b>\n"
|
||||
f"<b>Время устранения</b>: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(data['date_reception'])))} Мск\n"
|
||||
)
|
||||
if 'link' in data:
|
||||
message += f'<b>URL</b>: <a href="{data['link']}">Ссылка на график</a>'
|
||||
return message
|
||||
except KeyError as e:
|
||||
backend_flask.app.logger.error(f"Missing key in data: {e}")
|
||||
raise ValueError(f"Missing key in data: {e}")
|
||||
|
||||
|
||||
def extract_region_number(host):
|
||||
# Используем регулярное выражение для извлечения цифр после первого символа и до первой буквы
|
||||
match = re.match(r'^.\d+', host)
|
||||
if match:
|
||||
return match.group(0)[1:] # Возвращаем строку без первого символа
|
||||
return None
|
||||
|
||||
|
||||
def escape_telegram_chars(text):
|
||||
"""
|
||||
Экранирует запрещённые символы для Telegram API:
|
||||
< -> <
|
||||
> -> >
|
||||
& -> &
|
||||
Также проверяет на наличие запрещённых HTML-тегов и другие проблемы с форматированием.
|
||||
"""
|
||||
replacements = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"', # Для кавычек
|
||||
}
|
||||
|
||||
# Применяем замены
|
||||
for char, replacement in replacements.items():
|
||||
text = text.replace(char, replacement)
|
||||
|
||||
return text
|
||||
|
||||
|
||||
def show_main_menu(chat_id):
|
||||
markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
|
||||
if bot_database.is_whitelisted(chat_id):
|
||||
telezab.state.set_state(chat_id, "MAIN_MENU")
|
||||
markup.add('Настройки', 'Помощь', 'Активные события')
|
||||
else:
|
||||
telezab.state.set_state(chat_id, "REGISTRATION")
|
||||
markup.add('Регистрация')
|
||||
backend_bot.bot.send_message(chat_id, "Выберите действие:", reply_markup=markup)
|
||||
|
||||
|
||||
def create_settings_keyboard(chat_id, admins_list):
|
||||
markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
|
||||
markup.row('Подписаться', 'Отписаться')
|
||||
markup.row('Мои подписки', 'Режим уведомлений')
|
||||
markup.row('Назад')
|
||||
return markup
|
||||
|
||||
|
||||
def show_settings_menu(chat_id):
|
||||
if not bot_database.is_whitelisted(chat_id):
|
||||
telezab.state.set_state(chat_id, "REGISTRATION")
|
||||
backend_bot.bot.send_message(chat_id, "Вы неавторизованы для использования этого бота")
|
||||
return
|
||||
admins_list = bot_database.get_admins()
|
||||
markup = create_settings_keyboard(chat_id, admins_list)
|
||||
backend_bot.bot.send_message(chat_id, "Вы находитесь в режиме настроек. Выберите действие:", reply_markup=markup)
|
||||
@@ -0,0 +1,16 @@
|
||||
class UserStateManager:
|
||||
def __init__(self):
|
||||
# Словарь для хранения состояния каждого пользователя
|
||||
self.user_states = {}
|
||||
|
||||
def set_state(self, chat_id, state):
|
||||
"""Устанавливает состояние для пользователя."""
|
||||
self.user_states[chat_id] = state
|
||||
|
||||
def get_state(self, chat_id):
|
||||
"""Получает текущее состояние пользователя."""
|
||||
return self.user_states.get(chat_id, "MAIN_MENU")
|
||||
|
||||
def reset_state(self, chat_id):
|
||||
"""Сбрасывает состояние пользователя в главное меню."""
|
||||
self.user_states[chat_id] = "MAIN_MENU"
|
||||
Reference in New Issue
Block a user