| 1 | import Redis from 'ioredis'; |
| 2 | |
| 3 | import { RedisService } |
| 4 | import { |
| 5 | HttpException, |
| 6 | HttpStatus, |
| 7 | Injectable, |
| 8 | OnModuleInit, |
| 9 | } from '@nestjs/common'; |
| 10 | import { ConfigService } |
| 11 | |
| 12 | export interface AircraftState |
| 13 | icao24: string; |
| 14 | callsign: string |
| 15 | origin_country: string; |
| 16 | time_position: number |
| 17 | last_contact: number; |
| 18 | longitude: number |
| 19 | latitude: number |
| 20 | baro_altitude: number |
| 21 | on_ground: boolean; |
| 22 | velocity: number |
| 23 | true_track: number |
| 24 | vertical_rate: number |
| 25 | sensors: number[] |
| 26 | geo_altitude: number |
| 27 | squawk: string |
| 28 | spi: boolean; |
| 29 | position_source: number; |
| 30 | } |
| 31 | |
| 32 | export interface OpenskyResponse |
| 33 | time: number; |
| 34 | states: AircraftState |
| 35 | } |
| 36 | |
| 37 | @Injectable() |
| 38 | export class OpenskyNetworkService |
| 39 | private readonly baseUrl |
| 40 | private readonly openSkyAuthURL |
| 41 | 'https://auth.opensky-network.org/auth/realms/opensky-network/protocol/openid-connect/token'; |
| 42 | private readonly rateLimitDelay |
| 43 | private readonly tokenCacheKey |
| 44 | private readonly tokenTTL |
| 45 | private lastRequestTime = |
| 46 | private redis: |
| 47 | |
| 48 | constructor( |
| 49 | private readonly redisService |
| 50 | private readonly configService |
| 51 | ) { |
| 52 | this.redis = |
| 53 | } |
| 54 | |
| 55 | async onModuleInit() { |
| 56 | // Initialize token on module startup |
| 57 | await this.ensureValidToken |
| 58 | } |
| 59 | |
| 60 | private async ensureValidToken |
| 61 | try { |
| 62 | // Check if token exists in Redis |
| 63 | const cachedToken = |
| 64 | |
| 65 | if (cachedToken) { |
| 66 | return cachedToken; |
| 67 | } |
| 68 | |
| 69 | // Generate new token if not cached |
| 70 | return await this |
| 71 | } catch (error) |
| 72 | console.error('Error ensuring valid token: |
| 73 | // Fallback to generating new token |
| 74 | return await this |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | private async generateNewToken |
| 79 | const clientId = |
| 80 | const clientSecret = |
| 81 | 'OPENSKY_CLIENT_SECRET', |
| 82 | ); |
| 83 | |
| 84 | if (!clientId || |
| 85 | console.warn( |
| 86 | 'OpenSky credentials not configured. Using unauthenticated requests.', |
| 87 | ); |
| 88 | return ''; |
| 89 | } |
| 90 | |
| 91 | try { |
| 92 | const formData = |
| 93 | formData.append('grant_type |
| 94 | formData.append('client_id |
| 95 | formData.append('client_secret |
| 96 | |
| 97 | const response = |
| 98 | method: 'POST', |
| 99 | headers: { |
| 100 | 'Content-Type': 'application/x-www-form-urlencoded', |
| 101 | }, |
| 102 | body: formData, |
| 103 | }); |
| 104 | |
| 105 | if (!response.ok |
| 106 | throw new Error( |
| 107 | } |
| 108 | |
| 109 | const data = |
| 110 | const accessToken = |
| 111 | |
| 112 | if (!accessToken) |
| 113 | throw new Error( |
| 114 | } |
| 115 | |
| 116 | // Cache the token in Redis with TTL |
| 117 | await this.redis |
| 118 | |
| 119 | console.log('OpenSky access token generated and cached |
| 120 | return accessToken; |
| 121 | } catch (error) |
| 122 | console.error('Failed to generate OpenSky token: |
| 123 | return ''; |
| 124 | } |
| 125 | } |
| 126 | /** |
| 127 | * Get aircraft states within a bounding box |
| 128 | */ |
| 129 | async getAircraftStatesInBounds( |
| 130 | minLat: number, |
| 131 | maxLat: number, |
| 132 | minLng: number, |
| 133 | maxLng: number, |
| 134 | ): Promise<OpenskyResponse |
| 135 | // Rate limiting |
| 136 | const now = |
| 137 | const timeSinceLastRequest = |
| 138 | if (timeSinceLastRequest < |
| 139 | await new Promise |
| 140 | setTimeout(resolve, this |
| 141 | ); |
| 142 | } |
| 143 | |
| 144 | try { |
| 145 | // Ensure we have a valid token |
| 146 | const token = |
| 147 | |
| 148 | const url = |
| 149 | url.searchParams.append |
| 150 | url.searchParams.append |
| 151 | url.searchParams.append |
| 152 | url.searchParams.append |
| 153 | url.searchParams.append |
| 154 | |
| 155 | const headers: |
| 156 | |
| 157 | // Add Bearer token if available |
| 158 | if (token) { |
| 159 | headers['Authorization'] |
| 160 | } |
| 161 | const response = |
| 162 | headers, |
| 163 | }); |
| 164 | |
| 165 | this.lastRequestTime = |
| 166 | |
| 167 | if (!response.ok |
| 168 | if (response.status |
| 169 | throw new HttpException( |
| 170 | 'OpenSky API rate limit exceeded. Please try again later.', |
| 171 | HttpStatus.TOO_MANY_REQUESTS, |
| 172 | ); |
| 173 | } |
| 174 | if (response.status |
| 175 | // Token might be expired, try to generate a new one |
| 176 | console.log('Token expired, generating new one... |
| 177 | await this.redis |
| 178 | return this.getAircraftStatesInBounds |
| 179 | } |
| 180 | throw new HttpException( |
| 181 | `OpenSky API request failed with status ${response.status |
| 182 | HttpStatus.BAD_GATEWAY, |
| 183 | ); |
| 184 | } |
| 185 | |
| 186 | const data = |
| 187 | |
| 188 | if (!data.states |
| 189 | return { |
| 190 | time: data.time |
| 191 | states: [], |
| 192 | }; |
| 193 | } |
| 194 | |
| 195 | // Filter out invalid states and transform the data |
| 196 | const validStates = |
| 197 | .filter((state: |
| 198 | .map( |
| 199 | (state: any |
| 200 | icao24: state[0] |
| 201 | callsign: state[1] |
| 202 | origin_country: state[2] |
| 203 | time_position: state[3] |
| 204 | last_contact: state[4] |
| 205 | longitude: state[5] |
| 206 | latitude: state[6] |
| 207 | baro_altitude: state[7] |
| 208 | on_ground: state[8] |
| 209 | velocity: state[9] |
| 210 | true_track: state[10] |
| 211 | vertical_rate: state[11] |
| 212 | sensors: state[12] |
| 213 | geo_altitude: state[13] |
| 214 | squawk: state[14] |
| 215 | spi: state[15] |
| 216 | position_source: state[16] |
| 217 | }), |
| 218 | ) |
| 219 | .filter( |
| 220 | (state: AircraftState |
| 221 | state.latitude && |
| 222 | state.longitude && |
| 223 | state.latitude >= |
| 224 | state.latitude <= |
| 225 | state.longitude >= |
| 226 | state.longitude <= |
| 227 | ); |
| 228 | |
| 229 | return { |
| 230 | time: data.time |
| 231 | states: validStates, |
| 232 | }; |
| 233 | } catch (error) |
| 234 | console.error('OpenSky API error: |
| 235 | if (error instanceof |
| 236 | throw error; |
| 237 | } |
| 238 | throw new HttpException( |
| 239 | 'Failed to fetch aircraft data from OpenSky Network', |
| 240 | HttpStatus.INTERNAL_SERVER_ERROR, |
| 241 | ); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | /** |
| 246 | * Get aircraft states for a specific aircraft by ICAO24 code |
| 247 | */ |
| 248 | async getAircraftState(icao24 |
| 249 | try { |
| 250 | // Ensure we have a valid token |
| 251 | const token = |
| 252 | |
| 253 | const url = |
| 254 | url.searchParams.append |
| 255 | |
| 256 | const headers: |
| 257 | |
| 258 | // Add Bearer token if available |
| 259 | if (token) { |
| 260 | headers['Authorization'] |
| 261 | } |
| 262 | |
| 263 | const response = |
| 264 | headers, |
| 265 | }); |
| 266 | |
| 267 | if (!response.ok |
| 268 | if (response.status |
| 269 | // Token might be expired, try to generate a new one |
| 270 | console.log('Token expired, generating new one... |
| 271 | await this.redis |
| 272 | return this.getAircraftState |
| 273 | } |
| 274 | throw new HttpException( |
| 275 | `OpenSky API request failed with status ${response.status |
| 276 | HttpStatus.BAD_GATEWAY, |
| 277 | ); |
| 278 | } |
| 279 | |
| 280 | const data = |
| 281 | |
| 282 | if (!data.states |
| 283 | return null; |
| 284 | } |
| 285 | |
| 286 | const state = |
| 287 | if (!state || |
| 288 | return null; |
| 289 | } |
| 290 | |
| 291 | return { |
| 292 | icao24: state[0] |
| 293 | callsign: state[1] |
| 294 | origin_country: state[2] |
| 295 | time_position: state[3] |
| 296 | last_contact: state[4] |
| 297 | longitude: state[5] |
| 298 | latitude: state[6] |
| 299 | baro_altitude: state[7] |
| 300 | on_ground: state[8] |
| 301 | velocity: state[9] |
| 302 | true_track: state[10] |
| 303 | vertical_rate: state[11] |
| 304 | sensors: state[12] |
| 305 | geo_altitude: state[13] |
| 306 | squawk: state[14] |
| 307 | spi: state[15] |
| 308 | position_source: state[16] |
| 309 | }; |
| 310 | } catch (error) |
| 311 | console.error('OpenSky API error: |
| 312 | throw new HttpException( |
| 313 | 'Failed to fetch aircraft data from OpenSky Network', |
| 314 | HttpStatus.INTERNAL_SERVER_ERROR, |
| 315 | ); |
| 316 | } |
| 317 | } |
| 318 | } |