Alialdlfy1 commited on
Commit
cd2be21
·
verified ·
1 Parent(s): 1bb638c

Delete database.py

Browse files
Files changed (1) hide show
  1. database.py +0 -2427
database.py DELETED
@@ -1,2427 +0,0 @@
1
- import json
2
- import os
3
- import time
4
- import shutil
5
- from threading import Lock
6
-
7
- DB_FILE = "/data/data.json"
8
- BACKUP_DIR = "/data/backups"
9
- SCHEMA_VERSION = 2
10
- lock = Lock()
11
-
12
- DEFAULT_BLOCKED_WORDS = [
13
- "إعلان", "اعلان", "تبادل", "ممول", "تمويل", "للتواصل",
14
- "اشتراك", "تابعونا", "اشترك", "قناتنا", "بوت", "عبر البوت",
15
- "عرض خاص", "لفترة محدودة", "اضغط هنا", "لمشاهدة المزيد",
16
- "حصرياً", "تم النشر بواسطة"
17
- ]
18
-
19
- DEFAULT_DATA = {
20
- "schema_version": SCHEMA_VERSION,
21
- "channels": {},
22
- "public_sources": [],
23
- "source_meta": {},
24
- "blocked_words": DEFAULT_BLOCKED_WORDS,
25
- "allowed_users": [],
26
- "last_source_messages": {},
27
- "settings": {},
28
- "global_remove_terms": [],
29
- "recent_fingerprints": [],
30
- "source_stats": {},
31
- "source_logs": {},
32
- "system": {},
33
- "last_errors": [],
34
- "named_backups": [],
35
- "channel_failures": {},
36
- "published_messages": {},
37
- "sessions": {},
38
- "ai_keys": {},
39
- "publishing_bots": {},
40
- "websites": {},
41
- "trash": [],
42
- "naming_counters": {"session": 0, "ai_key": 0, "bot": 0, "website": 0},
43
- "channel_configs": {},
44
- "notification_settings": {
45
- "session_stopped": True,
46
- "ai_key_error": True,
47
- "source_stopped": True,
48
- "channel_idle_hour": True,
49
- "backup_failed": True,
50
- "db_issue": True,
51
- "last_alert_ts": {},
52
- },
53
- }
54
-
55
-
56
- def _now():
57
- return int(time.time())
58
-
59
-
60
- def _dedupe_int_list(values):
61
- out = []
62
- seen = set()
63
- for value in values or []:
64
- try:
65
- item = int(value)
66
- except Exception:
67
- item = value
68
- key = str(item)
69
- if key not in seen:
70
- seen.add(key)
71
- out.append(item)
72
- return out
73
-
74
-
75
- def _normalize_channel(cid, value):
76
- if not isinstance(value, dict):
77
- value = {"name": str(value)}
78
- value.setdefault("name", value.get("title") or str(cid))
79
- value.setdefault("title", value.get("name") or str(cid))
80
- value.setdefault("username", "")
81
- value.setdefault("link", "")
82
- value.setdefault("chat_type", "")
83
- value.setdefault("tail", "")
84
- value.setdefault("special_sources", [])
85
- value.setdefault("paused", False)
86
- value.setdefault("posts_count", 0)
87
- value.setdefault("publish_delay", None)
88
- value.setdefault("bold_publish", True)
89
- value.setdefault("quote_publish", False)
90
- # إعدادات الاقتباس حسب نوع المنشور.
91
- # توافق رجعي: إذا كان quote_publish القديم مفعلاً، نفعّل كل الأنواع افتراضياً.
92
- old_quote = bool(value.get("quote_publish", False))
93
- quote_types = value.get("quote_types")
94
- if not isinstance(quote_types, dict):
95
- quote_types = {}
96
- value["quote_types"] = {
97
- "text": bool(quote_types.get("text", old_quote)),
98
- "photo": bool(quote_types.get("photo", old_quote)),
99
- "video": bool(quote_types.get("video", old_quote)),
100
- "album": bool(quote_types.get("album", old_quote)),
101
- }
102
- # يبقى المفتاح القديم موجود للتوافق مع النسخ الاحتياطية القديمة.
103
- value["quote_publish"] = any(value["quote_types"].values())
104
- value.setdefault("hashtags", [])
105
- if not isinstance(value.get("hashtags"), list):
106
- value["hashtags"] = []
107
- value.setdefault("fail_count", 0)
108
- value.setdefault("disable_web_page_preview", False)
109
- value.setdefault("added_at", _now())
110
- value["special_sources"] = _dedupe_int_list(value.get("special_sources", []))
111
- return value
112
-
113
-
114
- def _normalize_source_meta(source_id, value=None):
115
- if not isinstance(value, dict):
116
- value = {}
117
- sid = str(source_id)
118
- value.setdefault("id", int(source_id) if str(source_id).lstrip('-').isdigit() else source_id)
119
- value.setdefault("name", value.get("title") or sid)
120
- value.setdefault("title", value.get("name") or sid)
121
- value.setdefault("username", "")
122
- value.setdefault("link", "")
123
- value.setdefault("chat_type", "")
124
- value.setdefault("added_at", _now())
125
- value.setdefault("paused", False)
126
- value.setdefault("remove_terms", [])
127
- if not isinstance(value.get("remove_terms"), list):
128
- value["remove_terms"] = []
129
- value.setdefault("remove_emoji", False)
130
- default_types = {"text": True, "photo": True, "video": True, "album": True, "voice": False, "audio": False, "document": False}
131
- types = value.get("content_types")
132
- if not isinstance(types, dict):
133
- types = {}
134
- value["content_types"] = {k: bool(types.get(k, v)) for k, v in default_types.items()}
135
- return value
136
-
137
-
138
- def _normalize_data(data):
139
- if not isinstance(data, dict):
140
- data = {}
141
-
142
- for key, value in DEFAULT_DATA.items():
143
- if key not in data:
144
- data[key] = value.copy() if isinstance(value, (list, dict)) else value
145
-
146
- if not isinstance(data.get("channels"), dict):
147
- data["channels"] = {}
148
- if not isinstance(data.get("public_sources"), list):
149
- data["public_sources"] = []
150
- if not isinstance(data.get("source_meta"), dict):
151
- data["source_meta"] = {}
152
- if not isinstance(data.get("blocked_words"), list):
153
- data["blocked_words"] = DEFAULT_BLOCKED_WORDS.copy()
154
- if not isinstance(data.get("allowed_users"), list):
155
- data["allowed_users"] = []
156
- if not isinstance(data.get("last_source_messages"), dict):
157
- data["last_source_messages"] = {}
158
- if not isinstance(data.get("settings"), dict):
159
- data["settings"] = {}
160
- if not isinstance(data.get("global_remove_terms"), list):
161
- data["global_remove_terms"] = []
162
- if not isinstance(data.get("recent_fingerprints"), list):
163
- data["recent_fingerprints"] = []
164
- if not isinstance(data.get("source_stats"), dict):
165
- data["source_stats"] = {}
166
- if not isinstance(data.get("source_logs"), dict):
167
- data["source_logs"] = {}
168
- if not isinstance(data.get("system"), dict):
169
- data["system"] = {}
170
- if not isinstance(data.get("last_errors"), list):
171
- data["last_errors"] = []
172
- if not isinstance(data.get("named_backups"), list):
173
- data["named_backups"] = []
174
- if not isinstance(data.get("channel_failures"), dict):
175
- data["channel_failures"] = {}
176
- if not isinstance(data.get("published_messages"), dict):
177
- data["published_messages"] = {}
178
- if not isinstance(data.get("sessions"), dict):
179
- data["sessions"] = {}
180
- if not isinstance(data.get("ai_keys"), dict):
181
- data["ai_keys"] = {}
182
- if not isinstance(data.get("publishing_bots"), dict):
183
- data["publishing_bots"] = {}
184
- if not isinstance(data.get("websites"), dict):
185
- data["websites"] = {}
186
- if not isinstance(data.get("trash"), list):
187
- data["trash"] = []
188
- if not isinstance(data.get("naming_counters"), dict):
189
- data["naming_counters"] = {"session": 0, "ai_key": 0, "bot": 0, "website": 0}
190
- if not isinstance(data.get("channel_configs"), dict):
191
- data["channel_configs"] = {}
192
- if not isinstance(data.get("notification_settings"), dict):
193
- data["notification_settings"] = DEFAULT_DATA["notification_settings"].copy()
194
- ns = data["notification_settings"]
195
- for k, v in DEFAULT_DATA["notification_settings"].items():
196
- ns.setdefault(k, v.copy() if isinstance(v, dict) else v)
197
-
198
- data["schema_version"] = SCHEMA_VERSION
199
- data["public_sources"] = _dedupe_int_list(data.get("public_sources", []))
200
-
201
- channels = {}
202
- for cid, ch in data.get("channels", {}).items():
203
- channels[str(cid)] = _normalize_channel(cid, ch)
204
- data["channels"] = channels
205
-
206
- meta = {}
207
- for source in data["public_sources"]:
208
- sid = str(source)
209
- meta[sid] = _normalize_source_meta(source, data.get("source_meta", {}).get(sid, {}))
210
- for sid, value in data.get("source_meta", {}).items():
211
- if sid not in meta:
212
- meta[sid] = _normalize_source_meta(sid, value)
213
- data["source_meta"] = meta
214
-
215
- # normalize last source ids as strings
216
- data["last_source_messages"] = {str(k): v for k, v in data.get("last_source_messages", {}).items()}
217
- return data
218
-
219
-
220
-
221
- def _is_valid_data(data, allow_empty=True):
222
- """يتأكد أن ملف البيانات صالح وليس فارغاً/تالفاً."""
223
- if not isinstance(data, dict):
224
- return False
225
- if "channels" not in data or "public_sources" not in data:
226
- return False
227
- if not isinstance(data.get("channels"), dict):
228
- return False
229
- if not isinstance(data.get("public_sources"), list):
230
- return False
231
- if not allow_empty:
232
- if not data.get("channels") and not data.get("public_sources") and not data.get("source_meta"):
233
- return False
234
- return True
235
-
236
-
237
- def _load_json_file(path):
238
- with open(path, "r", encoding="utf-8") as f:
239
- data = json.load(f)
240
- if not _is_valid_data(data, allow_empty=True):
241
- raise ValueError("ملف بيانات غير صالح")
242
- return _normalize_data(data)
243
-
244
-
245
- def _backup_candidates():
246
- files = []
247
- if os.path.exists(DB_FILE + ".bak"):
248
- files.append(DB_FILE + ".bak")
249
- if os.path.isdir(BACKUP_DIR):
250
- files.extend(
251
- os.path.join(BACKUP_DIR, x)
252
- for x in os.listdir(BACKUP_DIR)
253
- if x.endswith(".json")
254
- )
255
- return sorted(files, key=lambda p: os.path.getmtime(p), reverse=True)
256
-
257
-
258
- def _restore_latest_backup():
259
- """يحاول استعادة أحدث نسخة احتياطية صالحة."""
260
- os.makedirs("/data", exist_ok=True)
261
- for path in _backup_candidates():
262
- try:
263
- data = _load_json_file(path)
264
- tmp = DB_FILE + ".restore.tmp"
265
- with open(tmp, "w", encoding="utf-8") as f:
266
- json.dump(data, f, ensure_ascii=False, indent=2)
267
- os.replace(tmp, DB_FILE)
268
- return data
269
- except Exception:
270
- continue
271
- return None
272
-
273
-
274
- def verify_or_recover_storage():
275
- """فحص تخزين آمن عند تشغيل التطبيق/البوت."""
276
- os.makedirs("/data", exist_ok=True)
277
- if os.path.exists(DB_FILE):
278
- try:
279
- data = _load_json_file(DB_FILE)
280
- return {"ok": True, "recovered": False, "message": "data.json صالح", "data": data}
281
- except Exception as e:
282
- recovered = _restore_latest_backup()
283
- if recovered is not None:
284
- return {"ok": True, "recovered": True, "message": f"تمت الاستعادة من Backup بعد تلف data.json: {e}", "data": recovered}
285
- return {"ok": False, "recovered": False, "message": f"data.json تالف ولا توجد نسخة احتياطية صالحة: {e}", "data": None}
286
-
287
- recovered = _restore_latest_backup()
288
- if recovered is not None:
289
- return {"ok": True, "recovered": True, "message": "تمت الاستعادة من Backup لأن data.json غير موجود", "data": recovered}
290
-
291
- # أول تشغيل فقط: إنشاء ملف جديد فارغ
292
- data = _normalize_data(DEFAULT_DATA.copy())
293
- with open(DB_FILE, "w", encoding="utf-8") as f:
294
- json.dump(data, f, ensure_ascii=False, indent=2)
295
- return {"ok": True, "recovered": False, "message": "تم إنشاء قاعدة بيانات جديدة", "data": data}
296
-
297
-
298
- def _read():
299
- os.makedirs("/data", exist_ok=True)
300
- status = verify_or_recover_storage()
301
- if not status.get("ok"):
302
- raise RuntimeError(status.get("message", "فشل قراءة قاعدة البيانات"))
303
- return _normalize_data(status.get("data") or DEFAULT_DATA.copy())
304
-
305
-
306
- def _make_prewrite_backup():
307
- """نسخة احتياطية فورية قبل أي كتابة حتى لا تضيع البيانات عند توقف الاستضافة."""
308
- try:
309
- if os.path.exists(DB_FILE) and os.path.getsize(DB_FILE) > 5:
310
- shutil.copy2(DB_FILE, DB_FILE + ".bak")
311
- except Exception:
312
- pass
313
-
314
-
315
- def _write(data):
316
- os.makedirs("/data", exist_ok=True)
317
- data = _normalize_data(data)
318
-
319
- # حماية من الكتابة بملف فارغ فوق بيانات موجودة
320
- if not _is_valid_data(data, allow_empty=True):
321
- raise ValueError("رفض كتابة بيانات غير صالحة")
322
-
323
- _make_prewrite_backup()
324
- tmp_file = DB_FILE + ".tmp"
325
- with open(tmp_file, "w", encoding="utf-8") as f:
326
- json.dump(data, f, ensure_ascii=False, indent=2)
327
- f.flush()
328
- try:
329
- os.fsync(f.fileno())
330
- except Exception:
331
- pass
332
- os.replace(tmp_file, DB_FILE)
333
-
334
-
335
- def _write_backup(data):
336
- try:
337
- os.makedirs(BACKUP_DIR, exist_ok=True)
338
- data = _normalize_data(data)
339
- if not _is_valid_data(data, allow_empty=True):
340
- return
341
- backup_file = os.path.join(BACKUP_DIR, f"backup_{int(time.time())}.json")
342
- with open(backup_file, "w", encoding="utf-8") as f:
343
- json.dump(data, f, ensure_ascii=False, indent=2)
344
- # keep last 20 backups
345
- files = sorted([os.path.join(BACKUP_DIR, x) for x in os.listdir(BACKUP_DIR) if x.endswith('.json')])
346
- for old in files[:-20]:
347
- try:
348
- os.remove(old)
349
- except Exception:
350
- pass
351
- except Exception:
352
- pass
353
-
354
- def get_all_channels():
355
- with lock:
356
- data = _read()
357
- return [{"id": k, **v} for k, v in data["channels"].items()]
358
-
359
-
360
- def add_channel(channel_id, name="", title="", username="", link="", chat_type=""):
361
- cid = str(channel_id)
362
- with lock:
363
- data = _read()
364
- created = cid not in data["channels"]
365
- if created:
366
- data["channels"][cid] = _normalize_channel(cid, {
367
- "name": title or name or cid,
368
- "title": title or name or cid,
369
- "username": username or "",
370
- "link": link or "",
371
- "chat_type": chat_type or "",
372
- "tail": "",
373
- "special_sources": [],
374
- "paused": False,
375
- "posts_count": 0,
376
- "added_at": _now(),
377
- })
378
- else:
379
- ch = data["channels"][cid]
380
- if title or name:
381
- ch["name"] = title or name
382
- ch["title"] = title or name
383
- if username is not None:
384
- ch["username"] = username or ch.get("username", "")
385
- if link is not None:
386
- ch["link"] = link or ch.get("link", "")
387
- if chat_type is not None:
388
- ch["chat_type"] = chat_type or ch.get("chat_type", "")
389
- _write(data)
390
- if created:
391
- _write_backup(data)
392
- return created
393
-
394
-
395
- def delete_channel(channel_id):
396
- cid = str(channel_id)
397
- with lock:
398
- data = _read()
399
- if cid in data["channels"]:
400
- del data["channels"][cid]
401
- _write(data)
402
- _write_backup(data)
403
- return True
404
- return False
405
-
406
-
407
- def update_channel(channel_id, key, value):
408
- cid = str(channel_id)
409
- with lock:
410
- data = _read()
411
- if cid in data["channels"]:
412
- data["channels"][cid][key] = value
413
- _write(data)
414
- _write_backup(data)
415
- return True
416
- return False
417
-
418
-
419
- def increment_post_count(channel_id):
420
- cid = str(channel_id)
421
- with lock:
422
- data = _read()
423
- if cid in data["channels"]:
424
- data["channels"][cid].setdefault("posts_count", 0)
425
- data["channels"][cid]["posts_count"] += 1
426
- _write(data)
427
- return True
428
- return False
429
-
430
-
431
- def get_channel(channel_id):
432
- cid = str(channel_id)
433
- with lock:
434
- data = _read()
435
- return data["channels"].get(cid)
436
-
437
-
438
- def get_public_sources():
439
- with lock:
440
- data = _read()
441
- return data["public_sources"]
442
-
443
-
444
- def get_source_meta(source_id):
445
- sid = str(source_id)
446
- with lock:
447
- data = _read()
448
- return data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
449
-
450
-
451
- def get_all_public_sources_with_meta():
452
- with lock:
453
- data = _read()
454
- return [{"id": s, **data.get("source_meta", {}).get(str(s), _normalize_source_meta(s))} for s in data["public_sources"]]
455
-
456
-
457
- def add_public_source(source_id, name="", title="", username="", link="", chat_type=""):
458
- try:
459
- source_id = int(source_id)
460
- except Exception:
461
- pass
462
- sid = str(source_id)
463
-
464
- with lock:
465
- data = _read()
466
- created = source_id not in data["public_sources"]
467
- if created:
468
- data["public_sources"].append(source_id)
469
- old = data.setdefault("source_meta", {}).get(sid, {})
470
- meta = _normalize_source_meta(source_id, old)
471
- if title or name:
472
- meta["name"] = title or name
473
- meta["title"] = title or name
474
- if username is not None:
475
- meta["username"] = username or meta.get("username", "")
476
- if link is not None:
477
- meta["link"] = link or meta.get("link", "")
478
- if chat_type is not None:
479
- meta["chat_type"] = chat_type or meta.get("chat_type", "")
480
- data["source_meta"][sid] = meta
481
- _write(data)
482
- if created:
483
- _write_backup(data)
484
- return created
485
-
486
-
487
- def update_source_meta(source_id, **kwargs):
488
- sid = str(source_id)
489
- with lock:
490
- data = _read()
491
- meta = _normalize_source_meta(source_id, data.setdefault("source_meta", {}).get(sid, {}))
492
- for key, value in kwargs.items():
493
- if value is not None:
494
- meta[key] = value
495
- data["source_meta"][sid] = meta
496
- _write(data)
497
- return True
498
-
499
-
500
- def remove_public_source(source_id):
501
- try:
502
- source_id = int(source_id)
503
- except Exception:
504
- pass
505
- sid = str(source_id)
506
-
507
- with lock:
508
- data = _read()
509
- if source_id in data["public_sources"]:
510
- data["public_sources"].remove(source_id)
511
- data["last_source_messages"].pop(sid, None)
512
- data.get("source_meta", {}).pop(sid, None)
513
- _write(data)
514
- _write_backup(data)
515
- return True
516
- return False
517
-
518
-
519
- def get_blocked_words():
520
- with lock:
521
- data = _read()
522
- return data["blocked_words"]
523
-
524
-
525
- def add_blocked_word(word):
526
- word = str(word).strip()
527
- if not word:
528
- return False
529
- with lock:
530
- data = _read()
531
- if word not in data["blocked_words"]:
532
- data["blocked_words"].append(word)
533
- _write(data)
534
- _write_backup(data)
535
- return True
536
- return False
537
-
538
-
539
- def remove_blocked_word(word):
540
- word = str(word).strip()
541
- with lock:
542
- data = _read()
543
- if word in data["blocked_words"]:
544
- data["blocked_words"].remove(word)
545
- _write(data)
546
- _write_backup(data)
547
- return True
548
- return False
549
-
550
-
551
- def get_last_source_message(source_id):
552
- with lock:
553
- data = _read()
554
- value = data.get("last_source_messages", {}).get(str(source_id))
555
- try:
556
- if isinstance(value, dict):
557
- return int(value.get("id")) if value.get("id") is not None else None
558
- return int(value) if value is not None else None
559
- except Exception:
560
- return None
561
-
562
- def set_last_source_message(source_id, message_id):
563
- with lock:
564
- data = _read()
565
- data.setdefault("last_source_messages", {})[str(source_id)] = {"id": int(message_id), "ts": _now()}
566
- _write(data)
567
- return True
568
-
569
- def reset_last_source_message(source_id):
570
- with lock:
571
- data = _read()
572
- if str(source_id) in data.get("last_source_messages", {}):
573
- del data["last_source_messages"][str(source_id)]
574
- _write(data)
575
- _write_backup(data)
576
- return True
577
- return False
578
-
579
-
580
-
581
- def export_data():
582
- with lock:
583
- data = _read()
584
- data = cleanup_old_runtime_data(data, days=3)
585
- return json.dumps(_normalize_data(data), ensure_ascii=False, indent=2)
586
-
587
-
588
- def import_data(json_str):
589
- with lock:
590
- new_data = json.loads(json_str)
591
- if not _is_valid_data(new_data, allow_empty=False):
592
- raise ValueError("ملف الاستيراد فارغ أو غير صالح. تم رفضه لحماية بياناتك.")
593
- new_data = _normalize_data(new_data)
594
-
595
- # لا نقبل ملف بلا قنوات وبلا مصادر إلا إذا كان مقصوداً، وهذا غير مسموح هنا
596
- if not new_data.get("channels") and not new_data.get("public_sources") and not new_data.get("source_meta"):
597
- raise ValueError("ملف الاستيراد لا يحتوي قنوات أو مصادر.")
598
-
599
- _make_prewrite_backup()
600
- _write_backup(_read())
601
- new_data = cleanup_old_runtime_data(new_data, days=3)
602
- _write(new_data)
603
- _write_backup(new_data)
604
- return {
605
- "channels": len(new_data.get("channels", {})),
606
- "public_sources": len(new_data.get("public_sources", [])),
607
- "source_meta": len(new_data.get("source_meta", {})),
608
- "blocked_words": len(new_data.get("blocked_words", [])),
609
- "global_remove_terms": len(new_data.get("global_remove_terms", [])),
610
- "last_source_messages": len(new_data.get("last_source_messages", {})),
611
- "recent_fingerprints": len(new_data.get("recent_fingerprints", [])),
612
- }
613
-
614
-
615
- def cleanup_old_runtime_data(data=None, days=3):
616
- """حذف بيانات التكرار والسجلات و IDs المؤقتة الأقدم من 3 أيام حتى لا يكبر الملف."""
617
- cutoff = _now() - int(days) * 86400
618
- own_write = data is None
619
- if data is None:
620
- data = _read()
621
-
622
- items = data.get("recent_fingerprints", [])
623
- if isinstance(items, list):
624
- data["recent_fingerprints"] = [
625
- x for x in items
626
- if isinstance(x, dict) and int(x.get("ts", _now())) >= cutoff
627
- ][-500:]
628
-
629
- logs = data.get("source_logs", {})
630
- if isinstance(logs, dict):
631
- new_logs = {}
632
- for sid, entries in logs.items():
633
- if isinstance(entries, list):
634
- new_logs[sid] = [
635
- x for x in entries
636
- if isinstance(x, dict) and int(x.get("ts", _now())) >= cutoff
637
- ][-20:]
638
- data["source_logs"] = new_logs
639
-
640
- # تنظيف IDs آخر الأخبار للمصادر إذا خزنّت بصيغة حديثة مع تاريخ.
641
- # القيم القديمة الرقمية تُترك كما هي للتوافق حتى يتم تحديثها تلقائياً عند أول فحص.
642
- last_ids = data.get("last_source_messages", {})
643
- if isinstance(last_ids, dict):
644
- cleaned_last = {}
645
- for sid, value in last_ids.items():
646
- if isinstance(value, dict):
647
- try:
648
- if int(value.get("ts", _now())) >= cutoff:
649
- cleaned_last[str(sid)] = value
650
- except Exception:
651
- pass
652
- else:
653
- cleaned_last[str(sid)] = value
654
- data["last_source_messages"] = cleaned_last
655
-
656
- last_errors = data.get("last_errors", [])
657
- if isinstance(last_errors, list):
658
- data["last_errors"] = [
659
- x for x in last_errors
660
- if isinstance(x, dict) and int(x.get("ts", _now())) >= cutoff
661
- ][-50:]
662
-
663
-
664
- # تنظيف سجل الرسائل المنشورة القديمة حتى لا يكبر الملف.
665
- published = data.get("published_messages", {})
666
- if isinstance(published, dict):
667
- new_published = {}
668
- for cid, by_type in published.items():
669
- if not isinstance(by_type, dict):
670
- continue
671
- new_by_type = {}
672
- for kind, entries in by_type.items():
673
- if isinstance(entries, list):
674
- new_by_type[kind] = [
675
- x for x in entries
676
- if isinstance(x, dict) and int(x.get("ts", _now())) >= cutoff
677
- ][-1000:]
678
- new_published[str(cid)] = new_by_type
679
- data["published_messages"] = new_published
680
-
681
- if own_write:
682
- _write(data)
683
- return _normalize_data(data)
684
-
685
- def get_source_remove_terms(source_id):
686
- sid = str(source_id)
687
- with lock:
688
- data = _read()
689
- meta = data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
690
- terms = meta.get("remove_terms", [])
691
- if not isinstance(terms, list):
692
- return []
693
- return [str(x).strip() for x in terms if str(x).strip()]
694
-
695
-
696
- def add_source_remove_terms(source_id, terms):
697
- sid = str(source_id)
698
- clean_terms = []
699
- for term in terms or []:
700
- term = str(term).strip()
701
- if term:
702
- clean_terms.append(term)
703
-
704
- if not clean_terms:
705
- return {"added": 0, "exists": 0}
706
-
707
- with lock:
708
- data = _read()
709
- meta = _normalize_source_meta(source_id, data.setdefault("source_meta", {}).get(sid, {}))
710
- existing = [str(x).strip() for x in meta.get("remove_terms", []) if str(x).strip()]
711
- existing_keys = {x.lower() for x in existing}
712
-
713
- added = 0
714
- exists = 0
715
- for term in clean_terms:
716
- key = term.lower()
717
- if key in existing_keys:
718
- exists += 1
719
- continue
720
- existing.append(term)
721
- existing_keys.add(key)
722
- added += 1
723
-
724
- meta["remove_terms"] = existing
725
- data["source_meta"][sid] = meta
726
- _write(data)
727
- if added:
728
- _write_backup(data)
729
- return {"added": added, "exists": exists}
730
-
731
-
732
- def remove_source_remove_terms(source_id, terms):
733
- sid = str(source_id)
734
- remove_keys = {str(x).strip().lower() for x in terms or [] if str(x).strip()}
735
- if not remove_keys:
736
- return {"removed": 0, "missing": 0}
737
-
738
- with lock:
739
- data = _read()
740
- meta = _normalize_source_meta(source_id, data.setdefault("source_meta", {}).get(sid, {}))
741
- existing = [str(x).strip() for x in meta.get("remove_terms", []) if str(x).strip()]
742
- before = len(existing)
743
- existing = [x for x in existing if x.lower() not in remove_keys]
744
- removed = before - len(existing)
745
- meta["remove_terms"] = existing
746
- data["source_meta"][sid] = meta
747
- _write(data)
748
- if removed:
749
- _write_backup(data)
750
- return {"removed": removed, "missing": max(0, len(remove_keys) - removed)}
751
-
752
-
753
- def remove_source_remove_term(source_id, term_or_index):
754
- terms = get_source_remove_terms(source_id)
755
- try:
756
- idx = int(term_or_index)
757
- if 0 <= idx < len(terms):
758
- return bool(remove_source_remove_terms(source_id, [terms[idx]]).get("removed"))
759
- except Exception:
760
- pass
761
- return bool(remove_source_remove_terms(source_id, [term_or_index]).get("removed"))
762
-
763
-
764
- # ===== Phase 3 Part 1: source filters, global cleanup, smart dedupe =====
765
- def get_global_remove_terms():
766
- with lock:
767
- data = _read()
768
- terms = data.get("global_remove_terms", [])
769
- if not isinstance(terms, list):
770
- return []
771
- return [str(x).strip() for x in terms if str(x).strip()]
772
-
773
-
774
- def add_global_remove_terms(terms):
775
- clean_terms = []
776
- for term in terms or []:
777
- term = str(term).strip()
778
- if term:
779
- clean_terms.append(term)
780
-
781
- if not clean_terms:
782
- return {"added": 0, "exists": 0}
783
-
784
- with lock:
785
- data = _read()
786
- existing = [str(x).strip() for x in data.get("global_remove_terms", []) if str(x).strip()]
787
- existing_keys = {x.lower() for x in existing}
788
- added = 0
789
- exists = 0
790
- for term in clean_terms:
791
- key = term.lower()
792
- if key in existing_keys:
793
- exists += 1
794
- continue
795
- existing.append(term)
796
- existing_keys.add(key)
797
- added += 1
798
- data["global_remove_terms"] = existing
799
- _write(data)
800
- if added:
801
- _write_backup(data)
802
- return {"added": added, "exists": exists}
803
-
804
-
805
- def remove_global_remove_terms(terms):
806
- remove_keys = {str(x).strip().lower() for x in terms or [] if str(x).strip()}
807
- if not remove_keys:
808
- return {"removed": 0, "missing": 0}
809
-
810
- with lock:
811
- data = _read()
812
- existing = [str(x).strip() for x in data.get("global_remove_terms", []) if str(x).strip()]
813
- before = len(existing)
814
- existing = [x for x in existing if x.lower() not in remove_keys]
815
- removed = before - len(existing)
816
- data["global_remove_terms"] = existing
817
- _write(data)
818
- if removed:
819
- _write_backup(data)
820
- return {"removed": removed, "missing": max(0, len(remove_keys) - removed)}
821
-
822
-
823
- def set_source_paused(source_id, paused=True):
824
- return update_source_meta(source_id, paused=bool(paused))
825
-
826
-
827
- def is_source_paused(source_id):
828
- sid = str(source_id)
829
- with lock:
830
- data = _read()
831
- meta = data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
832
- return bool(meta.get("paused", False))
833
-
834
-
835
- def set_source_remove_emoji(source_id, enabled=True):
836
- return update_source_meta(source_id, remove_emoji=bool(enabled))
837
-
838
-
839
- def get_source_remove_emoji(source_id):
840
- sid = str(source_id)
841
- with lock:
842
- data = _read()
843
- meta = data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
844
- return bool(meta.get("remove_emoji", False))
845
-
846
-
847
- def get_source_content_types(source_id):
848
- sid = str(source_id)
849
- with lock:
850
- data = _read()
851
- meta = data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
852
- default_types = {"text": True, "photo": True, "video": True, "album": True, "voice": False, "audio": False, "document": False}
853
- types = meta.get("content_types", {})
854
- if not isinstance(types, dict):
855
- types = {}
856
- return {k: bool(types.get(k, v)) for k, v in default_types.items()}
857
-
858
-
859
- def set_source_content_type(source_id, content_type, enabled=True):
860
- if content_type not in {"text", "photo", "video", "album", "voice", "audio", "document"}:
861
- return False
862
- sid = str(source_id)
863
- default_types = {"text": True, "photo": True, "video": True, "album": True, "voice": False, "audio": False, "document": False}
864
- with lock:
865
- data = _read()
866
- meta = _normalize_source_meta(source_id, data.setdefault("source_meta", {}).get(sid, {}))
867
- current = meta.get("content_types", {})
868
- if not isinstance(current, dict):
869
- current = {}
870
- types = {k: bool(current.get(k, v)) for k, v in default_types.items()}
871
- types[content_type] = bool(enabled)
872
- # منع إطفاء كل الأنواع حتى لا يصبح المصدر شغال بلا أي محتوى
873
- if not any(types.values()):
874
- return False
875
- meta["content_types"] = types
876
- data["source_meta"][sid] = meta
877
- _write(data)
878
- _write_backup(data)
879
- return True
880
-
881
-
882
- def set_source_content_types(source_id, content_types):
883
- allowed = {"text", "photo", "video", "album", "voice", "audio", "document"}
884
- values = {k: bool(content_types.get(k, False)) for k in allowed}
885
- if not any(values.values()):
886
- return False
887
- return update_source_meta(source_id, content_types=values)
888
-
889
-
890
- def get_recent_fingerprints():
891
- cutoff = _now() - 3 * 86400
892
- with lock:
893
- data = _read()
894
- items = data.get("recent_fingerprints", [])
895
- if not isinstance(items, list):
896
- return []
897
- fresh = [x for x in items if isinstance(x, dict) and x.get("fp") and int(x.get("ts", _now())) >= cutoff]
898
- if len(fresh) != len(items):
899
- data["recent_fingerprints"] = fresh[-500:]
900
- _write(data)
901
- return fresh[-500:]
902
-
903
- def add_recent_fingerprint(fp, sample="", limit=500):
904
- fp = str(fp or "").strip()
905
- if not fp:
906
- return False
907
- cutoff = _now() - 3 * 86400
908
- with lock:
909
- data = _read()
910
- items = data.get("recent_fingerprints", [])
911
- if not isinstance(items, list):
912
- items = []
913
- items = [x for x in items if isinstance(x, dict) and x.get("fp") != fp and int(x.get("ts", _now())) >= cutoff]
914
- items.append({"fp": fp, "sample": str(sample or "")[:500], "ts": _now()})
915
- if len(items) > int(limit):
916
- items = items[-int(limit):]
917
- data["recent_fingerprints"] = items
918
- _write(data)
919
- return True
920
-
921
- def set_channel_publish_delay(channel_id, delay_seconds):
922
- try:
923
- if delay_seconds is None or str(delay_seconds).strip() == "":
924
- value = None
925
- else:
926
- value = max(0.0, float(delay_seconds))
927
- except Exception:
928
- return False
929
- return update_channel(channel_id, "publish_delay", value)
930
-
931
-
932
- def get_channel_publish_delay(channel_id, default=0.5):
933
- ch = get_channel(channel_id)
934
- if not ch:
935
- return float(default)
936
- value = ch.get("publish_delay", None)
937
- if value is None or value == "":
938
- return float(default)
939
- try:
940
- return max(0.0, float(value))
941
- except Exception:
942
- return float(default)
943
-
944
-
945
-
946
- def set_channel_bold_publish(channel_id, enabled=True):
947
- return update_channel(channel_id, "bold_publish", bool(enabled))
948
-
949
-
950
- def get_channel_bold_publish(channel_id, default=True):
951
- ch = get_channel(channel_id)
952
- if not ch:
953
- return bool(default)
954
- return bool(ch.get("bold_publish", default))
955
-
956
- def record_source_event(source_id, event_type, reason="", message_id=None, target_count=0):
957
- sid = str(source_id)
958
- with lock:
959
- data = _read()
960
- stats = data.setdefault("source_stats", {}).setdefault(sid, {
961
- "received": 0, "published": 0, "rejected": 0, "ignored": 0,
962
- "duplicates": 0, "errors": 0, "last_message_id": None,
963
- "last_event": "", "last_reason": "", "last_ts": None
964
- })
965
- event_type = str(event_type or "").lower()
966
- if event_type == "received":
967
- stats["received"] = int(stats.get("received", 0)) + 1
968
- elif event_type == "published":
969
- stats["published"] = int(stats.get("published", 0)) + 1
970
- elif event_type == "rejected":
971
- stats["rejected"] = int(stats.get("rejected", 0)) + 1
972
- elif event_type == "duplicate":
973
- stats["duplicates"] = int(stats.get("duplicates", 0)) + 1
974
- stats["ignored"] = int(stats.get("ignored", 0)) + 1
975
- elif event_type == "error":
976
- stats["errors"] = int(stats.get("errors", 0)) + 1
977
- else:
978
- stats["ignored"] = int(stats.get("ignored", 0)) + 1
979
- stats["last_message_id"] = message_id
980
- stats["last_event"] = event_type
981
- stats["last_reason"] = str(reason or "")[:300]
982
- stats["last_ts"] = _now()
983
- data["source_stats"][sid] = stats
984
-
985
- logs = data.setdefault("source_logs", {}).setdefault(sid, [])
986
- logs.append({
987
- "ts": _now(), "event": event_type, "reason": str(reason or "")[:300],
988
- "message_id": message_id, "target_count": int(target_count or 0)
989
- })
990
- data["source_logs"][sid] = logs[-20:]
991
- _write(data)
992
- return True
993
-
994
-
995
- def get_source_stats(source_id):
996
- sid = str(source_id)
997
- with lock:
998
- data = _read()
999
- return data.get("source_stats", {}).get(sid, {
1000
- "received": 0, "published": 0, "rejected": 0, "ignored": 0,
1001
- "duplicates": 0, "errors": 0, "last_message_id": None,
1002
- "last_event": "", "last_reason": "", "last_ts": None
1003
- })
1004
-
1005
-
1006
- def get_source_logs(source_id, limit=20):
1007
- sid = str(source_id)
1008
- with lock:
1009
- data = _read()
1010
- logs = data.get("source_logs", {}).get(sid, [])
1011
- if not isinstance(logs, list):
1012
- return []
1013
- return logs[-int(limit):]
1014
-
1015
-
1016
- def copy_source_settings(from_source_id, to_source_ids):
1017
- from_sid = str(from_source_id)
1018
- copied = 0
1019
- with lock:
1020
- data = _read()
1021
- source_meta = _normalize_source_meta(from_source_id, data.setdefault("source_meta", {}).get(from_sid, {}))
1022
- keys = ["remove_terms", "remove_emoji", "content_types", "paused"]
1023
- for dst in to_source_ids or []:
1024
- sid = str(dst)
1025
- meta = _normalize_source_meta(dst, data.setdefault("source_meta", {}).get(sid, {}))
1026
- for key in keys:
1027
- if key in source_meta:
1028
- # copy JSON-compatible value
1029
- meta[key] = json.loads(json.dumps(source_meta[key], ensure_ascii=False))
1030
- data["source_meta"][sid] = meta
1031
- copied += 1
1032
- _write(data)
1033
- if copied:
1034
- _write_backup(data)
1035
- return copied
1036
-
1037
-
1038
- def set_system_value(key, value):
1039
- with lock:
1040
- data = _read()
1041
- data.setdefault("system", {})[str(key)] = value
1042
- _write(data)
1043
- return True
1044
-
1045
-
1046
- def get_system_value(key, default=None):
1047
- with lock:
1048
- data = _read()
1049
- return data.get("system", {}).get(str(key), default)
1050
-
1051
-
1052
- # ===== Professional safety/ops additions =====
1053
- def is_maintenance_mode():
1054
- with lock:
1055
- data = _read()
1056
- return bool(data.get("system", {}).get("maintenance_mode", False))
1057
-
1058
-
1059
- def set_maintenance_mode(enabled):
1060
- with lock:
1061
- data = _read()
1062
- data.setdefault("system", {})["maintenance_mode"] = bool(enabled)
1063
- data["system"]["maintenance_updated_at"] = _now()
1064
- _write(data)
1065
- return True
1066
-
1067
-
1068
- def add_last_error(context, error):
1069
- with lock:
1070
- data = _read()
1071
- errors = data.setdefault("last_errors", [])
1072
- if not isinstance(errors, list):
1073
- errors = []
1074
- errors.append({
1075
- "ts": _now(),
1076
- "context": str(context or "")[:120],
1077
- "error": str(error or "")[:500],
1078
- })
1079
- data["last_errors"] = errors[-20:]
1080
- data.setdefault("system", {})["last_error"] = f"{context}: {error}"[:600]
1081
- data["system"]["last_error_ts"] = _now()
1082
- _write(data)
1083
- return True
1084
-
1085
-
1086
- def get_last_errors(limit=20):
1087
- with lock:
1088
- data = _read()
1089
- errors = data.get("last_errors", [])
1090
- if not isinstance(errors, list):
1091
- return []
1092
- return errors[-int(limit):]
1093
-
1094
-
1095
- def clear_last_errors():
1096
- with lock:
1097
- data = _read()
1098
- data["last_errors"] = []
1099
- data.setdefault("system", {})["last_error"] = ""
1100
- _write(data)
1101
- return True
1102
-
1103
-
1104
- def _normalize_quote_types(value=None, fallback=False):
1105
- if not isinstance(value, dict):
1106
- value = {}
1107
- return {
1108
- "text": bool(value.get("text", fallback)),
1109
- "photo": bool(value.get("photo", fallback)),
1110
- "video": bool(value.get("video", fallback)),
1111
- "album": bool(value.get("album", fallback)),
1112
- }
1113
-
1114
-
1115
- def set_channel_quote_publish(channel_id, enabled=True):
1116
- # المفتاح القديم: يبدّل كل الأنواع مرة واحدة للتوافق فقط.
1117
- cid = str(channel_id)
1118
- enabled = bool(enabled)
1119
- with lock:
1120
- data = _read()
1121
- if cid not in data.get("channels", {}):
1122
- return False
1123
- data["channels"][cid]["quote_types"] = _normalize_quote_types({}, enabled)
1124
- data["channels"][cid]["quote_publish"] = enabled
1125
- _write(data)
1126
- _write_backup(data)
1127
- return True
1128
-
1129
-
1130
- def get_channel_quote_publish(channel_id, default=False):
1131
- ch = get_channel(channel_id)
1132
- if not ch:
1133
- return bool(default)
1134
- qt = _normalize_quote_types(ch.get("quote_types"), ch.get("quote_publish", default))
1135
- return any(qt.values())
1136
-
1137
-
1138
- def get_channel_quote_types(channel_id):
1139
- ch = get_channel(channel_id)
1140
- if not ch:
1141
- return _normalize_quote_types({}, False)
1142
- return _normalize_quote_types(ch.get("quote_types"), ch.get("quote_publish", False))
1143
-
1144
-
1145
- def get_channel_quote_type(channel_id, content_type="text", default=False):
1146
- ctype = str(content_type or "text")
1147
- if ctype not in {"text", "photo", "video", "album"}:
1148
- ctype = "text"
1149
- return bool(get_channel_quote_types(channel_id).get(ctype, default))
1150
-
1151
-
1152
- def set_channel_quote_type(channel_id, content_type, enabled=True):
1153
- cid = str(channel_id)
1154
- ctype = str(content_type or "text")
1155
- if ctype not in {"text", "photo", "video", "album"}:
1156
- return False
1157
- with lock:
1158
- data = _read()
1159
- if cid not in data.get("channels", {}):
1160
- return False
1161
- ch = data["channels"][cid]
1162
- qt = _normalize_quote_types(ch.get("quote_types"), ch.get("quote_publish", False))
1163
- qt[ctype] = bool(enabled)
1164
- ch["quote_types"] = qt
1165
- ch["quote_publish"] = any(qt.values())
1166
- _write(data)
1167
- _write_backup(data)
1168
- return True
1169
-
1170
-
1171
- def get_channel_hashtags(channel_id):
1172
- ch = get_channel(channel_id)
1173
- if not ch:
1174
- return []
1175
- tags = ch.get("hashtags", [])
1176
- if not isinstance(tags, list):
1177
- return []
1178
- out = []
1179
- seen = set()
1180
- for tag in tags:
1181
- tag = str(tag).strip()
1182
- if not tag:
1183
- continue
1184
- if not tag.startswith("#"):
1185
- tag = "#" + tag.lstrip("#")
1186
- key = tag.lower()
1187
- if key not in seen:
1188
- seen.add(key)
1189
- out.append(tag)
1190
- return out
1191
-
1192
-
1193
- def add_channel_hashtags(channel_id, tags):
1194
- clean = []
1195
- for tag in tags or []:
1196
- tag = str(tag).strip()
1197
- if not tag:
1198
- continue
1199
- if not tag.startswith("#"):
1200
- tag = "#" + tag.lstrip("#")
1201
- clean.append(tag)
1202
- if not clean:
1203
- return {"added": 0, "exists": 0}
1204
- cid = str(channel_id)
1205
- with lock:
1206
- data = _read()
1207
- if cid not in data["channels"]:
1208
- return {"added": 0, "exists": 0}
1209
- existing = []
1210
- for tag in data["channels"][cid].get("hashtags", []):
1211
- tag = str(tag).strip()
1212
- if tag:
1213
- existing.append(tag if tag.startswith("#") else "#" + tag.lstrip("#"))
1214
- keys = {x.lower() for x in existing}
1215
- added = 0
1216
- exists = 0
1217
- for tag in clean:
1218
- key = tag.lower()
1219
- if key in keys:
1220
- exists += 1
1221
- continue
1222
- existing.append(tag)
1223
- keys.add(key)
1224
- added += 1
1225
- data["channels"][cid]["hashtags"] = existing
1226
- _write(data)
1227
- if added:
1228
- _write_backup(data)
1229
- return {"added": added, "exists": exists}
1230
-
1231
-
1232
- def remove_channel_hashtags(channel_id, tags):
1233
- remove_keys = set()
1234
- for tag in tags or []:
1235
- tag = str(tag).strip()
1236
- if not tag:
1237
- continue
1238
- if not tag.startswith("#"):
1239
- tag = "#" + tag.lstrip("#")
1240
- remove_keys.add(tag.lower())
1241
- if not remove_keys:
1242
- return {"removed": 0, "missing": 0}
1243
- cid = str(channel_id)
1244
- with lock:
1245
- data = _read()
1246
- if cid not in data["channels"]:
1247
- return {"removed": 0, "missing": len(remove_keys)}
1248
- existing = []
1249
- for tag in data["channels"][cid].get("hashtags", []):
1250
- tag = str(tag).strip()
1251
- if tag:
1252
- existing.append(tag if tag.startswith("#") else "#" + tag.lstrip("#"))
1253
- before = len(existing)
1254
- existing = [x for x in existing if x.lower() not in remove_keys]
1255
- removed = before - len(existing)
1256
- data["channels"][cid]["hashtags"] = existing
1257
- _write(data)
1258
- if removed:
1259
- _write_backup(data)
1260
- return {"removed": removed, "missing": max(0, len(remove_keys)-removed)}
1261
-
1262
-
1263
- def record_channel_publish_success(channel_id):
1264
- cid = str(channel_id)
1265
- with lock:
1266
- data = _read()
1267
- if cid in data.get("channels", {}):
1268
- data["channels"][cid]["fail_count"] = 0
1269
- data.setdefault("channel_failures", {})[cid] = 0
1270
- _write(data)
1271
- return True
1272
-
1273
-
1274
- def record_channel_publish_failure(channel_id, error="", limit=5):
1275
- cid = str(channel_id)
1276
- with lock:
1277
- data = _read()
1278
- failures = data.setdefault("channel_failures", {})
1279
- count = int(failures.get(cid, 0) or 0) + 1
1280
- failures[cid] = count
1281
- if cid in data.get("channels", {}):
1282
- data["channels"][cid]["fail_count"] = count
1283
- if count >= int(limit):
1284
- data["channels"][cid]["paused"] = True
1285
- data["channels"][cid]["auto_paused_reason"] = str(error or "")[:300]
1286
- data["channels"][cid]["auto_paused_at"] = _now()
1287
- errors = data.setdefault("last_errors", [])
1288
- errors.append({"ts": _now(), "context": f"publish channel {cid}", "error": str(error or "")[:500]})
1289
- data["last_errors"] = errors[-20:]
1290
- _write(data)
1291
- return count
1292
-
1293
-
1294
- def create_named_backup(name):
1295
- name = str(name or "").strip()
1296
- if not name:
1297
- name = f"backup_{_now()}"
1298
- safe = "".join(ch for ch in name if ch.isalnum() or ch in ("_", "-", ".", " ")).strip().replace(" ", "_")
1299
- if not safe:
1300
- safe = f"backup_{_now()}"
1301
- with lock:
1302
- data = _read()
1303
- os.makedirs(BACKUP_DIR, exist_ok=True)
1304
- path = os.path.join(BACKUP_DIR, f"manual_{safe}_{_now()}.json")
1305
- with open(path, "w", encoding="utf-8") as f:
1306
- json.dump(_normalize_data(data), f, ensure_ascii=False, indent=2)
1307
- named = data.setdefault("named_backups", [])
1308
- named.append({"name": name, "file": path, "ts": _now()})
1309
- data["named_backups"] = named[-30:]
1310
- _write(data)
1311
- return path
1312
-
1313
-
1314
- def get_named_backups():
1315
- with lock:
1316
- data = _read()
1317
- items = data.get("named_backups", [])
1318
- return items if isinstance(items, list) else []
1319
-
1320
-
1321
- # ===== Published message tracking for channel cleanup =====
1322
- def record_published_message(channel_id, message_id, content_type):
1323
- """يحفظ ID الرسالة التي نشرها البوت حتى يمكن حذفها لاحقاً حسب النوع."""
1324
- if not message_id:
1325
- return False
1326
- cid = str(channel_id)
1327
- ctype = str(content_type or "text")
1328
- if ctype not in {"text", "photo", "video", "album"}:
1329
- ctype = "photo"
1330
- with lock:
1331
- data = _read()
1332
- box = data.setdefault("published_messages", {}).setdefault(cid, {}).setdefault(ctype, [])
1333
- mid = int(message_id)
1334
- if not any(isinstance(x, dict) and int(x.get("id", -1)) == mid for x in box):
1335
- box.append({"id": mid, "ts": _now()})
1336
- data["published_messages"][cid][ctype] = box[-1000:]
1337
- _write(data)
1338
- return True
1339
-
1340
-
1341
- def record_published_messages(channel_id, message_ids, content_type):
1342
- count = 0
1343
- for mid in message_ids or []:
1344
- if record_published_message(channel_id, mid, content_type):
1345
- count += 1
1346
- return count
1347
-
1348
-
1349
- def get_published_message_ids(channel_id, content_type):
1350
- cid = str(channel_id)
1351
- ctype = str(content_type or "")
1352
- with lock:
1353
- data = _read()
1354
- entries = data.get("published_messages", {}).get(cid, {}).get(ctype, [])
1355
- ids = []
1356
- for item in entries:
1357
- try:
1358
- ids.append(int(item.get("id") if isinstance(item, dict) else item))
1359
- except Exception:
1360
- pass
1361
- return ids
1362
-
1363
-
1364
- def clear_published_message_ids(channel_id, content_type, message_ids=None):
1365
- cid = str(channel_id)
1366
- ctype = str(content_type or "")
1367
- remove_set = None
1368
- if message_ids is not None:
1369
- remove_set = {int(x) for x in message_ids if str(x).lstrip("-").isdigit()}
1370
- with lock:
1371
- data = _read()
1372
- entries = data.setdefault("published_messages", {}).setdefault(cid, {}).setdefault(ctype, [])
1373
- if remove_set is None:
1374
- removed = len(entries)
1375
- data["published_messages"][cid][ctype] = []
1376
- else:
1377
- before = len(entries)
1378
- data["published_messages"][cid][ctype] = [
1379
- x for x in entries
1380
- if int(x.get("id") if isinstance(x, dict) else x) not in remove_set
1381
- ]
1382
- removed = before - len(data["published_messages"][cid][ctype])
1383
- _write(data)
1384
- return removed
1385
-
1386
-
1387
- def get_ignore_short_posts():
1388
- with lock:
1389
- data = _read()
1390
- return bool(data.get("settings", {}).get("ignore_short_posts", False))
1391
-
1392
-
1393
- def set_ignore_short_posts(enabled):
1394
- with lock:
1395
- data = _read()
1396
- data.setdefault("settings", {})["ignore_short_posts"] = bool(enabled)
1397
- _write(data)
1398
- _write_backup(data)
1399
- return True
1400
-
1401
-
1402
- # ============================================================
1403
- # Link Preview: per-channel disable
1404
- # ============================================================
1405
-
1406
- def get_channel_disable_preview(channel_id, default=False):
1407
- ch = get_channel(channel_id)
1408
- if not ch:
1409
- return bool(default)
1410
- return bool(ch.get("disable_web_page_preview", default))
1411
-
1412
-
1413
- def set_channel_disable_preview(channel_id, enabled):
1414
- return update_channel(channel_id, "disable_web_page_preview", bool(enabled))
1415
-
1416
-
1417
- # ============================================================
1418
- # Notification Center Settings
1419
- # ============================================================
1420
-
1421
- NOTIFICATION_TYPES = {
1422
- "session_stopped": "توقف Session",
1423
- "ai_key_error": "خطأ في مفتاح AI",
1424
- "source_stopped": "توقف مصدر",
1425
- "channel_idle_hour": "قناة لم تنشر منذ ساعة",
1426
- "backup_failed": "فشل Backup",
1427
- "db_issue": "مشكلة بقاعدة البيانات",
1428
- }
1429
-
1430
-
1431
- def get_notification_settings():
1432
- with lock:
1433
- data = _read()
1434
- ns = data.get("notification_settings", {})
1435
- return {k: bool(ns.get(k, True)) for k in NOTIFICATION_TYPES}
1436
-
1437
-
1438
- def set_notification_setting(key, enabled):
1439
- if key not in NOTIFICATION_TYPES:
1440
- return False
1441
- with lock:
1442
- data = _read()
1443
- ns = data.setdefault("notification_settings", {})
1444
- ns[str(key)] = bool(enabled)
1445
- _write(data)
1446
- return True
1447
-
1448
-
1449
- def get_notification_last_alert(key):
1450
- with lock:
1451
- data = _read()
1452
- ns = data.get("notification_settings", {})
1453
- return ns.get("last_alert_ts", {}).get(str(key), 0)
1454
-
1455
-
1456
- def set_notification_last_alert(key, ts=None):
1457
- if ts is None:
1458
- ts = _now()
1459
- with lock:
1460
- data = _read()
1461
- ns = data.setdefault("notification_settings", {})
1462
- alerts = ns.setdefault("last_alert_ts", {})
1463
- alerts[str(key)] = int(ts)
1464
- _write(data)
1465
- return True
1466
-
1467
-
1468
- # ============================================================
1469
- # Multi-Bot Expansion: Sessions
1470
- # ============================================================
1471
-
1472
- def _normalize_session(sid, value):
1473
- if not isinstance(value, dict):
1474
- value = {}
1475
- sid = str(sid)
1476
- value.setdefault("id", sid)
1477
- value.setdefault("name", value.get("name") or f"Session {sid.split('_')[-1]}")
1478
- value.setdefault("api_id", 0)
1479
- value.setdefault("api_hash", "")
1480
- value.setdefault("session_string", "")
1481
- value.setdefault("enabled", True)
1482
- value.setdefault("created_at", _now())
1483
- value.setdefault("last_used", None)
1484
- value.setdefault("usage_count", 0)
1485
- value.setdefault("error_count", 0)
1486
- value.setdefault("status", "idle")
1487
- value.setdefault("channels_using", [])
1488
- return value
1489
-
1490
-
1491
- def get_all_sessions():
1492
- with lock:
1493
- data = _read()
1494
- return [{"id": k, **v} for k, v in data.get("sessions", {}).items()]
1495
-
1496
-
1497
- def get_session(session_id):
1498
- sid = str(session_id)
1499
- with lock:
1500
- data = _read()
1501
- raw = data.get("sessions", {}).get(sid)
1502
- if raw is None:
1503
- return None
1504
- return {"id": sid, **raw}
1505
-
1506
-
1507
- def add_session(api_id, api_hash, session_string, name=None):
1508
- items = get_all_sessions()
1509
- n = _find_available_number([s.get("name", "") for s in items], "Session")
1510
- final_name = name or f"Session {n}"
1511
- sid = f"session_{n}"
1512
- with lock:
1513
- data = _read()
1514
- if sid in data.get("sessions", {}):
1515
- return False
1516
- entry = _normalize_session(sid, {
1517
- "id": sid, "name": final_name,
1518
- "api_id": int(api_id), "api_hash": str(api_hash),
1519
- "session_string": str(session_string),
1520
- "enabled": True, "created_at": _now(),
1521
- })
1522
- data.setdefault("sessions", {})[sid] = entry
1523
- _write(data)
1524
- _write_backup(data)
1525
- return True
1526
-
1527
-
1528
- def update_session(session_id, **kwargs):
1529
- sid = str(session_id)
1530
- allowed = {"name", "api_id", "api_hash", "session_string", "enabled", "status"}
1531
- with lock:
1532
- data = _read()
1533
- entry = data.get("sessions", {}).get(sid)
1534
- if not entry:
1535
- return False
1536
- for k, v in kwargs.items():
1537
- if k in allowed and v is not None:
1538
- entry[k] = v
1539
- _write(data)
1540
- return True
1541
-
1542
-
1543
- def delete_session(session_id):
1544
- sid = str(session_id)
1545
- with lock:
1546
- data = _read()
1547
- entry = data.get("sessions", {}).pop(sid, None)
1548
- if entry is None:
1549
- return False
1550
- item = {"id": f"trash_session_{_now()}", "type": "session", "original_id": sid, "data": entry, "deleted_at": _now()}
1551
- data.setdefault("trash", []).append(item)
1552
- _write(data)
1553
- _write_backup(data)
1554
- return True
1555
-
1556
-
1557
- def set_session_enabled(session_id, enabled):
1558
- return update_session(session_id, enabled=bool(enabled))
1559
-
1560
-
1561
- def record_session_usage(session_id):
1562
- sid = str(session_id)
1563
- with lock:
1564
- data = _read()
1565
- entry = data.get("sessions", {}).get(sid)
1566
- if not entry:
1567
- return False
1568
- entry["last_used"] = _now()
1569
- entry["usage_count"] = int(entry.get("usage_count", 0)) + 1
1570
- _write(data)
1571
- return True
1572
-
1573
-
1574
- def get_session_stats(session_id):
1575
- s = get_session(session_id)
1576
- if not s:
1577
- return {}
1578
- return {
1579
- "usage_count": s.get("usage_count", 0),
1580
- "error_count": s.get("error_count", 0),
1581
- "last_used": s.get("last_used"),
1582
- "status": s.get("status", "idle"),
1583
- "enabled": s.get("enabled", True),
1584
- "name": s.get("name", ""),
1585
- }
1586
-
1587
-
1588
- # ============================================================
1589
- # Multi-Bot Expansion: AI Keys
1590
- # ============================================================
1591
-
1592
- def _normalize_ai_key(kid, value):
1593
- if not isinstance(value, dict):
1594
- value = {}
1595
- kid = str(kid)
1596
- value.setdefault("id", kid)
1597
- value.setdefault("name", value.get("name") or f"AI {kid.split('_')[-1]}")
1598
- value.setdefault("provider", "gemini")
1599
- value.setdefault("api_key", "")
1600
- value.setdefault("enabled", True)
1601
- value.setdefault("created_at", _now())
1602
- value.setdefault("last_used", None)
1603
- value.setdefault("usage_count", 0)
1604
- value.setdefault("error_count", 0)
1605
- value.setdefault("channels_using", [])
1606
- value.setdefault("models", ["gemini-pro"])
1607
- return value
1608
-
1609
-
1610
- def get_all_ai_keys():
1611
- with lock:
1612
- data = _read()
1613
- return [{"id": k, **v} for k, v in data.get("ai_keys", {}).items()]
1614
-
1615
-
1616
- def get_ai_key(key_id):
1617
- kid = str(key_id)
1618
- with lock:
1619
- data = _read()
1620
- raw = data.get("ai_keys", {}).get(kid)
1621
- return {"id": kid, **raw} if raw else None
1622
-
1623
-
1624
- def add_ai_key(provider, api_key, name=None):
1625
- items = get_all_ai_keys()
1626
- n = _find_available_number([k.get("name", "") for k in items], "AI")
1627
- final_name = name or f"AI {n}"
1628
- kid = f"ai_{n}"
1629
- with lock:
1630
- data = _read()
1631
- if kid in data.get("ai_keys", {}):
1632
- return False
1633
- entry = _normalize_ai_key(kid, {
1634
- "id": kid, "name": final_name,
1635
- "provider": str(provider), "api_key": str(api_key),
1636
- "enabled": True, "created_at": _now(),
1637
- })
1638
- data.setdefault("ai_keys", {})[kid] = entry
1639
- _write(data)
1640
- _write_backup(data)
1641
- return True
1642
-
1643
-
1644
- def update_ai_key(key_id, **kwargs):
1645
- kid = str(key_id)
1646
- allowed = {"name", "provider", "api_key", "enabled", "models"}
1647
- with lock:
1648
- data = _read()
1649
- entry = data.get("ai_keys", {}).get(kid)
1650
- if not entry:
1651
- return False
1652
- for k, v in kwargs.items():
1653
- if k in allowed and v is not None:
1654
- entry[k] = v
1655
- _write(data)
1656
- return True
1657
-
1658
-
1659
- def delete_ai_key(key_id):
1660
- kid = str(key_id)
1661
- with lock:
1662
- data = _read()
1663
- entry = data.get("ai_keys", {}).pop(kid, None)
1664
- if entry is None:
1665
- return False
1666
- item = {"id": f"trash_ai_{_now()}", "type": "ai_key", "original_id": kid, "data": entry, "deleted_at": _now()}
1667
- data.setdefault("trash", []).append(item)
1668
- _write(data)
1669
- _write_backup(data)
1670
- return True
1671
-
1672
-
1673
- def set_ai_key_enabled(key_id, enabled):
1674
- return update_ai_key(key_id, enabled=bool(enabled))
1675
-
1676
-
1677
- def record_ai_key_usage(key_id):
1678
- kid = str(key_id)
1679
- with lock:
1680
- data = _read()
1681
- entry = data.get("ai_keys", {}).get(kid)
1682
- if not entry:
1683
- return False
1684
- entry["last_used"] = _now()
1685
- entry["usage_count"] = int(entry.get("usage_count", 0)) + 1
1686
- _write(data)
1687
- return True
1688
-
1689
-
1690
- def get_ai_key_stats(key_id):
1691
- k = get_ai_key(key_id)
1692
- if not k:
1693
- return {}
1694
- return {
1695
- "provider": k.get("provider", ""),
1696
- "usage_count": k.get("usage_count", 0),
1697
- "error_count": k.get("error_count", 0),
1698
- "last_used": k.get("last_used"),
1699
- "enabled": k.get("enabled", True),
1700
- "name": k.get("name", ""),
1701
- }
1702
-
1703
-
1704
- # ============================================================
1705
- # Multi-Bot Expansion: Publishing Bots
1706
- # ============================================================
1707
-
1708
- def _normalize_publishing_bot(bid, value):
1709
- if not isinstance(value, dict):
1710
- value = {}
1711
- bid = str(bid)
1712
- value.setdefault("id", bid)
1713
- value.setdefault("name", value.get("name") or f"Bot {bid.split('_')[-1]}")
1714
- value.setdefault("token", "")
1715
- value.setdefault("username", "")
1716
- value.setdefault("enabled", True)
1717
- value.setdefault("created_at", _now())
1718
- value.setdefault("last_publish", None)
1719
- value.setdefault("publish_count", 0)
1720
- value.setdefault("error_count", 0)
1721
- value.setdefault("channels_using", [])
1722
- return value
1723
-
1724
-
1725
- def get_all_publishing_bots():
1726
- with lock:
1727
- data = _read()
1728
- return [{"id": k, **v} for k, v in data.get("publishing_bots", {}).items()]
1729
-
1730
-
1731
- def get_publishing_bot(bot_id):
1732
- bid = str(bot_id)
1733
- with lock:
1734
- data = _read()
1735
- raw = data.get("publishing_bots", {}).get(bid)
1736
- return {"id": bid, **raw} if raw else None
1737
-
1738
-
1739
- def add_publishing_bot(token, username="", name=None):
1740
- items = get_all_publishing_bots()
1741
- n = _find_available_number([b.get("name", "") for b in items], "Bot")
1742
- final_name = name or f"Bot {n}"
1743
- bid = f"bot_{n}"
1744
- with lock:
1745
- data = _read()
1746
- if bid in data.get("publishing_bots", {}):
1747
- return False
1748
- entry = _normalize_publishing_bot(bid, {
1749
- "id": bid, "name": final_name,
1750
- "token": str(token), "username": str(username),
1751
- "enabled": True, "created_at": _now(),
1752
- })
1753
- data.setdefault("publishing_bots", {})[bid] = entry
1754
- _write(data)
1755
- _write_backup(data)
1756
- return True
1757
-
1758
-
1759
- def update_publishing_bot(bot_id, **kwargs):
1760
- bid = str(bot_id)
1761
- allowed = {"name", "token", "username", "enabled"}
1762
- with lock:
1763
- data = _read()
1764
- entry = data.get("publishing_bots", {}).get(bid)
1765
- if not entry:
1766
- return False
1767
- for k, v in kwargs.items():
1768
- if k in allowed and v is not None:
1769
- entry[k] = v
1770
- _write(data)
1771
- return True
1772
-
1773
-
1774
- def delete_publishing_bot(bot_id):
1775
- bid = str(bot_id)
1776
- with lock:
1777
- data = _read()
1778
- entry = data.get("publishing_bots", {}).pop(bid, None)
1779
- if entry is None:
1780
- return False
1781
- item = {"id": f"trash_bot_{_now()}", "type": "publishing_bot", "original_id": bid, "data": entry, "deleted_at": _now()}
1782
- data.setdefault("trash", []).append(item)
1783
- _write(data)
1784
- _write_backup(data)
1785
- return True
1786
-
1787
-
1788
- def set_publishing_bot_enabled(bot_id, enabled):
1789
- return update_publishing_bot(bot_id, enabled=bool(enabled))
1790
-
1791
-
1792
- def record_bot_publish(bot_id, content_type="text"):
1793
- bid = str(bot_id)
1794
- ctype = str(content_type or "text")
1795
- if ctype not in ("text", "photo", "video", "album"):
1796
- ctype = "text"
1797
- with lock:
1798
- data = _read()
1799
- entry = data.get("publishing_bots", {}).get(bid)
1800
- if not entry:
1801
- return False
1802
- entry["last_publish"] = _now()
1803
- entry["publish_count"] = int(entry.get("publish_count", 0)) + 1
1804
- stats = entry.setdefault("stats", {})
1805
- stats[ctype] = int(stats.get(ctype, 0)) + 1
1806
- _write(data)
1807
- return True
1808
-
1809
-
1810
- # ============================================================
1811
- # Bot-Channel Verification
1812
- # ============================================================
1813
-
1814
- def _normalize_verification(key, value):
1815
- if not isinstance(value, dict):
1816
- value = {}
1817
- value.setdefault("verified", False)
1818
- value.setdefault("can_post", False)
1819
- value.setdefault("status", "")
1820
- value.setdefault("permissions", {})
1821
- value.setdefault("last_check", 0)
1822
- value.setdefault("bot_name", "")
1823
- value.setdefault("channel_name", "")
1824
- return value
1825
-
1826
-
1827
- def set_bot_channel_verification(bot_id, channel_id, verified, can_post=False, status="", permissions=None, bot_name="", channel_name=""):
1828
- """تخزين نتيجة التحقق من وجود بوت في قناة."""
1829
- key = f"{bot_id}|{channel_id}"
1830
- with lock:
1831
- data = _read()
1832
- mapping = data.setdefault("bot_channel_verified", {})
1833
- entry = _normalize_verification(key, mapping.get(key, {}))
1834
- entry["verified"] = bool(verified)
1835
- entry["can_post"] = bool(can_post)
1836
- entry["status"] = str(status)
1837
- entry["permissions"] = dict(permissions or {})
1838
- entry["last_check"] = _now()
1839
- entry["bot_name"] = str(bot_name)
1840
- entry["channel_name"] = str(channel_name)
1841
- mapping[key] = entry
1842
- _write(data)
1843
- return True
1844
-
1845
-
1846
- def get_bot_channel_verification(bot_id, channel_id):
1847
- """إرجاع حالة التحقق المخزنة لبوت في قناة."""
1848
- key = f"{bot_id}|{channel_id}"
1849
- with lock:
1850
- data = _read()
1851
- entry = data.get("bot_channel_verified", {}).get(key)
1852
- return _normalize_verification(key, entry)
1853
-
1854
-
1855
- def get_all_bot_channel_verifications():
1856
- """إرجاع كل حالات التحقق."""
1857
- with lock:
1858
- data = _read()
1859
- return {k: _normalize_verification(k, v) for k, v in data.get("bot_channel_verified", {}).items()}
1860
-
1861
-
1862
- def get_verifications_for_bot(bot_id):
1863
- """إرجاع كل التحققات لبوت معين."""
1864
- result = {}
1865
- prefix = f"{bot_id}|"
1866
- for k, v in get_all_bot_channel_verifications().items():
1867
- if k.startswith(prefix):
1868
- ch_id = k[len(prefix):]
1869
- result[ch_id] = v
1870
- return result
1871
-
1872
-
1873
- def get_verifications_for_channel(channel_id):
1874
- """إرجاع كل التحققات لقناة معينة."""
1875
- result = {}
1876
- suffix = f"|{channel_id}"
1877
- for k, v in get_all_bot_channel_verifications().items():
1878
- if k.endswith(suffix):
1879
- bot_id = k[:-len(suffix)]
1880
- result[bot_id] = v
1881
- return result
1882
-
1883
-
1884
- # ============================================================
1885
- # Multi-Bot Expansion: Website Sources
1886
- # ============================================================
1887
-
1888
- def _normalize_website(wid, value):
1889
- if not isinstance(value, dict):
1890
- value = {}
1891
- wid = str(wid)
1892
- value.setdefault("id", wid)
1893
- value.setdefault("name", value.get("name") or f"Website {wid.split('_')[-1]}")
1894
- value.setdefault("url", "")
1895
- value.setdefault("enabled", True)
1896
- value.setdefault("selector", "body")
1897
- value.setdefault("interval", 300)
1898
- value.setdefault("created_at", _now())
1899
- value.setdefault("last_fetch", None)
1900
- value.setdefault("error_count", 0)
1901
- value.setdefault("channels_using", [])
1902
- return value
1903
-
1904
-
1905
- def get_all_websites():
1906
- with lock:
1907
- data = _read()
1908
- return [{"id": k, **v} for k, v in data.get("websites", {}).items()]
1909
-
1910
-
1911
- def get_website(website_id):
1912
- wid = str(website_id)
1913
- with lock:
1914
- data = _read()
1915
- raw = data.get("websites", {}).get(wid)
1916
- return {"id": wid, **raw} if raw else None
1917
-
1918
-
1919
- def add_website(url, name=None, selector="body"):
1920
- items = get_all_websites()
1921
- n = _find_available_number([w.get("name", "") for w in items], "Website")
1922
- final_name = name or f"Website {n}"
1923
- wid = f"web_{n}"
1924
- with lock:
1925
- data = _read()
1926
- if wid in data.get("websites", {}):
1927
- return False
1928
- entry = _normalize_website(wid, {
1929
- "id": wid, "name": final_name,
1930
- "url": str(url), "selector": str(selector),
1931
- "enabled": True, "created_at": _now(),
1932
- })
1933
- data.setdefault("websites", {})[wid] = entry
1934
- _write(data)
1935
- _write_backup(data)
1936
- return True
1937
-
1938
-
1939
- def update_website(website_id, **kwargs):
1940
- wid = str(website_id)
1941
- allowed = {"name", "url", "enabled", "selector", "interval"}
1942
- with lock:
1943
- data = _read()
1944
- entry = data.get("websites", {}).get(wid)
1945
- if not entry:
1946
- return False
1947
- for k, v in kwargs.items():
1948
- if k in allowed and v is not None:
1949
- entry[k] = v
1950
- _write(data)
1951
- return True
1952
-
1953
-
1954
- def delete_website(website_id):
1955
- wid = str(website_id)
1956
- with lock:
1957
- data = _read()
1958
- entry = data.get("websites", {}).pop(wid, None)
1959
- if entry is None:
1960
- return False
1961
- item = {"id": f"trash_web_{_now()}", "type": "website", "original_id": wid, "data": entry, "deleted_at": _now()}
1962
- data.setdefault("trash", []).append(item)
1963
- _write(data)
1964
- _write_backup(data)
1965
- return True
1966
-
1967
-
1968
- def set_website_enabled(website_id, enabled):
1969
- return update_website(website_id, enabled=bool(enabled))
1970
-
1971
-
1972
- # ============================================================
1973
- # Multi-Bot Expansion: Trash System
1974
- # ============================================================
1975
-
1976
- def get_trash_items():
1977
- with lock:
1978
- data = _read()
1979
- items = data.get("trash", [])
1980
- return items if isinstance(items, list) else []
1981
-
1982
-
1983
- def restore_from_trash(trash_id):
1984
- with lock:
1985
- data = _read()
1986
- items = data.get("trash", [])
1987
- for idx, item in enumerate(items):
1988
- if item.get("id") == trash_id:
1989
- orig_type = item.get("type")
1990
- orig_id = item.get("original_id")
1991
- orig_data = item.get("data", {})
1992
- if orig_type == "session":
1993
- data.setdefault("sessions", {})[orig_id] = orig_data
1994
- elif orig_type == "ai_key":
1995
- data.setdefault("ai_keys", {})[orig_id] = orig_data
1996
- elif orig_type == "publishing_bot":
1997
- data.setdefault("publishing_bots", {})[orig_id] = orig_data
1998
- elif orig_type == "website":
1999
- data.setdefault("websites", {})[orig_id] = orig_data
2000
- else:
2001
- return False
2002
- items.pop(idx)
2003
- data["trash"] = items
2004
- _write(data)
2005
- _write_backup(data)
2006
- return True
2007
- return False
2008
-
2009
-
2010
- def permanent_delete_from_trash(trash_id):
2011
- with lock:
2012
- data = _read()
2013
- items = data.get("trash", [])
2014
- for idx, item in enumerate(items):
2015
- if item.get("id") == trash_id:
2016
- items.pop(idx)
2017
- data["trash"] = items
2018
- _write(data)
2019
- return True
2020
- return False
2021
-
2022
-
2023
- def empty_trash():
2024
- with lock:
2025
- data = _read()
2026
- data["trash"] = []
2027
- _write(data)
2028
- return True
2029
-
2030
-
2031
- # ============================================================
2032
- # Multi-Bot Expansion: Auto Naming
2033
- # ============================================================
2034
-
2035
- def _find_available_number(names, prefix):
2036
- used = set()
2037
- for name in names:
2038
- if name.startswith(prefix):
2039
- try:
2040
- num = int(name[len(prefix):].strip())
2041
- used.add(num)
2042
- except ValueError:
2043
- pass
2044
- n = 1
2045
- while n in used:
2046
- n += 1
2047
- return n
2048
-
2049
-
2050
- # ============================================================
2051
- # Multi-Bot Expansion: Channel Config Extensions
2052
- # ============================================================
2053
-
2054
- def _normalize_channel_config(cid, value):
2055
- if not isinstance(value, dict):
2056
- value = {}
2057
- cid = str(cid)
2058
- value.setdefault("title_quote", False)
2059
- value.setdefault("signature_quote", False)
2060
- value.setdefault("assigned_sessions", [])
2061
- value.setdefault("assigned_bots", [])
2062
- value.setdefault("assigned_ai", [])
2063
- value.setdefault("websites", [])
2064
- value.setdefault("rss_sources", [])
2065
- value.setdefault("prompt", "")
2066
- value.setdefault("first_comment", "")
2067
- value.setdefault("schedule", None)
2068
- return value
2069
-
2070
-
2071
- def get_channel_config(channel_id):
2072
- cid = str(channel_id)
2073
- with lock:
2074
- data = _read()
2075
- raw = data.get("channel_configs", {}).get(cid)
2076
- return _normalize_channel_config(cid, raw)
2077
-
2078
-
2079
- def update_channel_config(channel_id, **kwargs):
2080
- cid = str(channel_id)
2081
- allowed = {"title_quote", "signature_quote", "assigned_sessions", "assigned_bots", "assigned_ai", "websites", "rss_sources", "prompt", "first_comment", "schedule"}
2082
- with lock:
2083
- data = _read()
2084
- cfg = _normalize_channel_config(cid, data.setdefault("channel_configs", {}).get(cid, {}))
2085
- for k, v in kwargs.items():
2086
- if k in allowed and v is not None:
2087
- cfg[k] = v
2088
- data["channel_configs"][cid] = cfg
2089
- _write(data)
2090
- return True
2091
-
2092
-
2093
- def set_channel_title_quote(channel_id, enabled):
2094
- return update_channel_config(channel_id, title_quote=bool(enabled))
2095
-
2096
-
2097
- def get_channel_title_quote(channel_id):
2098
- cfg = get_channel_config(channel_id)
2099
- return bool(cfg.get("title_quote", False))
2100
-
2101
-
2102
- def set_channel_signature_quote(channel_id, enabled):
2103
- return update_channel_config(channel_id, signature_quote=bool(enabled))
2104
-
2105
-
2106
- def get_channel_signature_quote(channel_id):
2107
- cfg = get_channel_config(channel_id)
2108
- return bool(cfg.get("signature_quote", False))
2109
-
2110
-
2111
- # ============================================================
2112
- # Multi-Bot Expansion: Dependency Check
2113
- # ============================================================
2114
-
2115
- def get_dependencies_for(item_type, item_id):
2116
- cid = str(item_id)
2117
- result = []
2118
- for ch in get_all_channels():
2119
- ch_id = str(ch.get("id", ""))
2120
- cfg = get_channel_config(ch_id)
2121
- if item_type == "session":
2122
- if cid in [str(x) for x in cfg.get("assigned_sessions", [])]:
2123
- result.append(ch)
2124
- elif item_type == "ai_key":
2125
- if cid in [str(x) for x in cfg.get("assigned_ai", [])]:
2126
- result.append(ch)
2127
- elif item_type == "publishing_bot":
2128
- if cid in [str(x) for x in cfg.get("assigned_bots", [])]:
2129
- result.append(ch)
2130
- elif item_type == "website":
2131
- if cid in [str(x) for x in cfg.get("websites", [])]:
2132
- result.append(ch)
2133
- return result
2134
-
2135
-
2136
- # ============================================================
2137
- # Smart Cache System
2138
- # ============================================================
2139
-
2140
- CACHE_TTL = {
2141
- "bot_in_channel": 300, # 5 د للعمليات الحساسة
2142
- "channel_accessible": 600, # 10 د للتحقق من وجود القناة
2143
- "bot_token_valid": 3600, # 1 س لصحة التوكن
2144
- "session_valid": 600, # 10 د لصلاحية الجلسة
2145
- "ui_display": 900, # 15 د للعرض في الواجهات
2146
- }
2147
-
2148
- _verification_cache = {}
2149
- _cache_lock = Lock()
2150
-
2151
-
2152
- def cache_get(key):
2153
- """إرجاع قيمة مخبأة إذا كانت ضمن TTL."""
2154
- with _cache_lock:
2155
- entry = _verification_cache.get(key)
2156
- if entry is None:
2157
- return None
2158
- if time.time() - entry["ts"] < entry["ttl"]:
2159
- return entry["data"]
2160
- del _verification_cache[key]
2161
- return None
2162
-
2163
-
2164
- def cache_set(key, data, ttl=None):
2165
- """تخزين قيمة مع TTL."""
2166
- if ttl is None:
2167
- ttl = CACHE_TTL.get("ui_display", 900)
2168
- with _cache_lock:
2169
- _verification_cache[key] = {"data": data, "ts": time.time(), "ttl": ttl}
2170
-
2171
-
2172
- def cache_invalidate(key):
2173
- """حذف قيمة من الكاش."""
2174
- with _cache_lock:
2175
- _verification_cache.pop(key, None)
2176
-
2177
-
2178
- def cache_invalidate_bot(bot_id):
2179
- """مسح كل الكاش لبوت معين."""
2180
- with _cache_lock:
2181
- to_del = [k for k in _verification_cache if f"|{bot_id}|" in k or f"token_valid|{bot_id}" in k]
2182
- for k in to_del:
2183
- del _verification_cache[k]
2184
-
2185
-
2186
- def cache_invalidate_channel(channel_id):
2187
- """مسح كل الكاش لقناة معينة."""
2188
- with _cache_lock:
2189
- to_del = [k for k in _verification_cache if k.endswith(f"|{channel_id}") or k == f"channel|{channel_id}"]
2190
- for k in to_del:
2191
- del _verification_cache[k]
2192
-
2193
-
2194
- def cache_clear_expired():
2195
- """مسح القيم المنتهية."""
2196
- now = time.time()
2197
- with _cache_lock:
2198
- to_del = [k for k, v in _verification_cache.items() if now - v["ts"] >= v["ttl"]]
2199
- for k in to_del:
2200
- del _verification_cache[k]
2201
-
2202
-
2203
- # ============================================================
2204
- # Real-Time Verification Functions (Database Layer)
2205
- # ============================================================
2206
-
2207
- VERIFY_TTL_SHORT = 60 # 1 دقيقة
2208
- VERIFY_TTL_NORMAL = 300 # 5 دقائق
2209
-
2210
-
2211
- def get_fresh_bot_verification(bot_id, channel_id):
2212
- """إرجاع التحقق من الكاش فقط إذا كان حديثاً (أقل من TTL قصير)."""
2213
- key = f"verify|{bot_id}|{channel_id}"
2214
- return cache_get(key)
2215
-
2216
-
2217
- def set_fresh_bot_verification(bot_id, channel_id, result):
2218
- """تخزين نتيجة تحقق حديثة في الكاش."""
2219
- key = f"verify|{bot_id}|{channel_id}"
2220
- cache_set(key, result, ttl=VERIFY_TTL_SHORT)
2221
-
2222
-
2223
- def invalidate_bot_verification(bot_id, channel_id):
2224
- """مسح التحقق المخبأ لبوت في قناة."""
2225
- key = f"verify|{bot_id}|{channel_id}"
2226
- cache_invalidate(key)
2227
-
2228
-
2229
- # ============================================================
2230
- # Bot Manager - المصدر الوحيد لجميع Bot Tokens
2231
- # ============================================================
2232
-
2233
- class BotManager:
2234
- """يدير جميع بوتات النشر.
2235
-
2236
- - أي كود يحتاج توكن بوت يستخدم هذا المدير فقط.
2237
- - لا يسمح بالوصول المباشر إلى التوكن من أي مكان آخر.
2238
- - يوفر التوثيق والتخزين والربط مع القنوات.
2239
- """
2240
-
2241
- def __init__(self):
2242
- self._cache = {}
2243
-
2244
- # ---- المصدر الوحيد للتوكن ----
2245
- def get_token(self, bot_id):
2246
- """الطريقة الوحيدة في المشروع بأكمله للحصول على توكن بوت."""
2247
- b = get_publishing_bot(str(bot_id))
2248
- if not b:
2249
- return ""
2250
- return b.get("token", "")
2251
-
2252
- def get_bot(self, bot_id):
2253
- """إرجاع بيانات البوت كاملة (بدون ضمان إخفاء التوكن للاستخدام الداخلي)."""
2254
- return get_publishing_bot(str(bot_id))
2255
-
2256
- def get_all_bots(self):
2257
- """إرجاع جميع البوتات."""
2258
- return get_all_publishing_bots()
2259
-
2260
- def add_bot(self, token, username="", name=""):
2261
- """إضافة بوت جديد."""
2262
- return add_publishing_bot(token, username=username, name=name)
2263
-
2264
- def delete_bot(self, bot_id):
2265
- """حذف بوت ونقل إلى سلة المهملات."""
2266
- return delete_publishing_bot(str(bot_id))
2267
-
2268
- def update_bot(self, bot_id, **kwargs):
2269
- """تحديث بيانات بوت."""
2270
- return update_publishing_bot(str(bot_id), **kwargs)
2271
-
2272
- def set_enabled(self, bot_id, enabled):
2273
- """تشغيل/إيقاف بوت."""
2274
- return set_publishing_bot_enabled(str(bot_id), enabled)
2275
-
2276
- def record_publish(self, bot_id, content_type="text"):
2277
- """تسجيل عملية نشر لبوت."""
2278
- return record_bot_publish(str(bot_id), content_type)
2279
-
2280
- def validate_token_format(self, token):
2281
- """التحقق من صيغة التوكن (بدون اتصال بـ Telegram)."""
2282
- return bool(token and ":" in token and len(token) > 20)
2283
-
2284
-
2285
- # ============================================================
2286
- # Channel Manager - إدارة موحدة للقنوات
2287
- # ============================================================
2288
-
2289
- class ChannelManager:
2290
- """يدير جميع القنوات بشكل موحد.
2291
-
2292
- - يدمج معلومات القناة (channels) مع إعداداتها (channel_configs).
2293
- - كل قناة لها Chat ID كمعرف أساسي.
2294
- - لا يعتمد على الأسماء.
2295
- """
2296
-
2297
- def get(self, channel_id):
2298
- """إرجاع معلومات القناة موحدة مع إعداداتها."""
2299
- cid = str(channel_id)
2300
- ch = get_channel(cid)
2301
- if not ch:
2302
- return None
2303
- cfg = get_channel_config(cid)
2304
- result = dict(ch)
2305
- result["config"] = cfg
2306
- return result
2307
-
2308
- def get_all(self):
2309
- """إرجاع جميع القنوات مع إعداداتها."""
2310
- channels = get_all_channels()
2311
- result = []
2312
- for ch in channels:
2313
- cid = str(ch["id"])
2314
- cfg = get_channel_config(cid)
2315
- item = dict(ch)
2316
- item["config"] = cfg
2317
- result.append(item)
2318
- return result
2319
-
2320
- def get_active(self):
2321
- """إرجاع القنوات غير الموقوفة فقط."""
2322
- return [ch for ch in self.get_all() if not ch.get("paused")]
2323
-
2324
- def add(self, channel_id, **meta):
2325
- """إضافة قناة جديدة."""
2326
- return add_channel(str(channel_id), **meta)
2327
-
2328
- def delete(self, channel_id):
2329
- """حذف قناة."""
2330
- return delete_channel(str(channel_id))
2331
-
2332
- def update(self, channel_id, key, value):
2333
- """تحديث حقل في القناة."""
2334
- return update_channel(str(channel_id), key, value)
2335
-
2336
- def get_config(self, channel_id):
2337
- """إرجاع إعدادات القناة."""
2338
- return get_channel_config(str(channel_id))
2339
-
2340
- def update_config(self, channel_id, **kwargs):
2341
- """تحديث إعدادات القناة."""
2342
- return update_channel_config(str(channel_id), **kwargs)
2343
-
2344
- def exists(self, channel_id):
2345
- """التحقق من وجود القناة في قاعدة البيانات."""
2346
- return get_channel(str(channel_id)) is not None
2347
-
2348
-
2349
- # ============================================================
2350
- # Bot-Channel Mapper - جدول ربط مستقل
2351
- # ============================================================
2352
-
2353
- class BotChannelMapper:
2354
- """يدير العلاقة بين البوتات والقنوات.
2355
-
2356
- - المصدر الوحيد لمعرفة أي بوت مرتبط بأي قناة.
2357
- - لا يعتمد على التخزين في الذاكرة.
2358
- - كل العلاقات مخزنة في قاعدة البيانات.
2359
- """
2360
-
2361
- def assign(self, bot_id, channel_id):
2362
- """ربط بوت بقناة."""
2363
- bid = str(bot_id)
2364
- cid = str(channel_id)
2365
- cfg = get_channel_config(cid)
2366
- assigned = list(cfg.get("assigned_bots", []))
2367
- if bid not in [str(x) for x in assigned]:
2368
- assigned.append(bid)
2369
- update_channel_config(cid, assigned_bots=assigned)
2370
- return True
2371
- return False
2372
-
2373
- def unassign(self, bot_id, channel_id):
2374
- """فك ربط بوت من قناة."""
2375
- bid = str(bot_id)
2376
- cid = str(channel_id)
2377
- cfg = get_channel_config(cid)
2378
- assigned = [str(x) for x in cfg.get("assigned_bots", [])]
2379
- if bid in assigned:
2380
- assigned = [x for x in assigned if x != bid]
2381
- update_channel_config(cid, assigned_bots=assigned)
2382
- return True
2383
- return False
2384
-
2385
- def get_bots_for_channel(self, channel_id):
2386
- """إرجاع IDs البوتات المرتبطة بقناة."""
2387
- cfg = get_channel_config(str(channel_id))
2388
- return [str(x) for x in cfg.get("assigned_bots", [])]
2389
-
2390
- def get_channels_for_bot(self, bot_id):
2391
- """إرجاع IDs القنوات التي يستخدمها بوت."""
2392
- bid = str(bot_id)
2393
- result = []
2394
- for ch in get_all_channels():
2395
- cid = str(ch["id"])
2396
- cfg = get_channel_config(cid)
2397
- if bid in [str(x) for x in cfg.get("assigned_bots", [])]:
2398
- result.append(cid)
2399
- return result
2400
-
2401
- def get_assigned_bot_objects(self, channel_id):
2402
- """إرجاع بيانات البوتات الكاملة المرتبطة بقناة."""
2403
- bots = []
2404
- for bid in self.get_bots_for_channel(channel_id):
2405
- b = get_publishing_bot(bid)
2406
- if b:
2407
- bots.append(b)
2408
- return bots
2409
-
2410
- def is_assigned(self, bot_id, channel_id):
2411
- """التحقق من ارتباط بوت بقناة."""
2412
- return str(bot_id) in self.get_bots_for_channel(channel_id)
2413
-
2414
- def unassign_all_for_bot(self, bot_id):
2415
- """فك ربط بوت من جميع القنوات."""
2416
- bid = str(bot_id)
2417
- count = 0
2418
- for cid in self.get_channels_for_bot(bid):
2419
- if self.unassign(bid, cid):
2420
- count += 1
2421
- return count
2422
-
2423
-
2424
- # إنشاء instance عامة للاستخدام في جميع أنحاء المشروع
2425
- bot_manager = BotManager()
2426
- channel_manager = ChannelManager()
2427
- mapper = BotChannelMapper()