import logging import os import re import asyncio from datetime import datetime, timezone from typing import List, Optional from uuid import UUID from pydantic import BaseModel from contextlib import asynccontextmanager from fastapi import FastAPI, Depends, HTTPException, Query, UploadFile, File from fastapi.middleware.cors import CORSMiddleware import shutil import uuid from datetime import timedelta from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, desc from sqlalchemy.orm import selectinload from app.config import settings from app.database import init_db, get_db from app.models import Channel, RawPost, ContentDraft, FeedbackLog, PublishQueue from app.banner_generator import ( create_gemini_banner, create_vpn_banner, get_gemini_banner_from_pool_or_generate, get_vpn_banner_from_pool_or_generate, GEMINI_POOL_DIR, VPN_POOL_DIR ) from app.schemas import ( ChannelCreate, ChannelOut, ContentDraftOut, DraftActionRequest, FeedbackLogOut, PublishQueueOut, PipelineRunResponse ) from app.agents.agent_a_scraper import seed_default_channels, run_channel_ingestion from app.agents.agent_b_curator import generate_draft_for_post, record_human_feedback from app.agents.agent_c_publisher import dispatch_pending_queue, dispatch_single_queue_item, send_to_telegram from app.gemini_content_engine import ( generate_random_gemini_post, GEMINI_ANGLES, get_campaign_deadline_text ) logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s") logger = logging.getLogger("main_api") async def periodic_queue_worker(): """Background worker checking publish queue every 60 seconds and auto-dispatching due posts.""" logger.info("Starting background Telegram auto-dispatch worker...") while True: try: async for session in get_db(): dispatched = await dispatch_pending_queue(session) if dispatched > 0: logger.info(f"Auto-dispatch worker successfully published {dispatched} scheduled post(s) to Telegram.") break except Exception as e: logger.error(f"Error in periodic_queue_worker: {e}") await asyncio.sleep(60) async def periodic_scrape_worker(): """Background worker periodically scraping active Telegram channels.""" interval = max(1, getattr(settings, "SCRAPE_INTERVAL_HOURS", 4)) * 3600 logger.info(f"Starting background channel scraper worker (interval: {interval}s)...") while True: try: await asyncio.sleep(interval) logger.info("Executing scheduled channel scraping cycle...") async for session in get_db(): channels = (await session.execute(select(Channel).where(Channel.is_active == True))).scalars().all() for ch in channels: try: await run_channel_ingestion(session, ch, limit=10) except Exception as e: logger.error(f"Error scraping channel {ch.telegram_handle}: {e}") break except asyncio.CancelledError: break except Exception as e: logger.error(f"Error in periodic_scrape_worker: {e}") @asynccontextmanager async def lifespan(app: FastAPI): logger.info("Initializing database and seeding default channels...") await init_db() async for session in get_db(): await seed_default_channels(session) break # Start periodic publisher task and scraper worker in background worker_task = asyncio.create_task(periodic_queue_worker()) scraper_task = asyncio.create_task(periodic_scrape_worker()) yield logger.info("Cancelling background tasks...") worker_task.cancel() scraper_task.cancel() try: await worker_task except asyncio.CancelledError: pass try: await scraper_task except asyncio.CancelledError: pass logger.info("Shutting down pipeline service.") app = FastAPI( title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json", lifespan=lifespan ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # --- CHANNELS ENDPOINTS --- @app.get("/api/v1/channels", response_model=List[ChannelOut]) async def list_channels(db: AsyncSession = Depends(get_db)): stmt = select(Channel).order_by(Channel.niche, Channel.telegram_handle) result = await db.execute(stmt) return result.scalars().all() @app.post("/api/v1/channels", response_model=ChannelOut) async def create_channel(channel_in: ChannelCreate, db: AsyncSession = Depends(get_db)): clean_handle = channel_in.telegram_handle.replace("@", "").strip() stmt = select(Channel).where(Channel.telegram_handle == clean_handle) existing = (await db.execute(stmt)).scalar_one_or_none() if existing: raise HTTPException(status_code=400, detail="Channel handle already registered") new_ch = Channel( telegram_handle=clean_handle, title=channel_in.title or clean_handle, niche=channel_in.niche, subscriber_count=channel_in.subscriber_count or 0, is_active=channel_in.is_active ) db.add(new_ch) await db.commit() await db.refresh(new_ch) return new_ch # --- PIPELINE TRIGGER ENDPOINTS --- @app.api_route("/api/v1/pipeline/run-now", methods=["GET", "POST"], response_model=PipelineRunResponse) @app.post("/api/v1/pipeline/scrape-and-curate", response_model=PipelineRunResponse) async def run_full_pipeline(limit_posts: int = 10, db: AsyncSession = Depends(get_db)): channels = (await db.execute(select(Channel).where(Channel.is_active == True))).scalars().all() new_posts_total = 0 drafts_created_total = 0 errors = [] for ch in channels: try: new_p = await run_channel_ingestion(db, ch, limit=limit_posts) new_posts_total += new_p except Exception as e: errors.append(f"Scrape channel {ch.telegram_handle}: {str(e)}") # Curate un-drafted raw posts (prioritize newest posts with configs and high engagement) stmt_unprocessed = ( select(RawPost) .outerjoin(ContentDraft, RawPost.id == ContentDraft.raw_post_id) .where(ContentDraft.id == None) .order_by(desc(RawPost.posted_at), desc(RawPost.views)) .limit(40) ) unprocessed_posts = (await db.execute(stmt_unprocessed)).scalars().all() for p in unprocessed_posts: try: await generate_draft_for_post(db, p) drafts_created_total += 1 except Exception as e: errors.append(f"Curate post {p.id}: {str(e)}") return PipelineRunResponse( scraped_channels=len(channels), new_posts=new_posts_total, drafts_generated=drafts_created_total, errors=errors ) # --- DRAFTS & REVIEW ENDPOINTS --- @app.post("/api/v1/raw-posts/{post_id}/create-draft", response_model=ContentDraftOut) async def create_draft_for_single_post(post_id: str, db: AsyncSession = Depends(get_db)): stmt = select(RawPost).where(RawPost.id == post_id) post = (await db.execute(stmt)).scalar_one_or_none() if not post: raise HTTPException(status_code=404, detail="Post not found") draft = await generate_draft_for_post(db, post) stmt_draft = ( select(ContentDraft) .options(selectinload(ContentDraft.raw_post).selectinload(RawPost.channel)) .where(ContentDraft.id == draft.id) ) loaded_draft = (await db.execute(stmt_draft)).scalar_one() return loaded_draft @app.get("/api/v1/gemini/angles") async def get_gemini_angles_list(): """Return available marketing personas/angles for Gemini Pro.""" return [ {"id": a["id"], "name": a["name"], "banner_type": a["banner_type"]} for a in GEMINI_ANGLES ] @app.post("/api/v1/drafts/create-gemini-promo", response_model=ContentDraftOut) async def create_gemini_promo_draft( price_toman: str = Query("۶۰۰.۰۰۰ تومان"), is_flash_sale: bool = Query(True), angle_id: Optional[str] = Query(None), hours_remaining: int = Query(48), db: AsyncSession = Depends(get_db) ): """Generate an instant Gemini Pro promo draft with strictly selected user pool banners, rich copywriting angles, and precise countdown deadlines.""" promo_text, banner_type, angle_name = generate_random_gemini_post( angle_id=angle_id, hours_remaining=hours_remaining ) banner_url = get_gemini_banner_from_pool_or_generate( headline=f"پروموشن {angle_name}", price_toman=price_toman, is_discount=is_flash_sale, banner_type=banner_type ) stmt_post = select(RawPost).limit(1) sample_post = (await db.execute(stmt_post)).scalar_one_or_none() if not sample_post: stmt_ch = select(Channel).limit(1) ch = (await db.execute(stmt_ch)).scalar_one_or_none() if not ch: ch = Channel(name="NetVibe Seed", handle="NetVibe_VPN", is_active=True) db.add(ch) await db.flush() sample_post = RawPost( channel_id=ch.id, message_id=999999, original_text=promo_text, post_url="https://t.me/NetVibe_VPN", media_type="photo", views=1000, reactions=50, posted_at=datetime.now(timezone.utc) ) db.add(sample_post) await db.flush() draft = ContentDraft( raw_post_id=sample_post.id, ai_generated_text=promo_text, current_text=promo_text, banner_image_url=banner_url, status="pending" ) db.add(draft) await db.commit() stmt_load = ( select(ContentDraft) .options(selectinload(ContentDraft.raw_post).selectinload(RawPost.channel)) .where(ContentDraft.id == draft.id) ) loaded_draft = (await db.execute(stmt_load)).scalar_one() return loaded_draft @app.post("/api/v1/drafts/create-budget-vpn-promo", response_model=ContentDraftOut) async def create_budget_vpn_promo_draft(db: AsyncSession = Depends(get_db)): """Generate an instant Budget Marketing Package draft (100GB / 3 Months for 200,000 Tomans).""" banner_url = get_vpn_banner_from_pool_or_generate( title="بسته ویژه ۳ ماهه اقتصادی NetVibe", card1_title="بسته ۱۰۰ گیگ ۳ ماهه", card2_title="قیمت ویژه: ۲۰۰.۰۰۰ تومان", brand=settings.TARGET_CHANNEL ) promo_text = ( "🔥 جشنواره اقتصادی NetVibe: بسته ویژه ۳ ماهه با تخفیف طلایی\n\n" "اگر مصرف ماهانه‌ات خیلی سنگین نیست ولی دنبال یک اینترنت پایدار و بی‌دردسر برای چند ماه هستی:\n\n" "📦 بسته ۱۰۰ گیگابایت ۳ ماهه\n" "💰 قیمت استثنایی: فقط ۲۰۰.۰۰۰ تومان! (روزی کمتر از ۲.۵۰۰ تومان)\n\n" "▫️ اعتبار زمانی: ۹۰ روز کامل\n" "▫️ ساب‌لینک هوشمند با قابلیت اتصال خودکار به خلوت‌ترین سرور\n" "▫️ آی‌پی تمیز و باکیفیت مناسب ترید، صرافی و امور بانکی\n" "▫️ بدون محدودیت در تعداد دستگاه همزمان\n" "▫️ سازگار با تمام اپراتورها (همراه اول، ایرانسل، رایتل و مخابرات)\n\n" "⚡️ ظرفیت جشنواره محدود است. جهت خرید و دریافت تست:\n" "✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n" "🌐 کانال رسمی: https://t.me/NetVibe_VPN" ) stmt_post = select(RawPost).limit(1) sample_post = (await db.execute(stmt_post)).scalar_one_or_none() draft = ContentDraft( raw_post_id=sample_post.id if sample_post else None, ai_generated_text=promo_text, current_text=promo_text, banner_image_url=banner_url, status="pending" ) db.add(draft) await db.commit() stmt_load = ( select(ContentDraft) .options(selectinload(ContentDraft.raw_post).selectinload(RawPost.channel)) .where(ContentDraft.id == draft.id) ) return (await db.execute(stmt_load)).scalar_one() @app.post("/api/v1/drafts/create-unlimited-vpn-promo", response_model=ContentDraftOut) async def create_unlimited_vpn_promo_draft(db: AsyncSession = Depends(get_db)): """Generate an instant Unlimited VPN Promo draft (2-User 300k & 3-User 350k).""" banner_url = get_vpn_banner_from_pool_or_generate( title="اتصال پرسرعت، پایدار و بدون قطعی", card1_title="پلن ۲ کاربره نامحدود", card2_title="پلن ۳ کاربره نامحدود", brand=settings.TARGET_CHANNEL ) promo_text = ( "➕ اگر هنوز درگیر قطعی وصلی هستی و دنبال اتصال پایداری ؛ میتونی روی ما حساب کنی !\n\n" "✔️ یک اشتراک ثابت و پرسرعت\n" "✔️ پشتیبانی قدرتمند ۲۴ ساعته\n\n" "🛑 بسته‌های جدید بدون محدودیت حجم (نامحدود) 🛑\n" "فعال روی: تمامی سایت‌ها و اپلیکیشن‌ها (اینستاگرام، یوتیوب، تلگرام)\n" "بدون نگرانی بابت تمام شدن حجم! ♾️\n\n" "👤 ۲ کاربره: ۳۰۰.۰۰۰ تومان\n" "👥 ۳ کاربره: ۳۵۰.۰۰۰ تومان\n\n" "✅ مدت زمان استفاده: ۱ ماه\n" "✅ محدودیت حجم: ندارد (نامحدود واقعی)\n" "✅ ساب‌لینک اختصاصی و هوشمند: دارد\n" "✅ اتصال پایدار با همه اینترنت‌ها (همراه اول، ایرانسل، رایتل و مخابرات)\n\n" "✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n" "🌐 کانال رسمی: https://t.me/NetVibe_VPN" ) stmt_post = select(RawPost).limit(1) sample_post = (await db.execute(stmt_post)).scalar_one_or_none() draft = ContentDraft( raw_post_id=sample_post.id if sample_post else None, ai_generated_text=promo_text, current_text=promo_text, banner_image_url=banner_url, status="pending" ) db.add(draft) await db.commit() stmt_load = ( select(ContentDraft) .options(selectinload(ContentDraft.raw_post).selectinload(RawPost.channel)) .where(ContentDraft.id == draft.id) ) return (await db.execute(stmt_load)).scalar_one() @app.post("/api/v1/drafts/generate-marketing-batch") async def generate_marketing_batch(db: AsyncSession = Depends(get_db)): """Generate a batch of diverse creative marketing drafts across different angles and hooks.""" stmt_post = select(RawPost).limit(1) sample_post = (await db.execute(stmt_post)).scalar_one_or_none() marketing_promos = [ # Angle 1: Connection Agitation & Reality ( "➕ اگر هنوز درگیر قطعی وصلی هستی و دنبال اتصال پایداری ؛ میتونی روی ما حساب کنی !\n\n" "✔️ یک اشتراک ثابت و پرسرعت\n" "✔️ پشتیبانی قدرتمند ۲۴ ساعته\n\n" "🛑 بسته‌های جدید بدون محدودیت حجم (نامحدود) 🛑\n" "فعال روی: تمامی سایت‌ها و اپلیکیشن‌ها (اینستاگرام، یوتیوب، تلگرام)\n" "بدون نگرانی بابت تمام شدن حجم! ♾️\n\n" "👤 ۲ کاربره: ۳۰۰.۰۰۰ تومان\n" "👥 ۳ کاربره: ۳۵۰.۰۰۰ تومان\n\n" "✅ مدت زمان استفاده: ۱ ماه\n" "✅ محدودیت حجم: ندارد (نامحدود واقعی)\n" "✅ ساب‌لینک اختصاصی و هوشمند: دارد\n" "✅ اتصال پایدار با همه اینترنت‌ها (همراه اول، ایرانسل، رایتل و مخابرات)\n\n" "✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n" "🌐 کانال رسمی: https://t.me/NetVibe_VPN", get_vpn_banner_from_pool_or_generate( title="اتصال پایدار، بدون قطعی و نامحدود", card1_title="پلن ۲ کاربره نامحدود", card2_title="پلن ۳ کاربره نامحدود", brand=settings.TARGET_CHANNEL ) ), # Angle 2: Programmers & Coders Gemini Pro Angle ( generate_random_gemini_post(angle_id="programmers_coders")[0], get_gemini_banner_from_pool_or_generate(banner_type="discount_600k") ), # Angle 2.1: Researchers & Students Gemini Pro Angle ( generate_random_gemini_post(angle_id="researchers_students")[0], get_gemini_banner_from_pool_or_generate(banner_type="discount_600k") ), # Angle 2.2: 6-Gmail Multi-Account Team Package ( generate_random_gemini_post(angle_id="team_6gmails_agency")[0], get_gemini_banner_from_pool_or_generate(banner_type="multi_tier_6gmail") ), # Angle 2.3: Content Creators & Social Media ( generate_random_gemini_post(angle_id="content_creators_marketers")[0], get_gemini_banner_from_pool_or_generate(banner_type="discount_600k") ), # Angle 2.4: Economy 100GB 3-Month Plan (Budget Marketing) ( "🔥 بسته اقتصادی و بهینه ۱۰۰ گیگ ۳ ماهه NetVibe\n\n" "دنبال یک اشتراک طولانی‌مدت و باصرفه هستی که هر ماه نگران تمدید نباشی؟\n\n" "▫️ ترافیک: ۱۰۰ گیگابایت خالص\n" "▫️ مدت زمان اعتبار: ۳ ماه کامل\n" "▫️ اتصال آنی و پرسرعت روی تمام اپراتورها\n" "▫️ بدون افت سرعت در ساعات شلوغی\n\n" "💰 قیمت استثنایی: فقط ۲۰۰.۰۰۰ تومان!\n\n" "✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n" "🌐 کانال رسمی: https://t.me/NetVibe_VPN", get_vpn_banner_from_pool_or_generate( title="بسته بهینه ۱۰۰ گیگ ۳ ماهه", card1_title="قیمت اقتصادی ۲۰۰.۰۰۰ تومان", card2_title="اعتبار طولانی ۳ ماهه", brand=settings.TARGET_CHANNEL ) ), # Angle 3: Low Ping & Trader Dedicated IP Angle ( "⚡️ پینگ پایین و آی‌پی ثابت تمیز برای ترید و کارهای حساس\n\n" "بزرگترین دغدغه تریدرها، گیمرها و فریلنسرها پرش ناگهانی آی‌پی و مسدود شدن حساب‌هاست.\n" "در NetVibe ترافیک شما از تونل‌های اختصاصی و سرورهای خلوت عبور داده می‌شود تا بالاترین ثبات را تجربه کنید.\n\n" "▫️ پینگ پایدار زیر ۷۰ میلی‌ثانیه\n" "▫️ عدم تداخل لوکیشن و مناسب بایننس، تریدینگ‌ویو و صرافی‌ها\n" "▫️ تضمین تعویض سرور در صورت بروز اختلال زیرساختی\n\n" "تعرفه‌های ماهانه نامحدود:\n" "👤 ۲ کاربره: ۳۰۰.۰۰۰ تومان\n" "👥 ۳ کاربره: ۳۵۰.۰۰۰ تومان\n\n" "✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n" "🌐 کانال رسمی: https://t.me/NetVibe_VPN", get_vpn_banner_from_pool_or_generate( title="پینگ فوق‌العاده و آی‌پی تمیز ترید", card1_title="تونل اختصاصی آلمان و هلند", card2_title="ضمانت پایداری ۲۴ ساعته", brand=settings.TARGET_CHANNEL ) ), # Angle 4: Family & Team Multi-Device Solution ( "👥 یک اشتراک برای تمام اعضای خانواده یا همکاران\n\n" "لازم نیست برای هر گوشی جداگانه هزینه کنید؛ با پلن‌های چندکاربره NetVibe، همه به طور همزمان بدون افت سرعت متصل می‌مانید.\n\n" "✨ پلن ۳ کاربره نامحدود: ۳۵۰.۰۰۰ تومان\n" "✨ پلن ۲ کاربره نامحدود: ۳۰۰.۰۰۰ تومان\n\n" "✔️ سازگار با اندروید، iOS، ویندوز، مک و تلویزیون هوشمند\n" "✔️ پشتیبانی لحظه‌ای و اختصاصی\n\n" "✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n" "🌐 کانال رسمی: https://t.me/NetVibe_VPN", get_vpn_banner_from_pool_or_generate( title="اشتراک همزمان بدون افت سرعت", card1_title="پوشش همه دیوایس‌ها", card2_title="پشتیبانی ۲۴ ساعته اختصاصی", brand=settings.TARGET_CHANNEL ) ) ] created_ids = [] for promo_text, banner_url in marketing_promos: draft = ContentDraft( raw_post_id=sample_post.id if sample_post else None, ai_generated_text=promo_text, current_text=promo_text, banner_image_url=banner_url, status="pending" ) db.add(draft) await db.flush() created_ids.append(str(draft.id)) await db.commit() return {"status": "success", "count": len(created_ids), "draft_ids": created_ids} # --- BANNER POOL MANAGEMENT APIS --- @app.get("/api/v1/banner-pool") async def list_banner_pool(category: str = Query("gemini")): """List all banners in user-uploaded pool for gemini or vpn.""" target_dir = GEMINI_POOL_DIR if category == "gemini" else VPN_POOL_DIR os.makedirs(target_dir, exist_ok=True) items = [] valid_exts = ('.png', '.jpg', '.jpeg', '.webp') for fname in sorted(os.listdir(target_dir)): if fname.lower().endswith(valid_exts): fpath = os.path.join(target_dir, fname) stat = os.stat(fpath) items.append({ "filename": fname, "url": f"/static/banner_pool/{category}/{fname}", "size_kb": round(stat.st_size / 1024, 1), "modified_at": datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat() }) return {"category": category, "count": len(items), "banners": items} @app.post("/api/v1/banner-pool/upload") async def upload_banner_to_pool( category: str = Query("gemini"), file: UploadFile = File(...) ): """Upload a new banner into the Gemini or VPN banner pool (up to 10+ banners).""" target_dir = GEMINI_POOL_DIR if category == "gemini" else VPN_POOL_DIR os.makedirs(target_dir, exist_ok=True) clean_name = re.sub(r'[^a-zA-Z0-9_.-]', '_', file.filename or "banner.png") unique_name = f"{uuid.uuid4().hex[:6]}_{clean_name}" save_path = os.path.join(target_dir, unique_name) with open(save_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) return { "status": "success", "category": category, "filename": unique_name, "url": f"/static/banner_pool/{category}/{unique_name}" } @app.delete("/api/v1/banner-pool/{category}/{filename}") async def delete_banner_from_pool(category: str, filename: str): """Delete a banner from the pool.""" target_dir = GEMINI_POOL_DIR if category == "gemini" else VPN_POOL_DIR clean_name = os.path.basename(filename) target_path = os.path.join(target_dir, clean_name) if os.path.exists(target_path): os.remove(target_path) return {"status": "success", "message": f"Deleted {clean_name}"} raise HTTPException(status_code=404, detail="Banner not found in pool") @app.get("/api/v1/drafts", response_model=List[ContentDraftOut]) async def list_drafts( status: Optional[str] = Query("pending"), db: AsyncSession = Depends(get_db) ): query = ( select(ContentDraft) .options(selectinload(ContentDraft.raw_post)) .order_by(desc(ContentDraft.created_at)) ) if status and status != "all": query = query.where(ContentDraft.status == status) result = await db.execute(query) return result.scalars().all() import random def generate_random_tehran_prime_time(base_date: datetime, min_allowed_utc: Optional[datetime] = None) -> datetime: """ ساعات اوج بازدید ۴ تا ۸ شب به وقت تهران (16:00 تا 20:00 تهران == 12:30 تا 16:30 UTC): انتخاب تصادفی ساعت، دقیقه و ثانیه در این بازه ۲۴۰ دقیقه‌ای. """ year, month, day = base_date.year, base_date.month, base_date.day window_start = datetime(year, month, day, 12, 30, 0, tzinfo=timezone.utc) window_end = datetime(year, month, day, 16, 30, 0, tzinfo=timezone.utc) if min_allowed_utc and min_allowed_utc.tzinfo is None: min_allowed_utc = min_allowed_utc.replace(tzinfo=timezone.utc) if min_allowed_utc: earliest_possible = min_allowed_utc + timedelta(minutes=10) if earliest_possible > window_end: next_day = base_date + timedelta(days=1) return generate_random_tehran_prime_time(next_day, None) elif earliest_possible > window_start: window_start = earliest_possible total_seconds = int((window_end - window_start).total_seconds()) if total_seconds <= 60: rand_sec = 0 else: rand_sec = random.randint(0, total_seconds) return window_start + timedelta(seconds=rand_sec) @app.post("/api/v1/drafts/{draft_id}/action", response_model=ContentDraftOut) async def handle_draft_action( draft_id: UUID, payload: DraftActionRequest, db: AsyncSession = Depends(get_db) ): stmt = ( select(ContentDraft) .options(selectinload(ContentDraft.raw_post)) .where(ContentDraft.id == draft_id) ) draft = (await db.execute(stmt)).scalar_one_or_none() if not draft: raise HTTPException(status_code=404, detail="Draft not found") if payload.action == "reject": draft.status = "rejected" await record_human_feedback( db, draft_id=draft.id, original_ai_text=draft.ai_generated_text, final_human_text=payload.text or draft.current_text, rejection_reason=payload.rejection_reason or "Rejected by reviewer" ) elif payload.action in ["approve", "edit_approve"]: if payload.action == "edit_approve" and payload.text: draft.current_text = payload.text.strip() draft.status = "edited" await record_human_feedback( db, draft_id=draft.id, original_ai_text=draft.ai_generated_text, final_human_text=draft.current_text ) else: draft.status = "approved" # Apply Banner Choice (Remove banner or assign custom uploaded banner) if payload.remove_banner: draft.banner_image_url = None elif payload.banner_image_url: draft.banner_image_url = payload.banner_image_url # SMART AUTO-SCHEDULER (حداقل یک پست در هر روز در ساعات اوج بازدید) now_utc = datetime.now(timezone.utc) if payload.scheduled_time: sched_time = payload.scheduled_time if sched_time.tzinfo is None: sched_time = sched_time.replace(tzinfo=timezone.utc) else: # Query the latest scheduled time currently in queue stmt_latest = ( select(PublishQueue.scheduled_time) .where(PublishQueue.status == "queued") .order_by(desc(PublishQueue.scheduled_time)) .limit(1) ) latest_res = (await db.execute(stmt_latest)).scalar_one_or_none() if latest_res and latest_res.tzinfo is None: latest_res = latest_res.replace(tzinfo=timezone.utc) # ساعات اوج بازدید تلگرام: تصادفی بین ۱۶:۰۰ تا ۲۰:۰۰ عصر به وقت تهران if not latest_res or latest_res < now_utc: sched_time = generate_random_tehran_prime_time(now_utc, min_allowed_utc=now_utc) else: next_day = latest_res + timedelta(days=1) sched_time = generate_random_tehran_prime_time(next_day, None) # Push or update PublishQueue q_stmt = select(PublishQueue).where(PublishQueue.draft_id == draft.id) existing_q = (await db.execute(q_stmt)).scalar_one_or_none() if not existing_q: queue_item = PublishQueue( draft_id=draft.id, scheduled_time=sched_time, status="queued" ) db.add(queue_item) else: existing_q.scheduled_time = sched_time existing_q.status = "queued" await db.commit() await db.refresh(draft) return draft @app.post("/api/v1/upload-banner") async def upload_custom_banner(file: UploadFile = File(...)): # Validate content type if not file.content_type.startswith("image/"): raise HTTPException(status_code=400, detail="Only image files are allowed") ext = os.path.splitext(file.filename)[1] or ".png" unique_name = f"upload_{uuid.uuid4().hex[:10]}{ext}" dest_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static", "banners") os.makedirs(dest_dir, exist_ok=True) dest_path = os.path.join(dest_dir, unique_name) with open(dest_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) return {"banner_url": f"/static/banners/{unique_name}"} # --- FEEDBACK & QUEUE ENDPOINTS --- @app.get("/api/v1/feedback-logs", response_model=List[FeedbackLogOut]) async def list_feedback_logs(limit: int = 20, db: AsyncSession = Depends(get_db)): stmt = select(FeedbackLog).order_by(desc(FeedbackLog.created_at)).limit(limit) res = await db.execute(stmt) return res.scalars().all() @app.get("/api/v1/queue", response_model=List[PublishQueueOut]) async def list_publish_queue(db: AsyncSession = Depends(get_db)): stmt = ( select(PublishQueue) .options( selectinload(PublishQueue.draft).selectinload(ContentDraft.raw_post) ) .order_by(desc(PublishQueue.created_at)) ) res = await db.execute(stmt) return res.scalars().all() class QueueUpdateIn(BaseModel): scheduled_time: Optional[datetime] = None status: Optional[str] = None @app.patch("/api/v1/queue/{queue_id}") async def update_queue_item( queue_id: str, payload: QueueUpdateIn, db: AsyncSession = Depends(get_db) ): import uuid as _uuid try: qid = _uuid.UUID(queue_id) except Exception: raise HTTPException(status_code=400, detail="شناسه صف نامعتبر است") stmt = select(PublishQueue).where(PublishQueue.id == qid) item = (await db.execute(stmt)).scalar_one_or_none() if not item: raise HTTPException(status_code=404, detail="آیتم صف یافت نشد") if payload.scheduled_time: t = payload.scheduled_time if t.tzinfo is None: t = t.replace(tzinfo=timezone.utc) item.scheduled_time = t if payload.status: item.status = payload.status await db.commit() await db.refresh(item) return {"id": str(item.id), "scheduled_time": item.scheduled_time.isoformat(), "status": item.status} @app.post("/api/v1/queue/{queue_id}/randomize") async def randomize_queue_item( queue_id: str, db: AsyncSession = Depends(get_db) ): import uuid as _uuid try: qid = _uuid.UUID(queue_id) except Exception: raise HTTPException(status_code=400, detail="شناسه صف نامعتبر است") stmt = select(PublishQueue).where(PublishQueue.id == qid) item = (await db.execute(stmt)).scalar_one_or_none() if not item: raise HTTPException(status_code=404, detail="آیتم صف یافت نشد") now_utc = datetime.now(timezone.utc) base_date = item.scheduled_time or now_utc if base_date.tzinfo is None: base_date = base_date.replace(tzinfo=timezone.utc) # اگر برای امروز است، بررسی کنیم زمان گذشته نباشد min_allowed = now_utc if base_date.date() == now_utc.date() else None item.scheduled_time = generate_random_tehran_prime_time(base_date, min_allowed_utc=min_allowed) item.status = "queued" await db.commit() await db.refresh(item) return {"id": str(item.id), "scheduled_time": item.scheduled_time.isoformat(), "status": item.status} @app.post("/api/v1/queue/rebalance-random") async def rebalance_all_queued(db: AsyncSession = Depends(get_db)): """ تمام پست‌های در صف را بازآرایی و زمان آن‌ها را در بازه ۴ تا ۸ شب (۱۶:۰۰ تا ۲۰:۰۰ تهران) روزهای متوالی رندوم می‌کند. """ stmt = ( select(PublishQueue) .where(PublishQueue.status == "queued") .order_by(PublishQueue.scheduled_time.asc()) ) items = (await db.execute(stmt)).scalars().all() if not items: return {"rebalanced": 0, "items": []} now_utc = datetime.now(timezone.utc) curr_date = now_utc # اگر از امروز کمتر از ۲۰ دقیقه به ساعت ۲۰:۰۰ تهران (16:30 UTC) مانده، از فردا شروع کن today_deadline = curr_date.replace(hour=16, minute=30, second=0, microsecond=0) if now_utc >= today_deadline - timedelta(minutes=20): curr_date = curr_date + timedelta(days=1) min_allowed = None else: min_allowed = now_utc res_items = [] for i, item in enumerate(items): target_day = curr_date + timedelta(days=i) min_limit = min_allowed if i == 0 and min_allowed else None new_time = generate_random_tehran_prime_time(target_day, min_allowed_utc=min_limit) item.scheduled_time = new_time res_items.append({"id": str(item.id), "scheduled_time": new_time.isoformat()}) await db.commit() return {"rebalanced": len(items), "items": res_items} @app.delete("/api/v1/queue/{queue_id}") async def delete_queue_item( queue_id: str, db: AsyncSession = Depends(get_db) ): import uuid as _uuid try: qid = _uuid.UUID(queue_id) except Exception: raise HTTPException(status_code=400, detail="شناسه صف نامعتبر است") stmt = select(PublishQueue).where(PublishQueue.id == qid) item = (await db.execute(stmt)).scalar_one_or_none() if not item: raise HTTPException(status_code=404, detail="آیتم صف یافت نشد") if item.draft_id: d_stmt = select(ContentDraft).where(ContentDraft.id == item.draft_id) draft = (await db.execute(d_stmt)).scalar_one_or_none() if draft: draft.status = "pending" await db.delete(item) await db.commit() return {"status": "deleted", "id": str(qid)} import os from pydantic import BaseModel from fastapi.staticfiles import StaticFiles from app.banner_generator import create_vpn_banner, BANNER_DIR STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static") os.makedirs(os.path.join(STATIC_DIR, "banners"), exist_ok=True) app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") class BannerRequest(BaseModel): title: Optional[str] = "سرویس اینترنت پرسرعت و پایدار" location: Optional[str] = "آلمان 🇩🇪 و هلند 🇳🇱" subtitle: Optional[str] = "اتصال پایدار و بدون قطعی روی تمامی اپراتورها" @app.post("/api/v1/generate-banner") async def generate_banner_api(req: BannerRequest): path = create_vpn_banner( title=req.title or "سرویس اینترنت پرسرعت و پایدار", subtitle=req.subtitle or "اتصال پایدار و بدون قطعی روی تمامی اپراتورها" ) filename = os.path.basename(path) return {"banner_url": f"/static/banners/{filename}", "local_path": path} @app.get("/api/v1/stats") async def get_dashboard_stats(db: AsyncSession = Depends(get_db)): # Channels ch_stmt = select(Channel) channels = (await db.execute(ch_stmt)).scalars().all() total_subscribers = sum(c.subscriber_count or 0 for c in channels) # Raw Posts p_stmt = select(RawPost).options(selectinload(RawPost.channel)).order_by(desc(RawPost.views)).limit(25) viral_posts = (await db.execute(p_stmt)).scalars().all() p_latest_stmt = select(RawPost).options(selectinload(RawPost.channel)).order_by(desc(RawPost.posted_at)).limit(35) latest_posts = (await db.execute(p_latest_stmt)).scalars().all() # All posts for analytics all_p_stmt = select(RawPost) all_posts = (await db.execute(all_p_stmt)).scalars().all() # Protocols distribution proto_counts = {"VLESS": 0, "VMESS": 0, "TROJAN": 0, "SHADOWSOCKS": 0, "WARP": 0, "OTHER": 0} hourly = {i: 0 for i in range(24)} for p in all_posts: txt = (p.original_text or "").upper() matched = False for proto in ["VLESS", "VMESS", "TROJAN", "SHADOWSOCKS", "WARP"]: if proto in txt: proto_counts[proto] += 1 matched = True if not matched: proto_counts["OTHER"] += 1 if p.posted_at: h = p.posted_at.hour hourly[h] = hourly.get(h, 0) + 1 # Queue counts q_stmt = select(PublishQueue) all_q = (await db.execute(q_stmt)).scalars().all() # Drafts counts d_stmt = select(ContentDraft) all_d = (await db.execute(d_stmt)).scalars().all() return { "total_channels": len(channels), "total_subscribers": total_subscribers, "total_raw_posts": len(all_posts), "total_drafts": len(all_d), "total_queued": len([q for q in all_q if q.status == "queued"]), "total_published": len([q for q in all_q if q.status in ["published", "success"]]), "channels": [ { "id": str(c.id), "handle": c.telegram_handle, "title": c.title, "niche": c.niche, "subscribers": c.subscriber_count or 0, "is_active": c.is_active, "last_scraped_at": c.last_scraped_at.isoformat() if c.last_scraped_at else None } for c in channels ], "hourly_distribution": [{"hour": f"{h:02d}:00", "count": cnt} for h, cnt in hourly.items()], "protocol_distribution": [{"protocol": k, "count": v} for k, v in proto_counts.items()], "top_viral_posts": [ { "id": str(p.id), "message_id": p.message_id, "channel_handle": p.channel.telegram_handle if p.channel else "", "channel_title": p.channel.title if p.channel else "", "views": p.views or 0, "text": p.original_text or "", "media_type": p.media_type, "media_url": p.media_url, "post_url": p.post_url, "posted_at": p.posted_at.isoformat() if p.posted_at else None } for p in viral_posts ], "latest_posts": [ { "id": str(p.id), "message_id": p.message_id, "channel_handle": p.channel.telegram_handle if p.channel else "", "channel_title": p.channel.title if p.channel else "", "views": p.views or 0, "text": p.original_text or "", "media_type": p.media_type, "media_url": p.media_url, "post_url": p.post_url, "posted_at": p.posted_at.isoformat() if p.posted_at else None } for p in latest_posts ] } @app.post("/api/v1/pipeline/dispatch-now") async def trigger_dispatch_now(db: AsyncSession = Depends(get_db)): # Manual trigger forces dispatch of pending queued items without blocking on future scheduled_time count = await dispatch_pending_queue(db, force=True) return {"published_count": count} @app.post("/api/v1/queue/{queue_id}/send-now") async def trigger_send_single_queue_item(queue_id: str, db: AsyncSession = Depends(get_db)): success, error = await dispatch_single_queue_item(db, queue_id) if not success: raise HTTPException(status_code=400, detail=error or "Failed to publish queue item") return {"status": "success", "message": "Queue item published to Telegram successfully"}