Skip to content

Commit 9cc0978

Browse files
committed
refactor: Clean up AdminsManager and FeatureManager, streamline admin rights handling and database schema management
1 parent 0128cce commit 9cc0978

6 files changed

Lines changed: 67 additions & 84 deletions

File tree

bot/core/admin_rights_manager.py

Lines changed: 8 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -10,35 +10,20 @@
1010

1111

1212
class AdminsManager:
13-
"""
14-
Telegram botida administratorlarni va ularning huquqlarini boshqarish uchun klass.
15-
Redis va MySQL ma'lumotlar bazalaridan foydalanadi.
16-
"""
1713

1814
def __init__(self, db: Database,
1915
redis_client: Redis,
2016
root_logger: logging.Logger,
2117
redis_namespace: str = "admin_setting"):
22-
"""
23-
Klass konstruktori
24-
25-
Args:
26-
db: MySQL bilan ishlash uchun abstraksiya obyekti
27-
redis_client: Redis bilan muloqot qiluvchi obyekt
28-
root_logger: Loyihaviy loglar uchun logger
29-
redis_namespace: Redis kalitlari prefiksi
30-
"""
3118
self.db = db
3219
self.redis = redis_client
3320
self.logger = root_logger
3421
self.ns = redis_namespace
3522
self.now = datetime.now()
3623

37-
# Kerakli jadvallarni yaratish
3824
self._create_tables()
3925

4026
def _create_tables(self):
41-
"""Ma'lumotlar bazasida kerakli jadvallarni yaratish"""
4227
tables = [
4328
"""
4429
CREATE TABLE IF NOT EXISTS `admins` (
@@ -111,6 +96,10 @@ def __call__(self, user_id: int, feature: str, return_initiator: bool = False) -
11196
(is_active, initiator_user_id) yoki (is_active,) yoki (None, None)
11297
"""
11398
try:
99+
100+
if not isinstance(user_id, int) or not isinstance(feature, str) :
101+
return None, None if return_initiator else None
102+
114103
if user_id == ADMIN:
115104
return True, None if return_initiator else True
116105

@@ -133,18 +122,19 @@ def __call__(self, user_id: int, feature: str, return_initiator: bool = False) -
133122

134123
if not feature_active:
135124
return None, None if return_initiator else None
136-
137-
# Redis dan qidirish
125+
138126
redis_key = f"{self.ns}:admin_rights:{user_id}:{feature}"
139127
cached_data = self.redis.get(redis_key)
140128

141129
if cached_data:
142130
data = json.loads(cached_data)
131+
132+
143133
if return_initiator:
144134
return data.get('value', False), data.get('initiator_user_id')
135+
145136
return data.get('value', False)
146137

147-
# MySQL dan qidirish
148138
query = """
149139
SELECT ar.value, ar.initiator_user_id
150140
FROM admin_rights ar
@@ -160,7 +150,6 @@ def __call__(self, user_id: int, feature: str, return_initiator: bool = False) -
160150
result = self.db.cursor.fetchone()
161151

162152
if result:
163-
# Redis ga saqlash
164153
cache_data = {
165154
'value': result['value'],
166155
'initiator_user_id': result['initiator_user_id']
@@ -228,23 +217,11 @@ def __getitem__(self, user_id: int) -> Tuple[Optional[bool], Optional[int], Opti
228217
return None, None, None, None
229218

230219
def update(self, user_id: int, feature: str, value: bool, initiator_user_id: int) -> None:
231-
"""
232-
Admin huquqini yangilash yoki yaratish
233-
234-
Args:
235-
user_id: Yangilanayotgan admin telegram user ID
236-
feature: Yangilanayotgan xususiyat
237-
value: Huquq qiymati
238-
initiator_user_id: Huquq berayotgan admin telegram user ID
239-
"""
240220
try:
241-
# Admin ekanligini tekshirish
242221
is_admin, _, _, _ = self.__getitem__(user_id)
243222
if not is_admin:
244223
self.logger.warning(f"User {user_id} admin emas")
245224
return
246-
247-
# Rights mavjudligini tekshirish
248225
rights_query = "SELECT id FROM rights WHERE `key` = %s AND is_active = TRUE AND deleted_at IS NULL"
249226
self.db.cursor.execute(rights_query, (feature,))
250227
right_result = self.db.cursor.fetchone()

bot/core/feature_manager.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def feature(self, name: str) -> bool:
3939
def upsert_feature(self, name: str, enabled: bool) -> None:
4040
try:
4141
sql = """
42-
INSERT INTO features (name, enabled)
42+
INSERT INTO `features` (name, enabled)
4343
VALUES (%s, %s)
4444
ON DUPLICATE KEY UPDATE
4545
enabled = VALUES(enabled),
@@ -83,13 +83,13 @@ def _create_table_features(self):
8383
try:
8484
self.db.cursor.execute(
8585
"""
86-
CREATE TABLE IF NOT EXISTS features (
87-
id INT AUTO_INCREMENT PRIMARY KEY,
88-
name VARCHAR(255) NOT NULL UNIQUE,
89-
enabled TINYINT(1) NOT NULL DEFAULT 0,
90-
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
91-
deleted_at TIMESTAMP DEFAULT NULL,
92-
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
86+
CREATE TABLE IF NOT EXISTS `features` (
87+
`id` INT AUTO_INCREMENT PRIMARY KEY,
88+
`name` VARCHAR(255) NOT NULL UNIQUE,
89+
`enabled` TINYINT(1) NOT NULL DEFAULT 0,
90+
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
91+
`deleted_at` TIMESTAMP DEFAULT NULL,
92+
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
9393
)
9494
"""
9595
)

bot/db/database.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,6 @@ def update_user_status(self, user_id, status, updater_user_id):
184184
self.root_logger.error(err)
185185

186186
## ------------------ Select ------------------ ##
187-
188-
189187
def select_all_users_ban(self):
190188
"""
191189
Select all banned users from the 'users' table.
@@ -322,6 +320,12 @@ def stat(self):
322320

323321

324322

323+
def nuke_schema(self):
324+
tables = ['admins', 'admin_rights', 'channels', 'features', 'log_history', 'rights', 'settings', 'texts', 'translations', 'users']
325+
self.cursor.execute("SET FOREIGN_KEY_CHECKS = 0;")
326+
for t in tables:
327+
self.cursor.execute(f"DROP TABLE IF EXISTS `{t}`;")
328+
self.cursor.execute("SET FOREIGN_KEY_CHECKS = 1;")
325329

326330

327331

bot/handlers/admins/admin_settings/edit_admin.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ async def edit_admin(call: types.CallbackQuery, callback_data: EditAdminSetting,
3333
text = f'🔪 @{admin_info.username} {translator(text="✅ Removed from admin!", dest=language_code)}'
3434
await bot.send_message(chat_id=target_user_id, text='😪 Your admin rights have been revoked!')
3535
else:
36-
feature = AM(user_id=edit_key, feature=edit_key)
36+
feature = AM(user_id=target_user_id, feature=edit_key)
37+
# root_logger.info(feature)
3738
value = False if feature else True
3839
AM.update(user_id=target_user_id, feature=edit_key, value=value, initiator_user_id=user_id)
3940

bot/keyboards/inline/admin_btn.py

Lines changed: 41 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -57,46 +57,46 @@ async def admin_setting(user_id, language_code):
5757
root_logger.error(err)
5858
return False
5959

60-
def attach_admin(user_id, language_code):
61-
try:
62-
btn = InlineKeyboardBuilder()
63-
btn.attach(InlineKeyboardBuilder.from_markup(main_btn()))
64-
send_message_tx = x_or_y(AM('send_message', user_id))
65-
wiew_statistika_tx = x_or_y(AM('view_statistika', user_id))
66-
download_statistika_tx = x_or_y(AM('download_statistika', user_id))
67-
block_user_tx = x_or_y(AM('block_user', user_id))
68-
channel_settings_tx = x_or_y(AM('channel_settings', user_id))
69-
add_admin_tx = x_or_y(AM('add_admin', user_id))
70-
btn.button(text=translator(text=f"{send_message_tx} Send a message!",
71-
dest=language_code),
72-
callback_data=EditAdminSetting(action="edit", user_id=user_id, data='send_message').pack())
73-
74-
btn.button(text=translator(text=f"{wiew_statistika_tx} Wiew statistics!",
75-
dest=language_code),
76-
callback_data=EditAdminSetting(action="edit", user_id=user_id, data='statistika').pack())
77-
78-
btn.button(text=translator(text=f"{download_statistika_tx} Download statistics!",
79-
dest=language_code),
80-
callback_data=EditAdminSetting(action="edit", user_id=user_id, data='download_statistika').pack())
81-
82-
btn.button(text=translator(text=f"{block_user_tx} Block user!",
83-
dest=language_code),
84-
callback_data=EditAdminSetting(action="edit", user_id=user_id, data='block_user').pack())
85-
btn.button(text=translator(text=f"{channel_settings_tx} Channel settings!",
86-
dest=language_code),
87-
callback_data=EditAdminSetting(action="edit", user_id=user_id, data='channel_settings').pack())
88-
btn.button(text=translator(text=f"{add_admin_tx} Add a admin!",
89-
dest=language_code),
90-
callback_data=EditAdminSetting(action="edit", user_id=user_id, data='add_admin').pack())
91-
btn.button(text=translator(text=f"🔪Delete admin!",
92-
dest=language_code),
93-
callback_data=EditAdminSetting(action="edit", user_id=user_id, data='delete_admin').pack())
94-
btn.adjust(1)
95-
btn.attach(InlineKeyboardBuilder.from_markup(close_btn()))
96-
return btn.as_markup()
97-
except Exception as err:
98-
root_logger.error(err)
99-
return False
60+
# def attach_admin(user_id, language_code):
61+
# try:
62+
# btn = InlineKeyboardBuilder()
63+
# btn.attach(InlineKeyboardBuilder.from_markup(main_btn()))
64+
# send_message_tx = x_or_y(AM('send_message', user_id))
65+
# wiew_statistika_tx = x_or_y(AM('view_statistika', user_id))
66+
# download_statistika_tx = x_or_y(AM('download_statistika', user_id))
67+
# block_user_tx = x_or_y(AM('block_user', user_id))
68+
# channel_settings_tx = x_or_y(AM('channel_settings', user_id))
69+
# add_admin_tx = x_or_y(AM('add_admin', user_id))
70+
# btn.button(text=translator(text=f"{send_message_tx} Send a message!",
71+
# dest=language_code),
72+
# callback_data=EditAdminSetting(action="edit", user_id=user_id, data='send_message').pack())
73+
74+
# btn.button(text=translator(text=f"{wiew_statistika_tx} Wiew statistics!",
75+
# dest=language_code),
76+
# callback_data=EditAdminSetting(action="edit", user_id=user_id, data='statistika').pack())
77+
78+
# btn.button(text=translator(text=f"{download_statistika_tx} Download statistics!",
79+
# dest=language_code),
80+
# callback_data=EditAdminSetting(action="edit", user_id=user_id, data='download_statistika').pack())
81+
82+
# btn.button(text=translator(text=f"{block_user_tx} Block user!",
83+
# dest=language_code),
84+
# callback_data=EditAdminSetting(action="edit", user_id=user_id, data='block_user').pack())
85+
# btn.button(text=translator(text=f"{channel_settings_tx} Channel settings!",
86+
# dest=language_code),
87+
# callback_data=EditAdminSetting(action="edit", user_id=user_id, data='channel_settings').pack())
88+
# btn.button(text=translator(text=f"{add_admin_tx} Add a admin!",
89+
# dest=language_code),
90+
# callback_data=EditAdminSetting(action="edit", user_id=user_id, data='add_admin').pack())
91+
# btn.button(text=translator(text=f"🔪Delete admin!",
92+
# dest=language_code),
93+
# callback_data=EditAdminSetting(action="edit", user_id=user_id, data='delete_admin').pack())
94+
# btn.adjust(1)
95+
# btn.attach(InlineKeyboardBuilder.from_markup(close_btn()))
96+
# return btn.as_markup()
97+
# except Exception as err:
98+
# root_logger.error(err)
99+
# return False
100100

101101
def attach_admin_btn(user_id, language_code):
102102
try:
@@ -105,7 +105,7 @@ def attach_admin_btn(user_id, language_code):
105105

106106
rights = AM.list_features()
107107
for right in rights:
108-
check = AM.__call__(user_id=user_id, feature=right['key'])
108+
check = AM(user_id=user_id, feature=right['key'])
109109
text = x_or_y(check) + ' ' + translator(text=right['name'],
110110
dest=language_code)
111111

bot/main.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ async def main():
1212
await set_default_commands()
1313

1414
try:
15-
15+
16+
1617
admin_rights = [
1718
('admin_settings', '👮‍♂️ Admins settings!', 'Yangi adminlar qo\'shish imkoniyati.'),
1819
('add_rights', '✳️ Add rights.', 'Adminlar uchun qushimcha huqqu qushish.'),

0 commit comments

Comments
 (0)