| 1 | import requests |
| 2 | |
| 3 | class SurferClient: |
| 4 | def __init__(self, host: str = "localhost", port: int = 2024): |
| 5 | self.base_url = f"http://{host}:{port}/api" |
| 6 | self.session = requests.Session() |
| 7 | self._check_connection() |
| 8 | |
| 9 | def _check_connection(self): |
| 10 | try: |
| 11 | # Try to connect to the desktop app |
| 12 | response = self.session.get(f"{self.base_url}/health") |
| 13 | response.raise_for_status() |
| 14 | except requests.exceptions.RequestException as e: |
| 15 | raise ConnectionError("Couldn't connect to the Surfer Desktop app. Is it running?") from e |
| 16 | |
| 17 | |
| 18 | def get(self, platform_id: str) -> dict: |
| 19 | """Get the most recent run for a specific platform. |
| 20 | |
| 21 | Raises: |
| 22 | ConnectionError: If connection to desktop app fails |
| 23 | ValueError: If no successful runs are found for the platform |
| 24 | """ |
| 25 | try: |
| 26 | response = self.session.post(f"{self.base_url}/get", json={"platformId": platform_id}) |
| 27 | |
| 28 | # Handle 404 status codes specifically |
| 29 | if response.status_code == 404: |
| 30 | error_data = response.json() |
| 31 | raise ValueError(error_data['error']) |
| 32 | |
| 33 | # Handle other HTTP errors |
| 34 | response.raise_for_status() |
| 35 | |
| 36 | data = response.json() |
| 37 | if not data.get('success'): |
| 38 | raise ValueError(data.get('error', 'Unknown error occurred')) |
| 39 | |
| 40 | return data |
| 41 | |
| 42 | except requests.exceptions.RequestException as e: |
| 43 | raise ConnectionError(f"Failed to get most recent run: {str(e)}") from e |
| 44 | |
| 45 | def export(self, platform_id: str) -> dict: |
| 46 | """Trigger an export for a specific platform. |
| 47 | |
| 48 | Raises: |
| 49 | ConnectionError: If connection to desktop app fails |
| 50 | ValueError: If platform is not connected or export fails |
| 51 | """ |
| 52 | try: |
| 53 | response = self.session.post(f"{self.base_url}/export", json={"platformId": platform_id}) |
| 54 | response.raise_for_status() |
| 55 | data = response.json() |
| 56 | |
| 57 | if not data.get('success'): |
| 58 | raise ValueError(data.get('error', 'Export failed')) |
| 59 | |
| 60 | return data |