Alialdlfy1 commited on
Commit
e4d2ed4
·
verified ·
1 Parent(s): 2b9ed92

Upload 2 files

Browse files
Files changed (2) hide show
  1. bot_core.py +0 -0
  2. database.py +1363 -0
bot_core.py ADDED
The diff for this file is too large to render. See raw diff
 
database.py ADDED
@@ -0,0 +1,1363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }
38
+
39
+
40
+ def _now():
41
+ return int(time.time())
42
+
43
+
44
+ def _dedupe_int_list(values):
45
+ out = []
46
+ seen = set()
47
+ for value in values or []:
48
+ try:
49
+ item = int(value)
50
+ except Exception:
51
+ item = value
52
+ key = str(item)
53
+ if key not in seen:
54
+ seen.add(key)
55
+ out.append(item)
56
+ return out
57
+
58
+
59
+ def _normalize_channel(cid, value):
60
+ if not isinstance(value, dict):
61
+ value = {"name": str(value)}
62
+ value.setdefault("name", value.get("title") or str(cid))
63
+ value.setdefault("title", value.get("name") or str(cid))
64
+ value.setdefault("username", "")
65
+ value.setdefault("link", "")
66
+ value.setdefault("chat_type", "")
67
+ value.setdefault("tail", "")
68
+ value.setdefault("special_sources", [])
69
+ value.setdefault("paused", False)
70
+ value.setdefault("posts_count", 0)
71
+ value.setdefault("publish_delay", None)
72
+ value.setdefault("bold_publish", True)
73
+ value.setdefault("quote_publish", False)
74
+ # إعدادات الاقتباس حسب نوع المنشور.
75
+ # توافق رجعي: إذا كان quote_publish القديم مفعلاً، نفعّل كل الأنواع افتراضياً.
76
+ old_quote = bool(value.get("quote_publish", False))
77
+ quote_types = value.get("quote_types")
78
+ if not isinstance(quote_types, dict):
79
+ quote_types = {}
80
+ value["quote_types"] = {
81
+ "text": bool(quote_types.get("text", old_quote)),
82
+ "photo": bool(quote_types.get("photo", old_quote)),
83
+ "video": bool(quote_types.get("video", old_quote)),
84
+ "album": bool(quote_types.get("album", old_quote)),
85
+ }
86
+ # يبقى المفتاح القديم موجود للتوافق مع النسخ الاحتياطية القديمة.
87
+ value["quote_publish"] = any(value["quote_types"].values())
88
+ value.setdefault("hashtags", [])
89
+ if not isinstance(value.get("hashtags"), list):
90
+ value["hashtags"] = []
91
+ value.setdefault("fail_count", 0)
92
+ value.setdefault("added_at", _now())
93
+ value["special_sources"] = _dedupe_int_list(value.get("special_sources", []))
94
+ return value
95
+
96
+
97
+ def _normalize_source_meta(source_id, value=None):
98
+ if not isinstance(value, dict):
99
+ value = {}
100
+ sid = str(source_id)
101
+ value.setdefault("id", int(source_id) if str(source_id).lstrip('-').isdigit() else source_id)
102
+ value.setdefault("name", value.get("title") or sid)
103
+ value.setdefault("title", value.get("name") or sid)
104
+ value.setdefault("username", "")
105
+ value.setdefault("link", "")
106
+ value.setdefault("chat_type", "")
107
+ value.setdefault("added_at", _now())
108
+ value.setdefault("paused", False)
109
+ value.setdefault("remove_terms", [])
110
+ if not isinstance(value.get("remove_terms"), list):
111
+ value["remove_terms"] = []
112
+ value.setdefault("remove_emoji", False)
113
+ default_types = {"text": True, "photo": True, "video": True, "album": True, "voice": False, "audio": False, "document": False}
114
+ types = value.get("content_types")
115
+ if not isinstance(types, dict):
116
+ types = {}
117
+ value["content_types"] = {k: bool(types.get(k, v)) for k, v in default_types.items()}
118
+ return value
119
+
120
+
121
+ def _normalize_data(data):
122
+ if not isinstance(data, dict):
123
+ data = {}
124
+
125
+ for key, value in DEFAULT_DATA.items():
126
+ if key not in data:
127
+ data[key] = value.copy() if isinstance(value, (list, dict)) else value
128
+
129
+ if not isinstance(data.get("channels"), dict):
130
+ data["channels"] = {}
131
+ if not isinstance(data.get("public_sources"), list):
132
+ data["public_sources"] = []
133
+ if not isinstance(data.get("source_meta"), dict):
134
+ data["source_meta"] = {}
135
+ if not isinstance(data.get("blocked_words"), list):
136
+ data["blocked_words"] = DEFAULT_BLOCKED_WORDS.copy()
137
+ if not isinstance(data.get("allowed_users"), list):
138
+ data["allowed_users"] = []
139
+ if not isinstance(data.get("last_source_messages"), dict):
140
+ data["last_source_messages"] = {}
141
+ if not isinstance(data.get("settings"), dict):
142
+ data["settings"] = {}
143
+ if not isinstance(data.get("global_remove_terms"), list):
144
+ data["global_remove_terms"] = []
145
+ if not isinstance(data.get("recent_fingerprints"), list):
146
+ data["recent_fingerprints"] = []
147
+ if not isinstance(data.get("source_stats"), dict):
148
+ data["source_stats"] = {}
149
+ if not isinstance(data.get("source_logs"), dict):
150
+ data["source_logs"] = {}
151
+ if not isinstance(data.get("system"), dict):
152
+ data["system"] = {}
153
+ if not isinstance(data.get("last_errors"), list):
154
+ data["last_errors"] = []
155
+ if not isinstance(data.get("named_backups"), list):
156
+ data["named_backups"] = []
157
+ if not isinstance(data.get("channel_failures"), dict):
158
+ data["channel_failures"] = {}
159
+ if not isinstance(data.get("published_messages"), dict):
160
+ data["published_messages"] = {}
161
+
162
+ data["schema_version"] = SCHEMA_VERSION
163
+ data["public_sources"] = _dedupe_int_list(data.get("public_sources", []))
164
+
165
+ channels = {}
166
+ for cid, ch in data.get("channels", {}).items():
167
+ channels[str(cid)] = _normalize_channel(cid, ch)
168
+ data["channels"] = channels
169
+
170
+ meta = {}
171
+ for source in data["public_sources"]:
172
+ sid = str(source)
173
+ meta[sid] = _normalize_source_meta(source, data.get("source_meta", {}).get(sid, {}))
174
+ for sid, value in data.get("source_meta", {}).items():
175
+ if sid not in meta:
176
+ meta[sid] = _normalize_source_meta(sid, value)
177
+ data["source_meta"] = meta
178
+
179
+ # normalize last source ids as strings
180
+ data["last_source_messages"] = {str(k): v for k, v in data.get("last_source_messages", {}).items()}
181
+ return data
182
+
183
+
184
+
185
+ def _is_valid_data(data, allow_empty=True):
186
+ """يتأكد أن ملف البيانات صالح وليس فارغاً/تالفاً."""
187
+ if not isinstance(data, dict):
188
+ return False
189
+ if "channels" not in data or "public_sources" not in data:
190
+ return False
191
+ if not isinstance(data.get("channels"), dict):
192
+ return False
193
+ if not isinstance(data.get("public_sources"), list):
194
+ return False
195
+ if not allow_empty:
196
+ if not data.get("channels") and not data.get("public_sources") and not data.get("source_meta"):
197
+ return False
198
+ return True
199
+
200
+
201
+ def _load_json_file(path):
202
+ with open(path, "r", encoding="utf-8") as f:
203
+ data = json.load(f)
204
+ if not _is_valid_data(data, allow_empty=True):
205
+ raise ValueError("ملف بيانات غير صالح")
206
+ return _normalize_data(data)
207
+
208
+
209
+ def _backup_candidates():
210
+ files = []
211
+ if os.path.exists(DB_FILE + ".bak"):
212
+ files.append(DB_FILE + ".bak")
213
+ if os.path.isdir(BACKUP_DIR):
214
+ files.extend(
215
+ os.path.join(BACKUP_DIR, x)
216
+ for x in os.listdir(BACKUP_DIR)
217
+ if x.endswith(".json")
218
+ )
219
+ return sorted(files, key=lambda p: os.path.getmtime(p), reverse=True)
220
+
221
+
222
+ def _restore_latest_backup():
223
+ """يحاول استعادة أحدث نسخة احتياطية صالحة."""
224
+ os.makedirs("/data", exist_ok=True)
225
+ for path in _backup_candidates():
226
+ try:
227
+ data = _load_json_file(path)
228
+ tmp = DB_FILE + ".restore.tmp"
229
+ with open(tmp, "w", encoding="utf-8") as f:
230
+ json.dump(data, f, ensure_ascii=False, indent=2)
231
+ os.replace(tmp, DB_FILE)
232
+ return data
233
+ except Exception:
234
+ continue
235
+ return None
236
+
237
+
238
+ def verify_or_recover_storage():
239
+ """فحص تخزين آمن عند تشغيل التطبيق/البوت."""
240
+ os.makedirs("/data", exist_ok=True)
241
+ if os.path.exists(DB_FILE):
242
+ try:
243
+ data = _load_json_file(DB_FILE)
244
+ return {"ok": True, "recovered": False, "message": "data.json صالح", "data": data}
245
+ except Exception as e:
246
+ recovered = _restore_latest_backup()
247
+ if recovered is not None:
248
+ return {"ok": True, "recovered": True, "message": f"تمت الاستعادة من Backup بعد تلف data.json: {e}", "data": recovered}
249
+ return {"ok": False, "recovered": False, "message": f"data.json تالف ولا توجد نسخة احتياطية صالحة: {e}", "data": None}
250
+
251
+ recovered = _restore_latest_backup()
252
+ if recovered is not None:
253
+ return {"ok": True, "recovered": True, "message": "تمت الاستعادة من Backup لأن data.json غير موجود", "data": recovered}
254
+
255
+ # أول تشغيل فقط: إنشاء ملف جديد فارغ
256
+ data = _normalize_data(DEFAULT_DATA.copy())
257
+ with open(DB_FILE, "w", encoding="utf-8") as f:
258
+ json.dump(data, f, ensure_ascii=False, indent=2)
259
+ return {"ok": True, "recovered": False, "message": "تم إنشاء قاعدة بيانات جديدة", "data": data}
260
+
261
+
262
+ def _read():
263
+ os.makedirs("/data", exist_ok=True)
264
+ status = verify_or_recover_storage()
265
+ if not status.get("ok"):
266
+ raise RuntimeError(status.get("message", "فشل قراءة قاعدة البيانات"))
267
+ return _normalize_data(status.get("data") or DEFAULT_DATA.copy())
268
+
269
+
270
+ def _make_prewrite_backup():
271
+ """نسخة احتياطية فورية قبل أي كتابة حتى لا تضيع البيانات عند توقف الاستضافة."""
272
+ try:
273
+ if os.path.exists(DB_FILE) and os.path.getsize(DB_FILE) > 5:
274
+ shutil.copy2(DB_FILE, DB_FILE + ".bak")
275
+ except Exception:
276
+ pass
277
+
278
+
279
+ def _write(data):
280
+ os.makedirs("/data", exist_ok=True)
281
+ data = _normalize_data(data)
282
+
283
+ # حماية من الكتابة بملف فارغ فوق بيانات موجودة
284
+ if not _is_valid_data(data, allow_empty=True):
285
+ raise ValueError("رفض كتابة بيانات غير صالحة")
286
+
287
+ _make_prewrite_backup()
288
+ tmp_file = DB_FILE + ".tmp"
289
+ with open(tmp_file, "w", encoding="utf-8") as f:
290
+ json.dump(data, f, ensure_ascii=False, indent=2)
291
+ f.flush()
292
+ try:
293
+ os.fsync(f.fileno())
294
+ except Exception:
295
+ pass
296
+ os.replace(tmp_file, DB_FILE)
297
+
298
+
299
+ def _write_backup(data):
300
+ try:
301
+ os.makedirs(BACKUP_DIR, exist_ok=True)
302
+ data = _normalize_data(data)
303
+ if not _is_valid_data(data, allow_empty=True):
304
+ return
305
+ backup_file = os.path.join(BACKUP_DIR, f"backup_{int(time.time())}.json")
306
+ with open(backup_file, "w", encoding="utf-8") as f:
307
+ json.dump(data, f, ensure_ascii=False, indent=2)
308
+ # keep last 20 backups
309
+ files = sorted([os.path.join(BACKUP_DIR, x) for x in os.listdir(BACKUP_DIR) if x.endswith('.json')])
310
+ for old in files[:-20]:
311
+ try:
312
+ os.remove(old)
313
+ except Exception:
314
+ pass
315
+ except Exception:
316
+ pass
317
+
318
+ def get_all_channels():
319
+ with lock:
320
+ data = _read()
321
+ return [{"id": k, **v} for k, v in data["channels"].items()]
322
+
323
+
324
+ def add_channel(channel_id, name="", title="", username="", link="", chat_type=""):
325
+ cid = str(channel_id)
326
+ with lock:
327
+ data = _read()
328
+ created = cid not in data["channels"]
329
+ if created:
330
+ data["channels"][cid] = _normalize_channel(cid, {
331
+ "name": title or name or cid,
332
+ "title": title or name or cid,
333
+ "username": username or "",
334
+ "link": link or "",
335
+ "chat_type": chat_type or "",
336
+ "tail": "",
337
+ "special_sources": [],
338
+ "paused": False,
339
+ "posts_count": 0,
340
+ "added_at": _now(),
341
+ })
342
+ else:
343
+ ch = data["channels"][cid]
344
+ if title or name:
345
+ ch["name"] = title or name
346
+ ch["title"] = title or name
347
+ if username is not None:
348
+ ch["username"] = username or ch.get("username", "")
349
+ if link is not None:
350
+ ch["link"] = link or ch.get("link", "")
351
+ if chat_type is not None:
352
+ ch["chat_type"] = chat_type or ch.get("chat_type", "")
353
+ _write(data)
354
+ if created:
355
+ _write_backup(data)
356
+ return created
357
+
358
+
359
+ def delete_channel(channel_id):
360
+ cid = str(channel_id)
361
+ with lock:
362
+ data = _read()
363
+ if cid in data["channels"]:
364
+ del data["channels"][cid]
365
+ _write(data)
366
+ _write_backup(data)
367
+ return True
368
+ return False
369
+
370
+
371
+ def update_channel(channel_id, key, value):
372
+ cid = str(channel_id)
373
+ with lock:
374
+ data = _read()
375
+ if cid in data["channels"]:
376
+ data["channels"][cid][key] = value
377
+ _write(data)
378
+ _write_backup(data)
379
+ return True
380
+ return False
381
+
382
+
383
+ def increment_post_count(channel_id):
384
+ cid = str(channel_id)
385
+ with lock:
386
+ data = _read()
387
+ if cid in data["channels"]:
388
+ data["channels"][cid].setdefault("posts_count", 0)
389
+ data["channels"][cid]["posts_count"] += 1
390
+ _write(data)
391
+ return True
392
+ return False
393
+
394
+
395
+ def get_channel(channel_id):
396
+ cid = str(channel_id)
397
+ with lock:
398
+ data = _read()
399
+ return data["channels"].get(cid)
400
+
401
+
402
+ def get_public_sources():
403
+ with lock:
404
+ data = _read()
405
+ return data["public_sources"]
406
+
407
+
408
+ def get_source_meta(source_id):
409
+ sid = str(source_id)
410
+ with lock:
411
+ data = _read()
412
+ return data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
413
+
414
+
415
+ def get_all_public_sources_with_meta():
416
+ with lock:
417
+ data = _read()
418
+ return [{"id": s, **data.get("source_meta", {}).get(str(s), _normalize_source_meta(s))} for s in data["public_sources"]]
419
+
420
+
421
+ def add_public_source(source_id, name="", title="", username="", link="", chat_type=""):
422
+ try:
423
+ source_id = int(source_id)
424
+ except Exception:
425
+ pass
426
+ sid = str(source_id)
427
+
428
+ with lock:
429
+ data = _read()
430
+ created = source_id not in data["public_sources"]
431
+ if created:
432
+ data["public_sources"].append(source_id)
433
+ old = data.setdefault("source_meta", {}).get(sid, {})
434
+ meta = _normalize_source_meta(source_id, old)
435
+ if title or name:
436
+ meta["name"] = title or name
437
+ meta["title"] = title or name
438
+ if username is not None:
439
+ meta["username"] = username or meta.get("username", "")
440
+ if link is not None:
441
+ meta["link"] = link or meta.get("link", "")
442
+ if chat_type is not None:
443
+ meta["chat_type"] = chat_type or meta.get("chat_type", "")
444
+ data["source_meta"][sid] = meta
445
+ _write(data)
446
+ if created:
447
+ _write_backup(data)
448
+ return created
449
+
450
+
451
+ def update_source_meta(source_id, **kwargs):
452
+ sid = str(source_id)
453
+ with lock:
454
+ data = _read()
455
+ meta = _normalize_source_meta(source_id, data.setdefault("source_meta", {}).get(sid, {}))
456
+ for key, value in kwargs.items():
457
+ if value is not None:
458
+ meta[key] = value
459
+ data["source_meta"][sid] = meta
460
+ _write(data)
461
+ return True
462
+
463
+
464
+ def remove_public_source(source_id):
465
+ try:
466
+ source_id = int(source_id)
467
+ except Exception:
468
+ pass
469
+ sid = str(source_id)
470
+
471
+ with lock:
472
+ data = _read()
473
+ if source_id in data["public_sources"]:
474
+ data["public_sources"].remove(source_id)
475
+ data["last_source_messages"].pop(sid, None)
476
+ data.get("source_meta", {}).pop(sid, None)
477
+ _write(data)
478
+ _write_backup(data)
479
+ return True
480
+ return False
481
+
482
+
483
+ def get_blocked_words():
484
+ with lock:
485
+ data = _read()
486
+ return data["blocked_words"]
487
+
488
+
489
+ def add_blocked_word(word):
490
+ word = str(word).strip()
491
+ if not word:
492
+ return False
493
+ with lock:
494
+ data = _read()
495
+ if word not in data["blocked_words"]:
496
+ data["blocked_words"].append(word)
497
+ _write(data)
498
+ _write_backup(data)
499
+ return True
500
+ return False
501
+
502
+
503
+ def remove_blocked_word(word):
504
+ word = str(word).strip()
505
+ with lock:
506
+ data = _read()
507
+ if word in data["blocked_words"]:
508
+ data["blocked_words"].remove(word)
509
+ _write(data)
510
+ _write_backup(data)
511
+ return True
512
+ return False
513
+
514
+
515
+ def get_last_source_message(source_id):
516
+ with lock:
517
+ data = _read()
518
+ value = data.get("last_source_messages", {}).get(str(source_id))
519
+ try:
520
+ if isinstance(value, dict):
521
+ return int(value.get("id")) if value.get("id") is not None else None
522
+ return int(value) if value is not None else None
523
+ except Exception:
524
+ return None
525
+
526
+ def set_last_source_message(source_id, message_id):
527
+ with lock:
528
+ data = _read()
529
+ data.setdefault("last_source_messages", {})[str(source_id)] = {"id": int(message_id), "ts": _now()}
530
+ _write(data)
531
+ return True
532
+
533
+ def reset_last_source_message(source_id):
534
+ with lock:
535
+ data = _read()
536
+ if str(source_id) in data.get("last_source_messages", {}):
537
+ del data["last_source_messages"][str(source_id)]
538
+ _write(data)
539
+ _write_backup(data)
540
+ return True
541
+ return False
542
+
543
+
544
+
545
+ def export_data():
546
+ with lock:
547
+ data = _read()
548
+ data = cleanup_old_runtime_data(data, days=3)
549
+ return json.dumps(_normalize_data(data), ensure_ascii=False, indent=2)
550
+
551
+
552
+ def import_data(json_str):
553
+ with lock:
554
+ new_data = json.loads(json_str)
555
+ if not _is_valid_data(new_data, allow_empty=False):
556
+ raise ValueError("ملف الاستيراد فارغ أو غير صالح. تم رفضه لحماية بياناتك.")
557
+ new_data = _normalize_data(new_data)
558
+
559
+ # لا نقبل ملف بلا قنوات وبلا مصادر إلا إذا كان مقصوداً، وهذا غير مسموح هنا
560
+ if not new_data.get("channels") and not new_data.get("public_sources") and not new_data.get("source_meta"):
561
+ raise ValueError("ملف الاستيراد لا يحتوي قنوات أو مصادر.")
562
+
563
+ _make_prewrite_backup()
564
+ _write_backup(_read())
565
+ new_data = cleanup_old_runtime_data(new_data, days=3)
566
+ _write(new_data)
567
+ _write_backup(new_data)
568
+ return {
569
+ "channels": len(new_data.get("channels", {})),
570
+ "public_sources": len(new_data.get("public_sources", [])),
571
+ "source_meta": len(new_data.get("source_meta", {})),
572
+ "blocked_words": len(new_data.get("blocked_words", [])),
573
+ "global_remove_terms": len(new_data.get("global_remove_terms", [])),
574
+ "last_source_messages": len(new_data.get("last_source_messages", {})),
575
+ "recent_fingerprints": len(new_data.get("recent_fingerprints", [])),
576
+ }
577
+
578
+
579
+ def cleanup_old_runtime_data(data=None, days=3):
580
+ """حذف بيانات التكرار والسجلات و IDs المؤقتة الأقدم من 3 أيام حتى لا يكبر الملف."""
581
+ cutoff = _now() - int(days) * 86400
582
+ own_write = data is None
583
+ if data is None:
584
+ data = _read()
585
+
586
+ items = data.get("recent_fingerprints", [])
587
+ if isinstance(items, list):
588
+ data["recent_fingerprints"] = [
589
+ x for x in items
590
+ if isinstance(x, dict) and int(x.get("ts", _now())) >= cutoff
591
+ ][-500:]
592
+
593
+ logs = data.get("source_logs", {})
594
+ if isinstance(logs, dict):
595
+ new_logs = {}
596
+ for sid, entries in logs.items():
597
+ if isinstance(entries, list):
598
+ new_logs[sid] = [
599
+ x for x in entries
600
+ if isinstance(x, dict) and int(x.get("ts", _now())) >= cutoff
601
+ ][-20:]
602
+ data["source_logs"] = new_logs
603
+
604
+ # تنظيف IDs آخر الأخبار للمصادر إذا خزنّت بصيغة حديثة مع تاريخ.
605
+ # القيم القديمة الرقمية تُترك كما هي للتوافق حتى يتم تحديثها تلقائياً عند أول فحص.
606
+ last_ids = data.get("last_source_messages", {})
607
+ if isinstance(last_ids, dict):
608
+ cleaned_last = {}
609
+ for sid, value in last_ids.items():
610
+ if isinstance(value, dict):
611
+ try:
612
+ if int(value.get("ts", _now())) >= cutoff:
613
+ cleaned_last[str(sid)] = value
614
+ except Exception:
615
+ pass
616
+ else:
617
+ cleaned_last[str(sid)] = value
618
+ data["last_source_messages"] = cleaned_last
619
+
620
+ last_errors = data.get("last_errors", [])
621
+ if isinstance(last_errors, list):
622
+ data["last_errors"] = [
623
+ x for x in last_errors
624
+ if isinstance(x, dict) and int(x.get("ts", _now())) >= cutoff
625
+ ][-50:]
626
+
627
+
628
+ # تنظيف سجل الرسائل المنشورة القديمة حتى لا يكبر الملف.
629
+ published = data.get("published_messages", {})
630
+ if isinstance(published, dict):
631
+ new_published = {}
632
+ for cid, by_type in published.items():
633
+ if not isinstance(by_type, dict):
634
+ continue
635
+ new_by_type = {}
636
+ for kind, entries in by_type.items():
637
+ if isinstance(entries, list):
638
+ new_by_type[kind] = [
639
+ x for x in entries
640
+ if isinstance(x, dict) and int(x.get("ts", _now())) >= cutoff
641
+ ][-1000:]
642
+ new_published[str(cid)] = new_by_type
643
+ data["published_messages"] = new_published
644
+
645
+ if own_write:
646
+ _write(data)
647
+ return _normalize_data(data)
648
+
649
+ def get_source_remove_terms(source_id):
650
+ sid = str(source_id)
651
+ with lock:
652
+ data = _read()
653
+ meta = data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
654
+ terms = meta.get("remove_terms", [])
655
+ if not isinstance(terms, list):
656
+ return []
657
+ return [str(x).strip() for x in terms if str(x).strip()]
658
+
659
+
660
+ def add_source_remove_terms(source_id, terms):
661
+ sid = str(source_id)
662
+ clean_terms = []
663
+ for term in terms or []:
664
+ term = str(term).strip()
665
+ if term:
666
+ clean_terms.append(term)
667
+
668
+ if not clean_terms:
669
+ return {"added": 0, "exists": 0}
670
+
671
+ with lock:
672
+ data = _read()
673
+ meta = _normalize_source_meta(source_id, data.setdefault("source_meta", {}).get(sid, {}))
674
+ existing = [str(x).strip() for x in meta.get("remove_terms", []) if str(x).strip()]
675
+ existing_keys = {x.lower() for x in existing}
676
+
677
+ added = 0
678
+ exists = 0
679
+ for term in clean_terms:
680
+ key = term.lower()
681
+ if key in existing_keys:
682
+ exists += 1
683
+ continue
684
+ existing.append(term)
685
+ existing_keys.add(key)
686
+ added += 1
687
+
688
+ meta["remove_terms"] = existing
689
+ data["source_meta"][sid] = meta
690
+ _write(data)
691
+ if added:
692
+ _write_backup(data)
693
+ return {"added": added, "exists": exists}
694
+
695
+
696
+ def remove_source_remove_terms(source_id, terms):
697
+ sid = str(source_id)
698
+ remove_keys = {str(x).strip().lower() for x in terms or [] if str(x).strip()}
699
+ if not remove_keys:
700
+ return {"removed": 0, "missing": 0}
701
+
702
+ with lock:
703
+ data = _read()
704
+ meta = _normalize_source_meta(source_id, data.setdefault("source_meta", {}).get(sid, {}))
705
+ existing = [str(x).strip() for x in meta.get("remove_terms", []) if str(x).strip()]
706
+ before = len(existing)
707
+ existing = [x for x in existing if x.lower() not in remove_keys]
708
+ removed = before - len(existing)
709
+ meta["remove_terms"] = existing
710
+ data["source_meta"][sid] = meta
711
+ _write(data)
712
+ if removed:
713
+ _write_backup(data)
714
+ return {"removed": removed, "missing": max(0, len(remove_keys) - removed)}
715
+
716
+
717
+ def remove_source_remove_term(source_id, term_or_index):
718
+ terms = get_source_remove_terms(source_id)
719
+ try:
720
+ idx = int(term_or_index)
721
+ if 0 <= idx < len(terms):
722
+ return bool(remove_source_remove_terms(source_id, [terms[idx]]).get("removed"))
723
+ except Exception:
724
+ pass
725
+ return bool(remove_source_remove_terms(source_id, [term_or_index]).get("removed"))
726
+
727
+
728
+ # ===== Phase 3 Part 1: source filters, global cleanup, smart dedupe =====
729
+ def get_global_remove_terms():
730
+ with lock:
731
+ data = _read()
732
+ terms = data.get("global_remove_terms", [])
733
+ if not isinstance(terms, list):
734
+ return []
735
+ return [str(x).strip() for x in terms if str(x).strip()]
736
+
737
+
738
+ def add_global_remove_terms(terms):
739
+ clean_terms = []
740
+ for term in terms or []:
741
+ term = str(term).strip()
742
+ if term:
743
+ clean_terms.append(term)
744
+
745
+ if not clean_terms:
746
+ return {"added": 0, "exists": 0}
747
+
748
+ with lock:
749
+ data = _read()
750
+ existing = [str(x).strip() for x in data.get("global_remove_terms", []) if str(x).strip()]
751
+ existing_keys = {x.lower() for x in existing}
752
+ added = 0
753
+ exists = 0
754
+ for term in clean_terms:
755
+ key = term.lower()
756
+ if key in existing_keys:
757
+ exists += 1
758
+ continue
759
+ existing.append(term)
760
+ existing_keys.add(key)
761
+ added += 1
762
+ data["global_remove_terms"] = existing
763
+ _write(data)
764
+ if added:
765
+ _write_backup(data)
766
+ return {"added": added, "exists": exists}
767
+
768
+
769
+ def remove_global_remove_terms(terms):
770
+ remove_keys = {str(x).strip().lower() for x in terms or [] if str(x).strip()}
771
+ if not remove_keys:
772
+ return {"removed": 0, "missing": 0}
773
+
774
+ with lock:
775
+ data = _read()
776
+ existing = [str(x).strip() for x in data.get("global_remove_terms", []) if str(x).strip()]
777
+ before = len(existing)
778
+ existing = [x for x in existing if x.lower() not in remove_keys]
779
+ removed = before - len(existing)
780
+ data["global_remove_terms"] = existing
781
+ _write(data)
782
+ if removed:
783
+ _write_backup(data)
784
+ return {"removed": removed, "missing": max(0, len(remove_keys) - removed)}
785
+
786
+
787
+ def set_source_paused(source_id, paused=True):
788
+ return update_source_meta(source_id, paused=bool(paused))
789
+
790
+
791
+ def is_source_paused(source_id):
792
+ sid = str(source_id)
793
+ with lock:
794
+ data = _read()
795
+ meta = data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
796
+ return bool(meta.get("paused", False))
797
+
798
+
799
+ def set_source_remove_emoji(source_id, enabled=True):
800
+ return update_source_meta(source_id, remove_emoji=bool(enabled))
801
+
802
+
803
+ def get_source_remove_emoji(source_id):
804
+ sid = str(source_id)
805
+ with lock:
806
+ data = _read()
807
+ meta = data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
808
+ return bool(meta.get("remove_emoji", False))
809
+
810
+
811
+ def get_source_content_types(source_id):
812
+ sid = str(source_id)
813
+ with lock:
814
+ data = _read()
815
+ meta = data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
816
+ default_types = {"text": True, "photo": True, "video": True, "album": True, "voice": False, "audio": False, "document": False}
817
+ types = meta.get("content_types", {})
818
+ if not isinstance(types, dict):
819
+ types = {}
820
+ return {k: bool(types.get(k, v)) for k, v in default_types.items()}
821
+
822
+
823
+ def set_source_content_type(source_id, content_type, enabled=True):
824
+ if content_type not in {"text", "photo", "video", "album", "voice", "audio", "document"}:
825
+ return False
826
+ sid = str(source_id)
827
+ default_types = {"text": True, "photo": True, "video": True, "album": True, "voice": False, "audio": False, "document": False}
828
+ with lock:
829
+ data = _read()
830
+ meta = _normalize_source_meta(source_id, data.setdefault("source_meta", {}).get(sid, {}))
831
+ current = meta.get("content_types", {})
832
+ if not isinstance(current, dict):
833
+ current = {}
834
+ types = {k: bool(current.get(k, v)) for k, v in default_types.items()}
835
+ types[content_type] = bool(enabled)
836
+ # منع إطفاء كل الأنواع حتى لا يصبح المصدر شغال بلا أي محتوى
837
+ if not any(types.values()):
838
+ return False
839
+ meta["content_types"] = types
840
+ data["source_meta"][sid] = meta
841
+ _write(data)
842
+ _write_backup(data)
843
+ return True
844
+
845
+
846
+ def set_source_content_types(source_id, content_types):
847
+ allowed = {"text", "photo", "video", "album", "voice", "audio", "document"}
848
+ values = {k: bool(content_types.get(k, False)) for k in allowed}
849
+ if not any(values.values()):
850
+ return False
851
+ return update_source_meta(source_id, content_types=values)
852
+
853
+
854
+ def get_recent_fingerprints():
855
+ cutoff = _now() - 3 * 86400
856
+ with lock:
857
+ data = _read()
858
+ items = data.get("recent_fingerprints", [])
859
+ if not isinstance(items, list):
860
+ return []
861
+ fresh = [x for x in items if isinstance(x, dict) and x.get("fp") and int(x.get("ts", _now())) >= cutoff]
862
+ if len(fresh) != len(items):
863
+ data["recent_fingerprints"] = fresh[-500:]
864
+ _write(data)
865
+ return fresh[-500:]
866
+
867
+ def add_recent_fingerprint(fp, sample="", limit=500):
868
+ fp = str(fp or "").strip()
869
+ if not fp:
870
+ return False
871
+ cutoff = _now() - 3 * 86400
872
+ with lock:
873
+ data = _read()
874
+ items = data.get("recent_fingerprints", [])
875
+ if not isinstance(items, list):
876
+ items = []
877
+ items = [x for x in items if isinstance(x, dict) and x.get("fp") != fp and int(x.get("ts", _now())) >= cutoff]
878
+ items.append({"fp": fp, "sample": str(sample or "")[:500], "ts": _now()})
879
+ if len(items) > int(limit):
880
+ items = items[-int(limit):]
881
+ data["recent_fingerprints"] = items
882
+ _write(data)
883
+ return True
884
+
885
+ def set_channel_publish_delay(channel_id, delay_seconds):
886
+ try:
887
+ if delay_seconds is None or str(delay_seconds).strip() == "":
888
+ value = None
889
+ else:
890
+ value = max(0.0, float(delay_seconds))
891
+ except Exception:
892
+ return False
893
+ return update_channel(channel_id, "publish_delay", value)
894
+
895
+
896
+ def get_channel_publish_delay(channel_id, default=0.5):
897
+ ch = get_channel(channel_id)
898
+ if not ch:
899
+ return float(default)
900
+ value = ch.get("publish_delay", None)
901
+ if value is None or value == "":
902
+ return float(default)
903
+ try:
904
+ return max(0.0, float(value))
905
+ except Exception:
906
+ return float(default)
907
+
908
+
909
+
910
+ def set_channel_bold_publish(channel_id, enabled=True):
911
+ return update_channel(channel_id, "bold_publish", bool(enabled))
912
+
913
+
914
+ def get_channel_bold_publish(channel_id, default=True):
915
+ ch = get_channel(channel_id)
916
+ if not ch:
917
+ return bool(default)
918
+ return bool(ch.get("bold_publish", default))
919
+
920
+ def record_source_event(source_id, event_type, reason="", message_id=None, target_count=0):
921
+ sid = str(source_id)
922
+ with lock:
923
+ data = _read()
924
+ stats = data.setdefault("source_stats", {}).setdefault(sid, {
925
+ "received": 0, "published": 0, "rejected": 0, "ignored": 0,
926
+ "duplicates": 0, "errors": 0, "last_message_id": None,
927
+ "last_event": "", "last_reason": "", "last_ts": None
928
+ })
929
+ event_type = str(event_type or "").lower()
930
+ if event_type == "received":
931
+ stats["received"] = int(stats.get("received", 0)) + 1
932
+ elif event_type == "published":
933
+ stats["published"] = int(stats.get("published", 0)) + 1
934
+ elif event_type == "rejected":
935
+ stats["rejected"] = int(stats.get("rejected", 0)) + 1
936
+ elif event_type == "duplicate":
937
+ stats["duplicates"] = int(stats.get("duplicates", 0)) + 1
938
+ stats["ignored"] = int(stats.get("ignored", 0)) + 1
939
+ elif event_type == "error":
940
+ stats["errors"] = int(stats.get("errors", 0)) + 1
941
+ else:
942
+ stats["ignored"] = int(stats.get("ignored", 0)) + 1
943
+ stats["last_message_id"] = message_id
944
+ stats["last_event"] = event_type
945
+ stats["last_reason"] = str(reason or "")[:300]
946
+ stats["last_ts"] = _now()
947
+ data["source_stats"][sid] = stats
948
+
949
+ logs = data.setdefault("source_logs", {}).setdefault(sid, [])
950
+ logs.append({
951
+ "ts": _now(), "event": event_type, "reason": str(reason or "")[:300],
952
+ "message_id": message_id, "target_count": int(target_count or 0)
953
+ })
954
+ data["source_logs"][sid] = logs[-20:]
955
+ _write(data)
956
+ return True
957
+
958
+
959
+ def get_source_stats(source_id):
960
+ sid = str(source_id)
961
+ with lock:
962
+ data = _read()
963
+ return data.get("source_stats", {}).get(sid, {
964
+ "received": 0, "published": 0, "rejected": 0, "ignored": 0,
965
+ "duplicates": 0, "errors": 0, "last_message_id": None,
966
+ "last_event": "", "last_reason": "", "last_ts": None
967
+ })
968
+
969
+
970
+ def get_source_logs(source_id, limit=20):
971
+ sid = str(source_id)
972
+ with lock:
973
+ data = _read()
974
+ logs = data.get("source_logs", {}).get(sid, [])
975
+ if not isinstance(logs, list):
976
+ return []
977
+ return logs[-int(limit):]
978
+
979
+
980
+ def copy_source_settings(from_source_id, to_source_ids):
981
+ from_sid = str(from_source_id)
982
+ copied = 0
983
+ with lock:
984
+ data = _read()
985
+ source_meta = _normalize_source_meta(from_source_id, data.setdefault("source_meta", {}).get(from_sid, {}))
986
+ keys = ["remove_terms", "remove_emoji", "content_types", "paused"]
987
+ for dst in to_source_ids or []:
988
+ sid = str(dst)
989
+ meta = _normalize_source_meta(dst, data.setdefault("source_meta", {}).get(sid, {}))
990
+ for key in keys:
991
+ if key in source_meta:
992
+ # copy JSON-compatible value
993
+ meta[key] = json.loads(json.dumps(source_meta[key], ensure_ascii=False))
994
+ data["source_meta"][sid] = meta
995
+ copied += 1
996
+ _write(data)
997
+ if copied:
998
+ _write_backup(data)
999
+ return copied
1000
+
1001
+
1002
+ def set_system_value(key, value):
1003
+ with lock:
1004
+ data = _read()
1005
+ data.setdefault("system", {})[str(key)] = value
1006
+ _write(data)
1007
+ return True
1008
+
1009
+
1010
+ def get_system_value(key, default=None):
1011
+ with lock:
1012
+ data = _read()
1013
+ return data.get("system", {}).get(str(key), default)
1014
+
1015
+
1016
+ # ===== Professional safety/ops additions =====
1017
+ def is_maintenance_mode():
1018
+ with lock:
1019
+ data = _read()
1020
+ return bool(data.get("system", {}).get("maintenance_mode", False))
1021
+
1022
+
1023
+ def set_maintenance_mode(enabled):
1024
+ with lock:
1025
+ data = _read()
1026
+ data.setdefault("system", {})["maintenance_mode"] = bool(enabled)
1027
+ data["system"]["maintenance_updated_at"] = _now()
1028
+ _write(data)
1029
+ return True
1030
+
1031
+
1032
+ def add_last_error(context, error):
1033
+ with lock:
1034
+ data = _read()
1035
+ errors = data.setdefault("last_errors", [])
1036
+ if not isinstance(errors, list):
1037
+ errors = []
1038
+ errors.append({
1039
+ "ts": _now(),
1040
+ "context": str(context or "")[:120],
1041
+ "error": str(error or "")[:500],
1042
+ })
1043
+ data["last_errors"] = errors[-20:]
1044
+ data.setdefault("system", {})["last_error"] = f"{context}: {error}"[:600]
1045
+ data["system"]["last_error_ts"] = _now()
1046
+ _write(data)
1047
+ return True
1048
+
1049
+
1050
+ def get_last_errors(limit=20):
1051
+ with lock:
1052
+ data = _read()
1053
+ errors = data.get("last_errors", [])
1054
+ if not isinstance(errors, list):
1055
+ return []
1056
+ return errors[-int(limit):]
1057
+
1058
+
1059
+ def clear_last_errors():
1060
+ with lock:
1061
+ data = _read()
1062
+ data["last_errors"] = []
1063
+ data.setdefault("system", {})["last_error"] = ""
1064
+ _write(data)
1065
+ return True
1066
+
1067
+
1068
+ def _normalize_quote_types(value=None, fallback=False):
1069
+ if not isinstance(value, dict):
1070
+ value = {}
1071
+ return {
1072
+ "text": bool(value.get("text", fallback)),
1073
+ "photo": bool(value.get("photo", fallback)),
1074
+ "video": bool(value.get("video", fallback)),
1075
+ "album": bool(value.get("album", fallback)),
1076
+ }
1077
+
1078
+
1079
+ def set_channel_quote_publish(channel_id, enabled=True):
1080
+ # المفتاح القديم: يبدّل كل الأنواع مرة واحدة للتوافق فقط.
1081
+ cid = str(channel_id)
1082
+ enabled = bool(enabled)
1083
+ with lock:
1084
+ data = _read()
1085
+ if cid not in data.get("channels", {}):
1086
+ return False
1087
+ data["channels"][cid]["quote_types"] = _normalize_quote_types({}, enabled)
1088
+ data["channels"][cid]["quote_publish"] = enabled
1089
+ _write(data)
1090
+ _write_backup(data)
1091
+ return True
1092
+
1093
+
1094
+ def get_channel_quote_publish(channel_id, default=False):
1095
+ ch = get_channel(channel_id)
1096
+ if not ch:
1097
+ return bool(default)
1098
+ qt = _normalize_quote_types(ch.get("quote_types"), ch.get("quote_publish", default))
1099
+ return any(qt.values())
1100
+
1101
+
1102
+ def get_channel_quote_types(channel_id):
1103
+ ch = get_channel(channel_id)
1104
+ if not ch:
1105
+ return _normalize_quote_types({}, False)
1106
+ return _normalize_quote_types(ch.get("quote_types"), ch.get("quote_publish", False))
1107
+
1108
+
1109
+ def get_channel_quote_type(channel_id, content_type="text", default=False):
1110
+ ctype = str(content_type or "text")
1111
+ if ctype not in {"text", "photo", "video", "album"}:
1112
+ ctype = "text"
1113
+ return bool(get_channel_quote_types(channel_id).get(ctype, default))
1114
+
1115
+
1116
+ def set_channel_quote_type(channel_id, content_type, enabled=True):
1117
+ cid = str(channel_id)
1118
+ ctype = str(content_type or "text")
1119
+ if ctype not in {"text", "photo", "video", "album"}:
1120
+ return False
1121
+ with lock:
1122
+ data = _read()
1123
+ if cid not in data.get("channels", {}):
1124
+ return False
1125
+ ch = data["channels"][cid]
1126
+ qt = _normalize_quote_types(ch.get("quote_types"), ch.get("quote_publish", False))
1127
+ qt[ctype] = bool(enabled)
1128
+ ch["quote_types"] = qt
1129
+ ch["quote_publish"] = any(qt.values())
1130
+ _write(data)
1131
+ _write_backup(data)
1132
+ return True
1133
+
1134
+
1135
+ def get_channel_hashtags(channel_id):
1136
+ ch = get_channel(channel_id)
1137
+ if not ch:
1138
+ return []
1139
+ tags = ch.get("hashtags", [])
1140
+ if not isinstance(tags, list):
1141
+ return []
1142
+ out = []
1143
+ seen = set()
1144
+ for tag in tags:
1145
+ tag = str(tag).strip()
1146
+ if not tag:
1147
+ continue
1148
+ if not tag.startswith("#"):
1149
+ tag = "#" + tag.lstrip("#")
1150
+ key = tag.lower()
1151
+ if key not in seen:
1152
+ seen.add(key)
1153
+ out.append(tag)
1154
+ return out
1155
+
1156
+
1157
+ def add_channel_hashtags(channel_id, tags):
1158
+ clean = []
1159
+ for tag in tags or []:
1160
+ tag = str(tag).strip()
1161
+ if not tag:
1162
+ continue
1163
+ if not tag.startswith("#"):
1164
+ tag = "#" + tag.lstrip("#")
1165
+ clean.append(tag)
1166
+ if not clean:
1167
+ return {"added": 0, "exists": 0}
1168
+ cid = str(channel_id)
1169
+ with lock:
1170
+ data = _read()
1171
+ if cid not in data["channels"]:
1172
+ return {"added": 0, "exists": 0}
1173
+ existing = []
1174
+ for tag in data["channels"][cid].get("hashtags", []):
1175
+ tag = str(tag).strip()
1176
+ if tag:
1177
+ existing.append(tag if tag.startswith("#") else "#" + tag.lstrip("#"))
1178
+ keys = {x.lower() for x in existing}
1179
+ added = 0
1180
+ exists = 0
1181
+ for tag in clean:
1182
+ key = tag.lower()
1183
+ if key in keys:
1184
+ exists += 1
1185
+ continue
1186
+ existing.append(tag)
1187
+ keys.add(key)
1188
+ added += 1
1189
+ data["channels"][cid]["hashtags"] = existing
1190
+ _write(data)
1191
+ if added:
1192
+ _write_backup(data)
1193
+ return {"added": added, "exists": exists}
1194
+
1195
+
1196
+ def remove_channel_hashtags(channel_id, tags):
1197
+ remove_keys = set()
1198
+ for tag in tags or []:
1199
+ tag = str(tag).strip()
1200
+ if not tag:
1201
+ continue
1202
+ if not tag.startswith("#"):
1203
+ tag = "#" + tag.lstrip("#")
1204
+ remove_keys.add(tag.lower())
1205
+ if not remove_keys:
1206
+ return {"removed": 0, "missing": 0}
1207
+ cid = str(channel_id)
1208
+ with lock:
1209
+ data = _read()
1210
+ if cid not in data["channels"]:
1211
+ return {"removed": 0, "missing": len(remove_keys)}
1212
+ existing = []
1213
+ for tag in data["channels"][cid].get("hashtags", []):
1214
+ tag = str(tag).strip()
1215
+ if tag:
1216
+ existing.append(tag if tag.startswith("#") else "#" + tag.lstrip("#"))
1217
+ before = len(existing)
1218
+ existing = [x for x in existing if x.lower() not in remove_keys]
1219
+ removed = before - len(existing)
1220
+ data["channels"][cid]["hashtags"] = existing
1221
+ _write(data)
1222
+ if removed:
1223
+ _write_backup(data)
1224
+ return {"removed": removed, "missing": max(0, len(remove_keys)-removed)}
1225
+
1226
+
1227
+ def record_channel_publish_success(channel_id):
1228
+ cid = str(channel_id)
1229
+ with lock:
1230
+ data = _read()
1231
+ if cid in data.get("channels", {}):
1232
+ data["channels"][cid]["fail_count"] = 0
1233
+ data.setdefault("channel_failures", {})[cid] = 0
1234
+ _write(data)
1235
+ return True
1236
+
1237
+
1238
+ def record_channel_publish_failure(channel_id, error="", limit=5):
1239
+ cid = str(channel_id)
1240
+ with lock:
1241
+ data = _read()
1242
+ failures = data.setdefault("channel_failures", {})
1243
+ count = int(failures.get(cid, 0) or 0) + 1
1244
+ failures[cid] = count
1245
+ if cid in data.get("channels", {}):
1246
+ data["channels"][cid]["fail_count"] = count
1247
+ if count >= int(limit):
1248
+ data["channels"][cid]["paused"] = True
1249
+ data["channels"][cid]["auto_paused_reason"] = str(error or "")[:300]
1250
+ data["channels"][cid]["auto_paused_at"] = _now()
1251
+ errors = data.setdefault("last_errors", [])
1252
+ errors.append({"ts": _now(), "context": f"publish channel {cid}", "error": str(error or "")[:500]})
1253
+ data["last_errors"] = errors[-20:]
1254
+ _write(data)
1255
+ return count
1256
+
1257
+
1258
+ def create_named_backup(name):
1259
+ name = str(name or "").strip()
1260
+ if not name:
1261
+ name = f"backup_{_now()}"
1262
+ safe = "".join(ch for ch in name if ch.isalnum() or ch in ("_", "-", ".", " ")).strip().replace(" ", "_")
1263
+ if not safe:
1264
+ safe = f"backup_{_now()}"
1265
+ with lock:
1266
+ data = _read()
1267
+ os.makedirs(BACKUP_DIR, exist_ok=True)
1268
+ path = os.path.join(BACKUP_DIR, f"manual_{safe}_{_now()}.json")
1269
+ with open(path, "w", encoding="utf-8") as f:
1270
+ json.dump(_normalize_data(data), f, ensure_ascii=False, indent=2)
1271
+ named = data.setdefault("named_backups", [])
1272
+ named.append({"name": name, "file": path, "ts": _now()})
1273
+ data["named_backups"] = named[-30:]
1274
+ _write(data)
1275
+ return path
1276
+
1277
+
1278
+ def get_named_backups():
1279
+ with lock:
1280
+ data = _read()
1281
+ items = data.get("named_backups", [])
1282
+ return items if isinstance(items, list) else []
1283
+
1284
+
1285
+ # ===== Published message tracking for channel cleanup =====
1286
+ def record_published_message(channel_id, message_id, content_type):
1287
+ """يحفظ ID الرسالة التي نشرها البوت حتى يمكن حذفها لاحقاً حسب النوع."""
1288
+ if not message_id:
1289
+ return False
1290
+ cid = str(channel_id)
1291
+ ctype = str(content_type or "text")
1292
+ if ctype not in {"text", "photo", "video", "album"}:
1293
+ ctype = "photo"
1294
+ with lock:
1295
+ data = _read()
1296
+ box = data.setdefault("published_messages", {}).setdefault(cid, {}).setdefault(ctype, [])
1297
+ mid = int(message_id)
1298
+ if not any(isinstance(x, dict) and int(x.get("id", -1)) == mid for x in box):
1299
+ box.append({"id": mid, "ts": _now()})
1300
+ data["published_messages"][cid][ctype] = box[-1000:]
1301
+ _write(data)
1302
+ return True
1303
+
1304
+
1305
+ def record_published_messages(channel_id, message_ids, content_type):
1306
+ count = 0
1307
+ for mid in message_ids or []:
1308
+ if record_published_message(channel_id, mid, content_type):
1309
+ count += 1
1310
+ return count
1311
+
1312
+
1313
+ def get_published_message_ids(channel_id, content_type):
1314
+ cid = str(channel_id)
1315
+ ctype = str(content_type or "")
1316
+ with lock:
1317
+ data = _read()
1318
+ entries = data.get("published_messages", {}).get(cid, {}).get(ctype, [])
1319
+ ids = []
1320
+ for item in entries:
1321
+ try:
1322
+ ids.append(int(item.get("id") if isinstance(item, dict) else item))
1323
+ except Exception:
1324
+ pass
1325
+ return ids
1326
+
1327
+
1328
+ def clear_published_message_ids(channel_id, content_type, message_ids=None):
1329
+ cid = str(channel_id)
1330
+ ctype = str(content_type or "")
1331
+ remove_set = None
1332
+ if message_ids is not None:
1333
+ remove_set = {int(x) for x in message_ids if str(x).lstrip("-").isdigit()}
1334
+ with lock:
1335
+ data = _read()
1336
+ entries = data.setdefault("published_messages", {}).setdefault(cid, {}).setdefault(ctype, [])
1337
+ if remove_set is None:
1338
+ removed = len(entries)
1339
+ data["published_messages"][cid][ctype] = []
1340
+ else:
1341
+ before = len(entries)
1342
+ data["published_messages"][cid][ctype] = [
1343
+ x for x in entries
1344
+ if int(x.get("id") if isinstance(x, dict) else x) not in remove_set
1345
+ ]
1346
+ removed = before - len(data["published_messages"][cid][ctype])
1347
+ _write(data)
1348
+ return removed
1349
+
1350
+
1351
+ def get_ignore_short_posts():
1352
+ with lock:
1353
+ data = _read()
1354
+ return bool(data.get("settings", {}).get("ignore_short_posts", False))
1355
+
1356
+
1357
+ def set_ignore_short_posts(enabled):
1358
+ with lock:
1359
+ data = _read()
1360
+ data.setdefault("settings", {})["ignore_short_posts"] = bool(enabled)
1361
+ _write(data)
1362
+ _write_backup(data)
1363
+ return True