-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZwiftPowerService.cs
491 lines (418 loc) · 11.9 KB
/
ZwiftPowerService.cs
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace ZwiftPower
{
public class ZwiftPowerService
{
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _options;
private readonly IConfiguration _config;
private string _accessToken;
//private string _refreshToken;
//private int _refreshExpiresIn;
public HttpClient Client { get => _httpClient; }
public ZwiftPowerService(HttpClient httpClient, IConfiguration configuration)
{
_httpClient = httpClient;
_config = configuration;
_options = new JsonSerializerOptions
{
NumberHandling = JsonNumberHandling.AllowReadingFromString,
IncludeFields = true
};
_options.Converters.Add(new UnixDateTimeConverter());
_options.Converters.Add(new NumberBooleanConverter());
_options.Converters.Add(new NullableNumberAsStringConverter());
_options.Converters.Add(new NullableFloatAsStringConverter());
_options.Converters.Add(new IntAsStringArrayConverter());
}
private static long UnixTicks { get { return (DateTime.UtcNow - DateTime.UnixEpoch).Ticks; } }
internal async Task<T> DeserializeUrl<T>(string url)
{
int retries = 10;
bool loggedIn = false;
Exception lastException = null;
while (retries-- > 0)
{
try
{
return await _httpClient.GetFromJsonAsync<T>(url, _options);
}
catch (JsonException exn)
{
if (exn.BytePositionInLine == 0 && exn.LineNumber == 0)
{
// usually a good indication that we're not logged in
if (!loggedIn)
{
await Login();
loggedIn = true;
continue;
}
}
throw;
}
catch (HttpRequestException exn)
{
if (!loggedIn && exn.StatusCode == System.Net.HttpStatusCode.RedirectKeepVerb)
{
throw new Exception("Base URL needs to be updated", exn);
}
if (!loggedIn && exn.StatusCode == System.Net.HttpStatusCode.Forbidden)
{
await Login();
loggedIn = true;
continue;
}
lastException = exn;
// maybe ZwiftPower is down, wait for a minute
await Task.Delay(60 * 1000);
}
}
throw new TimeoutException($"Exceeded ZwiftPower retries for url: {url}", lastException);
}
internal T DeserializeString<T>(string json) => JsonSerializer.Deserialize<T>(json);
public async Task Login()
{
if (string.IsNullOrEmpty(_config["Zwiftpower:Username"]))
{
throw new ArgumentException("ZwiftPower Username is required to login", "Zwiftpower:Username");
}
if (string.IsNullOrEmpty(_config["Zwiftpower:Password"]))
{
throw new ArgumentException("ZwiftPower password is required to login", "Zwiftpower:Password");
}
using FormUrlEncodedContent content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "username", _config["Zwiftpower:Username"] },
{ "password", _config["Zwiftpower:Password"] },
{ "client_id", "Zwift Game Client" },
{ "grant_type", "password" }
});
var httpClient = new HttpClient();
using var response = await httpClient.PostAsync("https://secure.zwift.com/auth/realms/zwift/protocol/openid-connect/token", content);
var loginResponse = await response.Content.ReadFromJsonAsync<LoginResponse>();
_accessToken = loginResponse.access_token;
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", this._accessToken);
await _httpClient.GetAsync("/ucp.php?mode=login&login=external&oauth_service=oauthzpsso");
}
public string BearerToken() { return _accessToken; }
public record LoginResponse(string access_token, string refresh_token, int expires_in, int refresh_expires_in, string session_state);
internal class Data<T>
{
#pragma warning disable 0649 // used by JSON deserialization
public T[] data;
#pragma warning restore 0649
}
internal class DataArray<T>
{
#pragma warning disable 0649 // used by JSON deserialization
public T[][] data;
#pragma warning restore 0649
}
internal Task<TItem> ParseItemAsync<TItem>(string url) => DeserializeUrl<TItem>(url);
internal async Task<IEnumerable<T>> ParseListAsync<T>(string url)
{
var result = await DeserializeUrl<Data<T>>(url);
return result.data;
}
internal async Task<IEnumerable<T>> ParsePagedList<T>(string url)
{
var result = await DeserializeUrl<DataArray<T>>(url);
return result.data.SelectMany(results => results);
}
public async Task SubmitResultChanges(int eventId, IEnumerable<ResultSubmission> bumped, IEnumerable<ResultSubmission> disqualified)
{
await Login();
StringBuilder builder = new StringBuilder();
foreach (var bump in bumped)
{
builder.AppendLine($"{bump.CalculatedCategory}, {bump.Flag}, {bump.PowerType}, {bump.TeamId}, {bump.Name}, {bump.Id}, {bump.Uid}, {bump.Penalty}, ");
}
foreach (var dq in disqualified)
{
builder.AppendLine($"{dq.CalculatedCategory}, {dq.Flag}, {dq.PowerType}, {dq.TeamId}, {dq.Name}, {dq.Id}, {dq.Uid}, {dq.Penalty}, ");
}
// replace escapes: html decode, then url encode (url encode taken care of; just need HTML entities escaped, and strip commas)
using FormUrlEncodedContent content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "edit_results", System.Net.WebUtility.HtmlDecode(builder.ToString()) }
});
await _httpClient.PostAsync($"/zz.php?do=edit_results&act=save&zwift_event_id={eventId}", content);
}
// API surface
public Task<IEnumerable<PendingRequest>> PendingRequestsAsync() => ParseListAsync<PendingRequest>("/api3.php?do=team_pending&id=4");
public Task<IEnumerable<Result>> ProfileResultsAsync(int zwid) => ParseListAsync<Result>($"/cache3/profile/{zwid}_all.json?_={UnixTicks}");
public Task<IEnumerable<Signup>> EventSignupsAsync(int zid) => ParseListAsync<Signup>($"/cache3/results/{zid}_signups.json?_={UnixTicks}");
public Task<IEnumerable<Events>> EventsAsync() => ParseListAsync<Events>("/cache3/lists/0_zwift_event_list_7.json");
public Task<IEnumerable<EventResult>> EventResultsAsync(int zid) => ParseListAsync<EventResult>($"/cache3/results/{zid}_view.json?_={UnixTicks}");
public Task<IEnumerable<FilteredResult>> FilteredResultsAsync(int zid) => ParseListAsync<FilteredResult>($"/cache3/results/{zid}_filtered.json?_={UnixTicks}");
public Task<IEnumerable<Member>> TeamMembersAsync() => ParseListAsync<Member>("/api3.php?do=team_riders&id=4");
public Task<IEnumerable<LiveResult>> LiveResultsAsync(int zid) => ParseListAsync<LiveResult>($"/...{zid}");
public Task<IEnumerable<Event>> EventAsync() => ParseListAsync<Event>("/cache3/lists/0_zwift_event_list_3.json");
public Task<IEnumerable<SeriesEvent>> SeriesEventsAsync(string series) => ParseListAsync<SeriesEvent>($"/api3.php?do=series_event_list&id={series}");
public Task<IEnumerable<Segment>> EventSegmentsAsync(int zid, string category) => ParseListAsync<Segment>($"/api3.php?do=event_primes&zid={zid}&category={category}&prime_type=msec");
}
public class ResultSubmission
{
public int Id;
public int TeamId;
public string EnteredCategory;
public string HistoricalCategory;
public string CalculatedCategory;
public string Name;
public string Flag;
public int PowerType;
public string Uid;
public int Penalty;
}
public record PendingRequest(
string e,
string email,
string n,
string aid,
int tid,
string tname,
string tc,
string tbc,
string flag,
int?[] ftp,
float[] w,
int zwid
);
public record Result(
int zwid,
string zid,
string name,
string flag,
int? tid,
string tname,
string tc,
string tbc,
string tbd,
int? div,
int? divw,
bool male,
DateTime event_date,
int distance,
int[] avg_power,
float time_gun
);
public record SeriesEvent(
int DT_RowID,
string cats,
string t,
DateTime tm,
int zid
);
public record Signup(
int? tid,
int zwid,
string name,
DateTime tm
);
public record Events(
uint rt,
string t,
DateTime tm,
int zid
)
{
public string RouteName { get => Routes.Names[rt]; }
public Uri RouteLink { get => new Uri(Routes.Links[rt]); }
}
public record EventResultBase(
string category,
int div,
int divw,
string flag,
bool male,
DateTime event_date,
string name,
int pos,
int position_in_cat,
int power_type,
string tbc,
string tbd,
string tc,
int? tid,
string tname,
long uid,
float? vtta,
float vttat,
int zid,
int zwid
);
public record EventResult(
string category,
int div,
int divw,
string flag,
bool male,
DateTime event_date,
string name,
int pos,
int position_in_cat,
float[] time,
float time_gun,
int power_type,
string tbc,
string tbd,
string tc,
int? tid,
string tname,
long uid,
float? vtta,
float vttat,
int[] wftp,
float[] wkg_ftp,
int zid,
int zwid
)
: EventResultBase(category, div, divw, flag, male, event_date, name, pos, position_in_cat, power_type, tbc, tbd, tc, tid, tname, uid, vtta, vttat, zid, zwid)
{
// we need to return a *new* instance here, otherwise it will use EventResult equality, *not* EventResultBase equality
public EventResultBase Base() => new EventResultBase(category, div, divw, flag, male, event_date, name, pos, position_in_cat, power_type, tbc, tbd, tc, tid, tname, uid, vtta, vttat, zid, zwid);
public static bool SequenceEqual(IEnumerable<EventResult> left, IEnumerable<EventResult> right)
=> Enumerable.SequenceEqual(left.Select(item => item.Base()), right.Select(item => item.Base()));
}
public record Member(
int div,
int divw,
string email,
string age,
string aid,
int climbed,
int distance,
int energy,
string flag,
int[] ftp,
string h_15_watts,
string h_15_wkg,
string h_1200_watts,
string h_1200_wkg,
string name,
string r,
string rank,
int reg,
int skill,
int skill_power,
int skill_seg,
string status,
int time,
float[] w,
int zada,
int zwid
);
public record LiveResult(
int position,
int pos_in_grp,
int time_diff,
int time_diff_cat,
int div,
bool male,
string name
);
public record Event(
int zid,
DateTime tm
);
public record FilteredResult(
string category,
int div,
int divw,
string flag,
bool male,
string name,
string note,
int power_type,
string tbc,
string tbd,
string tc,
int? tid,
float[] time,
float time_gun,
string tname,
long uid,
int?[] w5,
int?[] w15,
int?[] w30,
int?[] w60,
int?[] w120,
int?[] w300,
int?[] w1200,
float[] weight,
int[] wftp,
float?[] wkg5,
float?[] wkg15,
float?[] wkg30,
float?[] wkg60,
float?[] wkg120,
float?[] wkg300,
float?[] wkg1200,
float[] wkg_ftp,
bool wkg_guess,
int zid,
int zwid
);
public record Segment(
int id,
int lap,
string name,
int sprint_id,
SegmentRider rider_1,
SegmentRider rider_2,
SegmentRider rider_3,
SegmentRider rider_4,
SegmentRider rider_5,
SegmentRider rider_6,
SegmentRider rider_7,
SegmentRider rider_8,
SegmentRider rider_9,
SegmentRider rider_10
)
{
public List<SegmentRider> riders
{
get
{
var riders = new SegmentRider[] {
rider_1, rider_2, rider_3, rider_4, rider_5, rider_6, rider_7, rider_8, rider_9, rider_10
};
return riders.Where(rider => rider != null).ToList();
}
}
public bool IsLap { get => Segments.Laps.Contains((Segments.Segment)sprint_id); }
public bool IsClimb { get => Segments.Climbs.Contains((Segments.Segment)sprint_id); }
public bool IsSprint { get => Segments.Sprints.Contains((Segments.Segment)sprint_id); }
public Segments.Segment Value { get => (Segments.Segment)sprint_id; }
}
public record SegmentRider(
string age,
int div,
int divw,
float elapsed,
float elapsed_diff,
string flag,
int ftp,
string gender,
long msec,
float msec_diff,
string name,
string tbc,
string tbd,
string tc,
int tid,
string tname,
float w,
int zwid
);
}