diff --git a/ARCHITECTURE_V29.md b/ARCHITECTURE_V29.md new file mode 100644 index 0000000000000000000000000000000000000000..f5839380e9a1e1854aa8b741f96a3e39af7a3491 --- /dev/null +++ b/ARCHITECTURE_V29.md @@ -0,0 +1,29 @@ +# P29 Refactor Architecture + +## هدف +إعادة الهيكلة تدريجيًا بدون كسر السلوك الحالي، مع إبقاء وحدات `modules/` متاحة أثناء الترحيل. + +## الطبقات +- `core/`: بنية تحتية مستقرة: jobs, health, secrets, plugins, events, supervisor, repair, storage. +- `adapters/`: محولات للخدمات الخارجية مثل Telegram/Gemini/Groq/Blogger. +- `modules/`: التنفيذ الحالي؛ يتم ترحيل وظيفة بعد أخرى إلى الخدمات الجديدة. +- `tests/`: اختبارات التوافق والانحدار. + +## قواعد مهمة +1. لا تعديل مباشر على الإنتاج بواسطة AI. +2. AI يقترح Patch -> Sandbox -> compile/tests/security -> backup -> apply -> monitor -> rollback. +3. الأسرار لا تدخل logs ولا source code. +4. كل job قابل للاستعادة بعد restart. +5. كل provider قابل للفشل دون إسقاط التطبيق كله. +6. إضافة secret/provider/plugin جديد تتم بالـ registry/metadata وليس بتعديل الـ core. + +## خارطة الترحيل +1. JobStore + Health + Supervisor. +2. SecretManager + ProviderRouter. +3. نقل Blogger scheduler إلى jobs. +4. نقل database JSON إلى SQLite عبر adapter ثم إيقاف JSON بعد فترة تحقق. +5. تقسيم `bot_core.py` إلى handlers/services. +6. تفعيل Auto-Repair بعد اكتمال الاختبارات. + +## التوافق +النسخة الحالية لا تحذف `bot_core.py` ولا وحدات Blogger؛ هذا مقصود لتقليل خطر الانقطاع أثناء الترحيل. diff --git a/CONTENT_PIPELINE_V29.md b/CONTENT_PIPELINE_V29.md new file mode 100644 index 0000000000000000000000000000000000000000..ca64da92a7475aba817fcbbb3527c2208858d238 --- /dev/null +++ b/CONTENT_PIPELINE_V29.md @@ -0,0 +1,21 @@ +# P29 Global Content Pipeline + +كل الأقسام (Blogger / News / Sports / مستقبلًا) تستخدم نفس البوابة قبل أي AI/API: + +1. Empty check +2. Global + channel blocked-word check +3. Duplicate check +4. Normalize + fingerprint +5. AI processing (single package request where applicable) +6. Post-AI blocked-word + duplicate check +7. Queue / publish + +المحتوى المرفوض في المرحلتين الأولى أو الثانية لا يستهلك أي طلب AI. + +## Single AI Request + +قسم Blogger يستخدم `SYSTEM_ARTICLE_PACKAGE` لطلب حزمة واحدة تشمل العنوان، النص، الملخص، SEO، الكلمات، الهاشتاكات، الملاحظات، الاستخراج وALT بدل عدة طلبات مستقلة. + +## Extensibility + +`core/content_pipeline.py` مستقل عن Blogger، لذلك أي Plugin جديد يستطيع استخدام `ContentGate` بدون نسخ منطق الحظر/التكرار. diff --git a/P29_MIGRATION_PLAN.md b/P29_MIGRATION_PLAN.md new file mode 100644 index 0000000000000000000000000000000000000000..9b775c6d0fca3fe37a9347e5cb491a1eace05b84 --- /dev/null +++ b/P29_MIGRATION_PLAN.md @@ -0,0 +1,29 @@ +# P29 Migration Plan + +## What was changed now +- Added `core/` foundation: durable jobs, health registry, supervisor, dynamic secrets, plugin registry, event bus, provider failover, repair validation. +- Added `v29_app.py` as a composition root. +- Added foundation tests under `tests/v29/`. +- Fixed the confirmed scheduler reference bug (`db` -> `self.db`). +- Changed Blogger DB read failure from silent `{}` fallback to an explicit error so corruption cannot masquerade as an empty database. + +## What is intentionally NOT changed yet +The existing Telegram/Blogger runtime remains in place. This is deliberate: a big-bang rewrite would create a larger outage risk. + +## Next migration slices +1. Wrap existing AI manager/Gemini clients with `ProviderRouter`. +2. Move scheduler queue persistence to `JobStore` and add claim/lease/idempotency. +3. Put Blogger and Telegram operations behind adapters. +4. Migrate JSON state to SQLite through a compatibility repository. +5. Split `bot_core.py` by responsibility while preserving public functions. +6. Add crash/restart integration tests. +7. Enable AI auto-repair in proposal-only mode. +8. Enable automatic patch application only after sandbox + tests + rollback checks are green. + +## Safety rule +No AI-generated patch is allowed to modify production directly. Production changes must have a backup, a validation result, and a rollback path. + +## Phase 15 completed +- RuntimeIntegration is now the shared orchestration path for new section traffic. +- News/Sports/Blogger receive the same section control contract while legacy callbacks remain intact. +- AI provider adapters, per-key rate limiting, bounded retry/backoff, persistent queue migration, publisher idempotency, health hooks, metrics and audit are wired together. diff --git a/P29_STAGE3_CHANGELOG.md b/P29_STAGE3_CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..ecdd66c8598fb2a758d4c7035b119b200ad6ca06 --- /dev/null +++ b/P29_STAGE3_CHANGELOG.md @@ -0,0 +1,20 @@ +# P29 Stage 3 — Content Gate + AI Batch Processing + +## Added +- Global `ContentGate` shared by all future sections. +- Blocked-word check before fingerprint/AI/API work. +- Global + per-channel blocked-word compatibility with existing database/UI names. +- Duplicate gate before AI. +- SHA-256 normalized fingerprints for new pipeline records. +- Post-AI blocked-word and duplicate gate. +- Single AI article-package request for Blogger instead of separate rewrite/extract/summary/metadata/keyword/hashtag/alt calls. + +## Compatibility +- Existing blocked-word database methods are reused; no existing secret names changed. +- Existing Blogger pending queue and legacy processor remain available. +- New pipeline is additive and can be adopted by News/Sports/future plugins. + +## Safety +- A blocked or duplicate article is discarded before any AI session is acquired. +- AI output is checked again before entering the processed state. +- The gate is fail-open only for legacy DB read exceptions to avoid taking down ingestion; the item remains available for later processing. diff --git a/PHASE_10_REPAIR_POLICY_CONTROL.md b/PHASE_10_REPAIR_POLICY_CONTROL.md new file mode 100644 index 0000000000000000000000000000000000000000..4e025210789a188c841d790066018547d04d06f3 --- /dev/null +++ b/PHASE_10_REPAIR_POLICY_CONTROL.md @@ -0,0 +1,19 @@ +# Phase 10 — Auto-Repair Policy + Control Bot + +Adds a conservative policy gate between sandbox-tested patches and production. + +Rules: +- secrets/credentials/tokens/keys/sessions/data/.git are blocked. +- code changes are medium risk by default and require admin approval. +- changes outside allowed roots are high risk and require admin approval. +- per-incident attempt cap and cooldown prevent repair loops. +- optional health check triggers rollback after application. + +Control-bot buttons are additive and callback-style: +- repair status +- pending repairs +- approve repair +- rollback last repair +- disable/enable auto-repair + +Existing button callbacks are not renamed or removed by this phase. The host bot should attach these buttons to its existing menu/router using the same callback mechanism already used by the project. diff --git a/PHASE_11_CONTROL_INTEGRATION.md b/PHASE_11_CONTROL_INTEGRATION.md new file mode 100644 index 0000000000000000000000000000000000000000..67e188b300bcadbab38455b7fcf9d5a1ed420cc0 --- /dev/null +++ b/PHASE_11_CONTROL_INTEGRATION.md @@ -0,0 +1,17 @@ +# Phase 11 — Control Bot Integration + Common Content Pipeline + +Adds an additive callback router and RepairControl façade for the existing control bot. + +New callbacks: +- `repair:status` +- `repair:pending` +- `repair:approve` +- `repair:rollback` +- `repair:disable` +- `repair:enable` + +The router does not replace or rename existing callbacks. + +Also adds `ContentPipeline`, a common service façade intended for Blogger, News, Sports and future sections. It applies the existing gate before queueing and sends accepted articles to the common AI Gateway. + +The actual Telegram framework handler should bind these callback strings to the project's existing button/menu code during final integration; this phase keeps framework-specific code isolated. diff --git a/PHASE_12_PLUGIN_ADAPTERS.md b/PHASE_12_PLUGIN_ADAPTERS.md new file mode 100644 index 0000000000000000000000000000000000000000..5af19582c2fc49517449b35e8d5b1d8bf130dcbf --- /dev/null +++ b/PHASE_12_PLUGIN_ADAPTERS.md @@ -0,0 +1,29 @@ +# Phase 12 — Plugin Adapters & Future Sections + +Implemented a section adapter contract and registry for Blogger, News, Sports and future sections. + +## Important compatibility rule +Legacy secret names are unchanged. Blogger continues to use: +- BLOGGER_BLOG_ID +- BLOGGER_CLIENT_ID +- BLOGGER_CLIENT_SECRET +- BLOGGER_REFRESH_TOKEN + +No secret is renamed or copied to a new required name. + +## New section flow +A new section registers a `SectionSpec`/adapter. It inherits the shared: +- blocked-word gate +- duplicate gate +- persistent queue +- AI Gateway/key rotation +- idempotent publisher +- health/supervisor layer + +The core pipeline does not need to be rewritten for each new section. + +External packages can register under the `p29.plugins` entry-point group. + +## Test note +All phase tests that do not require the optional Telegram/Pyrogram runtime passed: **30 passed**. +The full integration suite cannot be collected in this build environment because `pyrogram` is not installed; this is an environment dependency, not a code-test failure. diff --git a/PHASE_13_NEWS_SPORTS_SEPARATION.md b/PHASE_13_NEWS_SPORTS_SEPARATION.md new file mode 100644 index 0000000000000000000000000000000000000000..dd9e144103491ac417502b35751e503fffeb0c25 --- /dev/null +++ b/PHASE_13_NEWS_SPORTS_SEPARATION.md @@ -0,0 +1,23 @@ +# Phase 13 — Separate News and Sports + +News and Sports are now first-class independent sections. + +Each section has: +- its own key and namespace +- its own settings/state +- its own callbacks +- its own enable/disable status +- its own sources/blocked words/duplicate policy/AI settings/queue/repair controls + +They share infrastructure: +- ContentPipeline +- AI Gateway/provider rotation +- persistent Queue/Recovery +- idempotent publishing +- Health/Supervisor +- Auto-Repair policy and Sandbox + +Control buttons are generated with the same set for both sections, but callback namespaces are isolated: +`news:*` vs `sports:*`. + +No old secret names are changed. diff --git a/PHASE_14_INTEGRATED_HARDENING.md b/PHASE_14_INTEGRATED_HARDENING.md new file mode 100644 index 0000000000000000000000000000000000000000..1bafdac653c0679d9cdbd31469b7e3c2c51c1863 --- /dev/null +++ b/PHASE_14_INTEGRATED_HARDENING.md @@ -0,0 +1,15 @@ +# Phase 14 — Integrated Hardening Batch + +This batch adds multiple production foundations together: +- dynamic secret discovery while preserving legacy secret names +- key health/cooldown tracking +- log redaction +- zero-AI preflight for blocked words +- persistent content fingerprint deduplication +- provider token-bucket rate limiting +- audit log and metrics +- plugin manifests/registry +- common ContentGate for future sections + +Important: dynamic secret discovery is additive. Existing environment-variable names are not renamed or removed. +The gate is designed to run before any AI call, so blocked/duplicate content can be discarded without consuming AI quota. diff --git a/PHASE_15_RUNTIME_INTEGRATION.md b/PHASE_15_RUNTIME_INTEGRATION.md new file mode 100644 index 0000000000000000000000000000000000000000..d9b39736edfad91f597d6f12d98ae2955b512d29 --- /dev/null +++ b/PHASE_15_RUNTIME_INTEGRATION.md @@ -0,0 +1,39 @@ +# Phase 15 — Runtime Integration + +## Runtime order + +`article -> blocked words -> duplicate/fingerprint -> deterministic cleanup -> durable queue -> AI Gateway -> validation -> Publisher -> Idempotency -> Health` + +The gate runs before queue/AI/API use. Blocked or duplicate content is rejected without AI calls. + +## Integrated components + +- `core/runtime/integration.py`: phase-15 composition/orchestration root. +- News, Sports and Blogger use the same runtime contract with isolated section state. +- Persistent P29 job table (`p29_jobs`) with schema metadata and migration from the two older `jobs` schemas. +- AI Provider Pool rotates `GEMINI_KEY_N`, `GROQ_KEY_N`, `OPENROUTER_KEY_N` without renaming legacy secrets. +- Per-key token-bucket rate limits, cooldown and bounded retry/backoff. +- HTTP adapters for Gemini, Groq and OpenRouter. +- Post-AI validation reuses the same blocked-word and duplicate protection. +- Publisher remains idempotent through the durable publish ledger. +- Health monitoring is registered per section/provider. +- Auto-repair can be triggered by unhealthy services through the existing guarded sandbox/rollback policy; sensitive changes still require admin approval. +- Audit and metrics are exposed through the runtime control snapshot. +- Control Bot adds additive `news:*`, `sports:*`, and `blogger:*` callbacks while legacy callbacks remain unchanged. +- Plugin discovery remains the extension point for future sections. + +## Compatibility + +Existing secret names are unchanged. Existing legacy Blogger modules and callbacks remain available. The phase-15 job store uses a namespaced table so incompatible historical `jobs` schemas do not break startup; queued legacy rows are copied forward when their schema is recognized. + +## Verification + +Phase-15 tests cover: +- blocked content before queue/AI +- persistent duplicate rejection +- one structured AI package request +- provider/key failover +- idempotent publish +- stale-worker recovery +- legacy job schema migration +- section isolation/control parity diff --git a/PHASE_16_PRODUCTION_RELIABILITY.md b/PHASE_16_PRODUCTION_RELIABILITY.md new file mode 100644 index 0000000000000000000000000000000000000000..ea64d332dc093377cf7c6927c6a8fb7c28198eeb --- /dev/null +++ b/PHASE_16_PRODUCTION_RELIABILITY.md @@ -0,0 +1,19 @@ +# PHASE 16 — Production Reliability & Control Plane + +Phase 16 hardens the Phase-15 runtime for restarts and long-running operation without renaming legacy secrets or removing legacy callbacks. + +## Changes +- Durable per-section runtime/control state in `p29_runtime_state` with additive schema versioning. +- Section settings survive process restart: enabled state, blocked words, duplicate protection, AI, Auto-Repair and source allowlist. +- Source allowlist is enforced before Queue/AI; empty source is rejected when an allowlist is configured. +- Duplicate protection toggle is now honored by the runtime gate. +- Worker lease heartbeat prevents long AI/publish jobs from being reclaimed while still running. +- Completion is worker-aware to reduce stale-worker races. +- Auto-Repair respects each section's `auto_repair_enabled` flag. +- Runtime state changes invalidate cached section gates/pipelines. +- Existing legacy secrets and callback namespaces remain unchanged. + +## Verification +- `compileall` is required. +- Phase-15 and Phase-16 runtime tests cover persistence, source gating, duplicate toggle, worker heartbeat and section repair policy. +- Telegram-dependent legacy tests are reported separately when `pyrogram` is unavailable. diff --git a/PHASE_17_CHANGELOG.md b/PHASE_17_CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..b61617773d19c1652d681ec39b13ac23ee1c85a8 --- /dev/null +++ b/PHASE_17_CHANGELOG.md @@ -0,0 +1,30 @@ +# P29 Phase 17 Changelog + +## Runtime / Reliability +- Added `attempt_started_at` to `publish_ledger` with additive migration. +- Added stale publish lease recovery before each publish. +- Preserved the same `(target, article_id)` idempotency key across recovery. +- Added queue job listing and dead-letter requeue primitives. +- Added safe operational queue snapshots without payload exposure. +- Persisted global Auto-Repair enable/disable state. + +## Control Bot +Existing section callbacks remain available. New additive callbacks: +- `{section}:metrics` +- `{section}:health` +- `{section}:dead` + +These are generated for News, Sports and Blogger using the same section-control contract. + +## Security +- Dead-letter requeue requires admin approval at the runtime API. +- Operational queue views omit article payloads. +- Audit logging continues through the existing redaction layer. +- Secret names remain unchanged. + +## Verification +- `python3 -m compileall -q .` — PASS +- Phase 16 + Phase 17 + runtime/core compatibility tests — PASS +- Legacy non-Telegram test subset — PASS +- Full pytest collection remains blocked by missing `pyrogram` in the execution environment; affected tests are Telegram/Blogger UI-dependent. +- `python3 v29_app.py` — PASS; discovered `blogger, news, sports`. diff --git a/PHASE_18_LEGACY_RUNTIME_CUTOVER.md b/PHASE_18_LEGACY_RUNTIME_CUTOVER.md new file mode 100644 index 0000000000000000000000000000000000000000..38db42d39a8501cddaae6a2fc57a8397ee2451d9 --- /dev/null +++ b/PHASE_18_LEGACY_RUNTIME_CUTOVER.md @@ -0,0 +1,23 @@ +# PHASE 18 — Full Legacy Runtime Migration & Production Cutover + +Phase 18 turns the previously parallel legacy/new architecture into a controlled compatibility cutover. + +## Runtime path + +Telegram/legacy source -> legacy compatibility bridge -> RuntimeIntegration -> ContentGate -> persistent queue -> AI Gateway -> validation -> IdempotentPublisher -> legacy external target -> Health/Audit/Metrics. + +## Compatibility + +- Existing `BloggerPublisher`, `ArticleProcessor`, scheduler and UI APIs remain available. +- Legacy `enqueue_raw_post()` now routes automatic Blogger ingestion into the durable P29 runtime when a runtime is supplied by `BloggerPublisher`. +- Legacy direct/manual processing remains available for callers that construct `ArticleProcessor` without a runtime. +- Existing secret names are untouched. +- Existing callback modules remain untouched. + +## Cutover safety + +The bridge never bypasses the ContentGate. A rejected/duplicate item is stopped before the durable queue and therefore before AI/API consumption. Publisher idempotency remains owned by the core ledger. + +## Recovery + +The runtime worker uses the Phase 17 job lease/heartbeat/recovery path. The external Blogger client remains the legacy-compatible publishing adapter, so remote publishing semantics are not duplicated. diff --git a/PHASE_19_CHANGELOG.md b/PHASE_19_CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..e59a5a7d929cd4780eb3db01c0cbd15f2aef0f83 --- /dev/null +++ b/PHASE_19_CHANGELOG.md @@ -0,0 +1,9 @@ +# Phase 19 Changelog + +- Added `core/control/plane.py` operational alert/control layer. +- Extended `core/infra/metrics.py` with thread-safe latency aggregates and timers. +- Extended `core/infra/audit.py` with safe recent-event retrieval. +- Integrated control-plane data into `RuntimeIntegration.control_snapshot()`. +- Added runtime operational snapshot, recent audit access and alert acknowledgement APIs. +- Added global control callback façade without renaming old callbacks. +- Added regression tests for alerts, metrics compatibility and admin-gated control access. diff --git a/PHASE_19_PRODUCTION_CONTROL_OBSERVABILITY.md b/PHASE_19_PRODUCTION_CONTROL_OBSERVABILITY.md new file mode 100644 index 0000000000000000000000000000000000000000..781a702d64be38043b4e6928c6213f53a76b1226 --- /dev/null +++ b/PHASE_19_PRODUCTION_CONTROL_OBSERVABILITY.md @@ -0,0 +1,18 @@ +# P29 — PHASE 19: Production Control Plane & Observability + +## Integrated +- Unified operational snapshot for News, Sports and Blogger. +- Active alerts for unhealthy services, queue backlog and dead-letter jobs. +- Detailed latency metrics while preserving the legacy flat `metrics_snapshot()` API. +- Safe recent Audit Log viewer with existing redaction. +- Additive global control callbacks: `control:overview`, `control:alerts`, `control:providers`, `control:audit`. +- Existing section callbacks and legacy callback names remain unchanged. +- Runtime control snapshot now includes queue, alerts and detailed metrics. +- Admin gating is required for Audit Log access through the global control surface. +- No legacy secret names were renamed or removed. + +## Verification +- Python compile: PASS. +- Phase/core regression suite: 32 passed. +- App smoke start: PASS; discovered `blogger`, `news`, `sports`. +- Telegram-dependent tests remain environment-blocked because `pyrogram` is not installed. diff --git a/PHASE_20_CHANGELOG.md b/PHASE_20_CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..d1cb227788a56347a8136cb79572e8375f0cbdaf --- /dev/null +++ b/PHASE_20_CHANGELOG.md @@ -0,0 +1,15 @@ +# P29 Phase 20 Changelog — Performance, Concurrency & Chaos + +- Added canonical bounded concurrent worker pool over the persistent queue. +- Added compatibility facade so legacy `core.jobs.store.JobStore` callers use the canonical storage implementation without changing old call signatures. +- Added deterministic load harness and chaos scenario matrix. +- Added runtime helpers `build_concurrent_workers()` and `load_snapshot()`. +- Added tests for duplicate enqueue, concurrent claims, lease recovery, 40-job load, and chaos coverage. +- Existing secret names/callbacks/public runtime compatibility preserved. + +## Verification +- `python -m compileall -q .`: PASS +- Phase 20 + regression/core suite selected for non-Telegram paths: **61 passed** +- App smoke: PASS; `blogger, news, sports` discovered. +- Load test: 200 jobs / 8 workers: **200 processed, 0 queued, 200 done, 0 dead**, ~175.35 jobs/s in the local test environment. +- Full pytest collection is blocked by missing `pyrogram` in this environment; Telegram-dependent imports fail at collection. This is an environment dependency, not a compile/core test failure. diff --git a/PHASE_20_PERFORMANCE_CHAOS.md b/PHASE_20_PERFORMANCE_CHAOS.md new file mode 100644 index 0000000000000000000000000000000000000000..ede76da3d899a9953126401ce03fe6d4f9912088 --- /dev/null +++ b/PHASE_20_PERFORMANCE_CHAOS.md @@ -0,0 +1,16 @@ +# P29 — PHASE 20: Performance, Concurrency & Chaos Engineering + +## Integrated +- Added bounded `ConcurrentWorkers` using the existing persistent JobStore and lease/heartbeat logic. +- Added deterministic in-process `LoadHarness` for repeatable load and chaos scenarios without external services. +- Duplicate enqueue remains idempotent under repeated concurrent-style submission. +- SQLite queue claim remains the single atomic source of truth; concurrent workers cannot double-claim a queued job. +- Existing lease recovery is exercised as a worker-crash/restart simulation. +- Added performance result reporting: processed, elapsed time, throughput, queue/done/dead counts. +- Added a chaos matrix covering duplicate enqueue, concurrent claim, worker crash, lease expiry, provider 429/5xx, timeout, publish crash and restart recovery. +- No legacy secret names, callbacks, section configuration names, or public runtime APIs were removed. + +## Verification +- `compileall`: required before packaging. +- Core/regression suite plus Phase 20 concurrency/load tests required before delivery. +- Telegram-dependent tests remain environment-dependent when `pyrogram` is unavailable. diff --git a/PHASE_21_SECURITY_HARDENING.md b/PHASE_21_SECURITY_HARDENING.md new file mode 100644 index 0000000000000000000000000000000000000000..e6ede602cf832d43bd3fe1bb1c7541cdf89ec859 --- /dev/null +++ b/PHASE_21_SECURITY_HARDENING.md @@ -0,0 +1,8 @@ +# PHASE 21 — Security, Secrets & Production Hardening + +- Added runtime secret-value redaction and security findings. +- Added RBAC for control-plane sensitive operations. +- Added encrypted SecretManager master-key rotation without changing existing secret names. +- Existing SecretRegistry discovery and legacy environment names remain untouched. +- Sensitive repair/rollback/rotation actions can be restricted to admin. +- Added security regression tests. diff --git a/PHASE_22_23_CHANGELOG.md b/PHASE_22_23_CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..2649a86e4f03c1a75dcc80a1795cafe8c2cc3068 --- /dev/null +++ b/PHASE_22_23_CHANGELOG.md @@ -0,0 +1,8 @@ +# P29 Phase 22+23 Changelog + +- Production readiness gate. +- SQLite integrity checks. +- Atomic, verifiable backup/restore foundation. +- Release manifest and reproducible file hashes. +- Disaster-recovery regression coverage. +- Final-release candidate metadata. diff --git a/PHASE_22_23_PRODUCTION_READINESS_RELEASE.md b/PHASE_22_23_PRODUCTION_READINESS_RELEASE.md new file mode 100644 index 0000000000000000000000000000000000000000..ec0eb18cfffe68d497a3db48c03a7164ffa4ecc3 --- /dev/null +++ b/PHASE_22_23_PRODUCTION_READINESS_RELEASE.md @@ -0,0 +1,17 @@ +# PHASE 22+23 — Production Readiness, Disaster Recovery & Final Release + +## Integrated +- Added deterministic production readiness gate with Python/database/queue/health/security checks. +- Added atomic SQLite backup manager using SQLite online backup API, SHA-256 verification and backup discovery. +- Added corrupt-database detection and recovery-readiness checks without mutating runtime state. +- Added reproducible release manifest with SHA-256 file inventory while excluding runtime state, backups and bytecode. +- Added regression tests for backup verification, corruption detection, readiness and release manifest safety. +- Kept all legacy secret names, callbacks and public runtime APIs additive. + +## Combined acceleration +This release intentionally combines the planned Phase 22 disaster-recovery/readiness work with the planned Phase 23 final-release/go-live gate so the project reaches a single auditable release candidate faster. + +## Verification +- compileall required before packaging. +- Phase 22/23 and regression suite required before delivery. +- Telegram-dependent tests remain environment-dependent when `pyrogram` is unavailable. diff --git a/PHASE_24_FINAL_GO_LIVE.md b/PHASE_24_FINAL_GO_LIVE.md new file mode 100644 index 0000000000000000000000000000000000000000..0cea4c439526ba34e1ec74f89deafd249f8baebd --- /dev/null +++ b/PHASE_24_FINAL_GO_LIVE.md @@ -0,0 +1,22 @@ +# PHASE 24 — Final Go-Live / End-to-End Production Gate + +Final hardening and release gate for P29. + +## Integrated +- Final Go-Live readiness gate. +- Dry-run end-to-end verification for News, Sports and Blogger. +- Atomic publish-lease claim to eliminate the final concurrent idempotency race. +- CLI readiness and go-live checks. +- Telegram dependency/credential checks are optional and explicitly gated by `--require-telegram`. +- Legacy Telegram callbacks and runtime bridge remain unchanged. +- Release manifest advanced to phase 24. + +## Verification +- `python -m compileall -q .`: PASS +- Phase 24 + release/security/performance/cutover/runtime regression suite: 22/22 PASS +- `python v29_app.py --go-live`: PASS in dry-run mode +- `python v29_app.py --manifest`: PASS +- Full pytest collection: blocked by missing `pyrogram` in the execution environment; 3 integration modules cannot be collected. + +## Production note +A live Telegram publish cannot be truthfully marked successful without the deployment's real Telegram credentials and network access. The final gate therefore distinguishes deterministic offline readiness from live external-service verification. diff --git a/PHASE_4_AI_PROVIDER_POOL.md b/PHASE_4_AI_PROVIDER_POOL.md new file mode 100644 index 0000000000000000000000000000000000000000..95e761eb4a8a42a391ae862455b30ad8e26cbec3 --- /dev/null +++ b/PHASE_4_AI_PROVIDER_POOL.md @@ -0,0 +1,25 @@ +# P29 Phase 4 — AI Provider Pool + +This phase adds a provider/key scheduler without renaming legacy secrets. + +## Supported legacy names + +- `GEMINI_KEY_1 ... GEMINI_KEY_N` +- `GROQ_KEY_1 ... GROQ_KEY_N` +- `OPENROUTER_KEY_1 ... OPENROUTER_KEY_N` + +Any numbered key already present is discovered automatically. + +## Selection policy + +1. Ignore empty/unavailable keys. +2. Prefer the least-used key. +3. Break ties with least-recently-used. +4. Put failed/rate-limited keys into cooldown. +5. A future provider adapter can call `report_success()` / `report_failure()`. + +## Important + +This phase deliberately does not hard-wire provider HTTP SDKs into the pool. The existing provider clients remain responsible for making requests. The pool only decides which credential should be used, so migration is low-risk. + +The next integration step is to route every real AI request through this pool and add persistent usage/quota state. diff --git a/PHASE_5_AI_GATEWAY.md b/PHASE_5_AI_GATEWAY.md new file mode 100644 index 0000000000000000000000000000000000000000..e03dad23e70f4173a4f49426bac6e5aa36b2b1dd --- /dev/null +++ b/PHASE_5_AI_GATEWAY.md @@ -0,0 +1,20 @@ +# P29 Phase 5 — AI Gateway + +All future AI calls should go through `core.ai.AIGateway`. + +## What it adds + +- Uses the existing Provider Pool. +- Preserves legacy secret names. +- Automatic key/provider failover. +- Rate-limit cooldown. +- Token usage accounting when provider responses expose usage. +- One structured `article_package()` request for title/body/summary/keywords/hashtags/SEO/category/slug. + +## Migration rule + +Do not rewrite the existing provider clients in one risky step. Register their HTTP/API functions as adapters, then migrate call sites one service at a time. This keeps the legacy bot operational during the transition. + +## Token-minimization rule + +Before invoking this gateway, the global content gate must reject blocked or duplicate articles. The gateway should only receive accepted content. diff --git a/PHASE_6_PERSISTENT_JOB_QUEUE.md b/PHASE_6_PERSISTENT_JOB_QUEUE.md new file mode 100644 index 0000000000000000000000000000000000000000..458c3280e43a2ffc09f434f8c0babca142a90a4d --- /dev/null +++ b/PHASE_6_PERSISTENT_JOB_QUEUE.md @@ -0,0 +1,13 @@ +# Phase 6 — Persistent Job Queue & Crash Recovery + +Adds a SQLite/WAL job store with: +- durable queued jobs +- atomic-ish claim under SQLite locking +- worker lease timestamps +- recovery of jobs whose worker crashed +- retry with max attempts +- dead-letter (`dead`) state +- idempotent enqueue by job id + +This is a migration layer. Existing scheduler code is not deleted or replaced in this phase. +The next migration step is to route actual article processing/publishing through this store and make publish idempotency explicit. diff --git a/PHASE_7_PUBLISH_IDEMPOTENCY.md b/PHASE_7_PUBLISH_IDEMPOTENCY.md new file mode 100644 index 0000000000000000000000000000000000000000..f43edce4ec500fc05f1165e5fafcb37dde7ac4fa --- /dev/null +++ b/PHASE_7_PUBLISH_IDEMPOTENCY.md @@ -0,0 +1,15 @@ +# Phase 7 — Publish Idempotency + +Adds a durable publish ledger on the same SQLite/WAL store. + +## Safety +- One logical key per `(target, article_id)`. +- A completed publish is never sent again. +- A second worker seeing `publishing` will not issue another remote request. +- Failed attempts remain retryable. +- Remote IDs are retained when the adapter returns one. + +## Migration +Existing Blogger/News/Sports adapters should be wrapped with `IdempotentPublisher` one target at a time. No legacy secret names are changed. + +Important: a provider that supports an idempotency key should receive the generated key. For providers without native idempotency, the ledger still prevents duplicates within this application, while reconciliation by remote ID/search should be added before retrying ambiguous network failures. diff --git a/PHASE_8_HEALTH_SUPERVISOR.md b/PHASE_8_HEALTH_SUPERVISOR.md new file mode 100644 index 0000000000000000000000000000000000000000..b090adfb071bf2d084c3f234100865bd976db5bb --- /dev/null +++ b/PHASE_8_HEALTH_SUPERVISOR.md @@ -0,0 +1,11 @@ +# Phase 8 — Health Monitor + Supervisor + +Adds: +- service health checks +- consecutive failure tracking +- health snapshots +- supervised restart with exponential backoff +- restart caps and disable-on-persistent-failure + +This is intentionally a migration layer. Existing services are not forcibly wrapped yet. +The next phase can connect Telegram scheduler, workers, provider clients and publishers one by one. diff --git a/PHASE_9_AI_AUTO_REPAIR.md b/PHASE_9_AI_AUTO_REPAIR.md new file mode 100644 index 0000000000000000000000000000000000000000..9d7684765e709af201516665ab8bb17928f97f53 --- /dev/null +++ b/PHASE_9_AI_AUTO_REPAIR.md @@ -0,0 +1,22 @@ +# Phase 9 — AI Auto-Repair: Sandbox + Tests + Rollback + +AI never writes directly to production. + +Flow: +1. Error is classified outside the repair engine. +2. AI proposes a unified diff patch. +3. PatchSandbox rejects protected paths and traversal. +4. Patch is applied to an isolated copy. +5. Python compile + selected tests run in sandbox. +6. Only a passing patch may be applied. +7. Original files are backed up before apply. +8. Health monitoring can trigger rollback if the repaired service becomes unhealthy. + +Protected by default: +- secrets / credentials / tokens / keys +- `.env` +- runtime `data/` +- sessions +- `.git` + +This is deliberately conservative. Provider-specific AI proposal logic is not hard-wired here; it should use the existing AI Gateway and only return a patch. diff --git a/PRODUCTION_READINESS_REPORT.json b/PRODUCTION_READINESS_REPORT.json new file mode 100644 index 0000000000000000000000000000000000000000..49a054e4dc77688463c4cc6aa8f450f135f72e3d --- /dev/null +++ b/PRODUCTION_READINESS_REPORT.json @@ -0,0 +1,45 @@ +{ + "ready": true, + "generated_at": 1787486536.9508731, + "findings": [], + "checks": { + "python_version": "3.13.5", + "database_integrity": "ok", + "queue": { + "queued": 0, + "running": 0, + "done": 0, + "dead": 1 + }, + "health": { + "section:blogger": { + "name": "section:blogger", + "status": "unknown", + "consecutive_failures": 0, + "last_error": "", + "last_ok": 0.0, + "last_check": 0.0, + "metadata": {} + }, + "section:news": { + "name": "section:news", + "status": "unknown", + "consecutive_failures": 0, + "last_error": "", + "last_ok": 0.0, + "last_check": 0.0, + "metadata": {} + }, + "section:sports": { + "name": "section:sports", + "status": "unknown", + "consecutive_failures": 0, + "last_error": "", + "last_ok": 0.0, + "last_check": 0.0, + "metadata": {} + } + }, + "security_findings": [] + } +} \ No newline at end of file diff --git a/README_P29.md b/README_P29.md new file mode 100644 index 0000000000000000000000000000000000000000..6ccc84f32e48f0aa35e7e2cba7a9772d4f2d1dec --- /dev/null +++ b/README_P29.md @@ -0,0 +1,23 @@ +# P29 Foundation + +This package is a safe, incremental refactor of the P28 automatic publishing bot. + +### Start foundation check +`python v29_app.py` + +### Generate a Fernet master key +`python scripts_generate_secret_key.py` + +Set it as `P29_SECRET_MASTER_KEY` before using `core.secrets.SecretManager`. + +### Run new foundation tests +`pytest -q tests/v29` + +The legacy runtime is intentionally retained during migration so the refactor can be introduced service-by-service instead of risking a big-bang failure. + +## Phase 17 — Operational Resilience +- Durable publish leases with stale-operation recovery. +- Dead-letter queue inspection/requeue with admin approval. +- Persistent global Auto-Repair control state. +- Section health/metrics/dead-letter control callbacks added additively. +- No legacy secret names or callback namespaces were renamed. diff --git a/RELEASE_MANIFEST.json b/RELEASE_MANIFEST.json new file mode 100644 index 0000000000000000000000000000000000000000..533c30d7f0622677c819abf8a594829b5534af99 --- /dev/null +++ b/RELEASE_MANIFEST.json @@ -0,0 +1,849 @@ +{ + "files": [ + { + "path": "ARCHITECTURE_V29.md", + "sha256": "44fed5976a284ab0ff1ec43f98b8fbe61208598a83e6c2c2f00ccf3e07eaa199", + "size": 1673 + }, + { + "path": "CONTENT_PIPELINE_V29.md", + "sha256": "3354885a927709249c91918d99653742c31883ec915a37a75b4e5d8d9ff92969", + "size": 978 + }, + { + "path": "P29_MIGRATION_PLAN.md", + "sha256": "60503554d687ab320016f41f20ff9899e1d424463e8399e4e90f73f6faaf77d3", + "size": 1762 + }, + { + "path": "P29_STAGE3_CHANGELOG.md", + "sha256": "60e0e50d018dcd61e2494f6181f4c62b9a7f6b868b57580a4d528ff348b21e32", + "size": 1064 + }, + { + "path": "PHASE_10_REPAIR_POLICY_CONTROL.md", + "sha256": "eaa54d073268c6e93ab541f5b22fedeb75fc518373377f9478b2c2ed2d45d75b", + "size": 827 + }, + { + "path": "PHASE_11_CONTROL_INTEGRATION.md", + "sha256": "1cbc300cddd3d2df6f443ae81e511b5c9ab5d4092c7508ad2f6f4eb6a8cd96d4", + "size": 747 + }, + { + "path": "PHASE_12_PLUGIN_ADAPTERS.md", + "sha256": "3b211c8de9c85f627cbd3236a76e473f4686e2fae04fcc493b8420423fd609c1", + "size": 1038 + }, + { + "path": "PHASE_13_NEWS_SPORTS_SEPARATION.md", + "sha256": "13fbe7d8629a93a284da7a53611d1d64cf22b37938f514539dfb39f82bdbd3ae", + "size": 652 + }, + { + "path": "PHASE_14_INTEGRATED_HARDENING.md", + "sha256": "056a3d602b6d82420f7951794bfccba15d8bad2ee48480728a6a88aaafdefc80", + "size": 664 + }, + { + "path": "PHASE_15_RUNTIME_INTEGRATION.md", + "sha256": "c431d5471cfc6fca7e66049538478d60db7590fa73ef352a61713c9f38026206", + "size": 2028 + }, + { + "path": "PHASE_16_PRODUCTION_RELIABILITY.md", + "sha256": "95c050c6ca42186840e7748af9cbb25998ebd752da4244d8d8eae62b557f1875", + "size": 1239 + }, + { + "path": "PHASE_17_CHANGELOG.md", + "sha256": "63eefc10d46f1a5f95b290e7e69bb1809519a66a8a9c0fdaf2bfa5a99aeb3452", + "size": 1283 + }, + { + "path": "PHASE_18_LEGACY_RUNTIME_CUTOVER.md", + "sha256": "6d247c663f37c95368accf8a3b8dc5ce33d8a3490e764e1821ccab26834fb9b6", + "size": 1299 + }, + { + "path": "PHASE_19_CHANGELOG.md", + "sha256": "35701b51ecf10e705e4add6d31b34f4beca024fc61208d38693b693feb6ffed4", + "size": 568 + }, + { + "path": "PHASE_19_PRODUCTION_CONTROL_OBSERVABILITY.md", + "sha256": "84acc97e4ef360e7b893583b5fba0636ec40292494813a09ea55bc1c29e99e62", + "size": 990 + }, + { + "path": "PHASE_20_CHANGELOG.md", + "sha256": "671868193836b952c90bb3cf3f4ec90cb9e4a443d33ac9f903bda4fac5a1999a", + "size": 1121 + }, + { + "path": "PHASE_20_PERFORMANCE_CHAOS.md", + "sha256": "3e57069ca12864660e9f8505366d3bf28cc19bc285ca468e3c1530aaf4a9cb16", + "size": 1170 + }, + { + "path": "PHASE_21_SECURITY_HARDENING.md", + "sha256": "15f1760219dcd158e470ffc1b400e6b6880fd470bd4db4b3c3cfcfe0898e1af1", + "size": 455 + }, + { + "path": "PHASE_22_23_CHANGELOG.md", + "sha256": "48569be0981a5e1109838ebe0a27316fd8be9f3873bab04bb3327db633375b3d", + "size": 259 + }, + { + "path": "PHASE_22_23_PRODUCTION_READINESS_RELEASE.md", + "sha256": "5d87894cd88963c3c82ae0bc93d06151df8901f940ef63c7cfab8f5966ec117f", + "size": 1146 + }, + { + "path": "PHASE_24_FINAL_GO_LIVE.md", + "sha256": "8508b06c4c5f37d4f89ddc4f3baf44dde7eb3f5f8e644fdd67f7b1531fc99958", + "size": 1162 + }, + { + "path": "PHASE_4_AI_PROVIDER_POOL.md", + "sha256": "47cef98b91f1cfabade1d8a62044e1725d3da659ed511876ad47611d0423f767", + "size": 919 + }, + { + "path": "PHASE_5_AI_GATEWAY.md", + "sha256": "535dedbe44474726a58e1015127ff5a095cfaa3dc8f5f0ca5cbd112b81662107", + "size": 816 + }, + { + "path": "PHASE_6_PERSISTENT_JOB_QUEUE.md", + "sha256": "1cc6e8a5055c6e92ffedcbde61ada738aaacae325eb75f1ea62442eeff261303", + "size": 526 + }, + { + "path": "PHASE_7_PUBLISH_IDEMPOTENCY.md", + "sha256": "060d50a0189b3a6fea011d02ccf10b13b1c62925345873527e734d116b1e941f", + "size": 814 + }, + { + "path": "PHASE_8_HEALTH_SUPERVISOR.md", + "sha256": "f2eb3b743d198c4c2d02a6a51c4b6a5358af5651ce5ff44c963fcf8bb1233632", + "size": 408 + }, + { + "path": "PHASE_9_AI_AUTO_REPAIR.md", + "sha256": "8c052f61e0910f2c718f0a436e309ec6f0937a607c6ea1bd51e1cc8cd7a1f21d", + "size": 779 + }, + { + "path": "PRODUCTION_READINESS_REPORT.json", + "sha256": "eb88b88e9f73be63332fa6aca04e4cae006b6ca8a40af18f14c0522c6ca55469", + "size": 999 + }, + { + "path": "README_P29.md", + "sha256": "187453f0cd77847b515452c4e790a28cee138bab770389e58b6ecc092997fe4e", + "size": 845 + }, + { + "path": "RELEASE_MANIFEST.json", + "sha256": "6e8ddb3ccd4e94801791cbbf3ff412d3e6b939bbc3f327bd132f1765965eadf6", + "size": 26874 + }, + { + "path": "SECRET_COMPATIBILITY.md", + "sha256": "29f31311f7be8e98a39478c1bf0533c04288f56dedbd6fca2229a4718f89fc39", + "size": 917 + }, + { + "path": "adapters/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + { + "path": "bot_core.py", + "sha256": "8766333fa0a7a4e31ad835f3ff45bfa082a6f6d8554404e829d86ec71ec10c90", + "size": 379351 + }, + { + "path": "config.py", + "sha256": "0bd6fb5324b37d35d259d49cb2048bfd390742393c86ff388c28b13e928e48fd", + "size": 1085 + }, + { + "path": "core/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + { + "path": "core/ai/__init__.py", + "sha256": "1367728ac663ccdc3f9029fa71543a55ac9dd42bbefb8418c90a9f494188dffb", + "size": 82 + }, + { + "path": "core/ai/gateway.py", + "sha256": "96866dc9d91be17b146bd36a388fce673a27aaf263087d5ebcacab062576d04e", + "size": 4185 + }, + { + "path": "core/ai/http_adapters.py", + "sha256": "9baf3a4f69d7d501e16022f39d1c0392f07264c98f506d777d4a236925909391", + "size": 4513 + }, + { + "path": "core/app.py", + "sha256": "81ed0107330edf1541f196896e02e306126fc6a2e4e54d3a6637e8066ed7ed1a", + "size": 2563 + }, + { + "path": "core/config/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + { + "path": "core/config/settings.py", + "sha256": "eb1ede72b85405fcf80a40a300a20327e25fe592b306f487daff70a357086bfc", + "size": 779 + }, + { + "path": "core/content/__init__.py", + "sha256": "05a48970e396aacbd1c2559912e013f55274f56af2de8f1835228244e1928019", + "size": 139 + }, + { + "path": "core/content/dedup.py", + "sha256": "131e15642e06b33a5c03ebc4ff7c9c02d2966744c6f8b326a0bbc60c4eef5c45", + "size": 1176 + }, + { + "path": "core/content/orchestrator.py", + "sha256": "775a95fa9bfe7c8bbc34492859fe73b693e27fac5fc7c5fcf7d8ba68902b1777", + "size": 794 + }, + { + "path": "core/content/preflight.py", + "sha256": "bf591b475b8a006f24ef86b076a2c9383e815809d6a32f14cd6ac90a98086aac", + "size": 1219 + }, + { + "path": "core/content_pipeline.py", + "sha256": "a91974dcf6630d5415c8aaf1bd4be0535c20b360b99985f6a5347951a64a537a", + "size": 5881 + }, + { + "path": "core/control/__init__.py", + "sha256": "76c67ce186facda0e92cae72064f5f9597f479ecdd920e72b36e73d10a201907", + "size": 58 + }, + { + "path": "core/control/plane.py", + "sha256": "cefdd64451225e22770f9fb9416f1bd8d6d6e34ec650b6b85dec4a76f80e01df", + "size": 2707 + }, + { + "path": "core/control/repair_buttons.py", + "sha256": "4a87ec8f5e74959dd9022cc7d9dc7e7dbc4cc1ac6fc90ac5526152b0d450f8e2", + "size": 893 + }, + { + "path": "core/control/repair_control.py", + "sha256": "a91f8a00ad7c5bab5fe2fae00ad02fbbf3a9a5affc8bb95aa5bec208108a964d", + "size": 2303 + }, + { + "path": "core/control/router.py", + "sha256": "ab18bec51946ab6e94997347adcf85fdf43dd36bd2c30f9ed2ebf292da516bea", + "size": 768 + }, + { + "path": "core/control/section_control.py", + "sha256": "8fa76d61b9b36c8057125ed0836c1466371924156c0b0199c761b2dfe99e7014", + "size": 3677 + }, + { + "path": "core/events/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + { + "path": "core/events/bus.py", + "sha256": "56500b5221e248ad5d141f8cb20da17931df10f1f0e30f4eb5279eae008d281a", + "size": 326 + }, + { + "path": "core/health/__init__.py", + "sha256": "9b7fa3e154467918688494c5ba8f5fda47deef951a8fabc5556dcf49d43d02ac", + "size": 92 + }, + { + "path": "core/health/monitor.py", + "sha256": "82c7da1b434917e3c2b1aa40c50cfdc72dfbb899e5e189c49a1dee1129959aa0", + "size": 2258 + }, + { + "path": "core/health/registry.py", + "sha256": "087e32751fbc1dae1d61b97ffe965af435881e1d93dd998278f4fc120df084ea", + "size": 521 + }, + { + "path": "core/infra/audit.py", + "sha256": "b0df99430efbcbf07b215792136a0dc868e6829f834bfdae4b20967be00e1ea9", + "size": 819 + }, + { + "path": "core/infra/load.py", + "sha256": "968612284646ad5c130b804fdbbd6dfd59c675337cef7c76cc9366e3bdd169ce", + "size": 1563 + }, + { + "path": "core/infra/metrics.py", + "sha256": "642409bcae716d37f8b42b49e0705c439b9eb0dab638575814ab3d91d5172f13", + "size": 1041 + }, + { + "path": "core/infra/rate_limiter.py", + "sha256": "46c51ef8977570a08888c3686a0bed3a3b4c7377b41e78439bdb70386c388eec", + "size": 1079 + }, + { + "path": "core/jobs/__init__.py", + "sha256": "f5e17a175507583fde44aa8a4650f40df34ec5bd0ce7891f0a905829959a2c63", + "size": 52 + }, + { + "path": "core/jobs/concurrency.py", + "sha256": "5ab342a30750a0bfbe7aea65db562adba1f1e27ce8f4a954132b56532fef6bcb", + "size": 2060 + }, + { + "path": "core/jobs/queue.py", + "sha256": "75f1dff67ae30095af00a530b164811ff199e1e021e14624b51921d231a5e064", + "size": 590 + }, + { + "path": "core/jobs/store.py", + "sha256": "8d1a9393e2041892d007a82b3697a14d4a15a99639c806ad70d6ad24bec80daf", + "size": 1837 + }, + { + "path": "core/jobs/worker.py", + "sha256": "f8f6098bc1f8734a0bb3b2babb351b27e60f9fbdbd434e0bb5b338984a9dfd5b", + "size": 1713 + }, + { + "path": "core/pipeline/__init__.py", + "sha256": "a596c64d3dacbecb19b23abb61d6afd9feaa4252440822fc758c1801dff26f9e", + "size": 62 + }, + { + "path": "core/pipeline/adapter.py", + "sha256": "9c77de1b826b52fdce1e803db3ab49eaf839c4dcd2dc84cc88e43d51445a12a4", + "size": 1181 + }, + { + "path": "core/pipeline/content_pipeline.py", + "sha256": "896308ec8822bcc68006c56fced0d97cb6990e478bc738b322f5bf677fbd1062", + "size": 1359 + }, + { + "path": "core/plugins/__init__.py", + "sha256": "58e78856a6f30ec3253c707cae06a19e4b72f4b98dd1ad09467a7a93f6f26859", + "size": 224 + }, + { + "path": "core/plugins/builtin.py", + "sha256": "65e74b9135eace9f454d80586c5da325856ec9cd5bb7d832a9e11d69f8858a62", + "size": 543 + }, + { + "path": "core/plugins/contracts.py", + "sha256": "c666d845435950404d7d11dde2a3869cd06599bf00d334ad98372ce0eee39b6f", + "size": 659 + }, + { + "path": "core/plugins/manager.py", + "sha256": "1026577ffd512570024dc1e57478dda10ecf23ef7b3ba5498b4ef3a70b2ebd68", + "size": 505 + }, + { + "path": "core/plugins/manifest.py", + "sha256": "a2386943f2b46a435e60846b015649d994b22e8856dd20f066d4a601aea11ac5", + "size": 555 + }, + { + "path": "core/plugins/registry.py", + "sha256": "49f6de7c1c874304de76079b795991662761a256222d0b78916115d8d4c59f29", + "size": 893 + }, + { + "path": "core/providers/__init__.py", + "sha256": "e3542ea700e9c94c8c4a55b32e7aba4e039c75321a99b0430451eed0ef506385", + "size": 85 + }, + { + "path": "core/providers/pool.py", + "sha256": "baeb75794d436006c2dd1e11e34edd41ebcc820d3cf0967d001ad43e3bb34d91", + "size": 4891 + }, + { + "path": "core/providers/router.py", + "sha256": "8aa3cea570762612182fb7bdb66bd45c87402792a016b5a4cb7d545cda9d6756", + "size": 594 + }, + { + "path": "core/publishing/__init__.py", + "sha256": "49358478cbf68d430548938969cf4ce24183f842cc9ecea3ee004acba4b5f613", + "size": 60 + }, + { + "path": "core/publishing/ledger.py", + "sha256": "07565d42aa8938c41b18f7a13d4737ee29db090c23a020b378d5a0e1e17e73db", + "size": 6019 + }, + { + "path": "core/publishing/publisher.py", + "sha256": "8a8071979ab63b789cf8060d7140c16c9c38f34e4b7fc8c5d275dba27a29c965", + "size": 1741 + }, + { + "path": "core/release/__init__.py", + "sha256": "0f67c910abb7b7bec6ddf3d9c82116e4a86d45146c4768352808a8fd8cfbe2e9", + "size": 289 + }, + { + "path": "core/release/backup.py", + "sha256": "2fe14f325fac5487c65bfe25ad4823c6cc04687f90118e02213fbb356b391c37", + "size": 5737 + }, + { + "path": "core/release/go_live.py", + "sha256": "f2971108f26de0cd3f5f01df13c2838303230198801d64139199ca7011ddeb7b", + "size": 2214 + }, + { + "path": "core/release/readiness.py", + "sha256": "60709e484b79dc103a34f0247baf8afbefb22d1cd2336b90044816d0e3b22d9a", + "size": 3336 + }, + { + "path": "core/release/release.py", + "sha256": "b241d6975f2288a04d58858797bddabceb7da8cec82f8c9a7823cb1933a5aee9", + "size": 1045 + }, + { + "path": "core/repair/__init__.py", + "sha256": "ed7aed61d211cb63222e37bc90b8b193701eb064d58e1cb0dc08ade19b2425ef", + "size": 171 + }, + { + "path": "core/repair/engine.py", + "sha256": "9193c0375ed3f1e8e9b738db5924ae4ac4b8f2abb2a7ef4ce963d45458dbe186", + "size": 2462 + }, + { + "path": "core/repair/guarded.py", + "sha256": "31a06a67ad2da071c4c0f6ef75ac1d5f9a52edcf1131d95f412b3c0bd06d7c50", + "size": 1062 + }, + { + "path": "core/repair/policy.py", + "sha256": "d0cf78c1007b1a17222ba9021d1b796fc6bf476e544cc29b0cf78187c7107324", + "size": 2177 + }, + { + "path": "core/repair/sandbox.py", + "sha256": "ad55e35d74410533d1d2efbdebd9ecdaae849021ef5616af61bbcd0512be2282", + "size": 3294 + }, + { + "path": "core/runtime/__init__.py", + "sha256": "7f8f83aed7f61adbca76ec6e4d8884fa26bdb75c625652adb3e1a37c01835c31", + "size": 110 + }, + { + "path": "core/runtime/integration.py", + "sha256": "889c4f6b70d27d71ecaf734845e5f5387567850032e981c6c3c83b8b9924136e", + "size": 24254 + }, + { + "path": "core/runtime/legacy_bridge.py", + "sha256": "06e4a1e02a1e8003f760269f2744142fca6b86dd3b67ad5f4babcac537cc4d49", + "size": 1816 + }, + { + "path": "core/runtime/state_store.py", + "sha256": "9a3c2513e8049eb9390d2affd8593ae299abac6806193fd49b201305af694288", + "size": 2073 + }, + { + "path": "core/secrets/__init__.py", + "sha256": "55104b27336502968523805d754d4917c641b953aef2c926cde08e3aa94219b5", + "size": 183 + }, + { + "path": "core/secrets/compat.py", + "sha256": "669ed3b056876df3c5cd04f59103479958760190441ec07e686881c6b3a578ce", + "size": 1867 + }, + { + "path": "core/secrets/manager.py", + "sha256": "7ba68d240360c21d527c0700a9a59be7f6235540beaf7e8d1a90f11d2e27f510", + "size": 2896 + }, + { + "path": "core/sections/__init__.py", + "sha256": "a0b32e81a8cce33514177c49454132de829e9aef4d0a00ce99d8a9d1f0f07383", + "size": 264 + }, + { + "path": "core/sections/base.py", + "sha256": "1948bdd932a5b3cc62e0b8b25ece5e83ba078c568fe3d509364af83abfe285a1", + "size": 1762 + }, + { + "path": "core/sections/controls.py", + "sha256": "d70f7cd513e3fc180d089cc28ba6ef1e4e52267eec2a7eab68f85ebc383d12c1", + "size": 1427 + }, + { + "path": "core/sections/registry.py", + "sha256": "b48247ba36bcad32a96dcaa67397f71cf359325e9bc8c03782aa5662d795ede3", + "size": 1055 + }, + { + "path": "core/security/__init__.py", + "sha256": "27f5a8f46b417077357d3462d428dfa9d5bba85b714417dd4fa2ce3271e4194d", + "size": 301 + }, + { + "path": "core/security/access.py", + "sha256": "a796822274a76c104cdd0b12cc12fbd3a2821dedbeb58d13201f95588028fb51", + "size": 1445 + }, + { + "path": "core/security/hardening.py", + "sha256": "5da19900182af6fa6551c9cea8ad28dee822ce6d0d2a934961af5d6b47f687ed", + "size": 2213 + }, + { + "path": "core/security/redaction.py", + "sha256": "8036ba78b55fb7c71f30f85572e9a91fbcdb363a3fc5a04e801048ce57a217a3", + "size": 632 + }, + { + "path": "core/security/secret_registry.py", + "sha256": "6b82f41d851c75088b82ed776b2b537bc275a6e38402b78689938ee30ee27a18", + "size": 1594 + }, + { + "path": "core/storage/__init__.py", + "sha256": "31b608a029062f5a8667d64c82cfdb98528c2c14f33bc22a999a601a88aab899", + "size": 53 + }, + { + "path": "core/storage/job_store.py", + "sha256": "f6c6861da781150ba0421a59d6706c9736fcc0f328b4c1bcc20b6b28f0cc045f", + "size": 9139 + }, + { + "path": "core/storage/sqlite.py", + "sha256": "a099034a9b09183898479e759d863c437270eb3b7bea425bd53d9ebd1ed47ca9", + "size": 1087 + }, + { + "path": "core/supervisor/__init__.py", + "sha256": "ea70f60799e2adbffc41667442476fd17254f54d03bc5bd528ad808f3db45d98", + "size": 97 + }, + { + "path": "core/supervisor/service.py", + "sha256": "ef0eb2d3515a6f7a906f057ab8e5941f88f8b16e20ef9a7dee3b8b2adc11bc3a", + "size": 813 + }, + { + "path": "core/supervisor/supervisor.py", + "sha256": "b85581df41a312ae5302b0b3c2c96133a338f73d6d736b5aed250e1bfcff053c", + "size": 1775 + }, + { + "path": "daily_limit_audit.md", + "sha256": "750fa93935f47613bae322478faf6b712289f59b517384621c5463ef459d3e63", + "size": 3521 + }, + { + "path": "database.py", + "sha256": "5c06db36d3d608aefcc842e8a54676301d6ed3dcd5cce30e5a39a2d870952718", + "size": 94777 + }, + { + "path": "modules/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + { + "path": "modules/blogger/__init__.py", + "sha256": "e68be9c5cf36d18f4e9bfb05a9b20e2632a84555ac07e3945c5ea0ba273f6599", + "size": 408 + }, + { + "path": "modules/blogger/ai_manager.py", + "sha256": "334bb356f6c132db9d747652aa7022f855db003602e062c0996bf87ececfc99b", + "size": 35876 + }, + { + "path": "modules/blogger/blogger_client.py", + "sha256": "446732b7f113b866676d4a5e8f27d6b2e212adaaae17c9538290fdb25abcf0ae", + "size": 8066 + }, + { + "path": "modules/blogger/config.py", + "sha256": "ba895d67313799b53941a89340aec5aa20252162adb83c6b19b4f47cbe676ca0", + "size": 2310 + }, + { + "path": "modules/blogger/database.py", + "sha256": "355e1a92ba6a0f3ad65a1787f8c6668c01fb6745ffbee2355a1352f062f2c061", + "size": 14160 + }, + { + "path": "modules/blogger/gemini.py", + "sha256": "3e452bc364cbe9c799205a206e338b307b94f37f02b1981f0de2bcd0722cf8a7", + "size": 22471 + }, + { + "path": "modules/blogger/processor.py", + "sha256": "91ae6f6b59567d6142b3e60a5bc4e469c05ff1744565d265d4e92c76e8a74238", + "size": 45388 + }, + { + "path": "modules/blogger/prompts.py", + "sha256": "b4fd34780569f4dfa30e1d4c2d7a3df18a85d8d57908ca2f6e029e827246082f", + "size": 16518 + }, + { + "path": "modules/blogger/publisher.py", + "sha256": "cb06660bec141be9c0f5e7b80727350fd2de8a4645d44a8b5d9921b95bbf7fd7", + "size": 4938 + }, + { + "path": "modules/blogger/scheduler.py", + "sha256": "917db50001327ab9b5fc5244388c035e605cd2c8c09cf64fb4006195826c0347", + "size": 47984 + }, + { + "path": "modules/blogger/ui.py", + "sha256": "a2b3935a77544ed832a318bb6c3173c1b5d30d75f20bcfde76041d7f4ad697de", + "size": 95908 + }, + { + "path": "modules/logging_security.py", + "sha256": "972e444e75cf0ff735ca3744827a4ff6da970d7e8e84dde9c21e87c2abb3e422", + "size": 2980 + }, + { + "path": "modules/publish_target.py", + "sha256": "5efeaac8be400e8d20a1917551456d1778c7d674d487a75c2ae69a2a1a2fd435", + "size": 1115 + }, + { + "path": "p27_design_notes.md", + "sha256": "f59fa7eab2b07e4d158219f480136874bbc44305724394fcef7de8ba7e0fac6b", + "size": 19214 + }, + { + "path": "p28_design_notes.md", + "sha256": "a4f85afbb912c8a7eb8ca8cee6188e8073bd9a8330229ea373fd9a7084c6926e", + "size": 24318 + }, + { + "path": "p28_progress.md", + "sha256": "b04e58f284055c3bff81409d52aa560314867f026fdaa187174b16309a54bf70", + "size": 21321 + }, + { + "path": "p29_state.md", + "sha256": "037d0adba87d7ce0e1b3ccfbe01a35921d2ce79c0fed8a4254159b5066c112d5", + "size": 2065 + }, + { + "path": "requirements-v29.txt", + "sha256": "288bea19dea9f505702648cb4c6edf9947da5be88fd3a6f71b08eef587baf8e4", + "size": 50 + }, + { + "path": "requirements_audit.md", + "sha256": "797077908c16604f47edbe13a6f357fe6186308dca0a59e9541dbbbe8df6ebba", + "size": 4518 + }, + { + "path": "scripts_generate_secret_key.py", + "sha256": "46fc561d82104b33d6760a4554961d71b338f56932f6d55816d2463ba192cc57", + "size": 183 + }, + { + "path": "tests/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + { + "path": "tests/integration/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + { + "path": "tests/integration/test_channel_bot_verification.py", + "sha256": "07b3db4704dcc69643460c16fb618f49d0d00f9c33a226e2029f14ac1d3cd1ed", + "size": 36176 + }, + { + "path": "tests/integration/test_full_pipeline.py", + "sha256": "7993e679c65c372355fdb1665835919117bc0f1e5d512a39b57e6842b76baa0a", + "size": 63671 + }, + { + "path": "tests/test_ai_gateway.py", + "sha256": "f736ca9d0795bcde12118fa74c0ea00cb41c6e27bb9146ca12cdfb578664fbf8", + "size": 1209 + }, + { + "path": "tests/test_auto_repair.py", + "sha256": "49e8f05c584ec67ff3fb5bf2e0c90cab1d548bd7d3e28d8496c46fb1c6f85e7b", + "size": 1177 + }, + { + "path": "tests/test_control_integration.py", + "sha256": "7364274672d917f340bf6bc9a7b5ee12c15cf36350df888c550936d8e8248972", + "size": 725 + }, + { + "path": "tests/test_health_supervisor.py", + "sha256": "e766dd687e46ca28a7eb2811654752b165fe76006571e668803270cfece98a02", + "size": 1054 + }, + { + "path": "tests/test_job_store.py", + "sha256": "2880f17f04ca954d2c7a37641ce512bcca59c855f38291f9e2894f49d71c2e2d", + "size": 715 + }, + { + "path": "tests/test_phase14.py", + "sha256": "466ffd7759b53b421dd73acb305d46d49425d49cc11f9717f941bb280a308046", + "size": 876 + }, + { + "path": "tests/test_plugins_pipeline.py", + "sha256": "db03691da1e7b2c53f72c74245522f2505cc76c7c12349652d3ed8aa60bd7a16", + "size": 1001 + }, + { + "path": "tests/test_preview_cleanliness.py", + "sha256": "a43dc9472200a0f84f3bb2a6445be52690cd964227f228494671fdce682aa3dd", + "size": 2924 + }, + { + "path": "tests/test_provider_pool.py", + "sha256": "7f97f0b66300d0b047e7038655bec34fd00b7ecebecd6b78614afc46b3cf2bbf", + "size": 1131 + }, + { + "path": "tests/test_publish_idempotency.py", + "sha256": "4ff0ba960898b4abc9ea2de057b7e9c610c1a21ce1b2c8dddd4d3874aebba302", + "size": 1252 + }, + { + "path": "tests/test_repair_policy.py", + "sha256": "1384453e8948071101621b17826d57ec7fb65434dd7c8ab72fe6939a3c46cbe7", + "size": 671 + }, + { + "path": "tests/test_sections_news_sports.py", + "sha256": "aa46b1899a350e8038a3f4a2fc617f1cfdb470bb77a4a9fa0a570fab86b21369", + "size": 1046 + }, + { + "path": "tests/test_system_ui_move.py", + "sha256": "1df969deff6db2e7ccebaf5aa35a1cea6596e5fee2a9766cad5b37c2024c4adc", + "size": 3337 + }, + { + "path": "tests/v29/conftest.py", + "sha256": "993590cfa2be57cab132617bff46c8300d3ce78496651da91dedf0be04011a86", + "size": 97 + }, + { + "path": "tests/v29/test_article_package.py", + "sha256": "26a838911c25be7f9462ac2cd597599487ac35eda3bebf87d1b1fb6df33366f3", + "size": 597 + }, + { + "path": "tests/v29/test_content_gate.py", + "sha256": "87e27f7370bb92ec45491b2e56a9e8bac88d9d2292f7f22f6c89411eef9926c5", + "size": 1865 + }, + { + "path": "tests/v29/test_core_foundation.py", + "sha256": "9a90303524e9040babe32493cd6860811dac31f7220a826b20bc8fd7bd1b0278", + "size": 1122 + }, + { + "path": "tests/v29/test_phase16_reliability.py", + "sha256": "1156af92ccd907a6e836b8801cb630e55fcd6f8ffd83e59171812fc156bb8a92", + "size": 2578 + }, + { + "path": "tests/v29/test_phase17_operational_resilience.py", + "sha256": "4a8849f7489a9157438f6823604c58a12427ad3a71f09f546a5c11e89009c172", + "size": 4275 + }, + { + "path": "tests/v29/test_phase18_cutover.py", + "sha256": "a3bd167a14d20294255edb7e206e1e4282e3ae19fe31ed7309b74dabf093acfd", + "size": 1523 + }, + { + "path": "tests/v29/test_phase19_control_plane.py", + "sha256": "b63414e50a47656a00ac6b059dc9030ff5dc5027e8b304d28fcf6376e3769667", + "size": 1564 + }, + { + "path": "tests/v29/test_phase20_performance_chaos.py", + "sha256": "6ca87f7bcc4687ff70931ce0acd3eb834096980b3e09603d916a50f5e0614b8e", + "size": 1636 + }, + { + "path": "tests/v29/test_phase21_security.py", + "sha256": "794d8473c979269a39b9ab05423f7bc5a26edd2051a0bdbb20a210a1046a2961", + "size": 1399 + }, + { + "path": "tests/v29/test_phase22_23_release.py", + "sha256": "ebfb91e853df724e7b2423895ceddf4245ae3cb6bbd21865f14dd0ab56926a74", + "size": 1668 + }, + { + "path": "tests/v29/test_phase24_final.py", + "sha256": "9c2a15145f90afeefe308d14022e7e327ba0d1abb58404514d7f9b0c04079769", + "size": 2409 + }, + { + "path": "tests/v29/test_runtime_integration.py", + "sha256": "b38f297cdcbe6c1d506c96881143e51d2cc284c324f46ea97664030d2c5187f6", + "size": 4341 + }, + { + "path": "tests/v29/test_secret_compatibility.py", + "sha256": "5c6fc39e885a960e0288fb6db56a60ed2a0fac727a5249bb1a16d331038c2591", + "size": 948 + }, + { + "path": "v29_app.py", + "sha256": "3f803143e8011e6c777c4b9e1273e14beb4c240e60ff577854dd5b34b4f4bc1f", + "size": 1193 + } + ], + "generated_at": 1787486728.800977, + "phase": "24", + "product": "P29", + "python_min": "3.10", + "version": "29.0" +} \ No newline at end of file diff --git a/SECRET_COMPATIBILITY.md b/SECRET_COMPATIBILITY.md new file mode 100644 index 0000000000000000000000000000000000000000..e04bf74e75de592421d483f16e0d5a3eab9a12a9 --- /dev/null +++ b/SECRET_COMPATIBILITY.md @@ -0,0 +1,28 @@ +# P29 Secret Compatibility + +The existing secret names are intentionally unchanged. Existing deployments can +continue to use environment variables exactly as before. + +## Existing names + +- `API_ID` +- `API_HASH` +- `BOT_TOKEN` +- `SESSION_STRING` +- `ADMINS` (legacy fallback: `ADMIN_ID`) +- `MIDDLE_CHANNEL` +- `GEMINI_KEY_1`, `GEMINI_KEY_2`, and any additional `GEMINI_KEY_N` +- `GROQ_KEY_1` and any additional `GROQ_KEY_N` +- `OPENROUTER_KEY_1` and any additional `OPENROUTER_KEY_N` +- `BLOGGER_BLOG_ID` +- `BLOGGER_CLIENT_ID` +- `BLOGGER_CLIENT_SECRET` +- `BLOGGER_REFRESH_TOKEN` +- `P29_SECRET_MASTER_KEY` + +Environment values always have priority. If a value is absent from the +environment, the encrypted SecretManager can supply it. This allows new secrets +to be added at runtime without changing application code. + +The master key itself remains an environment/host secret and is never stored +inside the application database. diff --git a/adapters/__init__.py b/adapters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/bot_core.py b/bot_core.py new file mode 100644 index 0000000000000000000000000000000000000000..7b2932f12e518187ae9efd62ab1b8ec8e18a9b5c --- /dev/null +++ b/bot_core.py @@ -0,0 +1,7466 @@ +import asyncio +import re +import logging +import tempfile +import os +import time +import shutil +import html +import hashlib +import difflib + +from pyrogram import Client, filters +from pyrogram.handlers import MessageHandler, CallbackQueryHandler +from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, InputMediaPhoto, InputMediaVideo +try: + from pyrogram.types import MessageEntity + from pyrogram.enums import MessageEntityType +except Exception: + MessageEntity = None + MessageEntityType = None +from pyrogram.errors import MessageNotModified, FloodWait +from pyrogram.enums import ParseMode + +import config +import database as db +from modules.blogger.ui import register_blogger_handlers, BLOGGER_CALLBACKS, handle_blogger_text_input +from modules.blogger.publisher import BloggerPublisher +from core.app import App as P29App +from core.control.section_control import SectionControl + +logging.basicConfig(level=logging.INFO) +from modules.logging_security import install_logging_safety +install_logging_safety() +logger = logging.getLogger(__name__) +logging.getLogger("pyrogram").setLevel(logging.WARNING) +logging.getLogger("pyrogram.session").setLevel(logging.WARNING) +logging.getLogger("pyrogram.connection").setLevel(logging.WARNING) +logging.getLogger("pyrogram.dispatcher").setLevel(logging.WARNING) + +bot_client = None +user_client = None +BOT_LOG_FILE = "/tmp/telegram_auto_poster_bot.log" +user_states = {} +# Per-user back navigation stack so every shared UI page can return one step +# to the exact page the user came from, like a mobile app back gesture. +_BACK_STACKS = {} +_BACK_CURRENT = {} +_BACK_STACK_LIMIT = 16 + +_P29_APP = None +_P29_SECTION_CONTROL = None + +def _get_p29_runtime(): + global _P29_APP, _P29_SECTION_CONTROL + if _P29_APP is None: + _P29_APP = P29App(legacy_db=db) + _P29_SECTION_CONTROL = SectionControl(_P29_APP.runtime, admin_check=lambda uid: is_admin(uid) if uid is not None else False) + return _P29_APP.runtime, _P29_SECTION_CONTROL + + +def _back_stack_key(callback): + from_user = getattr(callback, "from_user", None) or {} + user_id = from_user.get("id") if isinstance(from_user, dict) else getattr(from_user, "id", None) + if user_id is None: + msg = getattr(callback, "message", None) + chat = getattr(msg, "chat", None) + user_id = getattr(chat, "id", None) if chat is not None else None + return user_id + + +def _push_back(callback): + key = _back_stack_key(callback) + if key is None: + return + stack = list(_BACK_STACKS.get(key) or []) + stack.append(str(callback.data)) + if len(stack) > _BACK_STACK_LIMIT: + stack = stack[-_BACK_STACK_LIMIT:] + _BACK_STACKS[key] = stack + _BACK_CURRENT[key] = str(callback.data) +def _back_step(callback): + """الصفحة السابقة للصفحة الحالية (سلوك زر الرجوع في تطبيقات الموبايل). + يزيل مدخلات الصفحة الحالية المتكررة في أعلى المكدس ثم يعيد الصفحة التي تحتها.""" + key = _back_stack_key(callback) + stack = list(_BACK_STACKS.get(key) or []) + current = _BACK_CURRENT.get(key) + while stack and stack[-1] == current: + stack.pop() + previous = None + if stack: + previous = stack.pop() + _BACK_STACKS[key] = stack + return previous +def _peek_prev_back(callback): + """الصفحة قبل الصفحة الحالية في المكدس (زر الرجوع في صفحات الشرح والتنفيذ).""" + key = _back_stack_key(callback) + stack = _BACK_STACKS.get(key) or [] + if len(stack) < 2: + return None + return stack[-2] + + +_middle_peer_warmed = False +_middle_auto_ignore_until = 0.0 +_middle_album_buffers = {} +_middle_album_tasks = {} +_last_poll_ok = time.time() +_last_publish_ok = time.time() +_last_watchdog_alert = 0.0 +_last_heartbeat_log = 0.0 +_notification_alerted_ids = set() +_last_alert_ts = {} + +# Telegram limits callback_data to 64 UTF-8 bytes. UI pages can carry nested +# back callbacks and resource IDs that exceed that limit, so retain the full +# UI payload server-side and expose only a short opaque token to Telegram. +_UI_CALLBACK_CONTEXTS = {} +_UI_CALLBACK_CONTEXT_LIMIT = 4096 + + +def _compact_ui_callback_data(callback_data): + if not callback_data: + return callback_data + if len(str(callback_data).encode("utf-8")) <= 64: + return callback_data + raw = str(callback_data) + token = hashlib.sha1(raw.encode("utf-8")).hexdigest()[:12] + key = f"ui_ctx|{token}" + _UI_CALLBACK_CONTEXTS[key] = raw + if len(_UI_CALLBACK_CONTEXTS) > _UI_CALLBACK_CONTEXT_LIMIT: + oldest = next(iter(_UI_CALLBACK_CONTEXTS), None) + if oldest is not None and oldest != key: + _UI_CALLBACK_CONTEXTS.pop(oldest, None) + return key + + +def _expand_ui_callback_data(callback_data): + if not str(callback_data).startswith("ui_ctx|"): + return callback_data + return _UI_CALLBACK_CONTEXTS.get(str(callback_data)) + + +def _compact_ui_markup(reply_markup): + if reply_markup is None: + return reply_markup + for row in getattr(reply_markup, "inline_keyboard", ()) or (): + for button in row or (): + callback_data = getattr(button, "callback_data", None) + compacted = _compact_ui_callback_data(callback_data) + if compacted != callback_data: + button.callback_data = compacted + return reply_markup + + +def is_admin(user_id): + return user_id in config.ADMINS + +def mark_runtime_activity(kind="poll"): + """يسجل آخر نشاط ناجح حتى نعرف إذا البوت عالق بدون نشر/فحص.""" + global _last_poll_ok, _last_publish_ok + now = time.time() + if kind == "publish": + _last_publish_ok = now + _last_poll_ok = now + + +def is_transient_network_error(error): + """أخطاء اتصال مؤقتة من HuggingFace/Telegram لا تعتبر عطل منطقي بالكود.""" + text = str(error).lower() + transient_terms = [ + "broken pipe", + "socket.send() raised exception", + "connection reset", + "connection aborted", + "server disconnected", + "transport closed", + "timed out", + "timeout", + "network is unreachable", + "cannot write to closing transport", + ] + return any(term in text for term in transient_terms) + + +async def reconnect_user_client_if_needed(reason=""): + """محاولة إنعاش جلسة الحساب عند Broken pipe بدون لمس إعدادات النشر.""" + global _middle_peer_warmed + try: + logger.warning(f"🔌 محاولة إعادة تهيئة اتصال user_client بسبب: {reason}") + try: + await user_client.stop() + except Exception: + pass + await asyncio.sleep(3) + await user_client.start() + _middle_peer_warmed = False + await warm_middle_peer() + logger.info("✅ تمت إعادة تهيئة اتصال user_client") + return True + except Exception as e: + logger.warning(f"⚠️ فشلت إعادة تهيئة user_client: {e}") + return False + + +async def _retry_on_flood(send_func, label="", max_retries=3): + """ينفذ عملية إرسال مع انتظار تلقائي عند حظر تيليجرام للإرسال السريع.""" + for attempt in range(max_retries): + try: + return await send_func() + except FloodWait as e: + wait = int(e.value) + 2 + logger.warning(f"⏳ FloodWait{' - ' + label if label else ''}: انتظار {wait}s (محاولة {attempt+1}/{max_retries})") + await asyncio.sleep(wait) + except Exception: + raise + return await send_func() + + +# ============================================================ +# VerificationService - طبقة التحقق الموحدة +# ============================================================ + +class VerificationService: + """طبقة تحقق موحدة. + + - جميع عمليات التحقق تمر من هنا فقط. + - يستخدم Smart Cache للواجهات والقوائم. + - يقوم بتحقق حقيقي من Telegram قبل العمليات الحساسة. + - يستخدم BotManager للحصول على التوكنات (لا وصول مباشر للتوكن). + """ + + def __init__(self): + self._verify_cache_ttl = 120 # 2 دقيقة للعمليات + self._ui_cache_ttl = 600 # 10 دقائق للواجهات + + # ---- تحقق داخلي من Telegram (بدون كاش) ---- + + async def _api_check_bot_in_channel(self, token, channel_id): + """اتصال مباشر بـ Telegram للتحقق من وجود البوت في القناة.""" + result = {"verified": False, "can_post": False, "status": "", "permissions": {}} + if not token or not channel_id: + return result + try: + temp = Client(":memory:", api_id=config.API_ID, api_hash=config.API_HASH, bot_token=token, in_memory=True) + await temp.start() + me = await temp.get_me() + try: + member = await temp.get_chat_member(int(channel_id), me.id) + status = member_status_value(getattr(member, "status", None)) + result["status"] = status + if is_bot_admin_status(status): + result["verified"] = True + if hasattr(member, "can_post_messages"): + result["can_post"] = bool(member.can_post_messages) + elif status in ("owner", "creator"): + result["can_post"] = True + else: + result["can_post"] = True + if hasattr(member, "privileges"): + priv = member.privileges + if priv: + result["permissions"] = { + "can_post_messages": bool(getattr(priv, "can_post_messages", True)), + "can_edit_messages": bool(getattr(priv, "can_edit_messages", True)), + "can_delete_messages": bool(getattr(priv, "can_delete_messages", True)), + } + except Exception as e: + result["status"] = str(e)[:50] + await temp.stop() + except Exception as e: + result["status"] = f"فشل الاتصال: {str(e)[:50]}" + return result + + async def _api_check_token(self, token): + """التحقق من صحة التوكن عبر Telegram.""" + result = {"valid": False, "id": "", "username": "", "first_name": "", "error": ""} + try: + temp = Client(":memory:", api_id=config.API_ID, api_hash=config.API_HASH, bot_token=token, in_memory=True) + await temp.start() + me = await temp.get_me() + result["valid"] = True + result["id"] = str(me.id) + result["username"] = me.username or "" + result["first_name"] = me.first_name or "" + await temp.stop() + except Exception as e: + result["error"] = str(e)[:100] + return result + + async def _api_check_session(self, session_string, api_id, api_hash): + """التحقق من صلاحية جلسة مستخدم.""" + result = {"valid": False, "id": "", "username": "", "error": ""} + try: + temp = Client(":memory:", api_id=api_id, api_hash=api_hash, session_string=session_string, in_memory=True) + await temp.start() + me = await temp.get_me() + result["valid"] = True + result["id"] = str(me.id) + result["username"] = me.username or "" + await temp.stop() + except Exception as e: + result["error"] = str(e)[:100] + return result + + async def _api_check_channel(self, channel_id): + """التحقق من إمكانية الوصول للقناة عبر البوت الرئيسي.""" + result = {"ok": False, "title": "", "username": "", "type": "", "error": ""} + try: + chat = await bot_client.get_chat(int(channel_id)) + result["ok"] = True + result["title"] = getattr(chat, "title", "") or "" + result["username"] = getattr(chat, "username", "") or "" + result["type"] = str(getattr(chat, "type", "")) or "" + except Exception as e: + result["error"] = str(e)[:100] + return result + + # ---- تحقق مع كاش للعمليات الحساسة ---- + + async def check_bot_in_channel(self, bot_id, channel_id, force=False): + """التحقق من وجود بوت في قناة. + + - force=True: يتجاهل الكاش ويتصل بـ Telegram مباشرة. + - force=False: يستخدم الكاش إذا كان حديثاً. + """ + token = db.bot_manager.get_token(bot_id) if hasattr(db, "bot_manager") else "" + if not token: + return {"verified": False, "can_post": False, "status": "no_token", + "permissions": {}, "from_cache": False, "last_check": 0} + + cache_key = f"verify_bot|{bot_id}|{channel_id}" + if not force: + cached = db.cache_get(cache_key) + if cached is not None: + cached["from_cache"] = True + return cached + + result = await self._api_check_bot_in_channel(token, channel_id) + result["last_check"] = time.time() + result["from_cache"] = False + result["bot_id"] = bot_id + + db.cache_set(cache_key, result, ttl=self._verify_cache_ttl) + if hasattr(db, "set_bot_channel_verification"): + bname = "" + b = db.get_publishing_bot(bot_id) + if b: + bname = b.get("name", "") + db.set_bot_channel_verification(bot_id, channel_id, + result["verified"], result["can_post"], + result["status"], result["permissions"], + bname, "") + return result + + async def check_channel_before_operation(self, channel_id, force=False): + """التحقق من القناة قبل أي عملية حساسة (نشر/حذف).""" + cache_key = f"channel_op|{channel_id}" + if not force: + cached = db.cache_get(cache_key) + if cached is not None: + return cached.get("ok", False) + + ch = db.get_channel(str(channel_id)) + if not ch: + return False + + ver = await self._api_check_channel(channel_id) + if ver.get("ok"): + db.cache_set(cache_key, {"ok": True}, ttl=self._verify_cache_ttl) + return True + + db.cache_set(cache_key, {"ok": False}, ttl=60) + return False + + async def validate_token(self, token): + """التحقق من صحة توكن بوت.""" + cache_key = f"token_valid|{token[:10]}" + cached = db.cache_get(cache_key) + if cached is not None: + return cached + result = await self._api_check_token(token) + db.cache_set(cache_key, result, ttl=db.CACHE_TTL.get("bot_token_valid", 3600)) + return result + + async def validate_session(self, session_string, api_id, api_hash): + """التحقق من صلاحية جلسة مستخدم.""" + cache_key = f"session_valid|{session_string[:20]}" + cached = db.cache_get(cache_key) + if cached is not None: + return cached + result = await self._api_check_session(session_string, api_id, api_hash) + db.cache_set(cache_key, result, ttl=db.CACHE_TTL.get("session_valid", 600)) + return result + + # ---- دوال مساعدة للواجهات ---- + + def get_cached_verification(self, bot_id, channel_id): + """إرجاع التحقق المخبأ للعرض في الواجهات فقط.""" + if hasattr(db, "get_bot_channel_verification"): + return db.get_bot_channel_verification(bot_id, channel_id) + return {"verified": False, "can_post": False, "status": "", "last_check": 0} + + def _get_from_smartcache_or_db(self, bot_id, channel_id): + """محاولة الحصول على التحقق من Smart Cache أولاً (TTL=120s)، + فإن لم يكن موجوداً→ من Persistent DB (data.json). + يطبع Trace كامل في Console.""" + # 1. حاول من Smart Cache + cache_key = f"verify_bot|{bot_id}|{channel_id}" + cached = db.cache_get(cache_key) if hasattr(db, "cache_get") else None + if cached is not None: + age = int(time.time() - cached.get("last_check", 0)) + logger.info( + f"🔍 TRACE: bot={bot_id} channel={channel_id} " + f"المصدر=SmartCache عمر={age}ث " + f"verified={cached.get('verified')} can_post={cached.get('can_post')}" + ) + return cached + # 2. من Persistent DB + persistent = db.get_bot_channel_verification(bot_id, channel_id) if hasattr(db, "get_bot_channel_verification") else {} + age = int(time.time() - persistent.get("last_check", 0)) if persistent.get("last_check") else -1 + logger.info( + f"🔍 TRACE: bot={bot_id} channel={channel_id} " + f"المصدر=PersistentDB عمر={age}ث " + f"verified={persistent.get('verified')} can_post={persistent.get('can_post')}" + ) + return persistent + + def get_cached_verifications_for_channel(self, channel_id): + """إرجاع جميع التحققات لقناة (للواجهات). + - يحاول Smart Cache أولاً + - يرجع Persistent DB إذا الكاش فارغ + """ + result = {} + # نحتاج IDs البوتات المرتبطة بالقناة + if hasattr(db, "mapper"): + bot_ids = db.mapper.get_bots_for_channel(channel_id) + else: + cfg = db.get_channel_config(channel_id) if hasattr(db, "get_channel_config") else {} + bot_ids = cfg.get("assigned_bots", []) + for bid in bot_ids: + result[str(bid)] = self._get_from_smartcache_or_db(bid, channel_id) + # إذا ما في بوتات مرتبطة بالم mapper، نبحث في persistent + if not bot_ids and hasattr(db, "get_verifications_for_channel"): + result = db.get_verifications_for_channel(channel_id) + return result + + def get_cached_verifications_for_bot(self, bot_id): + """إرجاع جميع التحققات لبوت (للواجهات). + - يحاول Smart Cache أولاً + - يرجع Persistent DB إذا الكاش فارغ + """ + result = {} + # نحتاج IDs القنوات المرتبطة بالبوت + if hasattr(db, "mapper"): + channel_ids = db.mapper.get_channels_for_bot(bot_id) + else: + deps = db.get_dependencies_for("publishing_bot", bot_id) if hasattr(db, "get_dependencies_for") else [] + channel_ids = [d.get("id", "") for d in deps] + for cid in channel_ids: + result[str(cid)] = self._get_from_smartcache_or_db(bot_id, cid) + # إذا ما في قنوات مرتبطة، نبحث في persistent + if not channel_ids and hasattr(db, "get_verifications_for_bot"): + result = db.get_verifications_for_bot(bot_id) + return result + + +# إنشاء instance عامة +verifier = VerificationService() + + +# ============================================================ +# دوال تحقق قديمة (متوافقة مع الكود الموجود) +# ============================================================ + +async def _telegram_verify_bot_in_channel(bot_token, channel_id): + """للتوافق مع الكود القديم - يستخدم VerificationService.""" + return await verifier._api_check_bot_in_channel(bot_token, channel_id) + + +async def require_bot_token_valid(token): + """للتوافق مع الكود القديم.""" + return await verifier.validate_token(token) + + +def member_status_value(member_status): + """يرجع قيمة حالة العضوية كنص نظيف (متوافق مع Enum أو نص من أي إصدار pyrogram).""" + if member_status is None: + return "" + if hasattr(member_status, "value"): + return str(member_status.value) + return str(member_status) + + +def is_bot_admin_status(status_value): + """الحالات الصالحة: ADMINISTRATOR / OWNER (و creator للتوافق القديم). + غير الصالحة: MEMBER / LEFT / BANNED / RESTRICTED.""" + return status_value in ("administrator", "owner", "creator") + + +async def _verify_channel_before_publish(target): + """التحقق من القناة قبل النشر.""" + return await verifier.check_channel_before_operation(str(target)) + + +async def heartbeat_watchdog_loop(): + """نبض مراقبة: يطبع حالة دورية وينبه إذا توقف الفحص/النشر مدة طويلة.""" + global _last_watchdog_alert, _last_heartbeat_log + await asyncio.sleep(60) + while True: + try: + now = time.time() + idle_poll = int(now - _last_poll_ok) + idle_publish = int(now - _last_publish_ok) + + if now - _last_heartbeat_log >= 600: + _last_heartbeat_log = now + logger.info(f"💓 Heartbeat OK | آخر فحص قبل {idle_poll}s | آخر نشر قبل {idle_publish}s") + + if idle_poll >= 3600 and now - _last_watchdog_alert >= 3600: + _last_watchdog_alert = now + logger.warning(f"⚠️ Watchdog: لا يوجد فحص ناجح منذ {idle_poll} ثانية") + await notify_admins(f"⚠️ تنبيه مراقبة: لا يوجد فحص ناجح منذ {idle_poll // 60} دقيقة. إذا لم يرجع النشر، افتح الاستضافة أو سوِ Restart.") + await reconnect_user_client_if_needed("watchdog idle poll") + except Exception as e: + logger.warning(f"⚠️ خطأ في Heartbeat/Watchdog: {e}") + await asyncio.sleep(60) + +def clean_text(text, source_id=None, channel_id=None): + """تنظيف نهائي قبل النشر لقناة معيّنة. يرجع None إذا النص يحتوي كلمة محظورة خاصة بهذه القناة.""" + if not text: + return text + + if isinstance(text, str): + text = full_clean_text(text, source_id=source_id) + text = apply_channel_remove_terms(text, channel_id) + text = apply_channel_link_filters(text, channel_id) + + blocked = db.get_channel_blocked_words(channel_id) if channel_id is not None and hasattr(db, "get_channel_blocked_words") else [] + for word in blocked: + if word and word in text: + return None + + return "\n".join(line for line in text.splitlines() if line.strip()) + + return text + +def apply_tail(text, tail): + if tail: + return f"{text}\n{tail}" if text else tail + return text + + +def get_publish_delay_for_channel(channel_id, default=0.5): + try: + return db.get_channel_publish_delay(channel_id, default) if hasattr(db, "get_channel_publish_delay") else default + except Exception: + return default + +def is_channel_bold_enabled(channel_id): + try: + return bool(db.get_channel_bold_publish(channel_id, True)) if hasattr(db, "get_channel_bold_publish") else True + except Exception: + return True + + +def _utf16_len(text): + try: + return len(str(text or "").encode("utf-16-le")) // 2 + except Exception: + return len(str(text or "")) + + +def _entity_type(name): + if MessageEntityType is None: + return None + try: + return getattr(MessageEntityType, name) + except Exception: + return None + + +def build_quote_entities_for_channel(text, channel_id, content_type="text"): + """يبني entities رسمية للاقتباس حتى لا نعتمد على HTML blockquote إذا ما يدعمه Pyrogram.""" + if not text: + return None + if not is_channel_quote_enabled(channel_id, content_type): + return None + if MessageEntity is None or MessageEntityType is None: + return None + + length = _utf16_len(text) + if length <= 0: + return None + + entities = [] + blockquote_type = _entity_type("BLOCKQUOTE") + bold_type = _entity_type("BOLD") + + if blockquote_type is not None: + try: + entities.append(MessageEntity(type=blockquote_type, offset=0, length=length)) + except Exception: + return None + + if is_channel_bold_enabled(channel_id) and bold_type is not None: + try: + entities.append(MessageEntity(type=bold_type, offset=0, length=length)) + except Exception: + pass + + return entities or None + + +def _html_quote_text_for_channel(text, channel_id): + """يبني اقتباس Telegram الرسمي بصيغة HTML بدون إضافة رموز مرئية مثل ▌.""" + escaped = html.escape(str(text or "")) + if is_channel_bold_enabled(channel_id): + escaped = f"{escaped}" + return f"
{escaped}" + + +def format_outgoing_payload_for_channel(text, channel_id, content_type="text", news_text=None, tail=None): + """يرجع النص + parse_mode + entities. عند تفعيل الاقتباس نستخدم Telegram Quote الرسمي فقط.""" + if not text: + return text, None, None + + cfg = db.get_channel_config(channel_id) if hasattr(db, "get_channel_config") else {} + title_quote = bool(cfg.get("title_quote", False)) + sig_quote = bool(cfg.get("signature_quote", False)) + + if title_quote or sig_quote: + bold_enabled = is_channel_bold_enabled(channel_id) + body = str(text) + news_text_str = str(news_text or "").strip() + tail_str = str(tail or "").strip() + escaped_body = html.escape(body) + # نبحث عن النص الأصلي ونبدله بالنسخة المقتبسة داخل الـ HTML + if title_quote and news_text_str: + escaped_news = html.escape(news_text_str) + if escaped_news in escaped_body: + escaped_body = escaped_body.replace(escaped_news, f"
{escaped_news}", 1) + if sig_quote and tail_str: + escaped_tail = html.escape(tail_str) + idx = escaped_body.rfind(escaped_tail) + if idx != -1: + escaped_body = escaped_body[:idx] + f"
{escaped_tail}" + escaped_body[idx + len(escaped_tail):] + if bold_enabled: + escaped_body = f"{escaped_body}" + return escaped_body, ParseMode.HTML, None + + if is_channel_quote_enabled(channel_id, content_type): + entities = build_quote_entities_for_channel(str(text), channel_id, content_type) + if entities: + return str(text), None, entities + return _html_quote_text_for_channel(text, channel_id), ParseMode.HTML, None + + formatted, parse_mode = format_outgoing_text_for_channel(text, channel_id) + return formatted, parse_mode, None + + +def format_outgoing_text_for_channel(text, channel_id): + """يرجع النص مع ParseMode المناسب. ترتيب الهاشتاك/التوقيع يتم قبل هذه الدالة.""" + if not text: + return text, None + + bold_enabled = is_channel_bold_enabled(channel_id) + + escaped = html.escape(str(text)) + if bold_enabled: + escaped = f"{escaped}" + + if bold_enabled: + return escaped, ParseMode.HTML + return str(text), None + +def channel_display_name(ch_or_id): + ch = ch_or_id if isinstance(ch_or_id, dict) else db.get_channel(ch_or_id) + if isinstance(ch, dict): + name = entity_name(ch) + cid = ch.get("id") + if isinstance(cid, (str, int)): + return f"{name} | ID: `{cid}`" + return name + if isinstance(ch_or_id, (str, int)): + return f"ID: `{ch_or_id}`" + return str(ch_or_id or "") + + +def source_display_name(src_id): + meta = db.get_source_meta(src_id) if hasattr(db, "get_source_meta") else {"id": src_id} + return f"{entity_name(meta)} | ID: `{src_id}`" + + +def pair_buttons(buttons): + """يرتب الأزرار المفردة على عمودين قدر الإمكان.""" + rows = [] + pending = [] + for item in buttons: + if isinstance(item, list): + if pending: + rows.append(pending) + pending = [] + rows.append(item) + else: + pending.append(item) + if len(pending) == 2: + rows.append(pending) + pending = [] + if pending: + rows.append(pending) + return rows + + + + +def grid_buttons(buttons, max_cols=3): + """يرتب الأزرار المفردة بعمودين فقط حتى تظهر أسماء الأزرار بوضوح.""" + rows = [] + pending = [] + max_cols = 2 + for item in buttons: + if isinstance(item, list): + if pending: + rows.append(pending) + pending = [] + rows.append(item) + else: + pending.append(item) + if len(pending) >= max_cols: + rows.append(pending) + pending = [] + if pending: + rows.append(pending) + return rows + + +def nav_row(back=None): + row = [] + if back: + row.append(InlineKeyboardButton("🔙 رجوع", callback_data=back)) + row.append(InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")) + return row + + +def append_channel_hashtags(text, channel_id): + try: + tags = db.get_channel_hashtags(channel_id) if hasattr(db, "get_channel_hashtags") else [] + except Exception: + tags = [] + if not tags: + return text + tag_line = " ".join(tags) + return f"{text}\n\n{tag_line}" if text else tag_line + + +def compose_channel_post_text(news_text, channel_id, tail=""): + """يرتب المنشور دائماً: الخبر ثم الهاشتاك ثم التوقيع ثم الفاصل.""" + parts = [] + news_text = str(news_text or "").strip() + if news_text: + parts.append(news_text) + try: + tags = db.get_channel_hashtags(channel_id) if hasattr(db, "get_channel_hashtags") else [] + except Exception: + tags = [] + if tags: + parts.append(" ".join(tags).strip()) + tail = str(tail or "").strip() + if tail: + parts.append(tail) + if "---" not in tail and "—" not in tail: + parts.append("------------") + return "\n\n".join([p for p in parts if p]) + +def is_channel_quote_enabled(channel_id, content_type="text"): + try: + if hasattr(db, "get_channel_quote_type"): + return bool(db.get_channel_quote_type(channel_id, content_type, False)) + return bool(db.get_channel_quote_publish(channel_id, False)) if hasattr(db, "get_channel_quote_publish") else False + except Exception: + return False + + +def get_channel_quote_types_safe(channel_id): + try: + if hasattr(db, "get_channel_quote_types"): + return db.get_channel_quote_types(channel_id) + except Exception: + pass + enabled = is_channel_quote_enabled(channel_id, "text") + return {"text": enabled, "photo": enabled, "video": enabled, "album": enabled} + + + +def is_ignore_short_posts_enabled(): + try: + return bool(db.get_ignore_short_posts()) if hasattr(db, "get_ignore_short_posts") else False + except Exception: + return False + + +def is_short_post_text(text, min_words=5, min_chars=20): + cleaned = compact_text(text or "") + if not cleaned: + return False + word_count = len([w for w in cleaned.split() if w.strip()]) + char_count = len(cleaned) + return word_count < int(min_words) or char_count < int(min_chars) + + +def is_ignore_short_posts_enabled_for_channel(channel_id): + try: + if hasattr(db, "get_channel_ignore_short_posts"): + return bool(db.get_channel_ignore_short_posts(channel_id)) + except Exception: + pass + return is_ignore_short_posts_enabled() + + +def should_ignore_short_post(text): + """Legacy global helper kept for compatibility with older callers/tests.""" + return is_ignore_short_posts_enabled() and is_short_post_text(text) + + +def should_ignore_short_post_for_channel(text, channel_id): + return is_ignore_short_posts_enabled_for_channel(channel_id) and is_short_post_text(text) + + +def record_channel_success(channel_id): + try: + if hasattr(db, "record_channel_publish_success"): + db.record_channel_publish_success(channel_id) + except Exception: + pass + + +async def record_channel_failure_and_maybe_alert(channel_id, error): + count = None + try: + if hasattr(db, "record_channel_publish_failure"): + count = db.record_channel_publish_failure(channel_id, error, limit=5) + except Exception: + pass + if count and int(count) >= 5: + await notify_admins(f"تم إيقاف قناة النشر تلقائياً بعد {count} أخطاء متتالية:\n{channel_display_name(channel_id)}\n\nالخطأ: {error}") + +async def notify_admins(text): + try: + if hasattr(db, "add_last_error"): + db.add_last_error("admin_alert", text) + except Exception: + pass + for admin_id in config.ADMINS: + try: + await bot_client.send_message(admin_id, f"⚠️ {text}") + except Exception as e: + logger.error(f"فشل إشعار الأدمن {admin_id}: {e}") + +async def hydrate_peer(client, chat_id, label="peer"): + """يحاول تحميل الـ peer داخل جلسة Pyrogram حتى لا يظهر Peer id invalid.""" + try: + chat = await client.get_chat(int(chat_id)) + logger.info(f"✅ تم تحميل {label}: {getattr(chat, 'id', chat_id)}") + return chat + except Exception as first_error: + logger.warning(f"⚠️ فشل get_chat أول مرة لـ {label}={chat_id}: {first_error}. سيتم فحص الحوارات...") + + try: + async for dialog in client.get_dialogs(limit=300): + if dialog.chat and int(dialog.chat.id) == int(chat_id): + logger.info(f"✅ تم العثور على {label} داخل الحوارات: {chat_id}") + return dialog.chat + except Exception as dialog_error: + logger.warning(f"⚠️ فشل فحص الحوارات لـ {label}: {dialog_error}") + + chat = await client.get_chat(int(chat_id)) + return chat + + +async def hydrate_publish_channel(channel_id): + """تهيئة قناة نشر قبل الإرسال، خصوصاً بعد الاستيراد.""" + ch = db.get_channel(channel_id) if hasattr(db, "get_channel") else None + candidates = [] + if ch: + username = ch.get("username") or "" + link = ch.get("link") or "" + if username: + candidates.append("@" + username.lstrip("@")) + if link: + candidates.append(link) + candidates.append(int(channel_id)) + last_error = None + for item in candidates: + try: + return await bot_client.get_chat(item) + except Exception as e: + last_error = e + raise last_error or ValueError(f"تعذر تهيئة قناة النشر {channel_id}") + + +async def hydrate_source_channel(source_id): + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {} + candidates = [] + username = meta.get("username") or "" if isinstance(meta, dict) else "" + link = meta.get("link") or "" if isinstance(meta, dict) else "" + if username: + candidates.append("@" + username.lstrip("@")) + if link: + candidates.append(link) + candidates.append(int(source_id)) + last_error = None + for item in candidates: + try: + return await user_client.get_chat(item) + except Exception as e: + last_error = e + raise last_error or ValueError(f"تعذر تهيئة المصدر {source_id}") + + +async def safe_send_channel_message(target, text, parse_mode=None, entities=None): + """إرسال نص مع معالجة FloodWait وإعادة تهيئة peer عند الحاجة.""" + try: + await hydrate_publish_channel(target) + except Exception as e: + logger.warning(f"⚠️ فشل تهيئة قناة النشر {target} قبل الإرسال: {e}") + + disable_preview = db.get_channel_disable_preview(target) if hasattr(db, "get_channel_disable_preview") else False + + async def _send_once(): + if entities: + try: + return await bot_client.send_message(target, text, entities=entities, disable_web_page_preview=disable_preview) + except TypeError: + return await bot_client.send_message(target, _html_quote_text_for_channel(text, target), parse_mode=ParseMode.HTML, disable_web_page_preview=disable_preview) + return await bot_client.send_message(target, text, parse_mode=parse_mode, disable_web_page_preview=disable_preview) + + for attempt in range(3): + try: + return await _send_once() + except FloodWait as e: + wait = int(e.value) + 2 + logger.warning(f"⏳ FloodWait في الإرسال إلى {target}: انتظار {wait}s (محاولة {attempt+1}/3)") + await asyncio.sleep(wait) + except Exception as first_error: + if "Peer id invalid" in str(first_error) or "PEER_ID_INVALID" in str(first_error): + await hydrate_publish_channel(target) + return await _send_once() + raise + return await _send_once() + +async def warm_middle_peer(): + """تحميل القناة الوسيطة داخل جلسة الحساب والبوت قبل أي تحويل ميديا.""" + global _middle_peer_warmed + if _middle_peer_warmed: + return True + + ok = True + try: + await hydrate_peer(user_client, config.MIDDLE_CHANNEL, "القناة الوسيطة / user_client") + except Exception as e: + ok = False + logger.error(f"❌ user_client لا يستطيع الوصول للقناة الوسيطة {config.MIDDLE_CHANNEL}: {e}") + + try: + await hydrate_peer(bot_client, config.MIDDLE_CHANNEL, "القناة الوسيطة / bot_client") + except Exception as e: + ok = False + logger.error(f"❌ bot_client لا يستطيع الوصول للقناة الوسيطة {config.MIDDLE_CHANNEL}: {e}") + + _middle_peer_warmed = ok + return ok + +async def forward_to_middle(source_chat_id, message_ids): + """يحّول رسالة أو مجموعة رسائل إلى القناة الوسيطة مع إعادة محاولة عند Peer id invalid.""" + await warm_middle_peer() + try: + return await user_client.forward_messages( + chat_id=config.MIDDLE_CHANNEL, + from_chat_id=int(source_chat_id), + message_ids=message_ids + ) + except Exception as e: + logger.warning(f"⚠️ فشل التوجيه للوسيطة، سيتم إعادة تحميل الـ peer والمحاولة مرة ثانية: {e}") + global _middle_peer_warmed + _middle_peer_warmed = False + await warm_middle_peer() + return await user_client.forward_messages( + chat_id=config.MIDDLE_CHANNEL, + from_chat_id=int(source_chat_id), + message_ids=message_ids + ) + +async def copy_middle_messages_to_target(target, middle_messages, caption=None, parse_mode=None, content_type=None, caption_entities=None): + """ينسخ رسائل الوسيطة لقناة النشر. + - الصور/الفيديو المفرد: copy_message بدون تحميل. + - الألبومات: send_media_group كألبوم واحد بدون Forward. + """ + if not isinstance(middle_messages, (list, tuple)): + middle_messages = [middle_messages] + + middle_messages = sorted([m for m in middle_messages if m], key=lambda m: m.id) + if not middle_messages: + return False + + try: + await hydrate_publish_channel(target) + except Exception as e: + logger.warning(f"⚠️ فشل تهيئة قناة النشر {target} قبل النسخ: {e}") + + is_album = len(middle_messages) > 1 or bool(getattr(middle_messages[0], "media_group_id", None)) + + # الألبومات فقط: نرسلها كـ Media Group واحد حتى لا تتفكك إلى صور منفصلة. + # هذا المسار قد يحمّل ملفات الألبوم مؤقتاً ثم يحذفها، بينما الصور/الفيديو المفرد تبقى بدون تحميل. + if is_album and len(middle_messages) > 1: + temp_dir = tempfile.mkdtemp(prefix="album_clean_") + downloaded_files = [] + media_items = [] + try: + for idx, m in enumerate(middle_messages): + if not getattr(m, "photo", None) and not getattr(m, "video", None): + logger.warning(f"⚠️ تم تخطي عنصر غير مدعوم داخل الألبوم | message_id={getattr(m, 'id', None)}") + continue + + file_path = await m.download(file_name=os.path.join(temp_dir, "")) + if not file_path: + logger.warning(f"⚠️ فشل تنزيل عنصر من الألبوم | message_id={getattr(m, 'id', None)}") + continue + + downloaded_files.append((file_path, bool(getattr(m, "video", None)))) + item_caption = caption if idx == 0 and caption else None + + if getattr(m, "video", None): + media_items.append(InputMediaVideo( + media=file_path, + caption=item_caption, + parse_mode=None if (idx == 0 and item_caption and caption_entities) else (parse_mode if item_caption else None), + caption_entities=caption_entities if idx == 0 and item_caption and caption_entities else None + )) + else: + media_items.append(InputMediaPhoto( + media=file_path, + caption=item_caption, + parse_mode=None if (idx == 0 and item_caption and caption_entities) else (parse_mode if item_caption else None), + caption_entities=caption_entities if idx == 0 and item_caption and caption_entities else None + )) + + if not media_items: + logger.error(f"❌ فشل نشر الألبوم النظيف إلى {target}: لا توجد وسائط صالحة") + return False + + sent = None + pyrofork_topics_success = False + try: + sent = await _retry_on_flood(lambda: bot_client.send_media_group(chat_id=int(target), media=media_items), label=f"album→{target}") + except TypeError as e: + err_text = str(e) + if "topics" in err_text and "Messages.__init__" in err_text: + pyrofork_topics_success = True + logger.warning(f"⚠️ نُشر الألبوم غالباً لكن Pyrofork فشل بقراءة الرد بسبب topics؛ اعتُبر نجاحاً لمنع التكرار | target={target}") + else: + # بعض إصدارات Pyrogram/Pyrofork لا تقبل caption_entities داخل InputMedia. + media_items = [] + for idx, (file_path, is_video_file) in enumerate(downloaded_files): + item_caption = caption if idx == 0 and caption else None + if is_video_file: + media_items.append(InputMediaVideo(media=file_path, caption=item_caption, parse_mode=parse_mode if item_caption else None)) + else: + media_items.append(InputMediaPhoto(media=file_path, caption=item_caption, parse_mode=parse_mode if item_caption else None)) + try: + sent = await _retry_on_flood(lambda: bot_client.send_media_group(chat_id=int(target), media=media_items), label=f"album→{target}") + except TypeError as e2: + err_text2 = str(e2) + if "topics" in err_text2 and "Messages.__init__" in err_text2: + pyrofork_topics_success = True + logger.warning(f"⚠️ نُشر الألبوم غالباً لكن Pyrofork فشل بقراءة الرد بسبب topics؛ اعتُبر نجاحاً لمنع التكرار | target={target}") + else: + raise + except Exception as e: + err_text = str(e) + if "topics" in err_text and "Messages.__init__" in err_text: + pyrofork_topics_success = True + logger.warning(f"⚠️ نُشر الألبوم غالباً لكن Pyrofork فشل بقراءة الرد بسبب topics؛ اعتُبر نجاحاً لمنع التكرار | target={target}") + else: + raise + + sent_list = [] if sent is None else (sent if isinstance(sent, list) else [sent]) + sent_ids = [m.id for m in sent_list if getattr(m, "id", None)] + try: + if hasattr(db, "record_published_messages") and sent_ids: + db.record_published_messages(target, sent_ids, content_type or "album") + except Exception: + pass + + mark_runtime_activity("publish") + if pyrofork_topics_success: + logger.info(f"✅ نُشر ألبوم نظيف إلى {target} بدون Forward | Pyrofork topics handled") + else: + logger.info(f"✅ نُشر ألبوم نظيف إلى {target} بدون Forward | count={len(sent_ids)}") + return True + except Exception as e: + logger.error(f"❌ فشل نشر الألبوم النظيف إلى {target}: {e}") + try: + if hasattr(db, "add_last_error"): + db.add_last_error("clean_album", f"{target}: {e}") + except Exception: + pass + return False + finally: + shutil.rmtree(temp_dir, ignore_errors=True) + + # الصور والفيديوهات المفردة: تبقى بدون تحميل عبر copy_message. + sent_ids = [] + disable_preview = db.get_channel_disable_preview(target) if hasattr(db, "get_channel_disable_preview") else False + for idx, m in enumerate(middle_messages): + item_caption = caption if idx == 0 and caption else None + item_parse_mode = None if (idx == 0 and caption and caption_entities) else (parse_mode if idx == 0 and caption else None) + + kwargs = dict( + chat_id=int(target), + from_chat_id=config.MIDDLE_CHANNEL, + message_id=m.id, + caption=item_caption, + parse_mode=item_parse_mode, + disable_web_page_preview=disable_preview, + ) + if idx == 0 and caption and caption_entities: + kwargs["caption_entities"] = caption_entities + + async def _do_copy(kw=kwargs, ix=idx, cap=item_caption): + try: + return await bot_client.copy_message(**kw) + except TypeError: + kw.pop("caption_entities", None) + kw.pop("disable_web_page_preview", None) + if ix == 0 and cap and caption_entities: + kw["caption"] = _html_quote_text_for_channel(cap, target) + kw["parse_mode"] = ParseMode.HTML + else: + kw["parse_mode"] = parse_mode if ix == 0 and cap else None + return await bot_client.copy_message(**kw) + + try: + sent = await _retry_on_flood(_do_copy, label=f"copy→{target}") + if getattr(sent, "id", None): + sent_ids.append(sent.id) + except Exception as e: + logger.warning(f"⚠️ فشل نسخ رسالة وسيطة إلى {target} (idx={idx}): {e}") + + await asyncio.sleep(0.3) + + try: + if hasattr(db, "record_published_messages") and sent_ids: + db.record_published_messages(target, sent_ids, content_type or "photo") + except Exception: + pass + + if sent_ids: + mark_runtime_activity("publish") + logger.info(f"✅ نُشر {len(sent_ids)} رسالة إلى {target} بدون تحميل") + return True + + logger.warning(f"⚠️ فشل نشر جميع رسائل الوسيطة إلى {target}") + return False + +async def safe_edit(callback, text, reply_markup=None): + if len(text) > 4096: + text = text[:4093] + "..." + reply_markup = _compact_ui_markup(reply_markup) + try: + await callback.edit_message_text(text, reply_markup=reply_markup) + except MessageNotModified: + try: + await callback.answer() + except Exception: + pass + except Exception as e: + callback_data = getattr(callback, "data", "") + logger.error( + "فشل تعديل الرسالة: callback=%r error=%s: %s", + callback_data, + type(e).__name__, + e, + ) + try: + await callback.answer("حدث خطأ أثناء تحديث القائمة.", show_alert=True) + except Exception: + pass + +async def resolve_chat_id(raw, prefer_user=True): + chat = await resolve_chat_info(raw, prefer_user=prefer_user) + return int(chat.id) + + +def normalize_chat_input(raw): + raw = str(raw).strip() + match = re.match(r'(?:https?://)?t\.me/([A-Za-z0-9_]+)', raw) + if match: + raw = "@" + match.group(1) + return raw + + +def split_bulk_lines(text): + items = [] + for line in str(text or "").splitlines(): + line = line.strip() + if not line: + continue + if "," in line and "t.me/" not in line: + items.extend([p.strip() for p in line.split(",") if p.strip()]) + else: + items.append(line) + seen = set() + unique = [] + for item in items: + key = normalize_chat_input(item).lower() + if key not in seen: + seen.add(key) + unique.append(item) + return unique + + +def split_terms_lines(text): + """يقسم النص إلى عناصر جماعية: كل سطر عنصر، ويدعم الفواصل إذا ما بيها روابط.""" + items = [] + for line in str(text or "").splitlines(): + line = line.strip() + if not line: + continue + if "," in line and "http" not in line and "t.me/" not in line: + items.extend([p.strip() for p in line.split(",") if p.strip()]) + else: + items.append(line) + seen = set() + out = [] + for item in items: + key = item.lower() + if key not in seen: + seen.add(key) + out.append(item) + return out + + +async def resolve_chat_info_timeout(raw, prefer_user=True, timeout=8): + """يجلب معلومات القناة/المصدر بمهلة حتى لا يعلق البوت عند الإضافة.""" + return await asyncio.wait_for(resolve_chat_info(raw, prefer_user=prefer_user), timeout=timeout) + + +def apply_source_remove_terms(text, source_id): + """التنظيف الذكي: يحذف عناصر هذا المصدر فقط ولا يمنع المنشور.""" + if not text: + return text + try: + terms = db.get_source_remove_terms(source_id) if hasattr(db, "get_source_remove_terms") else [] + except Exception: + terms = [] + cleaned = str(text) + for term in terms: + cleaned = remove_term_variants(cleaned, term) + return compact_text(cleaned) + + +# ===== 🔗 إدارة الروابط — خاصة بكل قناة على حدة ===== +CHANNEL_LINK_TG_RE = re.compile(r"(?:https?://)?(?:www\.)?(?:t(?:elegram|lgrm)?\.me|t\.me)/[^\s]+", re.IGNORECASE) +CHANNEL_TG_USERNAME_RE = re.compile(r"(?= 3 or token.isdigit()] + if len(tokens) < 3: + return "" + return hashlib.sha1(" ".join(sorted(set(tokens))).encode("utf-8", errors="ignore")).hexdigest() + + +def make_url_fp(text): + urls = re.findall(r"https?://[^\s<>]+", str(text or ""), flags=re.IGNORECASE) + if not urls: + return "" + clean_urls = sorted({url.rstrip(".,،؛:!?)]}'\"") for url in urls}) + return hashlib.sha1("\n".join(clean_urls).encode("utf-8", errors="ignore")).hexdigest() + + +def _event_overlap(left, right): + left_tokens = set(str(left or "").split()) + right_tokens = set(str(right or "").split()) + if len(left_tokens) < 3 or len(right_tokens) < 3: + return 0.0 + return len(left_tokens & right_tokens) / max(1, len(left_tokens | right_tokens)) + + +def _event_core_tokens(text): + """يبني مجموعة كلمات حدث حتمية لمطابقة الصياغات العربية المختصرة. + لا يعتمد على AI ولا يساوي بين خبرين لمجرد اشتراكهما بكلمة عامة.""" + stopwords = { + "من", "في", "عن", "على", "الى", "إلى", "مع", "هذا", "هذه", "ذلك", "تلك", + "الذي", "التي", "تم", "قد", "كما", "بعد", "قبل", "اليوم", "غدا", "غدًا", + "اعلن", "أعلن", "تعلن", "يعلن", "أعلنت", "قال", "تقول", "ذكر", "حول", "ضمن", + "بشأن", "بخصوص", "و", "أو", "او", "ثم", "أن", "ان", "إن", "وذلك", + } + tokens = set() + for token in normalize_for_similarity(text).split(): + token = token.strip(".,،؛:!?()[]{}\"'") + if len(token) < 3 or token in stopwords: + continue + variants = {token} + if token.startswith("ال") and len(token) > 4: + variants.add(token[2:]) + # توحيد لواصق عربية شائعة داخل هوية الحدث: للعراق/العراق → عراق. + if token.startswith("لل") and len(token) > 4: + variants.add(token[2:]) + if token.startswith("و") and len(token) > 4: + variants.add(token[1:]) + if token.endswith("ية") and len(token) > 5: + variants.add(token[:-2]) + tokens.update(variants) + return tokens + + +def _event_identity_score(left, right): + """درجة تغطية كلمات الحدث المشتركة؛ الصفر يعني عدم كفاية الهوية.""" + left_core = _event_core_tokens(left) + right_core = _event_core_tokens(right) + if len(left_core) < 3 or len(right_core) < 3: + return 0.0 + shared = left_core & right_core + if len(shared) < 3: + return 0.0 + return len(shared) / max(1, min(len(left_core), len(right_core))) + + +def _event_numbers(text): + return set(re.findall(r"(?= 0.75: + return True, "event_identity", event_identity_score + if ratio >= threshold: + stored_event_fp = item.get("event_fp", "") + if event_fp and stored_event_fp and stored_event_fp != event_fp: + details_differ = True + continue + return True, "similarity", ratio + # 4. Event Overlap — لا يجوز حكماً منفرداً: يتطلب تطابق event_fp + stored_event_fp = item.get("event_fp", "") + if ( + 0.60 <= ratio < threshold + and _event_overlap(normalized, sample) >= 0.70 + and event_fp + and stored_event_fp + and stored_event_fp == event_fp + ): + return True, "event_overlap", ratio + # 5. المنطقة الرمادية → AI للحسم عند الحاجة فقط + if 0.60 <= ratio < threshold and event_fp and stored_event_fp and stored_event_fp == event_fp: + try: + if _ai_decide_gray_zone(normalized, sample): + return True, "ai_gray_zone", ratio + except Exception: + pass + return False, "event_details_differ" if details_differ else "none", best + +def check_section_claim(scope_id, event_fp): + """حجز ذري على مستوى القسم: أول وصول يفوز، والباقي مرفوض Duplicate (TOCTOU protected).""" + if scope_id is None or event_fp is None: + return True + try: + if hasattr(db, "claim_section_event"): + return bool(db.claim_section_event(scope_id, event_fp)) + except Exception: + pass + return True + + +def is_smart_duplicate(text, threshold=0.75): + """Legacy similarity-only helper retained for media/caption compatibility.""" + fp, normalized = make_similarity_fp(text) + if not fp: + return False, 0.0 + try: + recent = db.get_recent_fingerprints() if hasattr(db, "get_recent_fingerprints") else [] + except Exception: + recent = [] + best = 0.0 + for item in recent[-300:]: + sample = item.get("sample", "") if isinstance(item, dict) else "" + if not sample: + continue + ratio = difflib.SequenceMatcher(None, normalized, sample).ratio() + best = max(best, ratio) + if ratio >= threshold: + return True, ratio + return False, best + + +def remember_published_text(text, source_id=None, message_id=None, scope_id=None, section_label=None): + fp, normalized = make_text_fp(text) + if fp and hasattr(db, "add_recent_fingerprint"): + try: + db.add_recent_fingerprint( + fp, + normalized, + source_id=source_id, + message_id=message_id, + event_fp=make_event_fp(text), + url_fp=make_url_fp(text), + scope_id=scope_id, + section_label=section_label, + ) + except Exception: + pass + + +def content_types_status_line(source_id): + labels = {"text": "نصوص", "photo": "صور", "video": "فيديو", "album": "ألبومات", "voice": "بصمات", "audio": "صوتيات", "document": "ملفات"} + try: + types = db.get_source_content_types(source_id) if hasattr(db, "get_source_content_types") else {} + except Exception: + types = {} + if not types: + types = {"text": True, "photo": True, "video": True, "album": True} + return " | ".join(("✅ " if types.get(k, True) else "❌ ") + v for k, v in labels.items()) + + + +async def resolve_chat_info(raw, prefer_user=True): + raw = normalize_chat_input(raw) + value = int(raw) if re.fullmatch(r"-?\d+", raw) else raw + clients = [user_client, bot_client] if prefer_user else [bot_client, user_client] + last_error = None + for c in [x for x in clients if x]: + try: + return await c.get_chat(value) + except Exception as e: + last_error = e + raise last_error or ValueError("تعذر جلب معلومات القناة") + + +def chat_title(chat, fallback=""): + return getattr(chat, "title", None) or getattr(chat, "first_name", None) or getattr(chat, "username", None) or str(fallback) + + +def chat_username(chat): + return getattr(chat, "username", None) or "" + + +def chat_link_from_username(username): + return f"https://t.me/{username}" if username else "" + + +def chat_type_name(chat): + return str(getattr(chat, "type", "")).replace("ChatType.", "") + + +def chat_meta(chat, fallback=""): + username = chat_username(chat) + title = chat_title(chat, fallback) + return { + "name": title, + "title": title, + "username": username, + "link": chat_link_from_username(username), + "chat_type": chat_type_name(chat), + } + + +def entity_name(record_or_id, is_source=False): + if isinstance(record_or_id, dict): + return record_or_id.get("title") or record_or_id.get("name") or record_or_id.get("username") or str(record_or_id.get("id", "")) + if is_source and hasattr(db, "get_source_meta"): + return entity_name(db.get_source_meta(record_or_id)) + return str(record_or_id) + + +def entity_details_line(item, is_source=False): + if is_source: + meta = db.get_source_meta(item) if not isinstance(item, dict) else item + item_id = meta.get("id", item) + else: + meta = item + item_id = item.get("id") + name = entity_name(meta) + username = meta.get("username") or "" + username_txt = f"@{username}" if username else "لا يوجد يوزر" + return f"• {name}\n {username_txt}\n ID: `{item_id}`" + + +async def show_public_sources_menu_from_message(message): + srcs = db.get_public_sources() + meta_list = db.get_all_public_sources_with_meta() if hasattr(db, "get_all_public_sources_with_meta") else [{"id": s, "name": str(s)} for s in srcs] + text = f"**المصادر العامة ({len(srcs)}):**\n➕ إضافة مصدر/مصادر: يضيف قنوات عامة جديدة يراقبها البوت (رابط/يوزر/ID).\n🗑 حذف مصدر عام: يحذف مصدراً عاماً من المراقبة." + text += "\n\n".join(entity_details_line(m, is_source=True) for m in meta_list) if srcs else "لا توجد." + buttons = [ + [InlineKeyboardButton("➕ إضافة مصدر/مصادر", callback_data="add_public_src")], + [InlineKeyboardButton("🗑 حذف مصدر عام", callback_data="del_public_src")], + nav_row("main_menu"), + ] + await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons)) + + +async def show_blocked_words_menu_from_message(message): + words = db.get_blocked_words() + text = "**الكلمات المحظورة:**\n" + (", ".join(words) if words else "لا توجد.") + "\n➕ إضافة كلمة: يمنع نشر أي منشور يحتوي هذه الكلمة.\n🗑 حذف كلمة: يزيل كلمة من القائمة المحظورة." + buttons = [ + [InlineKeyboardButton("➕ إضافة كلمة", callback_data="add_blocked_word")], + [InlineKeyboardButton("🗑 حذف كلمة", callback_data="del_blocked_word")], + nav_row("main_menu"), + ] + await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons)) + + +async def show_special_sources_menu_from_message(message, ch_id): + ch = db.get_channel(ch_id) + if not ch: + await message.reply("❌ القناة غير موجودة.") + return + sources = ch.get("special_sources", []) + text = "**المصادر المخصصة:**\n➕ إضافة: يضيف مصدراً خاصاً لهذه القناة فقط.\n🗑 حذف: يزيل مصدراً خاصاً." + text += "\n".join(f"• {entity_name(s, is_source=True)}\n ID: `{s}`" for s in sources) if sources else "لا توجد." + buttons = [ + [InlineKeyboardButton("➕ إضافة", callback_data=f"addspecsrc_{ch_id}")], + [InlineKeyboardButton("🗑 حذف", callback_data=f"delspecsrc_{ch_id}")], + nav_row(f"ch_{ch_id}"), + ] + await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons)) + + +def format_bulk_report(title, results): + ok = [r for r in results if r[0] == "ok"] + exists = [r for r in results if r[0] == "exists"] + failed = [r for r in results if r[0] == "fail"] + lines = [title, "", f"✅ تمت الإضافة: {len(ok)}", f"⚠️ موجود مسبقاً: {len(exists)}", f"❌ فشل: {len(failed)}"] + if ok: + lines.append("\n**المضافة:**") + lines.extend([f"• {name}" for _, name, _ in ok[:30]]) + if exists: + lines.append("\n**الموجودة مسبقاً:**") + lines.extend([f"• {name}" for _, name, _ in exists[:20]]) + if failed: + lines.append("\n**الفاشلة:**") + lines.extend([f"• {raw}: {err}" for _, raw, err in failed[:20]]) + return "\n".join(lines) + +main_keyboard = InlineKeyboardMarkup([ + [ + InlineKeyboardButton("📢 إدارة قنوات النشر", callback_data="menu_channels"), + InlineKeyboardButton("🌐 إدارة المصادر العامة", callback_data="menu_public_src") + ], + [ + InlineKeyboardButton("💾 الاستيراد / التصدير", callback_data="backup_menu"), + InlineKeyboardButton("📊 الإحصائيات", callback_data="stats") + ], + [ + InlineKeyboardButton("🖥️ النظام", callback_data="system_menu"), + InlineKeyboardButton("🔐 الأسرار", callback_data="secrets_menu") + ], + [ + InlineKeyboardButton("📰 الأخبار", callback_data="section_menu|news"), + InlineKeyboardButton("⚽ الرياضة", callback_data="section_menu|sports"), + ], + [ + InlineKeyboardButton("🌐 Blogger Publisher", callback_data="section_menu|blogger") + ] +]) + + +async def section_menu(client, callback): + """Unified Phase-15 controls; legacy Blogger callbacks remain untouched.""" + try: + section = str(callback.data).split("|", 1)[1] + except Exception: + await callback.answer("قسم غير صالح.", show_alert=True) + return + runtime, control = _get_p29_runtime() + state = runtime.get_section_state(section) + buttons = [ + [ + InlineKeyboardButton("⚙️ الإعدادات", callback_data=f"{section}:settings"), + InlineKeyboardButton("📡 المصادر", callback_data=f"{section}:sources"), + ], + [ + InlineKeyboardButton("🚫 الكلمات المحظورة", callback_data=f"{section}:blocked"), + InlineKeyboardButton("♻️ منع التكرار", callback_data=f"{section}:duplicates"), + ], + [ + InlineKeyboardButton("🤖 الذكاء الاصطناعي", callback_data=f"{section}:ai"), + InlineKeyboardButton("📋 الطابور", callback_data=f"{section}:queue"), + ], + [ + InlineKeyboardButton("📊 الحالة", callback_data=f"{section}:status"), + InlineKeyboardButton("🛠️ الإصلاح التلقائي", callback_data=f"{section}:repair"), + ], + [ + InlineKeyboardButton("▶️ تشغيل", callback_data=f"{section}:enable"), + InlineKeyboardButton("⛔ إيقاف", callback_data=f"{section}:disable"), + ], + [InlineKeyboardButton("⬅️ رجوع", callback_data="main_menu")], + ] + text = ( + f"**{section.upper()} — Phase 15**\n\n" + f"الحالة: {'🟢 تعمل' if state['enabled'] else '🔴 متوقفة'}\n" + f"AI: {'🟢' if state['ai_enabled'] else '🔴'}\n" + f"منع التكرار: {'🟢' if state['duplicate_protection'] else '🔴'}\n" + f"Auto-Repair: {'🟢' if state['auto_repair_enabled'] else '🔴'}" + ) + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + +async def section_control_callback(client, callback): + runtime, control = _get_p29_runtime() + result = control.handle(str(callback.data), getattr(callback.from_user, "id", None)) + if not result.get("ok"): + await callback.answer(str(result.get("reason", "فشل")), show_alert=True) + return + await callback.answer("تم.") + section = str(callback.data).split(":", 1)[0] + callback.data = f"section_menu|{section}" + await section_menu(client, callback) + +async def backup_menu(client, callback): + text = "**💾 الاستيراد / التصدير**\n\n📥 تصدير البيانات: ينزّل ملفاً يحتوي كل إعدادات البوت.\n📤 استيراد البيانات: يرفع ملف إعدادات سابقاً لاستعادة البوت." + buttons = [ + [ + InlineKeyboardButton("📥 تصدير البيانات", callback_data="export_data"), + InlineKeyboardButton("📤 استيراد البيانات", callback_data="import_data") + ], + nav_row("main_menu") + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def start(client, message): + user_id = message.from_user.id + user_states.pop(user_id, None) + + logger.info(f"📥 /start من ID: {user_id}") + + if not is_admin(user_id): + await message.reply(f"❌ غير مصرح. معرفك: `{user_id}`") + return + + await message.reply("أهلاً بك في لوحة تحكم البوت:", reply_markup=main_keyboard) + +async def export_callback(client, callback): + try: + data_str = db.export_data() + + with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as tmp: + tmp.write(data_str) + tmp_path = tmp.name + + await callback.message.reply_document(document=tmp_path, file_name=f"backup_{int(time.time())}.json") + os.unlink(tmp_path) + await callback.answer("تم إرسال ملف النسخة الاحتياطية.") + except Exception as e: + logger.error(f"فشل التصدير: {e}") + await callback.answer("فشل التصدير.", show_alert=True) + +async def import_callback(client, callback): + user_states[callback.from_user.id] = {"state": "waiting_import"} + await safe_edit(callback, "أرسل ملف JSON الذي تريد استيراده:") + +async def handle_import(client, message): + if not is_admin(message.from_user.id): + return + + uid = message.from_user.id + + if uid not in user_states or user_states[uid].get("state") != "waiting_import": + return + + if not message.document: + await message.reply("❌ أرفق ملف JSON صحيح.") + return + + try: + file_path = await message.download() + with open(file_path, "r", encoding="utf-8") as f: + data = f.read() + + result = db.import_data(data) + if isinstance(result, dict): + report = ( + "✅ تم استيراد الإعدادات بنجاح.\n\n" + f"• قنوات النشر: {result.get('channels', 0)}\n" + f"• المصادر العامة: {result.get('public_sources', 0)}\n" + f"• الكلمات المحظورة: {result.get('blocked_words', 0)}\n" + f"• قائمة الحذف العامة: {result.get('global_remove_terms', 0)}\n" + f"• إعدادات المصادر: {result.get('source_meta', 0)}\n" + f"• آخر رسائل المصادر: {result.get('last_source_messages', 0)}" + ) + else: + report = "✅ تم استيراد الإعدادات بنجاح." + await message.reply(report + "\n\n🔄 جارٍ تهيئة القنوات والمصادر بعد الاستيراد...", reply_markup=main_keyboard) + try: + await warm_all_peers_after_import() + await message.reply("✅ تمت تهيئة القنوات والمصادر بعد الاستيراد. المفروض النشر يشتغل بدون إعادة إضافة يدوية.") + except Exception as e: + logger.error(f"فشل تهيئة الاستيراد: {e}") + await message.reply(f"⚠️ تم الاستيراد، لكن فشلت التهيئة التلقائية: {e}") + except Exception as e: + await message.reply(f"❌ فشل الاستيراد: {e}") + finally: + user_states.pop(uid, None) + + +CONTENT_TYPE_LABELS = { + "text": "النصوص", + "photo": "الصور", + "video": "الفيديوهات", + "album": "الألبومات", +} + + +async def purge_published_prompt(client, callback): + try: + _, ch_id, kind = callback.data.split("|", 2) + except Exception: + await callback.answer("طلب غير صالح.", show_alert=True) + return + label = CONTENT_TYPE_LABELS.get(kind, kind) + ids = db.get_published_message_ids(ch_id, kind) if hasattr(db, "get_published_message_ids") else [] + ch = db.get_channel(ch_id) + text = ( + f"⚠️ **تأكيد حذف {label} من قناة النشر**\n\n" + f"{channel_display_name(ch_id)}\n\n" + f"عدد الرسائل المسجلة للحذف: {len(ids)}\n\n" + "سيحذف البوت فقط الرسائل التي يعرف IDs مالتهن والمنشورة بعد إضافة هذا النظام." + ) + buttons = [ + [InlineKeyboardButton(f"✅ نعم، احذف {label}", callback_data=f"confirmpurge|{ch_id}|{kind}")], + [InlineKeyboardButton("❌ إلغاء", callback_data=f"purgepage_{ch_id}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def _try_delete_with_bots(ch_id, mids): + """محاولة الحذف باستخدام البوت الأساسي ثم البوتات المخصصة للقناة.""" + deleted_ids = [] + failed_ids = [] + bots_to_try = [bot_client] + cfg = db.get_channel_config(ch_id) if hasattr(db, "get_channel_config") else {} + for bid in cfg.get("assigned_bots", []): + token = db.bot_manager.get_token(bid) if hasattr(db, "bot_manager") else (db.get_publishing_bot(bid) or {}).get("token", "") + bdata = db.get_publishing_bot(bid) if hasattr(db, "get_publishing_bot") else None + if token: + bots_to_try.append({"id": bid, "token": token, **(bdata or {})}) + remaining = list(mids) + for bot in bots_to_try: + if not remaining: + break + if isinstance(bot, dict): + token = db.bot_manager.get_token(bot.get("id", "")) if hasattr(db, "bot_manager") else bot.get("token", "") + try: + temp = Client(":memory:", api_id=config.API_ID, api_hash=config.API_HASH, bot_token=token, in_memory=True) + await temp.start() + for mid in remaining: + try: + await temp.delete_messages(int(ch_id), int(mid)) + deleted_ids.append(mid) + except Exception: + failed_ids.append(mid) + await asyncio.sleep(0.2) + await temp.stop() + except Exception: + failed_ids.extend(remaining) + remaining = [m for m in remaining if m not in deleted_ids] + else: + for i in range(0, len(remaining), 100): + chunk = remaining[i:i+100] + try: + await bot.delete_messages(int(ch_id), chunk) + deleted_ids.extend(chunk) + except Exception: + for mid in chunk: + try: + await bot.delete_messages(int(ch_id), int(mid)) + deleted_ids.append(mid) + except Exception as e: + failed_ids.append(mid) + await asyncio.sleep(0.3) + remaining = [m for m in remaining if m not in deleted_ids] + return deleted_ids, failed_ids + + +async def confirm_purge_published(client, callback): + try: + _, ch_id, kind = callback.data.split("|", 2) + except Exception: + await callback.answer("طلب غير صالح.", show_alert=True) + return + ids = db.get_published_message_ids(ch_id, kind) if hasattr(db, "get_published_message_ids") else [] + if not ids: + await callback.answer("لا توجد رسائل محفوظة من هذا النوع.", show_alert=True) + await post_settings_menu(client, callback) + return + + # تحقق فوري من صلاحية الحذف قبل التنفيذ + if not await _verify_channel_before_publish(ch_id): + await safe_edit(callback, f"⛔ **فشل التحقق من القناة**\n\nالبوت الرئيسي لا يمكنه الوصول إلى القناة `{ch_id}`.\nتأكد من أن البوت مشرف في القناة.", InlineKeyboardMarkup([nav_row(f"ch_{ch_id}")])) + return + + deleted_ids, failed_ids = await _try_delete_with_bots(ch_id, ids) + + if hasattr(db, "clear_published_message_ids"): + db.clear_published_message_ids(ch_id, kind, None if not failed_ids else deleted_ids) + + label = CONTENT_TYPE_LABELS.get(kind, kind) + deleted = len(deleted_ids) + failed = len(failed_ids) + await notify_admins(f"تم حذف {label} من {channel_display_name(ch_id)}\n✅ المحذوف: {deleted}\n❌ فشل: {failed}") + await safe_edit(callback, f"🧹 **نتيجة حذف {label}:**\n\n✅ تم حذف: {deleted}\n❌ فشل: {failed}\n\n💡 البوت لا يمكنه حذف رسائل أقدم من 48 ساعة (حد Telegram).", InlineKeyboardMarkup([ + [InlineKeyboardButton("🔙 رجوع لحذف المنشورات", callback_data=f"purgepage_{ch_id}"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")] + ])) + + +def channel_buttons(ch_id): + buttons = [ + InlineKeyboardButton("📰 إعدادات المنشورات", callback_data=f"postset_{ch_id}"), + InlineKeyboardButton("📡 المصادر", callback_data=f"srcset_{ch_id}"), + InlineKeyboardButton("⚙️ الإعدادات العامة", callback_data=f"genset_{ch_id}"), + ] + rows = grid_buttons(buttons, 2) + rows.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_channels"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")]) + return InlineKeyboardMarkup(rows) + + +# ============================================================ +# 📝 إعدادات المنشورات +# ============================================================ + +async def post_settings_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + bold = ch.get("bold_publish", True) + quote_types = get_channel_quote_types_safe(ch_id) + cfg = db.get_channel_config(ch_id) if hasattr(db, "get_channel_config") else {} + quote_count = sum(1 for v in quote_types.values() if v) + int(bool(cfg.get("title_quote"))) + int(bool(cfg.get("signature_quote"))) + disable_preview = db.get_channel_disable_preview(ch_id) if hasattr(db, "get_channel_disable_preview") else False + ignore_short = is_ignore_short_posts_enabled_for_channel(ch_id) + buttons = [ + InlineKeyboardButton(f"{'✅' if bold else '❌'} الخط السميك", callback_data=f"togglebold_{ch_id}"), + InlineKeyboardButton( + f"📝 النصوص القصيرة: {'✅ تشغيل' if ignore_short else '❌ إيقاف'}", + callback_data=f"toggle_short_posts|{ch_id}", + ), + InlineKeyboardButton(f"✍️ التوقيع", callback_data=f"tails_{ch_id}"), + InlineKeyboardButton(f"💬 الاقتباس ({quote_count}/6)", callback_data=f"quotemenu_{ch_id}"), + InlineKeyboardButton(f"#️⃣ الهاشتاكات", callback_data=f"hashtags_{ch_id}"), + InlineKeyboardButton(f"⏱ سرعة النشر", callback_data=f"speedmenu_{ch_id}"), + InlineKeyboardButton(f"🗑 حذف المنشورات", callback_data=f"purgepage_{ch_id}"), + InlineKeyboardButton(f"🚫 الكلمات المحظورة", callback_data=f"chwords|{ch_id}"), + InlineKeyboardButton(f"✂️ الكلمات المحذوفة", callback_data=f"chdelterms|{ch_id}"), + InlineKeyboardButton(f"🔗 إدارة الروابط", callback_data=f"chlinks|{ch_id}"), + InlineKeyboardButton(f"{'✅' if not disable_preview else '❌'} معاينة الروابط", callback_data=f"ch_preview_{ch_id}"), + InlineKeyboardButton("🧪 اختبار القناة", callback_data=f"testset_{ch_id}"), + ] + rows = grid_buttons(buttons, 2) + rows.append(nav_row(f"ch_{ch_id}")) + await safe_edit(callback, f"📰 **إعدادات المنشورات**\n{entity_name(ch)}\n📝 النصوص القصيرة: " + ("✅ الحظر مفعّل" if ignore_short else "❌ متوقف") + "\n💬 الاقتباسات: {quote_count}/6 أنواع مفعّلة\n" + "🔗 معاينة الروابط: " + ("✅ مفعّلة" if not disable_preview else "❌ معطّلة") + "\n" + "📌 الخط السميك: " + ("✅ مفعّل" if bold else "❌ معطّل") + "\n", InlineKeyboardMarkup(rows)) + + +async def purge_published_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + buttons = [ + InlineKeyboardButton("🧹 حذف النصوص", callback_data=f"purgepub|{ch_id}|text"), + InlineKeyboardButton("🧹 حذف الصور", callback_data=f"purgepub|{ch_id}|photo"), + InlineKeyboardButton("🧹 حذف الفيديوهات", callback_data=f"purgepub|{ch_id}|video"), + InlineKeyboardButton("🧹 حذف الألبومات", callback_data=f"purgepub|{ch_id}|album"), + ] + rows = grid_buttons(buttons, 2) + rows.append(nav_row(f"postset_{ch_id}")) + await safe_edit(callback, f"🗑 **حذف المنشورات**\n{channel_display_name(ch_id)}\n\nاختر نوع المنشورات المسجلة لحذفها من القناة:\n\n🧹 حذف النصوص/الصور/الفيديوهات/الألبومات: يحذف الرسائل المسجلة من هذا النوع في هذه القناة فقط.", InlineKeyboardMarkup(rows)) + + +# ============================================================ +# 📚 إعدادات المصادر +# ============================================================ + +async def source_settings_channel_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + sources = ch.get("special_sources", []) + buttons = [ + InlineKeyboardButton(f"📢 عرض المصادر ({len(sources)})", callback_data=f"specsrc_{ch_id}"), + InlineKeyboardButton("➕ إضافة مصدر", callback_data=f"addspecsrc_{ch_id}"), + InlineKeyboardButton("➖ حذف مصدر", callback_data=f"delspecsrc_{ch_id}"), + InlineKeyboardButton("📋 جميع المصادر", callback_data="menu_public_src"), + ] + rows = grid_buttons(buttons, 2) + rows.append(nav_row(f"ch_{ch_id}")) + text = ( + f"📚 **إعدادات المصادر**\n{entity_name(ch)}\n\n" + f"عدد المصادر المخصصة: {len(sources)}\n\n📢 عرض المصادر: يعرض قائمة المصادر المخصصة.\n➕ إضافة/➖ حذف: إدارة المصادر المخصصة." + ) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +# ============================================================ +# 🔖 إعدادات التوقيع +# ============================================================ + +async def tail_settings_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + tail_enabled = db.get_channel_tail_enabled(ch_id) if hasattr(db, "get_channel_tail_enabled") else True + tail_min = db.get_channel_tail_min_words(ch_id) if hasattr(db, "get_channel_tail_min_words") else 20 + tail_pos = db.get_channel_tail_position(ch_id) if hasattr(db, "get_channel_tail_position") else "bottom" + current_tail = ch.get("tail", "") + min_active = tail_min >= 20 + pos_label = "⬆️ أعلى" if tail_pos == "top" else "⬇️ أسفل" + text = ( + f"🔖 **إعدادات التوقيع**\n{entity_name(ch)}\n\n🔖 التوقيع نص يُضاف لنهاية (أو بداية) المنشورات في هذه القناة.\n" + f"{'✅' if tail_enabled else '❌'} التوقيع" + + (f":\n`{current_tail}`" if current_tail and tail_enabled else "") + + ("\n\n📊 شرط {0} كلمة: {1}".format(tail_min, "✅ مفعل" if min_active else "❌ متوقف")) + + f"\n📍 المكان: {pos_label}" + ) + buttons = [ + InlineKeyboardButton(f"{'✅' if tail_enabled else '❌'} تشغيل التوقيع", callback_data=f"tailtoggle_{ch_id}"), + InlineKeyboardButton(f"✏️ تعديل النص", callback_data=f"edittail_{ch_id}"), + InlineKeyboardButton(f"{'✅' if min_active else '❌'} شرط {tail_min} كلمة", callback_data=f"tailmintoggle_{ch_id}"), + InlineKeyboardButton(f"{'⬆️' if tail_pos=='top' else '⬇️'} المكان: {pos_label}", callback_data=f"tailpos_{ch_id}"), + InlineKeyboardButton("🗑 حذف التوقيع", callback_data=f"deltail_{ch_id}"), + ] + rows = grid_buttons(buttons, 2) + rows.append(nav_row(f"postset_{ch_id}")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def tail_toggle_handler(client, callback): + ch_id = callback.data.split("_", 1)[1] + cur = db.get_channel_tail_enabled(ch_id) if hasattr(db, "get_channel_tail_enabled") else True + if hasattr(db, "set_channel_tail_enabled"): + db.set_channel_tail_enabled(ch_id, not cur) + await callback.answer("تم التحديث.") + callback.data = f"tails_{ch_id}" + await tail_settings_menu(client, callback) + + +async def tail_min_toggle_handler(client, callback): + ch_id = callback.data.split("_", 1)[1] + cur = db.get_channel_tail_min_words(ch_id) if hasattr(db, "get_channel_tail_min_words") else 20 + new_val = 0 if cur >= 20 else 20 + if hasattr(db, "set_channel_tail_min_words"): + db.set_channel_tail_min_words(ch_id, new_val) + await callback.answer(f"تم التحديث إلى {'20' if new_val else 'بدون'} كلمة.") + callback.data = f"tails_{ch_id}" + await tail_settings_menu(client, callback) + + +async def tail_position_toggle_handler(client, callback): + ch_id = callback.data.split("_", 1)[1] + cur = db.get_channel_tail_position(ch_id) if hasattr(db, "get_channel_tail_position") else "bottom" + new_pos = "top" if cur == "bottom" else "bottom" + if hasattr(db, "set_channel_tail_position"): + db.set_channel_tail_position(ch_id, new_pos) + await callback.answer(f"تم تغيير المكان إلى {'أعلى' if new_pos == 'top' else 'أسفل'}.") + callback.data = f"tails_{ch_id}" + await tail_settings_menu(client, callback) + + +# ============================================================ +# 🧪 إعدادات الاختبار +# ============================================================ + +async def test_settings_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + buttons = [ + InlineKeyboardButton("🧪 اختبار نشر", callback_data=f"testpub_{ch_id}"), + InlineKeyboardButton("👁 معاينة المنشور", callback_data=f"preview_{ch_id}"), + ] + rows = grid_buttons(buttons, 2) + rows.append(nav_row(f"postset_{ch_id}")) + text = f"🧪 **إعدادات الاختبار**\n{entity_name(ch)}\n\n🧪 اختبار نشر: يرسل رسالة اختبار حقيقية للقناة.\n👁 معاينة المنشور: يعرض كيف سيبدو المنشور مع الإعدادات الحالية." + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def preview_post(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + await callback.answer("جاري تحضير المعاينة...") + try: + sources = ch.get("special_sources", []) + if not sources: + srcs = db.get_public_sources() + if srcs: + sources = [srcs[0].get("id") if isinstance(srcs[0], dict) else srcs[0]] + if not sources: + await safe_edit(callback, "❌ لا توجد مصادر لهذه القناة.\nأضف مصدراً أولاً.", InlineKeyboardMarkup([nav_row(f"testset_{ch_id}")])) + return + preview_text = f"""📄 معاينة المنشور لقناة {entity_name(ch)} + +━━━━━━━━━━━━━━━━ +نص تجريبي لتطبيق الإعدادات على المنشور قبل النشر. + +يتم تطبيق جميع إعدادات القناة الحالية على هذا النص. +━━━━━━━━━━━━━━━━""" + + bold = ch.get("bold_publish", True) + tail = ch.get("tail", "") + tail_enabled = db.get_channel_tail_enabled(ch_id) if hasattr(db, "get_channel_tail_enabled") else True + tail_min = db.get_channel_tail_min_words(ch_id) if hasattr(db, "get_channel_tail_min_words") else 20 + tail_pos = db.get_channel_tail_position(ch_id) if hasattr(db, "get_channel_tail_position") else "bottom" + tags = db.get_channel_hashtags(ch_id) if hasattr(db, "get_channel_hashtags") else [] + delay = ch.get("publish_delay") + + word_count = len(preview_text.split()) + tail_applied = tail_enabled and bool(tail) and (tail_min == 0 or word_count >= tail_min) + + report_lines = ["📄 **تقرير المعالجة**\n"] + report_lines.append(f"{'✅' if bold else '❌'} تم {'تطبيق' if bold else 'إلغاء'} الخط السميك") + if tail_applied: + report_lines.append(f"✅ تم إضافة التوقيع") + report_lines.append(f"📍 مكان التوقيع:\n{'⬆️ أعلى' if tail_pos == 'top' else '⬇️ أسفل'} المنشور") + else: + if not tail_enabled: + report_lines.append(f"❌ التوقيع متوقف") + elif not tail: + report_lines.append(f"❌ لا يوجد نص توقيع") + else: + report_lines.append(f"❌ تم تجاهل التوقيع (أقل من {tail_min} كلمة)") + report_lines.append(f"📊 عدد الكلمات: {word_count}") + report_lines.append(f"🏷 عدد الهاشتاكات: {len(tags)}") + if delay: + report_lines.append(f"⏱ تأخير النشر: {delay} ثانية") + else: + report_lines.append(f"⏱ سرعة النشر: افتراضي") + + text = "\n".join(report_lines) + buttons = [ + nav_row(f"testset_{ch_id}"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + except Exception as e: + logger.error(f"خطأ في المعاينة: {e}") + await safe_edit(callback, f"❌ فشلت المعاينة:\n{e}", InlineKeyboardMarkup([nav_row(f"testset_{ch_id}")])) + + +async def toggle_channel_bold(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + current = bool(ch.get("bold_publish", True)) + if hasattr(db, "set_channel_bold_publish"): + db.set_channel_bold_publish(ch_id, not current) + else: + db.update_channel(ch_id, "bold_publish", not current) + await callback.answer("تم تحديث خيار الخط السميك.") + callback.data = f"postset_{ch_id}" + await post_settings_menu(client, callback) + +async def menu_channels(client, callback): + channels = db.get_all_channels() + + if not channels: + text = "لا توجد قنوات منشورة بعد. اضغط ➕ لإضافتها." + rows = [ + [InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")], + nav_row("main_menu") + ] + else: + text = f"**قنوات النشر ({len(channels)}):**\n⚙️ اسم القناة: يفتح إعدادات القناة.\n➕ إضافة قناة/قنوات: يسجل قنوات نشر جديدة (رابط/يوزر/ID)." + btns = [] + for ch in channels: + paused = " ⏸️" if ch.get('paused') else "" + name = entity_name(ch) + username = ch.get("username") or "" + username_txt = f"@{username}" if username else "لا يوجد يوزر" + text += f"\n✅ {name}{paused}\n {username_txt}\n ID: `{ch['id']}`\n" + btns.append(InlineKeyboardButton(f"⚙️ {name}", callback_data=f"ch_{ch['id']}")) + rows = grid_buttons(btns, 2 if len(btns) <= 8 else 3) + rows.append([InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")]) + rows.append(nav_row("main_menu")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def show_channels_menu_from_message(message): + channels = db.get_all_channels() + if not channels: + text = "لا توجد قنوات منشورة بعد. اضغط ➕ لإضافتها." + rows = [ + [InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")], + nav_row("main_menu") + ] + else: + text = f"**قنوات النشر ({len(channels)}):**\n⚙️ اسم القناة: يفتح إعدادات القناة.\n➕ إضافة قناة/قنوات: يسجل قنوات نشر جديدة (رابط/يوزر/ID)." + btns = [] + for ch in channels: + paused = " ⏸️" if ch.get('paused') else "" + name = entity_name(ch) + username = ch.get("username") or "" + username_txt = f"@{username}" if username else "لا يوجد يوزر" + text += f"\n✅ {name}{paused}\n {username_txt}\n ID: `{ch['id']}`\n" + btns.append(InlineKeyboardButton(f"⚙️ {name}", callback_data=f"ch_{ch['id']}")) + rows = grid_buttons(btns, 2 if len(btns) <= 8 else 3) + rows.append([InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")]) + rows.append(nav_row("main_menu")) + await message.reply(text, reply_markup=InlineKeyboardMarkup(rows)) + +async def channel_settings(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + name = entity_name(ch) + username = ch.get("username") or "" + username_txt = f"@{username}" if username else "لا يوجد يوزر" + if hasattr(db, "mapper"): + assigned_bots = db.mapper.get_bots_for_channel(ch_id) + else: + cfg = db.get_channel_config(ch_id) if hasattr(db, "get_channel_config") else {} + assigned_bots = cfg.get("assigned_bots", []) + bot_count = len(assigned_bots) + verifications = verifier.get_cached_verifications_for_channel(ch_id) + ok_count = sum(1 for v in verifications.values() if v.get("verified") and v.get("can_post")) + ch_sources = ch.get("special_sources", []) + src_count = len(ch_sources) + if ch.get("bot_admin") is None: + bot_line = "🤖 ❓ لم يُفحص بعد" + else: + bot_line = "🤖 ✅ البوت مشرف" if ch.get("bot_admin") else "🤖 ❌ البوت ليس مشرفاً" + text = ( + f"📢 **{name}**\n\n" + f"👤 {username_txt}\n" + f"🆔 `{ch_id}`\n" + f"{'⏸️ موقوفة' if ch.get('paused') else '✅ شغالة'}" + f" | 📄 {ch.get('posts_count', 0)}" + f" | ⚠️ {ch.get('fail_count', 0)}\n" + f"{bot_line}\n" + f"🤖 {bot_count} بوت ({ok_count} جاهز)" + f" | 📚 {src_count} مصدر" + ) + await safe_edit(callback, text, channel_buttons(ch_id)) + +async def add_channel_prompt(client, callback): + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_channel_id"} + await safe_edit(callback, "أرسل قناة واحدة أو عدة قنوات نشر.\nكل رابط/يوزر/ID بسطر مستقل:") + +async def toggle_pause(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + + if not ch: + await callback.answer("غير موجودة.") + return + + db.update_channel(ch_id, "paused", not ch.get("paused")) + await callback.answer("تم التحديث.") + await channel_settings(client, callback) + +async def delete_channel_prompt(client, callback): + channels = db.get_all_channels() + if not channels: + await callback.answer("لا توجد قنوات.") + return + ch_id = callback.data.split("_", 1)[1] + buttons = [] + for ch in channels: + name = entity_name(ch) + buttons.append([InlineKeyboardButton(f"🗑 حذف {name}", callback_data=f"confirm_del_{ch['id']}")]) + buttons.append(nav_row(f"genset_{ch_id}")) + await safe_edit(callback, "اختر القناة التي تريد حذفها:", InlineKeyboardMarkup(buttons)) + +async def confirm_delete_channel(client, callback): + ch_id = callback.data.split("_", 2)[2] + db.delete_channel(ch_id) + await callback.answer("تم الحذف.") + await menu_channels(client, callback) + +async def tail_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + + if not ch: + await callback.answer("غير موجودة.") + return + + current = ch.get("tail", "") + text = (f"التوقيع الحالي:\n`{current}`" if current else "لا يوجد توقيع.") + "\n\n✏️ تعديل/إضافة: يحدّث نص التوقيع.\n🗑 حذف التوقيع: يمسح التوقيع الحالي." + + buttons = [ + [InlineKeyboardButton("✏️ تعديل/إضافة", callback_data=f"edittail_{ch_id}")], + [InlineKeyboardButton("🗑 حذف التوقيع", callback_data=f"deltail_{ch_id}")], + nav_row(f"tails_{ch_id}") + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + +async def edit_tail_prompt(client, callback): + ch_id = callback.data.split("_", 1)[1] + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_tail", "ch_id": ch_id} + await safe_edit(callback, "أرسل نص التوقيع الجديد:", InlineKeyboardMarkup([nav_row(f"tails_{ch_id}")])) + +async def delete_tail(client, callback): + ch_id = callback.data.split("_", 1)[1] + db.update_channel(ch_id, "tail", "") + await callback.answer("تم حذف التوقيع.") + await tail_menu(client, callback) + +async def menu_public_sources(client, callback): + srcs = db.get_public_sources() + meta_list = db.get_all_public_sources_with_meta() if hasattr(db, "get_all_public_sources_with_meta") else [{"id": s, "name": str(s)} for s in srcs] + text = f"**المصادر العامة ({len(srcs)}):**\n➕ إضافة مصدر/مصادر: يضيف قنوات عامة جديدة يراقبها البوت (رابط/يوزر/ID).\n🗑 حذف مصدر عام: يحذف مصدراً عاماً من المراقبة." + text += "\n\n".join(entity_details_line(m, is_source=True) for m in meta_list) if srcs else "لا توجد." + btns = [] + for meta in meta_list: + sid = meta.get("id") + paused = " ⏸️" if is_source_paused(sid) else "" + btns.append(InlineKeyboardButton(f"⚙️ {entity_name(meta)}{paused}", callback_data=f"srcset|{sid}|menu_public_src")) + rows = grid_buttons(btns, 2 if len(btns) <= 8 else 3) + rows.append([InlineKeyboardButton("➕ إضافة مصدر/مصادر", callback_data="add_public_src"), InlineKeyboardButton("🗑 حذف مصدر عام", callback_data="del_public_src")]) + rows.append(nav_row("main_menu")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def add_public_src_prompt(client, callback): + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_public_source"} + await safe_edit(callback, "أرسل مصدر واحد أو عدة مصادر عامة.\nكل رابط/يوزر/ID بسطر مستقل:", InlineKeyboardMarkup([nav_row("menu_public_src")])) + +async def del_public_src_prompt(client, callback): + srcs = db.get_public_sources() + if not srcs: + await callback.answer("لا توجد مصادر.") + return + buttons = [] + for idx, src in enumerate(srcs): + name = entity_name(src, is_source=True) + buttons.append([InlineKeyboardButton(f"🗑 حذف {name}", callback_data=f"del_pub_idx_{idx}")]) + buttons.append(nav_row("menu_public_src")) + await safe_edit(callback, "اختر المصدر للحذف:", InlineKeyboardMarkup(buttons)) + +async def confirm_del_public_src(client, callback): + idx = int(callback.data.split("_")[-1]) + srcs = db.get_public_sources() + + if idx < 0 or idx >= len(srcs): + await callback.answer("المصدر غير موجود.") + return + + db.remove_public_source(srcs[idx]) + await callback.answer("تم الحذف.") + await menu_public_sources(client, callback) + +async def menu_blocked_words(client, callback): + words = db.get_blocked_words() + + text = "**الكلمات المحظورة:**\n" + text += (", ".join(words) if words else "لا توجد.") + "\n➕ إضافة كلمة: يمنع نشر أي منشور يحتويها.\n🗑 حذف كلمة: يزيل كلمة من القائمة." + + buttons = [ + [InlineKeyboardButton("➕ إضافة كلمة", callback_data="add_blocked_word")], + [InlineKeyboardButton("🗑 حذف كلمة", callback_data="del_blocked_word")], + nav_row("main_menu") + ] + + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + +async def add_blocked_word_prompt(client, callback): + await callback.answer() + logger.info(f"add_blocked_word_prompt: user {callback.from_user.id}") + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_blocked_word"} + await safe_edit(callback, "أرسل كلمة أو عدة كلمات محظورة.\nكل كلمة/عبارة بسطر مستقل:", InlineKeyboardMarkup([nav_row("menu_blocked")])) + +async def del_blocked_word_prompt(client, callback): + await callback.answer() + logger.info(f"del_blocked_word_prompt: user {callback.from_user.id}") + words = db.get_blocked_words() + + if not words: + await callback.answer("لا توجد كلمات محظورة.") + return + + buttons = [] + + for idx, word in enumerate(words): + buttons.append([InlineKeyboardButton(f"حذف {word}", callback_data=f"delword_idx_{idx}")]) + + buttons.append(nav_row("menu_blocked")) + await safe_edit(callback, "اختر الكلمة:", InlineKeyboardMarkup(buttons)) + +async def confirm_del_blocked_word(client, callback): + idx = int(callback.data.split("_")[-1]) + words = db.get_blocked_words() + + if idx < 0 or idx >= len(words): + await callback.answer("الكلمة غير موجودة.") + return + + db.remove_blocked_word(words[idx]) + await callback.answer("تم الحذف.") + await menu_blocked_words(client, callback) + + +# ============================================================ +# 🚫 الكلمات المحظورة — خاصة بكل قناة على حدة +# ============================================================ + +async def channel_blocked_words_menu(client, callback): + ch_id = callback.data.split("|", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + words = db.get_channel_blocked_words(ch_id) + text = f"🚫 **الكلمات المحظورة — {entity_name(ch)}**\n\n" + text += "أي منشور يحتوي إحدى هذي الكلمات لن يُنشر بهذه القناة فقط (باقي القنوات غير متأثرة).\n\n" + text += (", ".join(words) if words else "لا توجد كلمات محظورة لهذه القناة.") + "\n\n➕ إضافة كلمة / 🗑 حذف كلمة: إدارة الكلمات المحظورة لهذه القناة فقط." + buttons = [ + [InlineKeyboardButton("➕ إضافة كلمة", callback_data=f"chwordadd|{ch_id}")], + [InlineKeyboardButton("🗑 حذف كلمة", callback_data=f"chworddel|{ch_id}")], + nav_row(f"postset_{ch_id}"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def channel_add_blocked_word_prompt(client, callback): + await callback.answer() + logger.info(f"channel_add_blocked_word_prompt: user {callback.from_user.id}") + ch_id = callback.data.split("|", 1)[1] + if not db.get_channel(ch_id): + await callback.answer("القناة غير موجودة.") + return + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_channel_blocked_word", "ch_id": ch_id} + await safe_edit(callback, "أرسل كلمة أو عدة كلمات محظورة لهذه القناة فقط.\nكل كلمة/عبارة بسطر مستقل:", InlineKeyboardMarkup([nav_row(f"chwords|{ch_id}")])) + + +async def channel_del_blocked_word_prompt(client, callback): + ch_id = callback.data.split("|", 1)[1] + words = db.get_channel_blocked_words(ch_id) + if not words: + await callback.answer("لا توجد كلمات محظورة لهذه القناة.") + return + buttons = [] + for idx, word in enumerate(words): + buttons.append([InlineKeyboardButton(f"حذف {word}", callback_data=f"chworddelidx|{ch_id}|{idx}")]) + buttons.append(nav_row(f"chwords|{ch_id}")) + await safe_edit(callback, "اختر الكلمة:", InlineKeyboardMarkup(buttons)) + + +async def confirm_channel_del_blocked_word(client, callback): + try: + _, ch_id, idx_str = callback.data.split("|", 2) + except ValueError: + await callback.answer("طلب غير صالح.") + return + words = db.get_channel_blocked_words(ch_id) + try: + idx = int(idx_str) + except ValueError: + await callback.answer("خطأ في البيانات.") + return + if idx < 0 or idx >= len(words): + await callback.answer("الكلمة غير موجودة.") + return + db.remove_channel_blocked_word(ch_id, words[idx]) + await callback.answer("تم الحذف.") + callback.data = f"chwords|{ch_id}" + await channel_blocked_words_menu(client, callback) + + +# ============================================================ +# 🔗 إدارة الروابط — خاصة بكل قناة على حدة +# ============================================================ + +CHANNEL_LINK_FILTER_KEYS = { + "chlinktg|": "link_remove_tg", + "chlinktguser|": "link_remove_tg_user", + "chlinkweb|": "link_remove_web", +} + + +async def channel_links_menu(client, callback): + ch_id = callback.data.split("|", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + link_tg = bool(ch.get("link_remove_tg")) + link_tg_user = bool(ch.get("link_remove_tg_user")) + link_web = bool(ch.get("link_remove_web")) + text = ( + f"🔗 **إدارة الروابط — {entity_name(ch)}**\n\n" + "التحكم بروابط المنشورات المُرسلة لهذه القناة فقط (باقي القنوات غير متأثرة).\n\n" + f"{'✅' if link_tg else '❌'} حذف روابط تيليجرام (t.me)\n" + f"{'✅' if link_tg_user else '❌'} حذف يوزرات تيليجرام (@username)\n" + f"{'✅' if link_web else '❌'} حذف روابط المواقع (ما عدا تيليجرام)\n\nاضغط على الزر لتفعيل/إيقاف حذف نوع الروابط في منشورات هذه القناة فقط." + ) + buttons = [ + [InlineKeyboardButton(f"{'✅' if link_tg else '❌'} حذف روابط تيليجرام", callback_data=f"chlinktg|{ch_id}")], + [InlineKeyboardButton(f"{'✅' if link_tg_user else '❌'} حذف يوزرات @", callback_data=f"chlinktguser|{ch_id}")], + [InlineKeyboardButton(f"{'✅' if link_web else '❌'} حذف روابط المواقع", callback_data=f"chlinkweb|{ch_id}")], + nav_row(f"postset_{ch_id}"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def toggle_channel_link_filter(client, callback): + prefix, ch_id = callback.data.split("|", 1) + key = CHANNEL_LINK_FILTER_KEYS.get(prefix + "|") + if not key: + await callback.answer("أمر غير معروف.") + return + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + db.update_channel(ch_id, key, not bool(ch.get(key))) + await callback.answer("تم التحديث.") + callback.data = f"chlinks|{ch_id}" + await channel_links_menu(client, callback) + + +# ============================================================ +# 🤖 التحقق من البوت — فحص حقيقي لحالة البوت داخل القناة +# ============================================================ + +def format_bot_check_result(status_value, privileges=None, error=""): + """يبني نص نتيجة الفحص الحقيقي لحالة البوت داخل القناة.""" + if error: + return f"❌ تعذر الوصول إلى القناة.\nالسبب الحقيقي: {error}" + status_value = status_value or "" + if is_bot_admin_status(status_value): + perm_lines = "" + if privileges: + perm_lines = "\n".join( + f"• {label}: {'✅' if bool(getattr(privileges, key, True)) else '❌'}" + for label, key in ( + ("نشر الرسائل", "can_post_messages"), + ("تعديل الرسائل", "can_edit_messages"), + ("حذف الرسائل", "can_delete_messages"), + ) + ) + text = f"✅ البوت مشرف في القناة\nالحالة: `{status_value}`" + if perm_lines: + text += f"\nالصلاحيات:\n{perm_lines}" + return text + if status_value in ("member", "restricted"): + return f"❌ البوت ليس مشرفاً في القناة\nالحالة الفعلية: `{status_value}`" + if status_value in ("left",): + return f"❌ البوت غير موجود داخل القناة.\nالحالة الفعلية: `{status_value}`" + if status_value in ("banned", "kicked"): + return f"❌ البوت محظور داخل القناة.\nالحالة الفعلية: `{status_value}`" + return f"❌ البوت ليس مشرفاً في القناة\nالحالة الفعلية: `{status_value}`" + + +async def channel_bot_check(client, callback): + """فحص حقيقي (Real Check) عبر Telegram API بحالة البوت داخل القناة — بدون أي نتيجة محفوظة.""" + ch_id = callback.data.split("|", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + await callback.answer("جاري الفحص الحقيقي...") + bot_status = "unknown" + bot_admin = False + result_text = "" + try: + bot_member = await bot_client.get_chat_member(int(ch_id), (await bot_client.get_me()).id) + bot_status = member_status_value(getattr(bot_member, "status", None)) + bot_admin = is_bot_admin_status(bot_status) + result_text = format_bot_check_result(bot_status, getattr(bot_member, "privileges", None)) + except Exception as e: + result_text = format_bot_check_result("", error=str(e)[:200]) + db.update_channel(ch_id, "bot_admin", bot_admin) + db.update_channel(ch_id, "bot_status", bot_status) + text = ( + f"🤖 **التحقق من البوت — {entity_name(ch)}**\n" + f"🆔 `{ch_id}`\n\n" + f"{result_text}" + ) + buttons = [[InlineKeyboardButton("🔙 رجوع لإعدادات القناة", callback_data=f"ch_{ch_id}")]] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + +async def manage_special_sources(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + sources = ch.get("special_sources", []) + text = "**المصادر المخصصة:**\n➕ إضافة: يضيف مصدراً خاصاً لهذه القناة فقط.\n🗑 حذف: يزيل مصدراً خاصاً." + text += "\n".join(f"• {entity_name(s, is_source=True)}\n ID: `{s}`" for s in sources) if sources else "لا توجد." + btns = [] + for s in sources: + paused = " ⏸️" if is_source_paused(s) else "" + btns.append(InlineKeyboardButton(f"⚙️ {entity_name(s, is_source=True)}{paused}", callback_data=f"srcset|{s}|specsrc_{ch_id}")) + rows = grid_buttons(btns, 2 if len(btns) <= 8 else 3) + rows.append([InlineKeyboardButton("➕ إضافة", callback_data=f"addspecsrc_{ch_id}"), InlineKeyboardButton("🗑 حذف", callback_data=f"delspecsrc_{ch_id}")]) + rows.append(nav_row(f"srcset_{ch_id}")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def source_cleanup_menu(client, callback): + parts = callback.data.split("|", 2) + source_id = parts[1] + back = parts[2] if len(parts) > 2 else "menu_public_src" + terms = db.get_source_remove_terms(source_id) if hasattr(db, "get_source_remove_terms") else [] + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + name = entity_name(meta) + text = f"🧹 **التنظيف الذكي للمصدر:**\n{name}\nID: `{source_id}`\n\n➕ إضافة عناصر جماعياً: تُحذف منشورات المصدر التي تحتوي هذه العناصر.\n🗑 حذف عناصر جماعياً: يزيل عناصر من قائمة التنظيف.\n\n" + text += "العناصر الحالية:\n" + ("\n".join(f"• `{t}`" for t in terms) if terms else "لا توجد عناصر.") + buttons = [ + [InlineKeyboardButton("➕ إضافة عناصر جماعياً", callback_data=f"addclean|{source_id}|{back}")], + [InlineKeyboardButton("🗑 حذف عناصر جماعياً", callback_data=f"delclean|{source_id}|{back}")], + [InlineKeyboardButton("🔙 رجوع", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def add_source_cleanup_prompt(client, callback): + _, source_id, back = callback.data.split("|", 2) + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_source_cleanup_add", "source_id": source_id, "back": back} + await safe_edit(callback, "أرسل عناصر التنظيف الذكي لهذا المصدر.\nكل كلمة/هاشتاك/يوزر بسطر مستقل:", InlineKeyboardMarkup([nav_row(f"srcset|{source_id}|{back}")])) + + +async def del_source_cleanup_prompt(client, callback): + _, source_id, back = callback.data.split("|", 2) + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_source_cleanup_del", "source_id": source_id, "back": back} + terms = db.get_source_remove_terms(source_id) if hasattr(db, "get_source_remove_terms") else [] + current = "\n".join(f"• {t}" for t in terms) if terms else "لا توجد عناصر حالياً." + await safe_edit(callback, "أرسل العناصر التي تريد حذفها من التنظيف الذكي.\nكل عنصر بسطر مستقل.\n\nالحالي:\n" + current, InlineKeyboardMarkup([nav_row(f"srcset|{source_id}|{back}")])) + + +async def source_settings_menu(client, callback): + _, source_id, back = callback.data.split("|", 2) + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + name = entity_name(meta) + paused = is_source_paused(source_id) + remove_emoji = db.get_source_remove_emoji(source_id) if hasattr(db, "get_source_remove_emoji") else False + terms = db.get_source_remove_terms(source_id) if hasattr(db, "get_source_remove_terms") else [] + text = ( + f"⚙️ **إعدادات المصدر:**\n{name}\n\n" + f"🆔 ID: `{source_id}`\n" + f"📊 الحالة: {'⏸️ موقوف' if paused else '✅ شغال'}\n" + f"😀 حذف الإيموجي: {'✅ مفعل' if remove_emoji else '❌ متوقف'}\n" + f"📦 أنواع المحتوى:\n{content_types_status_line(source_id)}\n" + f"🧹 عناصر التنظيف الذكي: {len(terms)}\n\n⏯️ تشغيل/إيقاف: يوقف فحص هذا المصدر دون حذفه.\n😀 الإيموجي: حذف الإيموجي من المنشورات.\n📦 المحتوى: اختيار أنواع المحتوى المسموحة.\n🧹 التنظيف: عناصر تحذف المنشورات المحتوية لها.\n📊 الإحصائيات / 📋 السجل / 🧪 اختبار: فحص حالة المصدر.\n📑 نسخ / 📋 لصق الإعدادات: نقل إعدادات مصدر لمصادر أخرى." + ) + btns = [ + InlineKeyboardButton("⏯️ تشغيل/إيقاف", callback_data=f"togglesource|{source_id}|{back}"), + InlineKeyboardButton("😀 الإيموجي", callback_data=f"toggleemoji|{source_id}|{back}"), + InlineKeyboardButton("📦 المحتوى", callback_data=f"contentmenu|{source_id}|{back}"), + InlineKeyboardButton("🧹 التنظيف", callback_data=f"clean_src|{source_id}|{back}"), + InlineKeyboardButton("📊 الإحصائيات", callback_data=f"srcstats|{source_id}|{back}"), + InlineKeyboardButton("📋 السجل", callback_data=f"srclog|{source_id}|{back}"), + InlineKeyboardButton("🧪 اختبار", callback_data=f"testsrc|{source_id}|{back}"), + InlineKeyboardButton("📑 نسخ الإعدادات", callback_data=f"copysrc|{source_id}|{back}"), + InlineKeyboardButton("📋 لصق الإعدادات", callback_data=f"pastesrc|{source_id}|{back}"), + ] + rows = grid_buttons(btns, 2) + rows.append(nav_row(back)) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def toggle_source_enabled(client, callback): + _, source_id, back = callback.data.split("|", 2) + new_state = not is_source_paused(source_id) + if hasattr(db, "set_source_paused"): + db.set_source_paused(source_id, new_state) + await callback.answer("تم إيقاف المصدر." if new_state else "تم تشغيل المصدر.") + callback.data = f"srcset|{source_id}|{back}" + await source_settings_menu(client, callback) + + +async def toggle_source_emoji(client, callback): + _, source_id, back = callback.data.split("|", 2) + current = db.get_source_remove_emoji(source_id) if hasattr(db, "get_source_remove_emoji") else False + if hasattr(db, "set_source_remove_emoji"): + db.set_source_remove_emoji(source_id, not current) + await callback.answer("تم التحديث.") + callback.data = f"srcset|{source_id}|{back}" + await source_settings_menu(client, callback) + + +async def source_content_menu(client, callback): + _, source_id, back = callback.data.split("|", 2) + types = db.get_source_content_types(source_id) if hasattr(db, "get_source_content_types") else {"text": True, "photo": True, "video": True, "album": True, "voice": False, "audio": False, "document": False} + labels = {"text": "نصوص", "photo": "صور", "video": "فيديو", "album": "ألبومات", "voice": "بصمات", "audio": "صوتيات", "document": "ملفات"} + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + text = f"📦 **فلتر أنواع المحتوى:**\n{entity_name(meta)}\n\nاختر نوع أو أكثر. الافتراضي هو الكل.\n\nيحدد أنواع المنشورات التي يستقبلها هذا المصدر (نصوص، صور، فيديو...)." + btns = [] + for key, label in labels.items(): + mark = "✅" if types.get(key, True) else "❌" + btns.append(InlineKeyboardButton(f"{mark} {label}", callback_data=f"togglectype|{source_id}|{key}|{back}")) + rows = grid_buttons(btns, 2) + rows.append(nav_row(f"srcset|{source_id}|{back}")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def toggle_content_type(client, callback): + _, source_id, ctype, back = callback.data.split("|", 3) + types = db.get_source_content_types(source_id) if hasattr(db, "get_source_content_types") else {"text": True, "photo": True, "video": True, "album": True, "voice": False, "audio": False, "document": False} + new_value = not bool(types.get(ctype, True)) + ok = True + if hasattr(db, "set_source_content_type"): + ok = db.set_source_content_type(source_id, ctype, new_value) + if not ok: + await callback.answer("لا يمكن إيقاف كل الأنواع. لازم يبقى نوع واحد على الأقل.", show_alert=True) + else: + await callback.answer("تم التحديث.") + callback.data = f"contentmenu|{source_id}|{back}" + await source_content_menu(client, callback) + + +async def global_cleanup_menu(client, callback): + terms = db.get_global_remove_terms() if hasattr(db, "get_global_remove_terms") else [] + text = "🧹 **قائمة الحذف العامة:**\n\n" + text += "تنطبق على كل المصادر قبل النشر.\n\n➕ إضافة جماعية / 🗑 حذف جماعي: إدارة العناصر المحذوفة من جميع المصادر.\n\n" + text += "العناصر الحالية:\n" + ("\n".join(f"• `{t}`" for t in terms) if terms else "لا توجد عناصر.") + rows = [ + [InlineKeyboardButton("➕ إضافة جماعية", callback_data="addglobalclean"), InlineKeyboardButton("🗑 حذف جماعي", callback_data="delglobalclean")], + nav_row("main_menu") + ] + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def add_global_cleanup_prompt(client, callback): + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_global_cleanup_add"} + await safe_edit(callback, "أرسل كلمات/هاشتاكات/أسماء للحذف العام.\nكل عنصر بسطر مستقل:", InlineKeyboardMarkup([nav_row("global_clean")])) + + +async def del_global_cleanup_prompt(client, callback): + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_global_cleanup_del"} + terms = db.get_global_remove_terms() if hasattr(db, "get_global_remove_terms") else [] + current = "\n".join(f"• {t}" for t in terms) if terms else "لا توجد عناصر حالياً." + await safe_edit(callback, "أرسل العناصر التي تريد حذفها من قائمة الحذف العامة.\nكل عنصر بسطر مستقل.\n\nالحالي:\n" + current, InlineKeyboardMarkup([nav_row("global_clean")])) + + +# ============================================================ +# 🧹 قائمة الكلمات المحذوفة — خاصة بكل قناة على حدة +# ============================================================ + +async def channel_delete_terms_menu(client, callback): + ch_id = callback.data.split("|", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + terms = db.get_channel_delete_terms(ch_id) + text = f"🧹 **قائمة الكلمات المحذوفة — {entity_name(ch)}**\n\n" + text += "تُحذف هذي العناصر من النص قبل نشره بهذه القناة فقط (باقي القنوات غير متأثرة).\n\n" + text += "العناصر الحالية:\n" + ("\n".join(f"• {t}" for t in terms) if terms else "لا توجد عناصر.") + "\n\n➕ إضافة جماعية / 🗑 حذف جماعي: إدارة الكلمات المحذوفة من منشورات هذه القناة فقط." + rows = [ + [InlineKeyboardButton("➕ إضافة جماعية", callback_data=f"chdeltermadd|{ch_id}"), InlineKeyboardButton("🗑 حذف جماعي", callback_data=f"chdeltermdel|{ch_id}")], + nav_row(f"postset_{ch_id}"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def channel_add_delete_term_prompt(client, callback): + await callback.answer() + logger.info(f"channel_add_delete_term_prompt: user {callback.from_user.id}") + ch_id = callback.data.split("|", 1)[1] + if not db.get_channel(ch_id): + await callback.answer("القناة غير موجودة.") + return + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_channel_delete_term_add", "ch_id": ch_id} + await safe_edit(callback, "أرسل كلمات/هاشتاكات/أسماء لحذفها من منشورات هذه القناة فقط.\nكل عنصر بسطر مستقل:", InlineKeyboardMarkup([nav_row(f"chdelterms|{ch_id}")])) + + +async def channel_del_delete_term_prompt(client, callback): + await callback.answer() + logger.info(f"channel_del_delete_term_prompt: user {callback.from_user.id}") + ch_id = callback.data.split("|", 1)[1] + if not db.get_channel(ch_id): + await callback.answer("القناة غير موجودة.") + return + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_channel_delete_term_del", "ch_id": ch_id} + terms = db.get_channel_delete_terms(ch_id) + current = "\n".join(f"• {t}" for t in terms) if terms else "لا توجد عناصر حالياً." + await safe_edit(callback, "أرسل العناصر التي تريد حذفها.\nكل عنصر بسطر مستقل.\n\nالحالي:\n" + current, InlineKeyboardMarkup([nav_row(f"chdelterms|{ch_id}")])) + + + +async def channel_speed_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + current = ch.get("publish_delay", None) + text = ( + f"⏱ **سرعة النشر للقناة:**\n{entity_name(ch)}\n\n⏱ الفترة بالثانية بين المنشورات في هذه القناة.\n" + f"الحالية: {'افتراضي' if current in (None, '') else str(current) + ' ثانية'}\n\n" + "اختر قيمة سريعة أو اضغط تخصيص. 0 يعني رجوع للوضع الافتراضي." + ) + buttons = [ + [InlineKeyboardButton("افتراضي", callback_data=f"setspeed|{ch_id}|default")], + [InlineKeyboardButton("1 ثانية", callback_data=f"setspeed|{ch_id}|1"), InlineKeyboardButton("3 ثواني", callback_data=f"setspeed|{ch_id}|3")], + [InlineKeyboardButton("5 ثواني", callback_data=f"setspeed|{ch_id}|5"), InlineKeyboardButton("10 ثواني", callback_data=f"setspeed|{ch_id}|10")], + [InlineKeyboardButton("✏️ تخصيص رقم", callback_data=f"customspeed_{ch_id}")], + [InlineKeyboardButton("🔙 رجوع", callback_data=f"postset_{ch_id}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def set_channel_speed(client, callback): + _, ch_id, value = callback.data.split("|", 2) + if value == "default": + db.set_channel_publish_delay(ch_id, None) if hasattr(db, "set_channel_publish_delay") else None + await callback.answer("تم ضبطها على الافتراضي.") + else: + db.set_channel_publish_delay(ch_id, float(value)) if hasattr(db, "set_channel_publish_delay") else None + await callback.answer(f"تم ضبطها على {value} ثانية.") + callback.data = f"speedmenu_{ch_id}" + await channel_speed_menu(client, callback) + + +async def custom_channel_speed_prompt(client, callback): + ch_id = callback.data.split("_", 1)[1] + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_channel_speed", "ch_id": ch_id} + await safe_edit(callback, "أرسل عدد الثواني لهذه القناة.\nمثال: 1 أو 2.5 أو 10\nأرسل 0 للرجوع للوضع الافتراضي:", InlineKeyboardMarkup([nav_row(f"speedmenu_{ch_id}")])) + + +def _format_ts(ts): + if not ts: + return "لا يوجد" + try: + return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(ts))) + except Exception: + return str(ts) + + +async def source_stats_menu(client, callback): + _, source_id, back = callback.data.split("|", 2) + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + stats = db.get_source_stats(source_id) if hasattr(db, "get_source_stats") else {} + text = ( + f"📊 **إحصائيات المصدر:**\n{entity_name(meta)}\nID: `{source_id}`\n\n" + f"• المستلمة: {stats.get('received', 0)}\n" + f"• المنشورة: {stats.get('published', 0)}\n" + f"• المرفوضة: {stats.get('rejected', 0)}\n" + f"• المتجاهلة: {stats.get('ignored', 0)}\n" + f"• المكررة: {stats.get('duplicates', 0)}\n" + f"• الأخطاء: {stats.get('errors', 0)}\n" + f"• آخر رسالة: {stats.get('last_message_id') or 'لا يوجد'}\n" + f"• آخر حدث: {stats.get('last_event') or 'لا يوجد'}\n" + f"• السبب: {stats.get('last_reason') or 'لا يوجد'}\n" + f"• الوقت: {_format_ts(stats.get('last_ts'))}" + ) + await safe_edit(callback, text, InlineKeyboardMarkup([ + [InlineKeyboardButton("🔙 رجوع", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + + +async def source_log_menu(client, callback): + _, source_id, back = callback.data.split("|", 2) + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + logs = db.get_source_logs(source_id, 20) if hasattr(db, "get_source_logs") else [] + text = f"📋 **سجل المصدر:**\n{entity_name(meta)}\nID: `{source_id}`\n\n" + if not logs: + text += "لا توجد عمليات مسجلة." + else: + rows = [] + for item in reversed(logs[-20:]): + rows.append(f"• {_format_ts(item.get('ts'))} | {item.get('event')} | msg={item.get('message_id')} | {item.get('reason') or ''}") + text += "\n".join(rows[:20]) + await safe_edit(callback, text[:3900], InlineKeyboardMarkup([ + [InlineKeyboardButton("🔙 رجوع", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + + +async def test_source(client, callback): + _, source_id, back = callback.data.split("|", 2) + source_id_int = int(source_id) + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": source_id} + kind = source_kind_label(source_id_int) + targets = sorted(get_targets_for_source(source_id_int)) + last_seen = db.get_last_source_message(source_id_int) if hasattr(db, "get_last_source_message") else None + try: + last_msg = None + async for msg in user_client.get_chat_history(source_id_int, limit=1): + last_msg = msg + break + access = "✅ متاح" + last_id = getattr(last_msg, "id", None) if last_msg else "لا يوجد" + preview = (getattr(last_msg, "text", None) or getattr(last_msg, "caption", None) or "")[:120] if last_msg else "" + except Exception as e: + access = f"❌ فشل: {e}" + last_id = "غير معروف" + preview = "" + text = ( + f"🧪 **اختبار المصدر:**\n{entity_name(meta)}\nID: `{source_id}`\n\n" + f"• الوصول: {access}\n" + f"• النوع: {kind}\n" + f"• آخر ID محفوظ: {last_seen or 'لا يوجد'}\n" + f"• آخر رسالة بالقناة: {last_id}\n" + f"• القنوات المستهدفة: {targets if targets else 'لا توجد'}\n" + f"• معاينة: {preview or 'لا يوجد'}" + ) + await safe_edit(callback, text, InlineKeyboardMarkup([ + [InlineKeyboardButton("🔙 رجوع", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + + +async def copy_source_settings_prompt(client, callback): + _, source_id, back = callback.data.split("|", 2) + user_states[callback.from_user.id] = {"state": "source_settings_copied", "source_id": source_id, "back": back} + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + text = ( + f"✅ تم نسخ إعدادات المصدر:\n{entity_name(meta)}\n\n" + "الآن يمكنك:\n" + "• الذهاب لأي مصدر آخر والضغط على 📋 لصق الإعدادات (واحد بواحد)\n" + "• أو اضغط الزر أدناه للصق لعدة مصادر دفعة واحدة" + ) + buttons = [ + [InlineKeyboardButton("📋 لصق لعدة مصادر دفعة واحدة", callback_data=f"bulkpastesrc|{source_id}|{back}")], + [InlineKeyboardButton("🔙 رجوع للمصدر", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def paste_source_settings(client, callback): + _, target_source_id, back = callback.data.split("|", 2) + saved = user_states.get(callback.from_user.id, {}) + from_source_id = saved.get("source_id") if saved.get("state") == "source_settings_copied" else None + if not from_source_id: + await callback.answer("ماكو إعدادات منسوخة. اضغط أولاً نسخ الإعدادات من مصدر آخر.", show_alert=True) + return + if str(from_source_id) == str(target_source_id): + await callback.answer("هذا نفس المصدر المنسوخ.", show_alert=True) + return + copied = db.copy_source_settings(from_source_id, [target_source_id]) if hasattr(db, "copy_source_settings") else 0 + await callback.answer("تم لصق الإعدادات." if copied else "فشل لصق الإعدادات.", show_alert=True) + callback.data = f"srcset|{target_source_id}|{back}" + await source_settings_menu(client, callback) + + +async def bulk_paste_source_prompt(client, callback): + """يفتح مربع إدخال نصي للصق إعدادات مصدر لعدة مصادر دفعة واحدة.""" + _, source_id, back = callback.data.split("|", 2) + saved = user_states.get(callback.from_user.id, {}) + from_source = saved.get("source_id") if saved.get("state") == "source_settings_copied" else None + if not from_source: + await callback.answer("ماكو إعدادات منسوخة. ارجع واضغط نسخ الإعدادات أولاً.", show_alert=True) + return + user_states[callback.from_user.id] = {"state": "waiting_copy_source_settings", "source_id": from_source, "back": back} + await safe_edit( + callback, + "أرسل المصادر التي تريد نسخ الإعدادات إليها.\nكل رابط/يوزر/ID بسطر مستقل:", + InlineKeyboardMarkup([nav_row(f"srcset|{source_id}|{back}")]) + ) + +async def system_menu(client, callback): + """القائمة الرئيسية لقسم النظام (خارج القنوات).""" + buttons = [ + InlineKeyboardButton("🧪 الفحص الشامل", callback_data="full_check"), + InlineKeyboardButton("🟢 حالة النظام", callback_data="system_status"), + InlineKeyboardButton("🛠 إدارة التشغيل", callback_data="ops_menu"), + InlineKeyboardButton("📝 إدارة السجل", callback_data="log_menu"), + InlineKeyboardButton("🔔 التنبيهات", callback_data="notifications_menu"), + ] + rows = grid_buttons(buttons, 2) + rows.append(nav_row("main_menu")) + await safe_edit(callback, "🖥 **النظام**\n\n🧪 الفحص الشامل: يفحص الجلسة والبوت والقنوات والمصادر.\n🟢 حالة النظام: يعرض اتصال البوت والجلسة وأعداد القنوات.\n🛠 إدارة التشغيل: الصيانة واختبار كل القنوات وآخر الأخطاء.\n📝 إدارة السجل: عرض وحجم ومسح سجل البوت.\n🔔 التنبيهات: تشغيل/إيقاف إشعارات الفحوصات.", InlineKeyboardMarkup(rows)) + + +async def system_status_menu(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + channels = db.get_all_channels() + public_count = len(db.get_public_sources()) + special_sources = set() + for ch in channels: + for src in ch.get("special_sources") or []: + try: + special_sources.add(int(src)) + except Exception: + pass + last_error = db.get_system_value("last_error", "لا يوجد") if hasattr(db, "get_system_value") else "لا يوجد" + text = ( + "🟢 **حالة النظام**\n\n" + f"• البوت: {'✅ متصل' if bot_client else '❌ غير معروف'}\n" + f"• الجلسة: {'✅ متصلة' if user_client else '❌ غير معروف'}\n" + f"• الوسيطة: `{config.MIDDLE_CHANNEL}`\n" + f"• قنوات النشر: {len(channels)}\n" + f"• المصادر العامة: {public_count}\n" + f"• المصادر الخاصة: {len(special_sources)}\n" + f"• مصادر الفحص الكلية: {len(get_polling_sources())}\n" + f"• آخر خطأ: {last_error}\n\n🧪 فحص شامل: يعيد فحص كل مكونات النظام مباشرة." + ) + full_btn = f"full_check|{ch_id}" if ch_id else "full_check" + back_btn = f"sysset_{ch_id}" if ch_id else "system_menu" + await safe_edit(callback, text, InlineKeyboardMarkup([ + [InlineKeyboardButton("🧪 فحص شامل", callback_data=full_btn)], + nav_row(back_btn), + ])) + + +async def full_check_menu(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + lines = ["🧪 **الفحص الشامل**", ""] + try: + await user_client.get_me() + lines.append("✅ الجلسة تعمل") + except Exception as e: + lines.append(f"❌ الجلسة: {e}") + try: + await bot_client.get_me() + lines.append("✅ البوت يعمل") + except Exception as e: + lines.append(f"❌ البوت: {e}") + try: + await warm_middle_peer() + lines.append("✅ الوسيطة تم فحصها") + except Exception as e: + lines.append(f"❌ الوسيطة: {e}") + channels = db.get_all_channels() + ok_ch = 0 + fail_ch = [] + for ch in channels[:80]: + try: + await hydrate_publish_channel(int(ch["id"])) + ok_ch += 1 + except Exception as e: + fail_ch.append(f"{entity_name(ch)}: {e}") + lines.append(f"✅ قنوات النشر المتاحة: {ok_ch}/{len(channels)}") + if fail_ch: + lines.append("⚠️ قنوات فشلت:") + lines.extend(["• " + x[:150] for x in fail_ch[:10]]) + sources = get_polling_sources() + ok_src = 0 + fail_src = [] + for src in sources[:120]: + try: + await hydrate_source_channel(int(src)) + ok_src += 1 + except Exception as e: + fail_src.append(f"{src}: {e}") + lines.append(f"✅ المصادر المتاحة: {ok_src}/{len(sources)}") + if fail_src: + lines.append("⚠️ مصادر فشلت:") + lines.extend(["• " + x[:150] for x in fail_src[:10]]) + await safe_edit(callback, "\n".join(lines)[:3900], InlineKeyboardMarkup([ + [InlineKeyboardButton("🟢 حالة النظام", callback_data=f"system_status|{ch_id}" if ch_id else "system_status")], + nav_row(f"system_status|{ch_id}" if ch_id else "system_status"), + ])) + + +async def warm_all_peers_after_import(): + await warm_middle_peer() + for ch in db.get_all_channels(): + try: + await hydrate_publish_channel(int(ch["id"])) + except Exception as e: + logger.warning(f"فشل تهيئة قناة نشر بعد الاستيراد {ch.get('id')}: {e}") + for src in get_polling_sources(): + try: + await hydrate_source_channel(int(src)) + except Exception as e: + logger.warning(f"فشل تهيئة مصدر بعد الاستيراد {src}: {e}") + + + +async def channel_quote_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + qt = get_channel_quote_types_safe(ch_id) + cfg = db.get_channel_config(ch_id) if hasattr(db, "get_channel_config") else {} + title_quote = bool(cfg.get("title_quote")) + sig_quote = bool(cfg.get("signature_quote")) + text = ( + f"💬 **إعدادات الاقتباس لقناة:**\n{channel_display_name(ch_id)}\n\n" + "اختر الأنواع التي تريد نشرها كاقتباس رسمي:\n\n" + f"• العنوان: {'✅ مفعل' if title_quote else '❌ متوقف'}\n" + f"• النصوص: {'✅ مفعل' if qt.get('text') else '❌ متوقف'}\n" + f"• الصور: {'✅ مفعل' if qt.get('photo') else '❌ متوقف'}\n" + f"• الفيديو: {'✅ مفعل' if qt.get('video') else '❌ متوقف'}\n" + f"• الألبومات: {'✅ مفعل' if qt.get('album') else '❌ متوقف'}\n" + f"• التوقيع: {'✅ مفعل' if sig_quote else '❌ متوقف'}\n\nاضغط النوع لتفعيله أو إيقافه كاقتباس رسمي في هذه القناة." + ) + labels = {"text": "النصوص", "photo": "الصور", "video": "الفيديو", "album": "الألبومات"} + buttons = [ + InlineKeyboardButton(f"{'✅' if title_quote else '❌'} العنوان", callback_data=f"ch_titlequote_{ch_id}"), + ] + for key in ["text", "photo", "video", "album"]: + mark = "✅" if qt.get(key) else "❌" + buttons.append(InlineKeyboardButton(f"{mark} {labels[key]}", callback_data=f"toggleqtype|{ch_id}|{key}")) + buttons.append(InlineKeyboardButton(f"{'✅' if sig_quote else '❌'} التوقيع", callback_data=f"ch_sigquote_{ch_id}")) + rows = grid_buttons(buttons, 2) + rows.append([InlineKeyboardButton("🔙 رجوع", callback_data=f"postset_{ch_id}"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")]) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def toggle_channel_quote_type(client, callback): + try: + _, ch_id, qtype = callback.data.split("|", 2) + except Exception: + await callback.answer("طلب غير صالح.", show_alert=True) + return + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + current = get_channel_quote_types_safe(ch_id).get(qtype, False) + if hasattr(db, "set_channel_quote_type"): + db.set_channel_quote_type(ch_id, qtype, not current) + else: + db.update_channel(ch_id, "quote_publish", not current) + await callback.answer("تم تحديث خيار الاقتباس.") + callback.data = f"quotemenu_{ch_id}" + await channel_quote_menu(client, callback) + + +async def toggle_channel_quote(client, callback): + # توافق قديم: إذا وصل callback قديم، افتح قائمة الأنواع بدل تبديل عام. + callback.data = callback.data.replace("togglequote_", "quotemenu_", 1) + await channel_quote_menu(client, callback) + + +async def channel_hashtags_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + tags = db.get_channel_hashtags(ch_id) if hasattr(db, "get_channel_hashtags") else ch.get("hashtags", []) + shown = tags[:50] + display = "\n".join(f"• `{t}`" for t in shown) + if len(tags) > len(shown): + display += f"\n… و{len(tags) - len(shown)} هاشتاك إضافي (يُعرض أول 50)." + text = ( + f"🏷 **هاشتاكات قناة النشر:**\n{channel_display_name(ch)}\n\n" + "تضاف تلقائياً أسفل المنشور لهذه القناة فقط.\n\n" + "الحالية:\n" + (display if tags else "لا توجد.") + "\n\n➕ إضافة جماعية: تضيف هاشتاكات للقناة (كل واحد بسطر).\n🗑 حذف جماعي: يزيل هاشتاكات موجودة." + ) + buttons = [ + InlineKeyboardButton("➕ إضافة جماعية", callback_data=f"addhashtags_{ch_id}"), + InlineKeyboardButton("🗑 حذف جماعي", callback_data=f"delhashtags_{ch_id}"), + ] + rows = grid_buttons(buttons, 2) + rows.append([InlineKeyboardButton("🔙 رجوع", callback_data=f"postset_{ch_id}"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")]) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def add_channel_hashtags_prompt(client, callback): + ch_id = callback.data.split("_", 1)[1] + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_channel_hashtags_add", "ch_id": ch_id} + await safe_edit(callback, "أرسل هاشتاك أو مجموعة هاشتاكات.\nكل هاشتاك بسطر مستقل:", InlineKeyboardMarkup([nav_row(f"hashtags_{ch_id}")])) + + +async def del_channel_hashtags_prompt(client, callback): + ch_id = callback.data.split("_", 1)[1] + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_channel_hashtags_del", "ch_id": ch_id} + tags = db.get_channel_hashtags(ch_id) if hasattr(db, "get_channel_hashtags") else [] + shown = tags[:50] + current = "\n".join(f"• {t}" for t in shown) if tags else "لا توجد هاشتاكات حالياً." + if len(tags) > len(shown): + current += f"\n… و{len(tags) - len(shown)} هاشتاك إضافي." + await safe_edit(callback, "أرسل الهاشتاكات التي تريد حذفها.\nكل هاشتاك بسطر مستقل.\n\nالحالي:\n" + current, InlineKeyboardMarkup([nav_row(f"hashtags_{ch_id}")])) + + +async def test_publish_channel(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + try: + text = compose_channel_post_text(f"✅ اختبار نشر ناجح\n{entity_name(ch)}", ch_id, ch.get("tail", "")) + formatted, parse_mode, entities = format_outgoing_payload_for_channel(text, ch_id, "text") + await safe_send_channel_message(int(ch_id), formatted, parse_mode=parse_mode, entities=entities) + record_channel_success(ch_id) + await callback.answer("تم إرسال اختبار النشر.") + await notify_admins(f"تم اختبار النشر بنجاح إلى:\n{channel_display_name(ch)}") + except Exception as e: + await record_channel_failure_and_maybe_alert(ch_id, e) + await callback.answer("فشل اختبار النشر.", show_alert=True) + await notify_admins(f"فشل اختبار النشر إلى:\n{channel_display_name(ch)}\n\n{e}") + + +async def operations_menu(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + maintenance = db.is_maintenance_mode() if hasattr(db, "is_maintenance_mode") else False + text = ( + "🛠 **إدارة التشغيل**\n\n" + f"وضع الصيانة: {'✅ مفعل' if maintenance else '❌ متوقف'}\n\n" + "وضع الصيانة يوقف النشر، لكن يبقي فحص المصادر مستمر حتى لا تتراكم الأخبار.\n\n🛠 تبديل الصيانة: يوقف النشر ويبقي فحص المصادر مستمراً.\n🧪 اختبار كل القنوات: يفحص إمكانية النشر في كل القنوات.\n⚠️ آخر الأخطاء: يعرض آخر 20 خطأ مسجلاً." + ) + buttons = [ + InlineKeyboardButton("🛠 تبديل الصيانة", callback_data=f"toggle_maintenance|{ch_id}" if ch_id else "toggle_maintenance"), + InlineKeyboardButton("🧪 اختبار كل القنوات", callback_data=f"test_all_channels|{ch_id}" if ch_id else "test_all_channels"), + InlineKeyboardButton("⚠️ آخر الأخطاء", callback_data=f"errors_menu|{ch_id}" if ch_id else "errors_menu"), + ] + rows = grid_buttons(buttons, 2) + rows.append(nav_row(f"sysset_{ch_id}" if ch_id else "system_menu")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def toggle_maintenance_mode(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + current = db.is_maintenance_mode() if hasattr(db, "is_maintenance_mode") else False + if hasattr(db, "set_maintenance_mode"): + db.set_maintenance_mode(not current) + await callback.answer("تم تشغيل وضع الصيانة." if not current else "تم إيقاف وضع الصيانة.") + callback.data = f"ops_menu|{ch_id}" if ch_id else "ops_menu" + await operations_menu(client, callback) + + + +async def toggle_short_posts_filter(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + if ch_id and hasattr(db, "get_channel_ignore_short_posts"): + current = bool(db.get_channel_ignore_short_posts(ch_id)) + if hasattr(db, "set_channel_ignore_short_posts"): + db.set_channel_ignore_short_posts(ch_id, not current) + else: + current = is_ignore_short_posts_enabled() + if hasattr(db, "set_ignore_short_posts"): + db.set_ignore_short_posts(not current) + await callback.answer("تم تحديث فلتر المنشورات القصيرة للقناة." if ch_id else "تم تحديث فلتر المنشورات القصيرة العام.") + callback.data = f"postset_{ch_id}" if ch_id else "ops_menu" + await (post_settings_menu(client, callback) if ch_id else operations_menu(client, callback)) + + +async def errors_menu(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + errors = db.get_last_errors(20) if hasattr(db, "get_last_errors") else [] + text = "⚠️ **آخر الأخطاء:**\n\n⚙️ عرض آخر 20 خطأ مسجل في البوت.\n\n" + if not errors: + text += "لا توجد أخطاء مسجلة." + else: + rows_txt = [] + for e in reversed(errors[-20:]): + rows_txt.append(f"• {_format_ts(e.get('ts'))}\n {e.get('context')}\n `{str(e.get('error'))[:180]}`") + text += "\n\n".join(rows_txt) + buttons = [ + [InlineKeyboardButton("🗑 مسح الأخطاء", callback_data=f"clear_errors|{ch_id}" if ch_id else "clear_errors")], + [InlineKeyboardButton("🔙 رجوع", callback_data=f"ops_menu|{ch_id}" if ch_id else "ops_menu"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")] + ] + await safe_edit(callback, text[:3900], InlineKeyboardMarkup(buttons)) + + +async def clear_errors(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + if hasattr(db, "clear_last_errors"): + db.clear_last_errors() + await callback.answer("تم مسح لوحة الأخطاء.") + callback.data = f"errors_menu|{ch_id}" if ch_id else "errors_menu" + await errors_menu(client, callback) + + +def _read_log_tail_lines(path, max_lines=500, chunk_size=8192): + """يقرأ آخر max_lines سطر فقط من الملف دون تحميله كاملاً في الذاكرة.""" + try: + with open(path, "rb") as f: + f.seek(0, os.SEEK_END) + file_size = f.tell() + data = b"" + lines_found = 0 + pos = file_size + while pos > 0 and lines_found <= max_lines: + read_size = min(chunk_size, pos) + pos -= read_size + f.seek(pos) + chunk = f.read(read_size) + data = chunk + data + lines_found = data.count(b"\n") + text = data.decode("utf-8", errors="ignore") + lines = text.splitlines() + return lines[-max_lines:] + except FileNotFoundError: + return [] + except Exception as e: + logger.error(f"فشل قراءة ملف السجل: {e}") + return [] + + +async def log_management_menu(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + text = "📝 **إدارة السجل**\n\n👁️ عرض آخر 500 سطر: يقرأ آخر أسطر سجل البوت.\n🔄 تحديث السجل: يعيد قراءة السجل.\n📦 عرض حجم السجل: يعرض حجم ملف السجل بالميغابايت.\n🗑️ مسح السجل: يفرّغ ملف السجل فقط (البوت يستمر بالعمل)." + buttons = [ + [InlineKeyboardButton("👁️ عرض آخر 500 سطر", callback_data=f"log_view|{ch_id}" if ch_id else "log_view")], + [InlineKeyboardButton("🔄 تحديث السجل", callback_data=f"log_refresh|{ch_id}" if ch_id else "log_refresh")], + [InlineKeyboardButton("📦 عرض حجم السجل", callback_data=f"log_size|{ch_id}" if ch_id else "log_size")], + [InlineKeyboardButton("🗑️ مسح السجل", callback_data=f"log_clear_prompt|{ch_id}" if ch_id else "log_clear_prompt")], + nav_row(f"sysset_{ch_id}" if ch_id else "system_menu"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def view_bot_log(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + lines = _read_log_tail_lines(BOT_LOG_FILE, 500) + if not lines: + body = "لا يوجد سجل حالياً." + else: + body = "\n".join(lines) + text = f"👁️ **آخر {len(lines)} سطر من السجل:**\n\n`{body}`" + if len(text) > 3900: + text = text[-3900:] + text = f"👁️ **آخر أسطر السجل (مقتصّة لطول الرسالة):**\n\n`{text}`" + buttons = [ + [InlineKeyboardButton("🔄 تحديث", callback_data=f"log_view|{ch_id}" if ch_id else "log_view")], + [InlineKeyboardButton("🔙 رجوع", callback_data=f"log_menu|{ch_id}" if ch_id else "log_menu"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def show_log_size(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + try: + size_bytes = os.path.getsize(BOT_LOG_FILE) + size_mb = size_bytes / (1024 * 1024) + text = f"📦 **حجم ملف السجل:**\n\n{size_mb:.3f} MB" + except FileNotFoundError: + text = "📦 لا يوجد ملف سجل حالياً." + except Exception as e: + text = f"❌ تعذر قراءة حجم السجل: {e}" + buttons = [ + [InlineKeyboardButton("🔙 رجوع", callback_data=f"log_menu|{ch_id}" if ch_id else "log_menu"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def clear_log_prompt(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + text = ( + "⚠️ **تأكيد مسح السجل**\n\n" + "سيتم تفريغ ملف السجل فقط. البوت سيستمر بالعمل والكتابة بنفس الملف بدون أي إعادة تشغيل.\n\n" + "هل تريد المتابعة؟" + ) + buttons = [ + [InlineKeyboardButton("✅ نعم، امسح السجل", callback_data=f"log_clear_confirm|{ch_id}" if ch_id else "log_clear_confirm")], + nav_row(f"log_menu|{ch_id}" if ch_id else "main_menu"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def confirm_clear_log(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + try: + with open(BOT_LOG_FILE, "w", encoding="utf-8"): + pass + await callback.answer("تم مسح السجل.") + except Exception as e: + logger.error(f"فشل مسح ملف السجل: {e}") + await callback.answer("تعذر مسح السجل.", show_alert=True) + callback.data = f"log_menu|{ch_id}" if ch_id else "log_menu" + await log_management_menu(client, callback) + + +async def named_backup_prompt(client, callback): + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_named_backup"} + await safe_edit(callback, "أرسل اسم النسخة الاحتياطية.\nمثال:\nstable_before_platform", InlineKeyboardMarkup([nav_row("main_menu")])) + + +async def test_all_channels(client, callback): + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + channels = db.get_all_channels() + ok = 0 + fail = 0 + for ch in channels: + if ch.get("paused"): + continue + try: + ch_id_int = int(ch["id"]) + text = compose_channel_post_text(f"✅ اختبار نشر جماعي ناجح\n{entity_name(ch)}", ch_id_int, ch.get("tail", "")) + formatted, parse_mode, entities = format_outgoing_payload_for_channel(text, ch_id_int, "text") + await safe_send_channel_message(ch_id_int, formatted, parse_mode=parse_mode, entities=entities) + record_channel_success(ch_id_int) + ok += 1 + await asyncio.sleep(get_publish_delay_for_channel(ch_id_int)) + except Exception as e: + fail += 1 + await record_channel_failure_and_maybe_alert(ch.get("id"), e) + await safe_edit(callback, f"🧪 **نتيجة اختبار كل القنوات:**\n\n✅ نجح: {ok}\n❌ فشل: {fail}", InlineKeyboardMarkup([ + [InlineKeyboardButton("🔙 رجوع", callback_data=f"ops_menu|{ch_id}" if ch_id else "ops_menu"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")] + ])) +async def add_special_source_prompt(client, callback): + ch_id = callback.data.split("_", 1)[1] + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = { + "state": "waiting_special_source", + "ch_id": ch_id + } + await safe_edit(callback, "أرسل مصدر خاص واحد أو عدة مصادر خاصة.\nكل رابط/يوزر/ID بسطر مستقل:", InlineKeyboardMarkup([nav_row(f"srcset_{ch_id}")])) + +async def delete_special_source_prompt(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + sources = ch.get("special_sources", []) + if not sources: + await callback.answer("لا توجد مصادر.") + return + buttons = [] + for idx, src in enumerate(sources): + name = entity_name(src, is_source=True) + buttons.append([InlineKeyboardButton(f"🗑 حذف {name}", callback_data=f"confdelspec_{ch_id}_{idx}")]) + buttons.append(nav_row(f"specsrc_{ch_id}")) + await safe_edit(callback, "اختر المصدر لحذفه:", InlineKeyboardMarkup(buttons)) + +async def confirm_delete_special_source(client, callback): + parts = callback.data.split("_") + ch_id = parts[1] + idx = int(parts[2]) + + ch = db.get_channel(ch_id) + + if not ch: + await callback.answer("غير موجودة.") + return + + sources = ch.get("special_sources", []) + + if idx < 0 or idx >= len(sources): + await callback.answer("المصدر غير موجود.") + return + + sources.pop(idx) + db.update_channel(ch_id, "special_sources", sources) + + await callback.answer("تم الحذف.") + await manage_special_sources(client, callback) + +async def show_stats(client, callback): + channels = db.get_all_channels() + total_posts = sum(ch.get("posts_count", 0) for ch in channels) + pub_src = len(db.get_public_sources()) + words = len(db.get_blocked_words()) + + text = "📊 **الإحصائيات:**\n\n" + text += f"• إجمالي المنشورات: **{total_posts}**\n" + text += f"• قنوات النشر: {len(channels)}\n" + text += f"• المصادر العامة: {pub_src}\n" + text += f"• الكلمات المحظورة: {words}\n\n" + + if channels: + text += "**تفصيل المنشورات حسب القناة:**\n" + for ch in channels: + text += f"• {entity_name(ch)}\n ID: `{ch['id']}`\n المنشورات: **{ch.get('posts_count', 0)}**\n" + + await safe_edit( + callback, + text, + InlineKeyboardMarkup([nav_row("main_menu")]) + ) + +async def handle_text_input(client, message): + if not is_admin(message.from_user.id): + return + uid = message.from_user.id + if uid not in user_states: + return + state = user_states[uid].get("state") + text = message.text.strip() + + if state and state.startswith("blogger_"): + await handle_blogger_text_input(client, message) + return + + try: + if state == "waiting_channel_id": + results = [] + for raw in split_bulk_lines(text): + try: + chat = await resolve_chat_info_timeout(raw, prefer_user=False) + bot_status = "" + bot_admin = False + check_note = "" + try: + bot_member = await bot_client.get_chat_member(int(chat.id), (await bot_client.get_me()).id) + bot_status = member_status_value(getattr(bot_member, "status", None)) + bot_admin = is_bot_admin_status(bot_status) + check_note = "✅ البوت مشرف" if bot_admin else "❌ البوت ليس مشرفاً" + except Exception as verr: + bot_status = "unknown" + check_note = f"تعذر التحقق من البوت: {str(verr)[:60]}" + meta = chat_meta(chat, raw) + created = db.add_channel(chat.id, **meta) + db.update_channel(chat.id, "bot_admin", bot_admin) + db.update_channel(chat.id, "bot_status", bot_status) + results.append(("ok" if created else "exists", f"{meta['title']} | {check_note}", raw)) + except Exception as e: + results.append(("fail", raw, "انتهت المهلة أو تعذر جلب المعلومات" if isinstance(e, asyncio.TimeoutError) else str(e))) + await message.reply(format_bulk_report("📢 نتيجة إضافة قنوات النشر", results)) + await show_channels_menu_from_message(message) + elif state == "waiting_tail": + ch_id = user_states[uid]["ch_id"] + db.update_channel(ch_id, "tail", text) + await message.reply("✅ تم حفظ التوقيع.") + ch = db.get_channel(ch_id) + if ch: + await message.reply(f"إعدادات القناة: {entity_name(ch)}", reply_markup=channel_buttons(ch_id)) + elif state == "waiting_public_source": + results = [] + for raw in split_bulk_lines(text): + try: + chat = await resolve_chat_info_timeout(raw, prefer_user=True) + meta = chat_meta(chat, raw) + created = db.add_public_source(chat.id, **meta) + results.append(("ok" if created else "exists", meta["title"], raw)) + except Exception as e: + results.append(("fail", raw, "انتهت المهلة أو تعذر جلب المعلومات" if isinstance(e, asyncio.TimeoutError) else str(e))) + await message.reply(format_bulk_report("🌐 نتيجة إضافة المصادر العامة", results)) + await show_public_sources_menu_from_message(message) + elif state == "waiting_blocked_word": + logger.info(f"handle_text_input: waiting_blocked_word from user {uid}") + added = 0 + exists = 0 + for word in split_bulk_lines(text): + if db.add_blocked_word(word): + added += 1 + else: + exists += 1 + logger.info(f"waiting_blocked_word: added={added}, exists={exists}") + await message.reply(f"✅ تمت إضافة {added} كلمة.\n⚠️ موجودة مسبقاً/فارغة: {exists}") + await show_blocked_words_menu_from_message(message) + elif state == "waiting_channel_blocked_word": + logger.info(f"handle_text_input: waiting_channel_blocked_word from user {uid}") + ch_id = user_states[uid]["ch_id"] + added = 0 + exists = 0 + for word in split_bulk_lines(text): + if db.add_channel_blocked_word(ch_id, word): + added += 1 + else: + exists += 1 + logger.info(f"waiting_channel_blocked_word: channel={ch_id}, added={added}, exists={exists}") + ch = db.get_channel(ch_id) + await message.reply( + f"✅ تمت إضافة {added} كلمة لقناة {entity_name(ch) if ch else ch_id}.\n⚠️ موجودة مسبقاً/فارغة: {exists}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🚫 رجوع للكلمات المحظورة", callback_data=f"chwords|{ch_id}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_special_source": + ch_id = user_states[uid]["ch_id"] + ch = db.get_channel(ch_id) + if not ch: + await message.reply("❌ القناة غير موجودة.") + return + sources = ch.get("special_sources", []) + results = [] + for raw in split_bulk_lines(text): + try: + chat = await resolve_chat_info_timeout(raw, prefer_user=True) + meta = chat_meta(chat, raw) + db.update_source_meta(chat.id, **meta) if hasattr(db, "update_source_meta") else None + if int(chat.id) not in [int(x) for x in sources]: + sources.append(int(chat.id)) + results.append(("ok", meta["title"], raw)) + else: + results.append(("exists", meta["title"], raw)) + except Exception as e: + results.append(("fail", raw, "انتهت المهلة أو تعذر جلب المعلومات" if isinstance(e, asyncio.TimeoutError) else str(e))) + db.update_channel(ch_id, "special_sources", sources) + await message.reply(format_bulk_report("🔍 نتيجة إضافة المصادر المخصصة", results)) + await show_special_sources_menu_from_message(message, ch_id) + elif state == "waiting_source_cleanup_add": + source_id = user_states[uid]["source_id"] + back = user_states[uid].get("back", "menu_public_src") + terms = split_terms_lines(text) + result = db.add_source_remove_terms(source_id, terms) if hasattr(db, "add_source_remove_terms") else {"added": 0, "exists": 0} + await message.reply( + f"✅ تمت إضافة {result.get('added', 0)} عنصر للتنظيف الذكي.\n⚠️ موجود مسبقاً/فارغ: {result.get('exists', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧹 رجوع للتنظيف الذكي", callback_data=f"clean_src|{source_id}|{back}")], + [InlineKeyboardButton("⚙️ إعدادات المصدر", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_source_cleanup_del": + source_id = user_states[uid]["source_id"] + back = user_states[uid].get("back", "menu_public_src") + terms = split_terms_lines(text) + result = db.remove_source_remove_terms(source_id, terms) if hasattr(db, "remove_source_remove_terms") else {"removed": 0, "missing": 0} + await message.reply( + f"✅ تم حذف {result.get('removed', 0)} عنصر من التنظيف الذكي.\n⚠️ غير موجود: {result.get('missing', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧹 رجوع للتنظيف الذكي", callback_data=f"clean_src|{source_id}|{back}")], + [InlineKeyboardButton("⚙️ إعدادات المصدر", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_global_cleanup_add": + terms = split_terms_lines(text) + result = db.add_global_remove_terms(terms) if hasattr(db, "add_global_remove_terms") else {"added": 0, "exists": 0} + await message.reply( + f"✅ تمت إضافة {result.get('added', 0)} عنصر لقائمة الحذف العامة.\n⚠️ موجود مسبقاً/فارغ: {result.get('exists', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧹 رجوع لقائمة الحذف العامة", callback_data="global_clean")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_global_cleanup_del": + terms = split_terms_lines(text) + result = db.remove_global_remove_terms(terms) if hasattr(db, "remove_global_remove_terms") else {"removed": 0, "missing": 0} + await message.reply( + f"✅ تم حذف {result.get('removed', 0)} عنصر من قائمة الحذف العامة.\n⚠️ غير موجود: {result.get('missing', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧹 رجوع لقائمة الحذف العامة", callback_data="global_clean")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_channel_delete_term_add": + logger.info(f"handle_text_input: waiting_channel_delete_term_add from user {uid}") + ch_id = user_states[uid]["ch_id"] + terms = split_terms_lines(text) + result = db.add_channel_delete_terms(ch_id, terms) + logger.info(f"waiting_channel_delete_term_add: channel={ch_id}, result={result}") + ch = db.get_channel(ch_id) + await message.reply( + f"✅ تمت إضافة {result.get('added', 0)} عنصر لقناة {entity_name(ch) if ch else ch_id}.\n⚠️ موجود مسبقاً/فارغ: {result.get('exists', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧹 رجوع لقائمة الكلمات المحذوفة", callback_data=f"chdelterms|{ch_id}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_channel_delete_term_del": + ch_id = user_states[uid]["ch_id"] + terms = split_terms_lines(text) + result = db.remove_channel_delete_terms(ch_id, terms) + ch = db.get_channel(ch_id) + await message.reply( + f"✅ تم حذف {result.get('removed', 0)} عنصر من قناة {entity_name(ch) if ch else ch_id}.\n⚠️ غير موجود: {result.get('missing', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧹 رجوع لقائمة الكلمات المحذوفة", callback_data=f"chdelterms|{ch_id}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_channel_speed": + ch_id = user_states[uid]["ch_id"] + value = text.strip() + if value in {"0", "افتراضي", "default", "DEFAULT", ""}: + ok = db.set_channel_publish_delay(ch_id, None) if hasattr(db, "set_channel_publish_delay") else False + msg = "✅ تم إرجاع سرعة القناة للوضع الافتراضي." + else: + try: + delay = max(0.0, float(value)) + ok = db.set_channel_publish_delay(ch_id, delay) if hasattr(db, "set_channel_publish_delay") else False + msg = f"✅ تم حفظ سرعة القناة: {delay} ثانية." + except Exception: + ok = False + msg = "❌ أرسل رقم بالثواني، أو 0 للوضع الافتراضي." + await message.reply(msg, reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("⏱ رجوع لسرعة النشر", callback_data=f"speedmenu_{ch_id}")], + [InlineKeyboardButton("⚙️ إعدادات القناة", callback_data=f"ch_{ch_id}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + elif state == "waiting_copy_source_settings": + from_source = user_states[uid]["source_id"] + back = user_states[uid].get("back", "menu_public_src") + targets = [] + failed = [] + for raw in split_bulk_lines(text): + try: + chat = await resolve_chat_info_timeout(raw, prefer_user=True) + meta = chat_meta(chat, raw) + db.update_source_meta(chat.id, **meta) if hasattr(db, "update_source_meta") else None + targets.append(int(chat.id)) + except Exception as e: + try: + targets.append(int(raw.strip())) + except Exception: + failed.append(f"{raw}: {e}") + copied = db.copy_source_settings(from_source, targets) if hasattr(db, "copy_source_settings") else 0 + msg = f"✅ تم نسخ إعدادات المصدر إلى {copied} مصدر." + if failed: + msg += "\n⚠️ فشل:\n" + "\n".join(failed[:10]) + await message.reply(msg, reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("⚙️ إعدادات المصدر", callback_data=f"srcset|{from_source}|{back}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + + elif state == "waiting_channel_hashtags_add": + ch_id = user_states[uid]["ch_id"] + terms = split_terms_lines(text) + result = db.add_channel_hashtags(ch_id, terms) if hasattr(db, "add_channel_hashtags") else {"added": 0, "exists": 0} + await message.reply( + f"✅ تمت إضافة {result.get('added', 0)} هاشتاك.\n⚠️ موجود مسبقاً/فارغ: {result.get('exists', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🏷 رجوع للهاشتاكات", callback_data=f"hashtags_{ch_id}")], + [InlineKeyboardButton("⚙️ إعدادات القناة", callback_data=f"ch_{ch_id}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_channel_hashtags_del": + ch_id = user_states[uid]["ch_id"] + terms = split_terms_lines(text) + result = db.remove_channel_hashtags(ch_id, terms) if hasattr(db, "remove_channel_hashtags") else {"removed": 0, "missing": 0} + await message.reply( + f"✅ تم حذف {result.get('removed', 0)} هاشتاك.\n⚠️ غير موجود: {result.get('missing', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🏷 رجوع للهاشتاكات", callback_data=f"hashtags_{ch_id}")], + [InlineKeyboardButton("⚙️ إعدادات القناة", callback_data=f"ch_{ch_id}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_named_backup": + name = text.strip() + path = db.create_named_backup(name) if hasattr(db, "create_named_backup") else "" + await message.reply( + f"✅ تم إنشاء Backup باسم:\n`{name}`\n\nالملف:\n`{path}`", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🛠 رجوع لإدارة التشغيل", callback_data="ops_menu")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ]) + ) + # Multi-Bot Expansion: Add Session + elif state == "waiting_session_add": + parts = [p.strip() for p in text.split("|", 2)] + if len(parts) < 3: + await message.reply("❌ التنسيق خطأ. استخدم:\n`API_ID | API_HASH | SESSION_STRING`") + return + api_id, api_hash, session_string = parts[0], parts[1], parts[2] + if not api_id.isdigit(): + await message.reply("❌ API_ID يجب أن يكون رقماً.") + return + ok = db.add_session(api_id, api_hash, session_string) + if ok: + await message.reply("✅ تمت إضافة الجلسة.", reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("📱 إدارة الجلسات", callback_data="sessions_list")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + else: + await message.reply("❌ فشل إضافة الجلسة. قد يكون المعرف موجوداً مسبقاً.") + # Multi-Bot Expansion: Add AI Key + elif state == "waiting_ai_key_add": + parts = [p.strip() for p in text.split("|", 1)] + if len(parts) < 2: + await message.reply("❌ التنسيق خطأ. استخدم:\n`المزود | المفتاح`\nمثال: `gemini | AIzaSy...`") + return + provider, api_key = parts[0], parts[1] + ok = db.add_ai_key(provider, api_key) + if ok: + await message.reply("✅ تمت إضافة مفتاح AI.", reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧠 إدارة المفاتيح", callback_data="ai_list")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + else: + await message.reply("❌ فشل إضافة المفتاح.") + # Multi-Bot Expansion: Add Publishing Bot + elif state == "waiting_bot_add": + token = text.strip() + if not db.bot_manager.validate_token_format(token): + await message.reply("❌ التوكن غير صالح. يجب أن يحتوي على `:`") + return + # تحقق فوري من صحة التوكن عبر Telegram API + ver = await verifier.validate_token(token) + if not ver.get("valid"): + await message.reply(f"❌ التوكن غير صالح: {ver.get('error', 'فشل الاتصال')}") + return + bot_username = ver.get("username", "") + bot_name = ver.get("first_name", "") + ok = db.bot_manager.add_bot(token, username=bot_username, name=bot_name) if hasattr(db, "bot_manager") else db.add_publishing_bot(token, username=bot_username, name=bot_name) + if ok: + # مسح الكاش لهذا التوكن لأنه جديد + if hasattr(db, "cache_invalidate"): + db.cache_invalidate(f"token_valid|{token[:10]}") + await message.reply("✅ تمت إضافة بوت النشر.", reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🤖 إدارة البوتات", callback_data="bots_list")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + else: + await message.reply("❌ فشل إضافة البوت.") + elif state == "waiting_bot_rename": + bid = user_states[uid].get("bot_id", "") + new_name = text.strip() + if new_name: + db.update_publishing_bot(bid, name=new_name) + await message.reply("✅ تم تحديث الاسم.", reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🤖 رجوع", callback_data=f"bot_show_{bid}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + else: + await message.reply("❌ الاسم فارغ.") + # Multi-Bot Expansion: Add Website + elif state == "waiting_website_add": + parts = [p.strip() for p in text.split("|", 1)] + url = parts[0] + selector = parts[1] if len(parts) > 1 else "body" + if not url.startswith("http"): + await message.reply("❌ الرابط يجب أن يبدأ بـ http:// أو https://") + return + ok = db.add_website(url, selector=selector) + if ok: + await message.reply("✅ تمت إضافة الموقع.", reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🌐 إدارة المواقع", callback_data="web_list")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + else: + await message.reply("❌ فشل إضافة الموقع.") + # Multi-Bot Expansion: Edit Website + elif state == "waiting_website_edit": + wid = user_states[uid].get("website_id", "") + parts = [p.strip() for p in text.split("|", 1)] + url = parts[0] + selector = parts[1] if len(parts) > 1 else "body" + if not url.startswith("http"): + await message.reply("❌ الرابط يجب أن يبدأ بـ http:// أو https://") + return + ok = db.update_website(wid, url=url, selector=selector) + if ok: + await message.reply("✅ تم تحديث الموقع.", reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🌐 رجوع للموقع", callback_data=f"web_show_{wid}")], + [InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ])) + else: + await message.reply("❌ فشل تحديث الموقع.") + except Exception as e: + logger.error(f"خطأ في إدخال المستخدم: {e}") + await message.reply(f"❌ فشل التنفيذ: {e}") + finally: + user_states.pop(uid, None) + +def _to_int_set(values): + result = set() + for value in values or []: + try: + result.add(int(value)) + except Exception: + pass + return result + + +def get_special_source_map(): + """يرجع خريطة المصادر الخاصة: source_id -> set(channel_ids).""" + mapping = {} + for ch in db.get_all_channels(): + if ch.get("paused"): + continue + try: + ch_id = int(ch["id"]) + except Exception: + continue + for src in ch.get("special_sources") or []: + try: + src_id = int(src) + except Exception: + continue + mapping.setdefault(src_id, set()).add(ch_id) + return mapping + + +def get_polling_sources(): + """يجمع مصادر الفحص: المصادر العامة + المصادر الخاصة، بدون تكرار.""" + sources = set() + for src in db.get_public_sources() or []: + try: + sources.add(int(src)) + except Exception: + pass + for src in get_special_source_map().keys(): + sources.add(int(src)) + return sorted(sources) + + +def source_kind_label(source_id): + """نوع المصدر للّوج: خاص يغلب على العام إذا مضاف بالمكانين.""" + source_id = int(source_id) + if source_id in get_special_source_map(): + return "خاص" + if source_id in _to_int_set(db.get_public_sources()): + return "عام" + return "غير معروف" + + +def get_targets_for_source(source_id): + """يرجع قنوات النشر التي يجب أن تستقبل منشوراً من هذا المصدر. + + القاعدة: + - إذا المصدر مضاف كمصدر خاص لأي قناة: ينشر فقط للقنوات التي أضافته. + - إذا المصدر عام فقط: ينشر فقط للقنوات العامة التي لا تحتوي مصادر خاصة. + - إذا المصدر موجود بالعام والخاص بالغلط: الخاص يغلب. + """ + source_id = int(source_id) + all_channels = db.get_all_channels() + public_sources = _to_int_set(db.get_public_sources()) + special_map = get_special_source_map() + target_ids = set() + + # الخاص يغلب على العام + if source_id in special_map: + target_ids.update(special_map.get(source_id, set())) + logger.info(f"🟢 المصدر {source_id} خاص؛ القنوات المستهدفة: {sorted(target_ids)}") + return target_ids + + # مصدر عام: فقط القنوات التي لا تمتلك مصادر خاصة + if source_id in public_sources: + for ch in all_channels: + if ch.get("paused"): + continue + specials = ch.get("special_sources") or [] + if specials: + continue + try: + target_ids.add(int(ch["id"])) + except Exception as e: + logger.error(f"تعذر تحويل قناة النشر إلى رقم: {ch.get('id')} | {e}") + return target_ids + + return target_ids + + +def blocked_word_in_text(text): + if not text: + return None + for word in db.get_blocked_words(): + if word and word in text: + return word + return None + + +def section_scope_for_channel(channel_id): + """معرف قسم/قناة النشر المستخدم لنطاق Dedup المشترك. القسم الجديد ينشأ تلقائياً.""" + return f"ch_{int(channel_id)}" + + +def section_label_for_channel(channel_id): + """تسمية القسم لأغراض اللوج (اسم القناة)، بدون أي Secrets.""" + try: + ch = db.get_channel(channel_id) + if ch and ch.get("name"): + return str(ch["name"]).strip()[:40] + except Exception: + pass + return str(channel_id) + + +def scopes_for_source(source_id): + """نطاقات Dedup التي ينشر إليها المصدر (واحد لكل قناة نشر).""" + return [section_scope_for_channel(t) for t in sorted(get_targets_for_source(source_id))] + + +def check_global_blocked_words_raw(raw_text, channel_ids=None): + """يفحص الكلمات المحظورة على النص الخام قبل أي تنظيف أو معالجة. + يطبق القائمة العامة، ثم قوائم القنوات المستهدفة فقط حتى لا يؤثر إعداد قسم + على قسم آخر. يرجع الكلمة المحظورة أو None، ولا يستدعي أي AI.""" + if not raw_text: + return None + for word in (db.get_blocked_words() if hasattr(db, "get_blocked_words") else []): + if word and word in raw_text: + return word + if not channel_ids or not hasattr(db, "get_channel_blocked_words"): + return None + try: + seen = set() + for channel_id in channel_ids: + if channel_id in seen: + continue + seen.add(channel_id) + for word in db.get_channel_blocked_words(channel_id) or []: + if word and word in raw_text: + return word + except Exception: + pass + return None + + +def unsupported_media_reason(message): + """يرجع سبب التجاهل إذا كان المنشور يحتوي ملصق أو صورة متحركة/GIF.""" + if getattr(message, "sticker", None): + return "ملصق" + if getattr(message, "animation", None): + return "صورة متحركة / GIF" + return None + + +def mark_middle_auto_forward_window(seconds=4): + """يمنع middle_channel_handler من نشر النسخة التي وصلت للوسيطة تلقائياً حتى لا تتكرر.""" + global _middle_auto_ignore_until + _middle_auto_ignore_until = max(_middle_auto_ignore_until, time.monotonic() + seconds) + + +def is_middle_auto_forward_window_active(): + return time.monotonic() <= _middle_auto_ignore_until + + +async def publish_source_message(message, source_id, origin="updates"): + raw_text = message.text or message.caption or "" + source_id = int(source_id) + content_type = content_type_for_message(message) + message_id = getattr(message, "id", None) + + # تحديد القنوات المستهدفة فقط لتطبيق قوائم الحظر الخاصة بها؛ لا توجد معالجة للنص هنا. + target_ids = get_targets_for_source(source_id) + raw_blocked_word = check_global_blocked_words_raw(raw_text, channel_ids=target_ids) + if raw_blocked_word: + logger.info(f"⛔ Blocked before processing: blocked_word='{raw_blocked_word}' source={source_id} message_id={message_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "rejected", f"blocked before processing: {raw_blocked_word}", message_id) + return True + + if hasattr(db, "is_maintenance_mode") and db.is_maintenance_mode(): + logger.info(f"🛠️ [{origin}] وضع الصيانة مفعل؛ تم تجاهل النشر وتحديث آخر رسالة للمصدر {source_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "maintenance mode", getattr(message, "id", None)) + return True + + if is_source_paused(source_id): + logger.info(f"⏸️ [{origin}] مصدر موقوف تم تجاهله: {source_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "source paused", getattr(message, "id", None)) + return True + + if not is_content_allowed_for_source(source_id, content_type): + logger.info(f"⛔ [{origin}] تم تجاهل منشور من {source_id} بسبب فلتر نوع المحتوى: {content_type}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", f"content type blocked: {content_type}", getattr(message, "id", None)) + return True + + if not target_ids: + logger.info("🟡 لا توجد قنوات مستهدفة لهذا المصدر، تم اعتبار المنشور معالجاً حتى لا يتكرر.") + return True + + raw_text = full_clean_text(raw_text, source_id=source_id) + logger.info(f"📨 [{origin}] رسالة من {source_id} | type={content_type} | message_id={message_id} | نص: {str(raw_text)[:80]}...") + + # كلمات الحذف الخاصة بالمصدر/القناة تُطبق قبل Dedup، بينما قالب النشر والروابط + # الخاصة بالقناة لا تدخل في هوية الحدث. + dedup_text_by_target = { + target: prepare_dedup_text(raw_text, source_id=source_id, channel_id=target) + for target in target_ids + } + + # حجز ذري لنفس رسالة المصدر بعد المحظورات وكلمات الحذف، وقبل Dedup والنشر. + # المساران updates وpolling يتنافسان هنا؛ الخاسر يخرج ولا ينشر. + if message_id is not None and hasattr(db, "claim_source_event"): + try: + claimed_now = db.claim_source_event(source_id, message_id) + except Exception as exc: + logger.exception(f"فشل claim للحدث؛ تم إيقاف النشر الآمن: source={source_id} message_id={message_id}: {exc}") + return False + if not claimed_now: + logger.info(f"🔒 [{origin}] الحدث محجوز مسبقاً من مسار آخر: source={source_id} message_id={message_id} — تم إيقاف المسار الخاسر") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "duplicate", "source event claim lost", message_id) + return True + + if message_id is not None and hasattr(db, "has_recent_source_event"): + try: + if db.has_recent_source_event(source_id, message_id): + logger.info(f"🔁 [{origin}] نفس الحدث من المصدر {source_id} تمت معالجته سابقاً: message_id={message_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "duplicate", "same source event", message_id) + return True + except Exception: + pass + + # ملاحظة: فحص الكلمة المحظورة الخاص بكل قناة ما زال يتم على حدة داخل حلقة + # الإرسال أدناه (عبر clean_text_for_source)، لأن كل قناة لها قائمتها المستقلة. + + unsupported_reason = unsupported_media_reason(message) + if unsupported_reason: + logger.info(f"⛔ تم تجاهل المنشور لأنه يحتوي {unsupported_reason}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", f"unsupported: {unsupported_reason}", getattr(message, "id", None)) + return True + + if raw_text: + if message.media: + duplicated, duplicate_score = is_smart_duplicate(raw_text, threshold=0.75) + duplicate_reason = "similarity" + else: + # Dedup مشترك حسب القسم: المقارنة مع النص بعد كلمات الحذف وقبل قالب النشر. + duplicated = False + duplicate_reason = "none" + duplicate_score = 0.0 + for target in sorted(target_ids): + candidate_text = dedup_text_by_target.get(target, "") + if not candidate_text: + continue + scope_id = section_scope_for_channel(target) + duplicated, duplicate_reason, duplicate_score = is_hybrid_news_duplicate( + candidate_text, source_id=source_id, message_id=message_id, threshold=0.75, scope_id=scope_id + ) + if duplicated: + event_fp = make_event_fp(candidate_text) + logger.info(f"🔁 Duplicate detected: scope={section_label_for_channel(target)} reason={duplicate_reason} score={duplicate_score:.3f} source={source_id} message_id={message_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "duplicate", f"section:{duplicate_reason}", message_id) + return True + # حجز ذري وقائي للنص الجديد في هذا القسم (يمنع سباق المصادر المختلفة). + event_fp = make_event_fp(candidate_text) + if not check_section_claim(scope_id, event_fp or f"fp:new:{message_id}"): + logger.info(f"🔁 [{origin}] الخبر محجوز مسبقاً في قسم {section_label_for_channel(target)} من مصدر آخر: source={source_id} message_id={message_id}") + duplicated = True + break + if duplicated: + return True + logger.info(f"✅ New event accepted: scopes={[section_label_for_channel(t) for t in target_ids]} source={source_id} message_id={message_id}") + + # تسجيل الحدث "مستلم" بعد اجتياز فحوصات التكرار — + # تسجيله قبل الفحص كان يجعل أول منشور نصي يُكتشف كمكرر لنفسه. + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "received", content_type, message_id) + + if message.media: + try: + mark_middle_auto_forward_window() + fwd = await forward_to_middle(message.chat.id, message.id) + mark_middle_auto_forward_window() + await asyncio.sleep(0.5) + middle_messages = fwd if isinstance(fwd, list) else [fwd] + middle_messages = [m for m in middle_messages if m] + logger.info(f"✅ تم تمرير منشور ميديا إلى الوسيطة | ids={[m.id for m in middle_messages]}") + except Exception as e: + logger.error(f"فشل التوجيه للوسيطة من المصدر {source_id}: {e}") + if hasattr(db, "release_source_event_claim") and message_id is not None: + db.release_source_event_claim(source_id, message_id) + await notify_admins(f"فشل توجيه رسالة من {source_id} إلى الوسيطة: {e}") + return False + + any_success = False + any_logical_rejection = False + for target in target_ids: + try: + ch = db.get_channel(target) + if not ch: + logger.warning(f"القناة {target} غير موجودة في قاعدة البيانات") + continue + + if not await _verify_channel_before_publish(target): + logger.warning(f"⛔ القناة {target} غير قابلة للوصول، تم تخطيها") + continue + + cleaned = clean_text_for_source(raw_text, source_id, channel_id=target) + if cleaned is None: + logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة") + any_logical_rejection = True + continue + final = compose_channel_post_text(cleaned, target, ch.get("tail", "")) + formatted_caption, parse_mode, caption_entities = format_outgoing_payload_for_channel(final, target, content_type, news_text=cleaned, tail=ch.get("tail", "")) if final else (None, None, None) + ok = await copy_middle_messages_to_target(target, middle_messages, formatted_caption, parse_mode=parse_mode, content_type=content_type, caption_entities=caption_entities) + if ok: + db.increment_post_count(target) + record_channel_success(target) + any_success = True + await asyncio.sleep(get_publish_delay_for_channel(target)) + + except Exception as e: + logger.error(f"نشر فاشل إلى {target}: {e}") + await record_channel_failure_and_maybe_alert(target, e) + await notify_admins(f"فشل النشر إلى {target}: {e}") + + if any_success and raw_text: + for target in target_ids: + remember_published_text( + dedup_text_by_target.get(target) or raw_text, + source_id=source_id, message_id=message_id, + scope_id=section_scope_for_channel(target), section_label=section_label_for_channel(target), + ) + if not any_success and not any_logical_rejection and hasattr(db, "release_source_event_claim") and message_id is not None: + db.release_source_event_claim(source_id, message_id) + processed = any_success or any_logical_rejection + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "published" if any_success else "rejected" if any_logical_rejection else "error", "media" if any_success else "media publish failed" if not any_logical_rejection else "media rejected", getattr(message, "id", None), len(target_ids)) + if any_logical_rejection and not any_success: + logger.info("✅ تم رفض المنشور منطقياً في كل القنوات، تم اعتباره معالجاً لتحديث last_seen.") + return processed + + else: + any_success = False + any_logical_rejection = False + for target in target_ids: + try: + ch = db.get_channel(target) + if not ch: + logger.warning(f"القناة {target} غير موجودة في قاعدة البيانات") + continue + + if not await _verify_channel_before_publish(target): + logger.warning(f"⛔ القناة {target} غير قابلة للوصول، تم تخطيها") + continue + + cleaned = clean_text_for_source(raw_text, source_id, channel_id=target) + if cleaned is None: + logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة") + any_logical_rejection = True + continue + if raw_text and should_ignore_short_post_for_channel(cleaned, target): + logger.info(f"⛔ منشور قصير مرفوض للقناة {target}") + any_logical_rejection = True + continue + + final = compose_channel_post_text(cleaned, target, ch.get("tail", "")) + + if final: + try: + await hydrate_publish_channel(target) + except Exception as e: + logger.warning(f"⚠️ فشل تهيئة قناة النشر {target} قبل النص: {e}") + formatted, parse_mode, entities = format_outgoing_payload_for_channel(final, target, "text", news_text=cleaned, tail=ch.get("tail", "")) + sent_msg = await safe_send_channel_message(target, formatted, parse_mode=parse_mode, entities=entities) + if hasattr(db, "record_published_message") and getattr(sent_msg, "id", None): + db.record_published_message(target, sent_msg.id, "text") + else: + logger.info("🟡 منشور نصي فارغ بعد التنظيف؛ لن يتم إرساله.") + continue + + db.increment_post_count(target) + record_channel_success(target) + any_success = True + logger.info(f"✅ نُشر نص إلى {target}") + await asyncio.sleep(get_publish_delay_for_channel(target)) + + except Exception as e: + logger.error(f"إرسال فاشل إلى {target}: {e}") + await record_channel_failure_and_maybe_alert(target, e) + await notify_admins(f"فشل الإرسال إلى {target}: {e}") + + if any_success and raw_text: + for target in target_ids: + remember_published_text( + dedup_text_by_target.get(target) or raw_text, + source_id=source_id, message_id=message_id, + scope_id=section_scope_for_channel(target), section_label=section_label_for_channel(target), + ) + if not any_success and not any_logical_rejection and hasattr(db, "release_source_event_claim") and message_id is not None: + db.release_source_event_claim(source_id, message_id) + processed = any_success or any_logical_rejection + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "published" if any_success else "rejected" if any_logical_rejection else "error", "text" if any_success else "text publish failed" if not any_logical_rejection else "text rejected", getattr(message, "id", None), len(target_ids)) + if any_logical_rejection and not any_success: + logger.info("✅ تم رفض النص منطقياً في كل القنوات، تم اعتباره معالجاً لتحديث last_seen.") + return processed + + +async def publish_source_album(messages, source_id, origin="polling"): + """ينشر مجموعة ميديا من المصدر إلى الوسيطة ثم إلى قنوات النشر بنفس ترتيب الرسائل.""" + if not messages: + return True + + messages = sorted(messages, key=lambda m: m.id) + first = messages[0] + raw_text = first.caption or first.text or "" + source_id = int(source_id) + content_type = "album" + + if hasattr(db, "is_maintenance_mode") and db.is_maintenance_mode(): + logger.info(f"🛠️ [{origin}] وضع الصيانة مفعل؛ تم تجاهل الألبوم وتحديث آخر رسالة للمصدر {source_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "maintenance mode", getattr(first, "id", None)) + return True + + if is_source_paused(source_id): + logger.info(f"⏸️ [{origin}] مصدر موقوف تم تجاهله: {source_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "source paused", ids[-1] if 'ids' in locals() and ids else None) + return True + + if not is_content_allowed_for_source(source_id, content_type): + logger.info(f"⛔ [{origin}] تم تجاهل ألبوم من {source_id} بسبب فلتر نوع المحتوى") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "content type blocked: album", ids[-1] if 'ids' in locals() and ids else None) + return True + + # Early reject: فحص الكلمات المحظورة على النص الخام قبل أي معالجة (مثل النصوص). + raw_album_blocked = check_global_blocked_words_raw(raw_text) + if raw_album_blocked: + logger.info(f"⛔ Blocked before processing: blocked_word='{raw_album_blocked}' source={source_id} album") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "rejected", f"blocked before processing: {raw_album_blocked}", getattr(first, "id", None)) + return True + + raw_text = full_clean_text(raw_text, source_id=source_id) + ids = [m.id for m in messages] + + album_event_id = ids[-1] if ids else None + + # حجز ذري دائم للألبوم (source_id:last_message_id) قبل أي فحص أو نشر — + # يغلق تكرار الألبوم بين مسار updates وpolling ومنع سباق TOCTOU. + if album_event_id is not None and hasattr(db, "claim_source_event"): + try: + album_claimed_now = db.claim_source_event(source_id, album_event_id) + except Exception as exc: + logger.exception(f"فشل claim للألبوم؛ تم إيقاف النشر الآمن: source={source_id} message_id={album_event_id}: {exc}") + return False + if not album_claimed_now: + logger.info(f"🔒 [{origin}] الألبوم محجوز مسبقاً من مسار آخر: source={source_id} message_id={album_event_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "duplicate", "album event already claimed", album_event_id) + return True + + if album_event_id is not None and hasattr(db, "has_recent_source_event"): + try: + if db.has_recent_source_event(source_id, album_event_id): + logger.info(f"🔁 [{origin}] نفس الألبوم من المصدر {source_id} تمت معالجته سابقاً: message_id={album_event_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "duplicate", "same source album event", album_event_id) + return True + except Exception: + pass + + logger.info(f"📨 [{origin}] ألبوم من {source_id} | message_ids={ids} | نص: {str(raw_text)[:80]}...") + + target_ids = get_targets_for_source(source_id) + if not target_ids: + logger.info("🟡 لا توجد قنوات مستهدفة لهذا الألبوم، تم اعتباره معالجاً حتى لا يتكرر.") + return True + + # كلمات الحذف الخاصة بالمصدر/القناة تُطبق قبل Dedup، بينما قالب النشر لا يدخل في البصمة. + dedup_text_by_target = { + target: prepare_dedup_text(raw_text, source_id=source_id, channel_id=target) + for target in target_ids + } + + for item in messages: + unsupported_reason = unsupported_media_reason(item) + if unsupported_reason: + logger.info(f"⛔ تم تجاهل الألبوم لأنه يحتوي {unsupported_reason}") + return True + + if raw_text: + # Dedup مشترك حسب القسم: المقارنة مع نطاق كل قناة نشر مستهدفة (48 ساعة). + target_ids_for_dedup = get_targets_for_source(source_id) + duplicated = False + for target in sorted(target_ids_for_dedup): + candidate_text = dedup_text_by_target.get(target, "") + if not candidate_text: + continue + scope_id = section_scope_for_channel(target) + duplicated, dup_reason, dup_score = is_hybrid_news_duplicate( + candidate_text, source_id=source_id, message_id=album_event_id, threshold=0.75, scope_id=scope_id + ) + if duplicated: + event_fp = make_event_fp(candidate_text) + claim_won = check_section_claim(scope_id, event_fp or f"fp:{dup_reason}") + logger.info(f"🔁 Duplicate detected: scope={section_label_for_channel(target)} reason={dup_reason} source={source_id} album claim_won={claim_won}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "duplicate", f"section:{dup_reason}", album_event_id) + return True + event_fp = make_event_fp(candidate_text) + if not check_section_claim(scope_id, event_fp or f"fp:new:{album_event_id}"): + logger.info(f"🔁 [{origin}] ألبوم محجوز مسبقاً في قسم {section_label_for_channel(target)} من مصدر آخر: source={source_id}") + duplicated = True + break + if duplicated: + return True + logger.info(f"✅ New album accepted: scopes={[section_label_for_channel(t) for t in target_ids_for_dedup]} source={source_id}") + + # تسجيل الألبوم "مستلم" بعد اجتياز فحوصات التكرار. + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "received", "album", album_event_id) + + try: + mark_middle_auto_forward_window() + fwd = await forward_to_middle(source_id, ids) + mark_middle_auto_forward_window() + await asyncio.sleep(0.8) + middle_messages = fwd if isinstance(fwd, list) else [fwd] + middle_messages = sorted([m for m in middle_messages if m], key=lambda m: m.id) + logger.info(f"✅ تم تمرير الألبوم إلى الوسيطة | middle_ids={[m.id for m in middle_messages]}") + except Exception as e: + logger.error(f"فشل توجيه الألبوم للوسيطة من المصدر {source_id}: {e}") + if hasattr(db, "release_source_event_claim") and album_event_id is not None: + db.release_source_event_claim(source_id, album_event_id) + await notify_admins(f"فشل توجيه ألبوم من {source_id} إلى الوسيطة: {e}") + return False + + any_success = False + for target in target_ids: + try: + ch = db.get_channel(target) + if not ch: + logger.warning(f"القناة {target} غير موجودة في قاعدة البيانات") + continue + + if not await _verify_channel_before_publish(target): + logger.warning(f"⛔ القناة {target} غير قابلة للوصول، تم تخطي الألبوم") + continue + + cleaned = clean_text_for_source(raw_text, source_id, channel_id=target) + if cleaned is None: + logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة") + continue + final = compose_channel_post_text(cleaned, target, ch.get("tail", "")) + formatted_caption, parse_mode, caption_entities = format_outgoing_payload_for_channel(final, target, "album", news_text=cleaned, tail=ch.get("tail", "")) if final else (None, None, None) + ok = await copy_middle_messages_to_target(target, middle_messages, formatted_caption, parse_mode=parse_mode, content_type=content_type, caption_entities=caption_entities) + if ok: + db.increment_post_count(target) + record_channel_success(target) + any_success = True + await asyncio.sleep(get_publish_delay_for_channel(target)) + + except Exception as e: + logger.error(f"نشر الألبوم فاشل إلى {target}: {e}") + await record_channel_failure_and_maybe_alert(target, e) + await notify_admins(f"فشل نشر ألبوم إلى {target}: {e}") + + if any_success and raw_text: + for target in target_ids: + remember_published_text( + dedup_text_by_target.get(target) or raw_text, source_id=source_id, message_id=album_event_id, + scope_id=section_scope_for_channel(target), section_label=section_label_for_channel(target), + ) + if not any_success and hasattr(db, "release_source_event_claim") and album_event_id is not None: + db.release_source_event_claim(source_id, album_event_id) + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "published" if any_success else "error", "album" if any_success else "album publish failed", album_event_id, len(target_ids)) + if not any_success: + logger.warning(f"⚠️ تم تمرير الألبوم للوسيطة لكن فشل نشره للقنوات. سيبقى قابلاً لإعادة المحاولة: {getattr(first, 'media_group_id', '')}") + return True + + +async def user_message_handler(client, message): + pass # log muted: user update received + + if not message.chat or message.chat.type not in ("channel", "supergroup"): + return + + await publish_source_message(message, int(message.chat.id), origin="updates") + + +async def poll_public_sources_loop(): + """يفحص المصادر العامة والخاصة دورياً، لأن Updates لا تصل أحياناً على Hugging Face.""" + await asyncio.sleep(8) + logger.info("🔁 بدأ نظام الفحص الدوري للمصادر العامة والخاصة Polling") + + while True: + try: + mark_runtime_activity("poll") + poll_sources = get_polling_sources() + if not poll_sources: + await asyncio.sleep(25) + continue + + for source in poll_sources: + try: + source_id = int(source) + except Exception: + logger.warning(f"مصدر غير رقمي تم تجاهله: {source}") + continue + + kind = source_kind_label(source_id) + + if is_source_paused(source_id): + continue + + try: + last_seen = db.get_last_source_message(source_id) + messages = [] + + async for msg in user_client.get_chat_history(source_id, limit=8): + if not msg or not getattr(msg, "id", None): + continue + messages.append(msg) + mark_runtime_activity("poll") + + if not messages: + continue + + newest_id = max(m.id for m in messages) + + if last_seen is None: + db.set_last_source_message(source_id, newest_id) + logger.info(f"🔁 [{kind}] المصدر {source_id}: أول تشغيل، تم حفظ آخر رسالة {newest_id} بدون نشر القديم.") + continue + + new_messages = [m for m in messages if m.id > int(last_seen)] + new_messages.sort(key=lambda m: m.id) + + if not new_messages: + continue + + logger.info(f"🔁 [{kind}] المصدر {source_id}: تم العثور على {len(new_messages)} منشور جديد.") + + processed_ids = set() + i = 0 + while i < len(new_messages): + msg = new_messages[i] + if msg.id in processed_ids: + i += 1 + continue + + media_group_id = getattr(msg, "media_group_id", None) + origin = f"polling][{kind}" + + if media_group_id: + group = [m for m in new_messages if getattr(m, "media_group_id", None) == media_group_id] + group.sort(key=lambda m: m.id) + ok = await publish_source_album(group, source_id, origin=origin) + if ok: + for gm in group: + processed_ids.add(gm.id) + db.set_last_source_message(source_id, max(gm.id for gm in group)) + else: + logger.warning(f"⚠️ لم يتم تحديث last_seen للألبوم {media_group_id} حتى يعاد المحاولة لاحقاً") + await asyncio.sleep(1) + else: + ok = await publish_source_message(msg, source_id, origin=origin) + if ok: + processed_ids.add(msg.id) + db.set_last_source_message(source_id, msg.id) + else: + logger.warning(f"⚠️ لم يتم تحديث last_seen للرسالة {msg.id} حتى تعاد المحاولة لاحقاً") + await asyncio.sleep(1) + i += 1 + + except Exception as e: + logger.exception(f"خطأ أثناء فحص المصدر [{kind}] {source}: {e}") + if is_transient_network_error(e): + await reconnect_user_client_if_needed(e) + await asyncio.sleep(10) + else: + await notify_admins(f"فشل فحص المصدر [{kind}] {source}: {e}") + + await asyncio.sleep(25) + + except Exception as e: + logger.exception(f"خطأ عام في حلقة Polling: {e}") + await asyncio.sleep(30) + + +async def publish_middle_messages_to_all(middle_messages): + """ينشر منشوراً أو ألبوماً منشوراً يدوياً في الوسيطة إلى كل قنوات النشر.""" + if not isinstance(middle_messages, (list, tuple)): + middle_messages = [middle_messages] + middle_messages = sorted([m for m in middle_messages if m], key=lambda m: m.id) + if not middle_messages: + return + + first = middle_messages[0] + raw_text = full_clean_text(first.text or first.caption or "") + + if hasattr(db, "is_maintenance_mode") and db.is_maintenance_mode(): + logger.info("🛠️ وضع الصيانة مفعل؛ تم تجاهل النشر اليدوي من الوسيطة.") + return + + for item in middle_messages: + unsupported_reason = unsupported_media_reason(item) + if unsupported_reason: + logger.info(f"⛔ تم تجاهل رسالة الوسيطة لأنها تحتوي {unsupported_reason}") + return + + # فحص الكلمة المحظورة صار لكل قناة على حدة داخل الحلقة أدناه (clean_text(channel_id=target)). + + all_channels = db.get_all_channels() + is_album = len(middle_messages) > 1 + + for ch in all_channels: + if ch.get("paused"): + continue + + target = int(ch["id"]) + + if not await _verify_channel_before_publish(target): + logger.warning(f"⛔ القناة {target} غير قابلة للوصول، تم تخطي النشر اليدوي") + continue + + try: + cleaned = clean_text(raw_text, channel_id=target) if raw_text else "" + if cleaned is None: + continue + if raw_text and not is_album and not first.media and should_ignore_short_post_for_channel(cleaned, target): + logger.info(f"⛔ منشور وسيطة قصير مرفوض للقناة {target}") + continue + + final = compose_channel_post_text(cleaned, target, ch.get("tail", "")) + + if is_album: + formatted_caption, parse_mode, caption_entities = format_outgoing_payload_for_channel(final, target, "album", news_text=cleaned, tail=ch.get("tail", "")) if final else (None, None, None) + ok = await copy_middle_messages_to_target(target, middle_messages, formatted_caption, parse_mode=parse_mode, content_type="album", caption_entities=caption_entities) + if not ok: + continue + elif first.media: + try: + await hydrate_publish_channel(target) + except Exception as e: + logger.warning(f"⚠️ فشل تهيئة قناة النشر {target} قبل نسخة الوسيطة: {e}") + middle_ctype = published_content_type_for_message(first, False) + formatted_caption, parse_mode, caption_entities = format_outgoing_payload_for_channel(final, target, middle_ctype, news_text=cleaned, tail=ch.get("tail", "")) if final else (None, None, None) + copy_kwargs = dict( + chat_id=target, + from_chat_id=config.MIDDLE_CHANNEL, + message_id=first.id, + caption=formatted_caption if formatted_caption else None, + parse_mode=None if caption_entities else parse_mode + ) + if caption_entities: + copy_kwargs["caption_entities"] = caption_entities + try: + sent = await _retry_on_flood(lambda: bot_client.copy_message(**copy_kwargs), label=f"middle→{target}") + except TypeError: + copy_kwargs.pop("caption_entities", None) + copy_kwargs["parse_mode"] = parse_mode + sent = await bot_client.copy_message(**copy_kwargs) + sent_msg = sent + if hasattr(db, "record_published_message") and getattr(sent_msg, "id", None): + db.record_published_message(target, sent_msg.id, published_content_type_for_message(first, False)) + else: + try: + await hydrate_publish_channel(target) + except Exception as e: + logger.warning(f"⚠️ فشل تهيئة قناة النشر {target} قبل نص الوسيطة: {e}") + formatted, parse_mode, entities = format_outgoing_payload_for_channel(final if final else ".", target, "text", news_text=cleaned, tail=ch.get("tail", "")) + sent_msg = await safe_send_channel_message(target, formatted, parse_mode=parse_mode, entities=entities) + if hasattr(db, "record_published_message") and getattr(sent_msg, "id", None): + db.record_published_message(target, sent_msg.id, "text") + + db.increment_post_count(target) + record_channel_success(target) + mark_runtime_activity("publish") + logger.info(f"✅ نُشر من الوسيطة إلى {target}") + await asyncio.sleep(get_publish_delay_for_channel(target)) + + except Exception as e: + logger.error(f"نشر فاشل من الوسيطة إلى {target}: {e}") + await record_channel_failure_and_maybe_alert(target, e) + await notify_admins(f"فشل النشر من الوسيطة إلى {target}: {e}") + + +async def flush_middle_album(media_group_id): + """يجمع ألبوم الوسيطة اليدوي ثم ينشره كألبوم واحد.""" + await asyncio.sleep(2.0) + messages = _middle_album_buffers.pop(media_group_id, []) + _middle_album_tasks.pop(media_group_id, None) + if not messages: + return + logger.info(f"📥 ألبوم في الوسيطة، جارٍ النشر كألبوم واحد | count={len(messages)}") + await publish_middle_messages_to_all(messages) + + +async def middle_channel_handler(client, message): + if int(message.chat.id) != int(config.MIDDLE_CHANNEL): + return + + if is_middle_auto_forward_window_active(): + logger.info(f"🟡 تم تجاهل رسالة وسيطة تلقائية لمنع التكرار | message_id={message.id}") + return + + media_group_id = getattr(message, "media_group_id", None) + if media_group_id: + key = str(media_group_id) + _middle_album_buffers.setdefault(key, []).append(message) + if key not in _middle_album_tasks: + _middle_album_tasks[key] = asyncio.create_task(flush_middle_album(key)) + return + + logger.info("📥 رسالة في الوسيطة، جارٍ النشر...") + await publish_middle_messages_to_all([message]) + +# ============================================================ +# Multi-Bot Expansion: Secrets Management UI +# ============================================================ + +async def secrets_menu(client, callback): + text = "🔐 **الأسرار والإعدادات**\n\n📱 الجلسات: حسابات Telegram المستخدمة للقراءة.\n🤖 بوتات النشر: البوتات التي تنشر في القنوات.\n🧠 مفاتيح AI: مزودو الذكاء الاصطناعي ومفاتيحهم.\n🌐 مواقع الويب: مصادر الجلب عبر الروابط.\n🗑 سلة المحذوفات: استعادة أو حذف العناصر نهائياً." + buttons = [ + [InlineKeyboardButton("📱 الجلسات", callback_data="sessions_list"), InlineKeyboardButton("🤖 بوتات النشر", callback_data="bots_list")], + [InlineKeyboardButton("🧠 مفاتيح AI", callback_data="ai_list"), InlineKeyboardButton("🌐 مواقع الويب", callback_data="web_list")], + [InlineKeyboardButton("🗑 سلة المحذوفات", callback_data="trash_menu")], + nav_row("main_menu"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def _show_secrets_list(client, callback, items, title, add_cb, item_cb_prefix, toggle_prefix, del_prefix, test_prefix, kind=""): + if not items: + text = f"{title}\n\nلا توجد عناصر." + buttons = [[InlineKeyboardButton("➕ إضافة", callback_data=add_cb)], nav_row("secrets_menu")] + else: + text = f"{title} ({len(items)}):\n\n✅ العناصر المفعلة تعمل في النشر أو الجلب.\n❌ العناصر المعطلة محفوظة لكنها لا تعمل حالياً.\n" + btns = [] + for item in items: + name = item.get("name", item.get("id", "")) + enabled = "✅" if item.get("enabled", True) else "❌" + btns.append(InlineKeyboardButton(f"{enabled} {name}", callback_data=f"{item_cb_prefix}{item.get('id')}")) + rows = grid_buttons(btns, 2) + rows.append([InlineKeyboardButton("➕ إضافة", callback_data=add_cb)]) + rows.append(nav_row("secrets_menu")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + return + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +# --- Sessions --- + +async def sessions_list_menu(client, callback): + items = db.get_all_sessions() + text = "📱 **الجلسات**\n\n✅ الجلسة المفعلة متاحة لقراءة المصادر.\n❌ الجلسة المعطلة لا تُستخدم حتى تعيد تشغيلها.\n\n" + if not items: + text += "لا توجد جلسات." + buttons = [[InlineKeyboardButton("➕ إضافة جلسة", callback_data="session_add")], nav_row("secrets_menu")] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + return + btns = [] + for s in items: + status = "✅" if s.get("enabled", True) else "❌" + btns.append(InlineKeyboardButton(f"{status} {s.get('name', s['id'])}", callback_data=f"session_show_{s['id']}")) + rows = grid_buttons(btns, 2) + rows.append([InlineKeyboardButton("➕ إضافة جلسة", callback_data="session_add")]) + rows.append(nav_row("secrets_menu")) + text += f"العدد: {len(items)}" + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def add_session_prompt(client, callback): + uid = callback.from_user.id + user_states.pop(uid, None) + user_states[uid] = {"state": "waiting_session_add"} + await safe_edit(callback, "✏️ أرسل بيانات الجلسة بهذا التنسيق:\n\n`API_ID | API_HASH | SESSION_STRING`\n\nفي سطر واحد.", InlineKeyboardMarkup([nav_row("sessions_list")])) + + +async def show_session_settings(client, callback): + sid = callback.data.split("_", 2)[2] + s = db.get_session(sid) + if not s: + await callback.answer("الجلسة غير موجودة.") + return + deps = db.get_dependencies_for("session", sid) + deps_text = "\n".join(f"• {entity_name(d)}" for d in deps[:10]) if deps else "لا توجد" + stats = db.get_session_stats(sid) + text = ( + f"📱 **{s.get('name', sid)}**\n" + f"🆔 `{sid}`\n" + f"🔢 API ID: `{'***' if s.get('api_id') else '?'}`\n" + f"🔑 الحالة: {'✅ مفعل' if s.get('enabled', True) else '❌ معطل'}\n" + f"📊 الاستخدام: {stats.get('usage_count', 0)}\n" + f"❌ الأخطاء: {stats.get('error_count', 0)}\n" + f"🕐 آخر استخدام: {_format_ts(stats.get('last_used'))}\n" + f"📡 الحالة: {s.get('status', 'idle')}\n\n⏯️ تشغيل/إيقاف: تفعيل أو تعطيل استخدام الجلسة.\n🧪 اختبار: التحقق من اتصال الجلسة دون تغيير إعداداتها.\n🗑 حذف: نقل الجلسة إلى سلة المحذوفات.\n\n" + f"**القنوات المستخدمة:**\n{deps_text}" + ) + buttons = [ + [InlineKeyboardButton("⏯️ تشغيل/إيقاف", callback_data=f"session_toggle_{sid}")], + [InlineKeyboardButton("🧪 اختبار", callback_data=f"session_test_{sid}")], + [InlineKeyboardButton("🗑 حذف", callback_data=f"session_delete_{sid}")], + [InlineKeyboardButton("🔙 رجوع", callback_data="sessions_list"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def toggle_session(client, callback): + sid = callback.data.split("_", 2)[2] + s = db.get_session(sid) + if not s: + await callback.answer("غير موجودة.") + return + db.set_session_enabled(sid, not s.get("enabled", True)) + await callback.answer("تم التحديث.") + callback.data = f"session_show_{sid}" + await show_session_settings(client, callback) + + +async def delete_session_with_deps(client, callback): + sid = callback.data.split("_", 2)[2] + s = db.get_session(sid) + if not s: + await callback.answer("غير موجودة.") + return + deps = db.get_dependencies_for("session", sid) + if deps: + dep_text = "\n".join(f"• {entity_name(d)}" for d in deps[:10]) + text = ( + f"⚠️ **لا يمكن حذف {s.get('name', sid)}**\n\n" + f"هذه الجلسة مستخدمة من قبل:\n{dep_text}\n\n" + f"قم بإزالتها من هذه القنوات أولاً." + ) + buttons = [nav_row(f"session_show_{sid}")] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + return + # Move to trash + db.delete_session(sid) + await callback.answer("✅ تم نقل الجلسة إلى سلة المحذوفات.") + await sessions_list_menu(client, callback) + + +async def test_session(client, callback): + sid = callback.data.split("_", 2)[2] + s = db.get_session(sid) + if not s: + await callback.answer("غير موجودة.") + return + await callback.answer(f"جاري اختبار {s.get('name', sid)}...", show_alert=False) + try: + from pyrogram import Client as PClient + test_client = PClient( + f"test_session_{sid}", + api_id=s.get("api_id", 0), + api_hash=s.get("api_hash", ""), + session_string=s.get("session_string", ""), + in_memory=True + ) + await test_client.start() + me = await test_client.get_me() + await test_client.stop() + db.record_session_usage(sid) + await callback.answer(f"✅ {s.get('name', sid)}: اتصال ناجح كـ {me.first_name or me.id}", show_alert=True) + except Exception as e: + await callback.answer(f"❌ فشل: {str(e)[:100]}", show_alert=True) + + +# --- AI Keys --- + +async def ai_list_menu(client, callback): + items = db.get_all_ai_keys() + text = "🧠 **مفاتيح AI**\n\n✅ المفتاح المفعّل متاح لطلبات الذكاء الاصطناعي.\n❌ المفتاح المعطّل محفوظ لكنه لا يُستخدم.\n\n" + if not items: + text += "لا توجد مفاتيح." + buttons = [[InlineKeyboardButton("➕ إضافة مفتاح", callback_data="ai_add")], nav_row("secrets_menu")] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + return + btns = [] + for k in items: + status = "✅" if k.get("enabled", True) else "❌" + btns.append(InlineKeyboardButton(f"{status} {k.get('name', k['id'])}", callback_data=f"ai_show_{k['id']}")) + rows = grid_buttons(btns, 2) + rows.append([InlineKeyboardButton("➕ إضافة مفتاح", callback_data="ai_add")]) + rows.append(nav_row("secrets_menu")) + text += f"العدد: {len(items)}" + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def add_ai_key_prompt(client, callback): + uid = callback.from_user.id + user_states.pop(uid, None) + user_states[uid] = {"state": "waiting_ai_key_add"} + await safe_edit(callback, "✏️ أرسل بيانات مفتاح AI بهذا التنسيق:\n\n`المزود | المفتاح`\n\nالمزود مثال: `gemini` أو `openai`\nمثال: `gemini | AIzaSy...`", InlineKeyboardMarkup([nav_row("ai_list")])) + + +async def show_ai_key_settings(client, callback): + kid = callback.data.split("_", 2)[2] + k = db.get_ai_key(kid) + if not k: + await callback.answer("غير موجود.") + return + deps = db.get_dependencies_for("ai_key", kid) + deps_text = "\n".join(f"• {entity_name(d)}" for d in deps[:10]) if deps else "لا توجد" + stats = db.get_ai_key_stats(kid) + text = ( + f"🧠 **{k.get('name', kid)}**\n" + f"🆔 `{kid}`\n" + f"🏢 المزود: {k.get('provider', '?')}\n" + f"🔑 الحالة: {'✅ مفعل' if k.get('enabled', True) else '❌ معطل'}\n" + f"📊 الاستخدام: {stats.get('usage_count', 0)}\n" + f"❌ الأخطاء: {stats.get('error_count', 0)}\n" + f"🕐 آخر استخدام: {_format_ts(stats.get('last_used'))}\n\n" + f"⏯️ تشغيل/إيقاف: التحكم في استخدام مفتاح {k.get('name', kid)}.\n🧪 اختبار: التحقق من اتصال المزود.\n🗑 حذف: نقل المفتاح إلى سلة المحذوفات.\n\n" + f"**القنوات المستخدمة:**\n{deps_text}" + ) + buttons = [ + [InlineKeyboardButton("⏯️ تشغيل/إيقاف", callback_data=f"ai_toggle_{kid}")], + [InlineKeyboardButton("🧪 اختبار", callback_data=f"ai_test_{kid}")], + [InlineKeyboardButton("🗑 حذف", callback_data=f"ai_delete_{kid}")], + [InlineKeyboardButton("🔙 رجوع", callback_data="ai_list"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def toggle_ai_key(client, callback): + kid = callback.data.split("_", 2)[2] + k = db.get_ai_key(kid) + if not k: + await callback.answer("غير موجود.") + return + db.set_ai_key_enabled(kid, not k.get("enabled", True)) + await callback.answer("تم التحديث.") + callback.data = f"ai_show_{kid}" + await show_ai_key_settings(client, callback) + + +async def delete_ai_key_with_deps(client, callback): + kid = callback.data.split("_", 2)[2] + k = db.get_ai_key(kid) + if not k: + await callback.answer("غير موجود.") + return + deps = db.get_dependencies_for("ai_key", kid) + if deps: + dep_text = "\n".join(f"• {entity_name(d)}" for d in deps[:10]) + text = f"⚠️ **لا يمكن حذف {k.get('name', kid)}**\n\nمستخدم من قبل:\n{dep_text}\n\nقم بإزالتها من هذه القنوات أولاً." + buttons = [nav_row(f"ai_show_{kid}")] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + return + db.delete_ai_key(kid) + await callback.answer("✅ تم النقل إلى سلة المحذوفات.") + await ai_list_menu(client, callback) + + +async def test_ai_key(client, callback): + kid = callback.data.split("_", 2)[2] + k = db.get_ai_key(kid) + if not k: + await callback.answer("غير موجود.") + return + provider = k.get("provider", "").lower() + api_key = k.get("api_key", "") + if not api_key: + await callback.answer("❌ لا يوجد مفتاح.", show_alert=True) + return + await callback.answer(f"جاري اختبار {k.get('name', kid)}...", show_alert=False) + try: + if provider == "gemini": + import httpx + url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={api_key}" + async with httpx.AsyncClient(timeout=10) as hc: + resp = await hc.post(url, json={"contents": [{"parts": [{"text": "hi"}]}]}) + if resp.status_code == 200: + db.record_ai_key_usage(kid) + await callback.answer("✅ اتصال ناجح!", show_alert=True) + else: + await callback.answer(f"❌ فشل: {resp.status_code}", show_alert=True) + else: + await callback.answer(f"✅ مزود {provider} مسجل.", show_alert=True) + except Exception as e: + await callback.answer(f"❌ فشل: {str(e)[:100]}", show_alert=True) + + +# --- Publishing Bots --- + +async def bots_list_menu(client, callback): + items = db.get_all_publishing_bots() + text = "🤖 **بوتات النشر**\n\n✅ البوت المفعّل متاح للنشر في القنوات المرتبطة.\n❌ البوت المعطّل لا ينشر حتى تعيد تشغيله.\n\n" + if not items: + text += "لا توجد بوتات." + buttons = [[InlineKeyboardButton("➕ إضافة بوت", callback_data="bot_add")], nav_row("secrets_menu")] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + return + btns = [] + for b in items: + status = "✅" if b.get("enabled", True) else "❌" + btns.append(InlineKeyboardButton(f"{status} {b.get('name', b['id'])}", callback_data=f"bot_show_{b['id']}")) + rows = grid_buttons(btns, 2) + rows.append([InlineKeyboardButton("➕ إضافة بوت", callback_data="bot_add")]) + rows.append(nav_row("secrets_menu")) + text += f"العدد: {len(items)}" + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def add_bot_prompt(client, callback): + uid = callback.from_user.id + user_states.pop(uid, None) + user_states[uid] = {"state": "waiting_bot_add"} + await safe_edit(callback, "✏️ أرسل توكن البوت:\n\nمثال:\n`123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`", InlineKeyboardMarkup([nav_row("bots_list")])) + + +async def show_bot_settings(client, callback): + bid = callback.data.split("_", 2)[2] + b = db.get_publishing_bot(bid) + if not b: + await callback.answer("غير موجود.") + return + deps_raw = db.get_dependencies_for("publishing_bot", bid) if hasattr(db, "get_dependencies_for") else [] + # استخدام BotChannelMapper للحصول على القنوات + if hasattr(db, "mapper") and hasattr(db.mapper, "get_channels_for_bot"): + mapped_ids = db.mapper.get_channels_for_bot(bid) + deps = [d for d in deps_raw if str(d.get("id", "")) in mapped_ids] if deps_raw else [] + if not deps_raw: + deps = [db.get_channel(cid) for cid in mapped_ids if db.get_channel(cid)] + else: + deps = deps_raw + deps_verified = verifier.get_cached_verifications_for_bot(bid) + deps_lines = [] + for d in deps: + ch_id = d.get("id", "") + ch_name = entity_name(d) + v = deps_verified.get(str(ch_id), {}) + vstatus = v.get("verified", False) + can_post = v.get("can_post", False) + last_check = v.get("last_check", 0) + if vstatus: + age = f" (منذ {int((time.time() - last_check) / 60)}د)" if last_check else "" + perm = "نشر:✅" if can_post else "نشر:❌" + deps_lines.append(f"✅ {ch_name} | {perm}{age}") + else: + deps_lines.append(f"❌ {ch_name} | غير موثوق") + deps_text = "\n".join(deps_lines) if deps_lines else "لا توجد" + stats = b.get("stats", {}) or {} + text = ( + f"🤖 **{b.get('name', bid)}**\n" + f"🆔 `{bid}`\n" + f"👤 @{b.get('username', '?')}\n" + f"🔑 الحالة: {'✅ مفعل' if b.get('enabled', True) else '❌ معطل'}\n" + f"📊 إجمالي النشرات: {b.get('publish_count', 0)}\n" + f" 📝 نصوص: {stats.get('text', 0)}\n" + f" 🖼 صور: {stats.get('photo', 0)}\n" + f" 🎥 فيديو: {stats.get('video', 0)}\n" + f" 🗂 البومات: {stats.get('album', 0)}\n" + f"❌ الأخطاء: {b.get('error_count', 0)}\n" + f"🕐 آخر نشر: {_format_ts(b.get('last_publish'))}\n\n" + f"⏯️ تشغيل/إيقاف: التحكم في استخدام البوت للنشر.\n✏️ إعادة تسمية: تغيير الاسم الظاهر للبوت فقط.\n🔍 فحص القنوات: التحقق من صلاحيات النشر في القنوات المرتبطة.\n🧪 اختبار: التحقق من توكن البوت واتصاله.\n🗑 حذف: نقل البوت إلى سلة المحذوفات.\n\n" + f"**القنوات المستخدمة:**\n{deps_text}" + ) + buttons = [ + [InlineKeyboardButton("⏯️ تشغيل/إيقاف", callback_data=f"bot_toggle_{bid}")], + [InlineKeyboardButton("✏️ إعادة تسمية", callback_data=f"bot_rename_{bid}")], + [InlineKeyboardButton("🔍 فحص القنوات", callback_data=f"bot_verify_{bid}")], + [InlineKeyboardButton("🧪 اختبار", callback_data=f"bot_test_{bid}")], + [InlineKeyboardButton("🗑 حذف", callback_data=f"bot_delete_{bid}")], + [InlineKeyboardButton("🔙 رجوع", callback_data="bots_list"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def toggle_bot(client, callback): + bid = callback.data.split("_", 2)[2] + b = db.get_publishing_bot(bid) + if not b: + await callback.answer("غير موجود.") + return + db.set_publishing_bot_enabled(bid, not b.get("enabled", True)) + await callback.answer("تم التحديث.") + callback.data = f"bot_show_{bid}" + await show_bot_settings(client, callback) + + +async def delete_bot_with_deps(client, callback): + bid = callback.data.split("_", 2)[2] + b = db.get_publishing_bot(bid) + if not b: + await callback.answer("غير موجود.") + return + # استخدام BotChannelMapper + if hasattr(db, "mapper"): + dep_ch_ids = db.mapper.get_channels_for_bot(bid) + deps = [db.get_channel(cid) for cid in dep_ch_ids if db.get_channel(cid)] + else: + deps = db.get_dependencies_for("publishing_bot", bid) + if deps: + dep_text = "\n".join(f"• {entity_name(d)}" for d in deps[:10]) + text = f"⚠️ **لا يمكن حذف {b.get('name', bid)}**\n\nمستخدم من قبل:\n{dep_text}\n\nقم بإزالتها من هذه القنوات أولاً." + buttons = [nav_row(f"bot_show_{bid}")] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + return + db.delete_publishing_bot(bid) + await callback.answer("✅ تم النقل إلى سلة المحذوفات.") + await bots_list_menu(client, callback) + + +async def test_bot(client, callback): + bid = callback.data.split("_", 2)[2] + b = db.get_publishing_bot(bid) + if not b: + await callback.answer("غير موجود.") + return + token = db.bot_manager.get_token(bid) if hasattr(db, "bot_manager") else b.get("token", "") + if not token: + await callback.answer("❌ لا يوجد توكن.", show_alert=True) + return + await callback.answer(f"جاري اختبار {b.get('name', bid)}...", show_alert=False) + ver = await verifier.validate_token(token) + if ver.get("valid"): + username = f"@{ver['username']}" if ver.get("username") else ver.get("id", "") + db.update_publishing_bot(bid, username=ver.get("username", "")) + db.record_bot_publish(bid) + await callback.answer(f"✅ {b.get('name', bid)}: {username}", show_alert=True) + else: + await callback.answer(f"❌ فشل: {ver.get('error', 'غير معروف')}", show_alert=True) + + +async def verify_bot_channels(client, callback): + bid = callback.data.split("_", 2)[2] + b = db.get_publishing_bot(bid) + if not b: + await callback.answer("غير موجود.") + return + token = db.bot_manager.get_token(bid) if hasattr(db, "bot_manager") else b.get("token", "") + if not token: + await callback.answer("❌ لا يوجد توكن.", show_alert=True) + return + await callback.answer(f"🔍 جاري فحص القنوات للبوت {b.get('name', bid)}...", show_alert=False) + # استخدام BotChannelMapper للحصول على القنوات المرتبطة + if hasattr(db, "mapper"): + channel_ids = db.mapper.get_channels_for_bot(bid) + else: + raw_deps = db.get_dependencies_for("publishing_bot", bid) + channel_ids = [d.get("id", "") for d in raw_deps] + if not channel_ids: + await callback.answer("لا توجد قنوات مربوطة.", show_alert=True) + return + ok_count = 0 + fail_count = 0 + for ch_id in channel_ids: + ch = db.get_channel(ch_id) if hasattr(db, "get_channel") else None + ch_name = entity_name(ch) if ch else ch_id + try: + ver = await verifier.check_bot_in_channel(bid, ch_id, force=True) + if ver.get("verified") and ver.get("can_post"): + ok_count += 1 + else: + fail_count += 1 + except Exception as e: + fail_count += 1 + msg = f"🔍 نتائج فحص {b.get('name', bid)}:\n✅ موثوق: {ok_count}\n❌ غير موثوق: {fail_count}" + await callback.answer(msg, show_alert=True) + callback.data = f"bot_show_{bid}" + await show_bot_settings(client, callback) + + +async def rename_bot_prompt(client, callback): + bid = callback.data.split("_", 2)[2] + b = db.get_publishing_bot(bid) + if not b: + await callback.answer("غير موجود.") + return + uid = callback.from_user.id + user_states[uid] = {"state": "waiting_bot_rename", "bot_id": bid} + await safe_edit(callback, f"✏️ أرسل الاسم الجديد للبوت **{b.get('name', bid)}**:\n\nالاسم الحالي: `{b.get('name', bid)}`\nاليوزر: @{b.get('username', '')}", InlineKeyboardMarkup([nav_row(f"bot_show_{bid}")])) + + +# --- Websites --- + +async def web_list_menu(client, callback): + items = db.get_all_websites() + text = "🌐 **مواقع الويب**\n\n✅ الموقع المفعّل يدخل ضمن دورات الجلب.\n❌ الموقع المعطّل محفوظ لكنه لا يُجلب.\n\n" + if not items: + text += "لا توجد مواقع." + buttons = [[InlineKeyboardButton("➕ إضافة موقع", callback_data="web_add")], nav_row("secrets_menu")] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + return + btns = [] + for w in items: + status = "✅" if w.get("enabled", True) else "❌" + btns.append(InlineKeyboardButton(f"{status} {w.get('name', w['id'])}", callback_data=f"web_show_{w['id']}")) + rows = grid_buttons(btns, 2) + rows.append([InlineKeyboardButton("➕ إضافة موقع", callback_data="web_add")]) + rows.append(nav_row("secrets_menu")) + text += f"العدد: {len(items)}" + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def add_website_prompt(client, callback): + uid = callback.from_user.id + user_states.pop(uid, None) + user_states[uid] = {"state": "waiting_website_add"} + await safe_edit(callback, "✏️ أرسل رابط الموقع:\n\nمثال:\n`https://example.com`\n\nيمكنك إضافة `| محدد` لاختيار عناصر محددة (CSS selector)\nمثال:\n`https://example.com | article.news`", InlineKeyboardMarkup([nav_row("web_list")])) + + +async def show_website_settings(client, callback): + wid = callback.data.split("_", 2)[2] + w = db.get_website(wid) + if not w: + await callback.answer("غير موجود.") + return + deps = db.get_dependencies_for("website", wid) + deps_text = "\n".join(f"• {entity_name(d)}" for d in deps[:10]) if deps else "لا توجد" + text = ( + f"🌐 **{w.get('name', wid)}**\n" + f"🆔 `{wid}`\n" + f"🔗 الرابط: {w.get('url', '?')}\n" + f"🎯 المحدد: `{w.get('selector', 'body')}`\n" + f"🔑 الحالة: {'✅ مفعل' if w.get('enabled', True) else '❌ معطل'}\n" + f"❌ الأخطاء: {w.get('error_count', 0)}\n" + f"🕐 آخر جلب: {_format_ts(w.get('last_fetch'))}\n\n" + "⏯️ تشغيل/إيقاف: التحكم في جلب هذا الموقع.\n✏️ تعديل: تغيير الرابط أو المحدد.\n🧪 اختبار: جلب الموقع والتحقق من استجابته.\n🗑 حذف: نقل الموقع إلى سلة المحذوفات.\n\n" + f"**القنوات المستخدمة:**\n{deps_text}" + ) + buttons = [ + [InlineKeyboardButton("⏯️ تشغيل/إيقاف", callback_data=f"web_toggle_{wid}")], + [InlineKeyboardButton("✏️ تعديل", callback_data=f"web_edit_{wid}")], + [InlineKeyboardButton("🧪 اختبار", callback_data=f"web_test_{wid}")], + [InlineKeyboardButton("🗑 حذف", callback_data=f"web_delete_{wid}")], + [InlineKeyboardButton("🔙 رجوع", callback_data="web_list"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def toggle_website(client, callback): + wid = callback.data.split("_", 2)[2] + w = db.get_website(wid) + if not w: + await callback.answer("غير موجود.") + return + db.set_website_enabled(wid, not w.get("enabled", True)) + await callback.answer("تم التحديث.") + callback.data = f"web_show_{wid}" + await show_website_settings(client, callback) + + +async def edit_website_prompt(client, callback): + wid = callback.data.split("_", 2)[2] + w = db.get_website(wid) + if not w: + await callback.answer("غير موجود.") + return + uid = callback.from_user.id + user_states.pop(uid, None) + user_states[uid] = {"state": "waiting_website_edit", "website_id": wid} + await safe_edit(callback, f"✏️ أرسل البيانات الجديدة للموقع:\n\n`الرابط | المحدد`\n\nالحالي:\nالرابط: {w.get('url')}\nالمحدد: `{w.get('selector', 'body')}`", InlineKeyboardMarkup([nav_row(f"web_show_{wid}")])) + + +async def delete_website_with_deps(client, callback): + wid = callback.data.split("_", 2)[2] + w = db.get_website(wid) + if not w: + await callback.answer("غير موجود.") + return + deps = db.get_dependencies_for("website", wid) + if deps: + dep_text = "\n".join(f"• {entity_name(d)}" for d in deps[:10]) + text = f"⚠️ **لا يمكن حذف {w.get('name', wid)}**\n\nمستخدم من قبل:\n{dep_text}\n\nقم بإزالتها من هذه القنوات أولاً." + buttons = [nav_row(f"web_show_{wid}")] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + return + db.delete_website(wid) + await callback.answer("✅ تم النقل إلى سلة المحذوفات.") + await web_list_menu(client, callback) + + +async def test_website(client, callback): + wid = callback.data.split("_", 2)[2] + w = db.get_website(wid) + if not w: + await callback.answer("غير موجود.") + return + await callback.answer(f"جاري اختبار {w.get('name', wid)}...", show_alert=False) + try: + import httpx + async with httpx.AsyncClient(timeout=15, follow_redirects=True) as hc: + resp = await hc.get(w.get("url", ""), headers={"User-Agent": "Mozilla/5.0"}) + if resp.status_code == 200: + content_len = len(resp.text) + db.update_website(wid, last_fetch=int(time.time())) + await callback.answer(f"✅ متاح! {content_len} حرف", show_alert=True) + else: + await callback.answer(f"❌ HTTP {resp.status_code}", show_alert=True) + except Exception as e: + await callback.answer(f"❌ فشل: {str(e)[:100]}", show_alert=True) + + +# --- Trash --- + +async def trash_menu(client, callback): + items = db.get_trash_items() + text = "🗑 **سلة المحذوفات**\n\n♻️ الاستعادة: يعيد العنصر إلى قائمته السابقة.\n🗑 الحذف النهائي: يزيل العنصر نهائياً ولا يمكن التراجع عنه.\n\n" + if not items: + text += "السلة فارغة." + buttons = [nav_row("secrets_menu")] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + return + type_labels = {"session": "📱 جلسة", "ai_key": "🧠 مفتاح AI", "publishing_bot": "🤖 بوت", "website": "🌐 موقع"} + rows = [] + for idx, item in enumerate(items[:30]): + t = item.get("type", "") + label = type_labels.get(t, t) + name = item.get("data", {}).get("name", item.get("original_id", "")) + tid = item.get("id", "") + rows.append([ + InlineKeyboardButton(f"♻️ {label}: {name}", callback_data=f"trash_restore_{tid}"), + InlineKeyboardButton(f"🗑 حذف", callback_data=f"trash_permdel_{tid}"), + ]) + rows.append([InlineKeyboardButton("🗑 حذف نهائي للكل", callback_data="trash_empty_prompt")]) + rows.append(nav_row("secrets_menu")) + text += f"العدد: {len(items)}" + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def trash_restore_item(client, callback): + tid = callback.data.split("_", 2)[2] + ok = db.restore_from_trash(tid) + if ok: + await callback.answer("✅ تمت الاستعادة.") + else: + await callback.answer("❌ فشل الاستعادة.", show_alert=True) + await trash_menu(client, callback) + + +async def trash_permanent_delete_prompt(client, callback): + tid = callback.data.split("_", 2)[2] + text = "⚠️ **تأكيد الحذف النهائي**\n\nهل تريد حذف هذا العنصر نهائياً؟ لا يمكن التراجع." + buttons = [ + [InlineKeyboardButton("✅ نعم، احذف نهائياً", callback_data=f"trash_permconfirm_{tid}")], + nav_row("trash_menu"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def trash_permanent_delete_confirm(client, callback): + tid = callback.data.split("_", 2)[2] + ok = db.permanent_delete_from_trash(tid) + await callback.answer("✅ تم الحذف النهائي." if ok else "❌ فشل.", show_alert=True) + await trash_menu(client, callback) + + +async def trash_empty_prompt(client, callback): + text = "⚠️ **تفريغ سلة المحذوفات**\n\nسيتم حذف جميع العناصر نهائياً. لا يمكن التراجع." + buttons = [ + [InlineKeyboardButton("✅ نعم، امسح الكل", callback_data="trash_empty_confirm")], + nav_row("trash_menu"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def trash_empty_confirm(client, callback): + db.empty_trash() + await callback.answer("✅ تم تفريغ السلة.") + await trash_menu(client, callback) + + +# --- Channel Extended Settings --- + +async def channel_extended_settings(client, callback): + ch_id = callback.data.split("_", 2)[2] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + cfg = db.get_channel_config(ch_id) + disable_preview = db.get_channel_disable_preview(ch_id) if hasattr(db, "get_channel_disable_preview") else False + text = ( + f"⚙️ **الإعدادات المتقدمة:**\n{entity_name(ch)}\n\n" + f"💬 اقتباس العنوان: {'✅ مفعل' if cfg.get('title_quote') else '❌ متوقف'}\n" + f"💬 اقتباس التوقيع: {'✅ مفعل' if cfg.get('signature_quote') else '❌ متوقف'}\n" + f"🔗 إخفاء معاينة الروابط: {'✅ مفعل' if disable_preview else '❌ متوقف'}\n" + f"📱 الجلسات المخصصة: {len(cfg.get('assigned_sessions', []))}\n" + f"🤖 البوتات المخصصة: {len(cfg.get('assigned_bots', []))}\n" + f"🧠 AI المخصص: {len(cfg.get('assigned_ai', []))}\n" + f"🌐 مواقع مخصصة: {len(cfg.get('websites', []))}\n\n" + "💬 الاقتباس: التحكم في تنسيق العنوان والتوقيع.\n🔗 المعاينة: إظهار أو إخفاء معاينة الروابط.\n📱/🤖/🧠/🌐 التخصيص: اختيار الموارد التي تستخدمها هذه القناة.\n" + ) + buttons = [ + [InlineKeyboardButton(f"💬 اقتباس العنوان: {'✅' if cfg.get('title_quote') else '❌'}", callback_data=f"ch_titlequote_{ch_id}")], + [InlineKeyboardButton(f"💬 اقتباس التوقيع: {'✅' if cfg.get('signature_quote') else '❌'}", callback_data=f"ch_sigquote_{ch_id}")], + [InlineKeyboardButton(f"🔗 معاينة: {'✅' if not disable_preview else '❌'}", callback_data=f"ch_preview_{ch_id}")], + [InlineKeyboardButton("📱 الجلسات", callback_data=f"assign_sessions_{ch_id}"), InlineKeyboardButton("🤖 البوتات", callback_data=f"assign_bots_{ch_id}")], + [InlineKeyboardButton("🧠 AI", callback_data=f"assign_ai_{ch_id}"), InlineKeyboardButton("🌐 مواقع", callback_data=f"assign_websites_{ch_id}")], + [InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}"), InlineKeyboardButton("🏠 القائمة الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def toggle_channel_title_quote(client, callback): + ch_id = callback.data.split("_", 2)[2] + cfg = db.get_channel_config(ch_id) + db.set_channel_title_quote(ch_id, not cfg.get("title_quote", False)) + await callback.answer("تم التحديث.") + callback.data = f"quotemenu_{ch_id}" + await channel_quote_menu(client, callback) + + +async def toggle_channel_signature_quote(client, callback): + ch_id = callback.data.split("_", 2)[2] + cfg = db.get_channel_config(ch_id) + db.set_channel_signature_quote(ch_id, not cfg.get("signature_quote", False)) + await callback.answer("تم التحديث.") + callback.data = f"quotemenu_{ch_id}" + await channel_quote_menu(client, callback) + + +async def toggle_channel_preview(client, callback): + ch_id = callback.data.split("_", 2)[2] + cur = db.get_channel_disable_preview(ch_id) if hasattr(db, "get_channel_disable_preview") else False + db.set_channel_disable_preview(ch_id, not cur) + await callback.answer("تم التحديث.") + callback.data = f"postset_{ch_id}" + await post_settings_menu(client, callback) + + +# ============================================================ +# General Channel Settings (الإعدادات العامة للقناة) +# ============================================================ + +async def general_settings_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + buttons = [ + InlineKeyboardButton("📋 ملخص الإعدادات", callback_data=f"genset_summary_{ch_id}"), + InlineKeyboardButton("📄 نسخ الإعدادات", callback_data=f"genset_copy_{ch_id}"), + InlineKeyboardButton("📥 لصق الإعدادات", callback_data=f"genset_paste_{ch_id}"), + InlineKeyboardButton("♻️ إعادة التعيين", callback_data=f"genset_reset_{ch_id}"), + InlineKeyboardButton("🤖 التحقق من البوت", callback_data=f"chbotcheck|{ch_id}"), + InlineKeyboardButton(f"{'⏸️' if ch.get('paused') else '▶️'} تشغيل/إيقاف القناة", callback_data=f"toggle_{ch_id}"), + InlineKeyboardButton("📱 الجلسات", callback_data=f"assign_sessions_{ch_id}"), + InlineKeyboardButton("🤖 البوتات", callback_data=f"assign_bots_{ch_id}"), + InlineKeyboardButton("🧠 AI", callback_data=f"assign_ai_{ch_id}"), + InlineKeyboardButton("🌐 المواقع", callback_data=f"assign_websites_{ch_id}"), + InlineKeyboardButton("🗑 حذف القناة", callback_data=f"delchannel_{ch_id}"), + ] + rows = grid_buttons(buttons, 2) + rows.append(nav_row(f"ch_{ch_id}")) + ch_state = '⏸️ متوقفة' if ch.get('paused') else '▶️ تعمل' + await safe_edit(callback, f"⚙️ **الإعدادات العامة**\n{channel_display_name(ch_id)}\n\nالحالة: {ch_state}\n\n📋 الملخص: عرض الإعدادات الحالية.\n📄 نسخ / 📥 لصق: نقل الإعدادات بين القنوات.\n♻️ إعادة التعيين: استرجاع القيم الافتراضية.\n🤖 التحقق: فحص صلاحية بوت القناة.\n▶️/⏸️ تشغيل/إيقاف: التحكم في استقبال القناة للمنشورات.\n📱 الجلسات / 🤖 البوتات / 🧠 AI / 🌐 المواقع: إدارة الموارد المخصصة.\n🗑 حذف القناة: إزالة القناة بعد التأكيد.", InlineKeyboardMarkup(rows)) + + +# ============================================================ +# 🖥 النظام — خاص بكل قناة على حدة +# ============================================================ + +async def system_channel_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + buttons = [ + InlineKeyboardButton("🧪 اختبار القناة", callback_data=f"testset_{ch_id}"), + InlineKeyboardButton("🔍 الفحص الشامل", callback_data=f"full_check|{ch_id}"), + InlineKeyboardButton("📊 حالة النظام", callback_data=f"system_status|{ch_id}"), + InlineKeyboardButton("▶️ إدارة التشغيل", callback_data=f"ops_menu|{ch_id}"), + InlineKeyboardButton("📝 إدارة السجل", callback_data=f"log_menu|{ch_id}"), + InlineKeyboardButton("🔔 الإشعارات", callback_data=f"notifications_menu|{ch_id}"), + ] + rows = grid_buttons(buttons, 2) + rows.append(nav_row(f"ch_{ch_id}")) + await safe_edit(callback, f"🖥 **النظام**\n{channel_display_name(ch_id)}\n\n🧪 اختبار القناة: تجربة إعدادات القناة.\n🔍 الفحص الشامل: فحص الموارد والصلاحيات.\n📊 حالة النظام: عرض الحالة والإحصائيات.\n▶️ إدارة التشغيل: الصيانة واختبار القنوات والأخطاء.\n📝 إدارة السجل: عرض أو تحديث أو مسح السجل.\n🔔 الإشعارات: التحكم في تنبيهات النظام.", InlineKeyboardMarkup(rows)) + + +async def general_settings_copy(client, callback): + """نسخ إعدادات القناة إلى الحافظة.""" + ch_id = callback.data.split("_", 2)[2] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + clip = { + "bold_publish": ch.get("bold_publish", True), + "tail": ch.get("tail", ""), + "tail_enabled": ch.get("tail_enabled", True), + "tail_min_words": ch.get("tail_min_words", 20), + "tail_position": ch.get("tail_position", "bottom"), + "quote_types": ch.get("quote_types", {"text": False, "photo": False, "video": False, "album": False}), + "publish_delay": ch.get("publish_delay"), + "hashtags": ch.get("hashtags", []), + "disable_web_page_preview": ch.get("disable_web_page_preview", False), + "link_remove_tg": ch.get("link_remove_tg", False), + "link_remove_tg_user": ch.get("link_remove_tg_user", False), + "link_remove_web": ch.get("link_remove_web", False), + } + if hasattr(db, "set_settings_clipboard"): + db.set_settings_clipboard(clip) + await callback.answer("✅ تم نسخ إعدادات هذه القناة.", show_alert=True) + + +async def general_settings_paste(client, callback): + """لصق إعدادات القناة من الحافظة مع تأكيد.""" + ch_id = callback.data.split("_", 2)[2] + clip = db.get_settings_clipboard() if hasattr(db, "get_settings_clipboard") else None + if not clip: + await callback.answer("❌ لا توجد إعدادات منسوخة. انسخ أولاً.", show_alert=True) + return + text = ( + f"⚠️ **هل تريد استبدال إعدادات هذه القناة؟**\n\n" + f"{entity_name(db.get_channel(ch_id))}\n\n" + f"سيتم لصق آخر إعدادات تم نسخها." + ) + buttons = [ + [InlineKeyboardButton("✅ نعم", callback_data=f"genset_paste_confirm_{ch_id}")], + nav_row(f"genset_{ch_id}"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def general_settings_paste_confirm(client, callback): + """تأكيد لصق الإعدادات.""" + ch_id = callback.data.split("_", 3)[3] + clip = db.get_settings_clipboard() if hasattr(db, "get_settings_clipboard") else None + if not clip: + await callback.answer("❌ لا توجد إعدادات.", show_alert=True) + return + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + for key in ("bold_publish", "tail", "tail_enabled", "tail_min_words", "tail_position", "quote_types", "publish_delay", "hashtags", "disable_web_page_preview", "link_remove_tg", "link_remove_tg_user", "link_remove_web"): + if key in clip: + db.update_channel(ch_id, key, clip[key]) + await callback.answer("✅ تم لصق الإعدادات بنجاح.", show_alert=True) + callback.data = f"genset_{ch_id}" + await general_settings_menu(client, callback) + + +async def general_settings_reset(client, callback): + """إعادة تعيين إعدادات القناة إلى الافتراضية مع تأكيد.""" + ch_id = callback.data.split("_", 2)[2] + text = ( + f"⚠️ **إعادة تعيين إعدادات القناة؟**\n\n" + f"{entity_name(db.get_channel(ch_id))}\n\n" + f"سيتم إرجاع جميع الإعدادات إلى القيم الافتراضية.\n" + f"لن يتم حذف القناة أو المصادر أو الربط." + ) + buttons = [ + [InlineKeyboardButton("✅ نعم", callback_data=f"genset_reset_confirm_{ch_id}")], + nav_row(f"genset_{ch_id}"), + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def general_settings_reset_confirm(client, callback): + """تأكيد إعادة التعيين.""" + ch_id = callback.data.split("_", 3)[3] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + db.update_channel(ch_id, "bold_publish", True) + db.update_channel(ch_id, "tail", "") + db.update_channel(ch_id, "tail_enabled", True) + db.update_channel(ch_id, "tail_min_words", 20) + if hasattr(db, "set_channel_tail_position"): + db.set_channel_tail_position(ch_id, "bottom") + if hasattr(db, "set_channel_quote_publish"): + db.set_channel_quote_publish(ch_id, False) + db.update_channel(ch_id, "publish_delay", None) + if hasattr(db, "set_channel_disable_preview"): + db.set_channel_disable_preview(ch_id, False) + db.update_channel(ch_id, "link_remove_tg", False) + db.update_channel(ch_id, "link_remove_tg_user", False) + db.update_channel(ch_id, "link_remove_web", False) + await callback.answer("♻️ تم إعادة تعيين الإعدادات.", show_alert=True) + callback.data = f"genset_{ch_id}" + await general_settings_menu(client, callback) + + +async def general_settings_summary(client, callback): + ch_id = callback.data.split("_", 2)[2] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("غير موجودة.") + return + bold = ch.get("bold_publish", True) + tail = ch.get("tail", "") + tail_enabled = ch.get("tail_enabled", True) + tail_min = ch.get("tail_min_words", 20) + tail_pos = ch.get("tail_position", "bottom") + quote_types = get_channel_quote_types_safe(ch_id) + hashtags = ch.get("hashtags", []) + delay = ch.get("publish_delay") + sources = ch.get("special_sources", []) + if hasattr(db, "mapper"): + bot_count = len(db.mapper.get_bots_for_channel(ch_id)) + else: + cfg = db.get_channel_config(ch_id) if hasattr(db, "get_channel_config") else {} + bot_count = len(cfg.get("assigned_bots", [])) + + enabled_count = 0 + disabled_count = 0 + lines = [f"📊 **ملخص إعدادات {entity_name(ch)}**\n"] + + lines.append("\n📝 **المنشورات**") + if bold: + lines.append("✅ الخط السميك"); enabled_count += 1 + else: + lines.append("❌ الخط السميك"); disabled_count += 1 + lines.append(f"{'✅' if quote_types.get('text') else '❌'} اقتباس النصوص") + if quote_types.get('text'): enabled_count += 1 + else: disabled_count += 1 + lines.append(f"{'✅' if quote_types.get('photo') else '❌'} اقتباس الصور") + if quote_types.get('photo'): enabled_count += 1 + else: disabled_count += 1 + lines.append(f"{'✅' if quote_types.get('video') else '❌'} اقتباس الفيديو") + if quote_types.get('video'): enabled_count += 1 + else: disabled_count += 1 + lines.append(f"{'✅' if quote_types.get('album') else '❌'} اقتباس الألبومات") + if quote_types.get('album'): enabled_count += 1 + else: disabled_count += 1 + lines.append(f"{'✅' if hashtags else '❌'} الهاشتاكات ({len(hashtags)})") + if hashtags: enabled_count += 1 + else: disabled_count += 1 + lines.append(f"{'✅' if delay is None else '⚠️'} سرعة النشر: {delay or 'افتراضي'}") + enabled_count += 1 + + lines.append(f"\n🔗 **الروابط**") + lines.append(f"{'✅' if ch.get('link_remove_tg') else '❌'} حذف روابط تيليجرام") + if ch.get("link_remove_tg"): enabled_count += 1 + else: disabled_count += 1 + lines.append(f"{'✅' if ch.get('link_remove_tg_user') else '❌'} حذف يوزرات @") + if ch.get("link_remove_tg_user"): enabled_count += 1 + else: disabled_count += 1 + lines.append(f"{'✅' if ch.get('link_remove_web') else '❌'} حذف روابط المواقع") + if ch.get("link_remove_web"): enabled_count += 1 + else: disabled_count += 1 + + lines.append(f"\n🔖 **التوقيع**") + lines.append(f"{'✅' if tail_enabled else '❌'} تشغيل") + if tail_enabled: enabled_count += 1 + else: disabled_count += 1 + lines.append(f"{'⬆️ أعلى' if tail_pos == 'top' else '⬇️ أسفل'} المنشور") + enabled_count += 1 + if tail_min >= 20: + lines.append(f"✅ شرط {tail_min} كلمة"); enabled_count += 1 + else: + lines.append(f"❌ شرط الكلمات"); disabled_count += 1 + if tail: + lines.append(f"📝 النص: {tail[:30]}{'...' if len(tail) > 30 else ''}") + + lines.append(f"\n📚 **المصادر**") + lines.append(f"{len(sources)} مصدر مخصص") + lines.append(f"{bot_count} بوت نشر") + + lines.append(f"\n-----------------------") + lines.append(f"🟢 مفعل: {enabled_count}") + lines.append(f"🔴 متوقف: {disabled_count}") + + buttons = [ + nav_row(f"genset_{ch_id}"), + ] + await safe_edit(callback, "\n".join(lines), InlineKeyboardMarkup(buttons)) + + +async def ui_setting_info_menu(client, callback): + """صفحة شرح وتحكم موحدة لإعدادات Boolean؛ لا تنفذ التغيير عند فتحها.""" + parts = callback.data.split("|", 3) + if len(parts) != 4: + await callback.answer("طلب غير صالح.", show_alert=True) + return + _, kind, target, back = parts + ch_id = target if target != "global" else None + back_target = back.replace("~", "|") if back else (_peek_prev_back(callback) or "main_menu") + back_token = back_target.replace("|", "~") + state = False + if kind == "short_posts": + state = is_ignore_short_posts_enabled_for_channel(ch_id) if ch_id else is_ignore_short_posts_enabled() + title, purpose = "📝 النصوص القصيرة", "يحدد هل تُمنع المنشورات النصية القصيرة من النشر في هذه القناة." + on_desc, off_desc = "يتم منع نشر المنشورات النصية القصيرة.", "تُنشر المنشورات النصية القصيرة بشكل طبيعي." + elif kind == "bold": + ch = db.get_channel(ch_id) or {} + state = bool(ch.get("bold_publish", True)) + title, purpose = "🖊 الخط السميك", "يحدد استخدام الخط السميك عند تنسيق منشورات هذه القناة." + on_desc, off_desc = "تُنشر النصوص المدعومة بالخط السميك.", "تُنشر النصوص دون تفعيل الخط السميك." + elif kind == "title_quote": + cfg = db.get_channel_config(ch_id) if ch_id and hasattr(db, "get_channel_config") else {} + state = bool(cfg.get("title_quote")) + title, purpose = "💬 اقتباس العنوان", "يحدد هل يظهر عنوان المنشور بصيغة اقتباس Telegram." + on_desc, off_desc = "يظهر العنوان داخل اقتباس.", "يُنشر العنوان بصيغة عادية." + elif kind == "signature_quote": + cfg = db.get_channel_config(ch_id) if ch_id and hasattr(db, "get_channel_config") else {} + state = bool(cfg.get("signature_quote")) + title, purpose = "💬 اقتباس التوقيع", "يحدد هل يظهر التوقيع بصيغة اقتباس Telegram." + on_desc, off_desc = "يظهر التوقيع داخل اقتباس.", "يُنشر التوقيع بصيغة عادية." + elif kind == "preview": + disabled = db.get_channel_disable_preview(ch_id) if ch_id and hasattr(db, "get_channel_disable_preview") else False + state = not bool(disabled) + title, purpose = "🔗 معاينة الروابط", "يحدد هل تظهر معاينة الروابط عند نشر منشورات هذه القناة." + on_desc, off_desc = "تظهر معاينة الروابط.", "تُنشر الروابط دون معاينة." + elif kind == "maintenance": + state = bool(db.is_maintenance_mode()) if hasattr(db, "is_maintenance_mode") else False + title, purpose = "🛠 وضع الصيانة", "يوقف النشر مع إبقاء فحص المصادر مستمراً." + on_desc, off_desc = "يتوقف النشر وتستمر عملية فحص المصادر.", "يعود النشر إلى العمل الطبيعي." + elif kind == "notification": + settings = db.get_notification_settings() if hasattr(db, "get_notification_settings") else {} + state = bool(settings.get(target, True)) + title = "🔔 " + str(getattr(db, "NOTIFICATION_TYPES", {}).get(target, target)) + purpose = "يحدد هل يرسل البوت هذا النوع من التنبيهات للمشرفين." + on_desc, off_desc = "يتم إرسال هذا التنبيه عند حدوثه.", "لا يتم إرسال هذا النوع من التنبيهات." + elif kind.startswith("quote_"): + qtype = kind.split("_", 1)[1] + state = bool(get_channel_quote_types_safe(ch_id).get(qtype, False)) + labels = {"text": "النصوص", "photo": "الصور", "video": "الفيديو", "album": "الألبومات"} + title, purpose = "💬 اقتباس " + labels.get(qtype, qtype), "يحدد هل يُنشر هذا النوع بصيغة اقتباس رسمي في هذه القناة." + on_desc, off_desc = "يُنشر هذا النوع داخل اقتباس رسمي.", "يُنشر هذا النوع بصيغته العادية." + elif kind == "tail": + state = bool(db.get_channel_tail_enabled(ch_id)) if hasattr(db, "get_channel_tail_enabled") else True + title, purpose = "🔖 التوقيع", "يحدد هل يضاف توقيع القناة إلى المنشورات." + on_desc, off_desc = "يُضاف التوقيع إلى المنشورات وفق الإعدادات الحالية.", "لا يُضاف التوقيع إلى المنشورات." + elif kind == "quote_type": + try: + ch_id, qtype = target.split("~", 1) + except ValueError: + await callback.answer("إعداد اقتباس غير صالح.", show_alert=True) + return + state = bool(get_channel_quote_types_safe(ch_id).get(qtype, False)) + labels = {"text": "النصوص", "photo": "الصور", "video": "الفيديو", "album": "الألبومات"} + title = "💬 اقتباس " + labels.get(qtype, qtype) + purpose = "يحدد هل يُنشر هذا النوع بصيغة اقتباس رسمية في هذه القناة." + on_desc, off_desc = "يُنشر هذا النوع داخل اقتباس رسمي.", "يُنشر هذا النوع بصيغته العادية." + elif kind == "source_enabled": + state = not bool(db.is_source_paused(target)) + title, purpose = "🟢 تشغيل المصدر", "يحدد هل يستمر هذا المصدر في استقبال المنشورات." + on_desc, off_desc = "يستمر استقبال منشورات المصدر.", "يتوقف استقبال منشورات المصدر مؤقتاً." + elif kind == "source_emoji": + state = bool(db.get_source_remove_emoji(target)) + title, purpose = "🙂 إزالة الإيموجي", "يحدد هل تُزال الإيموجيات من منشورات هذا المصدر." + on_desc, off_desc = "تُزال الإيموجيات من منشورات المصدر.", "تبقى الإيموجيات في منشورات المصدر." + elif kind == "source_content": + try: + source_id, ctype = target.split("~", 1) + except ValueError: + await callback.answer("فلتر محتوى غير صالح.", show_alert=True) + return + state = bool(db.get_source_content_types(source_id).get(ctype, True)) + title, purpose = "📰 نوع المحتوى", "يحدد هل يستقبل المصدر هذا النوع من المنشورات." + on_desc, off_desc = "يتم استقبال هذا النوع من المصدر.", "يتم تجاهل هذا النوع من المصدر." + elif kind.startswith("link_"): + key = kind + state = bool((db.get_channel(ch_id) or {}).get(key, False)) + labels = {"link_remove_tg": "روابط Telegram", "link_remove_tg_user": "مستخدمو Telegram", "link_remove_web": "روابط المواقع"} + title, purpose = "🔗 " + labels.get(key, key), "يحدد هل يُزال هذا النوع من الروابط من منشورات القناة." + on_desc, off_desc = "تُزال هذه الروابط من المنشورات.", "تبقى هذه الروابط في المنشورات." + elif kind == "tail_min": + cfg = db.get_channel_config(ch_id) if hasattr(db, "get_channel_config") else {} + state = int(cfg.get("tail_min_words", 20) or 0) > 0 + title, purpose = "🔢 الحد الأدنى للتوقيع", "يحدد هل يُطبّق الحد الأدنى للكلمات قبل إضافة التوقيع." + on_desc, off_desc = "يُضاف التوقيع عند بلوغ الحد الأدنى الحالي.", "لا يُطبّق حد أدنى للكلمات." + elif kind == "tail_pos": + position = db.get_channel_tail_position(ch_id) if hasattr(db, "get_channel_tail_position") else "bottom" + state = position == "top" + title, purpose = "📍 مكان التوقيع", "يحدد موضع التوقيع في أعلى المنشور أو أسفله." + on_desc, off_desc = "يوضع التوقيع أعلى المنشور.", "يوضع التوقيع أسفل المنشور." + elif kind == "pause": + ch = db.get_channel(ch_id) or {} + state = not bool(ch.get("paused", False)) + title, purpose = "⏯️ تشغيل القناة", "يحدد هل تستمر القناة في معالجة ونشر المنشورات." + on_desc, off_desc = "تستمر القناة في العمل والنشر.", "تتوقف القناة مؤقتاً عن المعالجة والنشر." + elif kind == "assign": + try: + rtype, ch_id, item_id = target.split("~", 2) + except ValueError: + await callback.answer("تعيين مورد غير صالح.", show_alert=True) + return + info = _RESOURCE_MAP.get(rtype) + if not info: + await callback.answer("نوع مورد غير معروف.", show_alert=True) + return + if rtype == "bots" and hasattr(db, "mapper"): + state = bool(db.mapper.is_assigned(item_id, ch_id)) + else: + cfg = db.get_channel_config(ch_id) or {} + state = str(item_id) in [str(x) for x in cfg.get(info["cfg_key"], [])] + title, purpose = "🔧 تعيين المورد", "يحدد هل هذا المورد مرتبط بهذه القناة." + on_desc, off_desc = "يُستخدم المورد مع هذه القناة.", "لا يُستخدم المورد مع هذه القناة." + elif kind == "session": + item = db.get_session(target) or {} + state = bool(item.get("enabled", True)) + title, purpose = "🔐 الجلسة", "يحدد هل تكون جلسة Telegram متاحة للتشغيل." + on_desc, off_desc = "تبقى الجلسة متاحة للتشغيل.", "تتوقف الجلسة عن التشغيل." + elif kind == "ai_key": + item = db.get_ai_key(target) or {} + state = bool(item.get("enabled", True)) + title, purpose = "🤖 مفتاح الذكاء الاصطناعي", "يحدد هل يمكن استخدام هذا المفتاح في عمليات AI." + on_desc, off_desc = "يمكن استخدام المفتاح.", "لا يُستخدم المفتاح." + elif kind == "publishing_bot": + item = db.get_publishing_bot(target) or {} + state = bool(item.get("enabled", True)) + title, purpose = "🤖 بوت النشر", "يحدد هل يمكن استخدام بوت النشر هذا." + on_desc, off_desc = "يبقى البوت متاحاً للنشر.", "يتوقف استخدام البوت للنشر." + elif kind == "website": + item = db.get_website(target) or {} + state = bool(item.get("enabled", True)) + title, purpose = "🌐 الموقع", "يحدد هل يمكن استخدام مصدر الموقع هذا." + on_desc, off_desc = "يبقى الموقع متاحاً للاستخدام.", "يتوقف استخدام الموقع." + else: + await callback.answer("إعداد غير معروف.", show_alert=True) + return + current = "✅ مفعّل" if state else "❌ متوقف" + text = f"{title}\n\nوظيفة الإعداد:\n{purpose}\n\nالحالة الحالية:\n{current}\n\nعند التشغيل:\n{on_desc}\n\nعند الإيقاف:\n{off_desc}" + rows = [[InlineKeyboardButton("✅ تشغيل", callback_data=f"ui_set|{kind}|{target}|{back_token}|1")], [InlineKeyboardButton("❌ إيقاف", callback_data=f"ui_set|{kind}|{target}|{back_token}|0")], [InlineKeyboardButton("🔙 رجوع", callback_data=back_target)]] + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def ui_setting_set(client, callback): + """يحفظ اختيار المستخدم ثم يعيد فتح صفحة الإعداد نفسها بالحالة الجديدة.""" + parts = callback.data.split("|", 4) + if len(parts) != 5: + await callback.answer("طلب غير صالح.", show_alert=True) + return + _, kind, target, back, desired_raw = parts + back = back.replace("~", "|") if back else (_peek_prev_back(callback) or "main_menu") + desired = desired_raw == "1" + ch_id = target if target != "global" else None + if kind == "short_posts": + current = is_ignore_short_posts_enabled_for_channel(ch_id) if ch_id else is_ignore_short_posts_enabled() + if current != desired: + if ch_id and hasattr(db, "set_channel_ignore_short_posts"): + db.set_channel_ignore_short_posts(ch_id, desired) + elif hasattr(db, "set_ignore_short_posts"): + db.set_ignore_short_posts(desired) + label = "منع النصوص القصيرة" + result = "سيتم منع المنشورات النصية القصيرة في هذه القناة." if desired else "سيتم نشر المنشورات النصية القصيرة بشكل طبيعي." + elif kind == "bold": + ch = db.get_channel(ch_id) or {} + current = bool(ch.get("bold_publish", True)) + if current != desired: + db.update_channel(ch_id, "bold_publish", desired) + label, result = "الخط السميك", "سيُستخدم الخط السميك عند توفره." if desired else "لن يُفعّل الخط السميك." + elif kind == "title_quote": + cfg = db.get_channel_config(ch_id) if hasattr(db, "get_channel_config") else {} + current = bool(cfg.get("title_quote")) + if current != desired and hasattr(db, "set_channel_title_quote"): + db.set_channel_title_quote(ch_id, desired) + label, result = "اقتباس العنوان", "سيظهر العنوان داخل اقتباس." if desired else "سيُنشر العنوان بصيغة عادية." + elif kind == "signature_quote": + cfg = db.get_channel_config(ch_id) if hasattr(db, "get_channel_config") else {} + current = bool(cfg.get("signature_quote")) + if current != desired and hasattr(db, "set_channel_signature_quote"): + db.set_channel_signature_quote(ch_id, desired) + label, result = "اقتباس التوقيع", "سيظهر التوقيع داخل اقتباس." if desired else "سيُنشر التوقيع بصيغة عادية." + elif kind == "preview": + current = not bool(db.get_channel_disable_preview(ch_id)) if hasattr(db, "get_channel_disable_preview") else True + if current != desired and hasattr(db, "set_channel_disable_preview"): + db.set_channel_disable_preview(ch_id, not desired) + label, result = "معاينة الروابط", "ستظهر معاينة الروابط." if desired else "ستُنشر الروابط دون معاينة." + elif kind == "maintenance": + current = bool(db.is_maintenance_mode()) if hasattr(db, "is_maintenance_mode") else False + if current != desired and hasattr(db, "set_maintenance_mode"): + db.set_maintenance_mode(desired) + label, result = "وضع الصيانة", "توقف النشر واستمر فحص المصادر." if desired else "عاد النشر إلى العمل الطبيعي." + elif kind == "notification": + settings = db.get_notification_settings() if hasattr(db, "get_notification_settings") else {} + current = bool(settings.get(target, True)) + if current != desired and hasattr(db, "set_notification_setting"): + db.set_notification_setting(target, desired) + label, result = "التنبيه", "سيتم إرسال التنبيه." if desired else "لن يتم إرسال التنبيه." + elif kind.startswith("quote_"): + qtype = kind.split("_", 1)[1] + current = bool(get_channel_quote_types_safe(ch_id).get(qtype, False)) + if current != desired and hasattr(db, "set_channel_quote_type"): + db.set_channel_quote_type(ch_id, qtype, desired) + label, result = "اقتباس النوع", "سيُنشر النوع داخل اقتباس رسمي." if desired else "سيُنشر النوع بصيغته العادية." + elif kind == "tail": + current = bool(db.get_channel_tail_enabled(ch_id)) if hasattr(db, "get_channel_tail_enabled") else True + if current != desired and hasattr(db, "set_channel_tail_enabled"): + db.set_channel_tail_enabled(ch_id, desired) + label, result = "التوقيع", "سيُضاف التوقيع إلى المنشورات." if desired else "لن يُضاف التوقيع إلى المنشورات." + elif kind == "quote_type": + try: + ch_id, qtype = target.split("~", 1) + except ValueError: + await callback.answer("إعداد اقتباس غير صالح.", show_alert=True) + return + current = bool(get_channel_quote_types_safe(ch_id).get(qtype, False)) + if current != desired and hasattr(db, "set_channel_quote_type"): + db.set_channel_quote_type(ch_id, qtype, desired) + label, result = "اقتباس النوع", "سيُنشر النوع داخل اقتباس رسمي." if desired else "سيُنشر النوع بصيغته العادية." + elif kind == "source_enabled": + current = not bool(db.is_source_paused(target)) + if current != desired: + db.set_source_paused(target, not desired) + label, result = "تشغيل المصدر", "يستمر استقبال منشورات المصدر." if desired else "يتوقف استقبال منشورات المصدر مؤقتاً." + elif kind == "source_emoji": + current = bool(db.get_source_remove_emoji(target)) + if current != desired: + db.set_source_remove_emoji(target, desired) + label, result = "إزالة الإيموجي", "تُزال الإيموجيات من منشورات المصدر." if desired else "تبقى الإيموجيات في منشورات المصدر." + elif kind == "source_content": + try: + source_id, ctype = target.split("~", 1) + except ValueError: + await callback.answer("فلتر محتوى غير صالح.", show_alert=True) + return + current = bool(db.get_source_content_types(source_id).get(ctype, True)) + if current != desired: + ok = db.set_source_content_type(source_id, ctype, desired) + if ok is False: + await callback.answer("لا يمكن إيقاف آخر نوع محتوى.", show_alert=True) + callback.data = f"ui_info|{kind}|{target}|{back.replace('|', '~')}" + await ui_setting_info_menu(client, callback) + return + label, result = "نوع المحتوى", "يتم استقبال هذا النوع من المصدر." if desired else "يتم تجاهل هذا النوع من المصدر." + elif kind.startswith("link_"): + key = kind + ch = db.get_channel(ch_id) or {} + current = bool(ch.get(key, False)) + if current != desired: + db.update_channel(ch_id, key, desired) + label, result = "فلتر الروابط", "تُزال هذه الروابط من المنشورات." if desired else "تبقى هذه الروابط في المنشورات." + elif kind == "tail_min": + current = int(db.get_channel_tail_min_words(ch_id) if hasattr(db, "get_channel_tail_min_words") else 20) >= 20 + if current != desired and hasattr(db, "set_channel_tail_min_words"): + db.set_channel_tail_min_words(ch_id, 20 if desired else 0) + label, result = "الحد الأدنى للتوقيع", "يُطبّق حد 20 كلمة للتوقيع." if desired else "لا يُطبّق حد أدنى للكلمات." + elif kind == "tail_pos": + current = (db.get_channel_tail_position(ch_id) if hasattr(db, "get_channel_tail_position") else "bottom") == "top" + if current != desired and hasattr(db, "set_channel_tail_position"): + db.set_channel_tail_position(ch_id, "top" if desired else "bottom") + label, result = "مكان التوقيع", "يوضع التوقيع أعلى المنشور." if desired else "يوضع التوقيع أسفل المنشور." + elif kind == "pause": + ch = db.get_channel(ch_id) or {} + current = not bool(ch.get("paused", False)) + if current != desired: + db.update_channel(ch_id, "paused", not desired) + label, result = "تشغيل القناة", "تستمر القناة في العمل والنشر." if desired else "تتوقف القناة مؤقتاً عن المعالجة والنشر." + elif kind == "assign": + try: + rtype, ch_id, item_id = target.split("~", 2) + except ValueError: + await callback.answer("تعيين مورد غير صالح.", show_alert=True) + return + info = _RESOURCE_MAP.get(rtype) + if not info: + await callback.answer("نوع مورد غير معروف.", show_alert=True) + return + if rtype == "bots" and hasattr(db, "mapper"): + current = bool(db.mapper.is_assigned(item_id, ch_id)) + else: + cfg = db.get_channel_config(ch_id) or {} + current = str(item_id) in [str(x) for x in cfg.get(info["cfg_key"], [])] + if current != desired: + if rtype == "bots" and hasattr(db, "mapper"): + if desired: + db.mapper.assign(item_id, ch_id) + token = db.bot_manager.get_token(item_id) if hasattr(db, "bot_manager") else "" + if token: + try: + await verifier.check_bot_in_channel(item_id, ch_id, force=True) + except Exception: + pass + else: + db.mapper.unassign(item_id, ch_id) + else: + values = list(cfg.get(info["cfg_key"], [])) + if desired and str(item_id) not in [str(x) for x in values]: + values.append(item_id) + elif not desired: + values = [x for x in values if str(x) != str(item_id)] + db.update_channel_config(ch_id, **{info["cfg_key"]: values}) + label, result = "تعيين المورد", "سيُستخدم المورد مع هذه القناة." if desired else "لن يُستخدم المورد مع هذه القناة." + elif kind == "session": + item = db.get_session(target) or {} + current = bool(item.get("enabled", True)) + if current != desired: + db.set_session_enabled(target, desired) + label, result = "الجلسة", "تبقى الجلسة متاحة للتشغيل." if desired else "تتوقف الجلسة عن التشغيل." + elif kind == "ai_key": + item = db.get_ai_key(target) or {} + current = bool(item.get("enabled", True)) + if current != desired: + db.set_ai_key_enabled(target, desired) + label, result = "مفتاح الذكاء الاصطناعي", "يمكن استخدام المفتاح." if desired else "لا يُستخدم المفتاح." + elif kind == "publishing_bot": + item = db.get_publishing_bot(target) or {} + current = bool(item.get("enabled", True)) + if current != desired: + db.set_publishing_bot_enabled(target, desired) + label, result = "بوت النشر", "يبقى البوت متاحاً للنشر." if desired else "يتوقف استخدام البوت للنشر." + elif kind == "website": + item = db.get_website(target) or {} + current = bool(item.get("enabled", True)) + if current != desired: + db.set_website_enabled(target, desired) + label, result = "الموقع", "يبقى الموقع متاحاً للاستخدام." if desired else "يتوقف استخدام الموقع." + else: + await callback.answer("إعداد غير معروف.", show_alert=True) + return + await callback.answer(f"✅ تم {'تشغيل' if desired else 'إيقاف'} {label}.", show_alert=True) + callback.data = f"ui_info|{kind}|{target}|{back.replace('|', '~')}" + await ui_setting_info_menu(client, callback) +async def action_info_menu(client, callback): + """صفحة شرح عامة للإجراءات قبل التنفيذ، مع الحفاظ على callback التنفيذي الأصلي.""" + parts = callback.data.split("|", 2) + if len(parts) != 3: + await callback.answer("طلب غير صالح.", show_alert=True) + return + _, action, payload = parts + descriptions = { + "testpub": ("🧪 اختبار نشر القناة", "يرسل منشور اختبار فعلياً إلى هذه القناة للتحقق من صلاحية النشر وتطبيق تنسيق القناة الحالي.", "▶️ إرسال اختبار النشر"), + "testsrc": ("🧪 اختبار المصدر", "يفحص إمكانية الوصول إلى المصدر ويعرض نوعه وآخر رسالة متاحة والقنوات المستهدفة دون تغيير إعداداته.", "▶️ اختبار المصدر"), + "chbotcheck": ("🤖 فحص بوت القناة", "يتحقق من وجود بوت النشر داخل القناة وصلاحياته، ثم يعرض الحالة الفعلية.", "▶️ بدء فحص البوت"), + "test_all_channels": ("🧪 اختبار كل القنوات", "ينفذ اختبار نشر للقنوات غير المتوقفة ويعرض عدد القنوات الناجحة والفاشلة.", "▶️ اختبار كل القنوات"), + "full_check": ("🔍 الفحص الشامل", "يفحص الجلسة والبوت والوسيطة وقنوات النشر والمصادر دون تغيير إعداداتها.", "▶️ بدء الفحص الشامل"), + "preview": ("👁 معاينة المنشور", "يعرض تقريراً يوضح كيف ستطبق إعدادات القناة الحالية على منشور تجريبي قبل النشر.", "▶️ عرض المعاينة"), + "clear_errors": ("🗑 مسح الأخطاء", "يمسح سجل الأخطاء المعروض في لوحة الأخطاء فقط، ولا يغيّر إعدادات النشر أو السجل التشغيلي العام.", "▶️ مسح سجل الأخطاء"), + "stats": ("📊 الإحصائيات", "يعرض إجمالي المنشورات والقنوات والمصادر والكلمات المحظورة وتفصيل المنشورات حسب القناة.", "▶️ عرض الإحصائيات"), + "export": ("📥 تصدير البيانات", "ينشئ ملف JSON يحتوي إعدادات وبيانات البوت الحالية ويرسله كنسخة احتياطية.", "▶️ تصدير البيانات"), + "srcstats": ("📊 إحصائيات المصدر", "يعرض أرقام الاستلام والنشر والرفض والتجاهل والتكرار والأخطاء وآخر حدث للمصدر.", "▶️ عرض إحصائيات المصدر"), + "srclog": ("📋 سجل المصدر", "يعرض آخر العمليات المسجلة لهذا المصدر مع الوقت ونوع الحدث ورقم الرسالة والسبب.", "▶️ عرض سجل المصدر"), + "session_test": ("🧪 اختبار الجلسة", "يتحقق من اتصال جلسة Telegram المحددة دون تغيير إعداد تفعيلها.", "▶️ اختبار الجلسة"), + "ai_test": ("🧪 اختبار مفتاح AI", "يتحقق من اتصال مزود الذكاء الاصطناعي للمفتاح المحدد دون تغيير حالته.", "▶️ اختبار المفتاح"), + "bot_test": ("🧪 اختبار بوت النشر", "يتحقق من توكن بوت النشر واتصاله، مع تحديث إحصائية الاستخدام عند نجاح الاختبار وفق الدالة الأصلية.", "▶️ اختبار البوت"), + "bot_verify": ("🔍 فحص قنوات البوت", "يفحص صلاحيات بوت النشر في القنوات المرتبطة به ويعرض عدد القنوات الموثوقة وغير الموثوقة.", "▶️ فحص القنوات"), + "web_test": ("🧪 اختبار الموقع", "يجلب الموقع المحدد ويتحقق من استجابته ويعرض رمز HTTP أو عدد الأحرف عند النجاح.", "▶️ اختبار الموقع"), + "test": ("🧪 اختبار القناة", "ينفذ اختباراً للقناة للتحقق من إمكانية النشر.", "▶️ تنفيذ الاختبار"), + "import": ("📥 استيراد البيانات", "يستورد إعدادات البوت من ملف JSON مدعوم. ⚠️ سيتم استبدال أو تحديث البيانات وفق سلوك الاستيراد الحالي، وسيبقى انتظار الملف عبر نفس MessageHandler وuser_state.", "📥 متابعة الاستيراد"), + "copysrc": ("📋 نسخ إعدادات المصدر", "يحفظ إعدادات هذا المصدر في user_state لتتمكن من لصقها في مصدر آخر أو عدة مصادر. لن يبدأ النسخ إلى مصادر أخرى من هذه الصفحة.", "📋 متابعة نسخ الإعدادات"), + "pastesrc": ("📋 لصق إعدادات المصدر", "يلصق الإعدادات المنسوخة في هذا المصدر باستخدام user_state الحالي ثم يعرض نتيجة العملية الأصلية.", "📋 تنفيذ اللصق"), + "bulkpastesrc": ("📋 لصق الإعدادات لعدة مصادر", "يفتح نفس MessageHandler الحالي لانتظار قائمة المصادر، مع الحفاظ على user_state وآلية الإدخال الأصلية.", "📋 متابعة اللصق المتعدد"), + "restore": ("♻️ استعادة العنصر", "يعيد العنصر من سلة المحذوفات إلى حالته السابقة. سيُستخدم مسار الاستعادة الأصلي ثم تظهر نتيجة العملية وتعود إلى السلة.", "♻️ متابعة الاستعادة"), + "delete_session": ("🗑 حذف الجلسة", "ينقل الجلسة إلى سلة المحذوفات إذا لم تكن مستخدمة. سيجري فحص dependencies الأصلي قبل التنفيذ ولن يتم تجاوز تحذير الاستخدام.", "🗑 متابعة حذف الجلسة"), + "delete_ai": ("🗑 حذف مفتاح AI", "ينقل مفتاح AI إلى سلة المحذوفات إذا لم يكن مستخدماً. سيبقى فحص dependencies الأصلي كما هو.", "🗑 متابعة حذف المفتاح"), + "delete_bot": ("🗑 حذف بوت النشر", "ينقل بوت النشر إلى سلة المحذوفات إذا لم يكن مرتبطاً بقنوات. سيبقى فحص dependencies الأصلي كما هو.", "🗑 متابعة حذف البوت"), + "delete_web": ("🗑 حذف الموقع", "ينقل الموقع إلى سلة المحذوفات وفق سلوكه الحالي، مع الحفاظ على أي فحص dependencies موجود في الدالة الأصلية.", "🗑 متابعة حذف الموقع"), + "delete_channel": ("🗑 حذف قناة النشر", "يفتح نفس قائمة اختيار القناة ثم يبقي زر التأكيد الحالي قبل الحذف الفعلي.", "🗑 متابعة حذف القناة"), + "purge": ("🗑 حذف المنشورات", "يفتح صفحة اختيار/تأكيد نوع المنشورات ثم يحافظ على تأكيد الحذف الحالي قبل التنفيذ.", "🗑 متابعة حذف المنشورات"), + "trash_permdel": ("🗑 الحذف النهائي من السلة", "يحذف العنصر نهائياً من سلة المحذوفات ولا يمكن التراجع عن العملية. ستبقى صفحة التأكيد الحالية.", "🗑 متابعة الحذف النهائي"), + "trash_empty": ("🗑 تفريغ سلة المحذوفات", "يحذف جميع عناصر السلة نهائياً ولا يمكن التراجع. ستبقى صفحة التأكيد الحالية.", "🗑 متابعة تفريغ السلة"), + } + title, desc, button = descriptions.get(action, ("ℹ️ شرح العملية", "راجع وظيفة العملية قبل تنفيذها.", "▶️ تنفيذ العملية")) + execute_token, back_token = (payload.split("^", 1) + [None])[:2] if "^" in payload else (payload, None) + back = back_token.replace("~", "|") if back_token else (_peek_prev_back(callback) or "main_menu") + text = f"{title}\n\nوظيفة العملية:\n{desc}\n\nلن يتم التنفيذ حتى تضغط زر التنفيذ." + await safe_edit(callback, text, InlineKeyboardMarkup([ + [InlineKeyboardButton(button, callback_data=f"ui_action_exec|{action}|{execute_token}^{back.replace('|', '~')}")], + [InlineKeyboardButton("🔙 رجوع", callback_data=back)], + ])) + + +async def action_execute_menu(client, callback): + """ينفذ Action محدداً عبر دالته الأصلية، ثم يعرض نتيجتها أو يعيد صفحة المورد.""" + parts = callback.data.split("|", 2) + if len(parts) != 3 or "^" not in parts[2]: + await callback.answer("طلب تنفيذ غير صالح.", show_alert=True) + return + _, action, payload = parts + execute_token, back_token = payload.split("^", 1) + execute_data = execute_token.replace("~", "|") + back_data = back_token.replace("~", "|") + executors = { + "testpub": test_publish_channel, + "testsrc": test_source, + "chbotcheck": channel_bot_check, + "test_all_channels": test_all_channels, + "full_check": full_check_menu, + "preview": preview_post, + "clear_errors": clear_errors, + "stats": show_stats, + "export": export_callback, + "srcstats": source_stats_menu, + "srclog": source_log_menu, + "session_test": test_session, + "ai_test": test_ai_key, + "bot_test": test_bot, + "bot_verify": verify_bot_channels, + "web_test": test_website, + "import": import_callback, + "copysrc": copy_source_settings_prompt, + "pastesrc": paste_source_settings, + "bulkpastesrc": bulk_paste_source_prompt, + "restore": trash_restore_item, + "delete_session": delete_session_with_deps, + "delete_ai": delete_ai_key_with_deps, + "delete_bot": delete_bot_with_deps, + "delete_web": delete_website_with_deps, + "delete_channel": delete_channel_prompt, + "purge": purge_published_prompt, + "trash_permdel": trash_permanent_delete_prompt, + "trash_empty": trash_empty_prompt, + } + if action not in executors: + await callback.answer("هذا الإجراء غير متاح.", show_alert=True) + return + callback.data = execute_data + await executors[action](client, callback) + return_handlers = { + "testpub": test_settings_menu, + "export": backup_menu, + "session_test": show_session_settings, + "ai_test": show_ai_key_settings, + "bot_test": show_bot_settings, + "web_test": show_website_settings, + } + if action in return_handlers: + callback.data = back_data + await return_handlers[action](client, callback) + + + +def register_bot_handlers(app: Client): + app.add_handler(MessageHandler(start, filters.command("start"))) + app.add_handler(MessageHandler(handle_import, filters.document)) + register_blogger_handlers(app) + + async def callback_dispatcher(client, callback): + data = callback.data + if str(data).startswith("ui_ctx|"): + expanded = _expand_ui_callback_data(data) + if expanded is None: + await callback.answer("انتهت صلاحية هذا الزر. افتح القائمة من جديد.", show_alert=True) + return + data = expanded + callback.data = expanded + + if data.startswith("section_menu|"): + await section_menu(client, callback) + return + if data.startswith(("news:", "sports:", "blogger:")): + await section_control_callback(client, callback) + return + if data == "main_menu": + await safe_edit(callback, "القائمة الرئيسية:", main_keyboard) + elif data == "back_stack": + previous = _back_step(callback) + if previous is None: + await callback.answer("لا توجد صفحة سابقة في هذه الجلسة.", show_alert=True) + return + callback.data = previous + if str(previous).startswith("ui_ctx|"): + expanded = _expand_ui_callback_data(previous) + if expanded is None: + await callback.answer("انتهت صلاحية هذا الزر. افتح القائمة من جديد.", show_alert=True) + return + callback.data = expanded + await callback_dispatcher(client, callback) + else: + _push_back(callback) + if data.startswith("ui_info|"): + await ui_setting_info_menu(client, callback) + elif data.startswith("ui_set|"): + await ui_setting_set(client, callback) + elif data.startswith("ui_action_exec|"): + await action_execute_menu(client, callback) + elif data.startswith("ui_action|"): + await action_info_menu(client, callback) + elif data in BLOGGER_CALLBACKS: + await BLOGGER_CALLBACKS[data](client, callback) + elif data.startswith("togglebold_"): + ch_id = data.rsplit("_", 1)[1] + callback.data = f"ui_info|bold|{ch_id}|postset_{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("toggle_short_posts|"): + ch_id = data.split("|", 1)[1] + callback.data = f"ui_info|short_posts|{ch_id}|postset_{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("ch_titlequote_"): + ch_id = data.rsplit("_", 1)[1] + callback.data = f"ui_info|title_quote|{ch_id}|quotemenu_{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("ch_sigquote_"): + ch_id = data.rsplit("_", 1)[1] + callback.data = f"ui_info|signature_quote|{ch_id}|quotemenu_{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("ch_preview_"): + ch_id = data.rsplit("_", 1)[1] + callback.data = f"ui_info|preview|{ch_id}|postset_{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("blogger_"): + from modules.blogger.ui import DYNAMIC_PREFIXES + matched = False + for prefix, handler_name in DYNAMIC_PREFIXES.items(): + if data.startswith(prefix): + import importlib + mod = importlib.import_module("modules.blogger.ui") + handler = getattr(mod, handler_name) + await handler(client, callback) + matched = True + break + if not matched: + await callback.answer("أمر غير معروف.") + elif data == "menu_channels": + await menu_channels(client, callback) + elif data.startswith("ch_extended_"): + await channel_extended_settings(client, callback) + elif data.startswith("ch_titlequote_"): + await toggle_channel_title_quote(client, callback) + elif data.startswith("ch_sigquote_"): + await toggle_channel_signature_quote(client, callback) + elif data.startswith("ch_preview_"): + await toggle_channel_preview(client, callback) + elif data.startswith("postset_"): + await post_settings_menu(client, callback) + elif data.startswith("srcset_"): + await source_settings_channel_menu(client, callback) + elif data.startswith("tails_"): + await tail_settings_menu(client, callback) + elif data.startswith("testset_"): + await test_settings_menu(client, callback) + elif data.startswith("preview_"): + ch_id = data.split("_", 1)[1] + callback.data = f"ui_action|preview|preview_{ch_id}^testset_{ch_id}" + await action_info_menu(client, callback) + elif data.startswith("tailtoggle_"): + ch_id = data.rsplit("_", 1)[1] + callback.data = f"ui_info|tail|{ch_id}|tails_{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("tailmintoggle_"): + ch_id = data.rsplit("_", 1)[1] + callback.data = f"ui_info|tail_min|{ch_id}|tails_{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("tailpos_"): + ch_id = data.rsplit("_", 1)[1] + callback.data = f"ui_info|tail_pos|{ch_id}|tails_{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("genset_copy_"): + await general_settings_copy(client, callback) + elif data.startswith("genset_paste_confirm_"): + await general_settings_paste_confirm(client, callback) + elif data.startswith("genset_paste_"): + await general_settings_paste(client, callback) + elif data.startswith("genset_reset_confirm_"): + await general_settings_reset_confirm(client, callback) + elif data.startswith("genset_reset_"): + await general_settings_reset(client, callback) + elif data.startswith("genset_summary_"): + await general_settings_summary(client, callback) + elif data.startswith("genset_"): + await general_settings_menu(client, callback) + elif data.startswith("sysset_"): + await system_channel_menu(client, callback) + elif data == "system_menu": + await system_menu(client, callback) + elif data.startswith("purgepage_"): + await purge_published_menu(client, callback) + elif data.startswith("chwordadd|"): + await channel_add_blocked_word_prompt(client, callback) + elif data.startswith("chworddelidx|"): + await confirm_channel_del_blocked_word(client, callback) + elif data.startswith("chworddel|"): + await channel_del_blocked_word_prompt(client, callback) + elif data.startswith("chwords|"): + await channel_blocked_words_menu(client, callback) + elif data.startswith("chlinks|"): + await channel_links_menu(client, callback) + elif data.startswith("chbotcheck|"): + ch_id = data.split("|", 1)[1] + callback.data = f"ui_action|chbotcheck|chbotcheck~{ch_id}^ch_{ch_id}" + await action_info_menu(client, callback) + elif data.startswith("chlinktg|") or data.startswith("chlinktguser|") or data.startswith("chlinkweb|"): + prefix, ch_id = data.split("|", 1) + kind = { + "chlinktg": "link_remove_tg", + "chlinktguser": "link_remove_tg_user", + "chlinkweb": "link_remove_web", + }[prefix] + callback.data = f"ui_info|{kind}|{ch_id}|chlinks~{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("chdeltermadd|"): + await channel_add_delete_term_prompt(client, callback) + elif data.startswith("chdeltermdel|"): + await channel_del_delete_term_prompt(client, callback) + elif data.startswith("chdelterms|"): + await channel_delete_terms_menu(client, callback) + elif data.startswith("ch_"): + await channel_settings(client, callback) + elif data == "add_channel": + await add_channel_prompt(client, callback) + elif data.startswith("togglebold_"): + await toggle_channel_bold(client, callback) + elif data.startswith("quotemenu_"): + await channel_quote_menu(client, callback) + elif data.startswith("toggleqtype|"): + _, ch_id, qtype = data.split("|", 2) + callback.data = f"ui_info|quote_type|{ch_id}~{qtype}|quotemenu_{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("togglequote_"): + # Compatibility/navigation alias: this opens the quote menu and is not a Boolean setter. + await toggle_channel_quote(client, callback) + elif data.startswith("hashtags_"): + await channel_hashtags_menu(client, callback) + elif data.startswith("addhashtags_"): + await add_channel_hashtags_prompt(client, callback) + elif data.startswith("delhashtags_"): + await del_channel_hashtags_prompt(client, callback) + elif data.startswith("testpub_"): + ch_id = data.split("_", 1)[1] + callback.data = f"ui_action|testpub|testpub_{ch_id}^testset_{ch_id}" + await action_info_menu(client, callback) + elif data.startswith("purgepub|"): + execute_token = data.replace("|", "~") + _, ch_id, kind = data.split("|", 2) + callback.data = f"ui_action|purge|{execute_token}^purgepage_{ch_id}" + await action_info_menu(client, callback) + elif data.startswith("confirmpurge|"): + await confirm_purge_published(client, callback) + elif data == "toggle_maintenance" or data.startswith("toggle_maintenance|"): + ch_id = data.split("|", 1)[1] if "|" in data else None + back = f"ops_menu~{ch_id}" if ch_id else "ops_menu" + callback.data = f"ui_info|maintenance|global|{back}" + await ui_setting_info_menu(client, callback) + elif data == "toggle_short_posts" or data.startswith("toggle_short_posts|"): + ch_id = data.split("|", 1)[1] if "|" in data else "global" + back = f"ops_menu~{ch_id}" if ch_id != "global" else "ops_menu" + callback.data = f"ui_info|short_posts|{ch_id}|{back}" + await ui_setting_info_menu(client, callback) + elif data.startswith("toggle_notif_"): + key = data.split("toggle_notif_", 1)[1].split("|", 1)[0] + notif_ch = data.split("|", 1)[1] if "|" in data else None + callback.data = f"ui_info|notification|{key}|notifications_menu~{notif_ch}" if notif_ch else f"ui_info|notification|{key}|notifications_menu" + await ui_setting_info_menu(client, callback) + elif data.startswith("legacy_toggle_notif_"): + key = data.split("legacy_toggle_notif_", 1)[1] + notif_ch = data.split("|", 1)[1] if "|" in data else None + if key in db.NOTIFICATION_TYPES: + settings = db.get_notification_settings() + db.set_notification_setting(key, not settings.get(key, True)) + await callback.answer("تم التبديل.") + callback.data = f"notifications_menu|{notif_ch}" if notif_ch else "notifications_menu" + await notifications_menu(client, callback) + else: + await callback.answer("غير معروف.") + elif data.startswith("toggle_assign_"): + parts = data.split("_", 4) + if len(parts) == 5: + _, _, rtype, ch_id, item_id = parts + callback.data = f"ui_info|assign|{rtype}~{ch_id}~{item_id}|assign_{rtype}_{ch_id}" + await ui_setting_info_menu(client, callback) + else: + await toggle_assign_resource(client, callback) + elif data.startswith("toggle_"): + ch_id = data.split("_", 1)[1] + callback.data = f"ui_info|pause|{ch_id}|ch_{ch_id}" + await ui_setting_info_menu(client, callback) + elif data.startswith("delchannel_"): + ch_id = data.split("_", 1)[1] + callback.data = f"ui_action|delete_channel|delchannel_{ch_id}^genset_{ch_id}" + await action_info_menu(client, callback) + elif data.startswith("confirm_del_"): + await confirm_delete_channel(client, callback) + elif data.startswith("tailmenu_"): + await tail_menu(client, callback) + elif data.startswith("edittail_"): + await edit_tail_prompt(client, callback) + elif data.startswith("deltail_"): + await delete_tail(client, callback) + elif data == "menu_public_src": + await menu_public_sources(client, callback) + elif data == "add_public_src": + await add_public_src_prompt(client, callback) + elif data == "del_public_src": + await del_public_src_prompt(client, callback) + elif data.startswith("del_pub_idx_"): + await confirm_del_public_src(client, callback) + elif data == "menu_blocked": + await menu_blocked_words(client, callback) + elif data == "add_blocked_word": + await add_blocked_word_prompt(client, callback) + elif data == "del_blocked_word": + await del_blocked_word_prompt(client, callback) + elif data.startswith("delword_idx_"): + await confirm_del_blocked_word(client, callback) + elif data.startswith("specsrc_"): + await manage_special_sources(client, callback) + elif data.startswith("addspecsrc_"): + await add_special_source_prompt(client, callback) + elif data.startswith("delspecsrc_"): + await delete_special_source_prompt(client, callback) + elif data.startswith("confdelspec_"): + await confirm_delete_special_source(client, callback) + elif data.startswith("srcset|"): + await source_settings_menu(client, callback) + elif data.startswith("togglesource|"): + _, source_id, back = data.split("|", 2) + back_token = back.replace("|", "~") + callback.data = f"ui_info|source_enabled|{source_id}|srcset~{source_id}~{back_token}" + await ui_setting_info_menu(client, callback) + elif data.startswith("toggleemoji|"): + _, source_id, back = data.split("|", 2) + back_token = back.replace("|", "~") + callback.data = f"ui_info|source_emoji|{source_id}|srcset~{source_id}~{back_token}" + await ui_setting_info_menu(client, callback) + elif data.startswith("contentmenu|"): + await source_content_menu(client, callback) + elif data.startswith("togglectype|"): + _, source_id, ctype, back = data.split("|", 3) + back_token = back.replace("|", "~") + callback.data = f"ui_info|source_content|{source_id}~{ctype}|contentmenu~{source_id}~{back_token}" + await ui_setting_info_menu(client, callback) + elif data.startswith("clean_src|"): + await source_cleanup_menu(client, callback) + elif data.startswith("addclean|"): + await add_source_cleanup_prompt(client, callback) + elif data.startswith("delclean|"): + await del_source_cleanup_prompt(client, callback) + elif data == "global_clean": + await global_cleanup_menu(client, callback) + elif data == "addglobalclean": + await add_global_cleanup_prompt(client, callback) + elif data == "delglobalclean": + await del_global_cleanup_prompt(client, callback) + elif data.startswith("speedmenu_"): + await channel_speed_menu(client, callback) + elif data.startswith("setspeed|"): + await set_channel_speed(client, callback) + elif data.startswith("customspeed_"): + await custom_channel_speed_prompt(client, callback) + elif data.startswith("srcstats|"): + _, source_id, back = data.split("|", 2) + execute_token = data.replace("|", "~") + back_token = f"srcset~{source_id}~{back.replace('|', '~')}" + callback.data = f"ui_action|srcstats|{execute_token}^{back_token}" + await action_info_menu(client, callback) + elif data.startswith("srclog|"): + _, source_id, back = data.split("|", 2) + execute_token = data.replace("|", "~") + back_token = f"srcset~{source_id}~{back.replace('|', '~')}" + callback.data = f"ui_action|srclog|{execute_token}^{back_token}" + await action_info_menu(client, callback) + elif data.startswith("testsrc|"): + _, source_id, back = data.split("|", 2) + execute_token = data.replace("|", "~") + back_token = f"srcset~{source_id}~{back.replace('|', '~')}" + callback.data = f"ui_action|testsrc|{execute_token}^{back_token}" + await action_info_menu(client, callback) + elif data.startswith("copysrc|"): + _, source_id, back = data.split("|", 2) + execute_token = data.replace("|", "~") + back_token = f"srcset~{source_id}~{back.replace('|', '~')}" + callback.data = f"ui_action|copysrc|{execute_token}^{back_token}" + await action_info_menu(client, callback) + elif data.startswith("pastesrc|"): + _, source_id, back = data.split("|", 2) + execute_token = data.replace("|", "~") + back_token = f"srcset~{source_id}~{back.replace('|', '~')}" + callback.data = f"ui_action|pastesrc|{execute_token}^{back_token}" + await action_info_menu(client, callback) + elif data.startswith("bulkpastesrc|"): + _, source_id, back = data.split("|", 2) + execute_token = data.replace("|", "~") + back_token = f"srcset~{source_id}~{back.replace('|', '~')}" + callback.data = f"ui_action|bulkpastesrc|{execute_token}^{back_token}" + await action_info_menu(client, callback) + elif data == "system_status" or data.startswith("system_status|"): + await system_status_menu(client, callback) + elif data == "full_check" or data.startswith("full_check|"): + ch_id = data.split("|", 1)[1] if "|" in data else None + execute_token = data.replace("|", "~") + back_token = f"system_status~{ch_id}" if ch_id else "system_status" + callback.data = f"ui_action|full_check|{execute_token}^{back_token}" + await action_info_menu(client, callback) + elif data == "ops_menu" or data.startswith("ops_menu|"): + await operations_menu(client, callback) + elif data == "errors_menu" or data.startswith("errors_menu|"): + await errors_menu(client, callback) + elif data == "clear_errors" or data.startswith("clear_errors|"): + ch_id = data.split("|", 1)[1] if "|" in data else None + execute_token = data.replace("|", "~") + back_token = f"errors_menu~{ch_id}" if ch_id else "errors_menu" + callback.data = f"ui_action|clear_errors|{execute_token}^{back_token}" + await action_info_menu(client, callback) + elif data == "named_backup_prompt": + await named_backup_prompt(client, callback) + elif data == "test_all_channels" or data.startswith("test_all_channels|"): + ch_id = data.split("|", 1)[1] if "|" in data else None + execute_token = data.replace("|", "~") + back_token = f"ops_menu~{ch_id}" if ch_id else "ops_menu" + callback.data = f"ui_action|test_all_channels|{execute_token}^{back_token}" + await action_info_menu(client, callback) + elif data == "stats": + callback.data = "ui_action|stats|stats^main_menu" + await action_info_menu(client, callback) + elif data == "backup_menu": + await backup_menu(client, callback) + elif data == "export_data": + callback.data = "ui_action|export|export_data^backup_menu" + await action_info_menu(client, callback) + elif data == "import_data": + callback.data = "ui_action|import|import_data^backup_menu" + await action_info_menu(client, callback) + elif data == "log_menu" or data.startswith("log_menu|"): + await log_management_menu(client, callback) + elif data.startswith("log_view"): + await view_bot_log(client, callback) + elif data.startswith("log_refresh"): + await view_bot_log(client, callback) + elif data.startswith("log_size"): + await show_log_size(client, callback) + elif data.startswith("log_clear_prompt"): + await clear_log_prompt(client, callback) + elif data.startswith("log_clear_confirm"): + await confirm_clear_log(client, callback) + # Multi-Bot Expansion: Secrets + elif data == "secrets_menu": + await secrets_menu(client, callback) + elif data == "sessions_list": + await sessions_list_menu(client, callback) + elif data == "session_add": + await add_session_prompt(client, callback) + elif data.startswith("session_show_"): + await show_session_settings(client, callback) + elif data.startswith("session_toggle_"): + sid = data.split("session_toggle_", 1)[1] + callback.data = f"ui_info|session|{sid}|session_show_{sid}" + await ui_setting_info_menu(client, callback) + elif data.startswith("session_delete_"): + sid = data.split("session_delete_", 1)[1] + callback.data = f"ui_action|delete_session|session_delete_{sid}^session_show_{sid}" + await action_info_menu(client, callback) + elif data.startswith("session_test_"): + sid = data.split("session_test_", 1)[1] + callback.data = f"ui_action|session_test|session_test_{sid}^session_show_{sid}" + await action_info_menu(client, callback) + elif data == "ai_list": + await ai_list_menu(client, callback) + elif data == "ai_add": + await add_ai_key_prompt(client, callback) + elif data.startswith("ai_show_"): + await show_ai_key_settings(client, callback) + elif data.startswith("ai_toggle_"): + kid = data.split("ai_toggle_", 1)[1] + callback.data = f"ui_info|ai_key|{kid}|ai_show_{kid}" + await ui_setting_info_menu(client, callback) + elif data.startswith("ai_delete_"): + kid = data.split("ai_delete_", 1)[1] + callback.data = f"ui_action|delete_ai|ai_delete_{kid}^ai_show_{kid}" + await action_info_menu(client, callback) + elif data.startswith("ai_test_"): + kid = data.split("ai_test_", 1)[1] + callback.data = f"ui_action|ai_test|ai_test_{kid}^ai_show_{kid}" + await action_info_menu(client, callback) + elif data == "bots_list": + await bots_list_menu(client, callback) + elif data == "bot_add": + await add_bot_prompt(client, callback) + elif data.startswith("bot_rename_"): + await rename_bot_prompt(client, callback) + elif data.startswith("bot_verify_"): + bid = data.split("bot_verify_", 1)[1] + callback.data = f"ui_action|bot_verify|bot_verify_{bid}^bot_show_{bid}" + await action_info_menu(client, callback) + elif data.startswith("bot_show_"): + await show_bot_settings(client, callback) + elif data.startswith("bot_toggle_"): + bid = data.split("bot_toggle_", 1)[1] + callback.data = f"ui_info|publishing_bot|{bid}|bot_show_{bid}" + await ui_setting_info_menu(client, callback) + elif data.startswith("bot_delete_"): + bid = data.split("bot_delete_", 1)[1] + callback.data = f"ui_action|delete_bot|bot_delete_{bid}^bot_show_{bid}" + await action_info_menu(client, callback) + elif data.startswith("bot_test_"): + bid = data.split("bot_test_", 1)[1] + callback.data = f"ui_action|bot_test|bot_test_{bid}^bot_show_{bid}" + await action_info_menu(client, callback) + elif data == "web_list": + await web_list_menu(client, callback) + elif data == "web_add": + await add_website_prompt(client, callback) + elif data.startswith("web_show_"): + await show_website_settings(client, callback) + elif data.startswith("web_toggle_"): + wid = data.split("web_toggle_", 1)[1] + callback.data = f"ui_info|website|{wid}|web_show_{wid}" + await ui_setting_info_menu(client, callback) + elif data.startswith("web_edit_"): + await edit_website_prompt(client, callback) + elif data.startswith("web_delete_"): + wid = data.split("web_delete_", 1)[1] + callback.data = f"ui_action|delete_web|web_delete_{wid}^web_show_{wid}" + await action_info_menu(client, callback) + elif data.startswith("web_test_"): + wid = data.split("web_test_", 1)[1] + callback.data = f"ui_action|web_test|web_test_{wid}^web_show_{wid}" + await action_info_menu(client, callback) + elif data == "trash_menu": + await trash_menu(client, callback) + elif data.startswith("trash_restore_"): + tid = data.split("trash_restore_", 1)[1] + callback.data = f"ui_action|restore|trash_restore_{tid}^trash_menu" + await action_info_menu(client, callback) + elif data.startswith("trash_permdel_"): + tid = data.split("trash_permdel_", 1)[1] + callback.data = f"ui_action|trash_permdel|trash_permdel_{tid}^trash_menu" + await action_info_menu(client, callback) + elif data.startswith("trash_permconfirm_"): + await trash_permanent_delete_confirm(client, callback) + elif data == "trash_empty_prompt": + callback.data = "ui_action|trash_empty|trash_empty_prompt^trash_menu" + await action_info_menu(client, callback) + elif data == "trash_empty_confirm": + await trash_empty_confirm(client, callback) + elif data == "notifications_menu" or data.startswith("notifications_menu|"): + await notifications_menu(client, callback) + elif data.startswith("toggle_assign_"): + await toggle_assign_resource(client, callback) + elif data.startswith("assign_"): + await assign_resource_menu(client, callback) + else: + await callback.answer("غير معروف.") + + app.add_handler(CallbackQueryHandler(callback_dispatcher)) + app.add_handler(MessageHandler(handle_text_input, filters.text & filters.private)) + +def register_user_handlers(app: Client): + # نلتقط كل رسائل حساب المستخدم ثم نفلتر داخل user_message_handler + # هذا يساعدنا نعرف هل SESSION_STRING يلتقط المصادر العامة أو لا + app.add_handler(MessageHandler(user_message_handler)) + +def register_middle_handlers(app: Client): + app.add_handler(MessageHandler(middle_channel_handler, filters.chat(config.MIDDLE_CHANNEL))) + +NOTIFICATION_CHECK_INTERVAL = 300 # 5 دقائق +NOTIFICATION_COOLDOWN = 3600 # إعادة التنبيه بعد ساعة + + +async def notify_admins_custom(text, check_key): + """إرسال إشعار لكل المشرفين مع مراعاة cooldown.""" + now = time.time() + last_ts = _last_alert_ts.get(check_key, 0) + if now - last_ts < NOTIFICATION_COOLDOWN: + return + _last_alert_ts[check_key] = now + for uid in config.ADMINS: + try: + await bot_client.send_message(uid, text) + except Exception as e: + logger.warning(f"فشل إرسال إشعار {check_key} للمشرف {uid}: {e}") + + +async def _check_sessions_health(): + """التأكد من أن Sessions شغالة.""" + for s in db.get_all_sessions(): + status = s.get("status", "") + enabled = s.get("enabled", True) + if not enabled or status in ("stopped", "error"): + await notify_admins_custom( + f"⚠️ **Session متوقفة:** `{s.get('name', s['id'])}`\n" + f"الحالة: {status}\n" + f"يرجى مراجعة إدارة الجلسات.", + "session_stopped" + ) + + +async def _check_ai_key_errors(): + """التأكد من أن مفاتيح AI سليمة.""" + for k in db.get_all_ai_keys(): + stats = db.get_ai_key_stats(k["id"]) + errs = stats.get("error_count", 0) + enabled = stats.get("enabled", True) + if not enabled or errs > 3: + await notify_admins_custom( + f"⚠️ **مفتاح AI به مشكلة:** `{k.get('name', k['id'])}`\n" + f"الأخطاء: {errs}\n" + f"المزوّد: {stats.get('provider', '?')}", + "ai_key_error" + ) + + +async def _check_sources_stopped(): + """التأكد من أن المصادر العامة ليست متوقفة.""" + for src in db.get_all_public_sources_with_meta(): + sid = src.get("id") or src.get("_id") + if sid is None: + continue + meta = db.get_source_meta(sid) + paused = meta.get("paused", False) + if paused: + await notify_admins_custom( + f"⚠️ **مصدر متوقف:** `{meta.get('name', sid)}`\n" + f"تم إيقافه يدوياً أو تلقائياً.", + "source_stopped" + ) + + +async def _check_channels_idle(): + """التأكد من أن القنوات تنشر بانتظام.""" + now = time.time() + for ch in db.get_all_channels(): + if ch.get("paused", False): + continue + cid = ch["id"] + try: + with db.lock: + data = db._read() + pm = data.get("published_messages", {}).get(str(cid), {}) + latest_ts = 0 + for msgs in pm.values(): + if isinstance(msgs, list) and msgs: + last_msg = msgs[-1] + if isinstance(last_msg, dict): + latest_ts = max(latest_ts, last_msg.get("ts", 0)) + if latest_ts and now - latest_ts > 3600: + name = ch.get("name", cid) + await notify_admins_custom( + f"⏰ **قناة لم تنشر منذ أكثر من ساعة:** `{name}`\n" + f"آخر نشر: {time.strftime('%Y-%m-%d %H:%M', time.localtime(latest_ts))}", + "channel_idle_hour" + ) + except Exception: + pass + + +async def _check_backup_fresh(): + """التأكد من أن النسخ الاحتياطي حديث.""" + try: + backups = db.get_named_backups() + if not backups: + await notify_admins_custom( + "⚠️ **لا توجد نسخ احتياطية!**\n" + "يرجى إنشاء نسخة احتياطية قريباً.", + "backup_failed" + ) + return + last = backups[-1] + last_ts = last.get("ts", 0) + now = time.time() + if now - last_ts > 86400: # أكثر من يوم + await notify_admins_custom( + f"⚠️ **آخر نسخة احتياطية قديمة:** {time.strftime('%Y-%m-%d %H:%M', time.localtime(last_ts))}\n" + f"يرجى إنشاء نسخة احتياطية جديدة.", + "backup_failed" + ) + except Exception as e: + await notify_admins_custom( + f"⚠️ **فشل التحقق من النسخ الاحتياطية:** {e}", + "backup_failed" + ) + + +async def _check_db_health(): + """التأكد من سلامة قاعدة البيانات.""" + try: + result = db.verify_or_recover_storage() + if not result.get("ok"): + msg = result.get("message", "خطأ غير معروف في قاعدة البيانات") + await notify_admins_custom( + f"❗ **مشكلة بقاعدة البيانات:** {msg}", + "db_issue" + ) + except Exception as e: + await notify_admins_custom( + f"❗ **استثناء أثناء فحص قاعدة البيانات:** {e}", + "db_issue" + ) + + +async def notification_checks_loop(): + """الحلقة الخلفية لفحص التنبيهات كل 5 دقائق.""" + CHECKS = [ + ("session_stopped", _check_sessions_health), + ("ai_key_error", _check_ai_key_errors), + ("source_stopped", _check_sources_stopped), + ("channel_idle_hour", _check_channels_idle), + ("backup_failed", _check_backup_fresh), + ("db_issue", _check_db_health), + ] + await asyncio.sleep(60) # انتظار دقيقة بعد بدء البوت + while True: + try: + settings = db.get_notification_settings() + for key, check_fn in CHECKS: + if settings.get(key, True): + try: + await check_fn() + except Exception as e: + logger.warning(f"خطأ في فحص {key}: {e}") + except Exception as e: + logger.warning(f"خطأ في حلقة التنبيهات: {e}") + await asyncio.sleep(NOTIFICATION_CHECK_INTERVAL) + + +BOT_VERIFY_INTERVAL = 3600 # إعادة التحقق كل ساعة + + +async def _auto_sync_channel_info(ch_id, ch_name=""): + """مزامنة معلومات القناة مع Telegram.""" + try: + chat = await bot_client.get_chat(int(ch_id)) + title = getattr(chat, "title", "") or "" + username = getattr(chat, "username", "") or "" + link = getattr(chat, "invite_link", "") or "" + if title: + old = db.get_channel(ch_id) or {} + updates = {} + if old.get("name") != title: + updates["name"] = title + if old.get("username") != username: + updates["username"] = username + if old.get("link") != link: + updates["link"] = link + if updates: + for k, v in updates.items(): + db.update_channel(ch_id, k, v) + logger.info(f"🔄 تم تحديث معلومات القناة {ch_id}: {updates}") + except Exception as e: + logger.warning(f"⚠️ فشل مزامنة القناة {ch_id}: {e}") + + +async def _auto_detect_bot_changes(b, old_ver, new_ver, ch_id, ch_name): + """كشف التغييرات في حالة البوت وإبلاغ المشرفين.""" + if not old_ver or not new_ver: + return + old_ok = old_ver.get("verified", False) and old_ver.get("can_post", False) + new_ok = new_ver.get("verified", False) and new_ver.get("can_post", False) + if old_ok and not new_ok: + msg = (f"⚠️ **تغيير في صلاحية البوت**\n\n" + f"🤖 {b.get('name', '')}\n" + f"📢 {ch_name}\n" + f"الحالة السابقة: ✅ موثوق\n" + f"الحالة الجديدة: ❌ غير موثوق\n" + f"السبب: {new_ver.get('status', 'غير معروف')}") + await notify_admins(msg) + elif not old_ok and new_ok: + msg = (f"✅ **تمت استعادة صلاحية البوت**\n\n" + f"🤖 {b.get('name', '')}\n" + f"📢 {ch_name}\n" + f"أصبح البوت قادراً على النشر مرة أخرى.") + await notify_admins(msg) + + +async def bot_channel_verify_loop(): + """حلقة دورية: التحقق من البوتات في القنوات + المزامنة التلقائية مع Telegram.""" + await asyncio.sleep(120) # انتظار دقيقتين بعد بدء البوت + while True: + try: + bots = db.get_all_publishing_bots() + for b in bots: + bid = b.get("id", "") + token = db.bot_manager.get_token(bid) if hasattr(db, "bot_manager") else b.get("token", "") + bname = b.get("name", bid) + if not token: + continue + # التحقق من صحة التوكن نفسه (هل البوت ما زال فعالاً) + try: + token_ver = await verifier.validate_token(token) + if not token_ver.get("valid"): + msg = f"⚠️ **بوت غير صالح**\n\n🤖 {bname}\nالتوكن لم يعد صالحاً: {token_ver.get('error', 'غير معروف')}" + await notify_admins(msg) + continue + except Exception: + pass + # استخدام BotChannelMapper للحصول على القنوات + if hasattr(db, "mapper"): + channel_ids = db.mapper.get_channels_for_bot(bid) + else: + deps = db.get_dependencies_for("publishing_bot", bid) + channel_ids = [d.get("id", "") for d in deps] + for ch_id in channel_ids: + if not ch_id: + continue + try: + # مزامنة معلومات القناة أولاً + ch = db.get_channel(ch_id) + await _auto_sync_channel_info(ch_id, entity_name(ch) if ch else ch_id) + # التحقق من وجود البوت في القناة + old_ver = db.get_bot_channel_verification(bid, ch_id) if hasattr(db, "get_bot_channel_verification") else {} + ver = await verifier.check_bot_in_channel(bid, ch_id, force=True) + # كشف التغييرات + if old_ver: + await _auto_detect_bot_changes(b, old_ver, ver, ch_id, entity_name(ch) if ch else ch_id) + except Exception: + pass + await asyncio.sleep(2) # تجنب ضغط API + except Exception as e: + logger.warning(f"خطأ في حلقة فحص البوتات: {e}") + await asyncio.sleep(BOT_VERIFY_INTERVAL) + + +# ============================================================ +# UI: تعيين الموارد للقناة (بوتات، جلسات، AI، مواقع) +# ============================================================ + +_RESOURCE_MAP = { + "bots": {"label": "🤖 بوتات النشر", "getter": "get_all_publishing_bots", "cfg_key": "assigned_bots"}, + "sessions": {"label": "📱 الجلسات", "getter": "get_all_sessions", "cfg_key": "assigned_sessions"}, + "ai": {"label": "🧠 مفاتيح AI", "getter": "get_all_ai_keys", "cfg_key": "assigned_ai"}, + "websites": {"label": "🌐 مواقع الويب", "getter": "get_all_websites", "cfg_key": "websites"}, +} + + +def _get_resource_items(rtype): + getter_name = _RESOURCE_MAP.get(rtype, {}).get("getter") + if not getter_name: + return [] + getter = getattr(db, getter_name, None) + if not getter: + return [] + try: + return getter() + except Exception: + return [] + + +async def assign_resource_menu(client, callback): + """قائمة تعيين مورد معين لقناة.""" + parts = callback.data.split("_", 2) + rtype = parts[1] + ch_id = parts[2] + info = _RESOURCE_MAP.get(rtype) + if not info: + await callback.answer("غير معروف.") + return + if rtype == "bots" and hasattr(db, "mapper"): + assigned = set(db.mapper.get_bots_for_channel(ch_id)) + else: + cfg = db.get_channel_config(ch_id) + assigned = set(str(x) for x in cfg.get(info["cfg_key"], [])) + items = _get_resource_items(rtype) + ch_name = entity_name(db.get_channel(ch_id)) + + if rtype == "bots": + # عرض خاص للبوتات: اسم + يوزر + إحصائيات + تشغيل/إيقاف + lines = [f"🤖 **بوتات النشر** — {ch_name}\n", "✅ معيّن / 🔲 غير معيّن: اضغط البوت لتعيينه لهذه القناة أو إلغاء تعيينه. 🟢/🔴 يوضح حالة البوت.\n"] + if not items: + lines.append("لا توجد بوتات متاحة.") + btns = [] + for item in items: + item_id = str(item.get("id", "")) + name = item.get("name", item_id) + username = item.get("username", "?") + enabled = item.get("enabled", True) + stats = item.get("stats", {}) or {} + pub = int(item.get("publish_count", 0)) + assigned_mark = "✅" if item_id in assigned else "🔲" + enabled_mark = "🟢" if enabled else "🔴" + lines.append( + f"{assigned_mark} {enabled_mark} {name} (@{username})\n" + f" 📊 {pub} منشور | نصوص:{stats.get('text',0)} صور:{stats.get('photo',0)} فيديو:{stats.get('video',0)} البوم:{stats.get('album',0)}" + ) + btns.append(InlineKeyboardButton(f"{'✅' if item_id in assigned else '🔲'} {name} {'🟢' if enabled else '🔴'}", callback_data=f"toggle_assign_{rtype}_{ch_id}_{item_id}")) + rows = grid_buttons(btns, 2) if btns else [] + rows.append(nav_row(f"genset_{ch_id}")) + await safe_edit(callback, "\n".join(lines), InlineKeyboardMarkup(rows)) + return + + lines = [f"{info['label']} — {ch_name}\n", "✅ معيّن / 🔲 غير معيّن: اضغط المورد لتعيينه لهذه القناة أو إلغاء تعيينه.\n"] + if not items: + lines.append("لا توجد عناصر متاحة.") + btns = [] + for item in items: + item_id = str(item.get("id", "")) + name = item.get("name", item_id) + on = "✅" if item_id in assigned else "🔲" + lines.append(f"{on} {name}") + btns.append(InlineKeyboardButton(f"{on} {name}", callback_data=f"toggle_assign_{rtype}_{ch_id}_{item_id}")) + rows = grid_buttons(btns, 2) if btns else [] + rows.append(nav_row(f"genset_{ch_id}")) + await safe_edit(callback, "\n".join(lines), InlineKeyboardMarkup(rows)) + + +async def toggle_assign_resource(client, callback): + """تبديل تعيين مورد لقناة.""" + # callback.data = "toggle_assign_bots_ch_id_bot_id" + parts = callback.data.split("_", 4) + # ['toggle', 'assign', 'bots', 'ch_id', 'bot_id'] + if len(parts) < 5: + await callback.answer("خطأ في البيانات.") + return + rtype = parts[2] + ch_id = parts[3] + item_id = parts[4] + info = _RESOURCE_MAP.get(rtype) + if not info: + await callback.answer("غير معروف.") + return + if rtype == "bots" and hasattr(db, "mapper"): + # استخدام BotChannelMapper للربط + was_assigned = db.mapper.is_assigned(item_id, ch_id) + if was_assigned: + db.mapper.unassign(item_id, ch_id) + else: + db.mapper.assign(item_id, ch_id) + # التحقق الفوري عند التعيين + token = db.bot_manager.get_token(item_id) if hasattr(db, "bot_manager") else "" + if token: + try: + ver = await verifier.check_bot_in_channel(item_id, ch_id, force=True) + except Exception: + pass + else: + # للأنواع الأخرى (sessions, ai, websites) - الطريقة القديمة + cfg = db.get_channel_config(ch_id) + key = info["cfg_key"] + current = list(cfg.get(key, [])) + str_current = [str(x) for x in current] + if str(item_id) in str_current: + current = [x for x in current if str(x) != str(item_id)] + else: + current.append(item_id) + db.update_channel_config(ch_id, **{key: current}) + await callback.answer("تم التحديث.") + callback.data = f"assign_{rtype}_{ch_id}" + await assign_resource_menu(client, callback) + + +# ============================================================ +# UI: قائمة التنبيهات +# ============================================================ + +async def notifications_menu(client, callback): + """عرض قائمة التنبيهات مع إمكانية تشغيل/إيقاف كل فحص.""" + ch_id = None + if "|" in callback.data: + ch_id = callback.data.split("|", 1)[1] + settings = db.get_notification_settings() + lines = ["🔔 **إعدادات التنبيهات**\n", "اضغط نوع التنبيه لتشغيله أو إيقافه. التنبيهات تصل للمشرفين عند حدوث أحداث:\n"] + buttons = [] + for key, label in db.NOTIFICATION_TYPES.items(): + on = settings.get(key, True) + lines.append(f"{'✅' if on else '❌'} {label}") + buttons.append([InlineKeyboardButton( + f"{'✅' if on else '❌'} {label}", + callback_data=f"toggle_notif_{key}|{ch_id}" if ch_id else f"toggle_notif_{key}" + )]) + buttons.append(nav_row(f"sysset_{ch_id}" if ch_id else "system_menu")) + await safe_edit(callback, "\n".join(lines), InlineKeyboardMarkup(buttons)) + + +async def _cache_cleanup_loop(): + """تنظيف دوري للكاش منتهي الصلاحية.""" + while True: + await asyncio.sleep(600) # كل 10 دقائق + try: + if hasattr(db, "cache_clear_expired"): + db.cache_clear_expired() + except Exception: + pass + + +async def run_clients(): + global bot_client, user_client + + os.makedirs("/data/sessions", exist_ok=True) + + bot_client = Client( + "/data/sessions/bot_session", + api_id=config.API_ID, + api_hash=config.API_HASH, + bot_token=config.BOT_TOKEN + ) + + user_client = Client( + "/data/sessions/user_session", + api_id=config.API_ID, + api_hash=config.API_HASH, + session_string=config.SESSION_STRING + ) + + register_bot_handlers(bot_client) + register_user_handlers(user_client) + register_middle_handlers(bot_client) + + await bot_client.start() + await user_client.start() + + try: + if hasattr(db, "cleanup_old_runtime_data"): + db.cleanup_old_runtime_data(days=3) + except Exception as e: + logger.warning(f"تعذر تنظيف بيانات التشغيل القديمة: {e}") + + await warm_middle_peer() + try: + await warm_all_peers_after_import() + except Exception as e: + logger.warning(f"فشل تهيئة القنوات/المصادر عند التشغيل: {e}") + + logger.info("✅ البوتان شغّالان") + asyncio.create_task(poll_public_sources_loop()) + asyncio.create_task(heartbeat_watchdog_loop()) + asyncio.create_task(notification_checks_loop()) + asyncio.create_task(bot_channel_verify_loop()) + asyncio.create_task(_cache_cleanup_loop()) + try: + blogger_pub = BloggerPublisher() + asyncio.create_task(blogger_pub.start()) + logger.info("✅ تم تشغيل Blogger Publisher") + except Exception as e: + logger.warning(f"⚠️ فشل تشغيل Blogger Publisher: {e}") + logger.info("✅ تم تشغيل نظام Polling للمصادر العامة") + logger.info("✅ تم تشغيل Heartbeat/Watchdog") + logger.info("✅ تم تشغيل نظام التنبيهات") + logger.info("✅ تم تشغيل فحص البوتات الدوري") + logger.info("✅ تم تشغيل تنظيف الكاش الدوري") + await asyncio.Event().wait() + +def run_bot(): + lock_file = "/tmp/telegram_bot_core_running.lock" + + if os.path.exists(lock_file): + # نتحقق إن البوت القديم فعلاً شغّال وليس ملف قفل متروك من crash سابق + stale = True + try: + with open(lock_file, "r") as f: + old_pid = int(f.read().strip()) + os.kill(old_pid, 0) # لا يرسل إشارة، فقط يتحقق من وجود العملية + stale = False + except (ValueError, FileNotFoundError): + stale = True + except ProcessLookupError: + stale = True + except PermissionError: + stale = False # العملية موجودة لكن لا صلاحية للفحص + + if not stale: + logger.warning("⚠️ البوت يعمل مسبقاً، تم منع تشغيل نسخة ثانية.") + return + + # ملف قفل متروك — نمسحه ونكمل + try: + os.remove(lock_file) + logger.info("🧹 تم مسح ملف قفل متروك من تشغيل سابق.") + except Exception: + pass + + with open(lock_file, "w") as f: + f.write(str(os.getpid())) + + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + try: + loop.run_until_complete(run_clients()) + except KeyboardInterrupt: + pass + except Exception as e: + logger.exception(f"توقف البوت بسبب خطأ: {e}") + finally: + try: + if bot_client: + loop.run_until_complete(bot_client.stop()) + except Exception: + pass + + try: + if user_client: + loop.run_until_complete(user_client.stop()) + except Exception: + pass + + try: + if os.path.exists(lock_file): + os.remove(lock_file) + except Exception: + pass + + loop.close() \ No newline at end of file diff --git a/config.py b/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9effcf8a9679d9af9b717f785f6e0d63b6292546 --- /dev/null +++ b/config.py @@ -0,0 +1,24 @@ +import os +from core.secrets.compat import env_or_secret + +API_ID = int(env_or_secret("API_ID", default="0") or "0") +API_HASH = env_or_secret("API_HASH", default="") or "" +BOT_TOKEN = env_or_secret("BOT_TOKEN", default="") or "" +SESSION_STRING = env_or_secret("SESSION_STRING", default="") or "" + +# قراءة قائمة الأدمن من متغير ADMINS (أرقام مفصولة بفواصل) +admins_str = env_or_secret("ADMINS", default="") or "" +ADMINS = [int(x.strip()) for x in admins_str.split(",") if x.strip()] + +# إذا لم يُضبط ADMINS نحاول استخدام ADMIN_ID القديم (للتوافق) +if not ADMINS: + old_admin = env_or_secret("ADMIN_ID", default="") or "" + if old_admin: + ADMINS = [int(old_admin)] + +MIDDLE_CHANNEL = int(env_or_secret("MIDDLE_CHANNEL", default="0") or "0") + +if not all([API_ID, API_HASH, BOT_TOKEN, SESSION_STRING, MIDDLE_CHANNEL]): + raise ValueError("جميع المتغيرات الأساسية مطلوبة") +if not ADMINS: + raise ValueError("يجب تعيين ADMINS على الأقل معرف أدمن واحد") \ No newline at end of file diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/core/ai/__init__.py b/core/ai/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..937dfe07a2ac0c0b020599c3f8f46001ab8220af --- /dev/null +++ b/core/ai/__init__.py @@ -0,0 +1,3 @@ +from .gateway import AIGateway, AIResponse + +__all__ = ['AIGateway', 'AIResponse'] diff --git a/core/ai/gateway.py b/core/ai/gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..ac8e0cb286eb9b37cfcf7904cd6f9fb350d8e8cd --- /dev/null +++ b/core/ai/gateway.py @@ -0,0 +1,110 @@ +""" +P29 AI Gateway — one entry point for all AI calls. + +Goals: +- Route every request through AIProviderPool. +- Keep legacy secret names unchanged. +- Fail over across keys/providers on rate limits/transient errors. +- Support one structured "article package" request instead of many calls. +- Track approximate usage when providers return token metadata. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Callable, Dict, Iterable, Optional +import json +import time + +from core.providers.pool import AIProviderPool, KeyState + + +@dataclass +class AIResponse: + data: Any + provider: str + key_name: str + attempts: int + input_tokens: int = 0 + output_tokens: int = 0 + + +class AIGateway: + def __init__(self, pool: AIProviderPool, adapters: Optional[Dict[str, Callable]] = None): + self.pool = pool + self.adapters = adapters or {} + + def register(self, provider: str, adapter: Callable) -> None: + self.adapters[provider.lower()] = adapter + + def _invoke(self, key: KeyState, payload: Any) -> Any: + adapter = self.adapters.get(key.provider) + if adapter is None: + raise RuntimeError(f"No adapter registered for provider: {key.provider}") + return adapter(key.value, payload) + + @staticmethod + def _usage(result: Any) -> tuple[int, int]: + if isinstance(result, dict): + usage = result.get("usage") or result.get("token_usage") or {} + return int(usage.get("prompt_tokens", usage.get("input_tokens", 0)) or 0), int( + usage.get("completion_tokens", usage.get("output_tokens", 0)) or 0 + ) + return 0, 0 + + def request( + self, + payload: Any, + providers: Optional[Iterable[str]] = None, + max_attempts: int = 6, + ) -> AIResponse: + attempts = 0 + last_error = None + for _ in range(max(1, max_attempts)): + key = self.pool.choose(providers) + if key is None: + break + attempts += 1 + try: + result = self._invoke(key, payload) + inp, out = self._usage(result) + self.pool.report_success(key, inp + out) + return AIResponse(result, key.provider, key.name, attempts, inp, out) + except Exception as exc: + last_error = exc + # Provider adapters may classify 429/5xx/timeout failures. + rate_limited = bool(getattr(exc, "rate_limited", False)) + transient = bool(getattr(exc, "transient", False)) + cooldown = int(getattr(exc, "cooldown_seconds", 30)) + self.pool.report_failure(key, cooldown_seconds=cooldown, rate_limited=rate_limited) + # Backoff is bounded so one broken key cannot stall the whole worker. + retry_after = float(getattr(exc, "retry_after_seconds", 0) or 0) + if retry_after <= 0: + retry_after = min(5.0, 0.25 * (2 ** max(0, attempts - 1))) + if transient or rate_limited: + time.sleep(max(0.0, min(retry_after, 5.0))) + if last_error: + raise RuntimeError(f"All AI attempts failed: {last_error}") from last_error + raise RuntimeError("No available AI provider keys") + + def article_package( + self, + article: str, + *, + task: str = "process_article", + fields: Optional[list[str]] = None, + providers: Optional[Iterable[str]] = None, + max_attempts: int = 6, + ) -> AIResponse: + """Build one compact structured request for all article outputs.""" + fields = fields or [ + "title", "article", "summary", "keywords", + "hashtags", "seo_title", "seo_description", "category", "slug" + ] + payload = { + "task": task, + "output_format": "json", + "fields": fields, + "article": article, + "instruction": "Return only the requested JSON object. Do not repeat the input outside the required fields.", + } + return self.request(payload, providers=providers, max_attempts=max_attempts) diff --git a/core/ai/http_adapters.py b/core/ai/http_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..7b480c92bef051b8efcc4896bfc986edc170eaf7 --- /dev/null +++ b/core/ai/http_adapters.py @@ -0,0 +1,137 @@ +"""HTTP adapters for the supported P29 providers. + +Adapters intentionally receive the selected secret as an argument from AIGateway; +they never read or log environment secrets themselves. +""" +from __future__ import annotations + +import json +import re +from typing import Any + + +class ProviderHTTPError(RuntimeError): + def __init__(self, message, *, status_code=0, rate_limited=False, transient=False, retry_after_seconds=0): + super().__init__(message) + self.status_code = status_code + self.rate_limited = rate_limited + self.transient = transient + self.retry_after_seconds = retry_after_seconds + self.cooldown_seconds = max(1, int(retry_after_seconds or (60 if rate_limited else 15))) + + +def _json_from_text(text: str) -> Any: + text = (text or "").strip() + # Models sometimes wrap JSON in markdown fences. + text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I) + text = re.sub(r"\s*```$", "", text) + try: + return json.loads(text) + except Exception: + m = re.search(r"\{.*\}", text, flags=re.S) + if m: + return json.loads(m.group(0)) + return {"text": text} + + +def _raise_response(response) -> None: + if response.is_success: + return + status = int(response.status_code) + retry_after = response.headers.get("retry-after", "0") + try: + retry = float(retry_after) + except Exception: + retry = 0 + raise ProviderHTTPError( + f"provider HTTP {status}", + status_code=status, + rate_limited=status == 429, + transient=status == 429 or status >= 500, + retry_after_seconds=retry, + ) + + +def gemini_adapter(api_key: str, payload: dict) -> dict: + import httpx + model = payload.get("model", "gemini-2.0-flash") + prompt = json.dumps(payload, ensure_ascii=False) + body = { + "contents": [{"parts": [{"text": prompt}]}], + "generationConfig": {"responseMimeType": "application/json"}, + } + with httpx.Client(timeout=45) as client: + response = client.post( + f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent", + params={"key": api_key}, + json=body, + ) + _raise_response(response) + data = response.json() + parts = data.get("candidates", [{}])[0].get("content", {}).get("parts", []) + text = "".join(str(p.get("text", "")) for p in parts if isinstance(p, dict)) + result = _json_from_text(text) + usage = data.get("usageMetadata") or {} + if isinstance(result, dict): + result.setdefault("usage", { + "prompt_tokens": usage.get("promptTokenCount", 0), + "completion_tokens": usage.get("candidatesTokenCount", 0), + }) + return result + + +def _openai_compatible(api_key: str, payload: dict, base_url: str, model: str) -> dict: + import httpx + system = payload.get("system") or ( + "Return only a JSON object matching the requested fields. " + "Do not include markdown fences." + ) + user = json.dumps(payload, ensure_ascii=False) + body = { + "model": model, + "messages": [ + {"role": "system", "content": system}, + {"role": "user", "content": user}, + ], + "response_format": {"type": "json_object"}, + } + with httpx.Client(timeout=45) as client: + response = client.post( + base_url, + headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, + json=body, + ) + _raise_response(response) + data = response.json() + content = ( + data.get("choices", [{}])[0] + .get("message", {}) + .get("content", "") + ) + result = _json_from_text(content) + usage = data.get("usage") or {} + if isinstance(result, dict): + result.setdefault("usage", usage) + return result + + +def groq_adapter(api_key: str, payload: dict) -> dict: + return _openai_compatible( + api_key, payload, + "https://api.groq.com/openai/v1/chat/completions", + payload.get("model", "llama-3.3-70b-versatile"), + ) + + +def openrouter_adapter(api_key: str, payload: dict) -> dict: + return _openai_compatible( + api_key, payload, + "https://openrouter.ai/api/v1/chat/completions", + payload.get("model", "openai/gpt-4o-mini"), + ) + + +def register_default_http_adapters(gateway) -> None: + gateway.register("gemini", gemini_adapter) + gateway.register("groq", groq_adapter) + gateway.register("openrouter", openrouter_adapter) diff --git a/core/app.py b/core/app.py new file mode 100644 index 0000000000000000000000000000000000000000..66c61a5f14075060c43c9942d7bf524a7499fbf4 --- /dev/null +++ b/core/app.py @@ -0,0 +1,68 @@ +"""P29 phase-15 composition root. + +The legacy runtime remains available, but all new section traffic can now use one +shared RuntimeIntegration instance. External adapters are registered by the host. +""" +from __future__ import annotations + +from .config.settings import settings +from .plugins.registry import PluginRegistry +from .plugins.builtin import register_builtins +from .plugins.manager import SectionManager +from .events.bus import EventBus +from .runtime.integration import RuntimeIntegration +from .ai.http_adapters import register_default_http_adapters +from .release.readiness import ProductionReadiness +from .release.backup import BackupManager +from .release.release import ReleaseManifest +from .release.go_live import GoLiveGate + + +class App: + def __init__(self, legacy_db=None, project_root="."): + self.settings = settings + self.plugins = PluginRegistry() + register_builtins(self.plugins) + self.events = EventBus() + self.runtime = RuntimeIntegration( + db=legacy_db, + db_path=settings.db_path, + project_root=project_root, + ) + register_default_http_adapters(self.runtime.ai) + self.sections = SectionManager(self.plugins) + self.readiness = ProductionReadiness(self.runtime, project_root) + self.backups = BackupManager(settings.data_dir, "backups") + self.release_manifest_builder = ReleaseManifest(project_root) + self.go_live = GoLiveGate(self) + + def discover_plugins(self): + return self.plugins.discover() + + def register_ai_provider(self, provider, adapter): + self.runtime.register_ai_provider(provider, adapter) + + def register_publisher(self, target, adapter): + self.runtime.register_publisher(target, adapter) + + def health(self): + return self.runtime.health_snapshot() + + def metrics(self): + return self.runtime.metrics_snapshot() + + def controls(self): + return self.runtime.control_snapshot() + + def production_readiness(self, require_secrets=()): + return self.readiness.evaluate(tuple(require_secrets)) + + def create_backup(self, databases=None, label="release"): + dbs = databases or [self.settings.db_path] + return self.backups.create(dbs, label=label) + + def release_manifest(self, version="29.0", phase="24", output=None): + return self.release_manifest_builder.build(version=version, phase=phase, output=output) + + def go_live_report(self, require_telegram=False): + return self.go_live.evaluate(require_telegram=require_telegram) diff --git a/core/config/__init__.py b/core/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/core/config/settings.py b/core/config/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc49bf16cfcd97877234708bc2e235e075d28fb --- /dev/null +++ b/core/config/settings.py @@ -0,0 +1,16 @@ +"""Central, extensible settings loaded from environment without hard-coding secrets.""" +from dataclasses import dataclass +import os + +@dataclass(frozen=True) +class Settings: + data_dir: str = os.getenv("APP_DATA_DIR", "data") + runtime_dir: str = os.getenv("APP_RUNTIME_DIR", "runtime") + db_path: str = os.getenv("APP_DB_PATH", "data/app.sqlite3") + log_level: str = os.getenv("APP_LOG_LEVEL", "INFO") + timezone: str = os.getenv("APP_TIMEZONE", "UTC") + auto_repair_enabled: bool = os.getenv("AUTO_REPAIR_ENABLED", "false").lower() in {"1","true","yes","on"} + auto_repair_apply: bool = os.getenv("AUTO_REPAIR_APPLY", "false").lower() in {"1","true","yes","on"} + max_repair_attempts: int = int(os.getenv("AUTO_REPAIR_MAX_ATTEMPTS", "2")) + +settings = Settings() diff --git a/core/content/__init__.py b/core/content/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b34ee07dad9001300f6632dc1cea5031d9dbdea1 --- /dev/null +++ b/core/content/__init__.py @@ -0,0 +1,3 @@ +from .preflight import ContentPreflight, PreflightResult +from .dedup import DedupStore +from .orchestrator import ContentGate, GateDecision diff --git a/core/content/dedup.py b/core/content/dedup.py new file mode 100644 index 0000000000000000000000000000000000000000..e863e68e2aae85187cfddcb20e8890628034e165 --- /dev/null +++ b/core/content/dedup.py @@ -0,0 +1,26 @@ +from __future__ import annotations +import sqlite3, time +from pathlib import Path + +class DedupStore: + def __init__(self,path="data/jobs.sqlite3"): + self.path=Path(path); self.path.parent.mkdir(parents=True,exist_ok=True) + self._init() + def _conn(self): + c=sqlite3.connect(self.path,timeout=30,isolation_level=None) + c.execute("PRAGMA journal_mode=WAL"); c.execute("PRAGMA synchronous=FULL") + return c + def _init(self): + with self._conn() as c: + c.execute("""CREATE TABLE IF NOT EXISTS content_dedup( + fingerprint TEXT PRIMARY KEY, source TEXT NOT NULL, article_id TEXT, + created_at REAL NOT NULL)""") + def seen(self,fp): + with self._conn() as c: return c.execute("SELECT 1 FROM content_dedup WHERE fingerprint=?",(fp,)).fetchone() is not None + def remember(self,fp,source,article_id=None): + with self._conn() as c: + c.execute("INSERT OR IGNORE INTO content_dedup VALUES(?,?,?,?)",(fp,source,article_id,time.time())) + + def forget(self, fp): + with self._conn() as c: + c.execute("DELETE FROM content_dedup WHERE fingerprint=?", (fp,)) diff --git a/core/content/orchestrator.py b/core/content/orchestrator.py new file mode 100644 index 0000000000000000000000000000000000000000..882faa80030e504a313f0e6349d2667e617ceca7 --- /dev/null +++ b/core/content/orchestrator.py @@ -0,0 +1,22 @@ +from __future__ import annotations +from dataclasses import dataclass +from .preflight import ContentPreflight +from .dedup import DedupStore + +@dataclass +class GateDecision: + accepted: bool + reason: str + fingerprint: str + +class ContentGate: + def __init__(self,blocked_words=(),dedup=None): + self.preflight=ContentPreflight(blocked_words) + self.dedup=dedup or DedupStore() + def check(self,text,source="unknown",article_id=None): + r=self.preflight.run(text) + if not r.accepted: return GateDecision(False,r.reason,r.fingerprint) + if self.dedup.seen(r.fingerprint): + return GateDecision(False,"duplicate",r.fingerprint) + self.dedup.remember(r.fingerprint,source,article_id) + return GateDecision(True,"accepted",r.fingerprint) diff --git a/core/content/preflight.py b/core/content/preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..ec5d546fe264f36f50d91b64106e15b3a3caefbd --- /dev/null +++ b/core/content/preflight.py @@ -0,0 +1,34 @@ +from __future__ import annotations +import hashlib, re +from dataclasses import dataclass + +@dataclass(frozen=True) +class PreflightResult: + accepted: bool + reason: str + cleaned: str + fingerprint: str + +class ContentPreflight: + """Zero-AI-cost gate: blocked words and exact/normalized duplicates run first.""" + def __init__(self, blocked_words=()): + self.blocked={str(x).strip().casefold() for x in blocked_words if str(x).strip()} + + @staticmethod + def normalize(text): + return re.sub(r'\s+',' ',re.sub(r'[^\w\s]',' ',str(text),flags=re.UNICODE)).strip().casefold() + + def fingerprint(self,text): + return hashlib.sha256(self.normalize(text).encode("utf-8")).hexdigest() + + def run(self,text,seen_fingerprints=None): + raw=str(text) + norm=self.normalize(raw) + hits=[w for w in self.blocked if w in norm] + if hits: + return PreflightResult(False,"blocked_word:"+hits[0],raw,self.fingerprint(raw)) + fp=self.fingerprint(raw) + if seen_fingerprints is not None and fp in seen_fingerprints: + return PreflightResult(False,"duplicate",raw,fp) + cleaned=raw + return PreflightResult(True,"accepted",cleaned,fp) diff --git a/core/content_pipeline.py b/core/content_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..51ce01ee07f84d058f4ae5fec457b765ed3559be --- /dev/null +++ b/core/content_pipeline.py @@ -0,0 +1,138 @@ +"""Global content gate used by every content section before AI or external APIs. + +Order is intentionally strict: blocked-word gate -> duplicate gate -> normalize/fingerprint. +This module is section-agnostic so Blogger, News, Sports and future plugins can reuse it. +""" +from __future__ import annotations + +import hashlib +import re +import unicodedata +from dataclasses import dataclass +from typing import Any, Iterable, Optional +from core.content.dedup import DedupStore + + +@dataclass(frozen=True) +class GateResult: + allowed: bool + reason: str = "" + matched: tuple[str, ...] = () + fingerprint: str = "" + + +class ContentGate: + def __init__(self, db: Any, dedup: Optional[DedupStore] = None): + self.db = db + self.dedup = dedup + + @staticmethod + def normalize(text: str) -> str: + text = text or "" + text = unicodedata.normalize("NFKC", text) + text = text.replace("ـ", "") + # Arabic diacritics / tatweel noise. + text = re.sub(r"[\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06ED]", "", text) + text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا") + text = text.replace("ى", "ي").replace("ؤ", "و").replace("ئ", "ي") + text = re.sub(r"https?://\S+", " URL ", text, flags=re.I) + text = re.sub(r"@\w+", " USER ", text) + text = re.sub(r"\s+", " ", text).strip().casefold() + return text + + @classmethod + def fingerprint(cls, text: str, source_url: str = "") -> str: + normalized = cls.normalize(text) + url = cls.normalize(source_url) + payload = f"{url}|{normalized}" + return hashlib.sha256(payload.encode("utf-8", errors="replace")).hexdigest() + + @classmethod + def title_fingerprint(cls, title: str) -> str: + return hashlib.sha256(cls.normalize(title).encode("utf-8")).hexdigest() + + @classmethod + def _contains(cls, text: str, words: Iterable[str]) -> tuple[str, ...]: + normalized = cls.normalize(text) + matches = [] + for raw in words or []: + word = str(raw or "").strip() + if not word: + continue + nw = cls.normalize(word) + if nw and nw in normalized: + matches.append(word) + return tuple(dict.fromkeys(matches)) + + def blocked_words(self, channel_id: str = "") -> list[str]: + words = [] + try: + words.extend(self.db.get_blocked_words() or []) + except Exception: + pass + if channel_id: + try: + words.extend(self.db.get_channel_blocked_words(channel_id) or []) + except Exception: + pass + return list(dict.fromkeys(str(w) for w in words if str(w).strip())) + + def check_blocked(self, text: str, channel_id: str = "") -> GateResult: + matched = self._contains(text, self.blocked_words(channel_id)) + if matched: + return GateResult(False, "blocked_word", matched=matched) + return GateResult(True) + + def check_duplicate(self, text: str, source_url: str = "", fingerprint: Optional[str] = None, + source: str = "", article_id: str = "") -> GateResult: + fp = fingerprint or self.fingerprint(text, source_url) + if self.dedup is not None: + try: + if self.dedup.seen(fp): + return GateResult(False, "duplicate", fingerprint=fp) + self.dedup.remember(fp, source or "unknown", article_id or None) + except Exception: + # Persistent dedup failure is fail-open only for compatibility with + # the legacy JSON store; the runtime health monitor records the fault. + pass + try: + if self.db.is_published(fp): + return GateResult(False, "duplicate", fingerprint=fp) + existing = self.db.get_article(fp) + if existing and existing.get("status") not in ("failed_permanent", "discarded"): + return GateResult(False, "duplicate", fingerprint=fp) + # Conservative normalized title/content comparison for older records. + norm = self.normalize(text) + if norm: + for article in self.db.get_all_articles() or []: + if article.get("fingerprint") == fp: + return GateResult(False, "duplicate", fingerprint=fp) + except Exception: + pass + return GateResult(True, fingerprint=fp) + + def preflight(self, text: str, source_url: str = "", channel_id: str = "", source: str = "", article_id: str = "") -> GateResult: + if not (text or "").strip(): + return GateResult(False, "empty") + # Deliberately before fingerprint/AI work: blocked content costs zero AI requests. + blocked = self.check_blocked(text, channel_id) + if not blocked.allowed: + return blocked + return self.check_duplicate(text, source_url, source=source, article_id=article_id) + + def postflight(self, article: dict, channel_id: str = "") -> GateResult: + text = "\n".join( + str(article.get(k, "") or "") + for k in ("title", "introduction", "body", "conclusion", "summary", "keywords") + ) + blocked = self.check_blocked(text, channel_id) + if not blocked.allowed: + return blocked + source_url = article.get("source_url", "") + original_fp = article.get("fingerprint", "") + candidate_fp = self.fingerprint(text, source_url) + # The input fingerprint is already reserved at ingest. It is expected to + # exist in the dedup store, so do not misclassify the same job as a duplicate. + if original_fp and candidate_fp == original_fp: + return GateResult(True, fingerprint=original_fp) + return self.check_duplicate(text, source_url, fingerprint=candidate_fp) diff --git a/core/control/__init__.py b/core/control/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7bba9455dfe04763da0eb9ed9f34417712e5ad6b --- /dev/null +++ b/core/control/__init__.py @@ -0,0 +1 @@ +from .repair_buttons import ControlButton, REPAIR_BUTTONS diff --git a/core/control/plane.py b/core/control/plane.py new file mode 100644 index 0000000000000000000000000000000000000000..b1a1c8067a7de6352e82e48feb2a561902d0f1ba --- /dev/null +++ b/core/control/plane.py @@ -0,0 +1,56 @@ +from __future__ import annotations +import time +from dataclasses import dataclass, asdict + +@dataclass +class Alert: + key: str + severity: str + message: str + first_seen: float + last_seen: float + count: int = 1 + active: bool = True + +class ControlPlane: + """Read-only operational control surface with safe, actionable alerts.""" + def __init__(self, runtime, dead_threshold=1, queue_threshold=50): + self.runtime = runtime + self.dead_threshold = int(dead_threshold) + self.queue_threshold = int(queue_threshold) + self._alerts: dict[str, Alert] = {} + + def _upsert(self, key, severity, message): + now=time.time(); old=self._alerts.get(key) + if old: + old.last_seen=now; old.count+=1; old.active=True; old.message=message + else: + self._alerts[key]=Alert(key,severity,message,now,now) + + def evaluate(self): + stats=self.runtime.queue.store.get_stats() + if stats.get("dead",0)>=self.dead_threshold: self._upsert("queue.dead","critical",f"Dead-letter jobs: {stats['dead']}") + else: self._resolve("queue.dead") + if stats.get("queued",0)>=self.queue_threshold: self._upsert("queue.backlog","warning",f"Queue backlog: {stats['queued']}") + else: self._resolve("queue.backlog") + for name,item in self.runtime.health_snapshot().items(): + key=f"health:{name}" + if item.get("status")=="unhealthy": self._upsert(key,"critical",f"Unhealthy service: {name}") + else: self._resolve(key) + return self.active_alerts() + + def _resolve(self,key): + if key in self._alerts: self._alerts[key].active=False + def active_alerts(self): return [asdict(a) for a in self._alerts.values() if a.active] + def snapshot(self): + return {"queue":self.runtime.queue.store.get_stats(),"health":self.runtime.health_snapshot(),"metrics":self.runtime.metrics_snapshot(),"providers":self.runtime.pool.snapshot(),"alerts":self.evaluate(),"sections":{s:self.runtime.get_section_state(s) for s in self.runtime._sections},"security":self.security_snapshot()} + def security_snapshot(self): + findings = self.runtime.security.validate_environment() if hasattr(self.runtime, "security") else [] + return {"rotation_epoch": getattr(getattr(self.runtime, "security", None), "rotation_epoch", 0), "findings":[getattr(x, "__dict__", str(x)) for x in findings]} + + def acknowledge(self,key,admin_approved=False): + if not admin_approved:return {"ok":False,"reason":"admin_required"} + alert=self._alerts.get(key) + if not alert:return {"ok":False,"reason":"not_found"} + alert.active=False + return {"ok":True,"key":key} diff --git a/core/control/repair_buttons.py b/core/control/repair_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..b94e9fc7b799536c658aa7d46b50dc7f1db5c395 --- /dev/null +++ b/core/control/repair_buttons.py @@ -0,0 +1,18 @@ +from __future__ import annotations +from dataclasses import dataclass + +@dataclass(frozen=True) +class ControlButton: + key: str + label: str + callback: str + +# Additive only: existing button callbacks are not renamed or removed. +REPAIR_BUTTONS = ( + ControlButton("repair_status", "🛠️ حالة الإصلاح التلقائي", "repair:status"), + ControlButton("repair_pending", "🛡️ الإصلاحات بانتظار الموافقة", "repair:pending"), + ControlButton("repair_approve", "✅ الموافقة على الإصلاح", "repair:approve"), + ControlButton("repair_rollback", "↩️ التراجع عن آخر إصلاح", "repair:rollback"), + ControlButton("repair_disable", "⛔ إيقاف الإصلاح التلقائي", "repair:disable"), + ControlButton("repair_enable", "▶️ تشغيل الإصلاح التلقائي", "repair:enable"), +) diff --git a/core/control/repair_control.py b/core/control/repair_control.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f4f6e5cbbdd2b14310ca0f4e761af8a7580bb1 --- /dev/null +++ b/core/control/repair_control.py @@ -0,0 +1,58 @@ +from __future__ import annotations +from core.control.router import ControlRouter +from core.control.repair_buttons import REPAIR_BUTTONS + +class RepairControl: + """Control-bot integration façade. Host Telegram layer only needs to dispatch callback strings.""" + def __init__(self, repair_engine, guard, state: dict|None=None): + self.engine=repair_engine + self.guard=guard + self.state=state if state is not None else {"enabled": True, "pending": [], "last": None} + self.router=ControlRouter() + self._register() + + def _register(self): + self.router.register("repair:status", lambda: { + "enabled": self.state["enabled"], + "pending": len(self.state["pending"]), + "last": self.state["last"], + }) + self.router.register("repair:pending", lambda: list(self.state["pending"])) + self.router.register("repair:disable", self.disable) + self.router.register("repair:enable", self.enable) + self.router.register("repair:rollback", self.rollback) + + def disable(self): + self.state["enabled"]=False + return {"ok":True,"enabled":False} + + def enable(self): + self.state["enabled"]=True + return {"ok":True,"enabled":True} + + def queue_for_approval(self, record): + self.state["pending"].append(record) + self.state["last"]=record + return record + + def approve(self, repair_record_id: str, apply_fn): + if not self.state["enabled"]: + return {"ok":False,"reason":"auto-repair disabled"} + match=next((x for x in self.state["pending"] if getattr(x,"repair_id",None)==repair_record_id),None) + if not match: + return {"ok":False,"reason":"repair not found"} + result=apply_fn(match) + self.state["pending"]=[x for x in self.state["pending"] if x is not match] + self.state["last"]=result + return {"ok":True,"result":result} + + def rollback(self): + last=self.state.get("last") + if not last: + return {"ok":False,"reason":"no repair recorded"} + try: + self.engine.rollback(last) + self.state["last"]=last + return {"ok":True,"status":"rolled_back"} + except Exception as exc: + return {"ok":False,"reason":str(exc)} diff --git a/core/control/router.py b/core/control/router.py new file mode 100644 index 0000000000000000000000000000000000000000..e051ef40777d8be3aef6150bfdab86cd8768bea6 --- /dev/null +++ b/core/control/router.py @@ -0,0 +1,25 @@ +from __future__ import annotations +from dataclasses import dataclass +from typing import Callable, Optional + +@dataclass +class CallbackAction: + callback: str + handler: Callable + +class ControlRouter: + """Additive callback router; existing bot callbacks remain untouched.""" + def __init__(self): + self._handlers: dict[str, Callable] = {} + + def register(self, callback: str, handler: Callable): + self._handlers[callback]=handler + + def dispatch(self, callback: str, *args, **kwargs): + handler=self._handlers.get(callback) + if handler is None: + raise KeyError(f"Unknown callback: {callback}") + return handler(*args, **kwargs) + + def has(self, callback: str) -> bool: + return callback in self._handlers diff --git a/core/control/section_control.py b/core/control/section_control.py new file mode 100644 index 0000000000000000000000000000000000000000..49b9520099ee7f45b00f3047be042321186310ff --- /dev/null +++ b/core/control/section_control.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from core.sections.controls import build_section_buttons + + +class SectionControl: + """Control-bot façade for all content sections. + + Callback names are additive (`news:*`, `sports:*`, `blogger:*`); legacy + callback strings are not renamed or removed. + """ + + def __init__(self, runtime, admin_check=None): + self.runtime = runtime + self.admin_check = admin_check or (lambda _user_id: True) + + def callbacks(self): + out = {} + for section in ("news", "sports", "blogger"): + for button in build_section_buttons(section): + out[button.callback] = self.handle + return out + + def handle(self, callback: str, user_id=None): + if callback.count(":") != 1: + return {"ok": False, "reason": "invalid_callback"} + section, action = callback.split(":", 1) + if section not in ("news", "sports", "blogger"): + return {"ok": False, "reason": "unknown_section"} + + if action == "settings" or action == "status": + return {"ok": True, "section": section, "state": self.runtime.get_section_state(section)} + if action == "sources": + return {"ok": True, "section": section, "sources": self.runtime.get_section_state(section)["sources"]} + if action == "blocked": + return {"ok": True, "section": section, "blocked_words": self.runtime.get_section_state(section)["blocked_words"]} + if action == "duplicates": + return {"ok": True, "section": section, "enabled": self.runtime.get_section_state(section)["duplicate_protection"]} + if action == "ai": + return {"ok": True, "section": section, "enabled": self.runtime.get_section_state(section)["ai_enabled"]} + if action == "queue": + return {"ok": True, "section": section, "queue": self.runtime.queue.store.get_stats()} + if action == "metrics": + return {"ok": True, "section": section, "metrics": self.runtime.metrics_snapshot(), "detailed": self.runtime.metrics.detailed_snapshot()} + if action == "health": + return {"ok": True, "section": section, "health": self.runtime.health_snapshot()} + if action == "dead": + return {"ok": True, "section": section, "jobs": self.runtime.queue_snapshot(status="dead")} + if action == "enable": + return self.runtime.set_section_state(section, enabled=True).__dict__ + if action == "disable": + return self.runtime.set_section_state(section, enabled=False).__dict__ + if action == "repair": + if not self.admin_check(user_id): + return {"ok": False, "reason": "admin_required"} + return {"ok": True, **self.runtime.set_auto_repair(True)} + return {"ok": False, "reason": "unknown_action"} + + +class ControlPlaneControl: + CALLBACKS=("control:overview","control:alerts","control:providers","control:audit") + def __init__(self,runtime,admin_check=None): self.runtime=runtime; self.admin_check=admin_check or (lambda _uid:True) + def handle(self,callback,user_id=None): + if callback=="control:overview": return {"ok":True,**self.runtime.operational_snapshot()} + if callback=="control:alerts": return {"ok":True,"alerts":self.runtime.control_plane.evaluate()} + if callback=="control:providers": return {"ok":True,"providers":self.runtime.pool.snapshot()} + if callback=="control:audit": + if not self.admin_check(user_id): return {"ok":False,"reason":"admin_required"} + return {"ok":True,"audit":self.runtime.recent_audit(50)} + return {"ok":False,"reason":"unknown_action"} diff --git a/core/events/__init__.py b/core/events/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/core/events/bus.py b/core/events/bus.py new file mode 100644 index 0000000000000000000000000000000000000000..7e784b9a93571e7bea2a83f88f289f4d1228865c --- /dev/null +++ b/core/events/bus.py @@ -0,0 +1,7 @@ +class EventBus: + def __init__(self): self._handlers={} + def on(self,event,handler): self._handlers.setdefault(event,[]).append(handler) + async def emit(self,event,**payload): + for h in list(self._handlers.get(event,[])): + result=h(**payload) + if hasattr(result,'__await__'): await result diff --git a/core/health/__init__.py b/core/health/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cec5532d645402e46a794b1d0e6ad3f1b4609429 --- /dev/null +++ b/core/health/__init__.py @@ -0,0 +1,2 @@ +from .monitor import HealthMonitor, ServiceHealth +__all__=['HealthMonitor','ServiceHealth'] diff --git a/core/health/monitor.py b/core/health/monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..8dd6f03a8745a4854830c6a7e5f3999b32347f60 --- /dev/null +++ b/core/health/monitor.py @@ -0,0 +1,62 @@ +from __future__ import annotations +from dataclasses import dataclass, field +from time import monotonic +from threading import RLock +from typing import Callable, Any + +@dataclass +class ServiceHealth: + name: str + status: str = "unknown" + consecutive_failures: int = 0 + last_error: str = "" + last_ok: float = 0.0 + last_check: float = 0.0 + metadata: dict = field(default_factory=dict) + +class HealthMonitor: + """Lightweight health registry. Checks are injected so providers remain decoupled.""" + def __init__(self, on_unhealthy: Callable[[str, ServiceHealth], Any] | None = None): + self.on_unhealthy = on_unhealthy + self._services: dict[str, ServiceHealth] = {} + self._checks: dict[str, Callable[[], Any]] = {} + self._lock=RLock() + + def register(self, name: str, check: Callable[[], Any]): + with self._lock: + self._services.setdefault(name, ServiceHealth(name)) + self._checks[name]=check + + def check(self, name: str) -> ServiceHealth: + with self._lock: + service=self._services.setdefault(name, ServiceHealth(name)) + check=self._checks[name] + try: + result=check() + with self._lock: + service.status="healthy" + service.consecutive_failures=0 + service.last_error="" + service.last_ok=monotonic() + service.last_check=monotonic() + if isinstance(result,dict): service.metadata=result + return service + except Exception as exc: + with self._lock: + service.status="unhealthy" + service.consecutive_failures += 1 + service.last_error=str(exc)[:2000] + service.last_check=monotonic() + if self.on_unhealthy: + try: + self.on_unhealthy(name, service) + except Exception: + pass + return service + + def check_all(self) -> dict[str, ServiceHealth]: + return {name:self.check(name) for name in list(self._checks)} + + def snapshot(self): + with self._lock: + return {n:s.__dict__.copy() for n,s in self._services.items()} diff --git a/core/health/registry.py b/core/health/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..9a56dc2ddf6c08c7a928c656851a967601f8be95 --- /dev/null +++ b/core/health/registry.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass, field +from datetime import datetime, timezone + +@dataclass +class Health: + name: str; ok: bool; message: str=''; latency_ms: float|None=None; updated_at: str=field(default_factory=lambda: datetime.now(timezone.utc).isoformat()) + +class HealthRegistry: + def __init__(self): self._items={} + def set(self, name, ok, message='', latency_ms=None): self._items[name]=Health(name,ok,message,latency_ms) + def snapshot(self): return {k:v.__dict__.copy() for k,v in self._items.items()} diff --git a/core/infra/audit.py b/core/infra/audit.py new file mode 100644 index 0000000000000000000000000000000000000000..c559928c454dbecf448a32ee4729841ce739dda9 --- /dev/null +++ b/core/infra/audit.py @@ -0,0 +1,16 @@ +from __future__ import annotations +import json,time +from pathlib import Path +from core.security.redaction import redact +class AuditLog: + def __init__(self,path="data/audit.jsonl"):self.path=Path(path);self.path.parent.mkdir(parents=True,exist_ok=True) + def write(self,event,**data): + row={"ts":time.time(),"event":event,**data} + with self.path.open("a",encoding="utf-8") as f:f.write(json.dumps({k:redact(v) if isinstance(v,str) else v for k,v in row.items()},ensure_ascii=False)+"\n") + def recent(self,limit=50): + if not self.path.exists():return [] + out=[] + for line in self.path.read_text(encoding="utf-8",errors="replace").splitlines()[-max(1,min(500,int(limit))):][::-1]: + try:out.append(json.loads(line)) + except Exception:pass + return out diff --git a/core/infra/load.py b/core/infra/load.py new file mode 100644 index 0000000000000000000000000000000000000000..79816bafc1291aa94bb8b0b55be90bb868b0a4dc --- /dev/null +++ b/core/infra/load.py @@ -0,0 +1,40 @@ +from __future__ import annotations +import time +from dataclasses import dataclass, asdict + +@dataclass +class LoadResult: + submitted: int + processed: int + queued: int + done: int + dead: int + elapsed: float + throughput: float + +class LoadHarness: + """Deterministic in-process load/chaos harness; no external services required.""" + def __init__(self, queue, worker_pool_factory): + self.queue = queue + self.worker_pool_factory = worker_pool_factory + + def submit(self, kind, payload_factory, count: int): + for i in range(max(0, int(count))): + self.queue.store.enqueue(kind, payload_factory(i), job_id=f"load:{kind}:{i}") + + def run(self, kind, payload_factory, count: int, workers: int = 4) -> LoadResult: + count = max(0, int(count)); self.submit(kind, payload_factory, count) + start = time.monotonic() + pool = self.worker_pool_factory(workers) + results = pool.run(max_jobs=count, idle_rounds=2) + elapsed = max(1e-9, time.monotonic() - start) + stats = self.queue.store.get_stats() + processed = sum(r.processed for r in results) + return LoadResult(count, processed, stats.get('queued',0), stats.get('done',0), stats.get('dead',0), elapsed, processed/elapsed) + + @staticmethod + def chaos_matrix() -> list[str]: + return ['duplicate_enqueue','concurrent_claim','worker_crash','lease_expiry','provider_429','provider_5xx','timeout','publish_crash','restart_recovery'] + + def snapshot(self): + return asdict(self.queue.store.get_stats()) diff --git a/core/infra/metrics.py b/core/infra/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..f6f65721a3424be9720f19923411dac0da508117 --- /dev/null +++ b/core/infra/metrics.py @@ -0,0 +1,22 @@ +from __future__ import annotations +from collections import Counter, defaultdict +from threading import Lock +from time import monotonic +class Metrics: + def __init__(self): self._c=Counter(); self._timings=defaultdict(lambda:[0.0,0,0.0]); self._lock=Lock() + def inc(self,name,n=1): + with self._lock:self._c[name]+=n + def observe(self,name,seconds): + v=max(0.0,float(seconds)) + with self._lock: + x=self._timings[name]; x[0]+=v; x[1]+=1; x[2]=max(x[2],v) + def timer(self,name): + metrics=self; start=monotonic() + class T: + def __enter__(self):return self + def __exit__(self,*exc):metrics.observe(name,monotonic()-start) + return T() + def snapshot(self): + with self._lock:return dict(self._c) + def detailed_snapshot(self): + with self._lock:return {"counters":dict(self._c),"latency":{k:{"total_seconds":round(v[0],6),"count":v[1],"max_seconds":round(v[2],6),"avg_seconds":round(v[0]/v[1],6) if v[1] else 0} for k,v in self._timings.items()}} diff --git a/core/infra/rate_limiter.py b/core/infra/rate_limiter.py new file mode 100644 index 0000000000000000000000000000000000000000..b11ca7059eb54460b6bee9ac9f428f7ed3e5a842 --- /dev/null +++ b/core/infra/rate_limiter.py @@ -0,0 +1,27 @@ +from __future__ import annotations +import time +from threading import Lock + +class TokenBucket: + def __init__(self,rate_per_second=1.0,capacity=1): + self.rate=max(float(rate_per_second),0.001); self.capacity=max(int(capacity),1) + self.tokens=float(self.capacity); self.updated=time.monotonic(); self.lock=Lock() + def acquire(self,tokens=1): + tokens=float(tokens) + while True: + with self.lock: + now=time.monotonic() + self.tokens=min(self.capacity,self.tokens+(now-self.updated)*self.rate) + self.updated=now + if self.tokens>=tokens: + self.tokens-=tokens; return + wait=(tokens-self.tokens)/self.rate + time.sleep(min(max(wait,0.01),5)) + +class ProviderLimiter: + def __init__(self): + self.buckets={} + def configure(self,name,rate_per_second,capacity=1): + self.buckets[name]=TokenBucket(rate_per_second,capacity) + def acquire(self,name,tokens=1): + self.buckets.setdefault(name,TokenBucket()).acquire(tokens) diff --git a/core/jobs/__init__.py b/core/jobs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..13e8bfb8f25a0e0b0d0361168fb1f1e6ab874e69 --- /dev/null +++ b/core/jobs/__init__.py @@ -0,0 +1,2 @@ +from .worker import JobWorker +__all__=['JobWorker'] diff --git a/core/jobs/concurrency.py b/core/jobs/concurrency.py new file mode 100644 index 0000000000000000000000000000000000000000..f070eed0d33a7b6cb4737fe1fe8b698fb67ef4de --- /dev/null +++ b/core/jobs/concurrency.py @@ -0,0 +1,47 @@ +from __future__ import annotations +import threading, time +from dataclasses import dataclass +from typing import Callable +from core.jobs.worker import JobWorker + +@dataclass +class WorkerRunResult: + worker_id: str + processed: int = 0 + errors: int = 0 + duration: float = 0.0 + +class ConcurrentWorkers: + """Small, dependency-free worker pool for bounded parallel queue processing.""" + def __init__(self, store, handlers: dict[str, Callable], workers: int = 2, lease_timeout=300): + self.store = store + self.handlers = handlers + self.workers = max(1, min(32, int(workers))) + self.lease_timeout = lease_timeout + + def run(self, max_jobs: int | None = None, idle_rounds: int = 1, idle_sleep: float = 0.01) -> list[WorkerRunResult]: + lock = threading.Lock() + remaining = [None if max_jobs is None else max(0, int(max_jobs))] + results: list[WorkerRunResult] = [] + def loop(idx: int): + worker = JobWorker(self.store, self.handlers, worker_id=f"p29-pool-{idx}-{threading.get_ident()}", lease_timeout=self.lease_timeout) + r = WorkerRunResult(worker.worker_id); start = time.monotonic() + idle = 0 + while idle < max(1, idle_rounds): + with lock: + if remaining[0] is not None and remaining[0] <= 0: break + if remaining[0] is not None: remaining[0] -= 1 + got = worker.run_once() + if got: + r.processed += 1; idle = 0 + else: + if remaining[0] is not None: + with lock: remaining[0] += 1 + idle += 1 + if idle < idle_rounds: time.sleep(idle_sleep) + r.duration = time.monotonic() - start + with lock: results.append(r) + threads = [threading.Thread(target=loop, args=(i,), daemon=True) for i in range(self.workers)] + for t in threads: t.start() + for t in threads: t.join() + return sorted(results, key=lambda x: x.worker_id) diff --git a/core/jobs/queue.py b/core/jobs/queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c934e44d76c86c11e1a0fe6171950cdd3ba9bcce --- /dev/null +++ b/core/jobs/queue.py @@ -0,0 +1,12 @@ +from core.storage.job_store import JobStore + +class ProcessingQueue: + """Stable façade for future migration of legacy scheduler queues to SQLite.""" + def __init__(self, path="data/jobs.sqlite3"): + self.store=JobStore(path) + + def enqueue_article(self, article_id, payload): + return self.store.enqueue("article.process", {"article_id": article_id, **payload}, job_id=f"article:{article_id}") + + def enqueue_publish(self, article_id, payload): + return self.store.enqueue("article.publish", {"article_id": article_id, **payload}, job_id=f"publish:{article_id}") diff --git a/core/jobs/store.py b/core/jobs/store.py new file mode 100644 index 0000000000000000000000000000000000000000..4a6d2f1be4b6e5cef056324798dc617b5d7889aa --- /dev/null +++ b/core/jobs/store.py @@ -0,0 +1,39 @@ +"""Compatibility facade over the Phase-15+ durable JobStore. + +Legacy callers may keep using ``core.jobs.store.JobStore`` while all new runtime +code uses the canonical ``core.storage.job_store.JobStore`` implementation. +""" +from __future__ import annotations +import sqlite3 +from core.storage.job_store import JobStore as _CanonicalJobStore + +class JobStore(_CanonicalJobStore): + def __init__(self, db_path): + super().__init__(db_path) + self.db_path = str(self.path) + self._ensure_legacy_view() + + def _ensure_legacy_view(self): + with self._conn() as c: + exists = c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='jobs'").fetchone() + if exists: + return + c.execute("""CREATE VIEW IF NOT EXISTS jobs AS + SELECT id, kind AS type, payload, status, attempts, + 5 AS max_attempts, available_at AS run_after, + worker_id AS locked_by, claimed_at AS locked_at, + last_error, created_at, updated_at + FROM p29_jobs""") + + def enqueue(self, job_type, payload, max_attempts=5, run_after=None, job_id=None, delay=0): + if run_after is not None: + import datetime + if hasattr(run_after, 'timestamp'): + delay = max(0.0, run_after.timestamp() - __import__('time').time()) + else: + try: delay = max(0.0, datetime.datetime.fromisoformat(str(run_after).replace('Z','+00:00')).timestamp() - __import__('time').time()) + except Exception: pass + return super().enqueue(job_type, payload, delay=delay, job_id=job_id) + + def recover_stale(self, timeout_seconds=300, timeout=None): + return super().recover_expired(float(timeout if timeout is not None else timeout_seconds)) diff --git a/core/jobs/worker.py b/core/jobs/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..9faf1e48484daa72b4abd8cc19aef31c05dae75e --- /dev/null +++ b/core/jobs/worker.py @@ -0,0 +1,45 @@ +from __future__ import annotations +import os, socket, time, traceback, threading +from typing import Callable +from core.storage.job_store import JobStore + + +class JobWorker: + def __init__(self, store: JobStore, handlers: dict[str, Callable], worker_id=None, lease_timeout=300, heartbeat_interval=None): + self.store=store + self.handlers=handlers + self.worker_id=worker_id or f"{socket.gethostname()}:{os.getpid()}" + self.running=True + self.lease_timeout=float(lease_timeout) + self.heartbeat_interval=float(heartbeat_interval or max(1.0, self.lease_timeout/3.0)) + + def stop(self): self.running=False + + def _heartbeat(self, job_id, stop_event): + while not stop_event.wait(self.heartbeat_interval): + try: + self.store.heartbeat(job_id, self.worker_id) + except Exception: + break + + def run_once(self) -> bool: + self.store.recover_expired(self.lease_timeout) + job=self.store.claim(self.worker_id) + if not job: return False + stop_event=threading.Event() + heartbeat=threading.Thread(target=self._heartbeat, args=(job["id"], stop_event), daemon=True) + heartbeat.start() + try: + handler=self.handlers[job["kind"]] + handler(job["payload"], job) + self.store.complete(job["id"], worker_id=self.worker_id) + except Exception as exc: + self.store.fail(job["id"], traceback.format_exc()) + finally: + stop_event.set() + heartbeat.join(timeout=1) + return True + + def run_forever(self, idle_sleep=1.0): + while self.running: + if not self.run_once(): time.sleep(idle_sleep) diff --git a/core/pipeline/__init__.py b/core/pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe200a38b079619d1ee45ccb4ea235d898e807d2 --- /dev/null +++ b/core/pipeline/__init__.py @@ -0,0 +1 @@ +from .content_pipeline import ContentPipeline, PipelineResult diff --git a/core/pipeline/adapter.py b/core/pipeline/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..cfe1ec7128dc23ab605b74f8f668f506fe558951 --- /dev/null +++ b/core/pipeline/adapter.py @@ -0,0 +1,23 @@ +from __future__ import annotations +from typing import Any + +class SectionPipelineAdapter: + """Small adapter layer for Blogger/News/Sports/future sections.""" + def __init__(self, section: str, gate, queue, ai_gateway, publisher): + self.section=section; self.gate=gate; self.queue=queue + self.ai=ai_gateway; self.publisher=publisher + + def submit(self, item_id: str, text: str, source_url: str="", channel_id: str="", **meta): + verdict=self.gate.preflight(text, source_url, channel_id) + if not verdict.allowed: + return {"status":"rejected","reason":verdict.reason,"matched":list(verdict.matched)} + job=self.queue.enqueue_article(item_id, {"section":self.section,"text":text,"source_url":source_url,**meta}) + return {"status":"queued","job_id":job,"fingerprint":verdict.fingerprint} + + def process(self, text: str, **kwargs): + response=self.ai.article_package(text, **kwargs) + data=response.data + return data if isinstance(data,dict) else {"result":data} + + def publish(self, item_id: str, target: str, content: str, **kwargs): + return self.publisher.publish(target,item_id,content,**kwargs) diff --git a/core/pipeline/content_pipeline.py b/core/pipeline/content_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..c9c4c39d2c21e609f5f4fa7da872a535203f79ca --- /dev/null +++ b/core/pipeline/content_pipeline.py @@ -0,0 +1,35 @@ +from __future__ import annotations +from dataclasses import dataclass, field +from typing import Callable, Any, Optional + +@dataclass +class PipelineResult: + status: str + data: Any = None + reason: str = "" + stage: str = "" + +class ContentPipeline: + """ + Common pipeline for Blogger, News, Sports and future sections. + Services plug into the same stages instead of duplicating business logic. + """ + def __init__(self, gate, queue, ai_gateway=None, publisher=None): + self.gate=gate + self.queue=queue + self.ai=ai_gateway + self.publisher=publisher + + def ingest(self, article: str, article_id: str, source: str, target: Optional[str]=None): + # gate API is intentionally duck-typed to preserve the existing implementation. + verdict=self.gate.check(article) + if not getattr(verdict,"accepted",False): + return PipelineResult("rejected", reason=getattr(verdict,"reason","blocked"), stage="gate") + job=self.queue.enqueue_article(article_id, {"article":article,"source":source,"target":target}) + return PipelineResult("queued", data={"job_id":job}, stage="queue") + + def process(self, payload: dict): + if not self.ai: + raise RuntimeError("AI gateway is not configured") + result=self.ai.article_package(payload["article"]) + return result diff --git a/core/plugins/__init__.py b/core/plugins/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..93369b2c3608250bfa17f1895b9f128b10d5c4d6 --- /dev/null +++ b/core/plugins/__init__.py @@ -0,0 +1,4 @@ +from .registry import PluginRegistry, PluginSpec +from .contracts import SectionSpec, SectionAdapter +from .manager import SectionManager +__all__=['PluginRegistry','PluginSpec','SectionSpec','SectionAdapter','SectionManager'] diff --git a/core/plugins/builtin.py b/core/plugins/builtin.py new file mode 100644 index 0000000000000000000000000000000000000000..bd7336a2db3dc7d4aa1d8a827a78b28f84852580 --- /dev/null +++ b/core/plugins/builtin.py @@ -0,0 +1,15 @@ +from __future__ import annotations +from .contracts import SectionSpec + +BUILTIN_SECTIONS = ( + SectionSpec("blogger", "publishing", secret_names=( + "BLOGGER_BLOG_ID", "BLOGGER_CLIENT_ID", "BLOGGER_CLIENT_SECRET", "BLOGGER_REFRESH_TOKEN" + )), + SectionSpec("news", "content", capabilities=("ingest", "process", "publish")), + SectionSpec("sports", "content", capabilities=("ingest", "process", "publish")), +) + +def register_builtins(registry): + for spec in BUILTIN_SECTIONS: + registry.register(spec) + return registry diff --git a/core/plugins/contracts.py b/core/plugins/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..e8f6fcbb4318070c61eb062908c068980d50c74f --- /dev/null +++ b/core/plugins/contracts.py @@ -0,0 +1,18 @@ +from __future__ import annotations +from dataclasses import dataclass, field +from typing import Any, Protocol + +@dataclass(frozen=True) +class SectionSpec: + name: str + kind: str + version: str = "1" + secret_names: tuple[str, ...] = () + capabilities: tuple[str, ...] = ("ingest", "process", "publish") + metadata: dict[str, Any] = field(default_factory=dict) + +class SectionAdapter(Protocol): + spec: SectionSpec + def ingest(self, item: dict[str, Any]) -> dict[str, Any]: ... + def process(self, item: dict[str, Any], ai_gateway: Any) -> dict[str, Any]: ... + def publish(self, item: dict[str, Any], publisher: Any) -> dict[str, Any]: ... diff --git a/core/plugins/manager.py b/core/plugins/manager.py new file mode 100644 index 0000000000000000000000000000000000000000..baaa7aabcef480392178876ea056af0b78c8f8aa --- /dev/null +++ b/core/plugins/manager.py @@ -0,0 +1,16 @@ +from __future__ import annotations +from .registry import PluginRegistry +from .builtin import register_builtins + +class SectionManager: + """Central registry: new sections are plugins, not edits to the core pipeline.""" + def __init__(self, registry=None): + self.registry=registry or PluginRegistry() + register_builtins(self.registry) + self.registry.discover() + + def get(self, name): + return self.registry.get(name) + + def list(self): + return self.registry.all() diff --git a/core/plugins/manifest.py b/core/plugins/manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..c657164bfa90d303c0dab075d7f4f8ac513db951 --- /dev/null +++ b/core/plugins/manifest.py @@ -0,0 +1,18 @@ +from __future__ import annotations +from dataclasses import dataclass + +@dataclass(frozen=True) +class PluginManifest: + key: str + version: str + section: str + adapter: str + enabled: bool=True + +class PluginRegistry: + def __init__(self): self._items={} + def register(self,manifest,adapter): + if manifest.key in self._items: raise ValueError("duplicate plugin") + self._items[manifest.key]=(manifest,adapter) + def get(self,key): return self._items[key][1] + def manifests(self): return [x[0] for x in self._items.values()] diff --git a/core/plugins/registry.py b/core/plugins/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..fa26d9d8fbdf869cb3778e8064593ad7ac371475 --- /dev/null +++ b/core/plugins/registry.py @@ -0,0 +1,24 @@ +"""Plugin discovery without hard-coding future providers.""" +from dataclasses import dataclass, field +from importlib.metadata import entry_points + +@dataclass +class PluginSpec: + name: str + kind: str + factory: object | None = None + secrets: list[str] = field(default_factory=list) + metadata: dict = field(default_factory=dict) + +class PluginRegistry: + def __init__(self): self._plugins = {} + def register(self, spec: PluginSpec): self._plugins[spec.name] = spec + def get(self, name): return self._plugins.get(name) + def all(self): return dict(self._plugins) + def discover(self, group="p29.plugins"): + eps = entry_points() + eps = eps.select(group=group) if hasattr(eps, 'select') else eps.get(group, []) + for ep in eps: + obj = ep.load(); spec = obj() if callable(obj) else obj + self.register(spec) + return self.all() diff --git a/core/providers/__init__.py b/core/providers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d8495179319038e8098db36c2df20a8607a2830f --- /dev/null +++ b/core/providers/__init__.py @@ -0,0 +1,3 @@ +from .pool import AIProviderPool, KeyState + +__all__ = ['AIProviderPool', 'KeyState'] diff --git a/core/providers/pool.py b/core/providers/pool.py new file mode 100644 index 0000000000000000000000000000000000000000..aa3970dfeb90a204cb037755b59f2fea9a34bc76 --- /dev/null +++ b/core/providers/pool.py @@ -0,0 +1,133 @@ +""" +P29 AI Provider Pool +- Discovers legacy key names without renaming them. +- Rotates keys using least-recently-used selection. +- Applies cooldowns for rate limits/transient failures. +- Keeps provider/key state in memory; persistence can be added to SQLite later. +""" +from __future__ import annotations + +from dataclasses import dataclass +from time import monotonic +from threading import RLock +import os +import re +from typing import Iterable, Optional +from core.infra.rate_limiter import ProviderLimiter + + +@dataclass +class KeyState: + name: str + value: str + provider: str + uses: int = 0 + failures: int = 0 + tokens: int = 0 + cooldown_until: float = 0.0 + last_used: float = 0.0 + rate_key: str = "" + + @property + def available(self) -> bool: + return bool(self.value) and monotonic() >= self.cooldown_until + + +class AIProviderPool: + """ + Provider/key scheduler. It never requires changing existing secret names. + + Recognized examples: + GEMINI_KEY_1, GEMINI_KEY_2, ... + GROQ_KEY_1, GROQ_KEY_2, ... + OPENROUTER_KEY_1, OPENROUTER_KEY_2, ... + """ + PATTERNS = { + "gemini": re.compile(r"^GEMINI_KEY_(\d+)$", re.I), + "groq": re.compile(r"^GROQ_KEY_(\d+)$", re.I), + "openrouter": re.compile(r"^OPENROUTER_KEY_(\d+)$", re.I), + } + + def __init__(self, environ: Optional[dict] = None): + self._env = environ if environ is not None else os.environ + self._lock = RLock() + self._keys: dict[str, list[KeyState]] = {} + self.limiter = ProviderLimiter() + self.reload() + + def reload(self) -> None: + with self._lock: + self._keys.clear() + for provider, pattern in self.PATTERNS.items(): + found = [] + for name, value in self._env.items(): + if pattern.match(name) and value: + found.append(KeyState(name=name, value=value, provider=provider, rate_key=name)) + # Per-key limiter. Defaults are intentionally conservative and + # can be tuned per provider/key through environment variables. + rate = float(self._env.get(f"P29_RATE_{provider.upper()}_PER_SEC", "2")) + capacity = int(self._env.get(f"P29_RATE_{provider.upper()}_CAPACITY", "2")) + self.limiter.configure(name, rate, capacity) + found.sort(key=lambda x: int(pattern.match(x.name).group(1))) + if found: + self._keys[provider] = found + + def providers(self) -> list[str]: + with self._lock: + return list(self._keys) + + def key_names(self, provider: str) -> list[str]: + with self._lock: + return [k.name for k in self._keys.get(provider.lower(), [])] + + def acquire(self, provider: str) -> Optional[KeyState]: + """Select the least-used available key; ties go to least recently used. + The rate limiter is waited on outside the pool lock so another worker can + still report failures/cooldowns while one key is rate-limited. + """ + with self._lock: + candidates = [k for k in self._keys.get(provider.lower(), []) if k.available] + if not candidates: + return None + candidates.sort(key=lambda k: (k.uses, k.last_used)) + selected = candidates[0] + self.limiter.acquire(selected.name) + with self._lock: + selected.uses += 1 + selected.last_used = monotonic() + return selected + + def report_success(self, key: KeyState, tokens: int = 0) -> None: + with self._lock: + key.tokens += max(0, int(tokens or 0)) + + def report_failure(self, key: KeyState, cooldown_seconds: int = 30, rate_limited: bool = False) -> None: + with self._lock: + key.failures += 1 + # Longer cooldown for explicit rate limits, bounded to avoid permanent lockout. + cd = max(1, min(3600, cooldown_seconds * (4 if rate_limited else 1))) + key.cooldown_until = monotonic() + cd + + def choose(self, preferred: Optional[Iterable[str]] = None) -> Optional[KeyState]: + order = list(preferred or self.providers()) + for provider in order: + key = self.acquire(provider) + if key: + return key + return None + + def snapshot(self) -> dict: + with self._lock: + return { + p: [ + { + "name": k.name, + "uses": k.uses, + "failures": k.failures, + "tokens": k.tokens, + "cooldown": max(0, round(k.cooldown_until - monotonic(), 2)), + } + for k in keys + ] + for p, keys in self._keys.items() + } diff --git a/core/providers/router.py b/core/providers/router.py new file mode 100644 index 0000000000000000000000000000000000000000..81a74eb466b8399391a76f0d461cc9e994b1d43d --- /dev/null +++ b/core/providers/router.py @@ -0,0 +1,10 @@ +"""Provider failover policy. Provider adapters can be registered dynamically.""" +class ProviderRouter: + def __init__(self): self._providers=[] + def register(self,name,client,priority=100): self._providers.append((priority,name,client)); self._providers.sort(key=lambda x:x[0]) + async def call(self, method, *args, **kwargs): + errors=[] + for _,name,client in self._providers: + try: return await getattr(client,method)(*args,**kwargs) + except Exception as exc: errors.append((name,exc)) + raise RuntimeError(f'All providers failed: {errors!r}') diff --git a/core/publishing/__init__.py b/core/publishing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..046d9747bf0b4f8bff787b3784229e60e739cec4 --- /dev/null +++ b/core/publishing/__init__.py @@ -0,0 +1,2 @@ +from .ledger import PublishLedger +__all__=['PublishLedger'] diff --git a/core/publishing/ledger.py b/core/publishing/ledger.py new file mode 100644 index 0000000000000000000000000000000000000000..803826060295ac007fa1c597f107747c5f699ebb --- /dev/null +++ b/core/publishing/ledger.py @@ -0,0 +1,125 @@ +from __future__ import annotations +import sqlite3, time, hashlib +from pathlib import Path +from threading import RLock +from typing import Optional + +class PublishLedger: + """ + Durable idempotency ledger for remote publishing. + + Key rule: + same (target, article_id) => one logical publish operation. + remote_id is recorded before/after completion when the target supports it. + """ + def __init__(self, path: str = "data/jobs.sqlite3"): + self.path = Path(path) + self.path.parent.mkdir(parents=True, exist_ok=True) + self._lock = RLock() + self._init() + + def _conn(self): + c = sqlite3.connect(self.path, timeout=30, isolation_level=None) + c.row_factory = sqlite3.Row + c.execute("PRAGMA journal_mode=WAL") + c.execute("PRAGMA synchronous=FULL") + c.execute("PRAGMA busy_timeout=30000") + return c + + def _init(self): + with self._conn() as c: + c.execute("""CREATE TABLE IF NOT EXISTS publish_ledger( + idempotency_key TEXT PRIMARY KEY, + target TEXT NOT NULL, + article_id TEXT NOT NULL, + content_hash TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + remote_id TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + created_at REAL NOT NULL, + updated_at REAL NOT NULL, + attempt_started_at REAL, + UNIQUE(target, article_id) + )""") + c.execute("CREATE INDEX IF NOT EXISTS idx_publish_status ON publish_ledger(status)") + columns = {row[1] for row in c.execute("PRAGMA table_info(publish_ledger)").fetchall()} + if "attempt_started_at" not in columns: + c.execute("ALTER TABLE publish_ledger ADD COLUMN attempt_started_at REAL") + + @staticmethod + def make_key(target: str, article_id: str) -> str: + raw = f"{target}\0{article_id}".encode() + return hashlib.sha256(raw).hexdigest() + + def begin(self, target: str, article_id: str, content: str) -> dict: + key = self.make_key(target, article_id) + now = time.time() + content_hash = hashlib.sha256(content.encode("utf-8", "ignore")).hexdigest() + with self._lock, self._conn() as c: + row = c.execute("SELECT * FROM publish_ledger WHERE idempotency_key=?", (key,)).fetchone() + if row: + item = dict(row) + if item.get("status") == "publishing": + started = float(item.get("attempt_started_at") or item.get("updated_at") or 0) + if started and now - started > 300: + c.execute("UPDATE publish_ledger SET status='pending', updated_at=?, attempt_started_at=NULL, last_error=? WHERE idempotency_key=?", + (now, "stale publishing lease recovered", key)) + item = dict(c.execute("SELECT * FROM publish_ledger WHERE idempotency_key=?", (key,)).fetchone()) + return item + c.execute("""INSERT INTO publish_ledger + (idempotency_key,target,article_id,content_hash,status,attempts,created_at,updated_at) + VALUES(?,?,?,?, 'pending',0,?,?)""", + (key, target, article_id, content_hash, now, now)) + return dict(c.execute("SELECT * FROM publish_ledger WHERE idempotency_key=?", (key,)).fetchone()) + + + def claim_attempt(self, key: str) -> bool: + """Atomically claim a publish lease for one idempotency key. + + This closes the final race where two workers both observed ``pending`` + before either called ``mark_attempt``. Only one worker can transition the + row into ``publishing`` at a time. + """ + now = time.time() + with self._lock, self._conn() as c: + cur = c.execute( + "UPDATE publish_ledger SET attempts=attempts+1,status='publishing'," + "updated_at=?,attempt_started_at=? " + "WHERE idempotency_key=? AND status IN ('pending','failed')", + (now, now, key), + ) + return cur.rowcount == 1 + + def mark_attempt(self, key: str): + with self._conn() as c: + c.execute("""UPDATE publish_ledger SET attempts=attempts+1,status='publishing', + updated_at=?,attempt_started_at=? WHERE idempotency_key=?""", (time.time(), time.time(), key)) + + def mark_published(self, key: str, remote_id: Optional[str] = None): + with self._conn() as c: + c.execute("""UPDATE publish_ledger SET status='published',remote_id=?, + updated_at=?,last_error=NULL,attempt_started_at=NULL WHERE idempotency_key=?""", + (remote_id, time.time(), key)) + + def mark_failed(self, key: str, error: str): + with self._conn() as c: + c.execute("""UPDATE publish_ledger SET status='failed',last_error=?, + updated_at=?,attempt_started_at=NULL WHERE idempotency_key=?""", + (str(error)[:4000], time.time(), key)) + + def get(self, key: str): + with self._conn() as c: + row = c.execute("SELECT * FROM publish_ledger WHERE idempotency_key=?", (key,)).fetchone() + return dict(row) if row else None + + def recover_stale(self, timeout: float = 300) -> int: + cutoff = time.time() - max(1, float(timeout)) + with self._conn() as c: + cur = c.execute("UPDATE publish_ledger SET status='pending', attempt_started_at=NULL, updated_at=?, last_error=? WHERE status='publishing' AND COALESCE(attempt_started_at, updated_at) < ?", + (time.time(), "stale publishing lease recovered", cutoff)) + return cur.rowcount + + def can_attempt(self, target: str, article_id: str) -> bool: + row = self.get(self.make_key(target, article_id)) + return not row or row["status"] not in {"published", "publishing"} diff --git a/core/publishing/publisher.py b/core/publishing/publisher.py new file mode 100644 index 0000000000000000000000000000000000000000..a16a984349294dbc1d066de91ff55ff5846da3cc --- /dev/null +++ b/core/publishing/publisher.py @@ -0,0 +1,37 @@ +from __future__ import annotations +from typing import Callable, Optional +from .ledger import PublishLedger + +class IdempotentPublisher: + def __init__(self, ledger: PublishLedger, adapters: dict[str, Callable], lease_timeout: float = 300): + self.ledger = ledger + self.adapters = adapters + self.lease_timeout = float(lease_timeout) + + def publish(self, target: str, article_id: str, content: str, **kwargs): + self.ledger.recover_stale(self.lease_timeout) + record = self.ledger.begin(target, article_id, content) + + # Already completed: never publish again. + if record["status"] == "published": + return {"status": "already_published", "remote_id": record["remote_id"]} + + # Another worker is publishing it. Avoid duplicate remote calls. + if record["status"] == "publishing": + return {"status": "in_progress", "remote_id": record["remote_id"]} + + adapter = self.adapters[target] + key = record["idempotency_key"] + if not self.ledger.claim_attempt(key): + latest = self.ledger.get(key) or {} + if latest.get("status") == "published": + return {"status": "already_published", "remote_id": latest.get("remote_id")} + return {"status": "in_progress", "remote_id": latest.get("remote_id")} + try: + result = adapter(content, idempotency_key=key, **kwargs) + remote_id = result.get("remote_id") if isinstance(result, dict) else None + self.ledger.mark_published(key, remote_id) + return {"status": "published", "remote_id": remote_id, "result": result} + except Exception as exc: + self.ledger.mark_failed(key, str(exc)) + raise diff --git a/core/release/__init__.py b/core/release/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9d3ade14dd2448c69f107f3daa4ee8dcbf93e9a3 --- /dev/null +++ b/core/release/__init__.py @@ -0,0 +1,5 @@ +from .backup import BackupManager, BackupResult +from .readiness import ProductionReadiness, ReadinessFinding, ReadinessReport +from .release import ReleaseManifest + +__all__ = ["BackupManager", "BackupResult", "ProductionReadiness", "ReadinessFinding", "ReadinessReport", "ReleaseManifest"] diff --git a/core/release/backup.py b/core/release/backup.py new file mode 100644 index 0000000000000000000000000000000000000000..969d46d971a7173105ba3e49baf0df010b04f80f --- /dev/null +++ b/core/release/backup.py @@ -0,0 +1,123 @@ +from __future__ import annotations +import hashlib, json, os, sqlite3, tempfile, time +from dataclasses import dataclass, asdict +from pathlib import Path + +@dataclass(frozen=True) +class BackupResult: + ok: bool + path: str + sha256: str + size: int + databases: tuple[str, ...] + verified: bool + error: str = "" + +class BackupManager: + """Atomic, verifiable backups for P29 SQLite state and release metadata.""" + def __init__(self, data_dir: str = "data", backup_dir: str = "backups"): + self.data_dir = Path(data_dir) + self.backup_dir = Path(backup_dir) + self.backup_dir.mkdir(parents=True, exist_ok=True) + + @staticmethod + def _sha256(path: Path) -> str: + h=hashlib.sha256() + with path.open("rb") as f: + for chunk in iter(lambda:f.read(1024*1024), b""): + h.update(chunk) + return h.hexdigest() + + @staticmethod + def _sqlite_backup(src: Path, dst: Path) -> None: + src_con = sqlite3.connect(src, timeout=30) + dst_con = sqlite3.connect(dst) + try: + src_con.execute("PRAGMA integrity_check") + src_con.backup(dst_con) + finally: + dst_con.close(); src_con.close() + + def create(self, databases: list[str] | tuple[str, ...], label: str = "release") -> BackupResult: + stamp=time.strftime("%Y%m%d-%H%M%S", time.gmtime()) + final=self.backup_dir / f"p29-{label}-{stamp}-{os.getpid()}.bak" + temp=Path(tempfile.mktemp(prefix=final.name+".", dir=str(self.backup_dir))) + dbs=[] + try: + with temp.open("wb") as out: + manifest={"created_at":time.time(),"label":label,"databases":[]} + for raw in databases: + p=Path(raw) + if not p.exists(): + continue + if p.suffix.lower() not in {".sqlite3",".sqlite",".db"}: + continue + dbtmp=Path(tempfile.mktemp(prefix="db-", suffix=p.suffix)) + try: + self._sqlite_backup(p, dbtmp) + blob=dbtmp.read_bytes() + finally: + dbtmp.unlink(missing_ok=True) + entry={"path":str(p),"name":p.name,"sha256":hashlib.sha256(blob).hexdigest(),"size":len(blob)} + manifest["databases"].append(entry); dbs.append(str(p)) + name_bytes=json.dumps(entry,sort_keys=True).encode() + out.write(len(name_bytes).to_bytes(4,"big")); out.write(name_bytes) + out.write(len(blob).to_bytes(8,"big")); out.write(blob) + m=json.dumps(manifest,ensure_ascii=False,sort_keys=True).encode() + out.write(b"P29M"); out.write(len(m).to_bytes(8,"big")); out.write(m) + out.flush(); os.fsync(out.fileno()) + os.replace(temp,final) + digest=self._sha256(final) + verified=self.verify(final) + return BackupResult(verified,str(final),digest,final.stat().st_size,tuple(dbs),verified) + except Exception as exc: + temp.unlink(missing_ok=True) + return BackupResult(False,str(final),"",0,tuple(dbs),False,str(exc)) + + def verify(self, backup_path: str | Path) -> bool: + p=Path(backup_path) + if not p.exists() or p.stat().st_size < 12:return False + raw=p.read_bytes() + pos=0; seen=[] + try: + while pos < len(raw): + if raw[pos:pos+4] == b"P29M": + n=int.from_bytes(raw[pos+4:pos+12],"big"); m=json.loads(raw[pos+12:pos+12+n]); + if m.get("schema") not in (None,): pass + return bool(m.get("databases",[]) or m.get("label")) + n=int.from_bytes(raw[pos:pos+4],"big"); pos+=4 + entry=json.loads(raw[pos:pos+n]); pos+=n + size=int.from_bytes(raw[pos:pos+8],"big"); pos+=8 + blob=raw[pos:pos+size]; pos+=size + if len(blob)!=size or hashlib.sha256(blob).hexdigest()!=entry.get("sha256"):return False + seen.append(blob) + return False + except Exception:return False + + + def restore(self, backup_path: str | Path, target_dir: str | Path, overwrite: bool = False) -> list[str]: + """Restore verified SQLite images into target_dir; refuses overwrite by default.""" + backup=Path(backup_path); target=Path(target_dir); target.mkdir(parents=True, exist_ok=True) + if not self.verify(backup): raise RuntimeError("backup verification failed") + raw=backup.read_bytes(); pos=0; restored=[] + while pos < len(raw): + if raw[pos:pos+4] == b"P29M": break + n=int.from_bytes(raw[pos:pos+4],"big"); pos+=4 + entry=json.loads(raw[pos:pos+n]); pos+=n + size=int.from_bytes(raw[pos:pos+8],"big"); pos+=8 + blob=raw[pos:pos+size]; pos+=size + name=Path(entry["name"]).name + dest=target/name + if dest.exists() and not overwrite: raise FileExistsError(str(dest)) + tmp=dest.with_suffix(dest.suffix+".restore.tmp") + tmp.write_bytes(blob); os.replace(tmp,dest) + with sqlite3.connect(dest) as c: + row=c.execute("PRAGMA integrity_check").fetchone() + if not row or row[0] != "ok": + dest.unlink(missing_ok=True); raise RuntimeError(f"restored database failed integrity check: {dest}") + restored.append(str(dest)) + return restored + + def latest(self) -> Path | None: + items=sorted(self.backup_dir.glob("p29-*.bak"), key=lambda p:p.stat().st_mtime, reverse=True) + return items[0] if items else None diff --git a/core/release/go_live.py b/core/release/go_live.py new file mode 100644 index 0000000000000000000000000000000000000000..1eca07ac8feb7500aa1aa2b5d0bcd4590b6579d1 --- /dev/null +++ b/core/release/go_live.py @@ -0,0 +1,52 @@ +from __future__ import annotations +import importlib.util +import os +import time +from dataclasses import dataclass, asdict +from typing import Any + +@dataclass +class GoLiveCheck: + name: str + ok: bool + detail: str = "" + critical: bool = True + +class GoLiveGate: + """Final release gate. External Telegram credentials are never required for dry-run CI.""" + def __init__(self, app): + self.app = app + + def checks(self, require_telegram: bool = False) -> list[GoLiveCheck]: + out: list[GoLiveCheck] = [] + report = self.app.production_readiness() + out.append(GoLiveCheck("production_readiness", report.ready, "; ".join(f.detail for f in report.findings))) + out.append(GoLiveCheck("sqlite_integrity", self._sqlite_integrity(), "runtime databases integrity")) + out.append(GoLiveCheck("plugins", set(self.app.discover_plugins()) >= {"blogger", "news", "sports"}, str(self.app.discover_plugins()))) + out.append(GoLiveCheck("telegram_dependency", self._pyrogram_available(), "pyrogram import" , critical=require_telegram)) + if require_telegram: + out.append(GoLiveCheck("telegram_credentials", bool(os.getenv("API_ID")) and bool(os.getenv("API_HASH")), "API_ID/API_HASH present")) + return out + + def evaluate(self, require_telegram: bool = False) -> dict[str, Any]: + checks = self.checks(require_telegram=require_telegram) + blocking = [c for c in checks if c.critical and not c.ok] + return {"ready": not blocking, "checks": [asdict(c) for c in checks], "timestamp": time.time()} + + def _sqlite_integrity(self) -> bool: + try: + import sqlite3 + paths = {str(self.app.settings.db_path), str(self.app.runtime.db_path)} + for path in paths: + if not os.path.exists(path): + continue + with sqlite3.connect(path) as c: + if c.execute("PRAGMA integrity_check").fetchone()[0] != "ok": + return False + return True + except Exception: + return False + + @staticmethod + def _pyrogram_available() -> bool: + return importlib.util.find_spec("pyrogram") is not None diff --git a/core/release/readiness.py b/core/release/readiness.py new file mode 100644 index 0000000000000000000000000000000000000000..7e67dc27b7a34989e5bbc09ea38f885cd333e0b9 --- /dev/null +++ b/core/release/readiness.py @@ -0,0 +1,66 @@ +from __future__ import annotations +import os, sqlite3, sys, time +from dataclasses import dataclass, asdict +from pathlib import Path + +@dataclass(frozen=True) +class ReadinessFinding: + code: str + severity: str + detail: str + +@dataclass(frozen=True) +class ReadinessReport: + ready: bool + findings: tuple[ReadinessFinding, ...] + checks: dict + generated_at: float + +class ProductionReadiness: + """Deterministic preflight gate; never mutates runtime state.""" + def __init__(self, runtime=None, project_root="."): + self.runtime=runtime; self.root=Path(project_root) + + def _db_check(self, path): + p=Path(path) + if not p.exists(): return False, "database_missing" + try: + with sqlite3.connect(p, timeout=5) as c: + row=c.execute("PRAGMA integrity_check").fetchone() + return bool(row and row[0]=="ok"), str(row[0] if row else "unknown") + except Exception as exc:return False, str(exc)[:200] + + def evaluate(self, require_secrets: tuple[str,...]=()) -> ReadinessReport: + findings=[]; checks={} + if sys.version_info < (3,10): findings.append(ReadinessFinding("python_version","critical",sys.version.split()[0])) + checks["python_version"]=sys.version.split()[0] + db_path=getattr(getattr(self.runtime,"queue",None),"store",None) + db_path=getattr(db_path,"path",None) or getattr(self.runtime,"db_path",None) + if db_path: + ok,detail=self._db_check(db_path); checks["database_integrity"]=detail + if not ok: findings.append(ReadinessFinding("database_integrity","critical",detail)) + if self.runtime is not None: + try: + stats=self.runtime.queue.store.get_stats(); checks["queue"]=stats + if stats.get("running",0): findings.append(ReadinessFinding("running_jobs","warning",str(stats["running"]))) + except Exception as exc: findings.append(ReadinessFinding("queue_check","critical",str(exc)[:200])) + try: + health=self.runtime.health_snapshot(); checks["health"]=health + bad=[k for k,v in health.items() if v.get("status")=="unhealthy"] + if bad: findings.append(ReadinessFinding("unhealthy_services","critical",",".join(bad))) + except Exception as exc: findings.append(ReadinessFinding("health_check","critical",str(exc)[:200])) + try: + sf=self.runtime.security.validate_environment(require_secrets) + checks["security_findings"]=[asdict(x) for x in sf] + findings.extend(ReadinessFinding(x.code,x.severity,x.detail) for x in sf) + except Exception as exc: findings.append(ReadinessFinding("security_check","critical",str(exc)[:200])) + for name in require_secrets: + if not os.getenv(name): findings.append(ReadinessFinding("missing_secret","critical",name)) + critical=any(x.severity=="critical" for x in findings) + return ReadinessReport(not critical,tuple(findings),checks,time.time()) + + def assert_ready(self, **kwargs): + report=self.evaluate(**kwargs) + if not report.ready: + raise RuntimeError("P29 production readiness failed: " + "; ".join(f"{x.code}:{x.detail}" for x in report.findings if x.severity=="critical")) + return report diff --git a/core/release/release.py b/core/release/release.py new file mode 100644 index 0000000000000000000000000000000000000000..4754a2371521e530c3cf89bc3934f1f7c98d4550 --- /dev/null +++ b/core/release/release.py @@ -0,0 +1,19 @@ +from __future__ import annotations +import hashlib, json, os, time +from pathlib import Path + +class ReleaseManifest: + """Reproducible release manifest without exposing environment secret values.""" + def __init__(self, root="."): + self.root=Path(root) + def build(self, version="29.0", phase="23", output=None): + files=[] + for p in sorted(self.root.rglob("*")): + if not p.is_file() or any(part in {".git","__pycache__","data","backups"} for part in p.parts): continue + if p.name.endswith(".pyc"): continue + h=hashlib.sha256(p.read_bytes()).hexdigest() + files.append({"path":str(p.relative_to(self.root)),"sha256":h,"size":p.stat().st_size}) + doc={"product":"P29","version":version,"phase":str(phase),"generated_at":time.time(),"python_min":"3.10","files":files} + if output: + out=Path(output); out.parent.mkdir(parents=True,exist_ok=True); out.write_text(json.dumps(doc,ensure_ascii=False,indent=2,sort_keys=True),encoding="utf-8") + return doc diff --git a/core/repair/__init__.py b/core/repair/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..80f653bc4790a9bb810f2dcd009d6f4fcaff3bcf --- /dev/null +++ b/core/repair/__init__.py @@ -0,0 +1,3 @@ +from .sandbox import PatchSandbox, PatchResult +from .engine import AutoRepairEngine, RepairRecord +__all__=['PatchSandbox','PatchResult','AutoRepairEngine','RepairRecord'] diff --git a/core/repair/engine.py b/core/repair/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..f161a949c84dd309f7491f55097eaad0ceda7b57 --- /dev/null +++ b/core/repair/engine.py @@ -0,0 +1,65 @@ +from __future__ import annotations +import shutil, time, uuid +from pathlib import Path +from dataclasses import dataclass +from .sandbox import PatchSandbox, PatchResult + +@dataclass +class RepairRecord: + repair_id: str + status: str + reason: str + changed_files: list[str] + backup_dir: str = "" + +class AutoRepairEngine: + """ + AI is a proposer, not an executor. + The engine only accepts a patch after sandbox validation/tests. + """ + def __init__(self, project_root: str, backup_root: str="data/repair_backups"): + self.root=Path(project_root).resolve() + self.backups=Path(backup_root) + self.backups.mkdir(parents=True,exist_ok=True) + self.sandbox=PatchSandbox(str(self.root)) + + def propose_and_test(self, patch: str, tests=None) -> tuple[RepairRecord,PatchResult]: + rid=str(uuid.uuid4()) + result=self.sandbox.test(patch,tests=tests) + status="approved" if result.passed else "rejected" + return RepairRecord(rid,status,result.reason,result.changed_files),result + + def apply_approved(self, record: RepairRecord, sandbox_dir: str) -> RepairRecord: + if record.status!="approved": + raise RuntimeError("Only an approved repair can be applied") + backup=self.backups/(record.repair_id) + backup.mkdir(parents=True,exist_ok=True) + # Backup only files the patch is allowed to change. + for rel in record.changed_files: + src=self.root/rel + if src.exists() and src.is_file(): + dst=backup/rel; dst.parent.mkdir(parents=True,exist_ok=True) + shutil.copy2(src,dst) + # Copy the tested versions from sandbox. + tested=Path(sandbox_dir)/"project" + for rel in record.changed_files: + src=tested/rel + dst=self.root/rel + if src.exists(): + dst.parent.mkdir(parents=True,exist_ok=True) + shutil.copy2(src,dst) + record.backup_dir=str(backup) + record.status="applied" + return record + + def rollback(self, record: RepairRecord): + if not record.backup_dir: + raise RuntimeError("No backup recorded") + backup=Path(record.backup_dir) + for rel in record.changed_files: + src=backup/rel + dst=self.root/rel + if src.exists(): shutil.copy2(src,dst) + elif dst.exists(): dst.unlink() + record.status="rolled_back" + return record diff --git a/core/repair/guarded.py b/core/repair/guarded.py new file mode 100644 index 0000000000000000000000000000000000000000..af729f7c67b53ea2d050e57d3d8f3c914e4fb54e --- /dev/null +++ b/core/repair/guarded.py @@ -0,0 +1,28 @@ +from __future__ import annotations +from .engine import AutoRepairEngine +from .policy import RepairGuard + +class GuardedRepair: + def __init__(self, engine: AutoRepairEngine, guard: RepairGuard, health_check=None): + self.engine=engine + self.guard=guard + self.health_check=health_check + + def test_and_apply(self, incident_id, patch, tests=None, admin_approved=False): + rec,res=self.engine.propose_and_test(patch, tests=tests) + if not res.passed: + return rec + allowed,risk,reason=self.guard.authorize(incident_id, rec.changed_files, admin_approved) + if not allowed: + rec.status="approval_required" if "approval" in reason else "blocked" + rec.reason=reason + return rec + rec=self.engine.apply_approved(rec,res.sandbox_dir) + if self.health_check: + try: + healthy=self.health_check() + except Exception: + healthy=False + if not healthy: + self.engine.rollback(rec) + return rec diff --git a/core/repair/policy.py b/core/repair/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5d5335f45534a099825a002f5f649eb405d3f9 --- /dev/null +++ b/core/repair/policy.py @@ -0,0 +1,49 @@ +from __future__ import annotations +from dataclasses import dataclass, field +from pathlib import Path +import time + +@dataclass(frozen=True) +class RepairPolicy: + enabled: bool = True + auto_apply_low_risk: bool = False + require_admin_for_medium: bool = True + require_admin_for_high: bool = True + max_attempts_per_incident: int = 2 + cooldown_seconds: int = 300 + allowed_roots: tuple[str,...] = ("core/", "modules/", "services/") + protected_fragments: tuple[str,...] = ( + ".env", "secret", "credential", "token", "key", + "sessions/", "data/", ".git/" + ) + +class RepairGuard: + def __init__(self, policy: RepairPolicy|None=None): + self.policy=policy or RepairPolicy() + self._incidents={} + + def classify(self, changed_files): + files=[x.replace("\\","/").lower() for x in changed_files] + if any(any(p in f for p in self.policy.protected_fragments) for f in files): + return "blocked" + if any(not any(f.startswith(r) for r in self.policy.allowed_roots) for f in files): + return "high" + if any(f.endswith((".py",".json",".yaml",".yml")) for f in files): + return "medium" + return "high" + + def authorize(self, incident_id, changed_files, admin_approved=False): + risk=self.classify(changed_files) + now=time.time() + state=self._incidents.get(incident_id, {"attempts":0,"last":0}) + if risk=="blocked": return False, risk, "protected files are never auto-repairable" + if state["attempts"] >= self.policy.max_attempts_per_incident: + return False, risk, "repair attempt limit reached" + if now-state["last"] < self.policy.cooldown_seconds: + return False, risk, "repair cooldown active" + if risk=="medium" and self.policy.require_admin_for_medium and not admin_approved: + return False, risk, "admin approval required" + if risk=="high" and self.policy.require_admin_for_high and not admin_approved: + return False, risk, "admin approval required" + state["attempts"]+=1; state["last"]=now; self._incidents[incident_id]=state + return True, risk, "authorized" diff --git a/core/repair/sandbox.py b/core/repair/sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..23f740a10d0e0ef5174e870a0a6d54f48733f609 --- /dev/null +++ b/core/repair/sandbox.py @@ -0,0 +1,76 @@ +from __future__ import annotations +import ast, shutil, tempfile, subprocess, sys, os +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable, Optional + +@dataclass +class PatchResult: + passed: bool + reason: str + sandbox_dir: str + changed_files: list[str] + +class PatchSandbox: + """ + Conservative patch gate: + - copies only explicitly allowed files + - rejects secrets/config/runtime data paths + - applies unified diff in an isolated temporary tree + - compiles the tree and optionally runs selected tests + """ + DEFAULT_DENY = ( + ".env", "secrets", "secret", "credentials", "token", "key", + "data/", "sessions/", ".git/" + ) + + def __init__(self, project_root: str, deny_patterns: Optional[Iterable[str]]=None): + self.root=Path(project_root).resolve() + self.deny=tuple(deny_patterns or self.DEFAULT_DENY) + + def _safe(self, rel: str) -> bool: + x=rel.replace("\\","/").lower().lstrip("./") + return not any(p in x for p in self.deny) + + def _changed_paths(self, patch: str) -> list[str]: + out=[] + for line in patch.splitlines(): + if line.startswith("+++ b/"): + out.append(line[6:]) + return out + + def validate_patch(self, patch: str) -> tuple[bool,str,list[str]]: + paths=self._changed_paths(patch) + if not paths: return False,"patch has no changed files",[] + bad=[p for p in paths if not self._safe(p)] + if bad: return False,f"protected paths rejected: {bad}",paths + for p in paths: + target=(self.root/p).resolve() + if self.root not in target.parents and target != self.root: + return False,"path traversal rejected",paths + if target.exists() and target.is_file() and target.stat().st_size > 1_000_000: + return False,f"file too large: {p}",paths + return True,"ok",paths + + def test(self, patch: str, tests: Optional[list[str]]=None) -> PatchResult: + ok,reason,paths=self.validate_patch(patch) + if not ok: return PatchResult(False,reason,"",paths) + td=tempfile.mkdtemp(prefix="p29_patch_") + sandbox=Path(td)/"project" + shutil.copytree(self.root,sandbox,ignore=shutil.ignore_patterns(".git","__pycache__","*.pyc")) + patch_file=Path(td)/"change.patch" + patch_file.write_text(patch,encoding="utf-8") + p=subprocess.run(["patch","-p1","--batch","--forward","-i",str(patch_file)], + cwd=sandbox,capture_output=True,text=True) + if p.returncode!=0: + return PatchResult(False,"patch apply failed: "+(p.stderr or p.stdout)[-2000:],td,paths) + c=subprocess.run([sys.executable,"-m","compileall","-q",str(sandbox)], + capture_output=True,text=True) + if c.returncode!=0: + return PatchResult(False,"compile failed: "+c.stderr[-2000:],td,paths) + if tests: + t=subprocess.run([sys.executable,"-m","pytest",*tests,"-q"],cwd=sandbox, + capture_output=True,text=True) + if t.returncode!=0: + return PatchResult(False,"tests failed: "+(t.stdout+t.stderr)[-3000:],td,paths) + return PatchResult(True,"sandbox checks passed",td,paths) diff --git a/core/runtime/__init__.py b/core/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c333450fbf7349565432488cf05840c420312d0c --- /dev/null +++ b/core/runtime/__init__.py @@ -0,0 +1,3 @@ +from .integration import RuntimeIntegration, RuntimeResult + +__all__ = ["RuntimeIntegration", "RuntimeResult"] diff --git a/core/runtime/integration.py b/core/runtime/integration.py new file mode 100644 index 0000000000000000000000000000000000000000..a0aadf8d573793a1426505e83b7bddd672947340 --- /dev/null +++ b/core/runtime/integration.py @@ -0,0 +1,612 @@ +from __future__ import annotations + +import asyncio +import inspect +import time +from dataclasses import dataclass, field +from typing import Any, Callable, Optional + +from core.content_pipeline import ContentGate +from core.content.dedup import DedupStore +from core.infra.audit import AuditLog +from core.infra.metrics import Metrics +from core.jobs.queue import ProcessingQueue +from core.pipeline.adapter import SectionPipelineAdapter +from core.providers.pool import AIProviderPool +from core.ai.gateway import AIGateway +from core.publishing.ledger import PublishLedger +from core.publishing.publisher import IdempotentPublisher +from core.health.monitor import HealthMonitor +from core.repair.engine import AutoRepairEngine +from core.repair.policy import RepairGuard, RepairPolicy +from core.repair.guarded import GuardedRepair +from core.sections.base import SectionConfig +from core.sections.registry import SectionRegistry +from core.runtime.state_store import RuntimeStateStore +from core.control.plane import ControlPlane +from core.security.secret_registry import SecretRegistry +from core.security.hardening import SecurityHardener + + +@dataclass +class RuntimeResult: + status: str + stage: str + reason: str = "" + data: Any = None + fingerprint: str = "" + job_id: str = "" + + +@dataclass +class SectionRuntimeState: + enabled: bool = True + blocked_words: list[str] = field(default_factory=list) + duplicate_protection: bool = True + ai_enabled: bool = True + auto_repair_enabled: bool = True + sources: list[str] = field(default_factory=list) + + +class RuntimeIntegration: + """The phase-15 composition root. + + Every section uses the same ordered runtime: + gate -> normalization -> durable queue -> AI gateway -> validation -> + idempotent publisher -> health/audit/metrics. + + External Telegram/Blogger implementations are injected as adapters so the + core remains testable and future sections do not require core edits. + """ + + def __init__( + self, + db: Any = None, + *, + db_path: str = "data/p29_runtime.sqlite3", + project_root: str = ".", + blocked_words: Optional[list[str]] = None, + ai_gateway: Optional[AIGateway] = None, + queue: Optional[ProcessingQueue] = None, + publisher: Optional[IdempotentPublisher] = None, + health: Optional[HealthMonitor] = None, + metrics: Optional[Metrics] = None, + audit: Optional[AuditLog] = None, + auto_repair: Optional[GuardedRepair] = None, + repair_proposer: Optional[Callable[[str, dict], Optional[str]]] = None, + ): + self.db = db + self.db_path = db_path + self.state_store = RuntimeStateStore(db_path) + self.queue = queue or ProcessingQueue(db_path) + self.pool = ai_gateway.pool if ai_gateway else AIProviderPool() + self.ai = ai_gateway or AIGateway(self.pool) + self.ledger = publisher.ledger if publisher else PublishLedger(db_path) + self.publisher = publisher or IdempotentPublisher(self.ledger, {}) + self.health = health or HealthMonitor() + self.metrics = metrics or Metrics() + self.audit = audit or AuditLog("data/audit.jsonl") + self.secret_registry = SecretRegistry() + self.security = SecurityHardener(self.secret_registry) + self.security.refresh() + if auto_repair is None: + policy = RepairPolicy( + enabled=True, + auto_apply_low_risk=False, + require_admin_for_medium=True, + require_admin_for_high=True, + ) + engine = AutoRepairEngine(project_root) + guard = RepairGuard(policy) + auto_repair = GuardedRepair(engine, guard) + self.auto_repair = auto_repair + self.repair_proposer = repair_proposer + self.health.on_unhealthy = self._on_unhealthy + + self._gates: dict[str, ContentGate] = {} + self._sections: dict[str, SectionRuntimeState] = { + "blogger": SectionRuntimeState(), + "news": SectionRuntimeState(), + "sports": SectionRuntimeState(), + } + self._load_section_state() + self._publisher_adapters: dict[str, Callable] = {} + self._section_pipelines: dict[str, SectionPipelineAdapter] = {} + self._repair_enabled = bool(self.state_store.get("control:auto_repair", True)) + self.control_plane = ControlPlane(self) + self._register_health() + + def _load_section_state(self) -> None: + for section, default in list(self._sections.items()): + raw = self.state_store.get(f"section:{section}", {}) or {} + if not isinstance(raw, dict): + continue + for key in ("enabled", "blocked_words", "duplicate_protection", "ai_enabled", "auto_repair_enabled", "sources"): + if key in raw: + setattr(default, key, raw[key]) + + def _persist_section_state(self, section: str) -> None: + state = self._sections[section] + self.state_store.set(f"section:{section}", { + "enabled": bool(state.enabled), + "blocked_words": list(state.blocked_words), + "duplicate_protection": bool(state.duplicate_protection), + "ai_enabled": bool(state.ai_enabled), + "auto_repair_enabled": bool(state.auto_repair_enabled), + "sources": list(state.sources), + }) + + def _register_health(self) -> None: + for section in self._sections: + self.health.register( + f"section:{section}", + lambda section=section: self._section_health(section), + ) + for provider in self.pool.providers(): + self.health.register( + f"provider:{provider}", + lambda provider=provider: self._provider_health(provider), + ) + + def _section_health(self, section: str) -> dict: + state = self._sections[section] + return { + "enabled": state.enabled, + "queue": self.queue.store.get_stats(), + "ai_enabled": state.ai_enabled, + } + + def _provider_health(self, provider: str) -> dict: + snap = self.pool.snapshot().get(provider, []) + if not snap: + raise RuntimeError("no provider keys available") + available = [x for x in snap if x["cooldown"] <= 0] + if not available: + raise RuntimeError("all provider keys are in cooldown") + return {"keys": len(snap), "available_keys": len(available)} + + def register_ai_provider(self, provider: str, adapter: Callable) -> None: + self.ai.register(provider, adapter) + self.health.register( + f"provider:{provider.lower()}", + lambda provider=provider.lower(): self._provider_health(provider), + ) + + def register_publisher(self, target: str, adapter: Callable) -> None: + self._publisher_adapters[target] = adapter + self.publisher.adapters[target] = adapter + + def set_section_state(self, section: str, **changes) -> SectionRuntimeState: + state = self._sections.setdefault(section, SectionRuntimeState()) + for key, value in changes.items(): + if not hasattr(state, key): + raise KeyError(key) + setattr(state, key, value) + self._gates.pop(section, None) + self._section_pipelines.pop(section, None) + self._persist_section_state(section) + self._audit("section.state_changed", section=section, changes=changes) + return state + + def get_section_state(self, section: str) -> dict: + state = self._sections.setdefault(section, SectionRuntimeState()) + return { + "section": section, + "enabled": state.enabled, + "blocked_words": list(state.blocked_words), + "duplicate_protection": state.duplicate_protection, + "ai_enabled": state.ai_enabled, + "auto_repair_enabled": state.auto_repair_enabled, + "sources": list(state.sources), + } + + def _gate(self, section: str) -> ContentGate: + if section not in self._gates: + words = list(self._sections.setdefault(section, SectionRuntimeState()).blocked_words) + state = self._sections.setdefault(section, SectionRuntimeState()) + self._gates[section] = ContentGate( + _OverlayGateDB(self.db, words, section), + dedup=DedupStore(self.db_path) if state.duplicate_protection else None, + ) + return self._gates[section] + + def ingest( + self, + section: str, + article: str, + article_id: str, + *, + source: str = "", + source_url: str = "", + channel_id: str = "", + target: str = "", + metadata: Optional[dict] = None, + ) -> RuntimeResult: + state = self._sections.setdefault(section, SectionRuntimeState()) + if not state.enabled: + self.metrics.inc(f"{section}.rejected.disabled") + return RuntimeResult("rejected", "section", "section_disabled") + if state.sources and source and source not in state.sources: + self.metrics.inc(f"{section}.rejected.source") + self._audit("content.rejected", section=section, article_id=article_id, reason="source_not_allowed") + return RuntimeResult("rejected", "source", "source_not_allowed") + if state.sources and not source: + self.metrics.inc(f"{section}.rejected.source") + return RuntimeResult("rejected", "source", "source_required") + + gate = self._gate(section) + # Blocked words are evaluated before fingerprint/dedup and therefore before + # queue/AI/API usage. + verdict = gate.preflight(article, source_url, channel_id, source=source, article_id=article_id) + if not verdict.allowed: + self.metrics.inc(f"{section}.rejected.{verdict.reason}") + self._audit( + "content.rejected", + section=section, + article_id=article_id, + reason=verdict.reason, + matched=list(verdict.matched), + ) + return RuntimeResult( + "rejected", "gate", verdict.reason, + fingerprint=verdict.fingerprint, + ) + + cleaned = self._clean_for_queue(article, channel_id) + if not cleaned: + self.metrics.inc(f"{section}.rejected.empty_after_cleanup") + self._audit("content.rejected", section=section, article_id=article_id, reason="empty_after_cleanup") + return RuntimeResult("rejected", "cleanup", "empty_after_cleanup", fingerprint=verdict.fingerprint) + scoped_id = f"{section}:{article_id}" + payload = { + "section": section, + "article_id": scoped_id, + "source": source, + "source_url": source_url, + "channel_id": channel_id, + "target": target or section, + "article": cleaned, + "fingerprint": verdict.fingerprint, + "metadata": metadata or {}, + } + try: + job_id = self.queue.enqueue_article(scoped_id, payload) + except Exception: + # A failed queue write must not leave a permanently reserved dedup + # record in the persistent gate. + try: + gate.dedup.forget(verdict.fingerprint) + except Exception: + pass + self.metrics.inc(f"{section}.queue.error") + self._audit("queue.enqueue_failed", section=section, article_id=article_id) + raise + + self.metrics.inc(f"{section}.queued") + self._audit( + "content.queued", + section=section, + article_id=article_id, + fingerprint=verdict.fingerprint, + job_id=job_id, + ) + return RuntimeResult( + "queued", "queue", data=payload, + fingerprint=verdict.fingerprint, job_id=job_id, + ) + + def _clean_for_queue(self, text: str, channel_id: str = "") -> str: + """Apply deterministic removal terms only after the zero-AI gate.""" + terms = [] + if self.db is not None: + try: + terms.extend(self.db.get_global_remove_terms() or []) + except Exception: + pass + if channel_id: + try: + terms.extend(self.db.get_channel_delete_terms(channel_id) or []) + except Exception: + pass + for raw in terms: + term = str(raw or "").strip() + if term: + text = text.replace(term, "") + return text.strip() + + def process_payload(self, payload: dict) -> RuntimeResult: + section = payload["section"] + state = self._sections.setdefault(section, SectionRuntimeState()) + if not state.enabled: + return RuntimeResult("rejected", "section", "section_disabled") + + if not state.ai_enabled: + return RuntimeResult("rejected", "ai", "ai_disabled") + + text = payload["article"] + try: + response = self.ai.article_package( + text, + task=f"process_{section}_article", + ) + data = response.data + if not isinstance(data, dict): + raise RuntimeError("AI returned non-object article package") + self.metrics.inc(f"{section}.ai.success") + self.metrics.inc(f"provider.{response.provider}.success") + except Exception as exc: + self.metrics.inc(f"{section}.ai.failure") + self._audit("ai.failure", section=section, error=str(exc)) + raise + + # The same gate runs after AI so generated content cannot bypass safety. + gate = self._gate(section) + article = dict(data) + article["source_url"] = payload.get("source_url", "") + article["fingerprint"] = payload.get("fingerprint", "") + post = gate.postflight(article, payload.get("channel_id", "")) + if not post.allowed: + self.metrics.inc(f"{section}.rejected.postflight") + self._audit( + "content.postflight_rejected", + section=section, + reason=post.reason, + matched=list(post.matched), + ) + return RuntimeResult("rejected", "validation", post.reason, fingerprint=post.fingerprint) + + article["_runtime"] = { + "section": section, + "article_id": payload["article_id"], + "target": payload.get("target") or section, + "fingerprint": payload.get("fingerprint", ""), + } + self.metrics.inc(f"{section}.validated") + return RuntimeResult("validated", "validation", data=article, fingerprint=payload.get("fingerprint", "")) + + def publish_payload(self, payload: dict) -> RuntimeResult: + article = payload["article"] + meta = article.get("_runtime", {}) + target = payload.get("target") or meta.get("target") or payload.get("section") + article_id = meta.get("article_id") or payload.get("article_id") + content = self._article_content(article) + + try: + result = self.publisher.publish( + target, article_id, content, + article=article, + section=payload.get("section"), + ) + except Exception as exc: + self.metrics.inc(f"{payload.get('section','unknown')}.publish.failure") + self._audit("publish.failure", section=payload.get("section"), error=str(exc)) + raise + + self.metrics.inc(f"{payload.get('section','unknown')}.publish.{result.get('status','unknown')}") + self._audit( + "publish.result", + section=payload.get("section"), + article_id=article_id, + status=result.get("status"), + remote_id=result.get("remote_id"), + ) + return RuntimeResult(result.get("status", "unknown"), "publisher", data=result) + + @staticmethod + def _article_content(article: dict) -> str: + # Keep a stable representation for idempotency hashing while allowing + # adapters to consume the structured article through the `article=` kwarg. + for key in ("body", "article", "content", "text"): + if article.get(key): + return str(article[key]) + return str(article) + + def handle_job(self, payload: dict, job: Optional[dict] = None) -> RuntimeResult: + """Worker handler: queue -> AI -> validation -> publisher. + + The persistent queue's retry/failure policy handles worker crashes. Publish + idempotency is checked inside IdempotentPublisher before the remote call. + """ + processed = self.process_payload(payload) + if processed.status != "validated": + return processed + payload = dict(payload) + payload["article"] = processed.data + published = self.publish_payload(payload) + return published + + def build_concurrent_workers(self, workers: int = 2, worker_lease_timeout: float = 300): + """Build a bounded concurrent worker pool on the canonical persistent queue.""" + from core.jobs.concurrency import ConcurrentWorkers + return ConcurrentWorkers(self.queue.store, self.worker_handlers(), workers=workers, lease_timeout=worker_lease_timeout) + + def load_snapshot(self) -> dict: + """Safe operational load snapshot; no article payloads are exposed.""" + return { + "queue": self.queue.store.get_stats(), + "workers": {"supported": True, "max_concurrency": 32}, + "metrics": self.metrics.detailed_snapshot(), + } + + def build_worker(self, worker_id: Optional[str] = None): + from core.jobs.worker import JobWorker + return JobWorker(self.queue.store, self.worker_handlers(), worker_id=worker_id) + + def worker_handlers(self) -> dict[str, Callable]: + return {"article.process": self.handle_job} + + def build_section_adapter(self, section: str) -> SectionPipelineAdapter: + if section not in self._section_pipelines: + self._section_pipelines[section] = SectionPipelineAdapter( + section, + self._gate(section), + self.queue, + self.ai, + self.publisher, + ) + return self._section_pipelines[section] + + def health_snapshot(self) -> dict: + return self.health.snapshot() + + def metrics_snapshot(self) -> dict: + return self.metrics.snapshot() + + def control_snapshot(self) -> dict: + return { + "sections": {k: self.get_section_state(k) for k in self._sections}, + "health": self.health_snapshot(), + "metrics": self.metrics_snapshot(), + "metrics_detailed": self.metrics.detailed_snapshot(), + "providers": self.pool.snapshot(), + "queue": self.queue.store.get_stats(), + "alerts": self.control_plane.evaluate(), + "auto_repair": { + "enabled": self._repair_enabled, + "policy": self.auto_repair.guard.policy.__dict__, + }, + } + + def set_auto_repair(self, enabled: bool) -> dict: + self._repair_enabled = bool(enabled) + self.state_store.set("control:auto_repair", self._repair_enabled) + self._audit("repair.toggled", enabled=self._repair_enabled) + return {"ok": True, "enabled": self._repair_enabled} + + def operational_snapshot(self) -> dict: + return self.control_plane.snapshot() + + def recent_audit(self, limit: int = 50) -> list[dict]: + return self.audit.recent(limit) + + def acknowledge_alert(self, key: str, *, admin_approved=False) -> dict: + return self.control_plane.acknowledge(key, admin_approved=admin_approved) + + def queue_snapshot(self, status: str | None = None, limit: int = 50) -> list[dict]: + rows = self.queue.store.list_jobs(status=status, limit=limit) + # Keep control-plane output safe: do not expose arbitrary payload content. + return [{ + "id": row.get("id"), "kind": row.get("kind"), "status": row.get("status"), + "attempts": row.get("attempts"), "available_at": row.get("available_at"), + "claimed_at": row.get("claimed_at"), "worker_id": row.get("worker_id"), + "last_error": row.get("last_error", ""), + } for row in rows] + + def requeue_dead_job(self, job_id: str, *, admin_approved: bool = False) -> dict: + if not admin_approved: + return {"ok": False, "reason": "admin_required"} + ok = self.queue.store.requeue_dead(job_id) + self._audit("queue.dead_requeued", job_id=job_id, ok=ok) + return {"ok": ok, "job_id": job_id} + + def _on_unhealthy(self, name: str, service) -> None: + self.metrics.inc("health.unhealthy") + self._audit("health.unhealthy", service=name, failures=service.consecutive_failures) + if not self._repair_enabled or not self.repair_proposer: + return + if name.startswith("section:"): + section = name.split(":", 1)[1] + if not self._sections.get(section, SectionRuntimeState()).auto_repair_enabled: + return + try: + patch = self.repair_proposer(name, service.__dict__.copy()) + if not patch: + return + record = self.auto_repair.test_and_apply( + f"health:{name}", + patch, + tests=["tests/v29"], + admin_approved=False, + ) + self._audit( + "repair.result", + service=name, + repair_id=record.repair_id, + status=record.status, + reason=record.reason, + ) + except Exception as exc: + self._audit("repair.failure", service=name, error=str(exc)) + + def monitor_once(self) -> dict: + result = self.health.check_all() + for name, service in result.items(): + if service.status == "unhealthy": + self.metrics.inc("health.unhealthy") + return self.health_snapshot() + + def _audit(self, event: str, **data) -> None: + # AuditLog redacts string values. No raw key/token is intentionally passed. + self.audit.write(event, **data) + + +class _OverlayGateDB: + def __init__(self, legacy, words, section): + self.legacy = legacy + self.words = list(words) + self.section = section + + def get_blocked_words(self): + out = list(self.words) + if self.legacy is not None: + try: + out.extend(self.legacy.get_blocked_words() or []) + except Exception: + pass + return list(dict.fromkeys(out)) + + def get_channel_blocked_words(self, channel_id): + if self.legacy is not None: + try: + return self.legacy.get_channel_blocked_words(channel_id) or [] + except Exception: + pass + return [] + + def is_published(self, fp): + if self.legacy is not None: + try: + return bool(self.legacy.is_published(fp)) + except Exception: + pass + return False + + def get_article(self, fp): + if self.legacy is not None: + try: + return self.legacy.get_article(fp) + except Exception: + pass + return None + + def get_all_articles(self): + if self.legacy is not None: + try: + return self.legacy.get_all_articles() or [] + except Exception: + pass + return [] + + +class _MemoryGateDB: + """Minimal DB contract used by isolated runtime tests.""" + + def __init__(self, words): + self.words = list(words) + self.articles = {} + self.published = set() + + def get_blocked_words(self): + return self.words + + def get_channel_blocked_words(self, channel_id): + return [] + + def is_published(self, fp): + return fp in self.published + + def get_article(self, fp): + return self.articles.get(fp) + + def get_all_articles(self): + return list(self.articles.values()) diff --git a/core/runtime/legacy_bridge.py b/core/runtime/legacy_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..18b9725745c46d023aff1abf5c82b7735b315e7a --- /dev/null +++ b/core/runtime/legacy_bridge.py @@ -0,0 +1,50 @@ +"""Phase 18 legacy-runtime compatibility bridge. + +Keeps the public legacy Blogger interfaces intact while routing automatic +ingestion through the P29 runtime. The bridge is deliberately small: section +adapters own external APIs, while RuntimeIntegration owns gate/queue/AI/ +validation/idempotency/health. +""" +from __future__ import annotations + +import asyncio +import threading +from typing import Any, Optional + +from core.runtime.integration import RuntimeIntegration + + +class LegacyRuntimeBridge: + def __init__(self, runtime: RuntimeIntegration, section: str = "blogger"): + self.runtime = runtime + self.section = section + + def ingest(self, raw_text: str, article_id: str, *, source: str = "", source_url: str = "", + channel_id: str = "", target: str = "", metadata: Optional[dict] = None): + return self.runtime.ingest( + self.section, raw_text, article_id, + source=source, source_url=source_url, channel_id=channel_id, + target=target or self.section, metadata=metadata, + ) + + def worker(self, worker_id: Optional[str] = None): + return self.runtime.build_worker(worker_id=worker_id) + + @staticmethod + def call_async(awaitable): + """Run a legacy async adapter from a synchronous runtime worker safely.""" + try: + asyncio.get_running_loop() + except RuntimeError: + return asyncio.run(awaitable) + result, error = [], [] + def runner(): + try: + result.append(asyncio.run(awaitable)) + except BaseException as exc: + error.append(exc) + thread = threading.Thread(target=runner, daemon=True) + thread.start(); thread.join() + if error: + raise error[0] + return result[0] if result else None diff --git a/core/runtime/state_store.py b/core/runtime/state_store.py new file mode 100644 index 0000000000000000000000000000000000000000..6ddecd41957ab93c011d590718bc13f41c0a2367 --- /dev/null +++ b/core/runtime/state_store.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +import json +import sqlite3 +import time +from pathlib import Path +from threading import RLock + + +class RuntimeStateStore: + """Small durable store for section/control-plane state. + + It is intentionally additive and namespaced so legacy tables are untouched. + """ + def __init__(self, path: str): + self.path = Path(path) + self.path.parent.mkdir(parents=True, exist_ok=True) + self._lock = RLock() + self._init() + + def _conn(self): + c = sqlite3.connect(self.path, timeout=30, isolation_level=None) + c.row_factory = sqlite3.Row + c.execute("PRAGMA journal_mode=WAL") + c.execute("PRAGMA synchronous=FULL") + c.execute("PRAGMA busy_timeout=30000") + return c + + def _init(self): + with self._conn() as c: + c.execute("""CREATE TABLE IF NOT EXISTS p29_runtime_state( + namespace TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at REAL NOT NULL + )""") + c.execute("""CREATE TABLE IF NOT EXISTS p29_runtime_schema( + key TEXT PRIMARY KEY, value TEXT NOT NULL + )""") + c.execute("INSERT OR REPLACE INTO p29_runtime_schema(key,value) VALUES('version','1')") + + def get(self, namespace: str, default=None): + with self._conn() as c: + row = c.execute("SELECT value FROM p29_runtime_state WHERE namespace=?", (namespace,)).fetchone() + if not row: + return default + try: + return json.loads(row["value"]) + except Exception: + return default + + def set(self, namespace: str, value) -> None: + raw = json.dumps(value, ensure_ascii=False, sort_keys=True) + with self._lock, self._conn() as c: + c.execute( + "INSERT INTO p29_runtime_state(namespace,value,updated_at) VALUES(?,?,?) " + "ON CONFLICT(namespace) DO UPDATE SET value=excluded.value,updated_at=excluded.updated_at", + (namespace, raw, time.time()), + ) diff --git a/core/secrets/__init__.py b/core/secrets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..16c4ef5a330c99071f045284fb23ff1c5a937fc9 --- /dev/null +++ b/core/secrets/__init__.py @@ -0,0 +1,4 @@ +from .manager import SecretManager +from .compat import env_or_secret, env_names, LEGACY_SECRET_NAMES + +__all__ = ["SecretManager", "env_or_secret", "env_names", "LEGACY_SECRET_NAMES"] diff --git a/core/secrets/compat.py b/core/secrets/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..6948ada27a2889aec6349c4e9b3677b73fa12a3e --- /dev/null +++ b/core/secrets/compat.py @@ -0,0 +1,45 @@ +"""Backward-compatible secret resolver. + +Environment variable names are deliberately kept identical to the legacy P28/P29 +names. Environment values always win, so existing deployments keep working +without any changes. If an environment value is absent, an encrypted value in +SecretManager may be used when the master key is configured. +""" +import os +from typing import Optional + +# Canonical names used by the existing project. Do not rename these. +LEGACY_SECRET_NAMES = { + "API_ID", "API_HASH", "BOT_TOKEN", "SESSION_STRING", "ADMINS", "ADMIN_ID", + "MIDDLE_CHANNEL", + "GEMINI_KEY_1", "GEMINI_KEY_2", "GROQ_KEY_1", "OPENROUTER_KEY_1", + "BLOGGER_BLOG_ID", "BLOGGER_CLIENT_ID", "BLOGGER_CLIENT_SECRET", "BLOGGER_REFRESH_TOKEN", + "P29_SECRET_MASTER_KEY", +} + + +def env_or_secret(name: str, db_path: Optional[str] = None, default: Optional[str] = None) -> Optional[str]: + value = os.getenv(name) + if value is not None and value != "": + return value + if not db_path: + db_path = os.getenv("APP_DB_PATH", "data/app.sqlite3") + try: + from .manager import SecretManager + manager = SecretManager(db_path, allow_unconfigured=True) + return manager.get(name) or default + except Exception: + # Secrets must never prevent the legacy environment-only deployment from booting. + return default + + +def env_names(prefix: str): + """Return all configured names matching a legacy prefix, from env and secret store.""" + names = {k for k, v in os.environ.items() if k.startswith(prefix) and v} + try: + from .manager import SecretManager + manager = SecretManager(os.getenv("APP_DB_PATH", "data/app.sqlite3"), allow_unconfigured=True) + names.update(row[0] for row in manager.list_metadata() if row[0].startswith(prefix) and row[2]) + except Exception: + pass + return sorted(names) diff --git a/core/secrets/manager.py b/core/secrets/manager.py new file mode 100644 index 0000000000000000000000000000000000000000..6ffef5c80e816352e216b3d0facab20a3273d7e0 --- /dev/null +++ b/core/secrets/manager.py @@ -0,0 +1,44 @@ +"""Encrypted persistent secret store with additive master-key rotation.""" +import base64, json, os, sqlite3, threading +from datetime import datetime, timezone +try: + from cryptography.fernet import Fernet +except ImportError: # pragma: no cover + Fernet = None + +class SecretManager: + def __init__(self, db_path: str, allow_unconfigured: bool = False): + self.db_path = db_path; self._lock = threading.RLock() + key = os.getenv("P29_SECRET_MASTER_KEY") + if not key or Fernet is None: + if allow_unconfigured: self._fernet = None + else: raise RuntimeError("SecretManager requires P29_SECRET_MASTER_KEY and cryptography") + else: self._fernet = Fernet(key.encode() if isinstance(key, str) else key) + os.makedirs(os.path.dirname(os.path.abspath(db_path)), exist_ok=True) + with sqlite3.connect(db_path) as c: + c.execute("CREATE TABLE IF NOT EXISTS secrets(name TEXT PRIMARY KEY, kind TEXT NOT NULL, value BLOB NOT NULL, enabled INTEGER NOT NULL DEFAULT 1, meta TEXT NOT NULL DEFAULT '{}', updated_at TEXT NOT NULL)") + + def set(self, name, value, kind="generic", meta=None, enabled=True): + if self._fernet is None: raise RuntimeError("Secret store is not configured: set P29_SECRET_MASTER_KEY") + blob = self._fernet.encrypt(value.encode()); now = datetime.now(timezone.utc).isoformat() + with self._lock, sqlite3.connect(self.db_path) as c: + c.execute("INSERT INTO secrets(name,kind,value,enabled,meta,updated_at) VALUES(?,?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET kind=excluded.kind,value=excluded.value,enabled=excluded.enabled,meta=excluded.meta,updated_at=excluded.updated_at", (name,kind,blob,int(enabled),json.dumps(meta or {}),now)) + + def get(self, name): + with sqlite3.connect(self.db_path) as c: row=c.execute("SELECT value,enabled FROM secrets WHERE name=?",(name,)).fetchone() + if not row or not row[1] or self._fernet is None:return None + return self._fernet.decrypt(row[0]).decode() + + def list_metadata(self): + with sqlite3.connect(self.db_path) as c:return c.execute("SELECT name,kind,enabled,meta,updated_at FROM secrets ORDER BY name").fetchall() + + def rotate_master_key(self, new_key: str): + if self._fernet is None: raise RuntimeError("secret store is not configured") + new_fernet = Fernet(new_key.encode() if isinstance(new_key,str) else new_key) + with self._lock, sqlite3.connect(self.db_path) as c: + rows=c.execute("SELECT name,value FROM secrets").fetchall() + decrypted=[(name,self._fernet.decrypt(blob)) for name,blob in rows] + for name,plain in decrypted: + c.execute("UPDATE secrets SET value=?,updated_at=? WHERE name=?",(new_fernet.encrypt(plain),datetime.now(timezone.utc).isoformat(),name)) + self._fernet = new_fernet + return len(decrypted) diff --git a/core/sections/__init__.py b/core/sections/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8184defd1375a8459b25cbe93fd6f21e62171ab3 --- /dev/null +++ b/core/sections/__init__.py @@ -0,0 +1,4 @@ +from .base import SectionAdapter, SectionConfig, NEWS, SPORTS +from .registry import SectionRegistry, BLOGGER +from .controls import build_section_buttons +__all__=['SectionAdapter','SectionConfig','NEWS','SPORTS','BLOGGER','SectionRegistry','build_section_buttons'] diff --git a/core/sections/base.py b/core/sections/base.py new file mode 100644 index 0000000000000000000000000000000000000000..278a6e2c0bffc159de5a1e59fc3d5cb6467a0ecb --- /dev/null +++ b/core/sections/base.py @@ -0,0 +1,52 @@ +from __future__ import annotations +from dataclasses import dataclass, field +from typing import Any, Callable + +@dataclass(frozen=True) +class SectionConfig: + key: str + title: str + source: str + content_type: str + settings_namespace: str + callbacks_namespace: str + enabled: bool = True + options: dict[str, Any] = field(default_factory=dict) + +class SectionAdapter: + """Common contract; each section has isolated configuration/state but shared infrastructure.""" + def __init__(self, config: SectionConfig, pipeline, publisher=None): + self.config=config + self.pipeline=pipeline + self.publisher=publisher + + def ingest(self, article: str, article_id: str, target=None): + return self.pipeline.ingest( + article=article, + article_id=f"{self.config.key}:{article_id}", + source=self.config.source, + target=target, + ) + + def process(self, payload: dict): + return self.pipeline.process(payload) + + def status(self): + return {"section":self.config.key,"enabled":self.config.enabled,"options":dict(self.config.options)} + + def set_option(self, name: str, value: Any): + opts=dict(self.config.options) + opts[name]=value + object.__setattr__(self.config,"options",opts) + +# News and Sports are deliberately separate sections, while sharing the same capabilities. +NEWS = SectionConfig( + key="news", title="📰 الأخبار", source="news", + content_type="news", settings_namespace="news", + callbacks_namespace="news", options={} +) +SPORTS = SectionConfig( + key="sports", title="⚽ الرياضة", source="sports", + content_type="sports", settings_namespace="sports", + callbacks_namespace="sports", options={} +) diff --git a/core/sections/controls.py b/core/sections/controls.py new file mode 100644 index 0000000000000000000000000000000000000000..f44a90540f1b67cd928634afd9d49b229c523db2 --- /dev/null +++ b/core/sections/controls.py @@ -0,0 +1,30 @@ +from __future__ import annotations +from dataclasses import dataclass + +@dataclass(frozen=True) +class SectionButton: + key: str + label: str + callback: str + +COMMON_SECTION_BUTTONS = ( + SectionButton("settings", "⚙️ الإعدادات", "{section}:settings"), + SectionButton("sources", "📡 المصادر", "{section}:sources"), + SectionButton("blocked", "🚫 الكلمات المحظورة", "{section}:blocked"), + SectionButton("duplicates", "♻️ منع التكرار", "{section}:duplicates"), + SectionButton("ai", "🤖 إعدادات الذكاء الاصطناعي", "{section}:ai"), + SectionButton("queue", "📋 الطابور", "{section}:queue"), + SectionButton("metrics", "📈 الإحصائيات", "{section}:metrics"), + SectionButton("health", "🩺 الصحة", "{section}:health"), + SectionButton("dead", "☠️ المهام الفاشلة", "{section}:dead"), + SectionButton("status", "📊 الحالة", "{section}:status"), + SectionButton("enable", "▶️ تشغيل القسم", "{section}:enable"), + SectionButton("disable", "⛔ إيقاف القسم", "{section}:disable"), + SectionButton("repair", "🛠️ الإصلاح التلقائي", "{section}:repair"), +) + +def build_section_buttons(section: str): + return tuple( + SectionButton(x.key, x.label, x.callback.format(section=section)) + for x in COMMON_SECTION_BUTTONS + ) diff --git a/core/sections/registry.py b/core/sections/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d925c290758c55f15602fac7dbc7cb267b1410 --- /dev/null +++ b/core/sections/registry.py @@ -0,0 +1,25 @@ +from __future__ import annotations +from .base import SectionAdapter, NEWS, SPORTS, SectionConfig + +BLOGGER = SectionConfig( + key="blogger", title="🌐 Blogger", source="blogger", + content_type="blogger", settings_namespace="blogger", + callbacks_namespace="blogger", options={} +) + +class SectionRegistry: + def __init__(self, pipeline, publisher=None, include_blogger=False): + self.sections={ + "news": SectionAdapter(NEWS,pipeline,publisher), + "sports": SectionAdapter(SPORTS,pipeline,publisher), + } + if include_blogger: + self.sections["blogger"]=SectionAdapter(BLOGGER,pipeline,publisher) + + def get(self,key): return self.sections[key] + def keys(self): return tuple(self.sections) + def statuses(self): return {k:v.status() for k,v in self.sections.items()} + def register(self, adapter: SectionAdapter): + if adapter.config.key in self.sections: + raise ValueError(f"section already exists: {adapter.config.key}") + self.sections[adapter.config.key]=adapter diff --git a/core/security/__init__.py b/core/security/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d88f75805becb8106d96f3f09f86f5eb9b4277b0 --- /dev/null +++ b/core/security/__init__.py @@ -0,0 +1,6 @@ +from .redaction import redact +from .secret_registry import SecretRegistry +from .hardening import SecurityHardener, SecurityFinding +from .access import AccessController, AccessDecision + +__all__ = ["redact", "SecretRegistry", "SecurityHardener", "SecurityFinding", "AccessController", "AccessDecision"] diff --git a/core/security/access.py b/core/security/access.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b11ca7f9de778b8271e7dbc525621228b26776 --- /dev/null +++ b/core/security/access.py @@ -0,0 +1,34 @@ +from __future__ import annotations +from dataclasses import dataclass + +@dataclass(frozen=True) +class AccessDecision: + allowed: bool + reason: str + role: str = "none" + +class AccessController: + """Small RBAC layer for sensitive control-plane operations.""" + def __init__(self, admin_check=None): + self.admin_check = admin_check or (lambda _uid: False) + self._roles: dict[str, set[str]] = {} + + def set_role(self, user_id, role: str): + self._roles[str(user_id)] = {role} + + def role(self, user_id) -> str: + uid = str(user_id) + if self.admin_check(user_id): + return "admin" + roles = self._roles.get(uid, set()) + return next(iter(roles), "none") + + def authorize(self, user_id, action: str) -> AccessDecision: + role = self.role(user_id) + if action in {"view_metrics", "view_health", "view_queue"} and role in {"admin", "operator", "viewer"}: + return AccessDecision(True, "allowed", role) + if action in {"retry_dead_letter", "ack_alert"} and role in {"admin", "operator"}: + return AccessDecision(True, "allowed", role) + if action in {"repair", "rollback", "rotate_secrets", "change_security"} and role == "admin": + return AccessDecision(True, "allowed", role) + return AccessDecision(False, "admin_required" if action in {"repair", "rollback", "rotate_secrets", "change_security"} else "forbidden", role) diff --git a/core/security/hardening.py b/core/security/hardening.py new file mode 100644 index 0000000000000000000000000000000000000000..80d8e2e8bdf0929ac80a2cc142b6d9d135769d68 --- /dev/null +++ b/core/security/hardening.py @@ -0,0 +1,62 @@ +from __future__ import annotations +import hashlib, os, re, time +from dataclasses import dataclass +from typing import Iterable + +@dataclass(frozen=True) +class SecurityFinding: + code: str + severity: str + detail: str + +class SecurityHardener: + """Runtime security guardrails; additive and backwards compatible.""" + def __init__(self, secret_registry=None): + self.registry = secret_registry + self._values: set[str] = set() + self._rotation_epoch = 0 + self._last_rotation = 0.0 + + def refresh(self) -> int: + if not self.registry: + return 0 + count = 0 + for name in self.registry.discover(): + value = os.environ.get(name, "") + if value: + self._values.add(value) + count += 1 + return count + + def register_secret_value(self, value: str | None): + if value and len(value) >= 4: + self._values.add(value) + + def redact(self, text: object) -> str: + out = str(text) + for value in sorted(self._values, key=len, reverse=True): + if value: + out = out.replace(value, "
{text}
"), + "introduction": result.get("introduction", ""), + "faq": result.get("faq", []), + "conclusion": result.get("conclusion", ""), + "gemini_used": True, + } + + async def _extract(self, text: str) -> Optional[Dict]: + prompt = make_extract_prompt(text) + return await self.gemini.generate_json(prompt, SYSTEM_EXTRACT) + + async def _seo(self, title: str, body: str) -> Optional[Dict]: + prompt = make_seo_prompt(title, body) + return await self.gemini.generate_json(prompt, SYSTEM_SEO) + + async def _hashtags(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]: + prompt = make_hashtag_prompt(extracted, title, body) + result = await self.gemini.generate_json(prompt, SYSTEM_HASHTAGS) + if result and isinstance(result, dict): + tags = result.get("hashtags", []) + if isinstance(tags, list): + logger.info(f"Hashtags Generated: {tags}") + return tags + logger.warning(f"Hashtags Generated but 'hashtags' key is not list: {type(tags)}") + else: + logger.warning(f"Hashtags Generated: AI returned invalid data: {result}") + return [] + + async def _alt_text(self, title: str, body: str) -> Optional[Dict]: + prompt = f"""أنشئ وصف ALT وتعليق للصورة بناءً على: +العنوان: {title} +المحتوى: {body[:500]} +الرد JSON فقط: {{"alt": "...", "caption": "..."}}""" + return await self.gemini.generate_json(prompt, SYSTEM_ALT_IMAGE) + + # Legacy — labels now come from section settings in scheduler + def _make_labels(self, extracted: Dict, seo: Dict) -> List[str]: + labels = set() + if extracted.get("type"): + labels.add(extracted["type"]) + if extracted.get("ministry"): + labels.add(extracted["ministry"]) + if extracted.get("province"): + labels.add(extracted["province"]) + if extracted.get("city"): + labels.add(extracted["city"]) + if extracted.get("company"): + labels.add(extracted["company"]) + seo_labels = seo.get("labels", []) + if isinstance(seo_labels, list): + for lbl in seo_labels: + if lbl: + labels.add(str(lbl)) + return list(labels)[:10] + + async def _summary(self, text: str) -> Optional[str]: + prompt = make_summary_prompt(text) + result = await self.gemini.generate_json(prompt, SYSTEM_SUMMARY) + if result and isinstance(result, dict): + return result.get("summary", "") + return None + + async def _notes(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]: + prompt = make_notes_prompt(extracted, title, body) + result = await self.gemini.generate_json(prompt, SYSTEM_NOTES) + if result and isinstance(result, dict): + notes = result.get("notes", []) + if isinstance(notes, list) and notes: + return notes + return None + + async def _keywords(self, title: str, body: str, extracted: Dict) -> Optional[str]: + prompt = make_keywords_prompt(title, body, extracted) + result = await self.gemini.generate_json(prompt, SYSTEM_KEYWORDS) + if result and isinstance(result, dict): + kw = result.get("keywords", "") + if kw and isinstance(kw, str): + return kw + return None + + async def _metadata(self, extracted: Dict, title: str, body: str) -> Optional[Dict]: + prompt = make_metadata_prompt(extracted, title, body) + result = await self.gemini.generate_json(prompt, SYSTEM_METADATA) + if result and isinstance(result, dict): + return result + return None + + @staticmethod + def _reading_time(body_html: str) -> int: + text = re.sub(r'<[^>]+>', '', body_html) + word_count = len(text.split()) + minutes = max(1, round(word_count / 150)) + return minutes + + def _add_inline_hashtags(self, body: str, extracted: Dict) -> str: + entities = [] + if extracted.get("city"): + entities.append(extracted["city"]) + if extracted.get("province"): + entities.append(extracted["province"]) + if extracted.get("ministry"): + entities.append(extracted["ministry"]) + if extracted.get("company"): + entities.append(extracted["company"]) + if extracted.get("university"): + entities.append(extracted["university"]) + if extracted.get("organization"): + entities.append(extracted["organization"]) + if extracted.get("job_type"): + entities.append(extracted["job_type"]) + if extracted.get("district"): + entities.append(extracted["district"]) + result = body + for entity in entities: + if entity and len(entity) > 2: + tag = entity.replace(" ", "_") + replacement = f'#{tag}' + result = result.replace(entity, replacement, 1) + return result + + def _article_css(self) -> str: + return """""" + + def make_article_html(self, article: Dict) -> str: + parts = [] + parts.append(self._article_css()) + + # ── 0. Article Title ── + title = article.get("title", "").strip() + if title: + parts.append(f'{intro}