Initial commit

Signed-off-by: Thomas Klaehn <thomas.klaehn@perinet.io>
This commit is contained in:
Thomas Klaehn
2026-02-10 11:47:49 +01:00
commit c54fa58c35
17 changed files with 1834 additions and 0 deletions

90
internal/client/auth.go Normal file
View File

@@ -0,0 +1,90 @@
package client
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
"golang.org/x/oauth2"
)
// TokenCache handles token persistence
type TokenCache struct {
filePath string
}
// NewTokenCache creates a new token cache
func NewTokenCache(filePath string) *TokenCache {
return &TokenCache{filePath: filePath}
}
// Load loads a token from cache
func (tc *TokenCache) Load() (*oauth2.Token, error) {
// Check if file exists
if _, err := os.Stat(tc.filePath); os.IsNotExist(err) {
return nil, nil // No cached token
}
// Read file
data, err := os.ReadFile(tc.filePath)
if err != nil {
return nil, fmt.Errorf("failed to read token cache: %w", err)
}
// Unmarshal token
var token oauth2.Token
if err := json.Unmarshal(data, &token); err != nil {
return nil, fmt.Errorf("failed to unmarshal token: %w", err)
}
// Check if token is expired
if token.Expiry.Before(time.Now()) {
return nil, nil // Token expired
}
return &token, nil
}
// Save saves a token to cache
func (tc *TokenCache) Save(token *oauth2.Token) error {
// Create directory if it doesn't exist
dir := filepath.Dir(tc.filePath)
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create token cache directory: %w", err)
}
// Marshal token
data, err := json.MarshalIndent(token, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal token: %w", err)
}
// Write to file with restricted permissions
if err := os.WriteFile(tc.filePath, data, 0600); err != nil {
return fmt.Errorf("failed to write token cache: %w", err)
}
return nil
}
// Authenticate authenticates with Zwift using username and password
func Authenticate(ctx context.Context, username, password string, tokenCache *TokenCache) (*oauth2.Token, error) {
// Try to load cached token first
if tokenCache != nil {
token, err := tokenCache.Load()
if err == nil && token != nil && token.Valid() {
return token, nil
}
}
// Authenticate with username/password
// Note: The gravl library handles the actual OAuth2 flow
// We'll use the credentials directly with the client
// For now, we'll return nil as the gravl client handles authentication
// This function serves as a placeholder for explicit token management
return nil, fmt.Errorf("authentication handled by gravl client")
}

125
internal/client/client.go Normal file
View File

@@ -0,0 +1,125 @@
package client
import (
"context"
"fmt"
"io"
"net/http"
"time"
"github.com/bzimmer/activity"
"github.com/bzimmer/activity/zwift"
"golang.org/x/time/rate"
)
// Client wraps the Zwift API client with rate limiting and retry logic
type Client struct {
client *zwift.Client
rateLimiter *rate.Limiter
maxRetries int
athleteID int64 // Cached athlete ID
}
// NewClient creates a new Zwift client
func NewClient(username, password string, rateLimit, maxRetries int) (*Client, error) {
// Create HTTP client
httpClient := &http.Client{
Timeout: 30 * time.Second,
}
// Create rate limiter (requests per second)
limiter := rate.NewLimiter(rate.Limit(rateLimit), rateLimit*2)
// Create Zwift client with credentials
zwiftClient, err := zwift.NewClient(
zwift.WithHTTPClient(httpClient),
zwift.WithRateLimiter(limiter),
zwift.WithTokenRefresh(username, password),
)
if err != nil {
return nil, fmt.Errorf("failed to create Zwift client: %w", err)
}
return &Client{
client: zwiftClient,
rateLimiter: limiter,
maxRetries: maxRetries,
}, nil
}
// GetProfile gets the authenticated user's profile and caches the athlete ID
func (c *Client) GetProfile(ctx context.Context) (int64, error) {
// Return cached athlete ID if available
if c.athleteID != 0 {
return c.athleteID, nil
}
// Get profile from Zwift (using "me" as the profile ID)
profile, err := c.client.Profile.Profile(ctx, zwift.Me)
if err != nil {
return 0, fmt.Errorf("failed to get profile: %w", err)
}
// Cache athlete ID
c.athleteID = profile.ID
return profile.ID, nil
}
// ListRecentActivities lists recent activities for the athlete
func (c *Client) ListRecentActivities(ctx context.Context, athleteID int64, limit int) ([]*zwift.Activity, error) {
// Create pagination spec
spec := activity.Pagination{
Total: limit,
}
// List activities from Zwift
activities, err := c.client.Activity.Activities(ctx, athleteID, spec)
if err != nil {
return nil, fmt.Errorf("failed to list activities: %w", err)
}
return activities, nil
}
// DownloadFIT downloads the FIT file for an activity
func (c *Client) DownloadFIT(ctx context.Context, athleteID, activityID int64) ([]byte, string, error) {
// Retry logic
var lastErr error
for attempt := 0; attempt < c.maxRetries; attempt++ {
if attempt > 0 {
// Exponential backoff
backoff := time.Duration(1<<uint(attempt)) * time.Second
select {
case <-ctx.Done():
return nil, "", ctx.Err()
case <-time.After(backoff):
}
}
// Export FIT file
export, err := c.client.Activity.Export(ctx, activityID)
if err != nil {
lastErr = err
continue
}
// Read data from reader
data, err := io.ReadAll(export.Reader)
if err != nil {
lastErr = err
continue
}
// Return data and filename
return data, export.Filename, nil
}
return nil, "", fmt.Errorf("failed to download FIT file after %d attempts: %w", c.maxRetries, lastErr)
}
// Close closes the client
func (c *Client) Close() error {
// Nothing to close for now
return nil
}