-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
283 lines (235 loc) · 11.4 KB
/
Program.cs
File metadata and controls
283 lines (235 loc) · 11.4 KB
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
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.Extensions.Configuration;
using StravaCloner.Models;
namespace StravaCloner
{
class Program
{
static async Task Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
string? clientId = config["Strava:ClientId"];
string? clientSecret = config["Strava:ClientSecret"];
string? refreshToken = config["Strava:RefreshToken"];
if (string.IsNullOrEmpty(clientId) || clientId == "YOUR_CLIENT_ID")
{
Console.WriteLine("Please configure your Strava API keys in appsettings.json");
return;
}
Console.WriteLine("Getting Strava Access Token...");
string? accessToken = await GetAccessToken(clientId, clientSecret, refreshToken);
if (string.IsNullOrEmpty(accessToken))
{
Console.WriteLine("Failed to get Access Token. Exiting.");
return;
}
Console.WriteLine("Successfully authenticated!");
Console.WriteLine();
string gpxDirectory = Path.Combine(Directory.GetCurrentDirectory(), "GPX");
if (!Directory.Exists(gpxDirectory))
{
Console.WriteLine($"GPX directory not found at: {gpxDirectory}. Please create it and add your GPX files.");
return;
}
var gpxFiles = Directory.GetFiles(gpxDirectory, "*.gpx");
if (gpxFiles.Length == 0)
{
Console.WriteLine($"No .gpx files found in the directory: {gpxDirectory}");
return;
}
Console.WriteLine("Available GPX files:");
for (int i = 0; i < gpxFiles.Length; i++)
{
Console.WriteLine($"[{i + 1}] {Path.GetFileName(gpxFiles[i])}");
}
Console.Write("\nEnter the number of the GPX file you want to upload: ");
string? selectionStr = Console.ReadLine();
if (!int.TryParse(selectionStr, out int selectedIndex) || selectedIndex < 1 || selectedIndex > gpxFiles.Length)
{
Console.WriteLine("Invalid selection. Exiting.");
return;
}
string gpxPath = gpxFiles[selectedIndex - 1];
Console.WriteLine($"Selected file: {Path.GetFileName(gpxPath)}");
Console.WriteLine();
Console.Write("Enter the new start timestamp (e.g., yyyy-MM-dd HH:mm:ss): ");
string? timeString = Console.ReadLine();
if (!DateTime.TryParse(timeString, out DateTime newStartTime))
{
Console.WriteLine("Invalid timestamp format.");
return;
}
// Convert to UTC as GPX typically stores UTC time
newStartTime = newStartTime.ToUniversalTime();
Console.Write("Enter a device name (e.g., Garmin Edge 530) or press Enter to keep original: ");
string? deviceName = Console.ReadLine();
Console.WriteLine($"Processing GPX file...");
string? newGpxPath = ProcessGpxFile(gpxPath, newStartTime, deviceName);
if (string.IsNullOrEmpty(newGpxPath))
{
return;
}
Console.WriteLine($"GPX timestamps shifted. Modified file saved to: {newGpxPath}");
Console.WriteLine("Uploading to Strava...");
await UploadToStrava(accessToken, newGpxPath);
// Clean up temporary file
// if (File.Exists(newGpxPath))
// {
// File.Delete(newGpxPath);
// }
Console.WriteLine("Done.");
}
static async Task<string?> GetAccessToken(string? clientId, string? clientSecret, string? refreshToken)
{
using var client = new HttpClient();
var values = new System.Collections.Generic.Dictionary<string, string>
{
{ "client_id", clientId ?? "" },
{ "client_secret", clientSecret ?? "" },
{ "grant_type", "refresh_token" },
{ "refresh_token", refreshToken ?? "" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://www.strava.com/oauth/token", content);
if (response.IsSuccessStatusCode)
{
var responseString = await response.Content.ReadAsStringAsync();
var tokenResponse = JsonSerializer.Deserialize<StravaTokenResponse>(responseString);
return tokenResponse?.AccessToken;
}
Console.WriteLine($"Error getting token: {response.StatusCode}");
string errorBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(errorBody);
return null;
}
static string? ProcessGpxFile(string filePath, DateTime newStartTime, string? deviceName)
{
try
{
XDocument gpxDoc = XDocument.Load(filePath);
if (!string.IsNullOrWhiteSpace(deviceName) && gpxDoc.Root != null)
{
var creatorAttr = gpxDoc.Root.Attribute("creator");
if (creatorAttr != null)
{
creatorAttr.Value = deviceName;
}
else
{
gpxDoc.Root.Add(new XAttribute("creator", deviceName));
}
}
XNamespace? ns = gpxDoc.Root?.GetDefaultNamespace() ?? XNamespace.None;
// Find the first time element to calculate the shift required
var firstTimeElement = gpxDoc.Descendants(ns + "time").FirstOrDefault();
if (firstTimeElement == null)
{
Console.WriteLine("No <time> elements found in the GPX file.");
return null;
}
if (!DateTime.TryParse(firstTimeElement.Value, out DateTime originalStartTime))
{
Console.WriteLine($"Could not parse the original start time: {firstTimeElement.Value}");
return null;
}
// Ensure original time is UTC for correct mathematical difference
originalStartTime = originalStartTime.ToUniversalTime();
TimeSpan timeShift = newStartTime - originalStartTime;
Console.WriteLine($"Original Start: {originalStartTime:O}");
Console.WriteLine($"New Start: {newStartTime:O}");
Console.WriteLine($"Time Shift: {timeShift}");
// Shift all time elements
foreach (var timeElement in gpxDoc.Descendants(ns + "time"))
{
if (DateTime.TryParse(timeElement.Value, out DateTime currentTime))
{
DateTime shiftedTime = currentTime.ToUniversalTime() + timeShift;
// GPX standard prefers ISO 8601 with 'Z' for UTC
timeElement.Value = shiftedTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
}
string newPath = Path.Combine(Path.GetDirectoryName(filePath) ?? "", $"shifted_{Path.GetFileName(filePath)}");
gpxDoc.Save(newPath);
return newPath;
}
catch (Exception ex)
{
Console.WriteLine($"Error processing GPX file: {ex.Message}");
return null;
}
}
static async Task UploadToStrava(string accessToken, string filePath)
{
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using var form = new MultipartFormDataContent();
// Add the file content
using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using var streamContent = new StreamContent(fileStream);
streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(streamContent, "file", Path.GetFileName(filePath));
// Add required metadata
form.Add(new StringContent("gpx"), "data_type");
Console.WriteLine("Sending file to Strava /uploads endpoint...");
var response = await client.PostAsync("https://www.strava.com/api/v3/uploads", form);
var responseString = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Upload failed with status {response.StatusCode}");
Console.WriteLine(responseString);
return;
}
var uploadResponse = JsonSerializer.Deserialize<StravaUploadResponse>(responseString);
Console.WriteLine($"Upload created successfully. Upload ID: {uploadResponse?.Id}");
await PollUploadStatus(client, uploadResponse?.Id ?? 0);
}
static async Task PollUploadStatus(HttpClient client, long uploadId)
{
if (uploadId == 0) return;
Console.WriteLine("Polling for processing status...");
bool isProcessing = true;
while (isProcessing)
{
await Task.Delay(3000); // Poll every 3 seconds
var response = await client.GetAsync($"https://www.strava.com/api/v3/uploads/{uploadId}");
var responseString = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var status = JsonSerializer.Deserialize<StravaUploadResponse>(responseString);
Console.WriteLine($"Status: {status?.Status}");
if (!string.IsNullOrEmpty(status?.Error))
{
Console.WriteLine($"Error during processing: {status.Error}");
isProcessing = false;
}
else if (status?.ActivityId != null)
{
Console.WriteLine($"Activity successfully created! Activity ID: {status.ActivityId}");
Console.WriteLine($"View at: https://www.strava.com/activities/{status.ActivityId}");
isProcessing = false;
}
else if (status?.Status == "Your activity is ready.") // Sometimes ActivityId is null but status indicates ready (rare but possible depending on parsing)
{
Console.WriteLine("Status indicates ready, but ActivityId was not parsed.");
isProcessing = false;
}
}
else
{
Console.WriteLine($"Failed to check status: {response.StatusCode}");
isProcessing = false;
}
}
}
}
}