Alialdlfy1 commited on
Commit
e7bf5b2
·
verified ·
1 Parent(s): a99f577

Upload service.py

Browse files
Files changed (1) hide show
  1. modules/info_channel/service.py +627 -0
modules/info_channel/service.py ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import email.utils
3
+ import html
4
+ import json
5
+ import logging
6
+ import os
7
+ import random
8
+ import re
9
+ import tempfile
10
+ import time
11
+ import xml.etree.ElementTree as ET
12
+ from datetime import datetime
13
+ from typing import Any, Dict, List, Optional, Tuple
14
+ from zoneinfo import ZoneInfo
15
+
16
+ import httpx
17
+ from bs4 import BeautifulSoup
18
+ from pyrogram.enums import ParseMode
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ BAGHDAD_TZ = ZoneInfo("Asia/Baghdad")
23
+ INFO_CHANNEL_USERNAME = os.getenv("INFO_CHANNEL_USERNAME", "@CastleInfoiq").strip() or "@CastleInfoiq"
24
+ INFO_PUBLISH_SLOTS = ["10:00", "12:00", "14:00", "16:00", "18:00", "20:00", "22:00"]
25
+ INFO_SIGNATURE = "#قلعة_المعلومات_العامة\nاشتـــرك الآن :- https://t.me/CastleInfoiq"
26
+ UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/125.0 Safari/537.36"
27
+ RSS_TIMEOUT = 15
28
+ RSS_RETRIES = 2
29
+ ARTICLE_TEXT_LIMIT = 3600
30
+ NON_NEWS_TERMS = ("event", "seminar", "workshop", "activity", "poster", "call for proposals")
31
+
32
+ INFO_RSS_SOURCES = [
33
+ {"name": "NASA", "category": "فضاء", "url": "https://www.nasa.gov/rss/dyn/breaking_news.rss", "hashtags": "#فضاء #ناسا #الكون #معلومات_عامة"},
34
+ {"name": "NASA Science", "category": "فضاء", "url": "https://science.nasa.gov/feed/", "hashtags": "#فضاء #علوم #الكون #معلومات_عامة"},
35
+ {"name": "ScienceDaily", "category": "علوم", "url": "https://www.sciencedaily.com/rss/top.xml", "hashtags": "#علوم #اكتشافات #معرفة #معلومات_عامة"},
36
+ {"name": "ScienceDaily Space", "category": "فضاء", "url": "https://www.sciencedaily.com/rss/space_time.xml", "hashtags": "#فضاء #علوم #الكون #معلومات_عامة"},
37
+ {"name": "ScienceDaily Matter", "category": "علوم", "url": "https://www.sciencedaily.com/rss/matter_energy.xml", "hashtags": "#علوم #اكتشافات #تكنولوجيا #معلومات_عامة"},
38
+ {"name": "World History Encyclopedia", "category": "تاريخ", "url": "https://www.worldhistory.org/rss/", "hashtags": "#تاريخ #حضارات #معرفة #معلومات_عامة"},
39
+ ]
40
+
41
+ FALLBACK_TOPICS = [
42
+ "قصة بناء الأهرامات وأسرارها العلمية",
43
+ "كيف غيّر نيوتن فهم البشر للكون",
44
+ "أغرب أسرار كوكب المشتري",
45
+ "قصة مكتبة الإسكندرية ولماذا بقيت لغزاً",
46
+ "كيف بدأت الثورة الصناعية وغيرت العالم",
47
+ "العلماء الذين غيروا مجرى التاريخ",
48
+ "أسرار الثقوب السوداء بطريقة مبسطة",
49
+ "حضارة وادي الرافدين وأثرها على العالم",
50
+ "كيف تعمل الذاكرة داخل دماغ الإنسان",
51
+ "اختراعات ظهرت بالصدفة وغيرت حياتنا",
52
+ "لماذا كان اكتشاف الكهرباء نقطة تحول في التاريخ",
53
+ "كيف عرف الإنسان الزمن قبل اختراع الساعة",
54
+ ]
55
+
56
+
57
+ def _data_file_path() -> str:
58
+ base = "/data" if os.path.isdir("/data") and "SPACE_ID" in os.environ else os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "data")
59
+ os.makedirs(base, exist_ok=True)
60
+ return os.path.join(base, "info_channel_data.json")
61
+
62
+
63
+ def _norm(s: str) -> str:
64
+ return re.sub(r"\s+", " ", BeautifulSoup(s or "", "html.parser").get_text(" ", strip=True)).strip()
65
+
66
+
67
+ def _compact_text(text: str, limit: int = ARTICLE_TEXT_LIMIT) -> str:
68
+ text = _norm(text)
69
+ if len(text) <= limit:
70
+ return text
71
+ parts = re.split(r"(?<=[.!?؟])\s+", text)
72
+ result: List[str] = []
73
+ size = 0
74
+ for part in parts:
75
+ if not part:
76
+ continue
77
+ extra = len(part) + (1 if result else 0)
78
+ if size + extra > limit:
79
+ break
80
+ result.append(part)
81
+ size += extra
82
+ return " ".join(result) or text[:limit].rstrip()
83
+
84
+
85
+ def _article_prompt(a: Dict[str, Any]) -> str:
86
+ return f"""أنت محرر قناة تيليجرام عربية اسمها قلعة المعلومات العامة.
87
+ اكتب المنشور النهائي فقط باللغة العربية.
88
+ السطر الأول عنوان جذاب قصير.
89
+ بعده ملخص قصصي مشوق من 4 إلى 8 أسطر، بدون تعداد.
90
+ لا تذكر المصدر ولا رابط القناة.
91
+ لا تخترع معلومة غير موجودة.
92
+ اختم بمعلومة قوية أو إحساس دهشة.
93
+ آخر سطر فقط 3 إلى 6 هاشتاكات مناسبة.
94
+ لا تضف #قلعة_المعلومات_العامة ولا التوقيع.
95
+ الطول قبل الهاشتاكات لا يتجاوز 900 حرف.
96
+
97
+ التصنيف: {a['category']}
98
+ العنوان: {a['title']}
99
+ الهاشتاكات المقترحة: {a['hashtags']}
100
+ المادة:
101
+ {a['text']}"""
102
+
103
+
104
+ def _fallback_prompt(topic: str) -> str:
105
+ return f"""اكتب منشور تيليجرام عربي عن: {topic}
106
+ عنوان جذاب، ثم قصة مشوقة من 4 إلى 8 أسطر بدون تعداد، ثم 3 إلى 6 هاشتاكات في آخر سطر.
107
+ لا تذكر المصدر ولا رابط القناة ولا التوقيع. لا تخترع أرقاماً أو حقائق دقيقة غير مؤكدة.
108
+ لا يتجاوز النص قبل الهاشتاكات 900 حرف."""
109
+
110
+
111
+ def _has_prompt_leak(text: str) -> bool:
112
+ bad = ["Key points:", "Story summary", "Editor for a Telegram channel", "Transform a provided", "No bullet points"]
113
+ low = (text or "").lower()
114
+ return any(b.lower() in low for b in bad)
115
+
116
+
117
+ def _numeric_tokens(text: str) -> set:
118
+ tokens = re.findall(r"(?<!\w)\d+(?:[.,]\d+)*", text or "")
119
+ return {t.replace(",", "") for t in tokens}
120
+
121
+
122
+ def _latin_names(text: str) -> set:
123
+ return set(re.findall(r"(?<![A-Za-z])[A-Z][A-Za-z]{2,}(?![A-Za-z])", text or ""))
124
+
125
+
126
+ def _validate_generated_post(post: str, a: Dict[str, Any]) -> bool:
127
+ if not isinstance(post, str) or not post.strip():
128
+ return False
129
+ if _has_prompt_leak(post):
130
+ return False
131
+ lines = [x.strip() for x in post.replace("**", "").splitlines() if x.strip()]
132
+ if len(lines) < 3:
133
+ return False
134
+ if len(lines[0]) > 180:
135
+ return False
136
+ hashtag_lines = [line for line in lines[1:] if "#" in line]
137
+ hashtags = re.findall(r"#\S+", " ".join(hashtag_lines))
138
+ if not 3 <= len(hashtags) <= 6:
139
+ return False
140
+ if re.search(r"https?://\S+", post):
141
+ return False
142
+ content_before_hashtags = "\n".join(line for line in lines if "#" not in line)
143
+ if len(content_before_hashtags) > 900:
144
+ return False
145
+ if a.get("mode") == "rss":
146
+ source = a.get("text", "")
147
+ if _numeric_tokens(post) - _numeric_tokens(source):
148
+ return False
149
+ source_names = {n.casefold() for n in _latin_names(source)}
150
+ output_names = {n for n in _latin_names(post) if n.casefold() not in {"html"}}
151
+ if any(n.casefold() not in source_names for n in output_names):
152
+ return False
153
+ return True
154
+
155
+
156
+ def _build_caption(post: str, signature: str = INFO_SIGNATURE) -> str:
157
+ lines = [x.strip() for x in post.replace("**", "").splitlines() if x.strip()]
158
+ title = lines[0] if lines else "معلومة جديدة تستحق أن تعرفها"
159
+ hs = [x for x in lines[1:] if "#" in x]
160
+ body_lines = [x for x in lines[1:] if "#" not in x]
161
+ tags = re.findall(r"#\S+", " ".join(hs))
162
+ tags = [x for x in tags if x != "#قلعة_المعلومات_العامة"][:6] or ["#علوم", "#معرفة", "#معلومات_عامة"]
163
+ body = "\n\n".join(body_lines) or "تفاصيل هذه المعلومة تكشف جانباً مثيراً من عالم المعرفة، وتفتح أمام القارئ سؤالاً جديداً."
164
+ tail = "\n\n━━━━━━━━━━━━\n\nلأنك تستحق أن تعرف\n\n" + " ".join(tags) + "\n\n" + (signature or INFO_SIGNATURE)
165
+ room = max(200, 900 - len(title) - len(tail))
166
+ if len(body) > room:
167
+ body = body[:room].rstrip() + "..."
168
+ caption = f"<b>{html.escape(title)}</b>\n\n<b>{html.escape(body)}</b>{tail}"
169
+ if len(caption) > 1020:
170
+ overflow = len(caption) - 1015
171
+ body = body[:max(100, len(body) - overflow)].rstrip() + "..."
172
+ caption = f"<b>{html.escape(title)}</b>\n\n<b>{html.escape(body)}</b>{tail}"
173
+ return caption
174
+
175
+
176
+ def _parse_rss_xml(xml_bytes: bytes) -> List[Dict[str, Any]]:
177
+ entries: List[Dict[str, Any]] = []
178
+ try:
179
+ root = ET.fromstring(xml_bytes)
180
+ except Exception:
181
+ return entries
182
+
183
+ def _strip_ns(tag: str) -> str:
184
+ return tag.split("}", 1)[-1] if "}" in tag else tag
185
+
186
+ items = root.findall(".//item")
187
+ if not items:
188
+ items = [el for el in root.iter() if _strip_ns(el.tag) == "entry"]
189
+
190
+ for item in items[:25]:
191
+ title = ""
192
+ link = ""
193
+ summary = ""
194
+ pub_ts = 0
195
+ images: List[str] = []
196
+ for child in item:
197
+ tag = _strip_ns(child.tag).lower()
198
+ text = (child.text or "").strip()
199
+ if tag == "title" and not title:
200
+ title = text
201
+ elif tag == "link":
202
+ href = child.attrib.get("href", "").strip()
203
+ if href and not link:
204
+ link = href
205
+ elif text and not link:
206
+ link = text
207
+ elif tag in ("description", "summary", "encoded", "content") and len(text) > len(summary):
208
+ summary = text
209
+ elif tag in ("pubdate", "published", "updated") and text and not pub_ts:
210
+ try:
211
+ dt = email.utils.parsedate_to_datetime(text)
212
+ pub_ts = int(dt.timestamp())
213
+ except Exception:
214
+ try:
215
+ dt = datetime.fromisoformat(text.replace("Z", "+00:00"))
216
+ pub_ts = int(dt.timestamp())
217
+ except Exception:
218
+ pass
219
+ elif tag in ("content", "thumbnail", "enclosure"):
220
+ u = child.attrib.get("url", "").strip()
221
+ t = child.attrib.get("type", "").lower()
222
+ if u.startswith("http") and (not t or t.startswith("image/") or u.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))):
223
+ images.append(u)
224
+ if title and link:
225
+ entries.append({
226
+ "title": _norm(title)[:180],
227
+ "link": link,
228
+ "summary": summary,
229
+ "ts": pub_ts,
230
+ "images": images,
231
+ })
232
+ return entries
233
+
234
+
235
+ class InfoChannelService:
236
+ def __init__(self):
237
+ self.data_path = _data_file_path()
238
+ self._lock = asyncio.Lock()
239
+ self._running = False
240
+
241
+ def _default_data(self) -> Dict[str, Any]:
242
+ return {
243
+ "enabled": True,
244
+ "channel_username": INFO_CHANNEL_USERNAME,
245
+ "slots": list(INFO_PUBLISH_SLOTS),
246
+ "signature": INFO_SIGNATURE,
247
+ "custom_prompt": "",
248
+ "rss_sources": [dict(s) for s in INFO_RSS_SOURCES],
249
+ "posted_links": [],
250
+ "posted_titles": [],
251
+ "posted_fallback": [],
252
+ "posted_slots": {},
253
+ "published_count": 0,
254
+ "last_published_at": 0,
255
+ "last_title": "",
256
+ }
257
+
258
+ def load_data(self) -> Dict[str, Any]:
259
+ default = self._default_data()
260
+ try:
261
+ if os.path.isfile(self.data_path):
262
+ with open(self.data_path, "r", encoding="utf-8") as f:
263
+ d = json.load(f)
264
+ if isinstance(d, dict):
265
+ for k, v in default.items():
266
+ d.setdefault(k, v)
267
+ return d
268
+ except Exception as e:
269
+ logger.error(f"InfoChannel: failed to load state: {e}")
270
+ return default
271
+
272
+ def save_data(self, data: Dict[str, Any]):
273
+ os.makedirs(os.path.dirname(self.data_path), exist_ok=True)
274
+ tmp = self.data_path + ".tmp"
275
+ with open(tmp, "w", encoding="utf-8") as f:
276
+ json.dump(data, f, ensure_ascii=False, indent=2)
277
+ os.replace(tmp, self.data_path)
278
+
279
+ def is_enabled(self) -> bool:
280
+ return bool(self.load_data().get("enabled", True))
281
+
282
+ def toggle_enabled(self) -> bool:
283
+ d = self.load_data()
284
+ d["enabled"] = not bool(d.get("enabled", True))
285
+ self.save_data(d)
286
+ return d["enabled"]
287
+
288
+ def get_target_channel(self) -> str:
289
+ d = self.load_data()
290
+ return d.get("channel_username") or INFO_CHANNEL_USERNAME
291
+
292
+ def get_slots(self) -> List[str]:
293
+ d = self.load_data()
294
+ slots = d.get("slots")
295
+ return list(slots) if isinstance(slots, list) and slots else list(INFO_PUBLISH_SLOTS)
296
+
297
+ def set_slots(self, slots: List[str]):
298
+ d = self.load_data()
299
+ d["slots"] = list(slots) if slots else list(INFO_PUBLISH_SLOTS)
300
+ self.save_data(d)
301
+
302
+ def get_signature(self) -> str:
303
+ d = self.load_data()
304
+ sig = d.get("signature")
305
+ return sig if isinstance(sig, str) and sig.strip() else INFO_SIGNATURE
306
+
307
+ def set_signature(self, sig: str):
308
+ d = self.load_data()
309
+ d["signature"] = (sig or "").strip() or INFO_SIGNATURE
310
+ self.save_data(d)
311
+
312
+ def get_custom_prompt(self) -> str:
313
+ return str(self.load_data().get("custom_prompt") or "").strip()
314
+
315
+ def set_custom_prompt(self, prompt: str):
316
+ d = self.load_data()
317
+ d["custom_prompt"] = (prompt or "").strip()
318
+ self.save_data(d)
319
+
320
+ def get_rss_sources(self) -> List[Dict[str, str]]:
321
+ d = self.load_data()
322
+ srcs = d.get("rss_sources")
323
+ if isinstance(srcs, list):
324
+ return srcs
325
+ return [dict(s) for s in INFO_RSS_SOURCES]
326
+
327
+ def add_rss_source(self, url: str, name: str = "", category: str = "معلومات عامة") -> bool:
328
+ url = (url or "").strip()
329
+ if not url.startswith(("http://", "https://")):
330
+ return False
331
+ d = self.load_data()
332
+ srcs = list(d.get("rss_sources") if isinstance(d.get("rss_sources"), list) else [dict(s) for s in INFO_RSS_SOURCES])
333
+ if any(str(s.get("url", "")).strip() == url for s in srcs):
334
+ return False
335
+ if not name:
336
+ from urllib.parse import urlparse
337
+ name = (urlparse(url).netloc or url).replace("www.", "")[:35]
338
+ srcs.append({"name": name, "category": category, "url": url, "hashtags": "#معلومات_عامة #معرفة #علوم"})
339
+ d["rss_sources"] = srcs
340
+ self.save_data(d)
341
+ return True
342
+
343
+ def remove_rss_source(self, index: int) -> bool:
344
+ d = self.load_data()
345
+ srcs = list(d.get("rss_sources") if isinstance(d.get("rss_sources"), list) else [dict(s) for s in INFO_RSS_SOURCES])
346
+ if 0 <= index < len(srcs):
347
+ srcs.pop(index)
348
+ d["rss_sources"] = srcs
349
+ self.save_data(d)
350
+ return True
351
+ return False
352
+
353
+ def reset_rss_sources(self):
354
+ d = self.load_data()
355
+ d["rss_sources"] = [dict(s) for s in INFO_RSS_SOURCES]
356
+ self.save_data(d)
357
+
358
+ def get_status(self) -> Dict[str, Any]:
359
+ d = self.load_data()
360
+ now = datetime.now(BAGHDAD_TZ)
361
+ today = now.strftime("%Y-%m-%d")
362
+ today_slots = list((d.get("posted_slots") or {}).get(today, []))
363
+ return {
364
+ "enabled": bool(d.get("enabled", True)),
365
+ "channel": self.get_target_channel(),
366
+ "slots": self.get_slots(),
367
+ "today_slots": today_slots,
368
+ "published_count": int(d.get("published_count", 0)),
369
+ "last_published_at": int(d.get("last_published_at", 0)),
370
+ "last_title": str(d.get("last_title", "")),
371
+ "rss_count": len(self.get_rss_sources()),
372
+ "signature": self.get_signature(),
373
+ "has_custom_prompt": bool(self.get_custom_prompt()),
374
+ }
375
+
376
+ async def _fetch_text(self, client: httpx.AsyncClient, url: str, timeout: int = 15) -> Optional[str]:
377
+ try:
378
+ r = await client.get(url, headers={"User-Agent": UA}, timeout=timeout, follow_redirects=True)
379
+ return r.text if r.status_code == 200 and r.text else None
380
+ except Exception:
381
+ return None
382
+
383
+ async def _extract_article_and_image(self, client: httpx.AsyncClient, entry: Dict[str, Any]) -> Tuple[str, Optional[str]]:
384
+ parts = [entry.get("title", ""), _norm(entry.get("summary", ""))]
385
+ images = list(entry.get("images") or [])
386
+ if entry.get("summary"):
387
+ try:
388
+ s = BeautifulSoup(entry["summary"], "html.parser")
389
+ img_tag = s.find("img")
390
+ if img_tag and img_tag.get("src", "").startswith("http"):
391
+ images.append(img_tag["src"])
392
+ except Exception:
393
+ pass
394
+ page_html = await self._fetch_text(client, entry.get("link", ""), timeout=15)
395
+ if page_html:
396
+ try:
397
+ soup = BeautifulSoup(page_html, "html.parser")
398
+ for attr, val in (("property", "og:image"), ("name", "twitter:image")):
399
+ meta = soup.find("meta", attrs={attr: val})
400
+ if meta and meta.get("content", "").startswith("http"):
401
+ images.append(meta["content"])
402
+ for bad in soup(["script", "style", "noscript", "header", "footer", "nav", "aside"]):
403
+ bad.decompose()
404
+ body = soup.find("article") or soup.find("main") or soup.body
405
+ if body:
406
+ paras = [_norm(p.get_text(" ", strip=True)) for p in body.find_all("p")]
407
+ parts.extend([p for p in paras if len(p) > 45][:9])
408
+ except Exception:
409
+ pass
410
+ text = _compact_text(" ".join(p for p in parts if p))
411
+ img_url = next((u for u in images if isinstance(u, str) and u.startswith("http")), None)
412
+ return text, img_url
413
+
414
+ async def _pick_candidate(self, data: Dict[str, Any]) -> Dict[str, Any]:
415
+ posted_links = {str(x).strip() for x in data.get("posted_links", []) if x}
416
+ posted_titles = {_norm(str(x)).casefold() for x in data.get("posted_titles", []) if x}
417
+ ranked: List[Tuple[int, Dict[str, Any], Dict[str, str]]] = []
418
+
419
+ async with httpx.AsyncClient(timeout=RSS_TIMEOUT, follow_redirects=True) as client:
420
+ for src in self.get_rss_sources():
421
+ for attempt in range(RSS_RETRIES):
422
+ try:
423
+ resp = await client.get(src["url"], headers={"User-Agent": UA}, timeout=RSS_TIMEOUT)
424
+ if resp.status_code == 200 and resp.content:
425
+ for e in _parse_rss_xml(resp.content):
426
+ link = e["link"]
427
+ title = e["title"]
428
+ if not link or not title or link in posted_links or title.casefold() in posted_titles:
429
+ continue
430
+ hay = (title + " " + _norm(e.get("summary", ""))).casefold()
431
+ if any(term in hay for term in NON_NEWS_TERMS):
432
+ continue
433
+ ranked.append((e["ts"], e, src))
434
+ break
435
+ except Exception:
436
+ if attempt + 1 < RSS_RETRIES:
437
+ await asyncio.sleep(1)
438
+
439
+ ranked.sort(key=lambda item: item[0], reverse=True)
440
+ for _, entry, src in ranked[:20]:
441
+ text, img_url = await self._extract_article_and_image(client, entry)
442
+ if len(text) < 220:
443
+ continue
444
+ return {
445
+ "mode": "rss",
446
+ "source": src["name"],
447
+ "category": src["category"],
448
+ "hashtags": src["hashtags"],
449
+ "title": entry["title"],
450
+ "link": entry["link"],
451
+ "text": text,
452
+ "image_url": img_url,
453
+ }
454
+
455
+ used_fb = set(data.get("posted_fallback", []))
456
+ avail = [t for t in FALLBACK_TOPICS if t not in used_fb] or list(FALLBACK_TOPICS)
457
+ topic = random.choice(avail)
458
+ return {
459
+ "mode": "fallback",
460
+ "source": "fallback",
461
+ "category": "معلومات عامة",
462
+ "hashtags": "#معلومات_عامة #معرفة #تاريخ #علوم",
463
+ "title": topic,
464
+ "link": "",
465
+ "text": topic,
466
+ "image_url": None,
467
+ }
468
+
469
+ async def _generate_post_via_ai_pool(self, candidate: Dict[str, Any]) -> Optional[str]:
470
+ """Uses the shared 25-key AIKeyManager + AIClient (Gemini / Groq / OpenRouter) round-robin."""
471
+ from modules.blogger.database import BloggerDatabase
472
+ from modules.blogger.ai_manager import AIKeyManager, AIClient
473
+
474
+ custom_p = self.get_custom_prompt()
475
+ if custom_p:
476
+ prompt = f"{custom_p}\n\nالتصنيف: {candidate['category']}\nالعنوان: {candidate['title']}\nالمادة:\n{candidate['text']}"
477
+ else:
478
+ prompt = _article_prompt(candidate) if candidate["mode"] == "rss" else _fallback_prompt(candidate["title"])
479
+ ai_client = AIClient(AIKeyManager(BloggerDatabase()))
480
+ try:
481
+ for _ in range(3):
482
+ raw = await ai_client.generate(prompt)
483
+ if not raw:
484
+ continue
485
+ if _validate_generated_post(raw, candidate):
486
+ return raw
487
+ raw = await ai_client.generate(prompt)
488
+ if raw and not _has_prompt_leak(raw) and len([x for x in raw.splitlines() if x.strip()]) >= 3:
489
+ return raw
490
+ return None
491
+ finally:
492
+ try:
493
+ await ai_client.close()
494
+ except Exception:
495
+ pass
496
+
497
+ async def _download_image(self, url: Optional[str]) -> Optional[str]:
498
+ if not url:
499
+ return None
500
+ try:
501
+ async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
502
+ r = await client.get(url, headers={"User-Agent": UA})
503
+ if r.status_code != 200 or not r.content:
504
+ return None
505
+ if len(r.content) < 1500 or len(r.content) > 8_000_000:
506
+ return None
507
+ ctype = (r.headers.get("content-type") or "").lower()
508
+ if ctype and not ctype.startswith("image/"):
509
+ return None
510
+ ext = ".png" if "png" in ctype else ".webp" if "webp" in ctype else ".jpg"
511
+ fd, path = tempfile.mkstemp(prefix="castle_info_", suffix=ext)
512
+ with os.fdopen(fd, "wb") as f:
513
+ f.write(r.content)
514
+ return path
515
+ except Exception:
516
+ return None
517
+
518
+ async def publish_one(self, bot_client, trigger: str = "scheduled", slot_key: Optional[str] = None) -> Tuple[bool, str]:
519
+ if not bot_client:
520
+ return False, "البوت غير متصل حالياً."
521
+ async with self._lock:
522
+ data = self.load_data()
523
+ candidate = await self._pick_candidate(data)
524
+ post_text = await self._generate_post_via_ai_pool(candidate)
525
+ if not post_text:
526
+ logger.error("InfoChannel: AI failed to generate valid post across all keys")
527
+ return False, "تعذر توليد المنشور عبر مفاتيح الذكاء الاصطناعي حالياً."
528
+
529
+ caption = _build_caption(post_text, signature=self.get_signature())
530
+ target = self.get_target_channel()
531
+ img_path = await self._download_image(candidate.get("image_url"))
532
+
533
+ # Optional inline Source button if enabled on this channel in DB
534
+ reply_markup = None
535
+ try:
536
+ import database as _main_db
537
+ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
538
+ from urllib.parse import urlparse
539
+ target_norm = str(target).lstrip("@").lower()
540
+ ch_rec = next((c for c in _main_db.get_all_channels() if str(c.get("id", "")) == str(target) or str(c.get("username", "") or "").lstrip("@").lower() == target_norm), None)
541
+ btn_mode = (ch_rec or {}).get("source_btn_mode", "off")
542
+ cand_link = candidate.get("link") or ""
543
+ if btn_mode == "post" and cand_link.startswith(("http://", "https://")):
544
+ reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton("🔗 المصدر", url=cand_link)]])
545
+ elif btn_mode == "home" and cand_link.startswith(("http://", "https://")):
546
+ p = urlparse(cand_link)
547
+ home_u = f"{p.scheme}://{p.netloc}" if p.scheme and p.netloc else cand_link
548
+ reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton("🔗 المصدر", url=home_u)]])
549
+ except Exception:
550
+ reply_markup = None
551
+
552
+ sent = False
553
+ try:
554
+ if img_path:
555
+ try:
556
+ await bot_client.send_photo(chat_id=target, photo=img_path, caption=caption, parse_mode=ParseMode.HTML, reply_markup=reply_markup)
557
+ sent = True
558
+ except Exception:
559
+ sent = False
560
+ if not sent:
561
+ await bot_client.send_message(chat_id=target, text=caption, parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=reply_markup)
562
+ sent = True
563
+ except Exception as e:
564
+ logger.error(f"InfoChannel: failed to publish to {target}: {e}")
565
+ return False, f"فشل النشر إلى {target}: {str(e)[:80]}"
566
+ finally:
567
+ if img_path and os.path.exists(img_path):
568
+ try:
569
+ os.remove(img_path)
570
+ except OSError:
571
+ pass
572
+
573
+ if candidate.get("link"):
574
+ data["posted_links"] = (data.get("posted_links") or [])[-299:] + [candidate["link"]]
575
+ if candidate.get("title"):
576
+ data["posted_titles"] = (data.get("posted_titles") or [])[-299:] + [candidate["title"]]
577
+ if candidate.get("mode") == "fallback":
578
+ data["posted_fallback"] = (data.get("posted_fallback") or [])[-50:] + [candidate["title"]]
579
+ if slot_key:
580
+ today = datetime.now(BAGHDAD_TZ).strftime("%Y-%m-%d")
581
+ slots_map = data.get("posted_slots") or {}
582
+ day_list = list(slots_map.get(today, []))
583
+ if slot_key not in day_list:
584
+ day_list.append(slot_key)
585
+ slots_map[today] = day_list
586
+ if len(slots_map) > 3:
587
+ for old_day in sorted(slots_map.keys())[:-3]:
588
+ slots_map.pop(old_day, None)
589
+ data["posted_slots"] = slots_map
590
+
591
+ data["published_count"] = int(data.get("published_count", 0)) + 1
592
+ data["last_published_at"] = int(time.time())
593
+ first_line = next((x.strip() for x in post_text.replace("**", "").splitlines() if x.strip()), candidate.get("title", ""))
594
+ data["last_title"] = first_line[:90]
595
+ self.save_data(data)
596
+
597
+ logger.info(f"[INFO_PUBLISH] ✅ [{datetime.now(BAGHDAD_TZ).strftime('%H:%M')}] تم النشر في قلعة المعلومات العامة ({trigger}): {first_line[:60]}")
598
+ return True, f"تم النشر بنجاح: {first_line[:60]}"
599
+
600
+ async def scheduler_loop(self, bot_client):
601
+ self._running = True
602
+ logger.info("✅ تم تشغيل خدمة المعلومات العامة")
603
+ await asyncio.sleep(20)
604
+ while self._running:
605
+ try:
606
+ if self.is_enabled():
607
+ now = datetime.now(BAGHDAD_TZ)
608
+ today = now.strftime("%Y-%m-%d")
609
+ hour_slot = f"{now.hour:02d}:00"
610
+ if hour_slot in self.get_slots() and now.minute < 15:
611
+ data = self.load_data()
612
+ today_done = (data.get("posted_slots") or {}).get(today, [])
613
+ if hour_slot not in today_done:
614
+ await self.publish_one(bot_client, trigger=f"slot:{hour_slot}", slot_key=hour_slot)
615
+ except Exception as e:
616
+ logger.error(f"InfoChannel scheduler loop error: {e}")
617
+ await asyncio.sleep(60)
618
+
619
+
620
+ _service_instance: Optional[InfoChannelService] = None
621
+
622
+
623
+ def get_info_service() -> InfoChannelService:
624
+ global _service_instance
625
+ if _service_instance is None:
626
+ _service_instance = InfoChannelService()
627
+ return _service_instance