diff --git a/bot_modules/access.py b/bot_modules/access.py index bbaf65c..b413b54 100644 --- a/bot_modules/access.py +++ b/bot_modules/access.py @@ -3,14 +3,12 @@ # Права пользователей -from bot_sys import bot_bd, log, config, keyboard, user_access -from bot_modules import access_utils -from template import simple_message, sql_request, bd_item_edit, bd_item +from bot_sys import keyboard, user_access, bot_bd +from bot_modules import mod_simple_message +from template import simple_message, sql_request, bd_item from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup -from aiogram.dispatcher import Dispatcher -from aiogram import types class FSMRequestToBDAccess(StatesGroup): sqlRequest = State() @@ -33,19 +31,10 @@ mod_default_access_field = 'itemDefaultAccess' #TODO: Автоматическое создание init_bd_cmds, необходимо table_name, mod_name_field ... объединить в объект -init_bd_cmds = [f"""CREATE TABLE IF NOT EXISTS {table_name}( - {mod_name_field} TEXT, - {moduleaccess_field} TEXT, - {mod_default_access_field} TEXT, - UNIQUE({mod_name_field}) -);""", -f"INSERT OR IGNORE INTO {table_name} ({mod_name_field}, {moduleaccess_field}, {mod_default_access_field}) VALUES ('{module_name}', '{user_access.user_access_group_new}=-', '{user_access.user_access_group_new}=-');" -] - # --------------------------------------------------------- # Сообщения -access_start_message = ''' +start_message = ''' Права пользователей находятся в стадии разработки Пока можете воспользоваться хардкорным способом через запросы к БД @@ -68,7 +57,7 @@ help_message = ''' modAccess - строка ''' + user_access.user_access_readme -access_button_name = "⛀ Доступ пользователей" +start_button_name = "⛀ Доступ пользователей" sql_request_button_name = "⛁ Запрос к БД для редактирования доступа" help_button_name = "📄 Информация по редактированию доступа" @@ -100,6 +89,65 @@ moduleaccess_edit_default_access_message = f''' moduleaccess_success_edit_message = '''✅ Проект успешно отредактирован!''' +init_access = f'{user_access.user_access_group_new}=-' + +class ModuleAccess(mod_simple_message.SimpleMessageModule): + def __init__(self, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log): + super().__init__(start_message, start_button_name, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) + self.m_SqlRequestButtonName = self.CreateButton('sql request', sql_request_button_name) + self.m_RequestStartMessage = self.CreateMessage('equest start', request_start_message) + + self.m_HelpButtonName = self.CreateButton('help', help_button_name) + self.m_HelpMessage = self.CreateMessage('help', help_message) + + self.m_HelpMessageHandler = simple_message.InfoMessageTemplate( + self.m_Bot, + self.m_HelpMessage, + self.m_GetStartKeyboardButtonsFunc, + None, + self.m_GetAccessFunc + ) + + def GetInitBDCommands(self): + return super(). GetInitBDCommands() + [ + f"""CREATE TABLE IF NOT EXISTS {table_name}( + {mod_name_field} TEXT, + {moduleaccess_field} TEXT, + {mod_default_access_field} TEXT, + UNIQUE({mod_name_field}) + );""", + ] + + def GetName(self): + return module_name + + def GetStartKeyboardButtons(self, a_Message, a_UserGroups): + mod_buttons = super().GetStartKeyboardButtons(a_Message, a_UserGroups) + cur_buttons = [ + keyboard.ButtonWithAccess(self.m_SqlRequestButtonName, user_access.AccessMode.EDIT, self.GetAccess()), + keyboard.ButtonWithAccess(self.m_HelpButtonName , user_access.AccessMode.VIEW, self.GetAccess()) + ] + return mod_buttons + keyboard.MakeButtons(cur_buttons, a_UserGroups) + + def RegisterHandlers(self): + super().RegisterHandlers() + sql_request.RequestToBDRegisterHandlers( + self.m_Bot, + self.m_SqlRequestButtonName, + self.m_RequestStartMessage, + FSMRequestToBDAccess, + self.m_GetStartKeyboardButtonsFunc, + user_access.AccessMode.EDIT, + self.m_GetAccessFunc + ) + self.m_Bot.RegisterMessageHandler( + self.m_HelpMessageHandler, + bd_item.GetCheckForTextFunc(self.m_HelpButtonName) + ) + + + + # --------------------------------------------------------- # Работа с кнопками ''' @@ -202,22 +250,4 @@ def RegisterHandlers(dp : Dispatcher): RegisterEdit(edit_moduleaccess_default_access_button_name, FSMEditDefaultAccessItem, moduleaccess_edit_default_access_message, mod_default_access_field, bd_item.FieldType.text, user_access.AccessMode.EDIT) ''' -def GetAccessForModuleRequest(module_name, access, default_access): - return f"INSERT OR IGNORE INTO {table_name} ({mod_name_field}, {moduleaccess_field}, {mod_default_access_field}) VALUES ('{module_name}', '{access}', '{default_access}');" - -def GetModulesAccessList(a_Bot): - return bot_bd.RequestSelectTemplate(a_Bot.m_BDFileName, table_name)() -def GetAccessForModule(a_Bot, a_ModuleName): - alist = GetModulesAccessList(a_Bot) - for i in alist: - if i[0] == a_ModuleName: - return i[1] - return '' - -def GetItemDefaultAccessForModule(a_Bot, a_ModuleName): - alist = GetModulesAccessList(a_Bot) - for i in alist: - if i[0] == a_ModuleName: - return i[2] - return '' diff --git a/bot_modules/backup.py b/bot_modules/backup.py index 552e036..75fb9b9 100644 --- a/bot_modules/backup.py +++ b/bot_modules/backup.py @@ -17,7 +17,7 @@ start_message = ''' Здесь вы можете выполнить специальные операции по сервисному обслуживанию ''' -start_menu_button_name = "📦 Резервные копии и логи" +start_button_name = "📦 Резервные копии и логи" backup_bd_message = ''' 📀 Резервная копия базы данных @@ -40,7 +40,7 @@ init_access = f'{user_access.user_access_group_new}=-' class ModuleBackup(mod_simple_message.SimpleMessageModule): def __init__(self, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log): - super().__init__(start_message, start_menu_button_name, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) + super().__init__(start_message, start_button_name, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) self.m_BackupBDButtonName = self.CreateButton('backup bd', backup_bd_button_name) self.m_BackupBDMessage = self.CreateMessage('backup bd', backup_bd_message) diff --git a/bot_modules/groups.py b/bot_modules/groups.py index 4b606e0..01b702c 100644 --- a/bot_modules/groups.py +++ b/bot_modules/groups.py @@ -53,15 +53,15 @@ help_message = ''' `user_in_groups(user_id, group_id)` - содержит соответсвия ID пользователей и групп ''' -start_menu_button_name = "‍️️▦ Группы пользователей" +start_button_name = "‍️️▦ Группы пользователей" sql_request_button_name = "⛃ Запрос к БД для редактирования групп" help_button_name = "📄 Информация по группам" -init_access = '{user_access.user_access_group_new}=-' +init_access = f'{user_access.user_access_group_new}=-' class ModuleGroups(mod_simple_message.SimpleMessageModule): def __init__(self, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log): - super().__init__(start_message, start_menu_button_name, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) + super().__init__(start_message, start_button_name, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) self.m_SqlRequestButtonName = self.CreateButton('sql request', sql_request_button_name) self.m_RequestStartMessage = self.CreateMessage('equest start', request_start_message) diff --git a/bot_modules/profile.py b/bot_modules/profile.py index 842fd4c..5ed35e7 100644 --- a/bot_modules/profile.py +++ b/bot_modules/profile.py @@ -4,7 +4,7 @@ # Профиль пользователя from bot_sys import user_access, bot_bd -from bot_modules import mod_simple_message, groups, access +from bot_modules import mod_simple_message, groups, access, access_utils from template import bd_item, simple_message # --------------------------------------------------------- @@ -32,13 +32,13 @@ start_message = f''' Дата добавления: #{create_datetime_field} ''' -start_menu_button_name = "📰 Профиль" +start_button_name = "📰 Профиль" init_access = f'{user_access.user_access_group_new}=+' class ModuleProfile(mod_simple_message.SimpleMessageModule): def __init__(self, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log): - super().__init__(start_message, start_menu_button_name, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) + super().__init__(start_message, start_button_name, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) def GetInitBDCommands(self): return super(). GetInitBDCommands() + [ @@ -83,16 +83,16 @@ class ModuleProfile(mod_simple_message.SimpleMessageModule): # Добавление пользователя, если он уже есть, то игнорируем def AddUser(a_Bot, a_UserID, a_UserName, a_UserName1, a_UserName2, a_UserIsBot, a_LanguageCode): a_Bot.SQLRequest(f"INSERT OR IGNORE INTO users ({key_name}, {name_field}, {name1_field}, {name2_field}, {is_bot_field}, {language_code_field}, {access_field}, {create_datetime_field}) VALUES (?, ?, ?, ?, ?, ?, ?, {bot_bd.GetBDDateTimeNow()});", - commit=True, param = (a_UserID, a_UserName, a_UserName1, a_UserName2, a_UserIsBot, a_LanguageCode, access.GetItemDefaultAccessForModule(a_Bot, module_name))) + commit=True, param = (a_UserID, a_UserName, a_UserName1, a_UserName2, a_UserIsBot, a_LanguageCode, access_utils.GetItemDefaultAccessForModule(a_Bot, module_name))) ''' - user_groups = access.GetUserGroupData(a_Bot, a_UserID) + user_groups = access_utils.GetUserGroupData(a_Bot, a_UserID) # Если пользователь не состоит ни в одной группе, то добавляем его в группу user_access.user_access_group_new if len(user_groups.group_names_list) == 0: new_group_id = a_Bot.SQLRequest(f'SELECT {groups.key_table_groups_name} FROM {groups.table_groups_name} WHERE {groups.name_table_groups_field} = ?', param = [user_access.user_access_group_new]) if new_group_id and new_group_id[0]: a_Bot.SQLRequest(f"INSERT OR IGNORE INTO {groups.table_user_in_groups_name} ({groups.user_id_field}, {groups.key_table_groups_name}, {groups.access_field}, {groups.create_datetime_field}) VALUES (?, ?, ?, {bot_bd.GetBDDateTimeNow()});", - commit=True, param = (a_UserID, new_group_id[0][0], access.GetItemDefaultAccessForModule(a_Bot, module_name))) + commit=True, param = (a_UserID, new_group_id[0][0], access_utils.GetItemDefaultAccessForModule(a_Bot, module_name))) ''' def GetUserInfo(a_Bot, a_UserID): user_info = a_Bot.SQLRequest('SELECT * FROM users WHERE user_id = ?', param = [a_UserID]) diff --git a/bot_modules/start.py b/bot_modules/start.py index be1ef0a..5c3f945 100644 --- a/bot_modules/start.py +++ b/bot_modules/start.py @@ -12,13 +12,13 @@ start_message = ''' Выберите возможные действия на кнопках ниже ⌨''' -start_menu_button_name = "☰ Главное меню" +start_button_name = "☰ Главное меню" init_access = f'{user_access.user_access_group_all}=+' class ModuleStart(mod_simple_message.SimpleMessageModule): def __init__(self, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log): - super().__init__(start_message, start_menu_button_name, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) + super().__init__(start_message, start_button_name, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) def GetName(self): return 'start' diff --git a/main.py b/main.py index 58015fa..f3271f3 100644 --- a/main.py +++ b/main.py @@ -6,7 +6,7 @@ log_start_message = 'Бот успешно запущен!' import os from bot_sys import config, log, bot_bd, user_access, aiogram_bot, bot_messages -from bot_modules import mod_agregator, start, profile, backup, groups #, projects, , access, , tasks, needs, comments, messages, , languages +from bot_modules import mod_agregator, start, profile, backup, groups, access #, projects, , access, , tasks, needs, comments, messages, , languages g_Log = log g_Bot = aiogram_bot.AiogramBot(config.GetTelegramBotApiToken(), bot_bd.GetBDFileName(), config.GetRootIDs(), g_Log) @@ -29,10 +29,14 @@ g_ModuleAgregator.AddModule(mod_backup) mod_groups = groups.ModuleGroups([mod_start_name], g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_groups) +mod_access = access.ModuleAccess([mod_start_name], g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +g_ModuleAgregator.AddModule(mod_access) + start_mod_name_list = [#, 'projects', 'groups', 'access', , 'languages'] mod_profile.GetName(), mod_backup.GetName(), mod_groups.GetName(), + mod_access.GetName(), ] mod_start = start.ModuleStart(start_mod_name_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_start)