Alialdlfy1 commited on
Commit
ad64341
·
verified ·
1 Parent(s): 74cf5d4

Delete database.py

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