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