import httpx import logging import os import time from datetime import datetime, timedelta from typing import Dict, List, Optional logger = logging.getLogger(__name__) class NgrokAPI: def __init__(self, api_key: str = None): self.api_key = api_key or os.environ.get("NGROK_API_KEY") self.base_url = "https://api.ngrok.com" self.headers = { "Authorization": f"Bearer {self.api_key}", "Ngrok-Version": "2" } self._last_message_hash = None self._last_refresh_time = None async def get_tunnels(self) -> List[Dict]: """Get all active tunnels""" try: async with httpx.AsyncClient() as client: response = await client.get( f"{self.base_url}/tunnels", headers=self.headers ) response.raise_for_status() data = response.json() return data.get("tunnels", []) except Exception as e: logger.error(f"Error fetching tunnels: {e}") return [] async def get_edges(self) -> List[Dict]: """Get all edges""" try: async with httpx.AsyncClient() as client: response = await client.get( f"{self.base_url}/edges/tcp", headers=self.headers ) response.raise_for_status() data = response.json() return data.get("tcp_edges", []) except Exception as e: logger.error(f"Error fetching edges: {e}") return [] async def get_endpoints(self) -> List[Dict]: """Get all endpoints""" try: async with httpx.AsyncClient() as client: response = await client.get( f"{self.base_url}/endpoints", headers=self.headers ) response.raise_for_status() data = response.json() return data.get("endpoints", []) except Exception as e: logger.error(f"Error fetching endpoints: {e}") return [] def _format_url(self, url: str) -> str: """Format URL by removing protocol prefix and handling edge cases""" if not url or url == "N/A" or url == "": return "N/A" # Handle malformed URLs that start with :// if url.startswith("://"): return url[3:] # Remove "://" elif url.startswith("tcp://"): return url[6:] # Remove "tcp://" elif url.startswith("http://"): return url[7:] # Remove "http://" elif url.startswith("https://"): return url[8:] # Remove "https://" return url def _calculate_uptime(self, created_at: str) -> str: """Calculate uptime from created_at timestamp""" try: # Parse the ISO timestamp created_time = datetime.fromisoformat(created_at.replace('Z', '+00:00')) current_time = datetime.now(created_time.tzinfo) uptime = current_time - created_time # Format uptime days = uptime.days hours, remainder = divmod(uptime.seconds, 3600) minutes, _ = divmod(remainder, 60) if days > 0: return f"{days}d {hours}h {minutes}m" elif hours > 0: return f"{hours}h {minutes}m" else: return f"{minutes}m" except Exception as e: logger.error(f"Error calculating uptime: {e}") return "Unknown" def _get_time_since_last_refresh(self) -> str: """Get time since last refresh in human readable format with random component""" current_time = datetime.now() if self._last_refresh_time is None: self._last_refresh_time = current_time return "now" time_diff = current_time - self._last_refresh_time total_seconds = int(time_diff.total_seconds()) # Add current timestamp to make message unique every time timestamp = current_time.strftime("%H:%M:%S") if total_seconds < 60: return f"{total_seconds} second{'s' if total_seconds != 1 else ''} ago ({timestamp})" elif total_seconds < 3600: minutes = total_seconds // 60 return f"{minutes} minute{'s' if minutes != 1 else ''} ago ({timestamp})" else: hours = total_seconds // 3600 return f"{hours} hour{'s' if hours != 1 else ''} ago ({timestamp})" def format_tunnel_info(self, tunnels: List[Dict], edges: List[Dict], endpoints: List[Dict]) -> str: """Format tunnel information for display with consistent formatting""" if not tunnels and not edges and not endpoints: return "❌ No active tunnels, edges, or endpoints found." # Update last refresh time current_time = datetime.now() time_since_refresh = self._get_time_since_last_refresh() self._last_refresh_time = current_time # Use f-string for better customization as requested message = f"""🔗 **Ngrok Status** """ if tunnels: message += f"""**🚇 Active Tunnels:** """ for tunnel in tunnels: name = tunnel.get("name", "") public_url = tunnel.get("public_url", "N/A") proto = tunnel.get("proto", "tcp") # Default to tcp if not specified created_at = tunnel.get("created_at", "") # Format URL without protocol and use code markdown formatted_url = self._format_url(public_url) # Consistent formatting - always show protocol and uptime structure if created_at and formatted_url != "N/A": uptime = self._calculate_uptime(created_at) message += f"""• ({proto}) `{formatted_url}` ⏱️ Uptime: {uptime} """ elif formatted_url != "N/A": message += f"""• ({proto}) `{formatted_url}` """ else: message += f"""• ({proto}) `N/A` """ if edges: message += f"""**⚡ TCP Edges:** """ for edge in edges: edge_id = edge.get("id", "Unknown") hostports = edge.get("hostports", []) created_at = edge.get("created_at", "") message += f"""• **Edge ID:** `{edge_id}` """ if hostports: message += f""" **Hostports:** {', '.join(hostports)} """ # Add uptime if available if created_at: uptime = self._calculate_uptime(created_at) message += f""" ⏱️ Uptime: {uptime} """ message += "\n" if endpoints: message += f"""**🎯 Endpoints:** """ for endpoint in endpoints: endpoint_id = endpoint.get("id", "Unknown") public_url = endpoint.get("public_url", "N/A") proto = endpoint.get("proto", "tcp") # Default to tcp if not specified created_at = endpoint.get("created_at", "") # Format URL without protocol and use code markdown formatted_url = self._format_url(public_url) # Consistent formatting - always show uptime structure for endpoints if created_at and formatted_url != "N/A": uptime = self._calculate_uptime(created_at) message += f"""• {endpoint_id} ({proto}) `{formatted_url}` ⏱️ Uptime: {uptime} """ elif formatted_url != "N/A": message += f"""• {endpoint_id} ({proto}) `{formatted_url}` """ else: message += f"""• {endpoint_id} ({proto}) `N/A` """ # Add relative time since last refresh message += f"""🕐 **Updated:** {time_since_refresh}""" return message def is_message_different(self, new_message: str) -> bool: """Check if the new message is different from the last one""" message_hash = hash(new_message) if self._last_message_hash != message_hash: self._last_message_hash = message_hash return True return False def is_configured(self) -> bool: """Check if API key is configured""" return bool(self.api_key)