PollForToken polls the token endpoint until the user authorizes or the device code expires.
(ctx context.Context, deviceCode *DeviceCodeResponse)
| 220 | |
| 221 | // PollForToken polls the token endpoint until the user authorizes or the device code expires. |
| 222 | func (c *DeviceFlowClient) PollForToken(ctx context.Context, deviceCode *DeviceCodeResponse) (*KimiTokenData, error) { |
| 223 | if deviceCode == nil { |
| 224 | return nil, fmt.Errorf("kimi: device code is nil") |
| 225 | } |
| 226 | |
| 227 | interval := time.Duration(deviceCode.Interval) * time.Second |
| 228 | if interval < defaultPollInterval { |
| 229 | interval = defaultPollInterval |
| 230 | } |
| 231 | |
| 232 | deadline := time.Now().Add(maxPollDuration) |
| 233 | if deviceCode.ExpiresIn > 0 { |
| 234 | codeDeadline := time.Now().Add(time.Duration(deviceCode.ExpiresIn) * time.Second) |
| 235 | if codeDeadline.Before(deadline) { |
| 236 | deadline = codeDeadline |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | ticker := time.NewTicker(interval) |
| 241 | defer ticker.Stop() |
| 242 | |
| 243 | for { |
| 244 | select { |
| 245 | case <-ctx.Done(): |
| 246 | return nil, fmt.Errorf("kimi: context cancelled: %w", ctx.Err()) |
| 247 | case <-ticker.C: |
| 248 | if time.Now().After(deadline) { |
| 249 | return nil, fmt.Errorf("kimi: device code expired") |
| 250 | } |
| 251 | |
| 252 | token, pollErr, shouldContinue := c.exchangeDeviceCode(ctx, deviceCode.DeviceCode) |
| 253 | if token != nil { |
| 254 | return token, nil |
| 255 | } |
| 256 | if !shouldContinue { |
| 257 | return nil, pollErr |
| 258 | } |
| 259 | // Continue polling |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // exchangeDeviceCode attempts to exchange the device code for an access token. |
| 265 | // Returns (token, error, shouldContinue). |
no test coverage detected