-
Notifications
You must be signed in to change notification settings - Fork 0
/
zwift.go
292 lines (274 loc) · 7.79 KB
/
zwift.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package zwift
import (
"context"
"os"
"path/filepath"
"strconv"
"sync"
api "github.com/bzimmer/activity"
"github.com/bzimmer/activity/zwift"
"github.com/rs/zerolog/log"
"github.com/spf13/afero"
"github.com/urfave/cli/v2"
"golang.org/x/time/rate"
"github.com/bzimmer/gravl"
"github.com/bzimmer/gravl/activity"
)
const (
tooSmall = 1024
Provider = "zwift"
)
var before sync.Once //nolint:gochecknoglobals // once
func athlete(c *cli.Context) error {
client := gravl.Runtime(c).Zwift
args := c.Args().Slice()
if len(args) == 0 {
args = append(args, zwift.Me)
}
enc := gravl.Runtime(c).Encoder
ctx, cancel := context.WithTimeout(c.Context, c.Duration("timeout"))
defer cancel()
for i := range args {
profile, err := client.Profile.Profile(ctx, args[i])
if err != nil {
return err
}
log.Info().Int64("id", profile.ID).Str("username", profile.PublicID).Msg(c.Command.Name)
gravl.Runtime(c).Metrics.IncrCounter([]string{Provider, c.Command.Name}, 1)
if err = enc.Encode(profile); err != nil {
return err
}
}
return nil
}
func athleteCommand() *cli.Command {
return &cli.Command{
Name: "athlete",
Usage: "Query the athlete profile from Zwift",
Aliases: []string{"t"},
Action: athlete,
}
}
func refresh(c *cli.Context) error {
client := gravl.Runtime(c).Zwift
ctx, cancel := context.WithTimeout(c.Context, c.Duration("timeout"))
defer cancel()
username, password := c.String("zwift.username"), c.String("zwift.password")
token, err := client.Auth.Refresh(ctx, username, password)
if err != nil {
return err
}
gravl.Runtime(c).Metrics.IncrCounter([]string{Provider, c.Command.Name}, 1)
return gravl.Runtime(c).Encoder.Encode(token)
}
func refreshCommand() *cli.Command {
return &cli.Command{
Name: "refresh",
Usage: "Acquire a new refresh token",
Action: refresh,
}
}
func activities(c *cli.Context) error {
client := gravl.Runtime(c).Zwift
ctx, cancel := context.WithTimeout(c.Context, c.Duration("timeout"))
defer cancel()
profile, err := client.Profile.Profile(ctx, zwift.Me)
if err != nil {
return err
}
spec := api.Pagination{Total: c.Int("count")}
acts, err := client.Activity.Activities(ctx, profile.ID, spec)
if err != nil {
return err
}
gravl.Runtime(c).Metrics.IncrCounter([]string{Provider, c.Command.Name}, 1)
for _, act := range acts {
gravl.Runtime(c).Metrics.IncrCounter([]string{Provider, "activity"}, 1)
log.Info().
Time("date", act.StartDate.Time).
Int64("id", act.ID).
Str("name", act.Name).
Msg(c.Command.Name)
if err = gravl.Runtime(c).Encoder.Encode(act); err != nil {
return err
}
}
return nil
}
func activitiesCommand() *cli.Command {
return &cli.Command{
Name: "activities",
Usage: "Query activities for an athlete from Zwift",
Aliases: []string{"A"},
Flags: []cli.Flag{
&cli.IntFlag{
Name: "count",
Aliases: []string{"N"},
Value: 0,
Usage: "The number of activities to query from Zwift (the number returned will be <= N)",
},
},
Action: activities,
}
}
func entity(c *cli.Context, f func(context.Context, *zwift.Activity) error) error {
if c.NArg() == 0 {
log.Warn().Msg("no args specified; exiting")
return nil
}
client := gravl.Runtime(c).Zwift
ctx, cancel := context.WithTimeout(c.Context, c.Duration("timeout"))
defer cancel()
profile, err := client.Profile.Profile(ctx, zwift.Me)
if err != nil {
return err
}
for _, arg := range c.Args().Slice() {
var x int64
var act *zwift.Activity
x, err = strconv.ParseInt(arg, 0, 64)
if err != nil {
return err
}
log.Info().Int64("id", x).Str("entity", c.Command.Name).Msg("querying")
gravl.Runtime(c).Metrics.IncrCounter([]string{Provider, c.Command.Name}, 1)
act, err = client.Activity.Activity(ctx, profile.ID, x)
if err != nil {
return err
}
if err = f(ctx, act); err != nil {
return err
}
}
return nil
}
func activityCommand() *cli.Command {
return &cli.Command{
Name: "activity",
Aliases: []string{"a"},
Usage: "Query an activity from Zwift",
ArgsUsage: "ACTIVITY_ID (...)",
Action: func(c *cli.Context) error {
return entity(c, func(_ context.Context, act *zwift.Activity) error {
return gravl.Runtime(c).Encoder.Encode(act)
})
},
}
}
// Primary use case has been uploading fit files from a local Zwift directory
// Filters small files (584 bytes) and files named "inProgressActivity.fit"
// If no arguments are specified will try to default to the Zwift Activities directory
func files(c *cli.Context) error { //nolint:gocognit
args := c.Args().Slice()
if len(args) == 0 {
home, err := os.UserHomeDir()
if err != nil {
// log but error silently since this is optional behavior
log.Warn().Err(err).Msg("homedir not found")
return nil
}
args = append(args, filepath.Join(home, "Documents", "Zwift", "Activities"))
}
fs := gravl.Runtime(c).Fs
enc := gravl.Runtime(c).Encoder
met := gravl.Runtime(c).Metrics
log.Info().Str("fs", fs.Name()).Msg("walk")
for _, arg := range args {
err := afero.Walk(fs, arg, func(path string, info os.FileInfo, err error) error {
if err != nil {
if os.IsNotExist(err) {
met.IncrCounter([]string{Provider, c.Command.Name, "skipping", "does-not-exist"}, 1)
log.Warn().Str("file", path).Msg("path does not exist")
return nil
}
return err
}
met.IncrCounter([]string{Provider, c.Command.Name, "found"}, 1)
if info.IsDir() {
met.IncrCounter([]string{Provider, c.Command.Name, "directory"}, 1)
return nil
}
base := filepath.Base(path)
if base == "inProgressActivity.fit" {
met.IncrCounter([]string{Provider, c.Command.Name, "skipping", "in-progress"}, 1)
log.Warn().Str("file", path).Msg("skipping, activity in progress")
return nil
}
if info.Size() <= tooSmall {
met.IncrCounter([]string{Provider, c.Command.Name, "skipping", "too-small"}, 1)
log.Warn().Int64("size", info.Size()).Str("file", path).Msg("skipping, too small")
return nil
}
format := api.ToFormat(filepath.Ext(path))
if format != api.FormatFIT {
met.IncrCounter([]string{Provider, c.Command.Name, "skipping", format.String()}, 1)
log.Info().Str("file", path).Msg("skipping, not a FIT file")
return nil
}
met.IncrCounter([]string{Provider, c.Command.Name, "success"}, 1)
return enc.Encode(path)
})
if err != nil {
return err
}
}
return nil
}
func filesCommand() *cli.Command {
return &cli.Command{
Name: "files",
Usage: "List all local Zwift files",
Action: files,
}
}
func AuthFlags() []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "zwift-username",
Usage: "Zwift username",
EnvVars: []string{"ZWIFT_USERNAME"},
},
&cli.StringFlag{
Name: "zwift-password",
Usage: "Zwift password",
EnvVars: []string{"ZWIFT_PASSWORD"},
},
}
}
// Before configures the zwift client
func Before(c *cli.Context) error {
var err error
before.Do(func() {
var client *zwift.Client
client, err = zwift.NewClient(
zwift.WithTokenRefresh(c.String("zwift-username"), c.String("zwift-password")),
zwift.WithHTTPTracing(c.Bool("http-tracing")),
zwift.WithRateLimiter(rate.NewLimiter(
rate.Every(c.Duration("rate-limit")), c.Int("rate-burst"))))
if err != nil {
return
}
gravl.Runtime(c).Endpoints[Provider] = zwift.Endpoint()
gravl.Runtime(c).Zwift = client
gravl.Runtime(c).Metrics.IncrCounter([]string{Provider, "client", "created"}, 1)
log.Info().Msg("created zwift client")
})
return err
}
func Command() *cli.Command {
return &cli.Command{
Name: "zwift",
Category: "activity",
Usage: "Query Zwift for activities",
Description: "Operations supported by the Zwift API",
Flags: append(AuthFlags(), activity.RateLimitFlags()...),
Before: Before,
Subcommands: []*cli.Command{
activitiesCommand(),
activityCommand(),
athleteCommand(),
filesCommand(),
refreshCommand(),
},
}
}