wakatime.go (3767B)
1 package external 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "net/http" 8 "net/url" 9 "time" 10 11 "git.prime8.dev/moncheeta/prime8dev/internal/config" 12 "github.com/patrickmn/go-cache" 13 ) 14 15 const ( 16 wakaTimeTTL = time.Hour 17 wakaTimePendingTTL = time.Minute 18 wakaTimeKey = "wakatime:total" 19 wakaTimeStaleKey = "wakatime:total:stale" 20 ) 21 22 // WakaTime reads a user's all-time total from the self-hosted Wakapi 23 // (time.prime8.dev) through its WakaTime-compatible public, 24 // unauthenticated stats endpoint. Public sharing must be on in Wakapi. 25 type WakaTime struct { 26 httpClient *http.Client 27 baseURL string 28 user string 29 cache *cache.Cache 30 } 31 32 func NewWakaTime(c *cache.Cache) *WakaTime { 33 return &WakaTime{ 34 httpClient: &http.Client{Timeout: 30 * time.Second}, 35 baseURL: "https://time.prime8.dev/api/compat/wakatime/v1", 36 user: config.WakaTimeUser, 37 cache: c, 38 } 39 } 40 41 type WakaTimeStats struct { 42 AllTime AllTimeStats 43 } 44 45 type AllTimeStats struct { 46 TotalText string 47 } 48 49 type publicStatsResponse struct { 50 Data struct { 51 Status string `json:"status"` 52 TotalSecondsIncludingOtherLanguage *float64 `json:"total_seconds_including_other_language"` 53 TotalSeconds *float64 `json:"total_seconds"` // Wakapi leaves the field above null 54 } `json:"data"` 55 } 56 57 // FetchTotal returns the all-time total ("3.4k hrs logged"). It returns nil, nil 58 // when no user is configured or while WakaTime is still computing the stats; 59 // on a failed fetch it serves the last good value when there is one. 60 func (s *WakaTime) FetchTotal() (*WakaTimeStats, error) { 61 if s.user == "" { 62 return nil, nil 63 } 64 65 if val, found := s.cache.Get(wakaTimeKey); found { 66 return val.(*WakaTimeStats), nil 67 } 68 69 seconds, ok, err := s.fetchAllTimeSeconds() 70 if err != nil { 71 if stale := s.stale(); stale != nil { 72 return stale, nil 73 } 74 return nil, err 75 } 76 if !ok { 77 // Still computing: keep showing the last good value (or nothing) and 78 // check again shortly. 79 stale := s.stale() 80 s.cache.Set(wakaTimeKey, stale, wakaTimePendingTTL) 81 return stale, nil 82 } 83 84 stats := &WakaTimeStats{AllTime: AllTimeStats{TotalText: formatTotalHours(seconds)}} 85 s.cache.Set(wakaTimeKey, stats, wakaTimeTTL) 86 s.cache.Set(wakaTimeStaleKey, stats, cache.NoExpiration) 87 return stats, nil 88 } 89 90 func (s *WakaTime) stale() *WakaTimeStats { 91 if val, found := s.cache.Get(wakaTimeStaleKey); found { 92 return val.(*WakaTimeStats) 93 } 94 return nil 95 } 96 97 // fetchAllTimeSeconds reports ok=false when the stats are not ready yet 98 // (202 Accepted, a non-ok status, or a missing total). 99 func (s *WakaTime) fetchAllTimeSeconds() (float64, bool, error) { 100 endpoint := fmt.Sprintf("%s/users/%s/stats/all_time", s.baseURL, url.PathEscape(s.user)) 101 resp, err := s.httpClient.Get(endpoint) 102 if err != nil { 103 return 0, false, err 104 } 105 defer resp.Body.Close() 106 107 switch resp.StatusCode { 108 case http.StatusOK: 109 case http.StatusAccepted: 110 return 0, false, nil 111 default: 112 return 0, false, fmt.Errorf("wakatime API returned %d", resp.StatusCode) 113 } 114 115 body, err := io.ReadAll(resp.Body) 116 if err != nil { 117 return 0, false, err 118 } 119 var data publicStatsResponse 120 if err := json.Unmarshal(body, &data); err != nil { 121 return 0, false, err 122 } 123 124 total := data.Data.TotalSecondsIncludingOtherLanguage 125 if total == nil { 126 total = data.Data.TotalSeconds 127 } 128 if (data.Data.Status != "" && data.Data.Status != "ok") || total == nil || *total <= 0 { 129 return 0, false, nil 130 } 131 return *total, true, nil 132 } 133 134 func formatTotalHours(totalSeconds float64) string { 135 hours := int(totalSeconds / 3600) 136 if hours < 1000 { 137 return fmt.Sprintf("%d hrs logged", hours) 138 } 139 // Truncate, never round up: 3447 h reads 3.4k. 140 return fmt.Sprintf("%d.%dk hrs logged", hours/1000, hours%1000/100) 141 }