Compare commits
10
Commits
d5f9d3be49
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
085be262b0 | ||
|
|
9fd69cc3a6 | ||
|
|
161ad3eaa3 | ||
|
|
ab33329e31 | ||
|
|
3d5a237d4d | ||
|
|
2b65d11622 | ||
|
|
a1c36de342 | ||
|
|
295c1f68e0 | ||
|
|
cec3bcb500 | ||
|
|
b296f786ec |
@@ -1,15 +1,16 @@
|
|||||||
# app/bot/handlers/start.py
|
# app/bot/handlers/start.py
|
||||||
from telebot.types import Message
|
|
||||||
from telebot import logger
|
from telebot import logger
|
||||||
from app.bot.keyboards.main_menu import get_main_menu
|
from telebot.types import Message
|
||||||
|
|
||||||
from app.bot.constants import UserStates
|
from app.bot.constants import UserStates
|
||||||
|
from app.bot.keyboards.main_menu import get_main_menu
|
||||||
from app.bot.states import UserStateManager
|
from app.bot.states import UserStateManager
|
||||||
from app.bot.utils.auth import check_registration
|
from app.bot.utils.auth import check_registration
|
||||||
|
|
||||||
|
|
||||||
def register_handlers(bot,app, state_manager: UserStateManager):
|
def register_handlers(bot,app, state_manager: UserStateManager):
|
||||||
@bot.message_handler(commands=['start'])
|
@bot.message_handler(commands=['start'])
|
||||||
@bot.message_handler(func=lambda msg: msg.text == "Продолжить" and state_manager.get_state(msg.chat.id) == UserStates.REGISTRATION)
|
@bot.message_handler(func=lambda msg: msg.text == "Продолжить")
|
||||||
def start_handler(message: Message):
|
def start_handler(message: Message):
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
username = f"{message.from_user.username}" if message.from_user.username else "N/A"
|
username = f"{message.from_user.username}" if message.from_user.username else "N/A"
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, C
|
|||||||
|
|
||||||
from app import Subscriptions
|
from app import Subscriptions
|
||||||
from app.bot.constants import UserStates
|
from app.bot.constants import UserStates
|
||||||
|
from app.bot.keyboards.settings_menu import get_settings_menu
|
||||||
from app.bot.processors.subscribe_processor import process_subscription_button, process_subscribe_all_regions
|
from app.bot.processors.subscribe_processor import process_subscription_button, process_subscribe_all_regions
|
||||||
from app.bot.states import UserStateManager
|
from app.bot.states import UserStateManager
|
||||||
from app.bot.utils.auth import auth
|
from app.bot.utils.auth import auth
|
||||||
@@ -28,10 +29,16 @@ def register_handlers(bot: TeleBot, app, state_manager: UserStateManager):
|
|||||||
# Получаем регионы
|
# Получаем регионы
|
||||||
regions = get_sorted_regions()
|
regions = get_sorted_regions()
|
||||||
|
|
||||||
|
if not regions:
|
||||||
|
bot.send_message(chat_id, "ℹ️ У вас нет доступных для подписки регионов.",reply_markup=get_settings_menu())
|
||||||
|
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
|
||||||
|
return
|
||||||
|
|
||||||
# Получаем список подписанных регионов пользователя
|
# Получаем список подписанных регионов пользователя
|
||||||
subscribed = {s.region_id for s in Subscriptions.query.filter_by(chat_id=chat_id, active=True).all()}
|
subscribed = {s.region_id for s in Subscriptions.query.filter_by(chat_id=chat_id, active=True).all()}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Формируем строку с пометками
|
# Формируем строку с пометками
|
||||||
regions_text = format_regions_list_marked(regions, subscribed)
|
regions_text = format_regions_list_marked(regions, subscribed)
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from telebot import logger
|
||||||
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
|
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
|
||||||
|
|
||||||
from app.bot.keyboards.groups import create_groups_keyboard
|
from app.bot.keyboards.groups import create_groups_keyboard
|
||||||
@@ -12,10 +13,14 @@ from app.bot.utils.zabbix_alt import (
|
|||||||
def process_region_selection(bot, chat_id, region_id):
|
def process_region_selection(bot, chat_id, region_id):
|
||||||
try:
|
try:
|
||||||
groups = get_region_groups(region_id)
|
groups = get_region_groups(region_id)
|
||||||
|
if groups is None:
|
||||||
|
return bot.send_message(chat_id, "❌ Сервер Zabbix временно недоступен. Попробуйте позже.", reply_markup=get_main_menu())
|
||||||
if not groups:
|
if not groups:
|
||||||
return bot.send_message(chat_id, "Нет групп хостов для этого региона.")
|
return bot.send_message(chat_id, "Нет групп хостов для этого региона.", reply_markup=get_main_menu())
|
||||||
|
|
||||||
markup = create_groups_keyboard(groups, region_id)
|
markup = create_groups_keyboard(groups, region_id)
|
||||||
bot.send_message(chat_id, "Выберите группу хостов:", reply_markup=markup)
|
bot.send_message(chat_id, "Выберите группу хостов:", reply_markup=markup)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
bot.send_message(chat_id, f"Ошибка при получении групп: {str(e)}", reply_markup=get_main_menu())
|
bot.send_message(chat_id, f"Ошибка при получении групп: {str(e)}", reply_markup=get_main_menu())
|
||||||
|
|
||||||
@@ -23,40 +28,61 @@ def process_region_selection(bot, chat_id, region_id):
|
|||||||
def process_group_selection(bot, chat_id, group_id):
|
def process_group_selection(bot, chat_id, group_id):
|
||||||
try:
|
try:
|
||||||
triggers = fetch_triggers_data(group_id)
|
triggers = fetch_triggers_data(group_id)
|
||||||
|
if triggers is None:
|
||||||
|
return bot.send_message(chat_id, "❌ Сервер Zabbix временно недоступен. Попробуйте позже.")
|
||||||
|
|
||||||
if not triggers:
|
if not triggers:
|
||||||
bot.send_message(chat_id, "Нет активных событий.")
|
return bot.send_message(chat_id, "Нет активных событий.")
|
||||||
return
|
|
||||||
|
|
||||||
for trigger in triggers:
|
for trigger in triggers:
|
||||||
|
try:
|
||||||
text, url = format_trigger_for_tg(trigger)
|
text, url = format_trigger_for_tg(trigger)
|
||||||
markup = InlineKeyboardMarkup()
|
markup = InlineKeyboardMarkup()
|
||||||
markup.add(InlineKeyboardButton(text="Открыть график", url=url))
|
markup.add(InlineKeyboardButton(text="Открыть график", url=url))
|
||||||
bot.send_message(chat_id, text, reply_markup=markup, parse_mode="HTML")
|
bot.send_message(chat_id, text, reply_markup=markup, parse_mode="HTML")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"[Bot] Ошибка при отправке сообщения о триггере: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
bot.send_message(chat_id, f"Ошибка при получении событий: {str(e)}")
|
bot.send_message(chat_id, f"Ошибка при получении событий: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def process_all_groups_request(bot, chat_id, region_id):
|
def process_all_groups_request(bot, chat_id, region_id):
|
||||||
try:
|
try:
|
||||||
all_triggers = []
|
all_triggers = []
|
||||||
groups = get_all_groups_for_region(region_id)
|
groups = get_all_groups_for_region(region_id)
|
||||||
|
zabbix_error = False
|
||||||
|
|
||||||
for group in groups:
|
for group in groups:
|
||||||
try:
|
try:
|
||||||
triggers = fetch_triggers_data(group['groupid'])
|
triggers = fetch_triggers_data(group['groupid'])
|
||||||
|
if triggers is None:
|
||||||
|
zabbix_error = True
|
||||||
|
continue
|
||||||
if triggers:
|
if triggers:
|
||||||
all_triggers.extend(triggers)
|
all_triggers.extend(triggers)
|
||||||
except Exception:
|
except Exception as e:
|
||||||
|
logger.error(f"[Bot] Ошибка при обработке группы {group['name']}: {e}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
if zabbix_error and not all_triggers:
|
||||||
|
return bot.send_message(chat_id, "❌ Сервер Zabbix временно недоступен. Попробуйте позже.")
|
||||||
|
|
||||||
if not all_triggers:
|
if not all_triggers:
|
||||||
bot.send_message(chat_id, "Нет активных событий.")
|
return bot.send_message(chat_id, "Нет активных событий.")
|
||||||
return
|
|
||||||
|
|
||||||
for trigger in all_triggers:
|
for trigger in all_triggers:
|
||||||
|
try:
|
||||||
text, url = format_trigger_for_tg(trigger)
|
text, url = format_trigger_for_tg(trigger)
|
||||||
markup = InlineKeyboardMarkup()
|
markup = InlineKeyboardMarkup()
|
||||||
markup.add(InlineKeyboardButton(text="Открыть график", url=url))
|
markup.add(InlineKeyboardButton(text="Открыть график", url=url))
|
||||||
bot.send_message(chat_id, text, reply_markup=markup, parse_mode="HTML")
|
bot.send_message(chat_id, text, reply_markup=markup, parse_mode="HTML")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"[Bot] Ошибка при отправке события: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
bot.send_message(chat_id, f"Ошибка при получении данных: {str(e)}")
|
bot.send_message(chat_id, f"Ошибка при получении данных: {str(e)}")
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
# composer.py
|
# composer.py
|
||||||
|
|
||||||
import time
|
from datetime import datetime
|
||||||
from typing import Optional, Tuple
|
from typing import Optional, Tuple
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
from app.bot.utils.tg_escape_chars import escape_telegram_chars # или твоя функция, если кастомная
|
from app.bot.utils.tg_escape_chars import escape_telegram_chars # или твоя функция, если кастомная
|
||||||
|
from config import ZABBIX_TZ
|
||||||
|
|
||||||
|
|
||||||
def compose_telegram_message(data: dict) -> Tuple[str, Optional[str]]:
|
def compose_telegram_message(data: dict) -> Tuple[str, Optional[str]]:
|
||||||
"""
|
"""
|
||||||
@@ -19,6 +23,12 @@ def compose_telegram_message(data: dict) -> Tuple[str, Optional[str]]:
|
|||||||
'High': '⚠️',
|
'High': '⚠️',
|
||||||
'Disaster': '⛔️'
|
'Disaster': '⛔️'
|
||||||
}
|
}
|
||||||
|
convert_time_format = {
|
||||||
|
"h": "ч",
|
||||||
|
"m": "м",
|
||||||
|
"s": "с"
|
||||||
|
}
|
||||||
|
|
||||||
priority = priority_map.get(data.get('severity', ''), '')
|
priority = priority_map.get(data.get('severity', ''), '')
|
||||||
msg = escape_telegram_chars(data.get('msg', ''))
|
msg = escape_telegram_chars(data.get('msg', ''))
|
||||||
host = escape_telegram_chars(data.get('host', ''))
|
host = escape_telegram_chars(data.get('host', ''))
|
||||||
@@ -26,7 +36,8 @@ def compose_telegram_message(data: dict) -> Tuple[str, Optional[str]]:
|
|||||||
severity = escape_telegram_chars(data.get('severity', ''))
|
severity = escape_telegram_chars(data.get('severity', ''))
|
||||||
status = data.get('status', '').upper()
|
status = data.get('status', '').upper()
|
||||||
timestamp = int(data.get('date_reception', 0))
|
timestamp = int(data.get('date_reception', 0))
|
||||||
time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
|
dt = datetime.fromtimestamp(timestamp, tz=ZoneInfo(ZABBIX_TZ))
|
||||||
|
time_str = dt.strftime('%d.%m.%Y %H:%M:%S')
|
||||||
|
|
||||||
if status == "PROBLEM":
|
if status == "PROBLEM":
|
||||||
message = (
|
message = (
|
||||||
@@ -36,12 +47,32 @@ def compose_telegram_message(data: dict) -> Tuple[str, Optional[str]]:
|
|||||||
f"<b>Время возникновения</b>: {time_str} Мск\n"
|
f"<b>Время возникновения</b>: {time_str} Мск\n"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
|
event_duration = data.get('event_duration', '')
|
||||||
|
duration = ' '.join(
|
||||||
|
f"{part[:-1]}{convert_time_format.get(part[-1], part[-1])}"
|
||||||
|
for part in event_duration.split()
|
||||||
|
)
|
||||||
|
|
||||||
|
# Переформатируем event_date из '2025.06.27 16:46:04' в '27.06.2025 16:46:04'
|
||||||
|
event_date_str = data.get('event_date', '')
|
||||||
|
if event_date_str:
|
||||||
|
try:
|
||||||
|
dt_start = datetime.strptime(event_date_str, "%Y.%m.%d %H:%M:%S")
|
||||||
|
# не меняем timezone, просто меняем формат
|
||||||
|
time_start = dt_start.strftime('%d.%m.%Y %H:%M:%S')
|
||||||
|
except Exception:
|
||||||
|
time_start = event_date_str # fallback — оставляем как есть
|
||||||
|
else:
|
||||||
|
time_start = ''
|
||||||
|
|
||||||
message = (
|
message = (
|
||||||
f"✅ {host} ({ip})\n"
|
f"✅ {host} ({ip})\n"
|
||||||
f"<b>Описание</b>: {msg}\n"
|
f"<b>Описание</b>: {msg}\n"
|
||||||
f"<b>Критичность</b>: {severity}\n"
|
f"<b>Критичность</b>: {severity}\n"
|
||||||
f"<b>Проблема устранена!</b>\n"
|
f"<b>Проблема устранена!</b>\n"
|
||||||
|
f"<b>Время начала</b>: {time_start} Мск\n"
|
||||||
f"<b>Время устранения</b>: {time_str} Мск\n"
|
f"<b>Время устранения</b>: {time_str} Мск\n"
|
||||||
|
f"<b>Длительность проблемы</b>: {duration}\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
link = data.get("link")
|
link = data.get("link")
|
||||||
|
|||||||
@@ -12,6 +12,6 @@ def create_link_button(link: Optional[str]) -> Optional[InlineKeyboardMarkup]:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
markup = InlineKeyboardMarkup()
|
markup = InlineKeyboardMarkup()
|
||||||
button = InlineKeyboardButton(text="График", url=link)
|
button = InlineKeyboardButton(text="Открыть график", url=link)
|
||||||
markup.add(button)
|
markup.add(button)
|
||||||
return markup
|
return markup
|
||||||
|
|||||||
+10
-11
@@ -9,7 +9,9 @@ from config import ZABBIX_URL, ZABBIX_API_TOKEN, ZABBIX_VERIFY_SSL
|
|||||||
|
|
||||||
def get_region_groups(region_id: str):
|
def get_region_groups(region_id: str):
|
||||||
"""
|
"""
|
||||||
Получает список групп, имя которых содержит регион region_id, исключая 'test' и группы, не соответствующие шаблону 'имя_число'.
|
Получает список групп, имя которых содержит регион region_id,
|
||||||
|
исключая 'test' и группы, не соответствующие шаблону 'имя_число'.
|
||||||
|
Возвращает None при ошибке подключения.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
zapi = ZabbixAPI(ZABBIX_URL)
|
zapi = ZabbixAPI(ZABBIX_URL)
|
||||||
@@ -17,8 +19,7 @@ def get_region_groups(region_id: str):
|
|||||||
zapi.session.verify = ZABBIX_VERIFY_SSL
|
zapi.session.verify = ZABBIX_VERIFY_SSL
|
||||||
|
|
||||||
host_groups = zapi.hostgroup.get(output=["groupid", "name"], search={"name": region_id})
|
host_groups = zapi.hostgroup.get(output=["groupid", "name"], search={"name": region_id})
|
||||||
|
pattern = re.compile(r'.+_\d+$')
|
||||||
pattern = re.compile(r'.+_\d+$') # строка с нижним подчёркиванием перед числом в конце
|
|
||||||
|
|
||||||
filtered_groups = [
|
filtered_groups = [
|
||||||
group for group in host_groups
|
group for group in host_groups
|
||||||
@@ -28,7 +29,7 @@ def get_region_groups(region_id: str):
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"[Zabbix] Error getting region groups for '{region_id}': {e}")
|
logger.error(f"[Zabbix] Error getting region groups for '{region_id}': {e}")
|
||||||
return []
|
return None # ← это важно
|
||||||
|
|
||||||
def get_all_groups_for_region(region_id: str):
|
def get_all_groups_for_region(region_id: str):
|
||||||
"""
|
"""
|
||||||
@@ -39,16 +40,15 @@ def get_all_groups_for_region(region_id: str):
|
|||||||
|
|
||||||
def fetch_triggers_data(group_id):
|
def fetch_triggers_data(group_id):
|
||||||
"""
|
"""
|
||||||
Возвращает список триггеров с необходимыми данными,
|
Возвращает список триггеров или None при ошибке подключения к Zabbix.
|
||||||
без форматирования сообщений.
|
|
||||||
"""
|
"""
|
||||||
pnet_mediatypes = {"Pnet integration JS 2025", "Pnet integration JS 2024", "Pnet integration new2"}
|
pnet_mediatypes = {"Pnet integration JS 2025", "Pnet integration JS 2024", "Pnet integration new2"}
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
try:
|
try:
|
||||||
zapi = ZabbixAPI(ZABBIX_URL)
|
zapi = ZabbixAPI(ZABBIX_URL)
|
||||||
zapi.login(api_token=ZABBIX_API_TOKEN)
|
zapi.login(api_token=ZABBIX_API_TOKEN)
|
||||||
|
zapi.session.verify = ZABBIX_VERIFY_SSL
|
||||||
|
|
||||||
# Получаем проблемы с высокой и критической важностью
|
|
||||||
problems = zapi.problem.get(
|
problems = zapi.problem.get(
|
||||||
severities=[4, 5],
|
severities=[4, 5],
|
||||||
suppressed=0,
|
suppressed=0,
|
||||||
@@ -56,7 +56,6 @@ def fetch_triggers_data(group_id):
|
|||||||
groupids=group_id
|
groupids=group_id
|
||||||
)
|
)
|
||||||
trigger_ids = [problem["objectid"] for problem in problems]
|
trigger_ids = [problem["objectid"] for problem in problems]
|
||||||
|
|
||||||
if not trigger_ids:
|
if not trigger_ids:
|
||||||
logger.info(f"No triggers found for group {group_id}")
|
logger.info(f"No triggers found for group {group_id}")
|
||||||
return []
|
return []
|
||||||
@@ -90,14 +89,14 @@ def fetch_triggers_data(group_id):
|
|||||||
break
|
break
|
||||||
|
|
||||||
triggers_sorted = sorted(pnet_triggers, key=lambda t: int(t['lastEvent']['clock']))
|
triggers_sorted = sorted(pnet_triggers, key=lambda t: int(t['lastEvent']['clock']))
|
||||||
logger.debug(f"Found {len(pnet_triggers)} pnet triggers for group {group_id}")
|
|
||||||
end_time = time.time()
|
end_time = time.time()
|
||||||
logger.info(f"[Zabbix] Fetched {len(triggers_sorted)} triggers for group {group_id} in {end_time - start_time:.2f} seconds.")
|
logger.info(f"[Zabbix] Fetched {len(triggers_sorted)} triggers for group {group_id} in {end_time - start_time:.2f} seconds.")
|
||||||
return triggers_sorted
|
return triggers_sorted
|
||||||
|
|
||||||
except ZabbixAPIException as e:
|
except ZabbixAPIException as e:
|
||||||
logger.error(f"[Zabbix] Zabbix API error for group {group_id}: {e}")
|
logger.error(f"[Zabbix] Zabbix API error for group {group_id}: {e}")
|
||||||
return []
|
return None # ← отличие
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"[Zabbix] Unexpected error fetching triggers for group {group_id}: {e}")
|
logger.error(f"[Zabbix] Unexpected error fetching triggers for group {group_id}: {e}")
|
||||||
return []
|
return None # ← отличие
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
import pika
|
|
||||||
from config import RABBITMQ_HOST, RABBITMQ_PORT, RABBITMQ_LOGIN, RABBITMQ_PASS, RABBITMQ_QUEUE
|
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
import pika
|
||||||
|
from pika.exceptions import ChannelClosedByBroker, ConnectionClosed, AMQPConnectionError
|
||||||
|
|
||||||
|
from config import RABBITMQ_HOST, RABBITMQ_PORT, RABBITMQ_LOGIN, RABBITMQ_PASS, RABBITMQ_QUEUE
|
||||||
|
|
||||||
|
|
||||||
class RabbitMQClient:
|
class RabbitMQClient:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._connect()
|
self._connect()
|
||||||
@@ -31,9 +35,9 @@ class RabbitMQClient:
|
|||||||
delivery_mode=2,
|
delivery_mode=2,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
except (pika.exceptions.ChannelClosedByBroker,
|
except (ChannelClosedByBroker,
|
||||||
pika.exceptions.ConnectionClosed,
|
ConnectionClosed,
|
||||||
pika.exceptions.AMQPConnectionError) as e:
|
AMQPConnectionError) as e:
|
||||||
if retry > 0:
|
if retry > 0:
|
||||||
# Короткая пауза перед переподключением
|
# Короткая пауза перед переподключением
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|||||||
+12
-6
@@ -1,11 +1,10 @@
|
|||||||
from flask import Blueprint, render_template, request, redirect, url_for, flash, session, current_app
|
from flask import Blueprint, render_template, request, redirect, url_for, flash, session
|
||||||
from flask_login import login_user, login_required, logout_user
|
from flask_login import login_user, login_required, logout_user
|
||||||
|
|
||||||
from app.extensions.db import db
|
|
||||||
from app.extensions.audit_logger import AuditLogger
|
from app.extensions.audit_logger import AuditLogger
|
||||||
from app.services.auth_service import authenticate_user, parse_ldap_user
|
from app.extensions.db import db
|
||||||
from app.models import User
|
from app.models import User
|
||||||
|
from app.services.auth_service import authenticate_user, parse_ldap_user
|
||||||
|
|
||||||
auditlog = AuditLogger(db.session)
|
auditlog = AuditLogger(db.session)
|
||||||
|
|
||||||
@@ -25,7 +24,11 @@ def login():
|
|||||||
if not success:
|
if not success:
|
||||||
flash(error, 'danger')
|
flash(error, 'danger')
|
||||||
auditlog.auth(username_attempted=username, success=False, error=error)
|
auditlog.auth(username_attempted=username, success=False, error=error)
|
||||||
return render_template("login.html")
|
session['login_username'] = username # сохраняем введённый логин
|
||||||
|
return redirect(url_for('auth.login')) # редирект вместо render_template
|
||||||
|
|
||||||
|
# Очистка сохранённого логина при успешном входе
|
||||||
|
session.pop('login_username', None)
|
||||||
|
|
||||||
data = parse_ldap_user(user_info)
|
data = parse_ldap_user(user_info)
|
||||||
display_name = (f"{data['user_surname']} {data['user_name']} {data['user_middle_name']}").strip()
|
display_name = (f"{data['user_surname']} {data['user_name']} {data['user_middle_name']}").strip()
|
||||||
@@ -48,7 +51,10 @@ def login():
|
|||||||
flash("Logged in successfully!", "success")
|
flash("Logged in successfully!", "success")
|
||||||
return redirect(url_for("dashboard.dashboard"))
|
return redirect(url_for("dashboard.dashboard"))
|
||||||
|
|
||||||
return render_template("login.html")
|
# GET-запрос — передаём в шаблон ранее введённый логин, если есть
|
||||||
|
username_prefill = session.pop('login_username', '')
|
||||||
|
return render_template("login.html", username=username_prefill)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.route('/logout')
|
@auth_bp.route('/logout')
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
# from utilities.notification_manager import NotificationManager
|
|
||||||
# from utilities.telegram_utilities import extract_region_number, format_message
|
|
||||||
# from flask import current_app
|
|
||||||
#
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# class NotificationService:
|
|
||||||
# def __init__(self):
|
|
||||||
# self.logger = current_app.logger
|
|
||||||
# self.manager = NotificationManager(self.logger)
|
|
||||||
#
|
|
||||||
# def process_notification(self, data):
|
|
||||||
# self.logger.info(f"Получены данные уведомления: {data}")
|
|
||||||
#
|
|
||||||
# region_id = extract_region_number(data.get("host"))
|
|
||||||
# if region_id is None:
|
|
||||||
# self.logger.error(f"Не удалось извлечь номер региона из host: {data.get('host')}")
|
|
||||||
# return {"status": "error", "message": "Invalid host format"}, 400
|
|
||||||
#
|
|
||||||
# self.logger.debug(f"Извлечён номер региона: {region_id}")
|
|
||||||
#
|
|
||||||
# subscribers = self.manager.get_subscribers(region_id, data['severity'])
|
|
||||||
#
|
|
||||||
# if self.manager.is_region_active(region_id):
|
|
||||||
# message = format_message(data)
|
|
||||||
# self.manager.send_notifications(subscribers, message)
|
|
||||||
#
|
|
||||||
# return {"status": "success"}, 200
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
import asyncio
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
from app import app, Users
|
|
||||||
import aio_pika
|
|
||||||
import pika
|
|
||||||
|
|
||||||
from config import RABBITMQ_LOGIN, RABBITMQ_PASS, RABBITMQ_HOST, RABBITMQ_QUEUE, RABBITMQ_URL_FULL
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
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,
|
|
||||||
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,
|
|
||||||
))
|
|
||||||
connection.close()
|
|
||||||
|
|
||||||
async def send_message(chat_id, message, backend_bot, is_notification=False):
|
|
||||||
telegram_id = "unknown"
|
|
||||||
try:
|
|
||||||
if is_notification:
|
|
||||||
await rate_limit_semaphore.acquire()
|
|
||||||
|
|
||||||
def get_user():
|
|
||||||
with app.app_context():
|
|
||||||
user = Users.query.get(chat_id)
|
|
||||||
return user.telegram_id if user else "unknown"
|
|
||||||
|
|
||||||
telegram_id = await asyncio.to_thread(get_user)
|
|
||||||
|
|
||||||
await asyncio.to_thread(backend_bot.bot.send_message, chat_id, message, parse_mode='HTML')
|
|
||||||
|
|
||||||
formatted_message = message.replace('\n', ' ').replace('\r', '')
|
|
||||||
logger.info(f'Send notification to {telegram_id} ({chat_id}) from RabbitMQ [{formatted_message}]')
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error sending message to {telegram_id} ({chat_id}): {e}")
|
|
||||||
finally:
|
|
||||||
if is_notification:
|
|
||||||
rate_limit_semaphore.release()
|
|
||||||
|
|
||||||
async def consume_from_queue(backend_bot):
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
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)
|
|
||||||
|
|
||||||
async for message in queue:
|
|
||||||
async with message.process():
|
|
||||||
try:
|
|
||||||
data = json.loads(message.body.decode('utf-8'))
|
|
||||||
chat_id = data["chat_id"]
|
|
||||||
message_text = data["message"]
|
|
||||||
await send_message(chat_id, message_text, backend_bot, is_notification=True)
|
|
||||||
except (json.JSONDecodeError, KeyError) as e:
|
|
||||||
logger.error(f"Error processing message: {e}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error sending message: {e}")
|
|
||||||
except aio_pika.exceptions.AMQPError as e:
|
|
||||||
logger.error(f"RabbitMQ error: {e}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Critical error: {e}")
|
|
||||||
finally:
|
|
||||||
await asyncio.sleep(5)
|
|
||||||
@@ -84,7 +84,7 @@
|
|||||||
<div id="formContent">
|
<div id="formContent">
|
||||||
<!-- Форма входа -->
|
<!-- Форма входа -->
|
||||||
<form method="POST" action="{{ url_for('auth.login') }}">
|
<form method="POST" action="{{ url_for('auth.login') }}">
|
||||||
<input type="text" id="username" class="fadeIn second form-control text-center" name="username" placeholder="Имя пользователя" required>
|
<input type="text" id="username" class="fadeIn second form-control text-center" name="username" value="{{ username|default('') }}" placeholder="Имя пользователя" required>
|
||||||
<input type="password" id="password" class="fadeIn third form-control text-center" name="password" placeholder="Пароль" required>
|
<input type="password" id="password" class="fadeIn third form-control text-center" name="password" placeholder="Пароль" required>
|
||||||
<input type="submit" class="fadeIn fourth btn btn-primary w-100 mt-3" value="Войти">
|
<input type="submit" class="fadeIn fourth btn btn-primary w-100 mt-3" value="Войти">
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -10,5 +10,7 @@ Werkzeug~=3.1.3
|
|||||||
aio-pika~=9.5.5
|
aio-pika~=9.5.5
|
||||||
pika~=1.3.2
|
pika~=1.3.2
|
||||||
pytz~=2025.2
|
pytz~=2025.2
|
||||||
|
tzdata~=2025.2
|
||||||
|
concurrent-log-handler~=0.9.26
|
||||||
requests~=2.32.3
|
requests~=2.32.3
|
||||||
gunicorn~=23.0.0
|
gunicorn~=23.0.0
|
||||||
Reference in New Issue
Block a user