diff --git a/.gitignore b/.gitignore index e3f5dc5..a67820b 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ config_root_ids __pycache__ log.txt bot.db +tmp.py diff --git a/auth_docs/test_doc.html b/auth_docs/test_doc.html new file mode 100644 index 0000000..3f326bf --- /dev/null +++ b/auth_docs/test_doc.html @@ -0,0 +1,120 @@ + + + + + + + + + + +

+
+ +

+

Регистрационные +данные

+


+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ ID пользователя

+

+ TableFieldDestiny.USER_ID +

+

+ Имя

+

+ TableFieldDestiny.USER_NAME

+

+ Фамилия

+

+ TableFieldDestiny.USER_FAMILY_NAME

+

+ Отчество

+

+ TableFieldDestiny.USER_MIDDLE_NAME

+

+ Дата рождения

+

+ TableFieldDestiny.USER_BIRTHDAY

+

+ Адрес

+

+ TableFieldDestiny.USER_ADDRESS

+

+ Контакты

+

+ TableFieldDestiny.USER_CONTACTS

+

+ Подтверждение

+

+ TableFieldDestiny.USER_CONFIRM

+

+ Доступ

+

+ TableFieldDestiny.ACCESS

+

+ Дата создания записи

+

+ TableFieldDestiny.CREATE_DATE

+
+


+ +

+ + \ No newline at end of file diff --git a/auth_docs/test_doc.odt b/auth_docs/test_doc.odt new file mode 100644 index 0000000..92fa308 Binary files /dev/null and b/auth_docs/test_doc.odt differ diff --git a/bot_modules/access.py b/bot_modules/access.py index c5b9b6b..da020e4 100644 --- a/bot_modules/access.py +++ b/bot_modules/access.py @@ -106,7 +106,7 @@ init_access = f'{user_access.user_access_group_new}=-' class ModuleAccess(mod_table_operate.TableOperateModule): def __init__(self, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, None, None, init_access, a_ChildModuleNameList, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, None, None, init_access, init_access, a_ChildModuleNameList, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, 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/all_orders.py b/bot_modules/all_orders.py index 5efd31f..9f40bb9 100644 --- a/bot_modules/all_orders.py +++ b/bot_modules/all_orders.py @@ -111,7 +111,7 @@ class DBItemForUserSelectSource(bd_item_select.DBItemSelectSource): class ModuleAllOrders(orders.ModuleOrders): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetInitBDCommands(self): # уже сделано в ModuleUserOrders diff --git a/bot_modules/authorize.py b/bot_modules/authorize.py new file mode 100644 index 0000000..dced8b2 --- /dev/null +++ b/bot_modules/authorize.py @@ -0,0 +1,394 @@ +# -*- coding: utf8 -*- +# Общественное достояние, 2023, Алексей Безбородов (Alexei Bezborodov) + +# Авторизация или регистрация в кооперативе или другой организации + +from bot_sys import bot_bd, keyboard, user_access, bd_table, bot_subscribes, config +from bot_modules import mod_table_operate, mod_simple_message, users_groups_agregator, groups_utils +from template import docs_message, bd_item, bd_item_select + +from enum import Enum +from enum import auto +# --------------------------------------------------------- +# БД +module_name = 'authorize' + +table_name = module_name +user_id_field = 'userID' +user_name_field = 'userName' +user_family_name_field = 'userFamilyName' +user_middle_name_field = 'userMiddleName' +user_birthday_field = 'userBirthday' +user_address_field = 'userAddress' +user_contacts_field = 'userContacts' +user_confirm_field = 'userConfirm' +user_auth_docs_field = 'authDocs' +user_photo_pay_field = 'photoPay' +access_field = 'authorizeAccess' +create_datetime_field = 'authorizeCreateDateTime' + +user_id_table_field = bd_table.TableField(user_id_field, bd_table.TableFieldDestiny.USER_ID, bd_table.TableFieldType.INT) + +class ConfirmStatus(Enum): + YES = auto() + NO = auto() + +table = bd_table.Table(table_name, [ + user_id_table_field, + bd_table.TableField(user_name_field, bd_table.TableFieldDestiny.USER_NAME, bd_table.TableFieldType.STR), + bd_table.TableField(user_family_name_field, bd_table.TableFieldDestiny.USER_FAMILY_NAME, bd_table.TableFieldType.STR), + bd_table.TableField(user_middle_name_field, bd_table.TableFieldDestiny.USER_MIDDLE_NAME, bd_table.TableFieldType.STR), + bd_table.TableField(user_birthday_field, bd_table.TableFieldDestiny.USER_BIRTHDAY, bd_table.TableFieldType.STR), + bd_table.TableField(user_address_field, bd_table.TableFieldDestiny.USER_ADDRESS, bd_table.TableFieldType.STR), + bd_table.TableField(user_contacts_field, bd_table.TableFieldDestiny.USER_CONTACTS, bd_table.TableFieldType.STR), + bd_table.TableField(user_confirm_field, bd_table.TableFieldDestiny.USER_CONFIRM, bd_table.TableFieldType.ENUM, a_Enum = ConfirmStatus), + bd_table.TableField(user_auth_docs_field, bd_table.TableFieldDestiny.AUTH_PHOTO_DOCS, bd_table.TableFieldType.PHOTO), + bd_table.TableField(user_photo_pay_field, bd_table.TableFieldDestiny.PHOTO_PAY, bd_table.TableFieldType.PHOTO), + bd_table.TableField(access_field, bd_table.TableFieldDestiny.ACCESS, bd_table.TableFieldType.STR), + bd_table.TableField(create_datetime_field, bd_table.TableFieldDestiny.CREATE_DATE, bd_table.TableFieldType.STR), + ] + , + [ + [user_id_table_field], + ] + ) + +init_access = f'{user_access.user_access_group_new}=vea' +def_init_access = f'{user_access.user_access_group_new}=a' + +def GetAuthorizeItem(a_Bot, a_UserID): + items = bd_item.GetBDItemsTemplate(a_Bot, table_name, user_id_field)(a_UserID) + if len(items) == 1: + return items[0] + return None + +# --------------------------------------------------------- +# Сообщения и кнопки + +class ButtonNames(Enum): + LIST_AUTH_DOCS = auto() + +button_names = { + mod_simple_message.ButtonNames.START: "🔑 Авторизация", + mod_table_operate.ButtonNames.LIST: "≣ Список авторизаций пользователей", + mod_table_operate.ButtonNames.ADD: "📨 Заявка на вступление", + ButtonNames.LIST_AUTH_DOCS: "📨 Регистрационные документы", + mod_table_operate.ButtonNames.EDIT: "🛠 Редактировать свои данные", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.USER_ID): "☐ Изменить id пользователя", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.USER_NAME): "☐ Изменить имя пользователя", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.USER_FAMILY_NAME): "☐ Изменить фамилию пользователя", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.USER_MIDDLE_NAME): "☐ Изменить отчество пользователя", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.USER_BIRTHDAY): "☐ Изменить дату рождения пользователя", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.USER_ADDRESS): "☐ Изменить адрес пользователя", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.USER_CONTACTS): "☐ Изменить контакты пользователя", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.USER_CONFIRM): "☐ Изменить подтверждение пользователя", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.USER_ID): "☐ Изменить id пользователя", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.ACCESS): "✋ Доступ к авторизации пользователя", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.AUTH_PHOTO_DOCS): "☐ Загрузить подписанные документы", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.PHOTO_PAY): "☐ Оплатить членский взнос", + mod_table_operate.EditButton(bd_table.TableFieldDestiny.ACCESS): "✋ Доступ к авторизации пользователя", + mod_table_operate.ButtonNames.DEL: "❌ Удалить авторизацию пользователя", + mod_table_operate.EnumButton(ConfirmStatus.YES): "Да, все данные верны", + mod_table_operate.EnumButton(ConfirmStatus.NO): "Нет, данные не верны", +} + +class Messages(Enum): + LIST_AUTH_DOCS = auto() + LIST_AUTH_DOCS_ERROR = auto() + +messages = { + mod_simple_message.Messages.START: f''' +{button_names[mod_simple_message.ButtonNames.START]} + +''', + Messages.LIST_AUTH_DOCS: ''' +ваши регистрационные документы: +''', + Messages.LIST_AUTH_DOCS_ERROR: ''' +Ошибка получения документов. Обратитесь в техподдержку. +''', + mod_table_operate.Messages.SELECT: ''' +Пожалуйста, выберите пользователя: +''', + mod_table_operate.Messages.ERROR_FIND: ''' +❌ Ошибка, пользователь не найден +''', + mod_table_operate.Messages.OPEN: f''' +Пользователь: #{user_id_field} + +Имя: #{user_name_field} +Фамилия: #{user_family_name_field} +Отчество: #{user_middle_name_field} +Дата рождения: #{user_birthday_field} +Адрес: #{user_address_field} +Контакты: #{user_contacts_field} +Подтверждение авторизации: #{user_confirm_field} + +Время создания: #{create_datetime_field} +''', + mod_table_operate.CreateMessage(bd_table.TableFieldDestiny.USER_NAME): ''' +Авторизация. Шаг №1 + +Введите своё имя: +''', + mod_table_operate.CreateMessage(bd_table.TableFieldDestiny.USER_FAMILY_NAME): ''' +Авторизация. Шаг №2 + +Введите свою фамилию: +''', + mod_table_operate.CreateMessage(bd_table.TableFieldDestiny.USER_MIDDLE_NAME): ''' +Авторизация. Шаг №3 + +Введите своё отчество: +''', + mod_table_operate.CreateMessage(bd_table.TableFieldDestiny.USER_BIRTHDAY): ''' +Авторизация. Шаг №4 + +Введите свою дату рождения в формате ДД.ММ.ГГГГ: +''', + mod_table_operate.CreateMessage(bd_table.TableFieldDestiny.USER_ADDRESS): ''' +Авторизация. Шаг №5 + +Введите свой домашний адрес: +''', + mod_table_operate.CreateMessage(bd_table.TableFieldDestiny.USER_CONTACTS): ''' +Авторизация. Шаг №6 + +Введите свои контакты: +''', + mod_table_operate.CreateMessage(bd_table.TableFieldDestiny.USER_CONFIRM): f''' +Авторизация. Шаг №7 + +Имя: #{user_name_field} +Фамилия: #{user_family_name_field} +Отчество: #{user_middle_name_field} +Дата рождения: #{user_birthday_field} +Адрес: #{user_address_field} +Контакты: #{user_contacts_field} +Подтверждение авторизации: #{user_confirm_field} + +Подтвердите свои данные: +''', + + mod_table_operate.Messages.SUCCESS_CREATE: '''✅ Вы успешно зарегистрированы! Посмотрите документы и отправьте фотографии подписанных документов''', + mod_table_operate.Messages.START_EDIT: ''' +Пожалуйста, выберите действие: +''', + mod_table_operate.Messages.SELECT_TO_EDIT: ''' +Выберите пользователя, у которого вы хотите отредактировать данные. +''', + mod_table_operate.EditMessage(bd_table.TableFieldDestiny.USER_NAME): f''' +Текущее имя пользователя: +#{user_name_field} + +Введите новое имя пользователя: +''', + mod_table_operate.EditMessage(bd_table.TableFieldDestiny.USER_FAMILY_NAME): f''' +Текущая фамилия пользователя: +#{user_family_name_field} + +Введите новую фамилию пользователя: +''', + mod_table_operate.EditMessage(bd_table.TableFieldDestiny.USER_MIDDLE_NAME): f''' +Текущее отчество пользователя: +#{user_middle_name_field} + +Введите новое отчество пользователя: +''', + mod_table_operate.EditMessage(bd_table.TableFieldDestiny.USER_BIRTHDAY): f''' +Текущая дата рождения пользователя: +#{user_birthday_field} + +Введите новую дату рождения пользователя: +''', + mod_table_operate.EditMessage(bd_table.TableFieldDestiny.USER_ADDRESS): f''' +Текущий адрес пользователя: +#{user_address_field} + +Введите новый адрес пользователя: +''', + mod_table_operate.EditMessage(bd_table.TableFieldDestiny.USER_CONTACTS): f''' +Текущие контакты пользователя: +#{user_contacts_field} + +Введите новые контакты пользователя: +''', + mod_table_operate.EditMessage(bd_table.TableFieldDestiny.USER_CONFIRM): f''' +Текущее подтвержение пользователя: +#{user_confirm_field} + +Введите новое подтверждение пользователя: +''', + mod_table_operate.EditMessage(bd_table.TableFieldDestiny.AUTH_PHOTO_DOCS): f''' +Загрузите подписанный документ: +''', + mod_table_operate.EditMessage(bd_table.TableFieldDestiny.PHOTO_PAY): f''' +Загрузите чек по оплате ЧВ: +''', + mod_table_operate.EditMessage(bd_table.TableFieldDestiny.ACCESS): f''' +Текущий доступ к проекту: +#{access_field} + +{user_access.user_access_readme} + +Введите новую строку доступа: +''', + mod_table_operate.Messages.SUCCESS_EDIT: '''✅ Данные успешно отредактированы!''', + mod_table_operate.Messages.SELECT_TO_DELETE: ''' +Выберите пользователя, у которого вы хотите удалить авторизованные данные. +''', + mod_table_operate.Messages.SUCCESS_DELETE: '''✅ Данные пользователя успешно удалены!''', +} + +messages_subscribes = { + mod_table_operate.SubscribeMessage(bot_subscribes.SubscribeType.ADD):f'''Данные по авторизации созданы''', + mod_table_operate.SubscribeMessage(bot_subscribes.SubscribeType.ANY_ITEM_EDIT):f'''Данные по авторизации отредактированы''', + mod_table_operate.SubscribeMessage(bot_subscribes.SubscribeType.ANY_ITEM_DEL):f'''Данные по авторизации удалены''', + mod_table_operate.SubscribeMessage(bot_subscribes.SubscribeType.ITEM_EDIT):f'''Данные по авторизации отредактированы #item_id''', + mod_table_operate.SubscribeMessage(bot_subscribes.SubscribeType.ITEM_DEL):f'''Данные по авторизации удалены #item_id''', +} + +messages.update(messages_subscribes) + +messages_confirm_status = { + mod_table_operate.EnumMessageForView(ConfirmStatus.YES): f'''Да, все данные верны''', + mod_table_operate.EnumMessageForView(ConfirmStatus.NO): f'''Нет, данные не верны''', +} + +messages.update(messages_confirm_status) + +class ModuleAuthorize(mod_table_operate.TableOperateModule): + def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, def_init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + + def GetName(self): + return module_name + + def GetAccessForEditKeyboardButtons(self, a_Field): + cur_dict = { + bd_table.TableFieldDestiny.USER_ID: user_access.AccessMode.NONE, + bd_table.TableFieldDestiny.USER_NAME: user_access.AccessMode.NONE, + bd_table.TableFieldDestiny.USER_FAMILY_NAME: user_access.AccessMode.NONE, + bd_table.TableFieldDestiny.USER_MIDDLE_NAME: user_access.AccessMode.NONE, + bd_table.TableFieldDestiny.USER_BIRTHDAY: user_access.AccessMode.NONE, + bd_table.TableFieldDestiny.USER_ADDRESS: user_access.AccessMode.NONE, + bd_table.TableFieldDestiny.USER_CONTACTS: user_access.AccessMode.NONE, + bd_table.TableFieldDestiny.USER_CONFIRM: user_access.AccessMode.NONE, + bd_table.TableFieldDestiny.ACCESS: user_access.AccessMode.NONE, + bd_table.TableFieldDestiny.AUTH_PHOTO_DOCS: user_access.AccessMode.ADD, + bd_table.TableFieldDestiny.PHOTO_PAY: user_access.AccessMode.ADD, + } + return cur_dict.get(a_Field.m_Destiny, super().GetAccessForEditKeyboardButtons(a_Field)) + + def GetButtonNameAndKeyValueAndAccess(self, a_Item): + key_name_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.USER_ID) + name_field_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.USER_NAME) + fam_name_field_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.USER_FAMILY_NAME) + access_field_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.ACCESS) + assert key_name_id != None + assert name_field_id != None + assert fam_name_field_id != None + assert access_field_id != None + return \ + a_Item[name_field_id] + ' ' + a_Item[fam_name_field_id] + '(' + str(a_Item[key_name_id]) +')',\ + a_Item[key_name_id],\ + a_Item[access_field_id] + + async def OnChangeField(self, a_Field, a_ItemID, a_ItemData, a_EditUserID): + super().OnChangeField(a_Field, a_ItemID, a_ItemData, a_EditUserID) + user_id_field_name = self.m_Table.GetFieldNameByDestiny(bd_table.TableFieldDestiny.USER_ID) + user_id = a_ItemData[user_id_field_name] + user_confirm_field_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.USER_CONFIRM) + auth_docs_field_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.AUTH_PHOTO_DOCS) + pay_field_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.PHOTO_PAY) + item = GetAuthorizeItem(self.m_Bot, user_id) + if item and item[user_confirm_field_id] != '' and item[auth_docs_field_id] != '' and item[pay_field_id] != '': + users_groups_agregator.AddUserInGroup(self.m_Bot, user_id, user_access.user_access_group_auth_users) + + def GetStartButtons(self, a_Message, a_UserGroups): + user_id = str(a_Message.from_user.id) + item = GetAuthorizeItem(self.m_Bot, user_id) + user_confirm_field_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.USER_CONFIRM) + + cur_buttons = [] + + if item and item[user_confirm_field_id] == self.GetMessage(mod_table_operate.EnumMessageForView(ConfirmStatus.YES)).GetDesc(): + cur_buttons += [[ButtonNames.LIST_AUTH_DOCS, user_access.AccessMode.VIEW]] + cur_buttons += [[mod_table_operate.EditButton(bd_table.TableFieldDestiny.AUTH_PHOTO_DOCS), user_access.AccessMode.VIEW]] + cur_buttons += [[mod_table_operate.EditButton(bd_table.TableFieldDestiny.PHOTO_PAY), user_access.AccessMode.VIEW]] + else: + cur_buttons += [[mod_table_operate.ButtonNames.ADD, user_access.AccessMode.ADD]] + + return cur_buttons + [ + [mod_table_operate.ButtonNames.LIST, user_access.AccessMode.VIEW], + [mod_table_operate.ButtonNames.DEL, user_access.AccessMode.DELETE], + [mod_table_operate.ButtonNames.EDIT, user_access.AccessMode.EDIT], + ] + + def RegisterHandlers(self): + super().RegisterHandlers() + + def GetFilesFunc(a_user_id): + files = GetAuthDocs() + cur_dict = GetReplaceDictFunc(self.m_Bot, a_user_id) + result = {} + for f in files: + result.update({f: cur_dict}) + + return result + + button_name = self.GetButton(ButtonNames.LIST_AUTH_DOCS) + if button_name: + self.m_Bot.RegisterMessageHandler( + docs_message.DocFilesTemplate( + self.m_Bot, + GetFilesFunc, + self.GetMessage(Messages.LIST_AUTH_DOCS), + self.m_GetAccessFunc, + self.m_GetStartKeyboardButtonsFunc, + None, + self.GetMessage(Messages.LIST_AUTH_DOCS_ERROR), + access_mode = user_access.AccessMode.VIEW + ), + bd_item.GetCheckForTextFunc(button_name) + ) + + def AddBDItemFunc(self, a_ItemData, a_UserID): + a_ItemData[user_id_field] = a_UserID + a_ItemData[user_auth_docs_field] = '' + a_ItemData[user_photo_pay_field] = '' + result = super().AddBDItemFunc(a_ItemData, a_UserID) + return result + + def GetKeyFieldDestiny(self): + return bd_table.TableFieldDestiny.USER_ID + + def GetInitBDCommands(self): + return super(). GetInitBDCommands() + [ + groups_utils.CreateGroupRequest(user_access.user_access_group_auth_users) + ] + +def GetReplaceDictFunc(a_Bot, a_user_id): + item = GetAuthorizeItem(a_Bot, a_user_id) + if not item: + return None + result = {} + i = 0 + for f in table.GetFields(): + result.update({str(f.m_Destiny): str(item[i])}) + i += 1 + print(result) + return result + +auth_docs_file_name = 'config_auth_docs' + +g_auth_docs = [] + +def GetAuthDocs(): + global g_auth_docs + if len(g_auth_docs) == 0: + root_ids = config.GetAllLinesFromFile(auth_docs_file_name) + for i in root_ids: + g_auth_docs += [config.ClearReadLine(i)] + + return g_auth_docs diff --git a/bot_modules/backup.py b/bot_modules/backup.py index cf294a2..dc7b989 100644 --- a/bot_modules/backup.py +++ b/bot_modules/backup.py @@ -48,7 +48,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_BotSubscribes, a_Log): - super().__init__(messages, button_names, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(messages, button_names, init_access, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, 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/bd_version.py b/bot_modules/bd_version.py index d74dfd9..081a075 100644 --- a/bot_modules/bd_version.py +++ b/bot_modules/bd_version.py @@ -40,7 +40,7 @@ messages = { class ModuleBDVersion(mod_table_operate.TableOperateModule): def __init__(self, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, None, None, init_access, None, None, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, None, None, init_access, init_access, None, None, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/buttons.py b/bot_modules/buttons.py index 63e77fa..09dbfda 100644 --- a/bot_modules/buttons.py +++ b/bot_modules/buttons.py @@ -128,7 +128,7 @@ messages = { class ModuleButtons(mod_table_operate.TableOperateModule): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/comments.py b/bot_modules/comments.py index 953169f..b5c8457 100644 --- a/bot_modules/comments.py +++ b/bot_modules/comments.py @@ -130,7 +130,7 @@ messages.update(messages_subscribes) class ModuleComments(mod_table_operate.TableOperateModule): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/groups.py b/bot_modules/groups.py index c82485c..4e10654 100644 --- a/bot_modules/groups.py +++ b/bot_modules/groups.py @@ -125,12 +125,12 @@ messages = { class ModuleGroups(mod_table_operate.TableOperateModule): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name def GetInitBDCommands(self): return super(). GetInitBDCommands() + [ - f"INSERT OR IGNORE INTO {table_name} ({name_field}, {access_field}, {create_datetime_field}) VALUES ('{user_access.user_access_group_new}', '{user_access.user_access_group_new}=-', {bot_bd.GetBDDateTimeNow()});" + groups_utils.CreateGroupRequest(user_access.user_access_group_new) ] diff --git a/bot_modules/groups_utils.py b/bot_modules/groups_utils.py index 1bc67a0..27b2bbe 100644 --- a/bot_modules/groups_utils.py +++ b/bot_modules/groups_utils.py @@ -3,7 +3,7 @@ # Группы пользователей -from bot_sys import user_access +from bot_sys import user_access, bot_bd table_name = 'user_groups' key_name = 'groupID' @@ -28,3 +28,7 @@ def GetUserGroupData(a_Bot, a_UserID): if len(i) > 0: groups += [i[0]] return user_access.UserGroups(a_UserID, groups) + +def CreateGroupRequest(a_GroupName): + return f"INSERT OR IGNORE INTO {table_name} ({name_field}, {access_field}, {create_datetime_field}) VALUES ('{a_GroupName}', '{user_access.user_access_group_new}=-', {bot_bd.GetBDDateTimeNow()});" + diff --git a/bot_modules/languages.py b/bot_modules/languages.py index 06d0835..b3022fb 100644 --- a/bot_modules/languages.py +++ b/bot_modules/languages.py @@ -126,7 +126,7 @@ messages = { class ModuleLanguages(mod_table_operate.TableOperateModule): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) self.m_LanguageIDs = {} def GetName(self): diff --git a/bot_modules/messages.py b/bot_modules/messages.py index 310b043..27ca51f 100644 --- a/bot_modules/messages.py +++ b/bot_modules/messages.py @@ -128,7 +128,7 @@ messages = { class ModuleMessages(mod_table_operate.TableOperateModule): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/mod_simple_message.py b/bot_modules/mod_simple_message.py index a533a9d..8f5e9a3 100644 --- a/bot_modules/mod_simple_message.py +++ b/bot_modules/mod_simple_message.py @@ -17,9 +17,10 @@ class Messages(Enum): START = auto() class SimpleMessageModule(mod_interface.IModule): - def __init__(self, a_Messages, a_Buttons, a_InitAccess, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): + def __init__(self, a_Messages, a_Buttons, a_InitAccess, a_DefInitAccess, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): self.m_ChildModuleNameList = a_ChildModuleNameList self.m_InitAccess = a_InitAccess + self.m_DefInitAccess = a_DefInitAccess self.m_Bot = a_Bot self.m_ModuleAgregator = a_ModuleAgregator self.m_BotMessages = a_BotMessages @@ -99,7 +100,7 @@ class SimpleMessageModule(mod_interface.IModule): def GetInitBDCommands(self): return [ - access_utils.GetAccessForModuleRequest(self.GetName(), self.m_InitAccess, self.m_InitAccess), + access_utils.GetAccessForModuleRequest(self.GetName(), self.m_InitAccess, self.m_DefInitAccess), ] def GetAccess(self): diff --git a/bot_modules/mod_table_operate.py b/bot_modules/mod_table_operate.py index acff162..5c257c4 100644 --- a/bot_modules/mod_table_operate.py +++ b/bot_modules/mod_table_operate.py @@ -83,8 +83,8 @@ def MakeFSMForEdit(a_ModName, a_FieldName): return _locals['fsm'] class TableOperateModule(mod_simple_message.SimpleMessageModule): - def __init__(self, a_Table, a_Messages, a_Buttons, a_ParentModName, a_ChildModName, a_InitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(a_Messages, a_Buttons, a_InitAccess, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + def __init__(self, a_Table, a_Messages, a_Buttons, a_ParentModName, a_ChildModName, a_InitAccess, a_DefInitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): + super().__init__(a_Messages, a_Buttons, a_InitAccess, a_DefInitAccess, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) self.m_Table = a_Table self.m_EditModuleNameList = a_EditModuleNameList self.m_ChildModName = a_ChildModName @@ -99,8 +99,8 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): return self.GetButtonNameAndKeyValueAndAccess(a_Item) self.m_GetButtonNameAndKeyValueAndAccessFunc = GetButtonNameAndKeyValueAndAccess - async def PreDelete(a_CallbackQuery, a_Item): - return await self.PreDelete(a_CallbackQuery, a_Item) + async def PreDelete(a_CallbackQuery, a_Item, a_None): + return await self.PreDelete(a_CallbackQuery, a_Item, a_None) self.m_PreDeleteFunc = PreDelete async def PostDelete(a_CallbackQuery, a_ItemID): @@ -116,23 +116,33 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): self.m_Table.GetInitTableRequest(), ] + super().GetInitBDCommands() + def GetStartButtons(self, a_Message, a_UserGroups): + return [ + [ButtonNames.LIST, user_access.AccessMode.VIEW], + [ButtonNames.ADD, user_access.AccessMode.ADD], + [ButtonNames.DEL, user_access.AccessMode.DELETE], + [ButtonNames.EDIT, user_access.AccessMode.EDIT], + ] + def GetStartKeyboardButtons(self, a_Message, a_UserGroups): mod_buttons = super().GetStartKeyboardButtons(a_Message, a_UserGroups) - cur_buttons = [ - keyboard.ButtonWithAccess(self.GetButton(ButtonNames.LIST), user_access.AccessMode.VIEW, self.GetAccess()), - keyboard.ButtonWithAccess(self.GetButton(ButtonNames.ADD), user_access.AccessMode.ADD, self.GetAccess()), - keyboard.ButtonWithAccess(self.GetButton(ButtonNames.DEL), user_access.AccessMode.DELETE, self.GetAccess()), - keyboard.ButtonWithAccess(self.GetButton(ButtonNames.EDIT), user_access.AccessMode.EDIT, self.GetAccess()), - ] + cur_buttons = [] + for b in self.GetStartButtons(a_Message, a_UserGroups): + bn = b[0] + ba = b[1] + cur_buttons += [keyboard.ButtonWithAccess(self.GetButton(bn), ba, self.GetAccess())] return mod_buttons + keyboard.MakeButtons(self.m_Bot, cur_buttons, a_UserGroups) + def GetAccessForEditKeyboardButtons(self, a_Field): + if a_Field.m_Destiny == bd_table.TableFieldDestiny.ACCESS or a_Field.m_Destiny == bd_table.TableFieldDestiny.DEFAULT_ACCESS: + return user_access.AccessMode.ACCEES_EDIT + return user_access.AccessMode.EDIT + def GetEditKeyboardButtons(self, a_Message, a_UserGroups): mod_buttons = keyboard.MakeButtons(self.m_Bot, self.GetButtons(self.m_EditModuleNameList), a_UserGroups) cur_buttons = [] for f in self.m_Table.GetFields(): - access = user_access.AccessMode.EDIT - if f.m_Destiny == bd_table.TableFieldDestiny.ACCESS or f.m_Destiny == bd_table.TableFieldDestiny.DEFAULT_ACCESS: - access = user_access.AccessMode.ACCEES_EDIT + access = self.GetAccessForEditKeyboardButtons(f) cur_buttons += [keyboard.ButtonWithAccess(self.GetButton(EditButton(f.m_Destiny)), access, self.GetAccess()),] return mod_buttons + keyboard.MakeButtons(self.m_Bot, cur_buttons, a_UserGroups) @@ -154,7 +164,7 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): return keyboard.MakeInlineKeyboardButtons(self.m_Bot, cur_buttons, a_UserGroups) def GetButtonNameAndKeyValueAndAccess(self, a_Item): - key_name_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.KEY) + key_name_id = self.GetKeyFieldID() name_field_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.NAME) access_field_id = self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.ACCESS) assert key_name_id != None @@ -182,12 +192,32 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): a_Msg.UpdatePhotoID(','.join(photos)) return a_Msg + def UpdateMessageByDict(self, a_Msg, a_Lang, a_ItemDict, a_EnablePhoto = False): + a_Msg.UpdateDesc(self.m_Table.ReplaceAllFieldTagsByDict(a_Msg.GetDesc(), a_ItemDict)) + photos = [] + for f in self.m_Table.GetFields(): + if f.m_Type == bd_table.TableFieldType.ENUM: + for s in f.m_Enum: + msg = self.GetMessage(EnumMessageForView(s)) + if msg: + a_Msg.UpdateDesc(a_Msg.GetDesc().replace(str(s), str(msg.GetMessageForLang(a_Lang).StaticCopy()))) + elif f.m_Type == bd_table.TableFieldType.PHOTO: + if f.m_Name in a_ItemDict: + photos += [str(a_ItemDict[f.m_Name])] + if a_EnablePhoto: + a_Msg.UpdatePhotoID(','.join(photos)) + return a_Msg + def ShowMessageTemplate(self, a_Message, Inline_keyboard_template_func = None, a_EnablePhoto = False): - async def ShowMessage(a_CallbackQuery, a_Item): + async def ShowMessage(a_CallbackQuery, a_Item, a_ItemDict): msg = a_Message.StaticCopy() - # TODO: добавить поддержку языка в a_MessageName + # TODO: добавить поддержку языков в a_MessageName Inline_keyboard_func = None item_access = None + if a_ItemDict: + lang = str(a_CallbackQuery.from_user.language_code) + msg = msg.GetMessageForLang(lang).StaticCopy() + msg = self.UpdateMessageByDict(msg, lang, a_ItemDict, a_EnablePhoto = a_EnablePhoto) if a_Item: if len(a_Item) < self.m_Table.GetFieldsCount() - 1: # Для проектов это нужно. Там на 1 меньше поле. TODO разделить отправку сообщений item_access и Inline_keyboard_func return simple_message.WorkFuncResult(self.GetMessage(Messages.ERROR_FIND)) @@ -197,14 +227,14 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): msg = self.UpdateMessage(msg, lang, a_Item, a_EnablePhoto = a_EnablePhoto) item_access = a_Item[self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.ACCESS)] if Inline_keyboard_template_func: - Inline_keyboard_func = Inline_keyboard_template_func(a_Item[self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.KEY)]) + Inline_keyboard_func = Inline_keyboard_template_func(a_Item[self.GetKeyFieldID()]) return simple_message.WorkFuncResult(msg, item_access = item_access, Inline_keyboard_func = Inline_keyboard_func) return ShowMessage - async def PreDelete(self, a_CallbackQuery, a_Item): + async def PreDelete(self, a_CallbackQuery, a_Item, a_None): if len(a_Item) < self.m_Table.GetFieldsCount(): - return simple_message.WorkFuncResult(error_find_proj_message) + return simple_message.WorkFuncResult(self.GetMessage(Messages.ERROR_FIND)) access = a_Item[self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.ACCESS)] return simple_message.WorkFuncResult(self.GetMessage(Messages.SUCCESS_DELETE), None, item_access = access) @@ -309,12 +339,12 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): return a_Prefix - def AdditionalKeyboardForEditTemplate(self, a_Field): + def AdditionalKeyboardForEditTemplate(self, a_Field, user_access = user_access.AccessMode.EDIT): if a_Field.m_Type == bd_table.TableFieldType.ENUM: def KeyboardButtons(a_Message, a_UserGroups): cur_buttons = [] for s in a_Field.m_Enum: - cur_buttons += [keyboard.ButtonWithAccess(self.GetButton(EnumButton(s)), user_access.AccessMode.EDIT, self.GetAccess()),] + cur_buttons += [keyboard.ButtonWithAccess(self.GetButton(EnumButton(s)), user_access, self.GetAccess()),] return keyboard.MakeButtons(self.m_Bot, cur_buttons, a_UserGroups) return KeyboardButtons return None @@ -356,7 +386,7 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): return self.OnChange() table_name = self.m_Table.GetName() - key_name = self.m_Table.GetFieldNameByDestiny(bd_table.TableFieldDestiny.KEY) + key_name = self.GetKeyFieldName() edit_keyboard_func = self.m_GetEditKeyboardButtonsFunc GetButtonNameAndKeyValueAndAccess = self.m_GetButtonNameAndKeyValueAndAccessFunc GetAccess = self.m_GetAccessFunc @@ -383,9 +413,23 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): ) def GetAddFields(self): + add_destiny = ( + bd_table.TableFieldDestiny.NAME, + bd_table.TableFieldDestiny.DESC, + bd_table.TableFieldDestiny.PHOTO, + bd_table.TableFieldDestiny.SUBSCRIBE_TYPE, + bd_table.TableFieldDestiny.ITEM_ID, + bd_table.TableFieldDestiny.USER_NAME, + bd_table.TableFieldDestiny.USER_FAMILY_NAME, + bd_table.TableFieldDestiny.USER_MIDDLE_NAME, + bd_table.TableFieldDestiny.USER_BIRTHDAY, + bd_table.TableFieldDestiny.USER_ADDRESS, + bd_table.TableFieldDestiny.USER_CONTACTS, + bd_table.TableFieldDestiny.USER_CONFIRM, + ) fields = [] for f in self.m_Table.GetFields(): - if f.m_Destiny in (bd_table.TableFieldDestiny.NAME, bd_table.TableFieldDestiny.DESC, bd_table.TableFieldDestiny.PHOTO, bd_table.TableFieldDestiny.SUBSCRIBE_TYPE, bd_table.TableFieldDestiny.ITEM_ID, ): + if f.m_Destiny in add_destiny: fields += [f] return fields @@ -419,23 +463,32 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): f_id = 0 f = fields[f_id] - keyboard = bd_item.MixKeyboardFuncTemplate(self.AdditionalKeyboardForEditTemplate(f), GetKeyboard(f)) + keyboard = bd_item.MixKeyboardFuncTemplate(self.AdditionalKeyboardForEditTemplate(f, user_access.AccessMode.ADD), GetKeyboard(f)) reg_func(bd_item_add.StartAddBDItemTemplate(self.m_Bot, fsm, getattr(fsm, f'item{f_id}'), self.ShowMessageTemplate(self.GetMessage(CreateMessage(f.m_Destiny))), a_ParentTableName, a_ParentKeyFieldName, a_ParentPrefix, a_AccessFunc, keyboard, a_ButtonFunc, access_mode), a_StartCheckFunc) for i in range(len(fields) - 1): f = fields[i] next_f = fields[i + 1] - keyboard = bd_item.MixKeyboardFuncTemplate(self.AdditionalKeyboardForEditTemplate(next_f), GetKeyboard(next_f)) + keyboard = bd_item.MixKeyboardFuncTemplate(self.AdditionalKeyboardForEditTemplate(next_f, user_access.AccessMode.ADD), GetKeyboard(next_f)) self.m_Bot.RegisterMessageHandler(bd_item_add.NextAddBDItemTemplate(self.m_Bot, fsm, None, a_ParentTableName, a_ParentKeyFieldName, f.m_Name, self.ShowMessageTemplate(self.GetMessage(CreateMessage(next_f.m_Destiny))), None, a_AccessFunc, keyboard, a_ButtonFunc, access_mode, field_type = GetFieldType(f)), content_types = GetContentTypes(f), state = getattr(fsm, f'item{i}')) f_id = len(fields) - 1 f = fields[f_id] self.m_Bot.RegisterMessageHandler(bd_item_add.FinishAddBDItemTemplate(self.m_Bot, fsm, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, f.m_Name, self.ShowMessageTemplate(self.GetMessage(Messages.SUCCESS_CREATE)), None, a_AccessFunc, a_ButtonFunc, access_mode, field_type = GetFieldType(f)), content_types = GetContentTypes(f), state = getattr(fsm, f'item{f_id}')) + def GetKeyFieldDestiny(self): + return bd_table.TableFieldDestiny.KEY + + def GetKeyFieldName(self): + return self.m_Table.GetFieldNameByDestiny(self.GetKeyFieldDestiny()) + + def GetKeyFieldID(self): + return self.m_Table.GetFieldIDByDestiny(self.GetKeyFieldDestiny()) + def RegisterHandlers(self): super().RegisterHandlers() table_name = self.m_Table.GetName() - key_name = self.m_Table.GetFieldNameByDestiny(bd_table.TableFieldDestiny.KEY) + key_name = self.GetKeyFieldName() name_field = self.m_Table.GetFieldNameByDestiny(bd_table.TableFieldDestiny.NAME) desc_field = self.m_Table.GetFieldNameByDestiny(bd_table.TableFieldDestiny.DESC) photo_field = self.m_Table.GetFieldNameByDestiny(bd_table.TableFieldDestiny.PHOTO) @@ -448,7 +501,7 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): if self.m_ParentModName: parent_mod = self.GetModule(self.m_ParentModName) parent_table_name = parent_mod.m_Table.GetName() - parent_key_name = parent_mod.m_Table.GetFieldNameByDestiny(bd_table.TableFieldDestiny.KEY) + parent_key_name = parent_mod.GetKeyFieldName() def GetViewItemInlineKeyboardTemplate(a_ItemID): return self.GetViewItemInlineKeyboardTemplate(a_ItemID) diff --git a/bot_modules/needs.py b/bot_modules/needs.py index 0f0bf2f..ace1d88 100644 --- a/bot_modules/needs.py +++ b/bot_modules/needs.py @@ -131,7 +131,7 @@ messages.update(messages_subscribes) class ModuleNeeds(mod_table_operate.TableOperateModule): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/orders.py b/bot_modules/orders.py index 3559006..1c4a973 100644 --- a/bot_modules/orders.py +++ b/bot_modules/orders.py @@ -45,7 +45,7 @@ table = bd_table.Table(table_name, [ bd_table.TableField(parent_id_field, bd_table.TableFieldDestiny.PARENT_ID, bd_table.TableFieldType.INT), ]) -init_access = f'{user_access.user_access_group_new}=vea' +init_access = f'{user_access.user_access_group_auth_users}=vea' # --------------------------------------------------------- # Сообщения и кнопки @@ -200,8 +200,8 @@ class DBItemForUserSelectSource(bd_item_select.DBItemSelectSource): return True class ModuleOrders(mod_table_operate.TableOperateModule): - def __init__(self, a_Table, a_Messages, a_Buttons, a_ParentModName, a_ChildModName, a_InitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, a_Messages, a_Buttons, a_ParentModName, a_ChildModName, a_InitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + def __init__(self, a_Table, a_Messages, a_Buttons, a_ParentModName, a_ChildModName, a_InitAccess, a_DefInitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): + super().__init__(table, a_Messages, a_Buttons, a_ParentModName, a_ChildModName, a_InitAccess, a_DefInitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def SelectSourceTemplate(self, a_PrevPrefix, a_ButtonName): parent_id_field = self.m_Table.GetFieldNameByDestiny(bd_table.TableFieldDestiny.PARENT_ID) @@ -262,7 +262,7 @@ class ModuleOrders(mod_table_operate.TableOperateModule): class ModuleUserOrders(ModuleOrders): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/profile.py b/bot_modules/profile.py index f0c2a67..c584a07 100644 --- a/bot_modules/profile.py +++ b/bot_modules/profile.py @@ -32,7 +32,7 @@ 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_BotSubscribes, a_Log): - super().__init__(messages, button_names, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(messages, button_names, init_access, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/projects.py b/bot_modules/projects.py index becbc93..a3fc0c0 100644 --- a/bot_modules/projects.py +++ b/bot_modules/projects.py @@ -129,7 +129,7 @@ messages.update(messages_subscribes) class ModuleProjects(mod_table_operate.TableOperateModule): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/start.py b/bot_modules/start.py index dc55776..58d3c63 100644 --- a/bot_modules/start.py +++ b/bot_modules/start.py @@ -24,7 +24,7 @@ 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_BotSubscribes, a_Log): - super().__init__(messages, button_names, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(messages, button_names, init_access, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/subscribes.py b/bot_modules/subscribes.py index 84c2715..6c4e663 100644 --- a/bot_modules/subscribes.py +++ b/bot_modules/subscribes.py @@ -154,13 +154,6 @@ messages_subs_type_status = { messages.update(messages_subs_type_status) -def GetCurItemsTemplate(a_Bot, a_TableName, a_UserIDFieldName, a_StatusFieldName): - def GetBDItems(a_Message, a_UserGroups, a_ParentID): - user_id = str(a_Message.from_user.id) - request = f'SELECT * FROM {a_TableName} WHERE {a_UserIDFieldName} = ? AND {a_StatusFieldName} != ?' - return a_Bot.SQLRequest(request, param = ([user_id, str(OrderStatus.FINISH)])) - return GetBDItems - def GetBDItemsForUserTemplate(a_Bot, a_TableName, a_UserIDFieldName): def GetBDItems(a_Message, a_UserGroups, a_ParentID): user_id = str(a_Message.from_user.id) @@ -178,8 +171,8 @@ class DBItemForUserSelectSource(bd_item_select.DBItemSelectSource): return True class ModuleSubscribe(mod_table_operate.TableOperateModule): - def __init__(self, a_Table, a_Messages, a_Buttons, a_ParentModName, a_ChildModName, a_InitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, a_Messages, a_Buttons, a_ParentModName, a_ChildModName, a_InitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + def __init__(self, a_Table, a_Messages, a_Buttons, a_ParentModName, a_ChildModName, a_InitAccess, a_DefInitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): + super().__init__(table, a_Messages, a_Buttons, a_ParentModName, a_ChildModName, a_InitAccess, a_DefInitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def SelectSourceTemplate(self, a_PrevPrefix, a_ButtonName): parent_id_field = self.m_Table.GetFieldNameByDestiny(bd_table.TableFieldDestiny.PARENT_ID) @@ -212,7 +205,7 @@ class ModuleSubscribe(mod_table_operate.TableOperateModule): class ModuleUserSubscribe(ModuleSubscribe): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) self.UpdateSubscribes() def GetName(self): diff --git a/bot_modules/tasks.py b/bot_modules/tasks.py index 8e148b7..1523adb 100644 --- a/bot_modules/tasks.py +++ b/bot_modules/tasks.py @@ -131,7 +131,7 @@ messages.update(messages_subscribes) class ModuleTasks(mod_table_operate.TableOperateModule): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/user_in_groups.py b/bot_modules/user_in_groups.py index f2e7830..3509cad 100644 --- a/bot_modules/user_in_groups.py +++ b/bot_modules/user_in_groups.py @@ -106,7 +106,7 @@ messages = { class ModuleUserInGroups(mod_table_operate.TableOperateModule): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/users.py b/bot_modules/users.py index e4feaee..ba92907 100644 --- a/bot_modules/users.py +++ b/bot_modules/users.py @@ -128,7 +128,7 @@ messages = { class ModuleUsers(mod_table_operate.TableOperateModule): def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) def GetName(self): return module_name diff --git a/bot_modules/users_groups_agregator.py b/bot_modules/users_groups_agregator.py index 4c4533a..e26b55d 100644 --- a/bot_modules/users_groups_agregator.py +++ b/bot_modules/users_groups_agregator.py @@ -57,7 +57,7 @@ init_access = f'{user_access.user_access_group_new}=-' class ModuleUsersGroupsAgregator(mod_simple_message.SimpleMessageModule): def __init__(self, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log): - super().__init__(messages, button_names, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) + super().__init__(messages, button_names, init_access, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_BotSubscribes, a_Log) self.m_SqlRequestButtonName = self.CreateButton('sql request', sql_request_button_name) self.m_RequestStartMessage = self.CreateMessage('equest start', request_start_message) @@ -99,3 +99,12 @@ class ModuleUsersGroupsAgregator(mod_simple_message.SimpleMessageModule): bd_item.GetCheckForTextFunc(self.m_HelpButtonName) ) +def AddUserInGroup(a_Bot, a_UserID, a_GroupName): + g_id = a_Bot.SQLRequest(f'SELECT {groups.key_name} FROM {groups.table_name} WHERE {groups.name_field} = "{a_GroupName}"'); + if not g_id or len(g_id) != 1 or len(g_id[0]) != 1: + return False + group_id = g_id[0][0] + r = f'INSERT OR IGNORE INTO {user_in_groups.table_name}({user_in_groups.name_field}, {user_in_groups.parent_id_field}) VALUES(?, ?)' + result = a_Bot.SQLRequest(r, commit=True, param = (a_UserID, group_id)) + + diff --git a/bot_sys/bd_table.py b/bot_sys/bd_table.py index 593b146..25c2981 100644 --- a/bot_sys/bd_table.py +++ b/bot_sys/bd_table.py @@ -38,6 +38,15 @@ class TableFieldDestiny(Enum): OTHER = auto() VERSION_NUMBER = auto() SUB_VERSION_NUMBER = auto() + USER_ID = auto() + USER_NAME = auto() # Имя + USER_FAMILY_NAME = auto() # Фамилия + USER_MIDDLE_NAME = auto() # Отчество + USER_BIRTHDAY = auto() # Дата рождения + USER_ADDRESS = auto() # Адресс + USER_CONTACTS = auto() # контакты + USER_CONFIRM = auto() # подтверждение + AUTH_PHOTO_DOCS = auto() class TableField: def __init__(self, a_Name, a_Destiny : TableFieldDestiny, a_Type : TableFieldType, a_Enum = None): @@ -103,6 +112,13 @@ class Table: result = result.replace(f'#{f.m_Name}', str(a_BDItem[i])) return result + def ReplaceAllFieldTagsByDict(self, a_String, a_BDItemDict): + result = a_String + for f in self.m_Fields: + if f.m_Name in a_BDItemDict: + result = result.replace(f'#{f.m_Name}', str(a_BDItemDict[f.m_Name])) + return result + class Status(Enum): NEW = auto() FINISH = auto() diff --git a/bot_sys/bot_bd.py b/bot_sys/bot_bd.py index ec81174..47583b2 100644 --- a/bot_sys/bot_bd.py +++ b/bot_sys/bot_bd.py @@ -9,6 +9,7 @@ from bot_sys import log def GetBDDateTimeNow(): return 'datetime(\'now\')' +# TODO: Удалить что-то из SelectBDTemplate RequestSelectTemplate def SelectBDTemplate(a_Bot, a_TableName): def SelectBD(): return a_Bot.SQLRequest(f'SELECT * FROM {a_TableName}') diff --git a/bot_sys/user_access.py b/bot_sys/user_access.py index abe3127..39394cd 100644 --- a/bot_sys/user_access.py +++ b/bot_sys/user_access.py @@ -8,6 +8,7 @@ from bot_sys import config user_access_group_all = 'all' user_access_group_new = 'new' +user_access_group_auth_users = 'authorize_users' user_access_readme = f''' Доступ к пользователям задаётся в виде строки @@ -32,11 +33,13 @@ ACCEES_EDIT = 'r' - изменение прав доступа # Типы уровня доступа class AccessMode(Enum): + NONE = '-' VIEW = 'v' ADD = 'a' EDIT = 'e' DELETE = 'd' ACCEES_EDIT = 'r' + ALL = '+' class UserGroups: def __init__(self, a_UserID : str, a_GroupNamesList : [str]): @@ -55,6 +58,7 @@ def CheckAccessItem(a_AccessItem : str, a_AccessMode : AccessMode): # Возвращает возможность доступа пользователю a_UserGroups в элемент с правами a_AccessValue по режиму доступа a_AccessMode def CheckAccess(a_RootIDs, a_AccessValue : str, a_UserGroups : UserGroups, a_AccessMode : AccessMode): + #print(a_RootIDs, a_AccessValue, a_UserGroups, a_AccessMode) if a_UserGroups.user_id in a_RootIDs: return True for i in a_AccessValue.split(';'): diff --git a/config_auth_docs b/config_auth_docs new file mode 100644 index 0000000..1524400 --- /dev/null +++ b/config_auth_docs @@ -0,0 +1 @@ +auth_docs/test_doc.html diff --git a/main.py b/main.py index 3ed4e1f..b064418 100644 --- a/main.py +++ b/main.py @@ -6,7 +6,7 @@ import os from bot_sys import config, log, aiogram_bot, bot_messages, bd_table, user_access from bot_modules import mod_agregator, start, profile, backup, users_groups_agregator, access, projects, tasks, needs, comments from bot_modules import languages, messages, buttons, users, groups, user_in_groups -from bot_modules import orders, all_orders +from bot_modules import orders, all_orders, authorize from bot_modules import bd_version from bot_sys import bot_subscribes @@ -110,6 +110,10 @@ g_ModuleAgregator.AddModule(mod_subscribe) mod_bd_version = bd_version.ModuleBDVersion(g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_BotSubscribes, g_Log) g_ModuleAgregator.AddModule(mod_bd_version) +child_mod_name_list = [mod_start_name] +mod_authorize = authorize.ModuleAuthorize(None, None, child_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_BotSubscribes, g_Log) +g_ModuleAgregator.AddModule(mod_authorize) + child_mod_name_list = [ mod_profile.GetName(), mod_backup.GetName(), @@ -121,6 +125,7 @@ child_mod_name_list = [ mod_all_orders.GetName(), mod_subscribe.GetName(), mod_bd_version.GetName(), + mod_authorize.GetName(), ] mod_start = start.ModuleStart(child_mod_name_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_BotSubscribes, g_Log) g_ModuleAgregator.AddModule(mod_start) diff --git a/requirements.txt b/requirements.txt index e99a1ef..296c19c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ aiogram==2.20 colorama==0.4.5 +weasyprint diff --git a/template/bd_item.py b/template/bd_item.py index 5a08a84..8cc9783 100644 --- a/template/bd_item.py +++ b/template/bd_item.py @@ -100,7 +100,7 @@ def CheckAccessBDItemTemplate(a_Bot, a_TableName, a_KeyName, a_KeyValue, a_WorkF a_Bot.GetLog().Error(msg) return simple_message.WorkFuncResult(bot_messages.MakeBotMessage(msg)), None - result_work_func = await a_WorkFunc(a_CallbackQuery, item[0]) + result_work_func = await a_WorkFunc(a_CallbackQuery, item[0], None) if result_work_func is None or result_work_func.m_BotMessage is None: return result_work_func, result_work_func diff --git a/template/bd_item_add.py b/template/bd_item_add.py index 54c6960..e52ae4c 100644 --- a/template/bd_item_add.py +++ b/template/bd_item_add.py @@ -30,7 +30,7 @@ def StartAddBDItemTemplate(a_Bot, a_FSM, a_FSMStart, a_MessageFunc, a_ParentTabl if parent_id: check, res_of_work_func = await bd_item.CheckAccessBDItemTemplate(a_Bot, a_ParentTableName, a_ParentKeyFieldName, parent_id, a_MessageFunc, access_mode)(a_CallbackQuery) else: - res_of_work_func = await a_MessageFunc(a_CallbackQuery, None) + res_of_work_func = await a_MessageFunc(a_CallbackQuery, None, item_data) if not check is None: await state.finish() @@ -68,7 +68,7 @@ def FinishOrNextAddBDItemTemplate(a_Bot, a_FSM, a_AddBDItemFunc, a_ParentTableNa if parent_id: check, res_of_work_func = await bd_item.CheckAccessBDItemTemplate(a_Bot, a_ParentTableName, a_ParentKeyFieldName, parent_id, a_MessageFunc, access_mode)(a_Message) else: - res_of_work_func = await a_MessageFunc(a_Message, None) + res_of_work_func = await a_MessageFunc(a_Message, None, item_data) if not check is None: await state_func() diff --git a/template/docs_message.py b/template/docs_message.py new file mode 100644 index 0000000..9354644 --- /dev/null +++ b/template/docs_message.py @@ -0,0 +1,93 @@ +# -*- coding: utf8 -*- +# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) + +# Сообщения для работы с документами + +from bot_sys import log, config, user_access +from bot_modules import groups_utils +from template import simple_message +#import odf + +def DocFilesTemplate(a_Bot, a_FilesFunc, a_CaptionMessage, a_AccessFunc, a_GetButtonsFunc, a_GetInlineButtonsFunc, a_ErrorMessage, access_mode = user_access.AccessMode.EDIT): + async def DocFiles(a_Message): + user_id = str(a_Message.from_user.id) + user_groups= groups_utils.GetUserGroupData(a_Bot, user_id) + if not user_access.CheckAccess(a_Bot.GetRootIDs(), a_AccessFunc(), user_groups, access_mode): + return await simple_message.AccessDeniedMessage(a_Bot, a_GetButtonsFunc, user_id, a_Message, user_groups) + + msg = a_CaptionMessage.GetDesc() + msg = msg.replace('@time', a_Bot.GetLog().GetTime()) + + files = a_FilesFunc(user_id) + if not files: + await simple_message.SendMessage(a_Bot, a_ErrorMessage, a_GetButtonsFunc, None, user_id, a_Message, user_groups) + return + + for file_path, dict_replace in files.items(): + if not dict_replace: + continue + new_file = await MakeDocFile(a_Bot, file_path, dict_replace, user_id) + document = await GetFile(a_Bot, new_file) + if document is None: + await simple_message.SendMessage(a_Bot, a_ErrorMessage, a_GetButtonsFunc, None, user_id, a_Message, user_groups) + else: + await a_Bot.SendDocument( + user_id, + document, + msg, + simple_message.ProxyGetButtonsTemplate(a_GetButtonsFunc)(a_Message, user_groups), + simple_message.ProxyGetButtonsTemplate(a_GetInlineButtonsFunc)(a_Message, user_groups) + ) + return DocFiles + +async def ReplaceInFile(a_Bot, a_InputFileName, a_OutFileName, a_DictReplace): + try: + filedata = '' + + with open(a_InputFileName, 'r') as in_f: + filedata = in_f.read() + s = filedata + + for rep_this, to_this in a_DictReplace.items(): + s = s.replace(rep_this, to_this) + + with open(a_OutFileName, 'w') as out_f: + out_f.write(s) + a_Bot.GetLog().Success(f'Создан файл {a_OutFileName}') + return a_OutFileName + except Exception as e: + a_Bot.GetLog().Error(f'Не удалось заменить текст в фале {a_InputFileName} и записать в {a_OutFileName}. Ошибка {str(e)}') + return None + +from weasyprint import HTML, CSS + +async def SaveAsPdf(a_Bot, a_InputFileName, a_OutFileName): + try: + HTML(filename = a_InputFileName).write_pdf(a_OutFileName) + a_Bot.GetLog().Success(f'Создан файл {a_OutFileName}') + return a_OutFileName + except Exception as e: + a_Bot.GetLog().Error(f'Не удалось создать пдф из фала {a_InputFileName} и записать в {a_OutFileName}. Ошибка {str(e)}') + return None + +async def MakeDocFile(a_Bot, a_FilePath, a_DictReplace, a_user_id): + user_file_path = a_FilePath[:-5] + pdf_file_path = user_file_path + user_file_path += f"_{a_user_id}.html" + pdf_file_path += f"_{a_user_id}.pdf" + user_file_path = await ReplaceInFile(a_Bot, a_FilePath, user_file_path, a_DictReplace) + if not user_file_path: + return None + + return await SaveAsPdf(a_Bot, user_file_path, pdf_file_path) + +async def GetFile(a_Bot, a_Path): + if not a_Path: + return None + try: + document = open(a_Path, 'rb') + a_Bot.GetLog().Success(f'Загружен файл {a_Path}') + return document + except Exception as e: + a_Bot.GetLog().Error(f'Не удалось загрузить файл {a_Path}. Ошибка {str(e)}') + return None diff --git a/template/file_message.py b/template/file_message.py index fe7e6a7..0159aa3 100644 --- a/template/file_message.py +++ b/template/file_message.py @@ -16,7 +16,7 @@ def BackupFileTemplate(a_Bot, a_Path, a_CaptionMessage, a_AccessFunc, a_GetButto document = await GetFile(a_Bot, a_Path) if document is None: - return simple_message.SendMessage(a_Bot, a_ErrorMessage, a_GetButtonsFunc, None, user_id, a_Message, user_groups) + return await simple_message.SendMessage(a_Bot, a_ErrorMessage, a_GetButtonsFunc, None, user_id, a_Message, user_groups) msg = a_CaptionMessage.GetDesc() msg = msg.replace('@time', a_Bot.GetLog().GetTime())