Spaces:
Running

File size: 11,105 Bytes
c924ee5
dbdd5c5
96f9f5f
dbdd5c5
 
 
96f9f5f
c924ee5
2aa3ef0
ded8996
c924ee5
dbdd5c5
2aa3ef0
 
 
dbdd5c5
 
 
 
 
 
 
 
 
c924ee5
 
 
 
 
 
 
 
 
 
ded8996
 
 
 
 
 
c924ee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbdd5c5
 
 
 
96f9f5f
c924ee5
dbdd5c5
 
 
 
 
 
 
 
 
 
 
 
 
96f9f5f
 
 
 
 
 
 
 
 
 
 
dbdd5c5
 
 
 
 
 
 
 
96f9f5f
 
 
 
c924ee5
8bd9e53
 
96f9f5f
 
dbdd5c5
96f9f5f
dbdd5c5
96f9f5f
297b450
 
 
 
 
dbdd5c5
96f9f5f
 
297b450
96f9f5f
 
297b450
96f9f5f
 
2aa3ef0
96f9f5f
 
 
 
 
 
dbdd5c5
 
 
 
 
 
 
 
 
 
 
 
 
96f9f5f
 
 
 
 
 
 
 
 
 
 
dbdd5c5
 
2ccc0b1
5153ac4
 
 
96f9f5f
 
 
 
 
 
 
 
 
 
dbdd5c5
5153ac4
 
dbdd5c5
23e66cd
 
3f7c4aa
 
 
 
 
23e66cd
76119a4
 
 
74a336b
3f7c4aa
74a336b
3f7c4aa
 
 
 
 
 
74a336b
3f7c4aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74a336b
 
96f9f5f
 
3f7c4aa
 
 
 
 
96f9f5f
 
5153ac4
96f9f5f
5153ac4
23e66cd
5153ac4
23e66cd
dbdd5c5
5153ac4
dbdd5c5
 
 
 
 
 
 
 
 
 
 
 
c924ee5
dbdd5c5
2aa3ef0
 
 
 
 
dbdd5c5
 
c924ee5
dbdd5c5
 
 
 
2aa3ef0
 
 
 
 
 
 
 
c924ee5
dbdd5c5
 
7f85ae5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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", [])),
    }