import os import json import base64 import requests from fastapi import FastAPI, HTTPException, Header, Depends from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from typing import Optional from google import genai # pip install google-genai from datetime import datetime, timedelta app = FastAPI() # --- CORS Settings --- app.add_middleware( CORSMiddleware, allow_origins=["*"], # 💡 စမ်းသပ်ရတာ မြန်ဆန်စေရန် origins ကို "*" ပေးထားခြင်းက ပိုအဆင်ပြေစေပါတယ် allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # --- Environment Configuration --- GITHUB_TOKEN = os.environ.get("GH_TOKEN") GITHUB_REPO = "Powerctc/s4itmm-db" GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY") # 🔒 တတိယအထပ် ကာကွယ်ရေး Token HF_SECURE_TOKEN = os.environ.get("HF_SECURE_TOKEN", "BFA_STREAM_SUPER_SECRET_TOKEN_2026") # --- Data Models --- class PaymentRequest(BaseModel): deviceID: str txnId: str amount: str method: str date: str userType: str screenshotBase64: str type: str = "pending" ai_verdict: Optional[str] = "unchecked" class ApproveRequest(BaseModel): id: str txnId: str userType: Optional[str] = "phone" days: int = 30 class ManualExtendRequest(BaseModel): user_id: str expiry_date: str # Format: YYYY-MM-DD userType: Optional[str] = "tv" # default ကို tv အဖြစ် ထားပေးသည် # --- Security Dependency --- def verify_admin_token(authorization: Optional[str] = Header(None)): if not authorization: raise HTTPException(status_code=401, detail="Missing Token Header") # 💡 Bearer ပါပါ မပါပါ အလုပ်လုပ်စေရန် ညှိခြင်း (Frontend စမ်းသပ်ရလွယ်ကူစေရန်) if authorization.startswith("Bearer "): token = authorization.split(" ")[1] else: token = authorization if token != HF_SECURE_TOKEN: raise HTTPException(status_code=403, detail="Unauthorized access. Invalid Token.") return token # --- Helper Functions --- # 💡 ဖြည့်စွက်ချက်- မင်းအရင်က သုံးထားတဲ့ လမ်းကြောင်းတွေအားလုံး (Adults, BFA Web) စုံလင်အောင် ဖြည့်ပေးထားသည် def get_target_path(category: str, user_type: str = "tv"): if category == "pending": return "Phone/pending_payments.json" user_type_lower = user_type.lower() if user_type else "tv" if user_type_lower == "phone": return "mobile_approve_user.json" # သို့မဟုတ် "mobile_approve_user.json" မင်းရဲ့ Repo အတိုင်း စစ်ပါ if user_type_lower == "web": return "Web/approved_users.json" if user_type_lower == "bfa_web": return "BFA_approved_users.json" if user_type_lower == "adults": return "Adults/approved_users.json" return "approved_users.json" # Default: TV လမ်းကြောင်း def check_screenshot_with_ai(base64_string: str) -> str: if not GEMINI_API_KEY: return "AI_KEY_MISSING" try: if "," in base64_string: base64_string = base64_string.split(",")[1] image_bytes = base64.b64decode(base64_string) client = genai.Client(api_key=GEMINI_API_KEY) response = client.models.generate_content( model='gemini-2.5-flash', contents=[ genai.types.Part.from_bytes(data=image_bytes, mime_type='image/jpeg'), "Analyze this mobile banking payment screenshot. Is it a REAL transaction receipt or a FAKE/EDITED one? Reply with only one word: 'REAL' or 'FAKE'." ] ) return response.text.strip().upper() except Exception as e: return f"AI_ERROR: {str(e)}" def fetch_github_file(path): url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{path}" headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"} res = requests.get(url, headers=headers) if res.status_code == 200: file_data = res.json() content = json.loads(base64.b64decode(file_data['content']).decode('utf-8')) return content, file_data['sha'] return [], "" def save_github_file(path, content_list, sha): url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{path}" headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"} updated_json = json.dumps(content_list, indent=4) encoded_content = base64.b64encode(updated_json.encode('utf-8')).decode('utf-8') payload = { "message": f"Update {path} via API", "content": encoded_content, "sha": sha if sha else None } put_res = requests.put(url, headers=headers, json=payload) return put_res.status_code in [200, 201], put_res.text # --- API Endpoints --- @app.get("/") def home(): return {"status": "Online", "service": "S4ITMM Intelligent Payment & VIP API"} # ၁။ User များ ငွေလွှဲပြေစာ တင်သွင်းသည့် နေရာ @app.post("/submit_payment") async def submit_payment(payment: PaymentRequest): if not GITHUB_TOKEN: raise HTTPException(status_code=500, detail="GH_TOKEN not found in environment") ai_result = check_screenshot_with_ai(payment.screenshotBase64) payment.ai_verdict = ai_result if "REAL" in ai_result: payment.type = "pending_by_ai_real" elif "FAKE" in ai_result: payment.type = "pending_by_ai_fake" else: payment.type = "pending" path = get_target_path("pending") content_list, sha = fetch_github_file(path) if any(item.get('txnId') == payment.txnId for item in content_list): raise HTTPException(status_code=400, detail="This Transaction ID has already been submitted.") content_list.append(payment.dict()) success, detail = save_github_file(path, content_list, sha) if success: return {"status": "success", "message": "Payment received", "ai_analysis": ai_result} else: raise HTTPException(status_code=500, detail=f"GitHub Error: {detail}") # ၂။ Next.js Admin Panel မှ Pending ပြေစာစာရင်း လှမ်းတောင်းသည့် နေရာ @app.get("/get_payments") async def get_payments(token: str = Depends(verify_admin_token)): path = get_target_path("pending") content_list, _ = fetch_github_file(path) formatted_list = [] for item in content_list: item["ai_analysis"] = item.get("ai_verdict", "unchecked") formatted_list.append(item) return formatted_list # ၃။ Admin က Panel မှနေ၍ Approve ခလုတ်နှိပ်သည့်အခါ ခေါ်မည့်နေရာ @app.post("/approve_user") async def approve_payment(req: ApproveRequest, token: str = Depends(verify_admin_token)): pending_path = get_target_path("pending") pending_list, pending_sha = fetch_github_file(pending_path) target_user = None for item in pending_list: if item.get('txnId') == req.txnId: target_user = item break if not target_user: raise HTTPException(status_code=404, detail="Transaction ID not found in pending list.") pending_list = [item for item in pending_list if item.get('txnId') != req.txnId] save_github_file(pending_path, pending_list, pending_sha) expired_date = (datetime.utcnow() + timedelta(days=req.days)).strftime("%Y-%m-%dT%H:%M:%SZ") actual_user_type = target_user.get("userType", "phone") approved_data = { "id": target_user["deviceID"], "expires": expired_date, "name": "Mobile_User", "type": actual_user_type } approved_path = get_target_path("approved", actual_user_type) approved_list, approved_sha = fetch_github_file(approved_path) approved_list = [item for item in approved_list if item.get('id') != target_user["deviceID"]] approved_list.append(approved_data) success, detail = save_github_file(approved_path, approved_list, approved_sha) if success: return {"status": "success", "message": f"User {target_user['deviceID']} approved until {expired_date}"} else: raise HTTPException(status_code=500, detail=f"GitHub Approved Sync Error: {detail}") # ၄။ Admin Panel မှ User ID နှင့် ရက်စွဲကို တိုက်ရိုက်ရိုက်ထည့်ပြီး VIP တိုးပေးမည့် နေရာ (Manual Extension) @app.post("/manual_extend_user") async def manual_extend_user(req: ManualExtendRequest, token: str = Depends(verify_admin_token)): if not GITHUB_TOKEN: raise HTTPException(status_code=500, detail="GH_TOKEN not found in environment") try: parsed_date = datetime.strptime(req.expiry_date, "%Y-%m-%d") formatted_expiry = parsed_date.replace(hour=23, minute=59, second=59).strftime("%Y-%m-%dT%H:%M:%SZ") except ValueError: raise HTTPException(status_code=400, detail="ရက်စွဲ Format တည်ဆောက်ပုံ မှားယွင်းနေပါသည်။ YYYY-MM-DD ပုံစံပဲ ဖြစ်ရပါမည်။") approved_data = { "id": req.user_id, "expires": formatted_expiry, "name": "Manual_VIP_User", "type": req.userType } approved_path = get_target_path("approved", req.userType) approved_list, approved_sha = fetch_github_file(approved_path) approved_list = [item for item in approved_list if item.get('id') != req.user_id] approved_list.append(approved_data) success, detail = save_github_file(approved_path, approved_list, approved_sha) if success: return {"status": "success", "message": f"User {req.user_id} အား {req.userType} လမ်းကြောင်းတွင် {req.expiry_date} အထိ သက်တမ်းတိုးပေးပြီးပါပြီ။"} else: raise HTTPException(status_code=500, detail=f"GitHub Manual Sync Error: {detail}") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)