File size: 9,045 Bytes
b28ce06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)