azils3 commited on
Commit
e60c4ed
·
verified ·
1 Parent(s): 57b6dd6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +586 -471
app.py CHANGED
@@ -1,501 +1,616 @@
1
- # app.py
2
- from flask import Flask, render_template, jsonify, request
 
 
 
 
 
 
3
  from pyrogram import Client
 
4
  import os
5
  import psutil
6
- import time
7
- import shutil
8
  import asyncio
9
- from utils import get_settings, save_group_settings, get_size, humanbytes, get_time, admin_check
10
- from database.users_chats_db import db
11
- from database.ia_filterdb import Media, get_search_results, get_file_details, save_file
12
- from database.filters_mdb import add_filter, get_filters, delete_filter, del_all
13
- from database.gfilters_mdb import add_gfilter, get_gfilters, delete_gfilter, del_allg
14
- from database.connections_mdb import add_connection, all_connections, if_active, delete_connection, make_active, make_inactive
15
- from info import ADMINS, LOG_CHANNEL, CHANNELS, DATABASE_URL, DATABASE_NAME, CACHE_TIME, API_ID, API_HASH, BOT_TOKEN, UPTIME, WEB_SUPPORT, LOG_MSG
16
- from pymongo import MongoClient
17
 
18
  app = Flask(__name__)
 
19
 
20
  # Initialize Pyrogram Client
21
  bot = Client(
22
  name="Professor-Bot",
23
- api_id=API_ID,
24
- api_hash=API_HASH,
25
- bot_token=BOT_TOKEN,
26
- plugins=dict(root="plugins")
27
  )
28
 
29
- # Initialize MongoDB Client
30
- mongo_client = MongoClient(DATABASE_URL)
31
- mongo_db = mongo_client[DATABASE_NAME]
32
-
33
  @app.route('/')
34
- def dashboard():
35
- return render_template('dashboard.html')
36
-
37
- @app.route('/api/system-info')
38
- def system_info():
39
- uptime = time.time() - UPTIME
40
- uptime_str = get_time(uptime)
41
- storage = shutil.disk_usage("/")
42
- return jsonify({
43
- "os": {
44
- "name": os.name,
45
- "version": os.uname().version
46
- },
47
- "uptime": uptime_str,
48
- "storage": {
49
- "total": storage.total,
50
- "free": storage.free
51
- }
52
- })
53
-
54
- @app.route('/api/bot-stats')
55
- def bot_stats():
56
- loop = asyncio.get_event_loop()
57
- total_files = loop.run_until_complete(Media.count_documents())
58
- total_users = loop.run_until_complete(db.total_users_count())
59
- total_chats = loop.run_until_complete(db.total_chat_count())
60
- monsize = loop.run_until_complete(db.get_db_size())
61
- free = 536870912 - monsize
62
- monsize = get_size(monsize)
63
- free = get_size(free)
64
- return jsonify({
65
- "total_files": total_files,
66
- "total_users": total_users,
67
- "total_chats": total_chats,
68
- "storage_used": monsize,
69
- "storage_free": free
70
- })
71
-
72
- @app.route('/api/filters')
73
- def get_filters_api():
74
- chat_id = request.args.get('chat_id')
75
- if not chat_id:
76
- return jsonify({"error": "Chat ID is required"}), 400
77
- loop = asyncio.get_event_loop()
78
- filters = loop.run_until_complete(get_filters(chat_id))
79
- return jsonify({"filters": filters})
80
-
81
- @app.route('/api/add-filter', methods=['POST'])
82
- def add_filter_api():
83
- chat_id = request.form.get('chat_id')
84
- text = request.form.get('text')
85
- reply_text = request.form.get('reply_text')
86
- btn = request.form.get('btn')
87
- file = request.form.get('file')
88
- alert = request.form.get('alert')
89
- if not chat_id or not text or not reply_text:
90
- return jsonify({"error": "Chat ID, text, and reply text are required"}), 400
91
- loop = asyncio.get_event_loop()
92
- loop.run_until_complete(add_filter(chat_id, text, reply_text, btn, file, alert))
93
- return jsonify({"message": "Filter added successfully"})
94
-
95
- @app.route('/api/delete-filter', methods=['POST'])
96
- def delete_filter_api():
97
- chat_id = request.form.get('chat_id')
98
- text = request.form.get('text')
99
- if not chat_id or not text:
100
- return jsonify({"error": "Chat ID and text are required"}), 400
101
- loop = asyncio.get_event_loop()
102
- loop.run_until_complete(delete_filter(request, text, chat_id))
103
- return jsonify({"message": "Filter deleted successfully"})
104
-
105
- @app.route('/api/gfilters')
106
- def get_gfilters_api():
107
- gfilters = 'gfilters'
108
- loop = asyncio.get_event_loop()
109
- filters = loop.run_until_complete(get_gfilters(gfilters))
110
- return jsonify({"filters": filters})
111
-
112
- @app.route('/api/add-gfilter', methods=['POST'])
113
- def add_gfilter_api():
114
- gfilters = 'gfilters'
115
- text = request.form.get('text')
116
- reply_text = request.form.get('reply_text')
117
- btn = request.form.get('btn')
118
- file = request.form.get('file')
119
- alert = request.form.get('alert')
120
- if not text or not reply_text:
121
- return jsonify({"error": "Text and reply text are required"}), 400
122
- loop = asyncio.get_event_loop()
123
- loop.run_until_complete(add_gfilter(gfilters, text, reply_text, btn, file, alert))
124
- return jsonify({"message": "Global filter added successfully"})
125
-
126
- @app.route('/api/delete-gfilter', methods=['POST'])
127
- def delete_gfilter_api():
128
- gfilters = 'gfilters'
129
- text = request.form.get('text')
130
- if not text:
131
- return jsonify({"error": "Text is required"}), 400
132
- loop = asyncio.get_event_loop()
133
- loop.run_until_complete(delete_gfilter(request, text, gfilters))
134
- return jsonify({"message": "Global filter deleted successfully"})
135
-
136
- @app.route('/api/users')
137
- def get_users_api():
138
- loop = asyncio.get_event_loop()
139
- users = loop.run_until_complete(db.get_all_users())
140
  user_list = []
141
- loop.run_until_complete(asyncio.gather(*(user_list.append({
142
- "id": user['id'],
143
- "name": user['name'],
144
- "ban_status": user['ban_status']
145
- }) for user in users)))
146
- return jsonify({"users": user_list})
147
-
148
- @app.route('/api/chats')
149
- def get_chats_api():
150
- loop = asyncio.get_event_loop()
151
- chats = loop.run_until_complete(db.get_all_chats())
 
 
 
 
 
152
  chat_list = []
153
- loop.run_until_complete(asyncio.gather(*(chat_list.append({
154
- "id": chat['id'],
155
- "title": chat['title'],
156
- "username": chat['username'],
157
- "chat_status": chat['chat_status']
158
- }) for chat in chats)))
159
- return jsonify({"chats": chat_list})
160
-
161
- @app.route('/api/files')
162
- def get_files_api():
163
- loop = asyncio.get_event_loop()
164
- files = loop.run_until_complete(Media.find().to_list(None))
165
- file_list = []
166
- for file in files:
167
- file_list.append({
168
- "file_id": file['file_id'],
169
- "file_name": file['file_name'],
170
- "file_size": file['file_size'],
171
- "file_type": file['file_type'],
172
- "mime_type": file['mime_type'],
173
- "caption": file['caption']
174
  })
175
- return jsonify({"files": file_list})
176
-
177
- @app.route('/api/add-file', methods=['POST'])
178
- def add_file_api():
179
- if 'fileUpload' not in request.files:
180
- return jsonify({"error": "No file part"}), 400
181
- file = request.files['fileUpload']
182
- if file.filename == '':
183
- return jsonify({"error": "No selected file"}), 400
184
- if file:
185
- file_path = os.path.join("/app/uploads", file.filename)
186
- file.save(file_path)
187
- loop = asyncio.get_event_loop()
188
- file_id, file_ref = loop.run_until_complete(save_file(file_path))
189
- os.remove(file_path)
190
- return jsonify({"file_id": file_id, "file_ref": file_ref, "message": "File uploaded successfully"})
191
- return jsonify({"error": "Failed to upload file"}), 500
192
-
193
- @app.route('/api/delete-file', methods=['POST'])
194
- def delete_file_api():
195
- file_id = request.form.get('file_id')
196
- if not file_id:
197
- return jsonify({"error": "File ID is required"}), 400
198
- loop = asyncio.get_event_loop()
199
- result = loop.run_until_complete(Media.collection.delete_one({'_id': file_id}))
200
- if result.deleted_count:
201
- return jsonify({"message": "File deleted successfully"})
202
- else:
203
- return jsonify({"error": "File not found"}), 404
204
-
205
- @app.route('/api/settings/<chat_id>')
206
- def get_settings_api(chat_id):
207
- loop = asyncio.get_event_loop()
208
- settings = loop.run_until_complete(get_settings(chat_id))
209
- return jsonify({"settings": settings})
210
-
211
- @app.route('/api/save-settings', methods=['POST'])
212
- def save_settings_api():
213
- chat_id = request.form.get('chat_id')
214
- setting_key = request.form.get('setting_key')
215
- setting_value = request.form.get('setting_value')
216
- if not chat_id or not setting_key or not setting_value:
217
- return jsonify({"error": "Chat ID, setting key, and setting value are required"}), 400
218
- loop = asyncio.get_event_loop()
219
- loop.run_until_complete(save_group_settings(chat_id, setting_key, setting_value))
220
- return jsonify({"message": "Settings saved successfully"})
221
-
222
- @app.route('/api/ban-user', methods=['POST'])
223
- def ban_user_api():
224
  user_id = request.form.get('user_id')
225
- ban_reason = request.form.get('ban_reason', "No Reason")
226
- if not user_id:
227
- return jsonify({"error": "User ID is required"}), 400
228
- loop = asyncio.get_event_loop()
229
- loop.run_until_complete(db.ban_user(int(user_id), ban_reason))
230
- temp.BANNED_USERS.append(int(user_id))
231
- return jsonify({"message": "User banned successfully"})
232
-
233
- @app.route('/api/unban-user', methods=['POST'])
234
- def unban_user_api():
 
 
 
 
 
 
 
 
 
 
 
 
235
  user_id = request.form.get('user_id')
236
- if not user_id:
237
- return jsonify({"error": "User ID is required"}), 400
238
- loop = asyncio.get_event_loop()
239
- loop.run_until_complete(db.remove_ban(int(user_id)))
240
- temp.BANNED_USERS.remove(int(user_id))
241
- return jsonify({"message": "User unbanned successfully"})
242
-
243
- @app.route('/api/disable-chat', methods=['POST'])
244
- def disable_chat_api():
 
 
 
 
 
 
 
 
 
 
 
 
245
  chat_id = request.form.get('chat_id')
246
- reason = request.form.get('reason', "No Reason")
247
- if not chat_id:
248
- return jsonify({"error": "Chat ID is required"}), 400
249
- loop = asyncio.get_event_loop()
250
- loop.run_until_complete(db.disable_chat(int(chat_id), reason))
251
- temp.BANNED_CHATS.append(int(chat_id))
252
- return jsonify({"message": "Chat disabled successfully"})
253
-
254
- @app.route('/api/enable-chat', methods=['POST'])
255
- def enable_chat_api():
 
 
 
 
 
 
 
 
 
 
 
 
256
  chat_id = request.form.get('chat_id')
257
- if not chat_id:
258
- return jsonify({"error": "Chat ID is required"}), 400
259
- loop = asyncio.get_event_loop()
260
- loop.run_until_complete(db.re_enable_chat(int(chat_id)))
261
- temp.BANNED_CHATS.remove(int(chat_id))
262
- return jsonify({"message": "Chat enabled successfully"})
263
-
264
- @app.route('/api/upload-file', methods=['POST'])
265
- def upload_file_api():
266
- if 'fileUpload' not in request.files:
267
- return jsonify({"error": "No file part"}), 400
268
- file = request.files['fileUpload']
269
- if file.filename == '':
270
- return jsonify({"error": "No selected file"}), 400
271
- if file:
272
- file_path = os.path.join("/app/uploads", file.filename)
273
- file.save(file_path)
274
- loop = asyncio.get_event_loop()
275
- file_id, file_ref = loop.run_until_complete(save_file(file_path))
276
- os.remove(file_path)
277
- return jsonify({"file_id": file_id, "file_ref": file_ref, "message": "File uploaded successfully"})
278
- return jsonify({"error": "Failed to upload file"}), 500
279
-
280
- @app.route('/api/download-file/<file_id>')
281
- def download_file_api(file_id):
282
- loop = asyncio.get_event_loop()
283
- file_details = loop.run_until_complete(get_file_details(file_id))
284
- if not file_details:
285
- return jsonify({"error": "File not found"}), 404
286
- file = file_details[0]
287
- return jsonify({
288
- "file_name": file['file_name'],
289
- "file_size": file['file_size'],
290
- "file_type": file['file_type'],
291
- "mime_type": file['mime_type'],
292
- "caption": file['caption']
293
- })
294
-
295
- @app.route('/api/search-files', methods=['GET'])
296
- def search_files_api():
297
- query = request.args.get('query')
298
- file_type = request.args.get('file_type')
299
- if not query:
300
- return jsonify({"error": "Query is required"}), 400
301
- loop = asyncio.get_event_loop()
302
- files, next_offset, total = loop.run_until_complete(get_search_results(query, file_type=file_type))
303
- file_list = []
304
- for file in files:
305
- file_list.append({
306
- "file_id": file['file_id'],
307
- "file_name": file['file_name'],
308
- "file_size": file['file_size'],
309
- "file_type": file['file_type'],
310
- "mime_type": file['mime_type'],
311
- "caption": file['caption']
312
- })
313
- return jsonify({"files": file_list, "next_offset": next_offset, "total": total})
314
-
315
- @app.route('/api/broadcast', methods=['POST'])
316
- def broadcast_api():
317
- message_text = request.form.get('message_text')
318
- if not message_text:
319
- return jsonify({"error": "Message text is required"}), 400
320
- loop = asyncio.get_event_loop()
321
- users = loop.run_until_complete(db.get_all_users())
322
- total_users = loop.run_until_complete(db.total_users_count())
323
- done = 0
324
- blocked = 0
325
- deleted = 0
326
- failed = 0
327
- success = 0
328
-
329
- async def handle_user(user):
330
- nonlocal success, blocked, deleted, failed, done
331
- try:
332
- await bot.send_message(user['id'], message_text)
333
- success += 1
334
- except UserIsBlocked:
335
- blocked += 1
336
- except InputUserDeactivated:
337
- deleted += 1
338
- except Exception as e:
339
- failed += 1
340
- done += 1
341
-
342
- loop.run_until_complete(asyncio.gather(*(handle_user(user) for user in users)))
343
-
344
- return jsonify({
345
- "total_users": total_users,
346
- "completed": done,
347
- "success": success,
348
- "blocked": blocked,
349
- "deleted": deleted,
350
- "failed": failed
351
- })
352
-
353
- @app.route('/api/ban-users')
354
- def ban_users_api():
355
- loop = asyncio.get_event_loop()
356
- users = loop.run_until_complete(db.get_all_users())
357
- banned_users = []
358
- loop.run_until_complete(asyncio.gather(*(banned_users.append({
359
- "id": user['id'],
360
- "name": user['name'],
361
- "ban_reason": user['ban_status']['ban_reason']
362
- }) for user in users if user['ban_status']['is_banned'])))
363
- return jsonify({"banned_users": banned_users})
364
-
365
- @app.route('/api/banned-chats')
366
- def banned_chats_api():
367
- loop = asyncio.get_event_loop()
368
- chats = loop.run_until_complete(db.get_all_chats())
369
- banned_chats = []
370
- loop.run_until_complete(asyncio.gather(*(banned_chats.append({
371
- "id": chat['id'],
372
- "title": chat['title'],
373
- "username": chat['username'],
374
- "reason": chat['chat_status']['reason']
375
- }) for chat in chats if chat['chat_status']['is_disabled'])))
376
- return jsonify({"banned_chats": banned_chats})
377
-
378
- @app.route('/api/user-info/<user_id>')
379
- def user_info_api(user_id):
380
  try:
381
- loop = asyncio.get_event_loop()
382
- user = loop.run_until_complete(bot.get_users(int(user_id)))
383
- return jsonify({
384
- "first_name": user.first_name,
385
- "last_name": user.last_name,
386
- "username": user.username,
387
- "id": user.id,
388
- "dc_id": user.dc_id
389
- })
390
  except Exception as e:
391
- return jsonify({"error": str(e)}), 500
392
-
393
- @app.route('/api/chat-info/<chat_id>')
394
- def chat_info_api(chat_id):
 
 
 
 
 
 
 
 
 
 
 
 
395
  try:
396
- loop = asyncio.get_event_loop()
397
- chat = loop.run_until_complete(bot.get_chat(int(chat_id)))
398
- members_count = loop.run_until_complete(bot.get_chat_members_count(int(chat_id)))
399
- return jsonify({
400
- "title": chat.title,
401
- "username": chat.username,
402
- "id": chat.id,
403
- "members_count": members_count
404
- })
405
  except Exception as e:
406
- return jsonify({"error": str(e)}), 500
407
-
408
- @app.route('/api/restart-bot', methods=['POST'])
409
- def restart_bot_api():
 
 
 
 
 
 
 
410
  admin_id = request.form.get('admin_id')
411
- if not admin_id or int(admin_id) not in ADMINS:
412
- return jsonify({"error": "Unauthorized access"}), 401
413
- loop = asyncio.get_event_loop()
414
- loop.run_until_complete(bot.stop())
415
- loop.run_until_complete(bot.start())
416
- return jsonify({"message": "Bot restarted successfully"})
417
-
418
- @app.route('/api/add-connection', methods=['POST'])
419
- def add_connection_api():
420
- group_id = request.form.get('group_id')
421
- user_id = request.form.get('user_id')
422
- if not group_id or not user_id:
423
- return jsonify({"error": "Group ID and User ID are required"}), 400
424
- loop = asyncio.get_event_loop()
425
- result = loop.run_until_complete(add_connection(group_id, user_id))
426
- if result:
427
- return jsonify({"message": "Connection added successfully"})
428
- else:
429
- return jsonify({"error": "Connection already exists"}), 400
430
-
431
- @app.route('/api/delete-connection', methods=['POST'])
432
- def delete_connection_api():
433
- group_id = request.form.get('group_id')
434
- user_id = request.form.get('user_id')
435
- if not group_id or not user_id:
436
- return jsonify({"error": "Group ID and User ID are required"}), 400
437
- loop = asyncio.get_event_loop()
438
- result = loop.run_until_complete(delete_connection(user_id, group_id))
439
- if result:
440
- return jsonify({"message": "Connection deleted successfully"})
441
- else:
442
- return jsonify({"error": "Connection not found"}), 404
443
-
444
- @app.route('/api/group-stats')
445
- def group_stats_api():
446
  chat_id = request.args.get('chat_id')
447
- if not chat_id:
448
- return jsonify({"error": "Chat ID is required"}), 400
449
- loop = asyncio.get_event_loop()
450
- chat = loop.run_until_complete(db.get_chat(chat_id))
451
- if not chat:
452
- return jsonify({"error": "Chat not found"}), 404
453
- return jsonify({
454
- "chat_id": chat['id'],
455
- "title": chat['title'],
456
- "username": chat['username'],
457
- "chat_status": chat['chat_status']
458
- })
459
-
460
- @app.route('/api/bot-status')
461
- def bot_status():
462
- cpu_usage = psutil.cpu_percent()
463
- ram_usage = psutil.virtual_memory().percent
464
- total_storage, used_storage, free_storage = shutil.disk_usage("/")
465
- return jsonify({
466
- "cpu_usage": cpu_usage,
467
- "ram_usage": ram_usage,
468
- "total_storage": humanbytes(total_storage),
469
- "used_storage": humanbytes(used_storage),
470
- "free_storage": humanbytes(free_storage),
471
- "uptime": get_time(time.time() - UPTIME)
472
- })
473
-
474
- @app.route('/api/connections')
475
- def connections_api():
476
  user_id = request.args.get('user_id')
477
- if not user_id:
478
- return jsonify({"error": "User ID is required"}), 400
479
- loop = asyncio.get_event_loop()
480
- groupids = loop.run_until_complete(all_connections(str(user_id)))
481
- if groupids is None:
482
- return jsonify({"connections": []})
483
- connections = []
484
- for groupid in groupids:
485
- try:
486
- loop = asyncio.get_event_loop()
487
- ttl = loop.run_until_complete(bot.get_chat(int(groupid)))
488
- title = ttl.title
489
- active = loop.run_until_complete(if_active(str(user_id), str(groupid)))
490
- connections.append({
491
- "group_id": groupid,
492
- "title": title,
493
- "active": active
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
494
  })
495
- except Exception as e:
496
- print(f"Error fetching chat info: {e}")
497
- return jsonify({"connections": connections})
 
 
 
 
 
 
 
 
 
 
 
 
 
498
 
499
  if __name__ == '__main__':
500
- bot.run()
501
- app.run(host='0.0.0.0', port=7860, debug=False)
 
1
+ from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
2
+ from utils import temp, admin_check, get_size, get_time
3
+ from database.users_chats_db import db
4
+ from database.ia_filterdb import Media
5
+ from database.filters_mdb import get_filters, find_filter, delete_filter, del_all
6
+ from database.gfilters_mdb import get_gfilters, find_gfilter, delete_gfilter, del_allg
7
+ from database.connections_mdb import all_connections, delete_connection, add_connection, active_connection
8
+ from info import ADMINS, LOG_CHANNEL, SUPPORT_CHAT, WELCOM_PIC, WELCOM_TEXT, IMDB_TEMPLATE
9
  from pyrogram import Client
10
+ import logging
11
  import os
12
  import psutil
 
 
13
  import asyncio
14
+
15
+ logger = logging.getLogger(__name__)
16
+ logger.setLevel(logging.INFO)
 
 
 
 
 
17
 
18
  app = Flask(__name__)
19
+ app.secret_key = 'your_secret_key'
20
 
21
  # Initialize Pyrogram Client
22
  bot = Client(
23
  name="Professor-Bot",
24
+ api_id=temp.API_ID,
25
+ api_hash=temp.API_HASH,
26
+ bot_token=temp.BOT_TOKEN
 
27
  )
28
 
 
 
 
 
29
  @app.route('/')
30
+ def index():
31
+ """
32
+ Render the home page of the dashboard.
33
+ """
34
+ logger.info("Rendering home page.")
35
+ return render_template('index.html')
36
+
37
+ @app.route('/dashboard')
38
+ async def dashboard():
39
+ """
40
+ Render the dashboard page with statistics.
41
+ """
42
+ logger.info("Rendering dashboard page.")
43
+ await bot.start()
44
+ total_users = await db.total_users_count()
45
+ total_chats = await db.total_chat_count()
46
+ total_files = await Media.count_documents()
47
+ db_size = await db.get_db_size()
48
+ free_space = 536870912 - db_size
49
+ db_size = get_size(db_size)
50
+ free_space = get_size(free_space)
51
+ uptime = get_time(time.time() - bot.uptime)
52
+ cpu_usage = psutil.cpu_percent(interval=1)
53
+ ram_usage = psutil.virtual_memory().percent
54
+ logger.info(f"Dashboard statistics: Users: {total_users}, Chats: {total_chats}, Files: {total_files}, DB Size: {db_size}, Free Space: {free_space}, Uptime: {uptime}, CPU Usage: {cpu_usage}%, RAM Usage: {ram_usage}%.")
55
+ return render_template('dashboard.html',
56
+ total_users=total_users,
57
+ total_chats=total_chats,
58
+ total_files=total_files,
59
+ db_size=db_size,
60
+ free_space=free_space,
61
+ uptime=uptime,
62
+ cpu_usage=cpu_usage,
63
+ ram_usage=ram_usage)
64
+
65
+ @app.route('/users')
66
+ async def users():
67
+ """
68
+ Render the page with a list of all users.
69
+ """
70
+ logger.info("Rendering users page.")
71
+ users = await db.get_all_users()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  user_list = []
73
+ async for user in users:
74
+ user_list.append({
75
+ 'id': user['id'],
76
+ 'name': user['name'],
77
+ 'ban_status': user['ban_status']
78
+ })
79
+ logger.info(f"Users list retrieved: {len(user_list)} users.")
80
+ return render_template('users.html', users=user_list)
81
+
82
+ @app.route('/chats')
83
+ async def chats():
84
+ """
85
+ Render the page with a list of all chats.
86
+ """
87
+ logger.info("Rendering chats page.")
88
+ chats = await db.get_all_chats()
89
  chat_list = []
90
+ async for chat in chats:
91
+ chat_list.append({
92
+ 'id': chat['id'],
93
+ 'title': chat['title'],
94
+ 'username': chat['username'],
95
+ 'chat_status': chat['chat_status']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  })
97
+ logger.info(f"Chats list retrieved: {len(chat_list)} chats.")
98
+ return render_template('chats.html', chats=chat_list)
99
+
100
+ @app.route('/logs')
101
+ def logs():
102
+ """
103
+ Render the page with bot logs.
104
+ """
105
+ logger.info("Rendering logs page.")
106
+ try:
107
+ with open('BotLog.txt', 'r') as file:
108
+ logs = file.readlines()
109
+ logger.info("Logs file read successfully.")
110
+ return render_template('logs.html', logs=logs)
111
+ except Exception as e:
112
+ logger.error(f"Error reading logs file: {e}")
113
+ flash("Error reading logs file.")
114
+ return redirect(url_for('index'))
115
+
116
+ @app.route('/admin_panel')
117
+ async def admin_panel():
118
+ """
119
+ Render the admin panel page.
120
+ """
121
+ logger.info("Rendering admin panel page.")
122
+ user_id = request.args.get('user_id')
123
+ if not user_id or not await admin_check(int(user_id)):
124
+ logger.info("User is not an admin, redirecting to index.")
125
+ flash("You are not authorized to access the admin panel.")
126
+ return redirect(url_for('index'))
127
+ logger.info("User is authorized to access the admin panel.")
128
+ return render_template('admin_panel.html', user_id=user_id)
129
+
130
+ @app.route('/ban_user', methods=['POST'])
131
+ async def ban_user():
132
+ """
133
+ Ban a user via the admin panel.
134
+ """
135
+ logger.info("Ban user request received.")
 
 
 
 
 
 
 
 
 
 
136
  user_id = request.form.get('user_id')
137
+ ban_reason = request.form.get('ban_reason', "No Reason Provided")
138
+ admin_id = request.form.get('admin_id')
139
+ if not admin_id or not await admin_check(int(admin_id)):
140
+ logger.info("Admin check failed for banning user.")
141
+ flash("You are not authorized to ban users.")
142
+ return redirect(url_for('admin_panel', user_id=admin_id))
143
+ try:
144
+ await db.ban_user(user_id, ban_reason)
145
+ temp.BANNED_USERS.append(int(user_id))
146
+ logger.info(f"User {user_id} banned successfully with reason: {ban_reason}.")
147
+ flash("User banned successfully.")
148
+ except Exception as e:
149
+ logger.error(f"Error banning user {user_id}: {e}")
150
+ flash("Error banning user.")
151
+ return redirect(url_for('admin_panel', user_id=admin_id))
152
+
153
+ @app.route('/unban_user', methods=['POST'])
154
+ async def unban_user():
155
+ """
156
+ Unban a user via the admin panel.
157
+ """
158
+ logger.info("Unban user request received.")
159
  user_id = request.form.get('user_id')
160
+ admin_id = request.form.get('admin_id')
161
+ if not admin_id or not await admin_check(int(admin_id)):
162
+ logger.info("Admin check failed for unbanning user.")
163
+ flash("You are not authorized to unban users.")
164
+ return redirect(url_for('admin_panel', user_id=admin_id))
165
+ try:
166
+ await db.remove_ban(user_id)
167
+ temp.BANNED_USERS.remove(int(user_id))
168
+ logger.info(f"User {user_id} unbanned successfully.")
169
+ flash("User unbanned successfully.")
170
+ except Exception as e:
171
+ logger.error(f"Error unbanning user {user_id}: {e}")
172
+ flash("Error unbanning user.")
173
+ return redirect(url_for('admin_panel', user_id=admin_id))
174
+
175
+ @app.route('/disable_chat', methods=['POST'])
176
+ async def disable_chat():
177
+ """
178
+ Disable a chat via the admin panel.
179
+ """
180
+ logger.info("Disable chat request received.")
181
  chat_id = request.form.get('chat_id')
182
+ reason = request.form.get('reason', "No Reason Provided")
183
+ admin_id = request.form.get('admin_id')
184
+ if not admin_id or not await admin_check(int(admin_id)):
185
+ logger.info("Admin check failed for disabling chat.")
186
+ flash("You are not authorized to disable chats.")
187
+ return redirect(url_for('admin_panel', user_id=admin_id))
188
+ try:
189
+ await db.disable_chat(chat_id, reason)
190
+ temp.BANNED_CHATS.append(int(chat_id))
191
+ logger.info(f"Chat {chat_id} disabled successfully with reason: {reason}.")
192
+ flash("Chat disabled successfully.")
193
+ except Exception as e:
194
+ logger.error(f"Error disabling chat {chat_id}: {e}")
195
+ flash("Error disabling chat.")
196
+ return redirect(url_for('admin_panel', user_id=admin_id))
197
+
198
+ @app.route('/enable_chat', methods=['POST'])
199
+ async def enable_chat():
200
+ """
201
+ Enable a chat via the admin panel.
202
+ """
203
+ logger.info("Enable chat request received.")
204
  chat_id = request.form.get('chat_id')
205
+ admin_id = request.form.get('admin_id')
206
+ if not admin_id or not await admin_check(int(admin_id)):
207
+ logger.info("Admin check failed for enabling chat.")
208
+ flash("You are not authorized to enable chats.")
209
+ return redirect(url_for('admin_panel', user_id=admin_id))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  try:
211
+ await db.re_enable_chat(chat_id)
212
+ temp.BANNED_CHATS.remove(int(chat_id))
213
+ logger.info(f"Chat {chat_id} enabled successfully.")
214
+ flash("Chat enabled successfully.")
 
 
 
 
 
215
  except Exception as e:
216
+ logger.error(f"Error enabling chat {chat_id}: {e}")
217
+ flash("Error enabling chat.")
218
+ return redirect(url_for('admin_panel', user_id=admin_id))
219
+
220
+ @app.route('/delete_user', methods=['POST'])
221
+ async def delete_user():
222
+ """
223
+ Delete a user from the database via the admin panel.
224
+ """
225
+ logger.info("Delete user request received.")
226
+ user_id = request.form.get('user_id')
227
+ admin_id = request.form.get('admin_id')
228
+ if not admin_id or not await admin_check(int(admin_id)):
229
+ logger.info("Admin check failed for deleting user.")
230
+ flash("You are not authorized to delete users.")
231
+ return redirect(url_for('admin_panel', user_id=admin_id))
232
  try:
233
+ await db.delete_user(user_id)
234
+ logger.info(f"User {user_id} deleted successfully.")
235
+ flash("User deleted successfully.")
 
 
 
 
 
 
236
  except Exception as e:
237
+ logger.error(f"Error deleting user {user_id}: {e}")
238
+ flash("Error deleting user.")
239
+ return redirect(url_for('admin_panel', user_id=admin_id))
240
+
241
+ @app.route('/delete_chat', methods=['POST'])
242
+ async def delete_chat():
243
+ """
244
+ Delete a chat from the database via the admin panel.
245
+ """
246
+ logger.info("Delete chat request received.")
247
+ chat_id = request.form.get('chat_id')
248
  admin_id = request.form.get('admin_id')
249
+ if not admin_id or not await admin_check(int(admin_id)):
250
+ logger.info("Admin check failed for deleting chat.")
251
+ flash("You are not authorized to delete chats.")
252
+ return redirect(url_for('admin_panel', user_id=admin_id))
253
+ try:
254
+ await db.delete_chat(chat_id)
255
+ logger.info(f"Chat {chat_id} deleted successfully.")
256
+ flash("Chat deleted successfully.")
257
+ except Exception as e:
258
+ logger.error(f"Error deleting chat {chat_id}: {e}")
259
+ flash("Error deleting chat.")
260
+ return redirect(url_for('admin_panel', user_id=admin_id))
261
+
262
+ @app.route('/filters')
263
+ async def filters():
264
+ """
265
+ Render the page with a list of all filters.
266
+ """
267
+ logger.info("Rendering filters page.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  chat_id = request.args.get('chat_id')
269
+ if not chat_id or not await admin_check(int(request.args.get('admin_id'))):
270
+ logger.info("User is not an admin, redirecting to index.")
271
+ flash("You are not authorized to view filters.")
272
+ return redirect(url_for('index'))
273
+ filters_list = await get_filters(chat_id)
274
+ logger.info(f"Filters list retrieved for chat {chat_id}: {len(filters_list)} filters.")
275
+ return render_template('filters.html', chat_id=chat_id, filters=filters_list)
276
+
277
+ @app.route('/global_filters')
278
+ async def global_filters():
279
+ """
280
+ Render the page with a list of all global filters.
281
+ """
282
+ logger.info("Rendering global filters page.")
283
+ if not await admin_check(int(request.args.get('admin_id'))):
284
+ logger.info("User is not an admin, redirecting to index.")
285
+ flash("You are not authorized to view global filters.")
286
+ return redirect(url_for('index'))
287
+ gfilters_list = await get_gfilters('gfilters')
288
+ logger.info(f"Global filters list retrieved: {len(gfilters_list)} global filters.")
289
+ return render_template('global_filters.html', gfilters=gfilters_list)
290
+
291
+ @app.route('/connections')
292
+ async def connections():
293
+ """
294
+ Render the page with a list of all connections.
295
+ """
296
+ logger.info("Rendering connections page.")
 
297
  user_id = request.args.get('user_id')
298
+ if not user_id or not await admin_check(int(user_id)):
299
+ logger.info("User is not an admin, redirecting to index.")
300
+ flash("You are not authorized to view connections.")
301
+ return redirect(url_for('index'))
302
+ connections_list = await all_connections(user_id)
303
+ logger.info(f"Connections list retrieved for user {user_id}: {len(connections_list)} connections.")
304
+ return render_template('connections.html', user_id=user_id, connections=connections_list)
305
+
306
+ @app.route('/settings')
307
+ async def settings():
308
+ """
309
+ Render the settings page for a specific group.
310
+ """
311
+ logger.info("Rendering settings page.")
312
+ grp_id = request.args.get('grp_id')
313
+ if not grp_id or not await admin_check(int(request.args.get('admin_id'))):
314
+ logger.info("User is not an admin, redirecting to index.")
315
+ flash("You are not authorized to view settings.")
316
+ return redirect(url_for('index'))
317
+ settings = await db.get_settings(grp_id)
318
+ logger.info(f"Settings retrieved for group {grp_id}: {settings}.")
319
+ return render_template('settings.html', grp_id=grp_id, settings=settings)
320
+
321
+ @app.route('/update_settings', methods=['POST'])
322
+ async def update_settings():
323
+ """
324
+ Update settings for a specific group via the settings page.
325
+ """
326
+ logger.info("Update settings request received.")
327
+ grp_id = request.form.get('grp_id')
328
+ button = request.form.get('button', 'False') == 'True'
329
+ botpm = request.form.get('botpm', 'False') == 'True'
330
+ file_secure = request.form.get('file_secure', 'False') == 'True'
331
+ imdb = request.form.get('imdb', 'False') == 'True'
332
+ spell_check = request.form.get('spell_check', 'False') == 'True'
333
+ welcome = request.form.get('welcome', 'False') == 'True'
334
+ template = request.form.get('template', IMDB_TEMPLATE)
335
+ admin_id = request.form.get('admin_id')
336
+ if not admin_id or not await admin_check(int(admin_id)):
337
+ logger.info("Admin check failed for updating settings.")
338
+ flash("You are not authorized to update settings.")
339
+ return redirect(url_for('settings', grp_id=grp_id))
340
+ try:
341
+ await db.update_settings(grp_id, {
342
+ 'button': button,
343
+ 'botpm': botpm,
344
+ 'file_secure': file_secure,
345
+ 'imdb': imdb,
346
+ 'spell_check': spell_check,
347
+ 'welcome': welcome,
348
+ 'template': template
349
+ })
350
+ logger.info(f"Settings updated for group {grp_id}.")
351
+ flash("Settings updated successfully.")
352
+ except Exception as e:
353
+ logger.error(f"Error updating settings for group {grp_id}: {e}")
354
+ flash("Error updating settings.")
355
+ return redirect(url_for('settings', grp_id=grp_id))
356
+
357
+ @app.route('/logs/<path:filename>')
358
+ def log_file(filename):
359
+ """
360
+ Serve a specific log file.
361
+ """
362
+ logger.info(f"Serving log file: {filename}.")
363
+ try:
364
+ with open(filename, 'r') as file:
365
+ logs = file.readlines()
366
+ logger.info(f"Log file {filename} read successfully.")
367
+ return render_template('log_file.html', logs=logs, filename=filename)
368
+ except Exception as e:
369
+ logger.error(f"Error reading log file {filename}: {e}")
370
+ flash("Error reading log file.")
371
+ return redirect(url_for('logs'))
372
+
373
+ @app.route('/add_filter', methods=['POST'])
374
+ async def add_filter():
375
+ """
376
+ Add a filter via the dashboard.
377
+ """
378
+ logger.info("Add filter request received.")
379
+ chat_id = request.form.get('chatId')
380
+ text = request.form.get('filterText')
381
+ reply_text = request.form.get('replyText')
382
+ btn = request.form.get('btn', '[]')
383
+ file = request.form.get('file', 'None')
384
+ alert = request.form.get('alert', 'None')
385
+ admin_id = request.form.get('admin_id')
386
+ if not admin_id or not await admin_check(int(admin_id)):
387
+ logger.info("Admin check failed for adding filter.")
388
+ flash("You are not authorized to add filters.")
389
+ return redirect(url_for('filters', chat_id=chat_id, admin_id=admin_id))
390
+ try:
391
+ await db.add_filter(chat_id, text, reply_text, btn, file, alert)
392
+ logger.info(f"Filter added for group {chat_id} with text: {text}.")
393
+ flash("Filter added successfully.")
394
+ except Exception as e:
395
+ logger.error(f"Error adding filter for group {chat_id} with text: {text}: {e}")
396
+ flash("Error adding filter.")
397
+ return redirect(url_for('filters', chat_id=chat_id, admin_id=admin_id))
398
+
399
+ @app.route('/delete_filter', methods=['POST'])
400
+ async def delete_filter_route():
401
+ """
402
+ Delete a filter via the dashboard.
403
+ """
404
+ logger.info("Delete filter request received.")
405
+ chat_id = request.form.get('chatId')
406
+ text = request.form.get('filterText')
407
+ admin_id = request.form.get('admin_id')
408
+ if not admin_id or not await admin_check(int(admin_id)):
409
+ logger.info("Admin check failed for deleting filter.")
410
+ flash("You are not authorized to delete filters.")
411
+ return redirect(url_for('filters', chat_id=chat_id, admin_id=admin_id))
412
+ try:
413
+ await delete_filter(request, text, chat_id)
414
+ logger.info(f"Filter deleted for group {chat_id} with text: {text}.")
415
+ flash("Filter deleted successfully.")
416
+ except Exception as e:
417
+ logger.error(f"Error deleting filter for group {chat_id} with text: {text}: {e}")
418
+ flash("Error deleting filter.")
419
+ return redirect(url_for('filters', chat_id=chat_id, admin_id=admin_id))
420
+
421
+ @app.route('/add_gfilter', methods=['POST'])
422
+ async def add_gfilter():
423
+ """
424
+ Add a global filter via the dashboard.
425
+ """
426
+ logger.info("Add global filter request received.")
427
+ text = request.form.get('gfilterText')
428
+ reply_text = request.form.get('greplyText')
429
+ btn = request.form.get('gbtn', '[]')
430
+ file = request.form.get('gfile', 'None')
431
+ alert = request.form.get('galert', 'None')
432
+ admin_id = request.form.get('admin_id')
433
+ if not admin_id or not await admin_check(int(admin_id)):
434
+ logger.info("Admin check failed for adding global filter.")
435
+ flash("You are not authorized to add global filters.")
436
+ return redirect(url_for('global_filters', admin_id=admin_id))
437
+ try:
438
+ await db.add_gfilter('gfilters', text, reply_text, btn, file, alert)
439
+ logger.info(f"Global filter added with text: {text}.")
440
+ flash("Global filter added successfully.")
441
+ except Exception as e:
442
+ logger.error(f"Error adding global filter with text: {text}: {e}")
443
+ flash("Error adding global filter.")
444
+ return redirect(url_for('global_filters', admin_id=admin_id))
445
+
446
+ @app.route('/delete_gfilter', methods=['POST'])
447
+ async def delete_gfilter_route():
448
+ """
449
+ Delete a global filter via the dashboard.
450
+ """
451
+ logger.info("Delete global filter request received.")
452
+ text = request.form.get('gfilterText')
453
+ admin_id = request.form.get('admin_id')
454
+ if not admin_id or not await admin_check(int(admin_id)):
455
+ logger.info("Admin check failed for deleting global filter.")
456
+ flash("You are not authorized to delete global filters.")
457
+ return redirect(url_for('global_filters', admin_id=admin_id))
458
+ try:
459
+ await delete_gfilter(request, text, 'gfilters')
460
+ logger.info(f"Global filter deleted with text: {text}.")
461
+ flash("Global filter deleted successfully.")
462
+ except Exception as e:
463
+ logger.error(f"Error deleting global filter with text: {text}: {e}")
464
+ flash("Error deleting global filter.")
465
+ return redirect(url_for('global_filters', admin_id=admin_id))
466
+
467
+ @app.route('/add_connection', methods=['POST'])
468
+ async def add_connection_route():
469
+ """
470
+ Add a connection between a user and a group via the dashboard.
471
+ """
472
+ logger.info("Add connection request received.")
473
+ group_id = request.form.get('groupId')
474
+ user_id = request.form.get('userId')
475
+ admin_id = request.form.get('admin_id')
476
+ if not admin_id or not await admin_check(int(admin_id)):
477
+ logger.info("Admin check failed for adding connection.")
478
+ flash("You are not authorized to add connections.")
479
+ return redirect(url_for('connections', user_id=user_id, admin_id=admin_id))
480
+ try:
481
+ await add_connection(group_id, user_id)
482
+ logger.info(f"Connection added for user {user_id} to group {group_id}.")
483
+ flash("Connection added successfully.")
484
+ except Exception as e:
485
+ logger.error(f"Error adding connection for user {user_id} to group {group_id}: {e}")
486
+ flash("Error adding connection.")
487
+ return redirect(url_for('connections', user_id=user_id, admin_id=admin_id))
488
+
489
+ @app.route('/delete_connection', methods=['POST'])
490
+ async def delete_connection_route():
491
+ """
492
+ Delete a connection between a user and a group via the dashboard.
493
+ """
494
+ logger.info("Delete connection request received.")
495
+ user_id = request.form.get('userId')
496
+ group_id = request.form.get('groupId')
497
+ admin_id = request.form.get('admin_id')
498
+ if not admin_id or not await admin_check(int(admin_id)):
499
+ logger.info("Admin check failed for deleting connection.")
500
+ flash("You are not authorized to delete connections.")
501
+ return redirect(url_for('connections', user_id=user_id, admin_id=admin_id))
502
+ try:
503
+ await delete_connection(user_id, group_id)
504
+ logger.info(f"Connection deleted for user {user_id} from group {group_id}.")
505
+ flash("Connection deleted successfully.")
506
+ except Exception as e:
507
+ logger.error(f"Error deleting connection for user {user_id} from group {group_id}: {e}")
508
+ flash("Error deleting connection.")
509
+ return redirect(url_for('connections', user_id=user_id, admin_id=admin_id))
510
+
511
+ @app.route('/broadcast', methods=['POST'])
512
+ async def broadcast():
513
+ """
514
+ Broadcast a message to all users or chats via the dashboard.
515
+ """
516
+ logger.info("Broadcast request received.")
517
+ message_text = request.form.get('broadcastText')
518
+ admin_id = request.form.get('admin_id')
519
+ if not admin_id or not await admin_check(int(admin_id)):
520
+ logger.info("Admin check failed for broadcasting.")
521
+ flash("You are not authorized to broadcast messages.")
522
+ return redirect(url_for('broadcast', admin_id=admin_id))
523
+ try:
524
+ users = await db.get_all_users()
525
+ total_users = await db.total_users_count()
526
+ done = 0
527
+ success = 0
528
+ failed = 0
529
+ async for user in users:
530
+ try:
531
+ await bot.send_message(user['id'], message_text)
532
+ success += 1
533
+ except Exception as e:
534
+ logger.error(f"Error broadcasting to user {user['id']}: {e}")
535
+ failed += 1
536
+ done += 1
537
+ if not done % 20:
538
+ logger.info(f"Broadcast in progress: Completed {done}/{total_users} users.")
539
+ logger.info(f"Broadcast completed: Success {success}, Failed {failed}.")
540
+ flash(f"Broadcast completed: Success {success}, Failed {failed}.")
541
+ except Exception as e:
542
+ logger.error(f"Error broadcasting message: {e}")
543
+ flash("Error broadcasting message.")
544
+ return redirect(url_for('broadcast', admin_id=admin_id))
545
+
546
+ @app.route('/restart_bot', methods=['POST'])
547
+ async def restart_bot():
548
+ """
549
+ Restart the bot via the dashboard.
550
+ """
551
+ logger.info("Restart bot request received.")
552
+ admin_id = request.form.get('admin_id')
553
+ if not admin_id or not await admin_check(int(admin_id)):
554
+ logger.info("Admin check failed for restarting bot.")
555
+ flash("You are not authorized to restart the bot.")
556
+ return redirect(url_for('extra_mods', admin_id=admin_id))
557
+ try:
558
+ await bot.stop()
559
+ logger.info("Bot stopped successfully.")
560
+ await bot.start()
561
+ logger.info("Bot started successfully.")
562
+ flash("Bot restarted successfully.")
563
+ except Exception as e:
564
+ logger.error(f"Error restarting bot: {e}")
565
+ flash("Error restarting bot.")
566
+ return redirect(url_for('extra_mods', admin_id=admin_id))
567
+
568
+ @app.route('/extra_mods')
569
+ async def extra_mods():
570
+ """
571
+ Render the extra mods page.
572
+ """
573
+ logger.info("Rendering extra mods page.")
574
+ admin_id = request.args.get('admin_id')
575
+ if not admin_id or not await admin_check(int(admin_id)):
576
+ logger.info("User is not an admin, redirecting to index.")
577
+ flash("You are not authorized to access extra mods.")
578
+ return redirect(url_for('index'))
579
+ logger.info("User is authorized to access extra mods.")
580
+ return render_template('extra_mods.html', admin_id=admin_id)
581
+
582
+ @app.route('/get_recent_files', methods=['GET'])
583
+ async def get_recent_files():
584
+ """
585
+ Get recent files for display in the dashboard.
586
+ """
587
+ logger.info("Request to get recent files.")
588
+ recent_files = []
589
+ try:
590
+ files = await Media.find().sort('_id', -1).limit(10).to_list(length=10)
591
+ for file in files:
592
+ recent_files.append({
593
+ 'file_name': file['file_name'],
594
+ 'file_size': get_size(file['file_size']),
595
+ 'file_id': file['file_id']
596
  })
597
+ logger.info(f"Recent files retrieved: {len(recent_files)} files.")
598
+ return jsonify(recent_files)
599
+ except Exception as e:
600
+ logger.error(f"Error retrieving recent files: {e}")
601
+ return jsonify([])
602
+
603
+ @app.route('/get_os_info', methods=['GET'])
604
+ def get_os_info():
605
+ """
606
+ Get operating system information for display in the dashboard.
607
+ """
608
+ logger.info("Request to get OS information.")
609
+ os_name = os.name
610
+ os_version = os.uname().version
611
+ logger.info(f"OS Information: Name: {os_name}, Version: {os_version}.")
612
+ return jsonify({'os_name': os_name, 'os_version': os_version})
613
 
614
  if __name__ == '__main__':
615
+ logger.info("Starting Flask app...")
616
+ app.run(host='0.0.0.0', port=8080)