from fastapi import FastAPI, Depends, HTTPException, Header from fastapi.middleware.cors import CORSMiddleware from bs4 import BeautifulSoup import httpx import asyncio import time import re import jwt import logging import os from jwt import PyJWKClient logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = FastAPI(title="Tazas API", version="1.0.0") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["GET"], allow_headers=["*"], ) # ────────────────────────────────────────────── # Firebase App Check # ────────────────────────────────────────────── PROJECT_NUMBER = "748155614527" APP_ID = "1:748155614527:android:c29d203cf594986dda8f8a" JWKS_URL = "https://firebaseappcheck.googleapis.com/v1/jwks" _jwks_client = PyJWKClient(JWKS_URL, cache_jwk_set=True, lifespan=3600) def verify_app_check(x_firebase_appcheck: str = Header(None)): # PARCHE TEMPORAL: DISABLE_APP_CHECK=1 omite la validación mientras Google revisa la app if os.getenv("DISABLE_APP_CHECK") == "1": return if not x_firebase_appcheck: raise HTTPException(status_code=401, detail="Token App Check requerido") try: signing_key = _jwks_client.get_signing_key_from_jwt(x_firebase_appcheck) claims = jwt.decode( x_firebase_appcheck, signing_key.key, algorithms=["RS256"], audience=f"projects/{PROJECT_NUMBER}", issuer=f"https://firebaseappcheck.googleapis.com/{PROJECT_NUMBER}", ) if claims.get("sub") != APP_ID: raise HTTPException(status_code=401, detail="App no autorizada") except jwt.exceptions.PyJWTError: raise HTTPException(status_code=401, detail="Token App Check inválido") # ────────────────────────────────────────────── # Cache simple en memoria # ────────────────────────────────────────────── _cache: dict = {} BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al día) P2P_TTL = 60 * 20 # 20 minutos def _cached(key: str, ttl: int): entry = _cache.get(key) if entry and (time.time() - entry["ts"]) < ttl: return entry["data"] return None def _store(key: str, data: dict): _cache[key] = {"ts": time.time(), "data": data} def _parse_bcv_rate(text: str) -> float | None: """Convierte '36,85' o '36.853,12' a float.""" cleaned = text.strip().replace("Bs.", "").replace("S", "").strip() # Formato venezolano: punto como separador de miles, coma como decimal cleaned = cleaned.replace(".", "").replace(",", ".") try: return float(cleaned) except ValueError: return None # ────────────────────────────────────────────── # Fetchers # ────────────────────────────────────────────── async def fetch_bcv() -> dict: cached = _cached("bcv", BCV_TTL) if cached: return cached headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept-Language": "es-VE,es;q=0.9", } # verify=False porque bcv.org.ve tiene cadena de certificados incompleta (problema del BCV) async with httpx.AsyncClient(timeout=15, follow_redirects=True, verify=False) as client: response = await client.get("https://www.bcv.org.ve/", headers=headers) response.raise_for_status() soup = BeautifulSoup(response.text, "lxml") currency_ids = { "Usd": "dolar", "Eur": "euro", "Cny": "yuan", "Try": "lira", "Rub": "rublo", } rates = {} for suffix, div_id in currency_ids.items(): div = soup.find(id=div_id) tag = div.find("strong") if div else None rates[f"bcv{suffix}"] = _parse_bcv_rate(tag.text) if tag else None if all(v is None for v in rates.values()): logger.error("BCV: all rates are None — scraping failed") raise HTTPException(status_code=503, detail="No se pudo obtener las tasas BCV") updated_tag = soup.find("span", {"class": re.compile(r"date-display")}) updated_at = updated_tag.text.strip() if updated_tag else None data = {**rates, "updatedAt": updated_at} _store("bcv", data) return data async def fetch_p2p() -> dict: cached = _cached("p2p", P2P_TTL) if cached: return cached headers = { "User-Agent": "Mozilla/5.0", "Content-Type": "application/json", } body_base = { "fiat": "VES", "page": 1, "rows": 20, "asset": "USDT", "countries": [], "proMerchantAds": False, "shieldMerchantAds": False, "publisherType": None, "payTypes": [], "classifies": ["mass", "profession"], } async with httpx.AsyncClient(timeout=10) as client: # BUY = compradores de USDT (tab "Vender" en Binance, ordenado de mayor a menor) # SELL = vendedores de USDT (tab "Comprar" en Binance, ordenado de menor a mayor) buy_ads_res, sell_ads_res = await asyncio.gather( client.post( "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search", json={**body_base, "tradeType": "BUY"}, headers=headers, ), client.post( "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search", json={**body_base, "tradeType": "SELL"}, headers=headers, ), ) buy_ads_res.raise_for_status() sell_ads_res.raise_for_status() def first_eligible_price(ads: list) -> float | None: """ 1. Promedia los precios de los anuncios 2, 3 y 4 (índices 1-3) como referencia. 2. fiat_ref = promedio * 20 (~20 USDT en VES). 3. Devuelve el primer anuncio donde minSingleTransAmount <= fiat_ref <= maxSingleTransAmount, es decir, uno que realmente acepte esa transacción. Fallback: primer anuncio desde índice 1 con min <= fiat_ref (sin chequeo de max). """ if not ads: return None # Paso 1: promedio de ads[3..5] (saltamos los primeros 3) sample = [] for item in ads[3:6]: try: sample.append(float(item["adv"]["price"])) except (KeyError, ValueError, TypeError): pass if not sample: return None avg_price = sum(sample) / len(sample) fiat_ref = avg_price * 20 # ~20 USDT en VES # Paso 2: primer anuncio que acepte la transacción (min <= fiat_ref <= max) for item in ads: adv = item.get("adv", {}) try: price = float(adv["price"]) surplus = float(adv.get("surplusAmount", 0)) min_fiat = float(adv.get("minSingleTransAmount", 0)) max_fiat = float(adv.get("maxSingleTransAmount", float("inf"))) if surplus > 0 and min_fiat <= fiat_ref <= max_fiat: return price except (KeyError, ValueError, TypeError): continue # Fallback: primer anuncio desde índice 3 con min <= fiat_ref for item in ads[3:]: adv = item.get("adv", {}) try: price = float(adv["price"]) surplus = float(adv.get("surplusAmount", 0)) min_fiat = float(adv.get("minSingleTransAmount", 0)) if surplus > 0 and min_fiat <= fiat_ref: return price except (KeyError, ValueError, TypeError): continue return None # Compra: vendedores de USDT (SELL ads), primer precio = el más barato disponible p2p_buy = first_eligible_price(sell_ads_res.json().get("data", [])) # Venta: compradores de USDT (BUY ads), primer precio = el más alto disponible p2p_sell = first_eligible_price(buy_ads_res.json().get("data", [])) data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell} _store("p2p", data) return data # ────────────────────────────────────────────── # Endpoints # ────────────────────────────────────────────── @app.get("/") async def root(): return {"status": "ok", "service": "Tazas API"} @app.get("/v1/rates", dependencies=[Depends(verify_app_check)]) async def rates(): bcv_data, p2p_data = await asyncio.gather( fetch_bcv(), fetch_p2p_safe(), ) return {**bcv_data, **p2p_data} @app.get("/v1/bcv", dependencies=[Depends(verify_app_check)]) async def bcv(): return await fetch_bcv() async def fetch_p2p_safe() -> dict: try: return await fetch_p2p() except Exception as e: logger.error("fetch_p2p failed: %s", e, exc_info=True) return {"p2pBuyMax": None, "p2pSellMax": None} @app.get("/v1/p2p", dependencies=[Depends(verify_app_check)]) async def p2p(): return await fetch_p2p() @app.get("/v1/p2p/debug") async def p2p_debug(): """Devuelve los primeros 5 anuncios crudos de cada dirección para diagnóstico.""" headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "application/json"} body_base = { "fiat": "VES", "page": 1, "rows": 10, "asset": "USDT", "countries": [], "proMerchantAds": False, "shieldMerchantAds": False, "publisherType": None, "payTypes": [], "classifies": ["mass", "profession"], } async with httpx.AsyncClient(timeout=10) as client: buy_res, sell_res = await asyncio.gather( client.post("https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search", json={**body_base, "tradeType": "BUY"}, headers=headers), client.post("https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search", json={**body_base, "tradeType": "SELL"}, headers=headers), ) def extract(ads): return [ { "price": item["adv"].get("price"), "surplusAmount": item["adv"].get("surplusAmount"), "minSingleTransAmount": item["adv"].get("minSingleTransAmount"), "maxSingleTransAmount": item["adv"].get("maxSingleTransAmount"), "publisherType": item["adv"].get("publisherType"), } for item in ads[:5] ] return { "buy_ads": extract(buy_res.json().get("data", [])), "sell_ads": extract(sell_res.json().get("data", [])), }