-
Notifications
You must be signed in to change notification settings - Fork 1
/
ApiClient.cs
237 lines (194 loc) · 8.05 KB
/
ApiClient.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
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Spectre.Console;
#pragma warning disable CA1031 // Do not catch general exception types
namespace SteamTokenDumper;
internal sealed class ApiClient : IDisposable
{
public const uint Version = 1728691200; // 2024-10-12
public const string Token = "@STEAMDB_BUILD_TOKEN@";
private const string Endpoint = "https://tokendumper.steamdb.info";
private HttpClient HttpClient = new();
public ApiClient()
{
var appVersion = typeof(Program).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
HttpClient.DefaultRequestVersion = HttpVersion.Version30;
HttpClient.Timeout = TimeSpan.FromMinutes(10);
HttpClient.DefaultRequestHeaders.Add("User-Agent", $"{nameof(SteamTokenDumper)} v{Version} ({RuntimeInformation.RuntimeIdentifier} {appVersion})");
}
public void Dispose()
{
HttpClient?.Dispose();
HttpClient = null;
}
public async Task<bool> SendTokens(Payload payload, Configuration config)
{
if (config.DumpPayload)
{
var payloadDump = new PayloadDump(payload);
var file = Path.Combine(Program.AppPath, "SteamTokenDumper.payload.json");
try
{
var json = JsonSerializer.SerializeToUtf8Bytes(payloadDump, new PayloadDumpJsonContext(new JsonSerializerOptions
{
WriteIndented = true,
}).PayloadDump);
await File.WriteAllBytesAsync(file, json);
AnsiConsole.WriteLine($"Written payload dump to '{Path.GetFileName(file)}'. Modifying this file will not do anything.");
}
catch (Exception e)
{
AnsiConsole.Write(
new Panel(new Text($"Failed to write payload dump: {e}", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
AnsiConsole.WriteLine();
}
if (config.VerifyBeforeSubmit)
{
// Read any buffered keys so it doesn't auto submit
while (Console.KeyAvailable)
{
Console.ReadKey(true);
}
AnsiConsole.WriteLine();
AnsiConsole.WriteLine("Press any key to continue submission...");
Console.ReadKey(true);
}
var returnValue = false;
Ansi.Progress(Ansi.ProgressState.Indeterminate);
await AnsiConsole.Status()
.StartAsync("Submitting tokens to SteamDB...", async ctx =>
{
var postData = JsonSerializer.Serialize(payload, PayloadJsonContext.Default.Payload);
try
{
using var content = new StringContent(postData, Encoding.UTF8, "application/json");
var result = await HttpClient.PostAsync($"{Endpoint}/submit", content);
var output = await result.Content.ReadAsStringAsync();
output = output.Trim();
if (!result.IsSuccessStatusCode)
{
AnsiConsole.Write(
new Panel(new Text($"Failed to submit tokens to SteamDB, received status code: {(int)result.StatusCode} ({result.ReasonPhrase})", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
var statusCode = (int)result.StatusCode;
if (result.StatusCode == HttpStatusCode.TooManyRequests)
{
output = "You got rate limited, please try again later.";
}
else if (statusCode < 200 || statusCode >= 500)
{
output = $"Something went wrong (HTTP {statusCode}).";
}
AnsiConsole.Write(
new Panel(new Text(output, new Style(result.IsSuccessStatusCode ? Color.CadetBlue : Color.Red)))
.BorderColor(result.IsSuccessStatusCode ? Color.Blue : Color.Red)
.RoundedBorder()
);
try
{
output = $"Dump submitted on {DateTime.Now}\nSteamID used: {payload.SteamID}\n\n{output}\n\n---\n\n".Replace("\r", "", StringComparison.Ordinal);
if (OperatingSystem.IsWindows())
{
output = output.Replace("\n", "\r\n", StringComparison.Ordinal);
}
await File.AppendAllTextAsync(Path.Combine(Program.AppPath, "SteamTokenDumper.result.log"), output);
}
catch (Exception)
{
// don't care
}
returnValue = true;
}
catch (Exception e)
{
AnsiConsole.Write(
new Panel(new Text($"Failed to submit tokens to SteamDB: {e}", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
});
Ansi.Progress(Ansi.ProgressState.Hidden);
return returnValue;
}
public async Task<bool> IsUpToDate()
{
try
{
var result = await HttpClient.GetAsync($"{Endpoint}/version");
result.EnsureSuccessStatusCode();
var version = await result.Content.ReadAsStringAsync();
if (!version.StartsWith("version=", StringComparison.Ordinal))
{
throw new InvalidDataException("Failed to get version.");
}
var versionInt = uint.Parse(version[8..], CultureInfo.InvariantCulture);
if (versionInt != Version)
{
AnsiConsole.Write(
new Panel(new Text("There is a new version of the token dumper available.\nPlease download the new version.", new Style(Color.Green)))
.BorderColor(Color.GreenYellow)
.RoundedBorder()
);
return false;
}
}
catch (Exception e)
{
AnsiConsole.Write(
new Panel(new Text($"Update check failed: {e}\n\nYour submission will most likely fail.", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
return false;
}
return true;
}
public async Task<ImmutableHashSet<uint>> GetBackendKnownDepotIds()
{
try
{
var result = await HttpClient.GetAsync($"{Endpoint}/knowndepots.csv");
result.EnsureSuccessStatusCode();
using var reader = new StreamReader(await result.Content.ReadAsStreamAsync());
var count = await reader.ReadLineAsync();
var countInt = int.Parse(count, CultureInfo.InvariantCulture);
var list = new HashSet<uint>(countInt);
while (await reader.ReadLineAsync() is { } line)
{
if (line.Length == 0)
{
continue;
}
list.Add(uint.Parse(line, CultureInfo.InvariantCulture));
}
return [.. list];
}
catch (Exception e)
{
AnsiConsole.Write(
new Panel(new Text($"Failed to get list of depots to skip: {e}", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
return [];
}
}