oh-my-posh/src/segments/wakatime.go

86 lines
1.7 KiB
Go
Raw Normal View History

2022-01-26 06:54:36 -08:00
package segments
2021-12-11 08:31:58 -08:00
import (
"encoding/json"
2022-12-28 08:30:48 -08:00
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/template"
2021-12-11 08:31:58 -08:00
)
2022-01-26 05:10:18 -08:00
type Wakatime struct {
props properties.Properties
2022-11-09 11:27:54 -08:00
env platform.Environment
2021-12-11 08:31:58 -08:00
wtData
}
type wtTotals struct {
Seconds float64 `json:"seconds"`
Text string `json:"text"`
}
type wtData struct {
CumulativeTotal wtTotals `json:"cumulative_total"`
Start string `json:"start"`
End string `json:"end"`
2021-12-11 08:31:58 -08:00
}
func (w *Wakatime) Template() string {
return " {{ secondsRound .CumulativeTotal.Seconds }} "
}
func (w *Wakatime) Enabled() bool {
2021-12-11 08:31:58 -08:00
err := w.setAPIData()
return err == nil
}
2022-01-26 05:10:18 -08:00
func (w *Wakatime) setAPIData() error {
2022-08-16 11:55:08 -07:00
url, err := w.getURL()
if err != nil {
return err
}
2022-07-15 04:24:56 -07:00
cacheTimeout := w.props.GetInt(properties.CacheTimeout, properties.DefaultCacheTimeout)
2021-12-11 08:31:58 -08:00
if cacheTimeout > 0 {
// check if data stored in cache
if val, found := w.env.Cache().Get(url); found {
2021-12-11 08:31:58 -08:00
err := json.Unmarshal([]byte(val), &w.wtData)
if err != nil {
return err
}
return nil
}
}
2022-07-15 04:24:56 -07:00
httpTimeout := w.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout)
2021-12-11 08:31:58 -08:00
2022-07-17 12:11:23 -07:00
body, err := w.env.HTTPRequest(url, nil, httpTimeout)
2021-12-11 08:31:58 -08:00
if err != nil {
return err
}
err = json.Unmarshal(body, &w.wtData)
if err != nil {
return err
}
if cacheTimeout > 0 {
w.env.Cache().Set(url, string(body), cacheTimeout)
2021-12-11 08:31:58 -08:00
}
return nil
}
2022-08-16 11:55:08 -07:00
func (w *Wakatime) getURL() (string, error) {
url := w.props.GetString(URL, "")
tmpl := &template.Text{
Template: url,
Context: w,
Env: w.env,
}
return tmpl.Render()
}
2022-11-09 11:27:54 -08:00
func (w *Wakatime) Init(props properties.Properties, env platform.Environment) {
2021-12-11 08:31:58 -08:00
w.props = props
w.env = env
}