Alialdlfy1 commited on
Commit
baede9c
·
verified ·
1 Parent(s): 087b896

Upload scheduler.py

Browse files
Files changed (1) hide show
  1. modules/blogger/scheduler.py +820 -0
modules/blogger/scheduler.py ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Keep an unpatched reference for converting persisted Unix timestamps. Tests
8
+ # patch the module-level datetime to simulate scheduler time.
9
+ REAL_DATETIME = datetime
10
+
11
+ from modules.blogger.database import BloggerDatabase
12
+ from modules.blogger.processor import ArticleProcessor
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ POLL_INTERVAL = 600
17
+ SCHEDULE_START_HOUR = 9
18
+ SCHEDULE_END_HOUR = 23
19
+ SCHEDULE_INTERVAL_MIN = 30
20
+ SLOTS_PER_DAY = ((SCHEDULE_END_HOUR - SCHEDULE_START_HOUR) * 60) // SCHEDULE_INTERVAL_MIN + 1
21
+
22
+ # Progressive AI draining: how many articles to recover from the Gemini pending queue per cycle.
23
+ PROGRESSIVE_DRAIN_BATCH = 5
24
+
25
+ # Default fixed-slot sections: these sections publish at explicit daily times
26
+ # ("HH:MM", 24h format) instead of the generic 30-minute queue slots.
27
+ # Any future section can be added here without touching the rest of the scheduler.
28
+ P28_SECTION_FIXED_SLOTS = {
29
+ "وظائف": ["10:00", "14:00", "18:00", "22:00"],
30
+ }
31
+ # A slotted section may publish one article per slot per cycle. The slot's fixed time
32
+ # plus this grace window is the moment it becomes publishable; missed slots are
33
+ # processed as soon as they are the earliest remaining slot (catch-up of the
34
+ # earliest missed slot only — no burst publishing).
35
+ P28_SLOT_GRACE_MIN = 30
36
+
37
+
38
+ class BloggerScheduler:
39
+ def __init__(self, db: BloggerDatabase, processor: ArticleProcessor, publisher):
40
+ self.db = db
41
+ self.processor = processor
42
+ self.publisher = publisher
43
+ self._running = False
44
+ self._queue: List[Dict] = []
45
+
46
+ async def start(self):
47
+ self._running = True
48
+ logger.info("BloggerScheduler: started")
49
+ self._queue = self.db.get_articles_by_status("queued")
50
+ logger.info(f"BloggerScheduler: loaded {len(self._queue)} queued articles from DB")
51
+ if self._queue:
52
+ logger.info(f"DB Load Sample Section: {self._queue[0].get('section', 'MISSING')}")
53
+ while self._running:
54
+ try:
55
+ await self._cycle()
56
+ except Exception as e:
57
+ logger.exception(f"BloggerScheduler: cycle error: {e}")
58
+ await asyncio.sleep(POLL_INTERVAL)
59
+
60
+ async def stop(self):
61
+ self._running = False
62
+ logger.info("BloggerScheduler: stopped")
63
+
64
+ async def _cycle(self):
65
+ logger.info("BloggerScheduler: cycle start")
66
+ if not self.publisher.config.is_enabled():
67
+ logger.info("BloggerScheduler: publisher disabled, skipping cycle")
68
+ return
69
+ channels = self.db.get_all_channels()
70
+ if not channels:
71
+ logger.info("BloggerScheduler: no channels configured, skipping cycle")
72
+ return
73
+ logger.info(f"BloggerScheduler: {len(channels)} channels, starting fetch")
74
+ await self._fetch_new_posts(channels)
75
+ logger.info("BloggerScheduler: fetch done")
76
+ await self._process_gemini_pending(channels)
77
+ await self._process_queue(channels)
78
+ logger.info("BloggerScheduler: cycle end")
79
+
80
+ async def _fetch_new_posts(self, channels: List[Dict]):
81
+ from bot_core import user_client
82
+ if not user_client:
83
+ logger.warning("BloggerScheduler: user_client not available for polling")
84
+ return
85
+ for ch in channels:
86
+ if not ch.get("enabled", True):
87
+ logger.info(f"BloggerScheduler: channel {ch.get('channel_id')} disabled, skip")
88
+ continue
89
+ ch_id = ch.get("channel_id", "")
90
+ if not ch_id:
91
+ continue
92
+ try:
93
+ last_id = ch.get("last_message_id", 0)
94
+ chat_identifier = int(ch_id) if str(ch_id).lstrip('-').isdigit() else ch_id
95
+ latest_id = last_id
96
+ any_success = False
97
+ logger.info(f"BloggerScheduler: polling channel {ch_id}, last_id={last_id}")
98
+
99
+ # Drive the async generator manually so a single corrupted message
100
+ # (e.g. Pyrogram failing to decode its entities) can be skipped
101
+ # without losing the rest of the batch or blocking last_message_id.
102
+ history_iter = user_client.get_chat_history(chat_identifier, limit=3).__aiter__()
103
+ while True:
104
+ try:
105
+ msg = await history_iter.__anext__()
106
+ except StopAsyncIteration:
107
+ break
108
+ except UnicodeDecodeError as e:
109
+ logger.warning(
110
+ f"BloggerScheduler: skipping a message in {ch_id} — "
111
+ f"Pyrogram failed to decode it ({e}). Cannot recover its content; "
112
+ f"continuing with the rest of the batch."
113
+ )
114
+ continue
115
+ except Exception as e:
116
+ logger.warning(f"BloggerScheduler: error fetching next message in {ch_id}, skipping it: {e}")
117
+ continue
118
+
119
+ if msg.id <= last_id:
120
+ logger.info(f"BloggerScheduler: msg {msg.id} <= last_id {last_id}, break")
121
+ break
122
+ if msg.id > latest_id:
123
+ latest_id = msg.id
124
+ # Force str() to trigger any deferred UTF-16-LE decode NOW,
125
+ # so the error is caught here — not later in _fingerprint.
126
+ try:
127
+ tmp = msg.text or msg.caption or ""
128
+ except UnicodeDecodeError as e:
129
+ logger.warning(f"BloggerScheduler: msg {msg.id} text decode failed, skipping: {e}")
130
+ continue
131
+ try:
132
+ raw = str(tmp) if tmp else ""
133
+ except (UnicodeDecodeError, UnicodeEncodeError) as e:
134
+ logger.warning(f"BloggerScheduler: msg {msg.id} text conversion failed, skipping: {e}")
135
+ continue
136
+ if not raw.strip():
137
+ logger.info(f"BloggerScheduler: msg {msg.id} has no text, skip")
138
+ continue
139
+ fingerprint = self.processor._fingerprint(raw, str(msg.id))
140
+ if self.db.is_published(fingerprint):
141
+ logger.info(f"BloggerScheduler: msg {msg.id} already published, skip")
142
+ continue
143
+ article = self.db.get_article(fingerprint)
144
+ if article and article.get("status") in ("queued", "published"):
145
+ logger.info(f"BloggerScheduler: msg {msg.id} already queued/published, skip")
146
+ continue
147
+ media = []
148
+ if msg.photo:
149
+ try:
150
+ media.append({"type": "photo", "file_id": msg.photo.file_id})
151
+ except Exception as e:
152
+ logger.warning(f"BloggerScheduler: msg {msg.id} photo access failed, skipping media: {e}")
153
+ else:
154
+ logger.info(f"BloggerScheduler: msg {msg.id} has photo")
155
+ elif msg.video:
156
+ try:
157
+ media.append({"type": "video", "file_id": msg.video.file_id})
158
+ except Exception as e:
159
+ logger.warning(f"BloggerScheduler: msg {msg.id} video access failed, skipping media: {e}")
160
+ else:
161
+ logger.info(f"BloggerScheduler: msg {msg.id} has video")
162
+ chat_str = str(ch_id).replace('-100', '') if str(ch_id).lstrip('-').isdigit() else str(ch_id).lstrip('@')
163
+ source_url = f"https://t.me/c/{chat_str}/{msg.id}"
164
+ # Ingestion never calls Gemini directly: save straight to the pending
165
+ # queue so a Gemini cooldown/outage can never cause a message to be lost.
166
+ try:
167
+ fingerprint = self.processor.enqueue_raw_post(raw, source_url, media, channel_id=ch_id, section=ch.get("section", ""))
168
+ except Exception as e:
169
+ logger.warning(f"BloggerScheduler: msg {msg.id} enqueue failed, skipping: {e}")
170
+ continue
171
+ if fingerprint:
172
+ any_success = True
173
+ logger.info(f"BloggerScheduler: msg {msg.id} from {ch_id} saved to Gemini pending queue")
174
+ else:
175
+ logger.info(f"BloggerScheduler: msg {msg.id} from {ch_id} already known/duplicate, skip")
176
+ # last_message_id only depends on messages being durably captured (saved to
177
+ # pending or already known) — never on whether Gemini processing succeeded,
178
+ # and it is always reached now even if a message in between failed to decode.
179
+ if latest_id > last_id:
180
+ self.db.save_channel(ch_id, {**ch, "last_message_id": latest_id})
181
+ logger.info(f"BloggerScheduler: updated last_message_id to {latest_id} for {ch_id}")
182
+ except Exception as e:
183
+ logger.warning(f"BloggerScheduler: failed to poll channel {ch_id}: {e}")
184
+
185
+ def _get_section_fixed_slots(self, section: str) -> Optional[List[str]]:
186
+ """Fixed daily publish slots for a section, if any. Override order: sections
187
+ table (per-section publish_slots) > P28_SECTION_FIXED_SLOTS default map.
188
+ Sections without an override keep the generic 30-minute queue slots."""
189
+ sections = self.db.get_all_sections()
190
+ for sdata in sections.values():
191
+ if sdata.get("name") == section:
192
+ override = sdata.get("publish_slots")
193
+ if override:
194
+ return list(override)
195
+ break
196
+ return list(P28_SECTION_FIXED_SLOTS.get(section, []))
197
+
198
+ def _p28_remaining_slot_keys(self, state_sections: Dict, section: str, slots: List[str], now_min: int) -> List[str]:
199
+ """Slot keys still unfixed for the section today, in schedule order.
200
+ A slot becomes publishable when its fixed time (+ grace) has passed and it
201
+ was not yet fixed/published (a truthy fingerprint). The "_locked" sentinel
202
+ means a slot is claimed this cycle and is counted as consumed for today.
203
+ Earlier missed slots come first so a missed 10:00 slot is handled
204
+ immediately as the earliest remaining slot, while slots still in the
205
+ future wait for their time."""
206
+ sec = state_sections.get(section, {})
207
+ # A slot is consumed for today once it appears in 'fixed' at all: a real
208
+ # fingerprint means published, an empty string means fixed-empty forever,
209
+ # and "_locked" means claimed mid-cycle (all three are used slots).
210
+ fixed = {k for k, v in sec.get("fixed", {}).items() if v != "_locked"}
211
+ remaining = []
212
+ for key in slots:
213
+ if key in fixed:
214
+ continue
215
+ hh, mm = (int(p) for p in key.split(":"))
216
+ total = hh * 60 + mm
217
+ # A missed slot (now past its fixed time) is catch-up publishable
218
+ # immediately on the next cycle (per requirement 2); a future slot is
219
+ # publishable exactly at its fixed time — never earlier (the timing
220
+ # gate lives in _process_slots). All unfixed slots stay in the
221
+ # remaining list: the scheduler picks the earliest one and either
222
+ # publishes it (when due) or returns "not yet due".
223
+ remaining.append(key)
224
+ return remaining
225
+
226
+ async def _process_gemini_pending(self, channels: List[Dict] = None):
227
+ """Process Gemini pending queue (raw posts waiting for AI processing).
228
+ Runs only when Gemini keys are available (cooldown check done by caller).
229
+ Drains progressively in batches of PROGRESSIVE_DRAIN_BATCH so a large backlog
230
+ never blocks one scheduler cycle — each success recovers one processed article.
231
+ For sections that declared fixed daily slots, draining is additionally capped
232
+ at the number of remaining unfixed slots today, so AI (and Gemini keys)
233
+ is never spent preparing candidates that cannot be published."""
234
+ pending = self.db.get_gemini_pending_queue()
235
+ if not pending:
236
+ logger.info("BloggerScheduler: Gemini pending queue is empty.")
237
+ return
238
+ max_batch = PROGRESSIVE_DRAIN_BATCH
239
+ # Section-aware drain cap for slotted sections (see _process_queue for the
240
+ # matching slot-side logic). Generic sections keep PROGRESSIVE_DRAIN_BATCH.
241
+ now_now = datetime.now()
242
+ today = now_now.date().strftime("%Y-%m-%d")
243
+ now_min = now_now.hour * 60 + now_now.minute
244
+ state = self.db.get_slots_state()
245
+ # Per slotted section, no more pending candidates than unfixed slots
246
+ # remaining today; the batch limit is the tightest such cap (>=1), so
247
+ # AI/Gemini is never spent preparing candidates that cannot publish.
248
+ section_cap_used = False
249
+ section_remaining: Dict[str, int] = {}
250
+ if state.get("day") == today:
251
+ # Slots state already initialized for today: cap at the unfixed
252
+ # slots still available (missed slots are included since they can
253
+ # still catch up; fixed-empty slots are excluded).
254
+ for section, slots in P28_SECTION_FIXED_SLOTS.items():
255
+ remaining = self._p28_remaining_slot_keys(state.get("sections", {}), section, slots, now_min)
256
+ if remaining:
257
+ section_remaining[section] = len(remaining)
258
+ logger.info(f"BloggerScheduler: section '{section}' has {len(remaining)} unfixed slots remaining today, "
259
+ f"pending drain for this section limited accordingly")
260
+ section_cap_used = True
261
+ else:
262
+ # First cycle of the day — slots state has not been reset yet (the
263
+ # reset lives in _process_queue which runs after pending drain).
264
+ # Conservatively cap at the full declared slot counts so a big
265
+ # backlog can never spend more AI than the day can publish.
266
+ # Only slotted sections that actually have pending items are capped;
267
+ # sections without fixed slots keep the full batch limit.
268
+ pending_sections = set(p.get("section", "") for p in pending)
269
+ for section, slots in P28_SECTION_FIXED_SLOTS.items():
270
+ if slots and section in pending_sections:
271
+ section_remaining[section] = len(slots)
272
+ section_cap_used = True
273
+ if section_cap_used:
274
+ limit = min(max_batch, max(1, min(section_remaining.values())))
275
+ else:
276
+ limit = max_batch
277
+ logger.info(f"BloggerScheduler: {len(pending)} items in Gemini pending queue, processing batch of up to {limit}...")
278
+ processed = 0
279
+ # Seed the per-section counters with the candidates ALREADY queued in the
280
+ # memory queue: a later drain invocation must see the coverage built by
281
+ # earlier batches/cycles, otherwise the cap would over-spend by one.
282
+ section_pending_counts: Dict[str, int] = {}
283
+ for _a in self._queue:
284
+ if _a.get("status") == "queued" and self._get_section_fixed_slots(_a.get("section", "")):
285
+ section_pending_counts[_a.get("section", "")] = (
286
+ section_pending_counts.get(_a.get("section", ""), 0) + 1)
287
+
288
+ def _section_max_allowed(section: str) -> int:
289
+ if section in section_remaining:
290
+ # Day-start fallback: cap at the full declared slot count
291
+ # until the slots state gets initialized this cycle.
292
+ return section_remaining[section]
293
+ today_state = self.db.get_slots_state()
294
+ if today_state.get("day") == today:
295
+ slots_def = self._get_section_fixed_slots(section)
296
+ remaining = self._p28_remaining_slot_keys(
297
+ today_state.get("sections", {}), section, slots_def, now_min)
298
+ return len(remaining)
299
+ slots_def = self._get_section_fixed_slots(section)
300
+ return len(slots_def)
301
+
302
+ def _cap_reached() -> bool:
303
+ if not section_cap_used:
304
+ return False
305
+ for section in section_pending_counts:
306
+ slots_def = self._get_section_fixed_slots(section)
307
+ if not slots_def:
308
+ continue
309
+ max_allowed = _section_max_allowed(section)
310
+ queued_now = sum(1 for a in self._queue
311
+ if a.get("section") == section and a.get("status") == "queued")
312
+ if queued_now >= max(1, max_allowed):
313
+ return True
314
+ return False
315
+
316
+ while pending and processed < limit and not _cap_reached():
317
+ # Slotted-section drain cap (pre-consume check): never spend AI
318
+ # preparing a candidate once the memory queue already covers all
319
+ # unfixed slots of that section for today.
320
+ if _cap_reached():
321
+ logger.info(f"BloggerScheduler: stop draining pending for sections with no unfixed slots today")
322
+ break
323
+ recovered = await self.processor._process_next_pending()
324
+ if not recovered:
325
+ break
326
+ processed += 1
327
+ recovered["status"] = "queued"
328
+ ch_id = recovered.get("channel_id", "")
329
+ if ch_id:
330
+ ch = self.db.get_channel(ch_id)
331
+ if ch:
332
+ section_name = ch.get("section", "")
333
+ recovered["section"] = section_name
334
+ recovered["labels"] = list(self._get_section_labels(section_name))
335
+ logger.info(f"Selected Section: {section_name}")
336
+ logger.info(f"Section Loaded From DB: {section_name}")
337
+ logger.info(f"Labels from section config: {recovered.get('labels', [])}")
338
+ else:
339
+ recovered_section = recovered.get("section", "")
340
+ if recovered_section:
341
+ recovered["labels"] = list(self._get_section_labels(recovered_section))
342
+ logger.info(f"Channel {ch_id} not found, using pending section: {recovered_section}")
343
+ else:
344
+ logger.warning(f"Channel {ch_id} not found in DB, no section fallback")
345
+ else:
346
+ logger.warning(f"No channel_id on recovered article")
347
+ logger.info(f"Section Before Queue: section={recovered.get('section', 'MISSING')}, labels={recovered.get('labels', [])}")
348
+ self._queue.append(recovered)
349
+ self.db.save_article(recovered["fingerprint"], recovered)
350
+ section_pending_counts[recovered.get("section", "")] = section_pending_counts.get(recovered.get("section", ""), 0) + 1
351
+ logger.info(f"BloggerScheduler: recovered article '{recovered.get('title', '')[:30]}' from pending queue")
352
+ pending = self.db.get_gemini_pending_queue()
353
+
354
+ async def _process_queue(self, channels: List[Dict] = None):
355
+ if channels is None:
356
+ channels = self.db.get_all_channels()
357
+ now = datetime.now()
358
+ today = now.strftime("%Y-%m-%d")
359
+ current_total_min = now.hour * 60 + now.minute
360
+
361
+ # Build all generic slots: 09:00, 09:30, 10:00, … 23:00 (29 slots)
362
+ slots = []
363
+ for hour in range(SCHEDULE_START_HOUR, SCHEDULE_END_HOUR):
364
+ for minute in (0, 30):
365
+ slots.append((hour, minute))
366
+ slots.append((SCHEDULE_END_HOUR, 0))
367
+ if not slots:
368
+ return
369
+
370
+ # Load persisted schedule state
371
+ state = self.db.get_schedule_state()
372
+ last_day = state.get("day", "")
373
+ last_slot = state.get("last_slot", -1)
374
+
375
+ # Reset for a new day
376
+ if last_day != today:
377
+ last_slot = -1
378
+ state["day"] = today
379
+ state["last_slot"] = -1
380
+ self.db.save_schedule_state(state)
381
+ # Daily slots state resets with the new day as well
382
+ self.db.save_slots_state({"day": today, "sections": {}})
383
+ logger.info(f"BloggerScheduler: new day {today}, reset schedule and daily slots")
384
+
385
+ # ---------- P28 fixed-slot sections ----------
386
+ # Sections with declared fixed daily times pick their own article at slot time
387
+ # (newest queued candidate of that section), independent of the generic queue.
388
+ # If a slot is fixed/published this cycle, the cycle ends here (one publish
389
+ # per cycle). If no slot could be published (not yet due / no candidate),
390
+ # the cycle falls through to the generic 30-minute queue below.
391
+ p28_result = await self._process_slots(now, today, current_total_min)
392
+ if p28_result is not None:
393
+ action, _reason = p28_result
394
+ if action is True:
395
+ return # a fixed-slot section published this cycle
396
+ # (False, ...) — nothing was published; continue with the generic queue.
397
+ # Generic 30-minute FIFO. Articles of P28 slotted sections NEVER use this
398
+ # path (they publish only via their fixed slots), so a late-arriving job
399
+ # cannot leak through the generic queue and cannot starve news/sports.
400
+ queue = [a for a in self._queue
401
+ if a.get("status") == "queued"
402
+ and a.get("section") not in P28_SECTION_FIXED_SLOTS]
403
+ if not queue:
404
+ return
405
+
406
+ next_slot_idx = last_slot + 1
407
+ if next_slot_idx >= len(slots):
408
+ logger.info(f"BloggerScheduler: all {len(slots)} slots used today, carry over to tomorrow")
409
+ return
410
+
411
+ next_hour, next_min = slots[next_slot_idx]
412
+ next_total_min = next_hour * 60 + next_min
413
+
414
+ # Not time yet
415
+ if current_total_min < next_total_min:
416
+ logger.info(f"BloggerScheduler: next slot {next_hour:02d}:{next_min:02d}, current {now.hour:02d}:{now.minute:02d}, waiting")
417
+ return
418
+
419
+ # Past the slot window — skip it to prevent catch-up burst publishing
420
+ slot_window_end = next_total_min + SCHEDULE_INTERVAL_MIN
421
+ if current_total_min >= slot_window_end:
422
+ logger.info(f"BloggerScheduler: slot {next_slot_idx} ({next_hour:02d}:{next_min:02d}) window already passed, skipping")
423
+ state["last_slot"] = next_slot_idx
424
+ self.db.save_schedule_state(state)
425
+ return
426
+
427
+ # Time to publish ONE article from the generic queue (sections without
428
+ # fixed daily slots keep their existing 30-minute FIFO behavior)
429
+ today_published = self._today_published_count()
430
+ article = queue[0]
431
+
432
+ ch_id = article.get("channel_id", "")
433
+ ch_config = next((c for c in channels if c.get("channel_id") == ch_id), {}) or {}
434
+ logger.info(f"Selected Article ID: {article.get('fingerprint', 'N/A')[:16]}")
435
+ logger.info(f"Selected Section: {article.get('section', 'MISSING')}")
436
+ logger.info(f"Selected Labels: {article.get('labels', 'MISSING')}")
437
+ logger.info(f"Selected Hashtags: {article.get('hashtags', 'MISSING')}")
438
+ logger.info(f"Article keys: {list(article.keys())}")
439
+
440
+ # Resolve section on the article itself so it propagates to publisher, labels, daily count
441
+ if not article.get("section"):
442
+ article["section"] = ch_config.get("section", "")
443
+ logger.info(f"Section was MISSING, resolved from channel to: {article['section']}")
444
+
445
+ section = article["section"]
446
+ section_today = today_published.get(section, 0)
447
+ daily_limit = ch_config.get("daily_limit", 10)
448
+ ready_queue_count = sum(1 for queued_article in self._queue
449
+ if queued_article.get("status") == "queued"
450
+ and queued_article.get("section") == section)
451
+ self._log_daily_budget(section, daily_limit, section_today, ready_queue_count, "generic")
452
+ decision = "SKIP - limit reached" if section_today >= daily_limit else "PUBLISH"
453
+ logger.info(f"Decision: {decision}")
454
+ logger.info("Before Daily Limit")
455
+ if section_today >= daily_limit:
456
+ logger.info(f"BloggerScheduler: daily limit {daily_limit} for section {section} reached, skipping article and scheduling next slot")
457
+ state["last_slot"] = next_slot_idx
458
+ self.db.save_schedule_state(state)
459
+ return
460
+ logger.info("After Daily Limit")
461
+
462
+ logger.info("Before Publish")
463
+ logger.info(f"BloggerScheduler: publishing article '{article.get('title', '')[:30]}' in slot {next_hour:02d}:{next_min:02d}")
464
+ logger.info(f"Section Before Publisher: section={section}")
465
+ logger.info(f"Article dict has labels: {article.get('labels', [])}")
466
+ logger.info(f"Article dict has hashtags: {article.get('hashtags', 'MISSING')}")
467
+ html = self.processor.make_article_html(article)
468
+ labels = list(self._get_section_labels(section))
469
+ logger.info(f"Labels Sent To Blogger: {labels}")
470
+ blogger_article = {
471
+ "title": article.get("title", "عنوان المقال"),
472
+ "content": html,
473
+ "labels": labels,
474
+ }
475
+ post_id = await self.publisher.publish_article(blogger_article, article.get("fingerprint"))
476
+ logger.info("After Publish")
477
+ if post_id:
478
+ self.db.update_article_status(article["fingerprint"], "published", {
479
+ "post_id": post_id,
480
+ "published_at": int(time.time()),
481
+ })
482
+ self.db.increment_daily_count(section)
483
+ article["status"] = "published"
484
+ logger.info(f"BloggerScheduler: published '{article.get('title', '')[:30]}' (post_id={post_id})")
485
+ logger.info("Before Queue Pop")
486
+ self._queue = [a for a in self._queue if a.get("fingerprint") != article["fingerprint"]]
487
+ logger.info("After Queue Pop: removed only after successful publish")
488
+
489
+ # Mark this slot as used only after the successful publish.
490
+ state["last_slot"] = next_slot_idx
491
+ self.db.save_schedule_state(state)
492
+ logger.info(f"BloggerScheduler: slot {next_slot_idx} used, next at slot {next_slot_idx + 1}")
493
+ else:
494
+ # Keep the article queued so the next cycle can retry it. Do not
495
+ # consume the generic slot or increment the daily counter.
496
+ self.db.update_article_status(article["fingerprint"], "queued", {
497
+ "last_publish_failed_at": int(time.time()),
498
+ })
499
+ article["status"] = "queued"
500
+ logger.warning(
501
+ f"BloggerScheduler: failed to publish '{article.get('title', '')[:30]}'; "
502
+ "article remains queued and the slot remains available"
503
+ )
504
+
505
+ async def _process_slots(self, now: datetime, today: str, current_total_min: int):
506
+ """P28 fixed-slot publishing for sections that declared explicit daily times.
507
+ Rules (per requirement):
508
+ - Each slot is fixed: candidate is prepared but only published at/after the
509
+ slot's time (+grace); earlier missed slots publish first (no burst).
510
+ - Candidate = newest queued article of the section (by Telegram message id).
511
+ - Candidate is locked to the slot on first pick; if it later turns out to be
512
+ a duplicate/invalid at fix time, the next newest candidate is tried.
513
+ - An article can never occupy two slots (fingerprint recorded per section).
514
+ - Slots with no remaining valid candidate stay empty permanently.
515
+ Returns (True, reason) when a slot was fixed this cycle, (False, reason) when
516
+ no slotted section had a publishable slot (caller falls through to the
517
+ generic queue), or (None, None) when there was nothing to do at all."""
518
+ state = self.db.get_slots_state()
519
+ if state.get("day") != today:
520
+ return (False, "new-day reset not yet applied")
521
+ state_sections = state.setdefault("sections", {})
522
+
523
+ channels = self.db.get_all_channels()
524
+ # Sections that declare fixed slots and have at least one enabled channel
525
+ slotted = {}
526
+ for section, slots in P28_SECTION_FIXED_SLOTS.items():
527
+ if not slots:
528
+ continue
529
+ has_channel = any(
530
+ c.get("section") == section and c.get("enabled", True) and c.get("channel_id")
531
+ for c in channels
532
+ )
533
+ if has_channel:
534
+ slotted[section] = slots
535
+ if not slotted:
536
+ return (False, "no slotted sections with active channels")
537
+
538
+ # Pick the earliest publishable slot across all slotted sections (missed
539
+ # slots first, then future slots in time order). Only ONE slot is fixed per
540
+ # cycle, exactly like the generic queue fixes one article per cycle.
541
+ best = None # (total_min, section, slot_key)
542
+ for section, slots in slotted.items():
543
+ for key in self._p28_remaining_slot_keys(state_sections, section, slots, current_total_min):
544
+ hh, mm = (int(p) for p in key.split(":"))
545
+ total = hh * 60 + mm
546
+ if best is None or total < best[0]:
547
+ best = (total, section, key)
548
+ if best is None:
549
+ logger.info("BloggerScheduler: no remaining publishable slot for slotted sections today")
550
+ return (False, "no remaining slots")
551
+ total, section, slot_key = best
552
+ # Publishing timing: a slot that has ALREADY PASSED (missed catch-up) may
553
+ # publish immediately once a valid candidate exists. A FUTURE slot waits
554
+ # for its exact fixed time (the candidate is prepared earlier but never
555
+ # published ahead of the slot). Grace is never used to publish early —
556
+ # it only softens the window for slots whose fixed time has passed.
557
+ # Lock the slot immediately (prevents two concurrent cycles fixing it twice)
558
+ sec_state = state_sections.setdefault(section, {"fixed": {}, "candidates": {}, "published": {}, "source_ids": {}})
559
+ sec_state.setdefault("fixed", {})
560
+ sec_state.setdefault("candidates", {})
561
+ sec_state.setdefault("published", {})
562
+ sec_state.setdefault("source_ids", {})
563
+
564
+ if current_total_min < total:
565
+ # Prepare-ahead rule: a future slot is prepared well before its fixed
566
+ # time — the newest queued article of the section is locked to the slot
567
+ # as its candidate now, stays a candidate (never published early), and
568
+ # is verified at publish time. If a newer job arrives before the slot,
569
+ # the candidate is refreshed to it.
570
+ if sec_state.get("candidates", {}).get(slot_key):
571
+ logger.info(f"BloggerScheduler: section '{section}' slot {slot_key} candidate already prepared, waiting for its time")
572
+ return (False, f"slot {slot_key} not yet due (candidate prepared)")
573
+ prepared = self._slot_candidates(section, sec_state)
574
+ if prepared:
575
+ sec_state["candidates"][slot_key] = prepared[0]
576
+ self.db.save_slots_state({"day": today, "sections": state_sections})
577
+ logger.info(f"BloggerScheduler: section '{section}' slot {slot_key} candidate {prepared[0][:16]} prepared in advance, will publish at its fixed time")
578
+ else:
579
+ logger.info(f"BloggerScheduler: section '{section}' slot {slot_key} not yet due, no queued article to prepare")
580
+ return (False, f"slot {slot_key} not yet due")
581
+
582
+ today_published = self._today_published_count()
583
+ # Any section channel works to read the daily limit (limit is per channel but
584
+ # sections share channels in our setup; take the first enabled one).
585
+ ch_config = next((c for c in channels if c.get("section") == section
586
+ and c.get("enabled", True) and c.get("channel_id")), {})
587
+ daily_limit = ch_config.get("daily_limit", 10)
588
+ section_today = today_published.get(section, 0)
589
+ ready_queue_count = sum(1 for queued_article in self._queue
590
+ if queued_article.get("status") == "queued"
591
+ and queued_article.get("section") == section)
592
+ self._log_daily_budget(section, daily_limit, section_today, ready_queue_count, f"fixed:{slot_key}")
593
+ if section_today >= daily_limit:
594
+ logger.info(f"BloggerScheduler: daily limit {daily_limit} for section '{section}' reached, slot {slot_key} skipped for today")
595
+ return (False, "daily limit reached")
596
+
597
+ # "_locked" means a slot is claimed this cycle but not yet fixed to a
598
+ # fingerprint; it is not counted as a used slot. Only real fingerprints
599
+ # (candidates/published) occupy a slot permanently.
600
+ # Choose/refresh the candidate: if one was prepared in advance for this
601
+ # slot, keep it (refresh only if a newer queued article arrived); otherwise
602
+ # pick the newest queued article of this section not already consumed by
603
+ # another slot today, not published before.
604
+ candidates = self._slot_candidates(section, sec_state)
605
+ pre_locked = sec_state.get("candidates", {}).get(slot_key)
606
+ # The prepared candidate was previously locked to this slot; keep it as
607
+ # the first choice at due time (unless it disappeared from the queue or
608
+ # a newer job arrived, in which case _slot_candidates already lists the
609
+ # newer one first and the lock simply moves to it below).
610
+ if pre_locked:
611
+ queued_fps = [a.get("fingerprint") for a in self._queue if a.get("status") == "queued"]
612
+ if pre_locked in queued_fps and pre_locked not in candidates:
613
+ candidates = [pre_locked] + candidates
614
+ # Missed-slot rule: if this slot's fixed time has already passed (missed
615
+ # catch-up), only candidates that were queued BEFORE the slot's fixed time
616
+ # may fill it. A job that arrived after the slot passed goes to the next
617
+ # future slot; a missed slot with no pre-existing candidate stays empty.
618
+ if candidates and current_total_min >= total:
619
+ allowed_before = total # queue time must precede the slot's time
620
+ candidates = [c for c in candidates
621
+ if self._slot_queue_time(c) < allowed_before]
622
+ fp = None
623
+ while candidates:
624
+ fp = candidates[0]
625
+ if self._p28_candidate_valid(fp, section, today, state_sections):
626
+ break
627
+ logger.info(f"BloggerScheduler: candidate {fp[:16]} invalid/duplicate for slot {slot_key}, dropping it")
628
+ candidates.pop(0)
629
+ if not fp:
630
+ # No valid candidate at all: the slot will never be fixed today. Mark
631
+ # it explicitly empty so it is never reconsidered in later cycles.
632
+ sec_state["fixed"][slot_key] = ""
633
+ self.db.save_slots_state({"day": today, "sections": state_sections})
634
+ logger.info(f"BloggerScheduler: no valid candidate for section '{section}' slot {slot_key} — slot stays empty permanently today")
635
+ return (False, "no valid candidate")
636
+
637
+ # Keep the candidate lock while rendering/publishing. The slot becomes
638
+ # permanently fixed only after a successful publish.
639
+ sec_state["candidates"][slot_key] = fp
640
+ self.db.save_slots_state({"day": today, "sections": state_sections})
641
+
642
+ article = next((a for a in self._queue if a.get("fingerprint") == fp), None)
643
+ if not article:
644
+ logger.warning(f"BloggerScheduler: slot {slot_key} candidate {fp[:16]} missing from memory queue, will retry next cycle")
645
+ return (False, "candidate not in memory queue")
646
+
647
+ # Resolve section/labels like the generic path does
648
+ if not article.get("section"):
649
+ article["section"] = ch_config.get("section", section)
650
+ article.setdefault("labels", list(self._get_section_labels(article.get("section", section))))
651
+ logger.info(f"P28 Slots: section='{section}' slot={slot_key} candidate={fp[:16]} title='{article.get('title', '')[:30]}'")
652
+
653
+ html = self.processor.make_article_html(article)
654
+ labels = list(self._get_section_labels(article.get("section", section)))
655
+ blogger_article = {"title": article.get("title", "عنوان المقال"), "content": html, "labels": labels}
656
+ post_id = await self.publisher.publish_article(blogger_article, fp)
657
+ if post_id:
658
+ self.db.update_article_status(fp, "published", {"post_id": post_id, "published_at": int(time.time())})
659
+ self.db.increment_daily_count(section)
660
+ sec_state["published"][slot_key] = fp
661
+ sec_state["fixed"][slot_key] = fp
662
+ self.db.save_slots_state({"day": today, "sections": state_sections})
663
+ self._queue = [a for a in self._queue if a.get("fingerprint") != fp]
664
+ logger.info(f"P28 Slots: section '{section}' slot {slot_key} published post_id={post_id}; removed from queue after success")
665
+ else:
666
+ self.db.update_article_status(fp, "queued", {"last_publish_failed_at": int(time.time())})
667
+ logger.warning(
668
+ f"P28 Slots: section '{section}' slot {slot_key} publish failed for {fp[:16]}; "
669
+ "candidate remains queued and slot remains retryable"
670
+ )
671
+ return (True, "published" if post_id else "failed")
672
+
673
+ def _slot_candidates(self, section: str, sec_state: Dict) -> List[str]:
674
+ """Newest queued articles of the section (by Telegram message id in the
675
+ source URL), excluding fingerprints already claimed by another slot today."""
676
+ claimed = set()
677
+ for keys in (sec_state.get("candidates", {}), sec_state.get("published", {}), sec_state.get("fixed", {})):
678
+ claimed.update(v for v in keys.values() if v)
679
+ queued = [a for a in self._queue
680
+ if a.get("status") == "queued" and a.get("section") == section
681
+ and a.get("fingerprint") not in claimed]
682
+ queued.sort(key=lambda a: self._slot_message_id(a), reverse=True)
683
+ return [a["fingerprint"] for a in queued]
684
+
685
+ def _slot_queue_time(self, fp: str) -> int:
686
+ """When the candidate arrived into the queue (enqueue time), used to
687
+ decide whether a MISSED slot may still catch up with it: a missed slot
688
+ only ever uses candidates that were already queued BEFORE the slot's
689
+ fixed time; a job that arrives after its slot has passed goes to the
690
+ nearest FUTURE unfixed slot and can never retro-fill an empty one."""
691
+ article = self.db.get_article(fp) or {}
692
+ return int(article.get("created_at") or 0)
693
+
694
+ @staticmethod
695
+ def _slot_message_id(article: Dict) -> int:
696
+ """Newest = latest Telegram message id from the source URL; falls back to
697
+ created_at so enqueue order still works when the URL has no message id."""
698
+ url = article.get("source_url", "") or ""
699
+ m = __import__("re").search(r"t\.me/c/[^/]+/(\d+)$", url)
700
+ if m:
701
+ return int(m.group(1))
702
+ return article.get("created_at", 0) or 0
703
+
704
+ def _p28_candidate_valid(self, fp: str, section: str, today: str, state_sections: Dict) -> bool:
705
+ """Gate at slot fix time: published-IDs dedup still holds, plus the P27
706
+ section-scoped hybrid dedup so the same news event cannot be republished
707
+ under a newer message id. Import is lazy to keep modules import-safe."""
708
+ if self.db.is_published(fp):
709
+ return False
710
+ try:
711
+ from bot_core import is_hybrid_news_duplicate
712
+ article = self.db.get_article(fp) or {}
713
+ text = article.get("source_text", "")
714
+ if text:
715
+ # Lazy import of the scope helper; any failure degrades to ingest-only dedup.
716
+ try:
717
+ from bot_core import section_scope_for_channel
718
+ cid = next((c.get("channel_id") for c in self.db.get_all_channels()
719
+ if c.get("section") == section and c.get("channel_id")), "")
720
+ scope_id = section_scope_for_channel(cid) if cid else ""
721
+ except Exception:
722
+ scope_id = ""
723
+ dup, why, best = is_hybrid_news_duplicate(text, scope_id=scope_id)
724
+ if dup:
725
+ try:
726
+ _recent = db.get_recent_fingerprints(scope_id=scope_id) if scope_id else []
727
+ except Exception:
728
+ _recent = []
729
+ logger.info(f"P28 Slots: candidate {fp[:16]} rejected by section-scoped dedup (recent={[r.get('fp','') for r in _recent][-6:]}, why={why}, best={best})")
730
+ return False
731
+ except Exception as e:
732
+ logger.warning(f"P28 Slots: hybrid dedup gate unavailable ({e}), using ingest dedup only")
733
+ return True
734
+
735
+ def _can_publish_now(self, ch_config: Dict, current_hour: int, today_published: Dict) -> bool:
736
+ if not ch_config.get("enabled", True):
737
+ logger.info(f"BloggerScheduler: channel disabled")
738
+ return False
739
+ start_hour = ch_config.get("start_hour", 9)
740
+ end_hour = ch_config.get("end_hour", 23)
741
+ if current_hour < start_hour or current_hour >= end_hour:
742
+ logger.info(f"BloggerScheduler: current hour {current_hour} outside window {start_hour}-{end_hour}")
743
+ return False
744
+ daily_limit = ch_config.get("daily_limit", 10)
745
+ section = ch_config.get("section", "")
746
+ section_count = today_published.get(section, 0)
747
+ if section_count >= daily_limit:
748
+ logger.info(f"BloggerScheduler: daily limit {daily_limit} reached for section {section}")
749
+ return False
750
+ return True
751
+
752
+ def _today_published_count(self) -> Dict:
753
+ """Return successful Blogger publishes for the current local calendar day.
754
+
755
+ The article records are authoritative because they carry the successful
756
+ publish timestamp. The legacy stats.daily counter remains for UI/history,
757
+ but it is not used for admission decisions, avoiding stale or duplicated
758
+ counter values after retries or restarts.
759
+ """
760
+ now = datetime.now()
761
+ today = now.date()
762
+ period_label = today.strftime("%Y-%m-%d")
763
+ counts: Dict[str, int] = {}
764
+ get_all_articles = getattr(self.db, "get_all_articles", None)
765
+ if callable(get_all_articles):
766
+ for article in get_all_articles():
767
+ if article.get("status") != "published":
768
+ continue
769
+ published_at = int(article.get("published_at") or 0)
770
+ if not published_at:
771
+ continue
772
+ if REAL_DATETIME.fromtimestamp(published_at).date() != today:
773
+ continue
774
+ section = article.get("section", "") or "general"
775
+ counts[section] = counts.get(section, 0) + 1
776
+ logger.info(
777
+ "BloggerScheduler: daily budget count method=published_articles "
778
+ f"period=local_calendar_day:{period_label} counts={counts}"
779
+ )
780
+ return counts
781
+
782
+ # Compatibility fallback for test doubles/older adapters without the
783
+ # article-list API. Production BloggerDatabase has get_all_articles().
784
+ stats = self.db.get_stats()
785
+ daily = stats.get("daily", {})
786
+ counts = dict(daily.get(period_label, {}))
787
+ logger.info(
788
+ "BloggerScheduler: daily budget count method=legacy_stats_daily "
789
+ f"period=local_calendar_day:{period_label} counts={counts}"
790
+ )
791
+ return counts
792
+
793
+ def _log_daily_budget(self, section: str, daily_limit: int, section_today: int,
794
+ ready_queue_count: int, context: str) -> None:
795
+ remaining = max(0, int(daily_limit) - int(section_today))
796
+ logger.info(
797
+ "BloggerScheduler: daily budget "
798
+ f"context={context} section={section!r} "
799
+ "period=local_calendar_day "
800
+ f"counted={section_today} limit={daily_limit} remaining={remaining} "
801
+ f"ready_queue={ready_queue_count}"
802
+ )
803
+
804
+ def _get_section_labels(self, section_name: str) -> list:
805
+ sections = self.db.get_all_sections()
806
+ for sdata in sections.values():
807
+ if sdata.get("name") == section_name:
808
+ labels = sdata.get("labels", [])
809
+ if labels:
810
+ return list(labels)
811
+ return [section_name]
812
+ if section_name and section_name != "general":
813
+ return [section_name]
814
+ return []
815
+
816
+ def add_to_queue(self, article: Dict):
817
+ article["status"] = "queued"
818
+ self._queue.append(article)
819
+ self.db.save_article(article["fingerprint"], article)
820
+ logger.info(f"BloggerScheduler: manually queued article '{article.get('title', '')[:30]}'")