|
| 1 | +"""Bytelixir earnings collector. |
| 2 | +
|
| 3 | +Authenticates via email/password to the Bytelixir dashboard API and |
| 4 | +fetches the current balance. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import logging |
| 10 | + |
| 11 | +import httpx |
| 12 | + |
| 13 | +from app.collectors.base import BaseCollector, EarningsResult |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +DASH_BASE = "https://dash.bytelixir.com" |
| 18 | + |
| 19 | + |
| 20 | +class BytelixirCollector(BaseCollector): |
| 21 | + """Collect earnings from Bytelixir's dashboard.""" |
| 22 | + |
| 23 | + platform = "bytelixir" |
| 24 | + |
| 25 | + def __init__(self, email: str, password: str) -> None: |
| 26 | + self.email = email |
| 27 | + self.password = password |
| 28 | + self._token: str | None = None |
| 29 | + |
| 30 | + async def _authenticate(self, client: httpx.AsyncClient) -> str: |
| 31 | + """Log in and obtain a session/token.""" |
| 32 | + resp = await client.post( |
| 33 | + f"{DASH_BASE}/api/auth/login", |
| 34 | + json={"email": self.email, "password": self.password}, |
| 35 | + headers={ |
| 36 | + "User-Agent": "Mozilla/5.0", |
| 37 | + "Origin": DASH_BASE, |
| 38 | + "Referer": f"{DASH_BASE}/", |
| 39 | + }, |
| 40 | + ) |
| 41 | + resp.raise_for_status() |
| 42 | + data = resp.json() |
| 43 | + |
| 44 | + # Try common token locations in response |
| 45 | + token = ( |
| 46 | + data.get("token") |
| 47 | + or data.get("access_token") |
| 48 | + or data.get("data", {}).get("token", "") |
| 49 | + or data.get("data", {}).get("access_token", "") |
| 50 | + ) |
| 51 | + if not token: |
| 52 | + raise ValueError(f"No token in Bytelixir login response (keys: {list(data.keys())})") |
| 53 | + return token |
| 54 | + |
| 55 | + async def collect(self) -> EarningsResult: |
| 56 | + """Fetch current Bytelixir balance.""" |
| 57 | + try: |
| 58 | + async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client: |
| 59 | + if not self._token: |
| 60 | + self._token = await self._authenticate(client) |
| 61 | + |
| 62 | + headers = { |
| 63 | + "Authorization": f"Bearer {self._token}", |
| 64 | + "User-Agent": "Mozilla/5.0", |
| 65 | + "Accept": "application/json", |
| 66 | + "Origin": DASH_BASE, |
| 67 | + "Referer": f"{DASH_BASE}/", |
| 68 | + } |
| 69 | + |
| 70 | + # Try the dashboard/earnings endpoints |
| 71 | + for path in ( |
| 72 | + "/api/user/balance", |
| 73 | + "/api/user/earnings", |
| 74 | + "/api/dashboard", |
| 75 | + "/api/user", |
| 76 | + "/api/me", |
| 77 | + ): |
| 78 | + resp = await client.get( |
| 79 | + f"{DASH_BASE}{path}", |
| 80 | + headers=headers, |
| 81 | + ) |
| 82 | + |
| 83 | + # Token expired — retry auth once |
| 84 | + if resp.status_code == 401: |
| 85 | + self._token = await self._authenticate(client) |
| 86 | + headers["Authorization"] = f"Bearer {self._token}" |
| 87 | + resp = await client.get( |
| 88 | + f"{DASH_BASE}{path}", |
| 89 | + headers=headers, |
| 90 | + ) |
| 91 | + |
| 92 | + if resp.status_code == 200: |
| 93 | + data = resp.json() |
| 94 | + balance = _extract_balance(data) |
| 95 | + if balance is not None: |
| 96 | + return EarningsResult( |
| 97 | + platform=self.platform, |
| 98 | + balance=round(balance, 4), |
| 99 | + currency="USD", |
| 100 | + ) |
| 101 | + |
| 102 | + return EarningsResult( |
| 103 | + platform=self.platform, |
| 104 | + balance=0.0, |
| 105 | + error="Could not find balance in Bytelixir API responses", |
| 106 | + ) |
| 107 | + except Exception as exc: |
| 108 | + logger.error("Bytelixir collection failed: %s", exc) |
| 109 | + return EarningsResult( |
| 110 | + platform=self.platform, |
| 111 | + balance=0.0, |
| 112 | + error=str(exc), |
| 113 | + ) |
| 114 | + |
| 115 | + |
| 116 | +def _extract_balance(data: dict) -> float | None: |
| 117 | + """Try to extract a USD balance from various response shapes.""" |
| 118 | + # Direct balance field |
| 119 | + for key in ("balance", "total_balance", "earnings", "total_earnings"): |
| 120 | + val = data.get(key) |
| 121 | + if val is not None: |
| 122 | + try: |
| 123 | + return float(val) |
| 124 | + except (ValueError, TypeError): |
| 125 | + continue |
| 126 | + |
| 127 | + # Nested under 'data' |
| 128 | + inner = data.get("data", {}) |
| 129 | + if isinstance(inner, dict): |
| 130 | + for key in ("balance", "total_balance", "earnings", "total_earnings"): |
| 131 | + val = inner.get(key) |
| 132 | + if val is not None: |
| 133 | + try: |
| 134 | + return float(val) |
| 135 | + except (ValueError, TypeError): |
| 136 | + continue |
| 137 | + |
| 138 | + # Nested under 'user' |
| 139 | + user = data.get("user", {}) |
| 140 | + if isinstance(user, dict): |
| 141 | + for key in ("balance", "earnings"): |
| 142 | + val = user.get(key) |
| 143 | + if val is not None: |
| 144 | + try: |
| 145 | + return float(val) |
| 146 | + except (ValueError, TypeError): |
| 147 | + continue |
| 148 | + |
| 149 | + return None |
0 commit comments