Alialdlfy1 commited on
Commit
d70c8dc
·
verified ·
1 Parent(s): fee5113

Delete database.py

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