Compare commits

...
17 Commits
Author SHA1 Message Date
udochudo 085be262b0 chore: (dependency) Update requirements.txt with all new dependencies include tzdate module
Build and Push Docker Images / build (push) Successful in 1m22s
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-27 20:48:27 +05:00
udochudo 9fd69cc3a6 chore: (dependency) Update requirements.txt with all new dependencies include tzdate module
Build and Push Docker Images / build (push) Successful in 1m31s
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-27 20:45:57 +05:00
udochudo 161ad3eaa3 chore: (dependency) Update requirements.txt with all new dependencies include tzdate module
Build and Push Docker Images / build (push) Failing after 1m37s
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-27 20:37:50 +05:00
udochudo ab33329e31 feat: (tg message composer) improve composing message now have more usefull information
Add event duration time
Add event start date and time
Add event resolved date and time
Add event chart link

Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-27 20:37:06 +05:00
udochudo 3d5a237d4d fix: (subscriptions) show message when no regions are available for subscription
Build and Push Docker Images / build (push) Successful in 1m15s
Improved the "Subscribe" button behavior. Now, if there are no regions available to subscribe to, the user sees a proper message instead of silent failure.

Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-25 16:31:19 +05:00
udochudo 2b65d11622 fix: (active triggers) add additional error message when zabbix server is unreachable, add error logging to console
Build and Push Docker Images / build (push) Successful in 1m18s
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-25 16:05:54 +05:00
udochudo a1c36de342 fix: (registration) fix handler for "Продолжить" button, now working without additional requirements
Build and Push Docker Images / build (push) Successful in 1m19s
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-24 10:32:12 +05:00
udochudo 295c1f68e0 chore: (rabbitmq flask client) optimize imports to resolve warnings
Build and Push Docker Images / build (push) Successful in 1m11s
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-23 00:38:25 +05:00
udochudo cec3bcb500 chore: (app structure) remove unused modules
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-23 00:37:50 +05:00
udochudo b296f786ec chore: (auth) fix small cosmetic problem, now refresh /login page not send POST request instead a fresh loading auth page
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-23 00:37:12 +05:00
udochudo d5f9d3be49 fix: (auth page) initialize checking ldap available before login connection to display correct message instean "Invalid username or password"
Build and Push Docker Images / build (push) Successful in 1m21s
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-22 23:23:31 +05:00
udochudo 4f7300e2ce chore: remove unused file and comments
Build and Push Docker Images / build (push) Successful in 36s
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-20 15:05:30 +05:00
udochudo e55e330c50 chore: remove unused placeholder file for settings functions
Build and Push Docker Images / build (push) Successful in 44s
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-19 23:54:44 +05:00
udochudo 8b34d79f4e fix(config): update environment variable retrieval for MAILING_MAX_WORKERS, MAILING_RATE_LIMIT, and MAILING_MAX_RETRIES
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-19 23:54:04 +05:00
udochudo 60f77b39eb feat(subscription): add "subscribe all" and "unsubscribe all" buttons
feat(subscription): add check on unsubscribe to notify user if no active subscriptions

Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-19 23:52:48 +05:00
udochudo 55510a4379 chore(notification mode switch): update icon in final message for notification importance change
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-19 23:50:43 +05:00
udochudo 604957f1a7 feat(notification): improve processing, formatting, and sending of user notifications
Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-19 23:49:22 +05:00
24 changed files with 409 additions and 275 deletions
+7 -5
View File
@@ -1,13 +1,13 @@
from . import subscribe, active_triggers
from . import unsubscribe
from . import my_subscriptions
from . import cancel_input from . import cancel_input
from . import notification_switch_mode from . import debug
from . import help from . import help
from . import my_subscriptions
from . import notification_switch_mode
from . import registration from . import registration
from . import settings from . import settings
from . import start from . import start
from . import debug from . import subscribe, active_triggers
from . import unsubscribe
from ..states import UserStateManager from ..states import UserStateManager
state_manager = UserStateManager() state_manager = UserStateManager()
@@ -32,3 +32,5 @@ def register_callbacks(bot, app):
notification_switch_mode.register_callback_notification(bot, app, state_manager) notification_switch_mode.register_callback_notification(bot, app, state_manager)
active_triggers.register_callbacks_active_triggers(bot, app, state_manager) active_triggers.register_callbacks_active_triggers(bot, app, state_manager)
cancel_input.register_callback_cancel_input(bot,state_manager) cancel_input.register_callback_cancel_input(bot,state_manager)
subscribe.register_callback_subscribe(bot, app, state_manager)
unsubscribe.register_callback_unsubscribe(bot, app, state_manager)
+3 -2
View File
@@ -1,8 +1,9 @@
import telebot import telebot
from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
from app.bot.keyboards.main_menu import get_main_menu
from app import Subscriptions, db from app import Subscriptions, db
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.keyboards.settings_menu import get_settings_menu from app.bot.keyboards.settings_menu import get_settings_menu
from app.bot.utils.auth import auth from app.bot.utils.auth import auth
from app.bot.utils.tg_audit import log_user_event from app.bot.utils.tg_audit import log_user_event
@@ -60,7 +61,7 @@ def register_callback_notification(bot, app, state_manager):
mode_text_emoji = "⛔️ Критические события" if disaster_only else "⚠️ Все события" mode_text_emoji = "⛔️ Критические события" if disaster_only else "⚠️ Все события"
mode_text = "Критические события" if disaster_only else "Все события" mode_text = "Критические события" if disaster_only else "Все события"
bot.send_message(chat_id, f"✅ Режим уведомлений успешно изменён на:\n {mode_text_emoji}",reply_markup=get_settings_menu()) bot.send_message(chat_id, f"🔄 Режим уведомлений успешно изменён на:\n {mode_text_emoji}",reply_markup=get_settings_menu())
log_user_event(chat_id, app, username, f"Режим уведомлений изменился на: {mode_text}") log_user_event(chat_id, app, username, f"Режим уведомлений изменился на: {mode_text}")
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU) state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
+4 -3
View File
@@ -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"
+26 -4
View File
@@ -1,13 +1,14 @@
from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton from telebot import TeleBot, logger
from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from app import Subscriptions from app import Subscriptions
from app.bot.constants import UserStates from app.bot.constants import UserStates
from app.bot.processors.subscribe_processor import process_subscription_button 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.states import UserStateManager from app.bot.states import UserStateManager
from app.bot.utils.auth import auth from app.bot.utils.auth import auth
from app.bot.utils.regions import get_sorted_regions, format_regions_list, format_regions_list_marked from app.bot.utils.regions import get_sorted_regions, format_regions_list_marked
from telebot import TeleBot, logger
def register_handlers(bot: TeleBot, app, state_manager: UserStateManager): def register_handlers(bot: TeleBot, app, state_manager: UserStateManager):
@@ -28,14 +29,21 @@ 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)
markup = InlineKeyboardMarkup() markup = InlineKeyboardMarkup()
markup.add(InlineKeyboardButton("Подписаться на все регионы", callback_data="subscribe_all"))
markup.add(InlineKeyboardButton(text="Отмена", callback_data="cancel_input")) markup.add(InlineKeyboardButton(text="Отмена", callback_data="cancel_input"))
bot_message = bot.send_message(chat_id, bot_message = bot.send_message(chat_id,
@@ -44,3 +52,17 @@ def register_handlers(bot: TeleBot, app, state_manager: UserStateManager):
bot.register_next_step_handler(message, process_subscription_button, app, bot, chat_id, state_manager, bot_message.message_id) bot.register_next_step_handler(message, process_subscription_button, app, bot, chat_id, state_manager, bot_message.message_id)
def register_callback_subscribe(bot: TeleBot, app, state_manager):
@bot.callback_query_handler(func=lambda call: call.data == "subscribe_all")
def handle_subscribe_all_button(call: CallbackQuery):
chat_id = call.message.chat.id
username = f"{call.from_user.username}" if call.from_user.username else "N/A"
with app.app_context():
if not auth(chat_id, app):
bot.send_message(chat_id, "Вы не авторизованы для использования этого бота.")
logger.warning(f"Неавторизованный пользователь {chat_id} @{username}")
state_manager.set_state(chat_id, UserStates.REGISTRATION)
return
process_subscribe_all_regions(call, app, bot, chat_id, state_manager)
-15
View File
@@ -1,15 +0,0 @@
# app/bot/handlers/settings.py
from telebot.types import Message
from app.bot.keyboards.main_menu import get_main_menu
from app.bot.keyboards.settings_menu import get_settings_menu
def register_handlers(bot,app):
@bot.message_handler(func=lambda msg: msg.text == "Режим уведомлений")
def handle_notify_mode(message: Message):
bot.send_message(message.chat.id, "⚙️ Настройка режима уведомлений пока не реализована.")
@bot.message_handler(func=lambda msg: msg.text == "Назад")
def handle_back(message: Message):
bot.send_message(message.chat.id, "Возврат в главное меню", reply_markup=get_main_menu())
+34 -6
View File
@@ -1,10 +1,12 @@
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton from telebot import logger, TeleBot
from telebot import logger from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
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.unsubscribe_processor import process_unsubscribe_button, process_unsubscribe_all_regions
from app.bot.utils.auth import auth from app.bot.utils.auth import auth
from app.bot.utils.helpers import get_user_subscribed_regions from app.bot.utils.helpers import get_user_subscribed_regions
from app.bot.utils.regions import format_regions_list from app.bot.utils.regions import format_regions_list
from app.bot.processors.unsubscribe_processor import process_unsubscribe_button
def register_handlers(bot, app, state_manager): def register_handlers(bot, app, state_manager):
@@ -14,22 +16,48 @@ def register_handlers(bot, app, state_manager):
with app.app_context(): with app.app_context():
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"
if not auth(chat_id, app): if not auth(chat_id, app):
bot.send_message(chat_id, "Вы не авторизованы для использования этого бота.") bot.send_message(chat_id, "Вы не авторизованы для использования этого бота.")
logger.warning(f"Неавторизованный пользователь {chat_id} @{username}") logger.warning(f"Неавторизованный пользователь {chat_id} @{username}")
state_manager.set_state(chat_id, UserStates.REGISTRATION) state_manager.set_state(chat_id, UserStates.REGISTRATION)
return return
else:
state_manager.set_state(chat_id, UserStates.WAITING_INPUT)
user_subscriptions = get_user_subscribed_regions(chat_id) user_subscriptions = get_user_subscribed_regions(chat_id)
# ✅ Предварительная проверка: есть ли подписки
if not user_subscriptions:
bot.send_message(chat_id, "ℹ️ У вас нет активных подписок для отписки.",reply_markup=get_settings_menu())
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
return
# Есть подписки — предлагаем меню отписки
state_manager.set_state(chat_id, UserStates.WAITING_INPUT)
formated_user_subscriptions = format_regions_list(user_subscriptions) formated_user_subscriptions = format_regions_list(user_subscriptions)
markup = InlineKeyboardMarkup() markup = InlineKeyboardMarkup()
markup.add(InlineKeyboardButton("Отписаться от всех регионов", callback_data="unsubscribe_all"))
markup.add(InlineKeyboardButton("Отмена", callback_data="cancel_input")) markup.add(InlineKeyboardButton("Отмена", callback_data="cancel_input"))
bot.send_message(chat_id, bot.send_message(chat_id,
f"Введите номер(а) региона(ов) через запятую подписки которых вы хотите удалить:\n\n{formated_user_subscriptions}", f"Введите номер(а) региона(ов) через запятую, от которых вы хотите отписаться:\n\n{formated_user_subscriptions}",
reply_markup=markup) reply_markup=markup)
bot.register_next_step_handler(message, process_unsubscribe_button, app, bot, chat_id, state_manager) bot.register_next_step_handler(message, process_unsubscribe_button, app, bot, chat_id, state_manager)
def register_callback_unsubscribe(bot: TeleBot, app, state_manager):
@bot.callback_query_handler(func=lambda call: call.data == "unsubscribe_all")
def handle_subscribe_all_button(call: CallbackQuery):
chat_id = call.message.chat.id
username = f"{call.from_user.username}" if call.from_user.username else "N/A"
with app.app_context():
if not auth(chat_id, app):
bot.send_message(chat_id, "Вы не авторизованы для использования этого бота.")
logger.warning(f"Неавторизованный пользователь {chat_id} @{username}")
state_manager.set_state(chat_id, UserStates.REGISTRATION)
return
process_unsubscribe_all_regions(call, app, bot, state_manager)
+40 -14
View File
@@ -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:
text, url = format_trigger_for_tg(trigger) try:
markup = InlineKeyboardMarkup() text, url = format_trigger_for_tg(trigger)
markup.add(InlineKeyboardButton(text="Открыть график", url=url)) markup = InlineKeyboardMarkup()
bot.send_message(chat_id, text, reply_markup=markup, parse_mode="HTML") markup.add(InlineKeyboardButton(text="Открыть график", url=url))
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:
text, url = format_trigger_for_tg(trigger) try:
markup = InlineKeyboardMarkup() text, url = format_trigger_for_tg(trigger)
markup.add(InlineKeyboardButton(text="Открыть график", url=url)) markup = InlineKeyboardMarkup()
bot.send_message(chat_id, text, reply_markup=markup, parse_mode="HTML") markup.add(InlineKeyboardButton(text="Открыть график", url=url))
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)}")
+47
View File
@@ -75,3 +75,50 @@ def process_subscription_button(message: Message, app, bot, chat_id: int, state_
# Показываем меню # Показываем меню
bot.send_message(chat_id, f"✅ Подписка на регионы: {', '.join(subbed_regions)} оформлена.", reply_markup=get_settings_menu()) bot.send_message(chat_id, f"✅ Подписка на регионы: {', '.join(subbed_regions)} оформлена.", reply_markup=get_settings_menu())
def process_subscribe_all_regions(call, app, bot, chat_id: int, state_manager):
try:
with app.app_context():
username = f"{call.from_user.username}" if call.from_user.username else "N/A"
# Получаем все активные регионы
active_regions = Regions.query.filter_by(active=True).all()
active_region_ids = {r.region_id for r in active_regions}
# Получаем уже подписанные регионы
existing_subs = Subscriptions.query.filter_by(chat_id=chat_id).all()
existing_region_ids = {sub.region_id for sub in existing_subs if sub.active}
newly_added = []
for region in active_regions:
if region.region_id in existing_region_ids:
continue
existing = next((sub for sub in existing_subs if sub.region_id == region.region_id), None)
if existing:
existing.active = True
db.session.add(existing)
else:
new_sub = Subscriptions(chat_id=chat_id, region_id=region.region_id, active=True)
db.session.add(new_sub)
newly_added.append(str(region.region_id))
db.session.commit()
# Логирование действия
if newly_added:
log_user_event(chat_id, app, username, f"Подписался на все регионы: {', '.join(newly_added)}")
bot.answer_callback_query(call.id)
bot.clear_step_handler_by_chat_id(chat_id)
bot.delete_message(chat_id, call.message.message_id)
bot.send_message(chat_id,
"✅ Вы подписались на все доступные регионы.",
reply_markup=get_settings_menu())
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
except Exception as e:
bot.send_message(chat_id, "⚠️ Не удалось выполнить подписку. Попробуйте позже.")
+42 -5
View File
@@ -1,13 +1,15 @@
from flask import Flask from flask import Flask
from telebot import TeleBot, logger from telebot import TeleBot, logger
from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from app.bot.keyboards.settings_menu import get_settings_menu
from app.bot.utils.helpers import get_user_subscribed_regions
from app import Subscriptions from app import Subscriptions
from app.bot.constants import UserStates
from app.bot.keyboards.settings_menu import get_settings_menu
from app.bot.states import UserStateManager
from app.bot.utils.helpers import get_user_subscribed_regions
from app.bot.utils.tg_audit import log_user_event from app.bot.utils.tg_audit import log_user_event
from app.extensions.db import db from app.extensions.db import db
from app.bot.states import UserStateManager
from app.bot.constants import UserStates
def process_unsubscribe_button(message: Message, app: Flask, bot: TeleBot, chat_id: int, state_manager: UserStateManager): def process_unsubscribe_button(message: Message, app: Flask, bot: TeleBot, chat_id: int, state_manager: UserStateManager):
unsubbed_regions = [] unsubbed_regions = []
@@ -63,3 +65,38 @@ def process_unsubscribe_button(message: Message, app: Flask, bot: TeleBot, chat_
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU) state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
bot.send_message(chat_id, "⚙ Вернулись в меню настроек.", reply_markup=get_settings_menu()) bot.send_message(chat_id, "⚙ Вернулись в меню настроек.", reply_markup=get_settings_menu())
def process_unsubscribe_all_regions(call: CallbackQuery, app: Flask, bot: TeleBot, state_manager: UserStateManager):
chat_id = call.message.chat.id
username = f"{call.from_user.username}" if call.from_user.username else "N/A"
try:
with app.app_context():
subscriptions = Subscriptions.query.filter_by(chat_id=chat_id, active=True).all()
if not subscriptions:
bot.answer_callback_query(call.id, text="❗ У вас нет активных подписок.")
return
for sub in subscriptions:
sub.active = False
db.session.add(sub)
db.session.commit()
log_user_event(chat_id, app, username, "Отписался от всех регионов")
bot.answer_callback_query(call.id)
bot.clear_step_handler_by_chat_id(chat_id)
bot.delete_message(chat_id, call.message.message_id)
bot.send_message(chat_id,
"✅ Вы успешно отписались от всех регионов.",
reply_markup=get_settings_menu())
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
except Exception as e:
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
bot.send_message(chat_id, "⚠ Произошла ошибка при отписке. Попробуйте позже.",reply_markup=get_settings_menu())
return
+34 -3
View File
@@ -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 app.bot.utils.tg_escape_chars import escape_telegram_chars # или твоя функция, если кастомная from zoneinfo import ZoneInfo
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")
@@ -1,17 +1,21 @@
import asyncio import asyncio
import json import json
import logging import logging
from typing import Optional
from telebot import apihelper
from aio_pika import connect_robust, Message, DeliveryMode from aio_pika import connect_robust, Message, DeliveryMode
from aio_pika.abc import AbstractIncomingMessage from aio_pika.abc import AbstractIncomingMessage
from app.bot.services.mailing_service.parser import parse_region_id from telebot import apihelper
from app.bot.services.mailing_service.composer import compose_telegram_message from app.bot.services.mailing_service.composer import compose_telegram_message
from app.bot.services.mailing_service.db_utils import get_recipients_by_region from app.bot.services.mailing_service.db_utils import get_recipients_by_region
from config import RABBITMQ_URL_FULL, RABBITMQ_QUEUE, RABBITMQ_NOTIFICATIONS_QUEUE from app.bot.services.mailing_service.parser import parse_region_id
from app.bot.services.mailing_service.utils.link_button import create_link_button
from app.bot.services.mailing_service.utils.tg_get_user import get_telegram_id_by_chat_id
from config import RABBITMQ_URL_FULL, RABBITMQ_QUEUE, RABBITMQ_NOTIFICATIONS_QUEUE, MAILING_RATE_LIMIT
logger = logging.getLogger("TeleBot") logger = logging.getLogger("TeleBot")
rate_limit_semaphore = asyncio.Semaphore(25) rate_limit_semaphore = asyncio.Semaphore(MAILING_RATE_LIMIT)
class AsyncMailingService: class AsyncMailingService:
def __init__(self, flask_app, bot): def __init__(self, flask_app, bot):
@@ -28,7 +32,7 @@ class AsyncMailingService:
async def consume_raw_messages(self): async def consume_raw_messages(self):
while True: while True:
try: try:
logger.info("[MailingService] Подключение к RabbitMQ (сырые сообщения)...") logger.info("[MailingService][raw] Подключение к RabbitMQ (сырые сообщения)...")
connection = await connect_robust(RABBITMQ_URL_FULL, loop=self.loop) connection = await connect_robust(RABBITMQ_URL_FULL, loop=self.loop)
async with connection: async with connection:
channel = await connection.channel() channel = await connection.channel()
@@ -36,14 +40,14 @@ class AsyncMailingService:
raw_queue = await channel.declare_queue(RABBITMQ_QUEUE, durable=True) raw_queue = await channel.declare_queue(RABBITMQ_QUEUE, durable=True)
notifications_queue = await channel.declare_queue(RABBITMQ_NOTIFICATIONS_QUEUE, durable=True) notifications_queue = await channel.declare_queue(RABBITMQ_NOTIFICATIONS_QUEUE, durable=True)
logger.info("[MailingService] Ожидание сообщений из очереди...") logger.info("[MailingService][raw] Ожидание сообщений из очереди...")
async with raw_queue.iterator() as queue_iter: async with raw_queue.iterator() as queue_iter:
async for message in queue_iter: async for message in queue_iter:
await self.handle_raw_message(message, channel, notifications_queue) await self.handle_raw_message(message, channel, notifications_queue)
except Exception as e: except Exception as e:
logger.error(f"[MailingService] Ошибка подключения или обработки: {e}") logger.error(f"[MailingService][raw] Ошибка подключения или обработки: {e}")
logger.info("[MailingService] Повторное подключение через 5 секунд...") logger.info("[MailingService][raw] Повторное подключение через 5 секунд...")
await asyncio.sleep(5) await asyncio.sleep(5)
async def handle_raw_message(self, message: AbstractIncomingMessage, channel, notifications_queue): async def handle_raw_message(self, message: AbstractIncomingMessage, channel, notifications_queue):
@@ -51,9 +55,9 @@ class AsyncMailingService:
with self.flask_app.app_context(): with self.flask_app.app_context():
try: try:
data = json.loads(message.body.decode("utf-8")) data = json.loads(message.body.decode("utf-8"))
logger.info(f"[MailingService] Получено сообщение: {json.dumps(data, ensure_ascii=False)}") logger.info(f"[MailingService][raw] Получены данные: {json.dumps(data, ensure_ascii=False)}")
region_id = parse_region_id(data.get("host")) region_id = int(parse_region_id(data.get("hostgroups")))
severity = data.get("severity", "") severity = data.get("severity", "")
# Получатели и сообщение параллельно # Получатели и сообщение параллельно
@@ -61,12 +65,8 @@ class AsyncMailingService:
message_task = asyncio.to_thread(compose_telegram_message, data) message_task = asyncio.to_thread(compose_telegram_message, data)
recipients, (final_message, link) = await asyncio.gather(recipients_task, message_task) recipients, (final_message, link) = await asyncio.gather(recipients_task, message_task)
logger.info(f"[MailingService][raw] Формирование списка получателей ({len(recipients)})")
logger.info(f"[MailingService] Получатели: {recipients}") logger.debug(f"[MailingService][raw] Список получателей: {', '.join(map(str, recipients))}")
if link:
logger.info(f"[MailingService] Сообщение для Telegram: {final_message} {link}")
else:
logger.info(f"[MailingService] Сообщение для Telegram: {final_message}")
# Формируем и публикуем индивидуальные уведомления в очередь отправки # Формируем и публикуем индивидуальные уведомления в очередь отправки
for chat_id in recipients: for chat_id in recipients:
@@ -79,29 +79,29 @@ class AsyncMailingService:
msg = Message(body, delivery_mode=DeliveryMode.PERSISTENT) msg = Message(body, delivery_mode=DeliveryMode.PERSISTENT)
await channel.default_exchange.publish(msg, routing_key=notifications_queue.name) await channel.default_exchange.publish(msg, routing_key=notifications_queue.name)
logger.info(f"[MailingService] Поставлено в очередь уведомлений: {len(recipients)} сообщений") logger.info(f"[MailingService][raw] Поставлено в очередь уведомлений: {len(recipients)} сообщений")
except Exception as e: except Exception as e:
logger.exception(f"[MailingService] Ошибка обработки сообщения: {e}") logger.exception(f"[MailingService][raw] Ошибка обработки сообщения: {e}")
async def consume_notifications(self): async def consume_notifications(self):
while True: while True:
try: try:
logger.info("[MailingService] Подключение к RabbitMQ (уведомления для отправки)...") logger.info("[MailingService][formated] Подключение к RabbitMQ (уведомления для отправки)...")
connection = await connect_robust(RABBITMQ_URL_FULL, loop=self.loop) connection = await connect_robust(RABBITMQ_URL_FULL, loop=self.loop)
async with connection: async with connection:
channel = await connection.channel() channel = await connection.channel()
await channel.set_qos(prefetch_count=5) await channel.set_qos(prefetch_count=5)
notif_queue = await channel.declare_queue(RABBITMQ_NOTIFICATIONS_QUEUE, durable=True) notif_queue = await channel.declare_queue(RABBITMQ_NOTIFICATIONS_QUEUE, durable=True)
logger.info("[MailingService] Ожидание сообщений из очереди уведомлений...") logger.info("[MailingService][formated] Ожидание сообщений из очереди уведомлений...")
async with notif_queue.iterator() as queue_iter: async with notif_queue.iterator() as queue_iter:
async for message in queue_iter: async for message in queue_iter:
await self.handle_notification_message(message) await self.handle_notification_message(message)
except Exception as e: except Exception as e:
logger.error(f"[MailingService] Ошибка подключения или обработки уведомлений: {e}") logger.error(f"[MailingService][formated] Ошибка подключения или обработки уведомлений: {e}")
logger.info("[MailingService] Повторное подключение через 5 секунд...") logger.info("[MailingService][formated] Повторное подключение через 5 секунд...")
await asyncio.sleep(5) await asyncio.sleep(5)
async def handle_notification_message(self, message: AbstractIncomingMessage): async def handle_notification_message(self, message: AbstractIncomingMessage):
@@ -111,41 +111,60 @@ class AsyncMailingService:
chat_id = data.get("chat_id") chat_id = data.get("chat_id")
message_text = data.get("message") message_text = data.get("message")
link = data.get("link") link = data.get("link")
if link:
message_text = f"{message_text} {link}"
# TODO: расширить логику отправки с кнопкой, если нужно
await self.send_message(chat_id, message_text) await self.send_message(chat_id, message_text, link)
except Exception as e: except Exception as e:
logger.error(f"[MailingService] Ошибка отправки уведомления: {e}") logger.error(f"[MailingService][tg message] Ошибка отправки уведомления: {e}")
# Можно реализовать message.nack() для повторной попытки # Можно реализовать message.nack() для повторной попытки
async def send_message(self, chat_id, message): async def send_message(self, chat_id, message, link: Optional[str] = None):
telegram_id = "unknown" telegram_id = "unknown"
try: try:
await rate_limit_semaphore.acquire() await rate_limit_semaphore.acquire()
def get_telegram_id(): # Получаем telegram_id в отдельном потоке
with self.flask_app.app_context(): telegram_id = await asyncio.to_thread(get_telegram_id_by_chat_id, self.flask_app, chat_id)
from app.models.users import Users
user = Users.query.filter_by(chat_id=chat_id).first()
return user.telegram_id if user else "unknown"
telegram_id = await asyncio.to_thread(get_telegram_id) # Формируем клавиатуру с кнопкой
link_button = create_link_button(link)
await asyncio.to_thread(self.bot.send_message, chat_id, message, parse_mode="HTML") await asyncio.to_thread(
self.bot.send_message,
chat_id,
message,
parse_mode="HTML",
reply_markup=link_button
)
formatted_message = message.replace("\n", " ").replace("\r", "") formatted_message = message.replace("\n", " ").replace("\r", "")
logger.info(f"[MailingService] Отправлено уведомление {telegram_id} ({chat_id}): {formatted_message}") logger.info(f"[MailingService][tg message] Отправлено уведомление {telegram_id} ({chat_id}): {formatted_message}")
except apihelper.ApiTelegramException as e: except apihelper.ApiTelegramException as e:
if "429" in str(e): # Попытка получить error_code и описание из исключения
logger.warning(f"[MailingService] Rate limit для {telegram_id} ({chat_id}), ждем и повторяем...") error_code = None
description = None
try:
if hasattr(e, "result") and e.result:
error_code = e.result.get("error_code")
description = e.result.get("description")
except Exception:
pass
if error_code == 429:
logger.warning(f"[MailingService][tg message] Rate limit для {telegram_id} ({chat_id}), ждем и повторяем...")
await asyncio.sleep(1) await asyncio.sleep(1)
await self.send_message(chat_id, message) await self.send_message(chat_id, message, link)
elif error_code in (400, 403) and description and (
"user is deactivated" in description.lower() or
"bot was blocked by the user" in description.lower() or
"user not found" in description.lower()
):
logger.warning(f"[MailingService][tg message] Ошибка {error_code}: {description}. Пользователь {telegram_id} ({chat_id}) заблокировал бота или не существует. Отправка пропущена.")
# Не повторяем отправку
else: else:
logger.error(f"[MailingService] Ошибка отправки сообщения {telegram_id} ({chat_id}): {e}") logger.error(f"[MailingService][tg message] Ошибка отправки сообщения {telegram_id} ({chat_id}): {e}")
except Exception as e: except Exception as e:
logger.error(f"[MailingService] Неожиданная ошибка отправки сообщения {telegram_id} ({chat_id}): {e}") logger.error(f"[MailingService][tg message] Неожиданная ошибка отправки сообщения {telegram_id} ({chat_id}): {e}")
finally: finally:
rate_limit_semaphore.release() rate_limit_semaphore.release()
+9 -14
View File
@@ -1,19 +1,14 @@
# parser.py # parser.py
import re
def parse_region_id(hostgroups: str | None) -> str:
if not hostgroups:
return "0"
def parse_region_id(host: str) -> int | None: if hostgroups == "p00rtmis":
""" return "0"
Извлекает region_id из строки host.
Формат: p<region><...>, например p18ecpapp01 → region_id = 18
Returns: parts = hostgroups.split("_")
int | None: номер региона или None if len(parts) >= 2:
""" return parts[1]
if not host or not host.startswith("p"):
return None
match = re.match(r"^p(\d+)", host) return "0"
if match:
return int(match.group(1))
return None
@@ -1,8 +0,0 @@
from .parser import parse_region_id
from .db_utils import get_recipients_by_features
from app import Systems
async def get_recipients_from_data(data: dict, flask_app) -> list[int]:
system_names = [sys.system_name for sys in Systems.query.all()]
parsed = parse_message(data, system_names)
return get_recipients_by_features(parsed, flask_app)
@@ -0,0 +1,17 @@
from typing import Optional
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
def create_link_button(link: Optional[str]) -> Optional[InlineKeyboardMarkup]:
"""
Создаёт InlineKeyboardMarkup с кнопкой-ссылкой.
Если ссылка не передана, возвращает None.
"""
if not link:
return None
markup = InlineKeyboardMarkup()
button = InlineKeyboardButton(text="Открыть график", url=link)
markup.add(button)
return markup
@@ -0,0 +1,6 @@
def get_telegram_id_by_chat_id(flask_app, chat_id: int) -> str:
from app.models.users import Users # импорт здесь, чтобы избежать циклических зависимостей
with flask_app.app_context():
user = Users.query.filter_by(chat_id=chat_id).first()
return user.telegram_id if user else "unknown"
+10 -11
View File
@@ -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 # ← отличие
+9 -5
View File
@@ -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)
+18 -12
View File
@@ -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,17 +24,21 @@ 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()
user = User( user = User(
user_id=data['sam_account_name'], user_id=data['sam_account_name'],
user_name=data['user_name'], user_name=data['user_name'],
user_surname=data['user_surname'], user_surname=data['user_surname'],
user_middle_name=data['user_middle_name'], user_middle_name=data['user_middle_name'],
display_name=display_name, display_name=display_name,
email=data['email'] email=data['email']
) )
session.permanent = True session.permanent = True
@@ -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')
+32 -3
View File
@@ -1,9 +1,12 @@
from flask import current_app from flask import current_app
from flask_ldap3_login import LDAP3LoginManager, AuthenticationResponseStatus from flask_ldap3_login import LDAP3LoginManager, AuthenticationResponseStatus
from ldap3.core.exceptions import LDAPSocketOpenError, LDAPServerPoolExhaustedError
from werkzeug.middleware.proxy_fix import ProxyFix from werkzeug.middleware.proxy_fix import ProxyFix
import config import config
def init_ldap(app): def init_ldap(app):
app.config['LDAP_HOST'] = config.LDAP_HOST app.config['LDAP_HOST'] = config.LDAP_HOST
app.config['LDAP_PORT'] = config.LDAP_PORT app.config['LDAP_PORT'] = config.LDAP_PORT
@@ -24,15 +27,41 @@ def init_ldap(app):
ldap_manager.init_app(app) ldap_manager.init_app(app)
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1) app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1)
def authenticate_user(username, password): def authenticate_user(username, password):
ldap_manager = current_app.extensions['ldap3_login'] ldap_manager = current_app.extensions['ldap3_login']
response = ldap_manager.authenticate(username, password)
try:
# Явно пытаемся подключиться к LDAP
conn = ldap_manager.connection
if not conn.bind():
current_app.logger.error(f"Ошибка соединения с LDAP: {conn.last_error}")
return False, None, "LDAP-сервер недоступен. Повторите попытку позже."
except LDAPServerPoolExhaustedError as e:
current_app.logger.error(f"LDAP сервер недоступен: {e}")
return False, None, "LDAP-сервер не отвечает. Повторите попытку позже."
except LDAPSocketOpenError as e:
current_app.logger.error(f"Ошибка подключения к LDAP: {e}")
return False, None, "Ошибка подключения к LDAP-серверу. Повторите попытку позже."
except Exception as e:
current_app.logger.exception("Непредвиденная ошибка при подключении к LDAP")
return False, None, "Внутренняя ошибка при подключении к LDAP."
try:
response = ldap_manager.authenticate(username, password)
except Exception as e:
current_app.logger.exception("Ошибка при попытке аутентификации")
return False, None, "Ошибка при выполнении аутентификации."
if response.status == AuthenticationResponseStatus.success: if response.status == AuthenticationResponseStatus.success:
return True, response.user_info, None return True, response.user_info, None
elif response.status == AuthenticationResponseStatus.fail: elif response.status == AuthenticationResponseStatus.fail:
return False, None, "Invalid username or password." return False, None, "Неверное имя пользователя или пароль."
else: else:
return False, None, f"LDAP Error: {response.status}" return False, None, f"LDAP ошибка: {response.status}"
def parse_ldap_user(user_info): def parse_ldap_user(user_info):
def get(attr): def get(attr):
-28
View File
@@ -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
-86
View File
@@ -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)
+1 -1
View File
@@ -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>
+3 -4
View File
@@ -27,14 +27,13 @@ RABBITMQ_QUEUE = os.environ.get("RABBITMQ_QUEUE", "telegram_notifications")
RABBITMQ_NOTIFICATIONS_QUEUE = os.environ.get("RABBITMQ_NOTIFICATIONS_QUEUE", "notifications_queue") RABBITMQ_NOTIFICATIONS_QUEUE = os.environ.get("RABBITMQ_NOTIFICATIONS_QUEUE", "notifications_queue")
RABBITMQ_VHOST = os.getenv("RABBITMQ_VHOST", "/") RABBITMQ_VHOST = os.getenv("RABBITMQ_VHOST", "/")
RABBITMQ_VHOST_ENCODED = quote_plus(RABBITMQ_VHOST) RABBITMQ_VHOST_ENCODED = quote_plus(RABBITMQ_VHOST)
RABBITMQ_URL_FULL = ( RABBITMQ_URL_FULL = (
f"amqp://{RABBITMQ_LOGIN}:{RABBITMQ_PASS}@{RABBITMQ_HOST}:{RABBITMQ_PORT}/{RABBITMQ_VHOST_ENCODED}" f"amqp://{RABBITMQ_LOGIN}:{RABBITMQ_PASS}@{RABBITMQ_HOST}:{RABBITMQ_PORT}/{RABBITMQ_VHOST_ENCODED}"
) )
# Mailing settings # Mailing settings
MAILING_MAX_WORKERS = int(os.environ.get("MAILING_MAX_WORKERS", "16")) MAILING_MAX_WORKERS = int(os.getenv("MAILING_MAX_WORKERS", "16"))
MAILING_RATE_LIMIT = int(os.environ.get("MAILING_RATE_LIMIT", "25")) MAILING_RATE_LIMIT = int(os.getenv("MAILING_RATE_LIMIT", "25"))
MAILING_MAX_RETRIES = int(os.getenv("MAILING_MAX_RETRIES", "5"))
# Настройки Flask-LDAP3-login # Настройки Flask-LDAP3-login
LDAP_HOST = os.getenv('LDAP_HOST', 'localhost') LDAP_HOST = os.getenv('LDAP_HOST', 'localhost')
LDAP_PORT = int(os.getenv('LDAP_PORT', 389)) LDAP_PORT = int(os.getenv('LDAP_PORT', 389))
+2
View File
@@ -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