Alialdlfy1 commited on
Commit
2dd41d7
·
verified ·
1 Parent(s): 39c6904

Delete modules/blogger/scheduler.py

Browse files
Files changed (1) hide show
  1. modules/blogger/scheduler.py +0 -369
modules/blogger/scheduler.py DELETED
@@ -1,369 +0,0 @@
1
- import asyncio
2
- import time
3
- import logging
4
- from typing import Optional, Dict, Any, List
5
- from datetime import datetime, timedelta
6
-
7
- from modules.blogger.database import BloggerDatabase
8
- from modules.blogger.processor import ArticleProcessor
9
-
10
- logger = logging.getLogger(__name__)
11
-
12
- POLL_INTERVAL = 600
13
- SCHEDULE_START_HOUR = 9
14
- SCHEDULE_END_HOUR = 23
15
- SCHEDULE_INTERVAL_MIN = 30
16
- SLOTS_PER_DAY = ((SCHEDULE_END_HOUR - SCHEDULE_START_HOUR) * 60) // SCHEDULE_INTERVAL_MIN + 1
17
-
18
-
19
- class BloggerScheduler:
20
- def __init__(self, db: BloggerDatabase, processor: ArticleProcessor, publisher):
21
- self.db = db
22
- self.processor = processor
23
- self.publisher = publisher
24
- self._running = False
25
- self._queue: List[Dict] = []
26
-
27
- async def start(self):
28
- self._running = True
29
- logger.info("BloggerScheduler: started")
30
- self._queue = self.db.get_articles_by_status("queued")
31
- logger.info(f"BloggerScheduler: loaded {len(self._queue)} queued articles from DB")
32
- if self._queue:
33
- logger.info(f"DB Load Sample Section: {self._queue[0].get('section', 'MISSING')}")
34
- while self._running:
35
- try:
36
- await self._cycle()
37
- except Exception as e:
38
- logger.exception(f"BloggerScheduler: cycle error: {e}")
39
- await asyncio.sleep(POLL_INTERVAL)
40
-
41
- async def stop(self):
42
- self._running = False
43
- logger.info("BloggerScheduler: stopped")
44
-
45
- async def _cycle(self):
46
- logger.info("BloggerScheduler: cycle start")
47
- if not self.publisher.config.is_enabled():
48
- logger.info("BloggerScheduler: publisher disabled, skipping cycle")
49
- return
50
- channels = self.db.get_all_channels()
51
- if not channels:
52
- logger.info("BloggerScheduler: no channels configured, skipping cycle")
53
- return
54
- logger.info(f"BloggerScheduler: {len(channels)} channels, starting fetch")
55
- await self._fetch_new_posts(channels)
56
- logger.info("BloggerScheduler: fetch done")
57
- await self._process_gemini_pending()
58
- await self._process_queue()
59
- logger.info("BloggerScheduler: cycle end")
60
-
61
- async def _fetch_new_posts(self, channels: List[Dict]):
62
- from bot_core import user_client
63
- if not user_client:
64
- logger.warning("BloggerScheduler: user_client not available for polling")
65
- return
66
- for ch in channels:
67
- if not ch.get("enabled", True):
68
- logger.info(f"BloggerScheduler: channel {ch.get('channel_id')} disabled, skip")
69
- continue
70
- ch_id = ch.get("channel_id", "")
71
- if not ch_id:
72
- continue
73
- try:
74
- last_id = ch.get("last_message_id", 0)
75
- chat_identifier = int(ch_id) if str(ch_id).lstrip('-').isdigit() else ch_id
76
- latest_id = last_id
77
- any_success = False
78
- logger.info(f"BloggerScheduler: polling channel {ch_id}, last_id={last_id}")
79
-
80
- # Drive the async generator manually so a single corrupted message
81
- # (e.g. Pyrogram failing to decode its entities) can be skipped
82
- # without losing the rest of the batch or blocking last_message_id.
83
- history_iter = user_client.get_chat_history(chat_identifier, limit=3).__aiter__()
84
- while True:
85
- try:
86
- msg = await history_iter.__anext__()
87
- except StopAsyncIteration:
88
- break
89
- except UnicodeDecodeError as e:
90
- logger.warning(
91
- f"BloggerScheduler: skipping a message in {ch_id} — "
92
- f"Pyrogram failed to decode it ({e}). Cannot recover its content; "
93
- f"continuing with the rest of the batch."
94
- )
95
- continue
96
- except Exception as e:
97
- logger.warning(f"BloggerScheduler: error fetching next message in {ch_id}, skipping it: {e}")
98
- continue
99
-
100
- if msg.id <= last_id:
101
- logger.info(f"BloggerScheduler: msg {msg.id} <= last_id {last_id}, break")
102
- break
103
- if msg.id > latest_id:
104
- latest_id = msg.id
105
- # Force str() to trigger any deferred UTF-16-LE decode NOW,
106
- # so the error is caught here — not later in _fingerprint.
107
- try:
108
- tmp = msg.text or msg.caption or ""
109
- except UnicodeDecodeError as e:
110
- logger.warning(f"BloggerScheduler: msg {msg.id} text decode failed, skipping: {e}")
111
- continue
112
- try:
113
- raw = str(tmp) if tmp else ""
114
- except (UnicodeDecodeError, UnicodeEncodeError) as e:
115
- logger.warning(f"BloggerScheduler: msg {msg.id} text conversion failed, skipping: {e}")
116
- continue
117
- if not raw.strip():
118
- logger.info(f"BloggerScheduler: msg {msg.id} has no text, skip")
119
- continue
120
- fingerprint = self.processor._fingerprint(raw, str(msg.id))
121
- if self.db.is_published(fingerprint):
122
- logger.info(f"BloggerScheduler: msg {msg.id} already published, skip")
123
- continue
124
- article = self.db.get_article(fingerprint)
125
- if article and article.get("status") in ("queued", "published"):
126
- logger.info(f"BloggerScheduler: msg {msg.id} already queued/published, skip")
127
- continue
128
- media = []
129
- if msg.photo:
130
- try:
131
- media.append({"type": "photo", "file_id": msg.photo.file_id})
132
- except Exception as e:
133
- logger.warning(f"BloggerScheduler: msg {msg.id} photo access failed, skipping media: {e}")
134
- else:
135
- logger.info(f"BloggerScheduler: msg {msg.id} has photo")
136
- elif msg.video:
137
- try:
138
- media.append({"type": "video", "file_id": msg.video.file_id})
139
- except Exception as e:
140
- logger.warning(f"BloggerScheduler: msg {msg.id} video access failed, skipping media: {e}")
141
- else:
142
- logger.info(f"BloggerScheduler: msg {msg.id} has video")
143
- chat_str = str(ch_id).replace('-100', '') if str(ch_id).lstrip('-').isdigit() else str(ch_id).lstrip('@')
144
- source_url = f"https://t.me/c/{chat_str}/{msg.id}"
145
- # Ingestion never calls Gemini directly: save straight to the pending
146
- # queue so a Gemini cooldown/outage can never cause a message to be lost.
147
- try:
148
- fingerprint = self.processor.enqueue_raw_post(raw, source_url, media, channel_id=ch_id, section=ch.get("section", ""))
149
- except Exception as e:
150
- logger.warning(f"BloggerScheduler: msg {msg.id} enqueue failed, skipping: {e}")
151
- continue
152
- if fingerprint:
153
- any_success = True
154
- logger.info(f"BloggerScheduler: msg {msg.id} from {ch_id} saved to Gemini pending queue")
155
- else:
156
- logger.info(f"BloggerScheduler: msg {msg.id} from {ch_id} already known/duplicate, skip")
157
- # last_message_id only depends on messages being durably captured (saved to
158
- # pending or already known) — never on whether Gemini processing succeeded,
159
- # and it is always reached now even if a message in between failed to decode.
160
- if latest_id > last_id:
161
- self.db.save_channel(ch_id, {**ch, "last_message_id": latest_id})
162
- logger.info(f"BloggerScheduler: updated last_message_id to {latest_id} for {ch_id}")
163
- except Exception as e:
164
- logger.warning(f"BloggerScheduler: failed to poll channel {ch_id}: {e}")
165
-
166
- async def _process_gemini_pending(self):
167
- """Process Gemini pending queue (raw posts waiting for AI processing).
168
- Runs only when Gemini keys are available (cooldown check done by caller).
169
- Drains in FIFO order — each success recovers one processed article."""
170
- pending = self.db.get_gemini_pending_queue()
171
- if not pending:
172
- logger.info("BloggerScheduler: Gemini pending queue is empty.")
173
- return
174
- logger.info(f"BloggerScheduler: {len(pending)} items in Gemini pending queue, processing...")
175
- while pending:
176
- recovered = await self.processor._process_next_pending()
177
- if not recovered:
178
- break
179
- recovered["status"] = "queued"
180
- ch_id = recovered.get("channel_id", "")
181
- if ch_id:
182
- ch = self.db.get_channel(ch_id)
183
- if ch:
184
- section_name = ch.get("section", "")
185
- recovered["section"] = section_name
186
- recovered["labels"] = list(self._get_section_labels(section_name))
187
- logger.info(f"Selected Section: {section_name}")
188
- logger.info(f"Section Loaded From DB: {section_name}")
189
- logger.info(f"Labels from section config: {recovered.get('labels', [])}")
190
- else:
191
- recovered_section = recovered.get("section", "")
192
- if recovered_section:
193
- recovered["labels"] = list(self._get_section_labels(recovered_section))
194
- logger.info(f"Channel {ch_id} not found, using pending section: {recovered_section}")
195
- else:
196
- logger.warning(f"Channel {ch_id} not found in DB, no section fallback")
197
- else:
198
- logger.warning(f"No channel_id on recovered article")
199
- logger.info(f"Section Before Queue: section={recovered.get('section', 'MISSING')}, labels={recovered.get('labels', [])}")
200
- self._queue.append(recovered)
201
- self.db.save_article(recovered["fingerprint"], recovered)
202
- logger.info(f"BloggerScheduler: recovered article '{recovered.get('title', '')[:30]}' from pending queue")
203
- pending = self.db.get_gemini_pending_queue()
204
-
205
- async def _process_queue(self):
206
- now = datetime.now()
207
- today = now.strftime("%Y-%m-%d")
208
- current_total_min = now.hour * 60 + now.minute
209
-
210
- # Build all slots: 09:00, 09:30, 10:00, … 23:00 (29 slots)
211
- slots = []
212
- for hour in range(SCHEDULE_START_HOUR, SCHEDULE_END_HOUR):
213
- for minute in (0, 30):
214
- slots.append((hour, minute))
215
- slots.append((SCHEDULE_END_HOUR, 0))
216
- if not slots:
217
- return
218
-
219
- # Load persisted schedule state
220
- state = self.db.get_schedule_state()
221
- last_day = state.get("day", "")
222
- last_slot = state.get("last_slot", -1)
223
-
224
- # Reset for a new day
225
- if last_day != today:
226
- last_slot = -1
227
- state["day"] = today
228
- state["last_slot"] = -1
229
- self.db.save_schedule_state(state)
230
- logger.info(f"BloggerScheduler: new day {today}, reset schedule")
231
-
232
- queue = [a for a in self._queue if a.get("status") == "queued"]
233
- if not queue:
234
- return
235
-
236
- next_slot_idx = last_slot + 1
237
- if next_slot_idx >= len(slots):
238
- logger.info(f"BloggerScheduler: all {len(slots)} slots used today, carry over to tomorrow")
239
- return
240
-
241
- next_hour, next_min = slots[next_slot_idx]
242
- next_total_min = next_hour * 60 + next_min
243
-
244
- # Not time yet
245
- if current_total_min < next_total_min:
246
- logger.info(f"BloggerScheduler: next slot {next_hour:02d}:{next_min:02d}, current {now.hour:02d}:{now.minute:02d}, waiting")
247
- return
248
-
249
- # Past the slot window — skip it to prevent catch-up burst publishing
250
- slot_window_end = next_total_min + SCHEDULE_INTERVAL_MIN
251
- if current_total_min >= slot_window_end:
252
- logger.info(f"BloggerScheduler: slot {next_slot_idx} ({next_hour:02d}:{next_min:02d}) window already passed, skipping")
253
- state["last_slot"] = next_slot_idx
254
- self.db.save_schedule_state(state)
255
- return
256
-
257
- # Time to publish ONE article
258
- channels = {c.get("channel_id"): c for c in self.db.get_all_channels()}
259
- today_published = self._today_published_count()
260
- article = queue[0]
261
-
262
- ch_id = article.get("channel_id", "")
263
- ch_config = channels.get(ch_id, {})
264
- logger.info(f"Selected Article ID: {article.get('fingerprint', 'N/A')[:16]}")
265
- logger.info(f"Selected Section: {article.get('section', 'MISSING')}")
266
- logger.info(f"Selected Labels: {article.get('labels', 'MISSING')}")
267
- logger.info(f"Selected Hashtags: {article.get('hashtags', 'MISSING')}")
268
- logger.info(f"Article keys: {list(article.keys())}")
269
-
270
- # Resolve section on the article itself so it propagates to publisher, labels, daily count
271
- if not article.get("section"):
272
- article["section"] = ch_config.get("section", "")
273
- logger.info(f"Section was MISSING, resolved from channel to: {article['section']}")
274
-
275
- section = article["section"]
276
- section_today = today_published.get(section, 0)
277
- daily_limit = ch_config.get("daily_limit", 10)
278
- logger.info(f"Incoming Section: {section}")
279
- logger.info(f"Daily Limit Section: {section}")
280
- logger.info(f"Daily Count: {section_today}")
281
- logger.info(f"Daily Limit: {daily_limit}")
282
- decision = "SKIP - limit reached" if section_today >= daily_limit else "PUBLISH"
283
- logger.info(f"Decision: {decision}")
284
- logger.info("Before Daily Limit")
285
- if section_today >= daily_limit:
286
- logger.info(f"BloggerScheduler: daily limit {daily_limit} for section {section} reached, skipping article and scheduling next slot")
287
- state["last_slot"] = next_slot_idx
288
- self.db.save_schedule_state(state)
289
- return
290
- logger.info("After Daily Limit")
291
-
292
- logger.info("Before Publish")
293
- logger.info(f"BloggerScheduler: publishing article '{article.get('title', '')[:30]}' in slot {next_hour:02d}:{next_min:02d}")
294
- logger.info(f"Section Before Publisher: section={section}")
295
- logger.info(f"Article dict has labels: {article.get('labels', [])}")
296
- logger.info(f"Article dict has hashtags: {article.get('hashtags', 'MISSING')}")
297
- html = self.processor.make_article_html(article)
298
- labels = list(self._get_section_labels(section))
299
- logger.info(f"Labels Sent To Blogger: {labels}")
300
- blogger_article = {
301
- "title": article.get("title", "عنوان المقال"),
302
- "content": html,
303
- "labels": labels,
304
- }
305
- post_id = await self.publisher.publish_article(blogger_article, article.get("fingerprint"))
306
- logger.info("After Publish")
307
- if post_id:
308
- self.db.update_article_status(article["fingerprint"], "published", {
309
- "post_id": post_id,
310
- "published_at": int(time.time()),
311
- })
312
- self.db.increment_daily_count(section)
313
- logger.info(f"BloggerScheduler: published '{article.get('title', '')[:30]}' (post_id={post_id})")
314
- else:
315
- self.db.update_article_status(article["fingerprint"], "failed", {
316
- "failed_at": int(time.time()),
317
- })
318
- logger.warning(f"BloggerScheduler: failed to publish '{article.get('title', '')[:30]}'")
319
-
320
- article["status"] = "published" if post_id else "failed"
321
- logger.info("Before Queue Pop")
322
- self._queue = [a for a in self._queue if a.get("fingerprint") != article["fingerprint"]]
323
- logger.info("After Queue Pop")
324
-
325
- # Mark this slot as used
326
- state["last_slot"] = next_slot_idx
327
- self.db.save_schedule_state(state)
328
- logger.info(f"BloggerScheduler: slot {next_slot_idx} used, next at slot {next_slot_idx + 1}")
329
-
330
- def _can_publish_now(self, ch_config: Dict, current_hour: int, today_published: Dict) -> bool:
331
- if not ch_config.get("enabled", True):
332
- logger.info(f"BloggerScheduler: channel disabled")
333
- return False
334
- start_hour = ch_config.get("start_hour", 9)
335
- end_hour = ch_config.get("end_hour", 23)
336
- if current_hour < start_hour or current_hour >= end_hour:
337
- logger.info(f"BloggerScheduler: current hour {current_hour} outside window {start_hour}-{end_hour}")
338
- return False
339
- daily_limit = ch_config.get("daily_limit", 10)
340
- section = ch_config.get("section", "")
341
- section_count = today_published.get(section, 0)
342
- if section_count >= daily_limit:
343
- logger.info(f"BloggerScheduler: daily limit {daily_limit} reached for section {section}")
344
- return False
345
- return True
346
-
347
- def _today_published_count(self) -> Dict:
348
- today = time.strftime("%Y-%m-%d")
349
- stats = self.db.get_stats()
350
- daily = stats.get("daily", {})
351
- return daily.get(today, {})
352
-
353
- def _get_section_labels(self, section_name: str) -> list:
354
- sections = self.db.get_all_sections()
355
- for sdata in sections.values():
356
- if sdata.get("name") == section_name:
357
- labels = sdata.get("labels", [])
358
- if labels:
359
- return list(labels)
360
- return [section_name]
361
- if section_name and section_name != "general":
362
- return [section_name]
363
- return []
364
-
365
- def add_to_queue(self, article: Dict):
366
- article["status"] = "queued"
367
- self._queue.append(article)
368
- self.db.save_article(article["fingerprint"], article)
369
- logger.info(f"BloggerScheduler: manually queued article '{article.get('title', '')[:30]}'")