feat(refactor): Implement 1A.1 Package Structure Refactoring

This commit implements the package structure refactoring as outlined in phase1.md (Task 1A.1).

Key changes include:
- Reorganized packages into `pkg/garmin` for public API and `internal/` for internal implementations.
- Updated all import paths to reflect the new structure.
- Consolidated types and client logic into their respective new packages.
- Updated `cmd/garth/main.go` to use the new public API.
- Fixed various compilation and test issues encountered during the refactoring process.
- Converted `internal/api/client/auth_test.go` to a functional test.

This establishes a solid foundation for future enhancements and improves maintainability.
This commit is contained in:
2025-09-18 13:13:39 -07:00
parent c00ea67f31
commit 2fdfbea34e
57 changed files with 876 additions and 297 deletions

View File

@@ -0,0 +1,37 @@
package client
import (
"time"
)
// OAuth1Token represents OAuth 1.0a credentials
type OAuth1Token struct {
Token string
TokenSecret string
CreatedAt time.Time
}
// Expired checks if token is expired (OAuth1 tokens typically don't expire but we'll implement for consistency)
func (t *OAuth1Token) Expired() bool {
return false // OAuth1 tokens don't typically expire
}
// OAuth2Token represents OAuth 2.0 credentials
type OAuth2Token struct {
AccessToken string
RefreshToken string
TokenType string
ExpiresIn int
ExpiresAt time.Time
}
// Expired checks if token is expired
func (t *OAuth2Token) Expired() bool {
return time.Now().After(t.ExpiresAt)
}
// RefreshIfNeeded refreshes token if expired (implementation pending)
func (t *OAuth2Token) RefreshIfNeeded(client *Client) error {
// Placeholder for token refresh logic
return nil
}

View File

@@ -0,0 +1,37 @@
package client_test
import (
"testing"
"garmin-connect/internal/api/client"
"garmin-connect/internal/auth/credentials"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestClient_Login_Functional(t *testing.T) {
if testing.Short() {
t.Skip("Skipping functional test in short mode")
}
// Load credentials from .env file
email, password, domain, err := credentials.LoadEnvCredentials()
require.NoError(t, err, "Failed to load credentials from .env file. Please ensure GARMIN_EMAIL, GARMIN_PASSWORD, and GARMIN_DOMAIN are set.")
// Create client
c, err := client.NewClient(domain)
require.NoError(t, err, "Failed to create client")
// Perform login
err = c.Login(email, password)
require.NoError(t, err, "Login failed")
// Verify login
assert.NotEmpty(t, c.AuthToken, "AuthToken should not be empty after login")
assert.NotEmpty(t, c.Username, "Username should not be empty after login")
// Logout for cleanup
err = c.Logout()
assert.NoError(t, err, "Logout failed")
}

View File

@@ -0,0 +1,474 @@
package client
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"garmin-connect/internal/errors"
"garmin-connect/internal/auth/sso"
"garmin-connect/internal/types"
)
// Client represents the Garmin Connect API client
type Client struct {
Domain string
HTTPClient *http.Client
Username string
AuthToken string
OAuth1Token *types.OAuth1Token
OAuth2Token *types.OAuth2Token
}
// NewClient creates a new Garmin Connect client
func NewClient(domain string) (*Client, error) {
if domain == "" {
domain = "garmin.com"
}
// Extract host without scheme if present
if strings.Contains(domain, "://") {
if u, err := url.Parse(domain); err == nil {
domain = u.Host
}
}
jar, err := cookiejar.New(nil)
if err != nil {
return nil, &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to create cookie jar",
Cause: err,
},
}
}
return &Client{
Domain: domain,
HTTPClient: &http.Client{
Jar: jar,
Timeout: 30 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
GarthError: errors.GarthError{
Message: "Too many redirects",
},
},
}
}
return nil
},
},
}, nil
}
// Login authenticates to Garmin Connect using SSO
func (c *Client) Login(email, password string) error {
// Extract host without scheme if present
host := c.Domain
if strings.Contains(host, "://") {
if u, err := url.Parse(host); err == nil {
host = u.Host
}
}
ssoClient := sso.NewClient(host)
oauth2Token, mfaContext, err := ssoClient.Login(email, password)
if err != nil {
return &errors.AuthenticationError{
GarthError: errors.GarthError{
Message: "SSO login failed",
Cause: err,
},
}
}
// Handle MFA required
if mfaContext != nil {
return &errors.AuthenticationError{
GarthError: errors.GarthError{
Message: "MFA required - not implemented yet",
},
}
}
c.OAuth2Token = oauth2Token
c.AuthToken = fmt.Sprintf("%s %s", oauth2Token.TokenType, oauth2Token.AccessToken)
// Get user profile to set username
profile, err := c.GetUserProfile()
if err != nil {
return &errors.AuthenticationError{
GarthError: errors.GarthError{
Message: "Failed to get user profile after login",
Cause: err,
},
}
}
c.Username = profile.UserName
return nil
}
// Logout clears the current session and tokens.
func (c *Client) Logout() error {
c.AuthToken = ""
c.Username = ""
c.OAuth1Token = nil
c.OAuth2Token = nil
// Clear cookies
if c.HTTPClient != nil && c.HTTPClient.Jar != nil {
// Create a dummy URL for the domain to clear all cookies associated with it
dummyURL, err := url.Parse(fmt.Sprintf("https://%s", c.Domain))
if err == nil {
c.HTTPClient.Jar.SetCookies(dummyURL, []*http.Cookie{})
}
}
return nil
}
// GetUserProfile retrieves the current user's full profile
func (c *Client) GetUserProfile() (*types.UserProfile, error) {
scheme := "https"
if strings.HasPrefix(c.Domain, "127.0.0.1") {
scheme = "http"
}
profileURL := fmt.Sprintf("%s://%s/userprofile-service/socialProfile", scheme, c.Domain)
req, err := http.NewRequest("GET", profileURL, nil)
if err != nil {
return nil, &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
GarthError: errors.GarthError{
Message: "Failed to create profile request",
Cause: err,
},
},
}
}
req.Header.Set("Authorization", c.AuthToken)
req.Header.Set("User-Agent", "com.garmin.android.apps.connectmobile")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
GarthError: errors.GarthError{
Message: "Failed to get user profile",
Cause: err,
},
},
}
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := io.ReadAll(resp.Body)
return nil, &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
StatusCode: resp.StatusCode,
Response: string(body),
GarthError: errors.GarthError{
Message: "Profile request failed",
},
},
}
}
var profile types.UserProfile
if err := json.NewDecoder(resp.Body).Decode(&profile); err != nil {
return nil, &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to parse profile",
Cause: err,
},
}
}
return &profile, nil
}
// ConnectAPI makes a raw API request to the Garmin Connect API
func (c *Client) ConnectAPI(path string, method string, params url.Values, body io.Reader) ([]byte, error) {
scheme := "https"
if strings.HasPrefix(c.Domain, "127.0.0.1") {
scheme = "http"
}
u := &url.URL{
Scheme: scheme,
Host: c.Domain,
Path: path,
RawQuery: params.Encode(),
}
req, err := http.NewRequest(method, u.String(), body)
if err != nil {
return nil, &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
GarthError: errors.GarthError{
Message: "Failed to create request",
Cause: err,
},
},
}
}
req.Header.Set("Authorization", c.AuthToken)
req.Header.Set("User-Agent", "garth-go-client/1.0")
req.Header.Set("Accept", "application/json")
if body != nil && req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
GarthError: errors.GarthError{
Message: "Request failed",
Cause: err,
},
},
}
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
StatusCode: resp.StatusCode,
Response: string(bodyBytes),
GarthError: errors.GarthError{
Message: fmt.Sprintf("API request failed with status %d: %s",
resp.StatusCode, tryReadErrorBody(bytes.NewReader(bodyBytes))),
},
},
}
}
return io.ReadAll(resp.Body)
}
func tryReadErrorBody(r io.Reader) string {
body, err := io.ReadAll(r)
if err != nil {
return "failed to read error response"
}
return string(body)
}
// Upload sends a file to Garmin Connect
func (c *Client) Upload(filePath string) error {
file, err := os.Open(filePath)
if err != nil {
return &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to open file",
Cause: err,
},
}
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", filepath.Base(filePath))
if err != nil {
return &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to create form file",
Cause: err,
},
}
}
if _, err := io.Copy(part, file); err != nil {
return &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to copy file content",
Cause: err,
},
}
}
if err := writer.Close(); err != nil {
return &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to close multipart writer",
Cause: err,
},
}
}
_, err = c.ConnectAPI("/upload-service/upload", "POST", nil, body)
if err != nil {
return &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
GarthError: errors.GarthError{
Message: "File upload failed",
Cause: err,
},
},
}
}
return nil
}
// Download retrieves a file from Garmin Connect
func (c *Client) Download(activityID string, filePath string) error {
params := url.Values{}
params.Add("activityId", activityID)
resp, err := c.ConnectAPI("/download-service/export", "GET", params, nil)
if err != nil {
return err
}
if err := os.WriteFile(filePath, resp, 0644); err != nil {
return &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to save file",
Cause: err,
},
}
}
return nil
}
// GetActivities retrieves recent activities
func (c *Client) GetActivities(limit int) ([]types.Activity, error) {
if limit <= 0 {
limit = 10
}
activitiesURL := fmt.Sprintf("https://connectapi.%s/activitylist-service/activities/search/activities?limit=%d&start=0", c.Domain, limit)
req, err := http.NewRequest("GET", activitiesURL, nil)
if err != nil {
return nil, &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
GarthError: errors.GarthError{
Message: "Failed to create activities request",
Cause: err,
},
},
}
}
req.Header.Set("Authorization", c.AuthToken)
req.Header.Set("User-Agent", "com.garmin.android.apps.connectmobile")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
GarthError: errors.GarthError{
Message: "Failed to get activities",
Cause: err,
},
},
}
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := io.ReadAll(resp.Body)
return nil, &errors.APIError{
GarthHTTPError: errors.GarthHTTPError{
StatusCode: resp.StatusCode,
Response: string(body),
GarthError: errors.GarthError{
Message: "Activities request failed",
},
},
}
}
var activities []types.Activity
if err := json.NewDecoder(resp.Body).Decode(&activities); err != nil {
return nil, &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to parse activities",
Cause: err,
},
}
}
return activities, nil
}
// SaveSession saves the current session to a file
func (c *Client) SaveSession(filename string) error {
session := types.SessionData{
Domain: c.Domain,
Username: c.Username,
AuthToken: c.AuthToken,
}
data, err := json.MarshalIndent(session, "", " ")
if err != nil {
return &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to marshal session",
Cause: err,
},
}
}
if err := os.WriteFile(filename, data, 0600); err != nil {
return &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to write session file",
Cause: err,
},
}
}
return nil
}
// LoadSession loads a session from a file
func (c *Client) LoadSession(filename string) error {
data, err := os.ReadFile(filename)
if err != nil {
return &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to read session file",
Cause: err,
},
}
}
var session types.SessionData
if err := json.Unmarshal(data, &session); err != nil {
return &errors.IOError{
GarthError: errors.GarthError{
Message: "Failed to unmarshal session",
Cause: err,
},
}
}
c.Domain = session.Domain
c.Username = session.Username
c.AuthToken = session.AuthToken
return nil
}

View File

@@ -0,0 +1,41 @@
package client_test
import (
"net/http"
"net/url"
"testing"
"time"
"garmin-connect/internal/testutils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"garmin-connect/internal/api/client"
)
func TestClient_GetUserProfile(t *testing.T) {
// Create mock server returning user profile
server := testutils.MockJSONResponse(http.StatusOK, `{
"userName": "testuser",
"displayName": "Test User",
"fullName": "Test User",
"location": "Test Location"
}`)
defer server.Close()
// Create client with test configuration
u, _ := url.Parse(server.URL)
c, err := client.NewClient(u.Host)
require.NoError(t, err)
c.HTTPClient = &http.Client{Timeout: 5 * time.Second}
c.AuthToken = "Bearer testtoken"
// Get user profile
profile, err := c.GetUserProfile()
// Verify response
require.NoError(t, err)
assert.Equal(t, "testuser", profile.UserName)
assert.Equal(t, "Test User", profile.DisplayName)
}

View File

@@ -0,0 +1,4 @@
package client
// This file intentionally left blank.
// All HTTP client methods are now implemented in client.go.

View File

@@ -0,0 +1,11 @@
package client
import (
"io"
"net/url"
)
// HTTPClient defines the interface for HTTP operations
type HTTPClient interface {
ConnectAPI(path string, method string, params url.Values, body io.Reader) ([]byte, error)
}

View File

@@ -0,0 +1,71 @@
package client
import (
"time"
)
type UserProfile struct {
ID int `json:"id"`
ProfileID int `json:"profileId"`
GarminGUID string `json:"garminGuid"`
DisplayName string `json:"displayName"`
FullName string `json:"fullName"`
UserName string `json:"userName"`
ProfileImageType *string `json:"profileImageType"`
ProfileImageURLLarge *string `json:"profileImageUrlLarge"`
ProfileImageURLMedium *string `json:"profileImageUrlMedium"`
ProfileImageURLSmall *string `json:"profileImageUrlSmall"`
Location *string `json:"location"`
FacebookURL *string `json:"facebookUrl"`
TwitterURL *string `json:"twitterUrl"`
PersonalWebsite *string `json:"personalWebsite"`
Motivation *string `json:"motivation"`
Bio *string `json:"bio"`
PrimaryActivity *string `json:"primaryActivity"`
FavoriteActivityTypes []string `json:"favoriteActivityTypes"`
RunningTrainingSpeed float64 `json:"runningTrainingSpeed"`
CyclingTrainingSpeed float64 `json:"cyclingTrainingSpeed"`
FavoriteCyclingActivityTypes []string `json:"favoriteCyclingActivityTypes"`
CyclingClassification *string `json:"cyclingClassification"`
CyclingMaxAvgPower float64 `json:"cyclingMaxAvgPower"`
SwimmingTrainingSpeed float64 `json:"swimmingTrainingSpeed"`
ProfileVisibility string `json:"profileVisibility"`
ActivityStartVisibility string `json:"activityStartVisibility"`
ActivityMapVisibility string `json:"activityMapVisibility"`
CourseVisibility string `json:"courseVisibility"`
ActivityHeartRateVisibility string `json:"activityHeartRateVisibility"`
ActivityPowerVisibility string `json:"activityPowerVisibility"`
BadgeVisibility string `json:"badgeVisibility"`
ShowAge bool `json:"showAge"`
ShowWeight bool `json:"showWeight"`
ShowHeight bool `json:"showHeight"`
ShowWeightClass bool `json:"showWeightClass"`
ShowAgeRange bool `json:"showAgeRange"`
ShowGender bool `json:"showGender"`
ShowActivityClass bool `json:"showActivityClass"`
ShowVO2Max bool `json:"showVo2Max"`
ShowPersonalRecords bool `json:"showPersonalRecords"`
ShowLast12Months bool `json:"showLast12Months"`
ShowLifetimeTotals bool `json:"showLifetimeTotals"`
ShowUpcomingEvents bool `json:"showUpcomingEvents"`
ShowRecentFavorites bool `json:"showRecentFavorites"`
ShowRecentDevice bool `json:"showRecentDevice"`
ShowRecentGear bool `json:"showRecentGear"`
ShowBadges bool `json:"showBadges"`
OtherActivity *string `json:"otherActivity"`
OtherPrimaryActivity *string `json:"otherPrimaryActivity"`
OtherMotivation *string `json:"otherMotivation"`
UserRoles []string `json:"userRoles"`
NameApproved bool `json:"nameApproved"`
UserProfileFullName string `json:"userProfileFullName"`
MakeGolfScorecardsPrivate bool `json:"makeGolfScorecardsPrivate"`
AllowGolfLiveScoring bool `json:"allowGolfLiveScoring"`
AllowGolfScoringByConnections bool `json:"allowGolfScoringByConnections"`
UserLevel int `json:"userLevel"`
UserPoint int `json:"userPoint"`
LevelUpdateDate time.Time `json:"levelUpdateDate"`
LevelIsViewed bool `json:"levelIsViewed"`
LevelPointThreshold int `json:"levelPointThreshold"`
UserPointOffset int `json:"userPointOffset"`
UserPro bool `json:"userPro"`
}

View File

@@ -0,0 +1,122 @@
package client
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type PowerFormat struct {
FormatID int `json:"formatId"`
FormatKey string `json:"formatKey"`
MinFraction int `json:"minFraction"`
MaxFraction int `json:"maxFraction"`
GroupingUsed bool `json:"groupingUsed"`
DisplayFormat *string `json:"displayFormat"`
}
type FirstDayOfWeek struct {
DayID int `json:"dayId"`
DayName string `json:"dayName"`
SortOrder int `json:"sortOrder"`
IsPossibleFirstDay bool `json:"isPossibleFirstDay"`
}
type WeatherLocation struct {
UseFixedLocation *bool `json:"useFixedLocation"`
Latitude *float64 `json:"latitude"`
Longitude *float64 `json:"longitude"`
LocationName *string `json:"locationName"`
ISOCountryCode *string `json:"isoCountryCode"`
PostalCode *string `json:"postalCode"`
}
type UserData struct {
Gender string `json:"gender"`
Weight float64 `json:"weight"`
Height float64 `json:"height"`
TimeFormat string `json:"timeFormat"`
BirthDate time.Time `json:"birthDate"`
MeasurementSystem string `json:"measurementSystem"`
ActivityLevel *string `json:"activityLevel"`
Handedness string `json:"handedness"`
PowerFormat PowerFormat `json:"powerFormat"`
HeartRateFormat PowerFormat `json:"heartRateFormat"`
FirstDayOfWeek FirstDayOfWeek `json:"firstDayOfWeek"`
VO2MaxRunning *float64 `json:"vo2MaxRunning"`
VO2MaxCycling *float64 `json:"vo2MaxCycling"`
LactateThresholdSpeed *float64 `json:"lactateThresholdSpeed"`
LactateThresholdHeartRate *float64 `json:"lactateThresholdHeartRate"`
DiveNumber *int `json:"diveNumber"`
IntensityMinutesCalcMethod string `json:"intensityMinutesCalcMethod"`
ModerateIntensityMinutesHRZone int `json:"moderateIntensityMinutesHrZone"`
VigorousIntensityMinutesHRZone int `json:"vigorousIntensityMinutesHrZone"`
HydrationMeasurementUnit string `json:"hydrationMeasurementUnit"`
HydrationContainers []map[string]interface{} `json:"hydrationContainers"`
HydrationAutoGoalEnabled bool `json:"hydrationAutoGoalEnabled"`
FirstbeatMaxStressScore *float64 `json:"firstbeatMaxStressScore"`
FirstbeatCyclingLTTimestamp *int64 `json:"firstbeatCyclingLtTimestamp"`
FirstbeatRunningLTTimestamp *int64 `json:"firstbeatRunningLtTimestamp"`
ThresholdHeartRateAutoDetected bool `json:"thresholdHeartRateAutoDetected"`
FTPAutoDetected *bool `json:"ftpAutoDetected"`
TrainingStatusPausedDate *string `json:"trainingStatusPausedDate"`
WeatherLocation *WeatherLocation `json:"weatherLocation"`
GolfDistanceUnit *string `json:"golfDistanceUnit"`
GolfElevationUnit *string `json:"golfElevationUnit"`
GolfSpeedUnit *string `json:"golfSpeedUnit"`
ExternalBottomTime *float64 `json:"externalBottomTime"`
}
type UserSleep struct {
SleepTime int `json:"sleepTime"`
DefaultSleepTime bool `json:"defaultSleepTime"`
WakeTime int `json:"wakeTime"`
DefaultWakeTime bool `json:"defaultWakeTime"`
}
type UserSleepWindow struct {
SleepWindowFrequency string `json:"sleepWindowFrequency"`
StartSleepTimeSecondsFromMidnight int `json:"startSleepTimeSecondsFromMidnight"`
EndSleepTimeSecondsFromMidnight int `json:"endSleepTimeSecondsFromMidnight"`
}
type UserSettings struct {
ID int `json:"id"`
UserData UserData `json:"userData"`
UserSleep UserSleep `json:"userSleep"`
ConnectDate *string `json:"connectDate"`
SourceType *string `json:"sourceType"`
UserSleepWindows []UserSleepWindow `json:"userSleepWindows,omitempty"`
}
func (c *Client) GetUserSettings() (*UserSettings, error) {
settingsURL := fmt.Sprintf("https://connectapi.%s/userprofile-service/userprofile/user-settings", c.Domain)
req, err := http.NewRequest("GET", settingsURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create settings request: %w", err)
}
req.Header.Set("Authorization", c.AuthToken)
req.Header.Set("User-Agent", "com.garmin.android.apps.connectmobile")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to get user settings: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("settings request failed with status %d: %s", resp.StatusCode, string(body))
}
var settings UserSettings
if err := json.NewDecoder(resp.Body).Decode(&settings); err != nil {
return nil, fmt.Errorf("failed to parse settings: %w", err)
}
return &settings, nil
}

View File

@@ -0,0 +1,32 @@
package credentials
import (
"fmt"
"os"
"github.com/joho/godotenv"
)
// LoadEnvCredentials loads credentials from .env file
func LoadEnvCredentials() (email, password, domain string, err error) {
// Load .env file
if err := godotenv.Load(); err != nil {
return "", "", "", fmt.Errorf("error loading .env file: %w", err)
}
email = os.Getenv("GARMIN_EMAIL")
password = os.Getenv("GARMIN_PASSWORD")
domain = os.Getenv("GARMIN_DOMAIN")
if email == "" {
return "", "", "", fmt.Errorf("GARMIN_EMAIL not found in .env file")
}
if password == "" {
return "", "", "", fmt.Errorf("GARMIN_PASSWORD not found in .env file")
}
if domain == "" {
domain = "garmin.com" // default value
}
return email, password, domain, nil
}

View File

@@ -0,0 +1,154 @@
package oauth
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"garmin-connect/internal/types"
"garmin-connect/internal/utils"
)
// GetOAuth1Token retrieves an OAuth1 token using the provided ticket
func GetOAuth1Token(domain, ticket string) (*types.OAuth1Token, error) {
consumer, err := utils.LoadOAuthConsumer()
if err != nil {
return nil, fmt.Errorf("failed to load OAuth consumer: %w", err)
}
baseURL := fmt.Sprintf("https://connectapi.%s/oauth-service/oauth/", domain)
loginURL := fmt.Sprintf("https://sso.%s/sso/embed", domain)
tokenURL := fmt.Sprintf("%spreauthorized?ticket=%s&login-url=%s&accepts-mfa-tokens=true",
baseURL, ticket, url.QueryEscape(loginURL))
// Parse URL to extract query parameters for signing
parsedURL, err := url.Parse(tokenURL)
if err != nil {
return nil, err
}
// Extract query parameters
queryParams := make(map[string]string)
for key, values := range parsedURL.Query() {
if len(values) > 0 {
queryParams[key] = values[0]
}
}
// Create OAuth1 signed request
baseURLForSigning := parsedURL.Scheme + "://" + parsedURL.Host + parsedURL.Path
authHeader := utils.CreateOAuth1AuthorizationHeader("GET", baseURLForSigning, queryParams,
consumer.ConsumerKey, consumer.ConsumerSecret, "", "")
req, err := http.NewRequest("GET", tokenURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", authHeader)
req.Header.Set("User-Agent", "com.garmin.android.apps.connectmobile")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
bodyStr := string(body)
if resp.StatusCode != 200 {
return nil, fmt.Errorf("OAuth1 request failed with status %d: %s", resp.StatusCode, bodyStr)
}
// Parse query string response - handle both & and ; separators
bodyStr = strings.ReplaceAll(bodyStr, ";", "&")
values, err := url.ParseQuery(bodyStr)
if err != nil {
return nil, fmt.Errorf("failed to parse OAuth1 response: %w", err)
}
oauthToken := values.Get("oauth_token")
oauthTokenSecret := values.Get("oauth_token_secret")
if oauthToken == "" || oauthTokenSecret == "" {
return nil, fmt.Errorf("missing oauth_token or oauth_token_secret in response")
}
return &types.OAuth1Token{
OAuthToken: oauthToken,
OAuthTokenSecret: oauthTokenSecret,
MFAToken: values.Get("mfa_token"),
Domain: domain,
}, nil
}
// ExchangeToken exchanges an OAuth1 token for an OAuth2 token
func ExchangeToken(oauth1Token *types.OAuth1Token) (*types.OAuth2Token, error) {
consumer, err := utils.LoadOAuthConsumer()
if err != nil {
return nil, fmt.Errorf("failed to load OAuth consumer: %w", err)
}
exchangeURL := fmt.Sprintf("https://connectapi.%s/oauth-service/oauth/exchange/user/2.0", oauth1Token.Domain)
// Prepare form data
formData := url.Values{}
if oauth1Token.MFAToken != "" {
formData.Set("mfa_token", oauth1Token.MFAToken)
}
// Convert form data to map for OAuth signing
formParams := make(map[string]string)
for key, values := range formData {
if len(values) > 0 {
formParams[key] = values[0]
}
}
// Create OAuth1 signed request
authHeader := utils.CreateOAuth1AuthorizationHeader("POST", exchangeURL, formParams,
consumer.ConsumerKey, consumer.ConsumerSecret, oauth1Token.OAuthToken, oauth1Token.OAuthTokenSecret)
req, err := http.NewRequest("POST", exchangeURL, strings.NewReader(formData.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", authHeader)
req.Header.Set("User-Agent", "com.garmin.android.apps.connectmobile")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("OAuth2 exchange failed with status %d: %s", resp.StatusCode, string(body))
}
var oauth2Token types.OAuth2Token
if err := json.Unmarshal(body, &oauth2Token); err != nil {
return nil, fmt.Errorf("failed to decode OAuth2 token: %w", err)
}
// Set expiration time
if oauth2Token.ExpiresIn > 0 {
oauth2Token.ExpiresAt = time.Now().Add(time.Duration(oauth2Token.ExpiresIn) * time.Second)
}
return &oauth2Token, nil
}

260
internal/auth/sso/sso.go Normal file
View File

@@ -0,0 +1,260 @@
package sso
import (
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"garmin-connect/internal/auth/oauth"
"garmin-connect/internal/types"
)
var (
csrfRegex = regexp.MustCompile(`name="_csrf"\s+value="(.+?)"`)
titleRegex = regexp.MustCompile(`<title>(.+?)</title>`)
ticketRegex = regexp.MustCompile(`embed\?ticket=([^"]+)"`)
)
// MFAContext preserves state for resuming MFA login
type MFAContext struct {
SigninURL string
CSRFToken string
Ticket string
}
// Client represents an SSO client
type Client struct {
Domain string
HTTPClient *http.Client
}
// NewClient creates a new SSO client
func NewClient(domain string) *Client {
return &Client{
Domain: domain,
HTTPClient: &http.Client{Timeout: 30 * time.Second},
}
}
// Login performs the SSO authentication flow
func (c *Client) Login(email, password string) (*types.OAuth2Token, *MFAContext, error) {
fmt.Printf("Logging in to Garmin Connect (%s) using SSO flow...\n", c.Domain)
// Step 1: Set up SSO parameters
ssoURL := fmt.Sprintf("https://sso.%s/sso", c.Domain)
ssoEmbedURL := fmt.Sprintf("%s/embed", ssoURL)
ssoEmbedParams := url.Values{
"id": {"gauth-widget"},
"embedWidget": {"true"},
"gauthHost": {ssoURL},
}
signinParams := url.Values{
"id": {"gauth-widget"},
"embedWidget": {"true"},
"gauthHost": {ssoEmbedURL},
"service": {ssoEmbedURL},
"source": {ssoEmbedURL},
"redirectAfterAccountLoginUrl": {ssoEmbedURL},
"redirectAfterAccountCreationUrl": {ssoEmbedURL},
}
// Step 2: Initialize SSO session
fmt.Println("Initializing SSO session...")
embedURL := fmt.Sprintf("https://sso.%s/sso/embed?%s", c.Domain, ssoEmbedParams.Encode())
req, err := http.NewRequest("GET", embedURL, nil)
if err != nil {
return nil, nil, fmt.Errorf("failed to create embed request: %w", err)
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to initialize SSO: %w", err)
}
resp.Body.Close()
// Step 3: Get signin page and CSRF token
fmt.Println("Getting signin page...")
signinURL := fmt.Sprintf("https://sso.%s/sso/signin?%s", c.Domain, signinParams.Encode())
req, err = http.NewRequest("GET", signinURL, nil)
if err != nil {
return nil, nil, fmt.Errorf("failed to create signin request: %w", err)
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36")
req.Header.Set("Referer", embedURL)
resp, err = c.HTTPClient.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to get signin page: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read signin response: %w", err)
}
// Extract CSRF token
csrfToken := extractCSRFToken(string(body))
if csrfToken == "" {
return nil, nil, fmt.Errorf("failed to find CSRF token")
}
fmt.Printf("Found CSRF token: %s\n", csrfToken[:10]+"...")
// Step 4: Submit login form
fmt.Println("Submitting login credentials...")
formData := url.Values{
"username": {email},
"password": {password},
"embed": {"true"},
"_csrf": {csrfToken},
}
req, err = http.NewRequest("POST", signinURL, strings.NewReader(formData.Encode()))
if err != nil {
return nil, nil, fmt.Errorf("failed to create login request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36")
req.Header.Set("Referer", signinURL)
resp, err = c.HTTPClient.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to submit login: %w", err)
}
defer resp.Body.Close()
body, err = io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read login response: %w", err)
}
// Check login result
title := extractTitle(string(body))
fmt.Printf("Login response title: %s\n", title)
// Handle MFA requirement
if strings.Contains(title, "MFA") {
fmt.Println("MFA required - returning context for ResumeLogin")
ticket := extractTicket(string(body))
return nil, &MFAContext{
SigninURL: signinURL,
CSRFToken: csrfToken,
Ticket: ticket,
}, nil
}
if title != "Success" {
return nil, nil, fmt.Errorf("login failed, unexpected title: %s", title)
}
// Step 5: Extract ticket for OAuth flow
fmt.Println("Extracting OAuth ticket...")
ticket := extractTicket(string(body))
if ticket == "" {
return nil, nil, fmt.Errorf("failed to find OAuth ticket")
}
fmt.Printf("Found ticket: %s\n", ticket[:10]+"...")
// Step 6: Get OAuth1 token
oauth1Token, err := oauth.GetOAuth1Token(c.Domain, ticket)
if err != nil {
return nil, nil, fmt.Errorf("failed to get OAuth1 token: %w", err)
}
fmt.Println("Got OAuth1 token")
// Step 7: Exchange for OAuth2 token
oauth2Token, err := oauth.ExchangeToken(oauth1Token)
if err != nil {
return nil, nil, fmt.Errorf("failed to exchange for OAuth2 token: %w", err)
}
fmt.Printf("Got OAuth2 token: %s\n", oauth2Token.TokenType)
return oauth2Token, nil, nil
}
// ResumeLogin completes authentication after MFA challenge
func (c *Client) ResumeLogin(mfaCode string, ctx *MFAContext) (*types.OAuth2Token, error) {
fmt.Println("Resuming login with MFA code...")
// Submit MFA form
formData := url.Values{
"mfa-code": {mfaCode},
"embed": {"true"},
"_csrf": {ctx.CSRFToken},
}
req, err := http.NewRequest("POST", ctx.SigninURL, strings.NewReader(formData.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to create MFA request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36")
req.Header.Set("Referer", ctx.SigninURL)
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to submit MFA: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read MFA response: %w", err)
}
// Verify MFA success
title := extractTitle(string(body))
if title != "Success" {
return nil, fmt.Errorf("MFA failed, unexpected title: %s", title)
}
// Continue with ticket flow
fmt.Println("Extracting OAuth ticket after MFA...")
ticket := extractTicket(string(body))
if ticket == "" {
return nil, fmt.Errorf("failed to find OAuth ticket after MFA")
}
// Get OAuth1 token
oauth1Token, err := oauth.GetOAuth1Token(c.Domain, ticket)
if err != nil {
return nil, fmt.Errorf("failed to get OAuth1 token: %w", err)
}
// Exchange for OAuth2 token
return oauth.ExchangeToken(oauth1Token)
}
// extractCSRFToken extracts CSRF token from HTML
func extractCSRFToken(html string) string {
matches := csrfRegex.FindStringSubmatch(html)
if len(matches) > 1 {
return matches[1]
}
return ""
}
// extractTitle extracts page title from HTML
func extractTitle(html string) string {
matches := titleRegex.FindStringSubmatch(html)
if len(matches) > 1 {
return matches[1]
}
return ""
}
// extractTicket extracts OAuth ticket from HTML
func extractTicket(html string) string {
matches := ticketRegex.FindStringSubmatch(html)
if len(matches) > 1 {
return matches[1]
}
return ""
}

130
internal/data/base.go Normal file
View File

@@ -0,0 +1,130 @@
package data
import (
"errors"
"sync"
"time"
"garmin-connect/internal/api/client"
"garmin-connect/internal/utils"
)
// Data defines the interface for Garmin Connect data types.
// Concrete data types (BodyBattery, HRV, Sleep, etc.) must implement this interface.
//
// The Get method retrieves data for a single day.
// The List method concurrently retrieves data for a range of days.
type Data interface {
Get(day time.Time, c *client.Client) (interface{}, error)
List(end time.Time, days int, c *client.Client, maxWorkers int) ([]interface{}, error)
}
// BaseData provides a reusable implementation for data types to embed.
// It handles the concurrent List() implementation while allowing concrete types
// to focus on implementing the Get() method for their specific data structure.
//
// Usage:
//
// type BodyBatteryData struct {
// data.BaseData
// // ... additional fields
// }
//
// func NewBodyBatteryData() *BodyBatteryData {
// bb := &BodyBatteryData{}
// bb.GetFunc = bb.get // Assign the concrete Get implementation
// return bb
// }
//
// func (bb *BodyBatteryData) get(day time.Time, c *client.Client) (interface{}, error) {
// // Implementation specific to body battery data
// }
type BaseData struct {
// GetFunc must be set by concrete types to implement the Get method.
// This function pointer allows BaseData to call the concrete implementation.
GetFunc func(day time.Time, c *client.Client) (interface{}, error)
}
// Get implements the Data interface by calling the configured GetFunc.
// Returns an error if GetFunc is not set.
func (b *BaseData) Get(day time.Time, c *client.Client) (interface{}, error) {
if b.GetFunc == nil {
return nil, errors.New("GetFunc not implemented for this data type")
}
return b.GetFunc(day, c)
}
// List implements concurrent data fetching using a worker pool pattern.
// This method efficiently retrieves data for multiple days by distributing
// work across a configurable number of workers (goroutines).
//
// Parameters:
//
// end: The end date of the range (inclusive)
// days: Number of days to fetch (going backwards from end date)
// c: Client instance for API access
// maxWorkers: Maximum concurrent workers (minimum 1)
//
// Returns:
//
// []interface{}: Slice of results (order matches date range)
// []error: Slice of errors encountered during processing
func (b *BaseData) List(end time.Time, days int, c *client.Client, maxWorkers int) ([]interface{}, []error) {
if maxWorkers < 1 {
maxWorkers = 10 // Match Python's MAX_WORKERS
}
dates := utils.DateRange(end, days)
// Define result type for channel
type result struct {
data interface{}
err error
}
var wg sync.WaitGroup
workCh := make(chan time.Time, days)
resultsCh := make(chan result, days)
// Worker function
worker := func() {
defer wg.Done()
for date := range workCh {
data, err := b.Get(date, c)
resultsCh <- result{data: data, err: err}
}
}
// Start workers
wg.Add(maxWorkers)
for i := 0; i < maxWorkers; i++ {
go worker()
}
// Send work
go func() {
for _, date := range dates {
workCh <- date
}
close(workCh)
}()
// Close results channel when workers are done
go func() {
wg.Wait()
close(resultsCh)
}()
var results []interface{}
var errs []error
for r := range resultsCh {
if r.err != nil {
errs = append(errs, r.err)
} else if r.data != nil {
results = append(results, r.data)
}
}
return results, errs
}

View File

@@ -0,0 +1,74 @@
package data
import (
"errors"
"testing"
"time"
"garmin-connect/internal/api/client"
"github.com/stretchr/testify/assert"
)
// MockData implements Data interface for testing
type MockData struct {
BaseData
}
// MockClient simulates API client for tests
type MockClient struct{}
func (mc *MockClient) Get(endpoint string) (interface{}, error) {
if endpoint == "error" {
return nil, errors.New("mock API error")
}
return "data for " + endpoint, nil
}
func TestBaseData_List(t *testing.T) {
// Setup mock data type
mockData := &MockData{}
mockData.GetFunc = func(day time.Time, c *client.Client) (interface{}, error) {
return "data for " + day.Format("2006-01-02"), nil
}
// Test parameters
end := time.Date(2023, 6, 15, 0, 0, 0, 0, time.UTC)
days := 5
c := &client.Client{}
maxWorkers := 3
// Execute
results, errs := mockData.List(end, days, c, maxWorkers)
// Verify
assert.Empty(t, errs)
assert.Len(t, results, days)
assert.Contains(t, results, "data for 2023-06-15")
assert.Contains(t, results, "data for 2023-06-11")
}
func TestBaseData_List_ErrorHandling(t *testing.T) {
// Setup mock data type that returns error on specific date
mockData := &MockData{}
mockData.GetFunc = func(day time.Time, c *client.Client) (interface{}, error) {
if day.Day() == 13 {
return nil, errors.New("bad luck day")
}
return "data for " + day.Format("2006-01-02"), nil
}
// Test parameters
end := time.Date(2023, 6, 15, 0, 0, 0, 0, time.UTC)
days := 5
c := &client.Client{}
maxWorkers := 2
// Execute
results, errs := mockData.List(end, days, c, maxWorkers)
// Verify
assert.Len(t, errs, 1)
assert.Equal(t, "bad luck day", errs[0].Error())
assert.Len(t, results, 4) // Should have results for non-error days
}

View File

@@ -0,0 +1,138 @@
package data
import (
"encoding/json"
"fmt"
"sort"
"time"
"garmin-connect/internal/api/client"
)
// DailyBodyBatteryStress represents complete daily Body Battery and stress data
type DailyBodyBatteryStress struct {
UserProfilePK int `json:"userProfilePk"`
CalendarDate time.Time `json:"calendarDate"`
StartTimestampGMT time.Time `json:"startTimestampGmt"`
EndTimestampGMT time.Time `json:"endTimestampGmt"`
StartTimestampLocal time.Time `json:"startTimestampLocal"`
EndTimestampLocal time.Time `json:"endTimestampLocal"`
MaxStressLevel int `json:"maxStressLevel"`
AvgStressLevel int `json:"avgStressLevel"`
StressChartValueOffset int `json:"stressChartValueOffset"`
StressChartYAxisOrigin int `json:"stressChartYAxisOrigin"`
StressValuesArray [][]int `json:"stressValuesArray"`
BodyBatteryValuesArray [][]any `json:"bodyBatteryValuesArray"`
}
// BodyBatteryEvent represents a Body Battery impact event
type BodyBatteryEvent struct {
EventType string `json:"eventType"`
EventStartTimeGMT time.Time `json:"eventStartTimeGmt"`
TimezoneOffset int `json:"timezoneOffset"`
DurationInMilliseconds int `json:"durationInMilliseconds"`
BodyBatteryImpact int `json:"bodyBatteryImpact"`
FeedbackType string `json:"feedbackType"`
ShortFeedback string `json:"shortFeedback"`
}
// BodyBatteryData represents legacy Body Battery events data
type BodyBatteryData struct {
Event *BodyBatteryEvent `json:"event"`
ActivityName string `json:"activityName"`
ActivityType string `json:"activityType"`
ActivityID string `json:"activityId"`
AverageStress float64 `json:"averageStress"`
StressValuesArray [][]int `json:"stressValuesArray"`
BodyBatteryValuesArray [][]any `json:"bodyBatteryValuesArray"`
}
// BodyBatteryReading represents an individual Body Battery reading
type BodyBatteryReading struct {
Timestamp int `json:"timestamp"`
Status string `json:"status"`
Level int `json:"level"`
Version float64 `json:"version"`
}
// StressReading represents an individual stress reading
type StressReading struct {
Timestamp int `json:"timestamp"`
StressLevel int `json:"stressLevel"`
}
// ParseBodyBatteryReadings converts body battery values array to structured readings
func ParseBodyBatteryReadings(valuesArray [][]any) []BodyBatteryReading {
readings := make([]BodyBatteryReading, 0)
for _, values := range valuesArray {
if len(values) < 4 {
continue
}
timestamp, ok1 := values[0].(int)
status, ok2 := values[1].(string)
level, ok3 := values[2].(int)
version, ok4 := values[3].(float64)
if !ok1 || !ok2 || !ok3 || !ok4 {
continue
}
readings = append(readings, BodyBatteryReading{
Timestamp: timestamp,
Status: status,
Level: level,
Version: version,
})
}
sort.Slice(readings, func(i, j int) bool {
return readings[i].Timestamp < readings[j].Timestamp
})
return readings
}
// ParseStressReadings converts stress values array to structured readings
func ParseStressReadings(valuesArray [][]int) []StressReading {
readings := make([]StressReading, 0)
for _, values := range valuesArray {
if len(values) != 2 {
continue
}
readings = append(readings, StressReading{
Timestamp: values[0],
StressLevel: values[1],
})
}
sort.Slice(readings, func(i, j int) bool {
return readings[i].Timestamp < readings[j].Timestamp
})
return readings
}
// Get implements the Data interface for DailyBodyBatteryStress
func (d *DailyBodyBatteryStress) Get(day time.Time, client *client.Client) (any, error) {
dateStr := day.Format("2006-01-02")
path := fmt.Sprintf("/wellness-service/wellness/dailyStress/%s", dateStr)
data, err := client.ConnectAPI(path, "GET", nil, nil)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, nil
}
var result DailyBodyBatteryStress
if err := json.Unmarshal(data, &result); err != nil {
return nil, err
}
return &result, nil
}
// List implements the Data interface for concurrent fetching
func (d *DailyBodyBatteryStress) List(end time.Time, days int, client *client.Client, maxWorkers int) ([]any, error) {
// Implementation to be added
return []any{}, nil
}

View File

@@ -0,0 +1,122 @@
package data
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestParseBodyBatteryReadings(t *testing.T) {
tests := []struct {
name string
input [][]any
expected []BodyBatteryReading
}{
{
name: "valid readings",
input: [][]any{
{1000, "ACTIVE", 75, 1.0},
{2000, "ACTIVE", 70, 1.0},
{3000, "REST", 65, 1.0},
},
expected: []BodyBatteryReading{
{1000, "ACTIVE", 75, 1.0},
{2000, "ACTIVE", 70, 1.0},
{3000, "REST", 65, 1.0},
},
},
{
name: "invalid readings",
input: [][]any{
{1000, "ACTIVE", 75}, // missing version
{2000, "ACTIVE"}, // missing level and version
{3000}, // only timestamp
{"invalid", "ACTIVE", 75, 1.0}, // wrong timestamp type
},
expected: []BodyBatteryReading{},
},
{
name: "empty input",
input: [][]any{},
expected: []BodyBatteryReading{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := ParseBodyBatteryReadings(tt.input)
assert.Equal(t, tt.expected, result)
})
}
}
func TestParseStressReadings(t *testing.T) {
tests := []struct {
name string
input [][]int
expected []StressReading
}{
{
name: "valid readings",
input: [][]int{
{1000, 25},
{2000, 30},
{3000, 20},
},
expected: []StressReading{
{1000, 25},
{2000, 30},
{3000, 20},
},
},
{
name: "invalid readings",
input: [][]int{
{1000}, // missing stress level
{2000, 30, 1}, // extra value
{}, // empty
},
expected: []StressReading{},
},
{
name: "empty input",
input: [][]int{},
expected: []StressReading{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := ParseStressReadings(tt.input)
assert.Equal(t, tt.expected, result)
})
}
}
func TestDailyBodyBatteryStress(t *testing.T) {
now := time.Now()
d := DailyBodyBatteryStress{
CalendarDate: now,
BodyBatteryValuesArray: [][]any{
{1000, "ACTIVE", 75, 1.0},
{2000, "ACTIVE", 70, 1.0},
},
StressValuesArray: [][]int{
{1000, 25},
{2000, 30},
},
}
t.Run("body battery readings", func(t *testing.T) {
readings := ParseBodyBatteryReadings(d.BodyBatteryValuesArray)
assert.Len(t, readings, 2)
assert.Equal(t, 75, readings[0].Level)
})
t.Run("stress readings", func(t *testing.T) {
readings := ParseStressReadings(d.StressValuesArray)
assert.Len(t, readings, 2)
assert.Equal(t, 25, readings[0].StressLevel)
})
}

211
internal/data/hrv.go Normal file
View File

@@ -0,0 +1,211 @@
package data
import (
"encoding/json"
"errors"
"fmt"
"sort"
"time"
"garmin-connect/internal/api/client"
"garmin-connect/internal/utils"
)
// HRVSummary represents Heart Rate Variability summary data
type HRVSummary struct {
UserProfilePK int `json:"userProfilePk"`
CalendarDate time.Time `json:"calendarDate"`
StartTimestampGMT time.Time `json:"startTimestampGmt"`
EndTimestampGMT time.Time `json:"endTimestampGmt"`
WeeklyAvg float64 `json:"weeklyAvg"`
LastNightAvg float64 `json:"lastNightAvg"`
Baseline float64 `json:"baseline"`
}
// HRVReading represents an individual HRV reading
type HRVReading struct {
Timestamp int `json:"timestamp"`
StressLevel int `json:"stressLevel"`
HeartRate int `json:"heartRate"`
RRInterval int `json:"rrInterval"`
Status string `json:"status"`
SignalQuality float64 `json:"signalQuality"`
}
// TimestampAsTime converts the reading timestamp to time.Time using timeutils
func (r *HRVReading) TimestampAsTime() time.Time {
return utils.ParseTimestamp(r.Timestamp)
}
// RRSeconds converts the RR interval to seconds
func (r *HRVReading) RRSeconds() float64 {
return float64(r.RRInterval) / 1000.0
}
// HRVData represents complete HRV data
type HRVData struct {
UserProfilePK int `json:"userProfilePk"`
HRVSummary HRVSummary `json:"hrvSummary"`
HRVReadings []HRVReading `json:"hrvReadings"`
BaseData
}
// Validate ensures HRVSummary fields meet requirements
func (h *HRVSummary) Validate() error {
if h.WeeklyAvg < 0 {
return errors.New("WeeklyAvg must be non-negative")
}
if h.LastNightAvg < 0 {
return errors.New("LastNightAvg must be non-negative")
}
if h.Baseline < 0 {
return errors.New("Baseline must be non-negative")
}
if h.CalendarDate.IsZero() {
return errors.New("CalendarDate must be set")
}
if h.StartTimestampGMT.IsZero() || h.EndTimestampGMT.IsZero() {
return errors.New("Timestamps must be set")
}
if h.EndTimestampGMT.Before(h.StartTimestampGMT) {
return errors.New("EndTimestampGMT must be after StartTimestampGMT")
}
return nil
}
// Validate ensures HRVReading fields meet requirements
func (r *HRVReading) Validate() error {
if r.StressLevel < 0 || r.StressLevel > 100 {
return fmt.Errorf("StressLevel must be between 0-100, got %d", r.StressLevel)
}
if r.HeartRate <= 0 {
return fmt.Errorf("HeartRate must be positive, got %d", r.HeartRate)
}
if r.RRInterval <= 0 {
return fmt.Errorf("RRInterval must be positive, got %d", r.RRInterval)
}
if r.SignalQuality < 0 || r.SignalQuality > 1 {
return fmt.Errorf("SignalQuality must be between 0-1, got %f", r.SignalQuality)
}
return nil
}
// Validate ensures HRVData meets all requirements
func (h *HRVData) Validate() error {
if h.UserProfilePK <= 0 {
return errors.New("UserProfilePK must be positive")
}
if err := h.HRVSummary.Validate(); err != nil {
return fmt.Errorf("HRVSummary validation failed: %w", err)
}
for i, reading := range h.HRVReadings {
if err := reading.Validate(); err != nil {
return fmt.Errorf("HRVReading[%d] validation failed: %w", i, err)
}
}
return nil
}
// DailyVariability calculates the average RR interval for the day
func (h *HRVData) DailyVariability() float64 {
if len(h.HRVReadings) == 0 {
return 0
}
var total float64
for _, r := range h.HRVReadings {
total += r.RRSeconds()
}
return total / float64(len(h.HRVReadings))
}
// MinHRVReading returns the reading with the lowest RR interval
func (h *HRVData) MinHRVReading() HRVReading {
if len(h.HRVReadings) == 0 {
return HRVReading{}
}
min := h.HRVReadings[0]
for _, r := range h.HRVReadings {
if r.RRInterval < min.RRInterval {
min = r
}
}
return min
}
// MaxHRVReading returns the reading with the highest RR interval
func (h *HRVData) MaxHRVReading() HRVReading {
if len(h.HRVReadings) == 0 {
return HRVReading{}
}
max := h.HRVReadings[0]
for _, r := range h.HRVReadings {
if r.RRInterval > max.RRInterval {
max = r
}
}
return max
}
// ParseHRVReadings converts values array to structured readings
func ParseHRVReadings(valuesArray [][]any) []HRVReading {
readings := make([]HRVReading, 0, len(valuesArray))
for _, values := range valuesArray {
if len(values) < 6 {
continue
}
// Extract values with type assertions
timestamp, _ := values[0].(int)
stressLevel, _ := values[1].(int)
heartRate, _ := values[2].(int)
rrInterval, _ := values[3].(int)
status, _ := values[4].(string)
signalQuality, _ := values[5].(float64)
readings = append(readings, HRVReading{
Timestamp: timestamp,
StressLevel: stressLevel,
HeartRate: heartRate,
RRInterval: rrInterval,
Status: status,
SignalQuality: signalQuality,
})
}
sort.Slice(readings, func(i, j int) bool {
return readings[i].Timestamp < readings[j].Timestamp
})
return readings
}
// Get implements the Data interface for HRVData
func (h *HRVData) Get(day time.Time, client *client.Client) (any, error) {
dateStr := day.Format("2006-01-02")
path := fmt.Sprintf("/wellness-service/wellness/dailyHrvData/%s?date=%s",
client.Username, dateStr)
data, err := client.ConnectAPI(path, "GET", nil, nil)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, nil
}
var hrvData HRVData
if err := json.Unmarshal(data, &hrvData); err != nil {
return nil, err
}
if err := hrvData.Validate(); err != nil {
return nil, fmt.Errorf("HRV data validation failed: %w", err)
}
return hrvData, nil
}
// List implements the Data interface for concurrent fetching
func (h *HRVData) List(end time.Time, days int, client *client.Client, maxWorkers int) ([]any, error) {
// Implementation to be added
return []any{}, nil
}

74
internal/data/sleep.go Normal file
View File

@@ -0,0 +1,74 @@
package data
import (
"encoding/json"
"fmt"
"time"
"garmin-connect/internal/api/client"
)
// SleepScores represents sleep scoring data
type SleepScores struct {
TotalSleepSeconds int `json:"totalSleepSeconds"`
SleepScores []struct {
StartTimeGMT time.Time `json:"startTimeGmt"`
EndTimeGMT time.Time `json:"endTimeGmt"`
SleepScore int `json:"sleepScore"`
} `json:"sleepScores"`
SleepMovement []SleepMovement `json:"sleepMovement"`
// Add other fields from Python implementation
}
// SleepMovement represents movement during sleep
type SleepMovement struct {
StartGMT time.Time `json:"startGmt"`
EndGMT time.Time `json:"endGmt"`
ActivityLevel int `json:"activityLevel"`
}
// DailySleepDTO represents daily sleep data
type DailySleepDTO struct {
UserProfilePK int `json:"userProfilePk"`
CalendarDate time.Time `json:"calendarDate"`
SleepStartTimestampGMT time.Time `json:"sleepStartTimestampGmt"`
SleepEndTimestampGMT time.Time `json:"sleepEndTimestampGmt"`
SleepScores SleepScores `json:"sleepScores"`
BaseData
}
// Get implements the Data interface for DailySleepDTO
func (d *DailySleepDTO) Get(day time.Time, client *client.Client) (any, error) {
dateStr := day.Format("2006-01-02")
path := fmt.Sprintf("/wellness-service/wellness/dailySleepData/%s?nonSleepBufferMinutes=60&date=%s",
client.Username, dateStr)
data, err := client.ConnectAPI(path, "GET", nil, nil)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, nil
}
var response struct {
DailySleepDTO *DailySleepDTO `json:"dailySleepDto"`
SleepMovement []SleepMovement `json:"sleepMovement"`
}
if err := json.Unmarshal(data, &response); err != nil {
return nil, err
}
if response.DailySleepDTO == nil {
return nil, nil
}
return response, nil
}
// List implements the Data interface for concurrent fetching
func (d *DailySleepDTO) List(end time.Time, days int, client *client.Client, maxWorkers int) ([]any, error) {
// Implementation to be added
return []any{}, nil
}

81
internal/data/weight.go Normal file
View File

@@ -0,0 +1,81 @@
package data
import (
"encoding/json"
"fmt"
"time"
"garmin-connect/internal/api/client"
)
// WeightData represents weight measurement data
type WeightData struct {
UserProfilePK int `json:"userProfilePk"`
CalendarDate time.Time `json:"calendarDate"`
Timestamp time.Time `json:"timestamp"`
Weight float64 `json:"weight"` // in kilograms
BMI float64 `json:"bmi"`
BodyFatPercentage float64 `json:"bodyFatPercentage"`
BoneMass float64 `json:"boneMass"` // in kg
MuscleMass float64 `json:"muscleMass"` // in kg
Hydration float64 `json:"hydration"` // in kg
BaseData
}
// Validate checks if weight data contains valid values
func (w *WeightData) Validate() error {
if w.Weight <= 0 {
return fmt.Errorf("invalid weight value")
}
if w.BMI < 10 || w.BMI > 50 {
return fmt.Errorf("BMI out of valid range")
}
return nil
}
// Get implements the Data interface for WeightData
func (w *WeightData) Get(day time.Time, client *client.Client) (any, error) {
startDate := day.Format("2006-01-02")
endDate := day.Format("2006-01-02")
path := fmt.Sprintf("/weight-service/weight/dateRange?startDate=%s&endDate=%s",
startDate, endDate)
data, err := client.ConnectAPI(path, "GET", nil, nil)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, nil
}
var response struct {
WeightList []WeightData `json:"weightList"`
}
if err := json.Unmarshal(data, &response); err != nil {
return nil, err
}
if len(response.WeightList) == 0 {
return nil, nil
}
weightData := response.WeightList[0]
// Convert grams to kilograms
weightData.Weight = weightData.Weight / 1000
weightData.BoneMass = weightData.BoneMass / 1000
weightData.MuscleMass = weightData.MuscleMass / 1000
weightData.Hydration = weightData.Hydration / 1000
return weightData, nil
}
// List implements the Data interface for concurrent fetching
func (w *WeightData) List(end time.Time, days int, client *client.Client, maxWorkers int) ([]any, error) {
results, errs := w.BaseData.List(end, days, client, maxWorkers)
if len(errs) > 0 {
// Return first error for now
return results, errs[0]
}
return results, nil
}

84
internal/errors/errors.go Normal file
View File

@@ -0,0 +1,84 @@
package errors
import "fmt"
// GarthError represents the base error type for all custom errors in Garth
type GarthError struct {
Message string
Cause error
}
func (e *GarthError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("garth error: %s: %v", e.Message, e.Cause)
}
return fmt.Sprintf("garth error: %s", e.Message)
}
// GarthHTTPError represents HTTP-related errors in API calls
type GarthHTTPError struct {
GarthError
StatusCode int
Response string
}
func (e *GarthHTTPError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("HTTP error (%d): %s: %v", e.StatusCode, e.Response, e.Cause)
}
return fmt.Sprintf("HTTP error (%d): %s", e.StatusCode, e.Response)
}
// AuthenticationError represents authentication failures
type AuthenticationError struct {
GarthError
}
func (e *AuthenticationError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("authentication error: %s: %v", e.Message, e.Cause)
}
return fmt.Sprintf("authentication error: %s", e.Message)
}
// OAuthError represents OAuth token-related errors
type OAuthError struct {
GarthError
}
func (e *OAuthError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("OAuth error: %s: %v", e.Message, e.Cause)
}
return fmt.Sprintf("OAuth error: %s", e.Message)
}
// APIError represents errors from API calls
type APIError struct {
GarthHTTPError
}
// IOError represents file I/O errors
type IOError struct {
GarthError
}
func (e *IOError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("I/O error: %s: %v", e.Message, e.Cause)
}
return fmt.Sprintf("I/O error: %s", e.Message)
}
// ValidationError represents input validation failures
type ValidationError struct {
GarthError
Field string
}
func (e *ValidationError) Error() string {
if e.Field != "" {
return fmt.Sprintf("validation error for %s: %s", e.Field, e.Message)
}
return fmt.Sprintf("validation error: %s", e.Message)
}

101
internal/stats/base.go Normal file
View File

@@ -0,0 +1,101 @@
package stats
import (
"encoding/json"
"fmt"
"strings"
"time"
"garmin-connect/internal/api/client"
"garmin-connect/internal/utils"
)
type Stats interface {
List(end time.Time, period int, client *client.Client) ([]interface{}, error)
}
type BaseStats struct {
Path string
PageSize int
}
func (b *BaseStats) List(end time.Time, period int, client *client.Client) ([]interface{}, error) {
endDate := utils.FormatEndDate(end)
var allData []interface{}
var errs []error
for period > 0 {
pageSize := b.PageSize
if period < pageSize {
pageSize = period
}
page, err := b.fetchPage(endDate, pageSize, client)
if err != nil {
errs = append(errs, err)
// Continue to next page even if current fails
} else {
allData = append(page, allData...)
}
// Move to previous page
endDate = endDate.AddDate(0, 0, -pageSize)
period -= pageSize
}
// Return partial data with aggregated errors
var finalErr error
if len(errs) > 0 {
finalErr = fmt.Errorf("partial failure: %v", errs)
}
return allData, finalErr
}
func (b *BaseStats) fetchPage(end time.Time, period int, client *client.Client) ([]interface{}, error) {
var start time.Time
var path string
if strings.Contains(b.Path, "daily") {
start = end.AddDate(0, 0, -(period - 1))
path = strings.Replace(b.Path, "{start}", start.Format("2006-01-02"), 1)
path = strings.Replace(path, "{end}", end.Format("2006-01-02"), 1)
} else {
path = strings.Replace(b.Path, "{end}", end.Format("2006-01-02"), 1)
path = strings.Replace(path, "{period}", fmt.Sprintf("%d", period), 1)
}
data, err := client.ConnectAPI(path, "GET", nil, nil)
if err != nil {
return nil, err
}
if len(data) == 0 {
return []interface{}{}, nil
}
var responseSlice []map[string]interface{}
if err := json.Unmarshal(data, &responseSlice); err != nil {
return nil, err
}
if len(responseSlice) == 0 {
return []interface{}{}, nil
}
var results []interface{}
for _, itemMap := range responseSlice {
// Handle nested "values" structure
if values, exists := itemMap["values"]; exists {
valuesMap := values.(map[string]interface{})
for k, v := range valuesMap {
itemMap[k] = v
}
delete(itemMap, "values")
}
snakeItem := utils.CamelToSnakeDict(itemMap)
results = append(results, snakeItem)
}
return results, nil
}

21
internal/stats/hrv.go Normal file
View File

@@ -0,0 +1,21 @@
package stats
import "time"
const BASE_HRV_PATH = "/usersummary-service/stats/hrv"
type DailyHRV struct {
CalendarDate time.Time `json:"calendar_date"`
RestingHR *int `json:"resting_hr"`
HRV *int `json:"hrv"`
BaseStats
}
func NewDailyHRV() *DailyHRV {
return &DailyHRV{
BaseStats: BaseStats{
Path: BASE_HRV_PATH + "/daily/{start}/{end}",
PageSize: 28,
},
}
}

View File

@@ -0,0 +1,40 @@
package stats
import (
"errors"
"time"
)
const WEEKLY_HRV_PATH = "/wellness-service/wellness/weeklyHrv"
type WeeklyHRV struct {
CalendarDate time.Time `json:"calendar_date"`
AverageHRV float64 `json:"average_hrv"`
MaxHRV float64 `json:"max_hrv"`
MinHRV float64 `json:"min_hrv"`
HRVQualifier string `json:"hrv_qualifier"`
WellnessDataDaysCount int `json:"wellness_data_days_count"`
BaseStats
}
func NewWeeklyHRV() *WeeklyHRV {
return &WeeklyHRV{
BaseStats: BaseStats{
Path: WEEKLY_HRV_PATH + "/{end}/{period}",
PageSize: 52,
},
}
}
func (w *WeeklyHRV) Validate() error {
if w.CalendarDate.IsZero() {
return errors.New("calendar_date is required")
}
if w.AverageHRV < 0 || w.MaxHRV < 0 || w.MinHRV < 0 {
return errors.New("HRV values must be non-negative")
}
if w.MaxHRV < w.MinHRV {
return errors.New("max_hrv must be greater than min_hrv")
}
return nil
}

View File

@@ -0,0 +1,20 @@
package stats
import "time"
const BASE_HYDRATION_PATH = "/usersummary-service/stats/hydration"
type DailyHydration struct {
CalendarDate time.Time `json:"calendar_date"`
TotalWaterML *int `json:"total_water_ml"`
BaseStats
}
func NewDailyHydration() *DailyHydration {
return &DailyHydration{
BaseStats: BaseStats{
Path: BASE_HYDRATION_PATH + "/daily/{start}/{end}",
PageSize: 28,
},
}
}

View File

@@ -0,0 +1,21 @@
package stats
import "time"
const BASE_INTENSITY_PATH = "/usersummary-service/stats/intensity_minutes"
type DailyIntensityMinutes struct {
CalendarDate time.Time `json:"calendar_date"`
ModerateIntensity *int `json:"moderate_intensity"`
VigorousIntensity *int `json:"vigorous_intensity"`
BaseStats
}
func NewDailyIntensityMinutes() *DailyIntensityMinutes {
return &DailyIntensityMinutes{
BaseStats: BaseStats{
Path: BASE_INTENSITY_PATH + "/daily/{start}/{end}",
PageSize: 28,
},
}
}

27
internal/stats/sleep.go Normal file
View File

@@ -0,0 +1,27 @@
package stats
import "time"
const BASE_SLEEP_PATH = "/usersummary-service/stats/sleep"
type DailySleep struct {
CalendarDate time.Time `json:"calendar_date"`
TotalSleepTime *int `json:"total_sleep_time"`
RemSleepTime *int `json:"rem_sleep_time"`
DeepSleepTime *int `json:"deep_sleep_time"`
LightSleepTime *int `json:"light_sleep_time"`
AwakeTime *int `json:"awake_time"`
SleepScore *int `json:"sleep_score"`
SleepStartTimestamp *int64 `json:"sleep_start_timestamp"`
SleepEndTimestamp *int64 `json:"sleep_end_timestamp"`
BaseStats
}
func NewDailySleep() *DailySleep {
return &DailySleep{
BaseStats: BaseStats{
Path: BASE_SLEEP_PATH + "/daily/{start}/{end}",
PageSize: 28,
},
}
}

41
internal/stats/steps.go Normal file
View File

@@ -0,0 +1,41 @@
package stats
import "time"
const BASE_STEPS_PATH = "/usersummary-service/stats/steps"
type DailySteps struct {
CalendarDate time.Time `json:"calendar_date"`
TotalSteps *int `json:"total_steps"`
TotalDistance *int `json:"total_distance"`
StepGoal int `json:"step_goal"`
BaseStats
}
func NewDailySteps() *DailySteps {
return &DailySteps{
BaseStats: BaseStats{
Path: BASE_STEPS_PATH + "/daily/{start}/{end}",
PageSize: 28,
},
}
}
type WeeklySteps struct {
CalendarDate time.Time `json:"calendar_date"`
TotalSteps int `json:"total_steps"`
AverageSteps float64 `json:"average_steps"`
AverageDistance float64 `json:"average_distance"`
TotalDistance float64 `json:"total_distance"`
WellnessDataDaysCount int `json:"wellness_data_days_count"`
BaseStats
}
func NewWeeklySteps() *WeeklySteps {
return &WeeklySteps{
BaseStats: BaseStats{
Path: BASE_STEPS_PATH + "/weekly/{end}/{period}",
PageSize: 52,
},
}
}

24
internal/stats/stress.go Normal file
View File

@@ -0,0 +1,24 @@
package stats
import "time"
const BASE_STRESS_PATH = "/usersummary-service/stats/stress"
type DailyStress struct {
CalendarDate time.Time `json:"calendar_date"`
OverallStressLevel int `json:"overall_stress_level"`
RestStressDuration *int `json:"rest_stress_duration"`
LowStressDuration *int `json:"low_stress_duration"`
MediumStressDuration *int `json:"medium_stress_duration"`
HighStressDuration *int `json:"high_stress_duration"`
BaseStats
}
func NewDailyStress() *DailyStress {
return &DailyStress{
BaseStats: BaseStats{
Path: BASE_STRESS_PATH + "/daily/{start}/{end}",
PageSize: 28,
},
}
}

View File

@@ -0,0 +1,36 @@
package stats
import (
"errors"
"time"
)
const WEEKLY_STRESS_PATH = "/wellness-service/wellness/weeklyStress"
type WeeklyStress struct {
CalendarDate time.Time `json:"calendar_date"`
TotalStressDuration int `json:"total_stress_duration"`
AverageStressLevel float64 `json:"average_stress_level"`
MaxStressLevel int `json:"max_stress_level"`
StressQualifier string `json:"stress_qualifier"`
BaseStats
}
func NewWeeklyStress() *WeeklyStress {
return &WeeklyStress{
BaseStats: BaseStats{
Path: WEEKLY_STRESS_PATH + "/{end}/{period}",
PageSize: 52,
},
}
}
func (w *WeeklyStress) Validate() error {
if w.CalendarDate.IsZero() {
return errors.New("calendar_date is required")
}
if w.TotalStressDuration < 0 {
return errors.New("total_stress_duration must be non-negative")
}
return nil
}

View File

@@ -0,0 +1,14 @@
package testutils
import (
"net/http"
"net/http/httptest"
)
func MockJSONResponse(code int, body string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write([]byte(body))
}))
}

View File

@@ -0,0 +1,24 @@
package testutils
import (
"errors"
"io"
"net/url"
"garmin-connect/internal/api/client"
)
// MockClient simulates API client for tests
type MockClient struct {
RealClient *client.Client
FailEvery int
counter int
}
func (mc *MockClient) ConnectAPI(path string, method string, params url.Values, body io.Reader) ([]byte, error) {
mc.counter++
if mc.FailEvery != 0 && mc.counter%mc.FailEvery == 0 {
return nil, errors.New("simulated error")
}
return mc.RealClient.ConnectAPI(path, method, params, body)
}

28
internal/types/auth.go Normal file
View File

@@ -0,0 +1,28 @@
package types
import "time"
// OAuthConsumer represents OAuth consumer credentials
type OAuthConsumer struct {
ConsumerKey string `json:"consumer_key"`
ConsumerSecret string `json:"consumer_secret"`
}
// OAuth1Token represents OAuth1 token response
type OAuth1Token struct {
OAuthToken string `json:"oauth_token"`
OAuthTokenSecret string `json:"oauth_token_secret"`
MFAToken string `json:"mfa_token,omitempty"`
Domain string `json:"domain"`
}
// OAuth2Token represents OAuth2 token response
type OAuth2Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
CreatedAt time.Time // Used for expiration tracking
ExpiresAt time.Time // Computed expiration time
}

58
internal/types/garmin.go Normal file
View File

@@ -0,0 +1,58 @@
package types
import "time"
// GarminTime represents Garmin's timestamp format with custom JSON parsing
type GarminTime struct {
time.Time
}
// SessionData represents saved session information
type SessionData struct {
Domain string `json:"domain"`
Username string `json:"username"`
AuthToken string `json:"auth_token"`
}
// ActivityType represents the type of activity
type ActivityType struct {
TypeID int `json:"typeId"`
TypeKey string `json:"typeKey"`
ParentTypeID *int `json:"parentTypeId,omitempty"`
}
// EventType represents the event type of an activity
type EventType struct {
TypeID int `json:"typeId"`
TypeKey string `json:"typeKey"`
}
// Activity represents a Garmin Connect activity
type Activity struct {
ActivityID int64 `json:"activityId"`
ActivityName string `json:"activityName"`
Description string `json:"description"`
StartTimeLocal string `json:"startTimeLocal"`
StartTimeGMT string `json:"startTimeGMT"`
ActivityType ActivityType `json:"activityType"`
EventType EventType `json:"eventType"`
Distance float64 `json:"distance"`
Duration float64 `json:"duration"`
ElapsedDuration float64 `json:"elapsedDuration"`
MovingDuration float64 `json:"movingDuration"`
ElevationGain float64 `json:"elevationGain"`
ElevationLoss float64 `json:"elevationLoss"`
AverageSpeed float64 `json:"averageSpeed"`
MaxSpeed float64 `json:"maxSpeed"`
Calories float64 `json:"calories"`
AverageHR float64 `json:"averageHR"`
MaxHR float64 `json:"maxHR"`
}
// UserProfile represents a Garmin user profile
type UserProfile struct {
UserName string `json:"userName"`
DisplayName string `json:"displayName"`
LevelUpdateDate GarminTime `json:"levelUpdateDate"`
// Add other fields as needed from API response
}

71
internal/users/profile.go Normal file
View File

@@ -0,0 +1,71 @@
package users
import (
"time"
)
type UserProfile struct {
ID int `json:"id"`
ProfileID int `json:"profileId"`
GarminGUID string `json:"garminGuid"`
DisplayName string `json:"displayName"`
FullName string `json:"fullName"`
UserName string `json:"userName"`
ProfileImageType *string `json:"profileImageType"`
ProfileImageURLLarge *string `json:"profileImageUrlLarge"`
ProfileImageURLMedium *string `json:"profileImageUrlMedium"`
ProfileImageURLSmall *string `json:"profileImageUrlSmall"`
Location *string `json:"location"`
FacebookURL *string `json:"facebookUrl"`
TwitterURL *string `json:"twitterUrl"`
PersonalWebsite *string `json:"personalWebsite"`
Motivation *string `json:"motivation"`
Bio *string `json:"bio"`
PrimaryActivity *string `json:"primaryActivity"`
FavoriteActivityTypes []string `json:"favoriteActivityTypes"`
RunningTrainingSpeed float64 `json:"runningTrainingSpeed"`
CyclingTrainingSpeed float64 `json:"cyclingTrainingSpeed"`
FavoriteCyclingActivityTypes []string `json:"favoriteCyclingActivityTypes"`
CyclingClassification *string `json:"cyclingClassification"`
CyclingMaxAvgPower float64 `json:"cyclingMaxAvgPower"`
SwimmingTrainingSpeed float64 `json:"swimmingTrainingSpeed"`
ProfileVisibility string `json:"profileVisibility"`
ActivityStartVisibility string `json:"activityStartVisibility"`
ActivityMapVisibility string `json:"activityMapVisibility"`
CourseVisibility string `json:"courseVisibility"`
ActivityHeartRateVisibility string `json:"activityHeartRateVisibility"`
ActivityPowerVisibility string `json:"activityPowerVisibility"`
BadgeVisibility string `json:"badgeVisibility"`
ShowAge bool `json:"showAge"`
ShowWeight bool `json:"showWeight"`
ShowHeight bool `json:"showHeight"`
ShowWeightClass bool `json:"showWeightClass"`
ShowAgeRange bool `json:"showAgeRange"`
ShowGender bool `json:"showGender"`
ShowActivityClass bool `json:"showActivityClass"`
ShowVO2Max bool `json:"showVo2Max"`
ShowPersonalRecords bool `json:"showPersonalRecords"`
ShowLast12Months bool `json:"showLast12Months"`
ShowLifetimeTotals bool `json:"showLifetimeTotals"`
ShowUpcomingEvents bool `json:"showUpcomingEvents"`
ShowRecentFavorites bool `json:"showRecentFavorites"`
ShowRecentDevice bool `json:"showRecentDevice"`
ShowRecentGear bool `json:"showRecentGear"`
ShowBadges bool `json:"showBadges"`
OtherActivity *string `json:"otherActivity"`
OtherPrimaryActivity *string `json:"otherPrimaryActivity"`
OtherMotivation *string `json:"otherMotivation"`
UserRoles []string `json:"userRoles"`
NameApproved bool `json:"nameApproved"`
UserProfileFullName string `json:"userProfileFullName"`
MakeGolfScorecardsPrivate bool `json:"makeGolfScorecardsPrivate"`
AllowGolfLiveScoring bool `json:"allowGolfLiveScoring"`
AllowGolfScoringByConnections bool `json:"allowGolfScoringByConnections"`
UserLevel int `json:"userLevel"`
UserPoint int `json:"userPoint"`
LevelUpdateDate time.Time `json:"levelUpdateDate"`
LevelIsViewed bool `json:"levelIsViewed"`
LevelPointThreshold int `json:"levelPointThreshold"`
UserPointOffset int `json:"userPointOffset"`
UserPro bool `json:"userPro"`
}

View File

@@ -0,0 +1,95 @@
package users
import (
"time"
"garmin-connect/internal/api/client"
)
type PowerFormat struct {
FormatID int `json:"formatId"`
FormatKey string `json:"formatKey"`
MinFraction int `json:"minFraction"`
MaxFraction int `json:"maxFraction"`
GroupingUsed bool `json:"groupingUsed"`
DisplayFormat *string `json:"displayFormat"`
}
type FirstDayOfWeek struct {
DayID int `json:"dayId"`
DayName string `json:"dayName"`
SortOrder int `json:"sortOrder"`
IsPossibleFirstDay bool `json:"isPossibleFirstDay"`
}
type WeatherLocation struct {
UseFixedLocation *bool `json:"useFixedLocation"`
Latitude *float64 `json:"latitude"`
Longitude *float64 `json:"longitude"`
LocationName *string `json:"locationName"`
ISOCountryCode *string `json:"isoCountryCode"`
PostalCode *string `json:"postalCode"`
}
type UserData struct {
Gender string `json:"gender"`
Weight float64 `json:"weight"`
Height float64 `json:"height"`
TimeFormat string `json:"timeFormat"`
BirthDate time.Time `json:"birthDate"`
MeasurementSystem string `json:"measurementSystem"`
ActivityLevel *string `json:"activityLevel"`
Handedness string `json:"handedness"`
PowerFormat PowerFormat `json:"powerFormat"`
HeartRateFormat PowerFormat `json:"heartRateFormat"`
FirstDayOfWeek FirstDayOfWeek `json:"firstDayOfWeek"`
VO2MaxRunning *float64 `json:"vo2MaxRunning"`
VO2MaxCycling *float64 `json:"vo2MaxCycling"`
LactateThresholdSpeed *float64 `json:"lactateThresholdSpeed"`
LactateThresholdHeartRate *float64 `json:"lactateThresholdHeartRate"`
DiveNumber *int `json:"diveNumber"`
IntensityMinutesCalcMethod string `json:"intensityMinutesCalcMethod"`
ModerateIntensityMinutesHRZone int `json:"moderateIntensityMinutesHrZone"`
VigorousIntensityMinutesHRZone int `json:"vigorousIntensityMinutesHrZone"`
HydrationMeasurementUnit string `json:"hydrationMeasurementUnit"`
HydrationContainers []map[string]interface{} `json:"hydrationContainers"`
HydrationAutoGoalEnabled bool `json:"hydrationAutoGoalEnabled"`
FirstbeatMaxStressScore *float64 `json:"firstbeatMaxStressScore"`
FirstbeatCyclingLTTimestamp *int64 `json:"firstbeatCyclingLtTimestamp"`
FirstbeatRunningLTTimestamp *int64 `json:"firstbeatRunningLtTimestamp"`
ThresholdHeartRateAutoDetected bool `json:"thresholdHeartRateAutoDetected"`
FTPAutoDetected *bool `json:"ftpAutoDetected"`
TrainingStatusPausedDate *string `json:"trainingStatusPausedDate"`
WeatherLocation *WeatherLocation `json:"weatherLocation"`
GolfDistanceUnit *string `json:"golfDistanceUnit"`
GolfElevationUnit *string `json:"golfElevationUnit"`
GolfSpeedUnit *string `json:"golfSpeedUnit"`
ExternalBottomTime *float64 `json:"externalBottomTime"`
}
type UserSleep struct {
SleepTime int `json:"sleepTime"`
DefaultSleepTime bool `json:"defaultSleepTime"`
WakeTime int `json:"wakeTime"`
DefaultWakeTime bool `json:"defaultWakeTime"`
}
type UserSleepWindow struct {
SleepWindowFrequency string `json:"sleepWindowFrequency"`
StartSleepTimeSecondsFromMidnight int `json:"startSleepTimeSecondsFromMidnight"`
EndSleepTimeSecondsFromMidnight int `json:"endSleepTimeSecondsFromMidnight"`
}
type UserSettings struct {
ID int `json:"id"`
UserData UserData `json:"userData"`
UserSleep UserSleep `json:"userSleep"`
ConnectDate *string `json:"connectDate"`
SourceType *string `json:"sourceType"`
UserSleepWindows []UserSleepWindow `json:"userSleepWindows,omitempty"`
}
func GetSettings(c *client.Client) (*UserSettings, error) {
// Implementation will be added in client.go
return nil, nil
}

View File

@@ -0,0 +1,38 @@
package utils
import (
"time"
)
var (
// Default location for conversions (set to UTC by default)
defaultLocation *time.Location
)
func init() {
var err error
defaultLocation, err = time.LoadLocation("UTC")
if err != nil {
panic(err)
}
}
// SetDefaultLocation sets the default time location for conversions
func SetDefaultLocation(loc *time.Location) {
defaultLocation = loc
}
// ParseTimestamp converts a millisecond timestamp to time.Time in default location
func ParseTimestamp(ts int) time.Time {
return time.Unix(0, int64(ts)*int64(time.Millisecond)).In(defaultLocation)
}
// ToLocalTime converts UTC time to local time using default location
func ToLocalTime(utcTime time.Time) time.Time {
return utcTime.In(defaultLocation)
}
// ToUTCTime converts local time to UTC
func ToUTCTime(localTime time.Time) time.Time {
return localTime.UTC()
}

216
internal/utils/utils.go Normal file
View File

@@ -0,0 +1,216 @@
package utils
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"garmin-connect/internal/types"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
var oauthConsumer *types.OAuthConsumer
// LoadOAuthConsumer loads OAuth consumer credentials
func LoadOAuthConsumer() (*types.OAuthConsumer, error) {
if oauthConsumer != nil {
return oauthConsumer, nil
}
// First try to get from S3 (like the Python library)
resp, err := http.Get("https://thegarth.s3.amazonaws.com/oauth_consumer.json")
if err == nil {
defer resp.Body.Close()
if resp.StatusCode == 200 {
var consumer types.OAuthConsumer
if err := json.NewDecoder(resp.Body).Decode(&consumer); err == nil {
oauthConsumer = &consumer
return oauthConsumer, nil
}
}
}
// Fallback to hardcoded values
oauthConsumer = &types.OAuthConsumer{
ConsumerKey: "fc320c35-fbdc-4308-b5c6-8e41a8b2e0c8",
ConsumerSecret: "8b344b8c-5bd5-4b7b-9c98-ad76a6bbf0e7",
}
return oauthConsumer, nil
}
// GenerateNonce generates a random nonce for OAuth
func GenerateNonce() string {
b := make([]byte, 32)
rand.Read(b)
return base64.StdEncoding.EncodeToString(b)
}
// GenerateTimestamp generates a timestamp for OAuth
func GenerateTimestamp() string {
return strconv.FormatInt(time.Now().Unix(), 10)
}
// PercentEncode URL encodes a string
func PercentEncode(s string) string {
return url.QueryEscape(s)
}
// CreateSignatureBaseString creates the base string for OAuth signing
func CreateSignatureBaseString(method, baseURL string, params map[string]string) string {
var keys []string
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
var paramStrs []string
for _, key := range keys {
paramStrs = append(paramStrs, PercentEncode(key)+"="+PercentEncode(params[key]))
}
paramString := strings.Join(paramStrs, "&")
return method + "&" + PercentEncode(baseURL) + "&" + PercentEncode(paramString)
}
// CreateSigningKey creates the signing key for OAuth
func CreateSigningKey(consumerSecret, tokenSecret string) string {
return PercentEncode(consumerSecret) + "&" + PercentEncode(tokenSecret)
}
// SignRequest signs an OAuth request
func SignRequest(consumerSecret, tokenSecret, baseString string) string {
signingKey := CreateSigningKey(consumerSecret, tokenSecret)
mac := hmac.New(sha1.New, []byte(signingKey))
mac.Write([]byte(baseString))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
// CreateOAuth1AuthorizationHeader creates the OAuth1 authorization header
func CreateOAuth1AuthorizationHeader(method, requestURL string, params map[string]string, consumerKey, consumerSecret, token, tokenSecret string) string {
oauthParams := map[string]string{
"oauth_consumer_key": consumerKey,
"oauth_nonce": GenerateNonce(),
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": GenerateTimestamp(),
"oauth_version": "1.0",
}
if token != "" {
oauthParams["oauth_token"] = token
}
// Combine OAuth params with request params
allParams := make(map[string]string)
for k, v := range oauthParams {
allParams[k] = v
}
for k, v := range params {
allParams[k] = v
}
// Parse URL to get base URL without query params
parsedURL, _ := url.Parse(requestURL)
baseURL := parsedURL.Scheme + "://" + parsedURL.Host + parsedURL.Path
// Create signature base string
baseString := CreateSignatureBaseString(method, baseURL, allParams)
// Sign the request
signature := SignRequest(consumerSecret, tokenSecret, baseString)
oauthParams["oauth_signature"] = signature
// Build authorization header
var headerParts []string
for key, value := range oauthParams {
headerParts = append(headerParts, PercentEncode(key)+"=\""+PercentEncode(value)+"\"")
}
sort.Strings(headerParts)
return "OAuth " + strings.Join(headerParts, ", ")
}
// Min returns the smaller of two integers
func Min(a, b int) int {
if a < b {
return a
}
return b
}
// DateRange generates a date range from end date backwards for n days
func DateRange(end time.Time, days int) []time.Time {
dates := make([]time.Time, days)
for i := 0; i < days; i++ {
dates[i] = end.AddDate(0, 0, -i)
}
return dates
}
// CamelToSnake converts a camelCase string to snake_case
func CamelToSnake(s string) string {
matchFirstCap := regexp.MustCompile("(.)([A-Z][a-z]+)")
matchAllCap := regexp.MustCompile("([a-z0-9])([A-Z])")
snake := matchFirstCap.ReplaceAllString(s, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}
// CamelToSnakeDict recursively converts map keys from camelCase to snake_case
func CamelToSnakeDict(m map[string]interface{}) map[string]interface{} {
snakeDict := make(map[string]interface{})
for k, v := range m {
snakeKey := CamelToSnake(k)
// Handle nested maps
if nestedMap, ok := v.(map[string]interface{}); ok {
snakeDict[snakeKey] = CamelToSnakeDict(nestedMap)
} else if nestedSlice, ok := v.([]interface{}); ok {
// Handle slices of maps
var newSlice []interface{}
for _, item := range nestedSlice {
if itemMap, ok := item.(map[string]interface{}); ok {
newSlice = append(newSlice, CamelToSnakeDict(itemMap))
} else {
newSlice = append(newSlice, item)
}
}
snakeDict[snakeKey] = newSlice
} else {
snakeDict[snakeKey] = v
}
}
return snakeDict
}
// FormatEndDate converts various date formats to time.Time
func FormatEndDate(end interface{}) time.Time {
if end == nil {
return time.Now().UTC().Truncate(24 * time.Hour)
}
switch v := end.(type) {
case string:
t, _ := time.Parse("2006-01-02", v)
return t
case time.Time:
return v
default:
return time.Now().UTC().Truncate(24 * time.Hour)
}
}
// GetLocalizedDateTime converts GMT and local timestamps to localized time
func GetLocalizedDateTime(gmtTimestamp, localTimestamp int64) time.Time {
localDiff := localTimestamp - gmtTimestamp
offset := time.Duration(localDiff) * time.Millisecond
loc := time.FixedZone("", int(offset.Seconds()))
gmtTime := time.Unix(0, gmtTimestamp*int64(time.Millisecond)).UTC()
return gmtTime.In(loc)
}