|
| 1 | +""" |
| 2 | +Dashboard API Client |
| 3 | +
|
| 4 | +Fetches points data from Microsoft Rewards Dashboard API. |
| 5 | +""" |
| 6 | + |
| 7 | +import logging |
| 8 | +import re |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +from playwright.async_api import Page |
| 12 | + |
| 13 | +from constants import API_ENDPOINTS, REWARDS_URLS |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class DashboardClient: |
| 19 | + """Client for fetching data from Microsoft Rewards Dashboard API""" |
| 20 | + |
| 21 | + def __init__(self, page: Page): |
| 22 | + """ |
| 23 | + Initialize Dashboard client |
| 24 | +
|
| 25 | + Args: |
| 26 | + page: Playwright Page object |
| 27 | + """ |
| 28 | + self.page = page |
| 29 | + self._cached_points: int | None = None |
| 30 | + base = REWARDS_URLS.get("dashboard", "https://rewards.bing.com") |
| 31 | + self._base_url = base.rstrip("/") |
| 32 | + |
| 33 | + async def get_current_points(self) -> int | None: |
| 34 | + """ |
| 35 | + Get current points from Dashboard API |
| 36 | +
|
| 37 | + Attempts to fetch points via API call first, falls back to |
| 38 | + parsing page content if API fails. |
| 39 | +
|
| 40 | + Returns: |
| 41 | + Points balance or None if unable to determine |
| 42 | + """ |
| 43 | + try: |
| 44 | + points = await self._fetch_points_via_api() |
| 45 | + if points is not None and points >= 0: |
| 46 | + self._cached_points = points |
| 47 | + return points |
| 48 | + except TimeoutError as e: |
| 49 | + logger.warning(f"API request timeout: {e}") |
| 50 | + except ConnectionError as e: |
| 51 | + logger.warning(f"API connection error: {e}") |
| 52 | + except Exception as e: |
| 53 | + logger.warning(f"API call failed: {e}") |
| 54 | + |
| 55 | + try: |
| 56 | + points = await self._fetch_points_via_page_content() |
| 57 | + if points is not None and points >= 0: |
| 58 | + self._cached_points = points |
| 59 | + return points |
| 60 | + except Exception as e: |
| 61 | + logger.debug(f"Page content parsing failed: {e}") |
| 62 | + |
| 63 | + return self._cached_points |
| 64 | + |
| 65 | + async def _fetch_points_via_api(self) -> int | None: |
| 66 | + """ |
| 67 | + Fetch points via internal API endpoint |
| 68 | +
|
| 69 | + Returns: |
| 70 | + Points balance or None |
| 71 | + """ |
| 72 | + try: |
| 73 | + api_url = f"{self._base_url}{API_ENDPOINTS['dashboard_balance']}" |
| 74 | + response = await self.page.evaluate( |
| 75 | + f""" |
| 76 | + async () => {{ |
| 77 | + try {{ |
| 78 | + const resp = await fetch('{api_url}', {{ |
| 79 | + method: 'GET', |
| 80 | + credentials: 'include' |
| 81 | + }}); |
| 82 | + if (!resp.ok) return null; |
| 83 | + return await resp.json(); |
| 84 | + }} catch {{ |
| 85 | + return null; |
| 86 | + }} |
| 87 | + }} |
| 88 | + """ |
| 89 | + ) |
| 90 | + |
| 91 | + if response and isinstance(response, dict): |
| 92 | + available = response.get("availablePoints") |
| 93 | + balance = response.get("pointsBalance") |
| 94 | + points = available if available is not None else balance |
| 95 | + if points is not None: |
| 96 | + try: |
| 97 | + return int(points) |
| 98 | + except (ValueError, TypeError): |
| 99 | + pass |
| 100 | + |
| 101 | + except Exception as e: |
| 102 | + logger.debug(f"API fetch error: {e}") |
| 103 | + |
| 104 | + return None |
| 105 | + |
| 106 | + async def _fetch_points_via_page_content(self) -> int | None: |
| 107 | + """ |
| 108 | + Extract points from page content as fallback |
| 109 | +
|
| 110 | + Returns: |
| 111 | + Points balance or None |
| 112 | + """ |
| 113 | + try: |
| 114 | + content = await self.page.content() |
| 115 | + |
| 116 | + patterns = [ |
| 117 | + r'"availablePoints"\s*:\s*(\d+)', |
| 118 | + r'"pointsBalance"\s*:\s*(\d+)', |
| 119 | + r'"totalPoints"\s*:\s*(\d+)', |
| 120 | + ] |
| 121 | + |
| 122 | + for pattern in patterns: |
| 123 | + match = re.search(pattern, content) |
| 124 | + if match: |
| 125 | + points = int(match.group(1)) |
| 126 | + if 0 <= points <= 1000000: |
| 127 | + return points |
| 128 | + |
| 129 | + except Exception as e: |
| 130 | + logger.debug(f"Page content extraction error: {e}") |
| 131 | + |
| 132 | + return None |
| 133 | + |
| 134 | + async def get_dashboard_data(self) -> dict[str, Any] | None: |
| 135 | + """ |
| 136 | + Fetch full dashboard data |
| 137 | +
|
| 138 | + Returns: |
| 139 | + Dashboard data dict or None |
| 140 | + """ |
| 141 | + try: |
| 142 | + api_url = f"{self._base_url}{API_ENDPOINTS['dashboard_data']}" |
| 143 | + response = await self.page.evaluate( |
| 144 | + f""" |
| 145 | + async () => {{ |
| 146 | + try {{ |
| 147 | + const resp = await fetch('{api_url}', {{ |
| 148 | + method: 'GET', |
| 149 | + credentials: 'include' |
| 150 | + }}); |
| 151 | + if (!resp.ok) return null; |
| 152 | + return await resp.json(); |
| 153 | + }} catch {{ |
| 154 | + return null; |
| 155 | + }} |
| 156 | + }} |
| 157 | + """ |
| 158 | + ) |
| 159 | + |
| 160 | + if response is not None and isinstance(response, dict): |
| 161 | + return dict(response) |
| 162 | + |
| 163 | + except TimeoutError as e: |
| 164 | + logger.warning(f"Dashboard API timeout: {e}") |
| 165 | + except ConnectionError as e: |
| 166 | + logger.warning(f"Dashboard API connection error: {e}") |
| 167 | + except Exception as e: |
| 168 | + logger.warning(f"Dashboard API error: {e}") |
| 169 | + |
| 170 | + return None |
0 commit comments