Repository navigation
Expand file tree
/
Copy pathGameController.cs
More file actions
412 lines (368 loc) · 14.8 KB
/
Copy pathGameController.cs
File metadata and controls
412 lines (368 loc) · 14.8 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
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
/*
* Random Steam Game
*
* Copyright (c) 2026 Kyle Givler
* Licensed under the MIT License.
*/
using ErrorOr;
using JoyfulReaperLib.MissionControl;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using RandomSteamGame.Common.Errors;
using RandomSteamGame.Events;
using RandomSteamGame.Options;
using RandomSteamGame.Services;
using RandomSteamGame.Services.Interfaces;
using RandomSteamGame.Shared.Contracts;
using SteamApiClient.Services;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using SteamDeckCompatibilityCategory = SteamApiClient.Contracts.SteamApi.SteamDeckCompatibilityCategory;
namespace RandomSteamGame.Controllers;
[Route("api/{provider}")]
[AllowAnonymous]
[ApiController]
[EnableRateLimiting("steam_api_limiter")]
public class GameController : ApiController
{
private readonly GameProviderFactory _factory;
private readonly GameApplicationService _gameOperations;
private readonly IAppStatsService _appStatsService;
private readonly ISteamLibraryExportService _steamLibraryExportService;
private readonly IMissionControlClient _missionControlClient;
private readonly ApplicationOptions _applicationOptions;
private readonly ILogger<GameController> _logger;
private readonly IVisitorIdProvider _visitorIdProvider;
private readonly ILibraryExportCooldownTracker _libraryExportCooldownTracker;
private readonly LibraryExportOptions _libraryExportOptions;
private readonly GlobalLibraryExportCooldownTracker _globalExportCooldown;
public GameController(
GameProviderFactory factory,
GameApplicationService gameOperations,
IAppStatsService appStatsService,
ISteamLibraryExportService steamLibraryExportService,
IMissionControlClient missionControlClient,
IVisitorIdProvider visitorIdProvider,
ILibraryExportCooldownTracker libraryExportCooldownTracker,
IOptions<ApplicationOptions> applicationOptions,
ILogger<GameController> logger,
IOptions<LibraryExportOptions> libraryExportOptions,
GlobalLibraryExportCooldownTracker globalExportCooldown)
{
_missionControlClient = missionControlClient;
_visitorIdProvider = visitorIdProvider;
_applicationOptions = applicationOptions.Value;
_factory = factory;
_gameOperations = gameOperations;
_appStatsService = appStatsService;
_steamLibraryExportService = steamLibraryExportService;
_logger = logger;
_libraryExportCooldownTracker = libraryExportCooldownTracker;
_libraryExportOptions = libraryExportOptions.Value;
_globalExportCooldown = globalExportCooldown;
}
/// <summary>
/// Gets the list of owned games for a specific Steam ID.
/// GET /api/steam/{steamId}/library
/// </summary>
[HttpGet("{steamId}/library")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(OwnedGamesResponse))]
public async Task<IActionResult> GetLibrary(string provider, long steamId)
{
var result = await _gameOperations.GetLibrary(provider, steamId, HttpContext.RequestAborted);
return result.Match(Ok, Problem);
}
/// <summary>
/// Exports the list of owned games for a specific Steam ID as CSV.
/// POST /api/steam/{steamId}/library/export.csv
/// </summary>
[HttpPost("{steamId:long}/library/export.csv")]
[RequireAntiforgeryToken]
[EnableRateLimiting("library_export_limiter")]
[Produces("text/csv")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> ExportLibrary(
string provider,
long steamId)
{
var ct = HttpContext.RequestAborted;
ct.ThrowIfCancellationRequested();
Response.Headers["Cache-Control"] = "private, no-store";
Response.Headers["CDN-Cache-Control"] = "no-store";
if (!TryGetProvider(provider, out var service))
{
return Problem([Errors.Steam.UnsupportedProvider(provider)]);
}
if (!IsValidSteamId(steamId))
{
return Problem([Errors.Steam.InvalidSteamId]);
}
var occurredAt = DateTimeOffset.UtcNow;
var correlationId = Guid.NewGuid().ToString("N");
var partitionKey = LibraryExportRateLimitPartitionKey.From(HttpContext.Connection.RemoteIpAddress);
var isGlobal = _libraryExportOptions.RateLimitMode == LibraryExportRateLimitMode.Global;
var retryAfter = isGlobal
? _globalExportCooldown.TryStart()
: _libraryExportCooldownTracker.GetRetryAfter(partitionKey);
if (retryAfter is not null)
{
ct.ThrowIfCancellationRequested();
var retryAfterSeconds = Math.Max(1, (long)Math.Ceiling(retryAfter.Value.TotalSeconds));
Response.Headers.RetryAfter = retryAfterSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture);
_ = PublishLibraryExportRejectedEventAsync(
provider,
LibraryExportRejectionReason.Cooldown,
retryAfterSeconds,
occurredAt,
correlationId);
return new ContentResult
{
StatusCode = StatusCodes.Status429TooManyRequests,
ContentType = "text/plain; charset=utf-8",
Content = isGlobal
? $"Steam library CSV exports share a global cooldown. Please try again in {retryAfterSeconds} seconds."
: "Steam library CSV exports are limited to one per IP address " +
"every 72 hours after a successful export."
};
}
var stopwatch = Stopwatch.StartNew();
var result = await service.GetOwnedGamesAsync(steamId, ct);
ct.ThrowIfCancellationRequested();
if (result.IsError)
{
return Problem(result.Errors);
}
IReadOnlyDictionary<int, SteamDeckCompatibilityCategory> deckCompatibility =
new Dictionary<int, SteamDeckCompatibilityCategory>();
if (service is ISteamDeckCompatibilityProvider deckProvider)
{
deckCompatibility = await deckProvider.GetSteamDeckCompatibilityAsync(
result.Value.Games.Select(game => game.AppId),
ct);
}
ct.ThrowIfCancellationRequested();
var csvBytes = _steamLibraryExportService.Export(result.Value, deckCompatibility);
ct.ThrowIfCancellationRequested();
await TrackLibraryExportedAsync();
ct.ThrowIfCancellationRequested();
if (!isGlobal)
{
_libraryExportCooldownTracker.MarkSucceeded(partitionKey);
}
ct.ThrowIfCancellationRequested();
var verifiedCount = 0;
var playableCount = 0;
var unsupportedCount = 0;
var unknownCount = 0;
foreach (var game in result.Value.Games)
{
var category =
deckCompatibility.TryGetValue(game.AppId, out var value)
? value
: SteamDeckCompatibilityCategory.Unknown;
switch (category)
{
case SteamDeckCompatibilityCategory.Verified:
verifiedCount++;
break;
case SteamDeckCompatibilityCategory.Playable:
playableCount++;
break;
case SteamDeckCompatibilityCategory.Unsupported:
unsupportedCount++;
break;
default:
unknownCount++;
break;
}
}
stopwatch.Stop();
await PublishLibraryExportCompletedEventAsync(
provider,
result.Value.Games.Count,
stopwatch.ElapsedMilliseconds,
verifiedCount,
playableCount,
unsupportedCount,
unknownCount,
occurredAt,
correlationId);
ct.ThrowIfCancellationRequested();
return File(
csvBytes,
"text/csv; charset=utf-8",
$"steam-library-{steamId}.csv");
}
[HttpGet("{steamId:long}/library/export.csv")]
[HttpHead("{steamId:long}/library/export.csv")]
[DisableRateLimiting]
public IActionResult ExportLibraryMethodNotAllowed()
{
Response.Headers.Allow = "POST";
Response.Headers.CacheControl = "private, no-store";
Response.Headers["CDN-Cache-Control"] = "no-store";
return new ContentResult
{
StatusCode = StatusCodes.Status405MethodNotAllowed,
ContentType = "text/plain; charset=utf-8",
Content = "Library export requires POST with valid antiforgery credentials."
};
}
/// <summary>
/// Invalidates the cached owned games for a user.
/// POST /api/steam/{userId}/library/refresh
/// </summary>
[HttpPost("{userId}/library/refresh")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> RefreshLibrary(string provider, long userId)
{
var result = await _gameOperations.RefreshLibraryAsync(provider, userId, HttpContext.RequestAborted);
if (result.IsError)
{
return Problem(result.Errors);
}
return result.Value.CooldownProblem is { } problem
? StatusCode(StatusCodes.Status429TooManyRequests, problem)
: NoContent();
}
/// <summary>
/// Gets simplified game details for a random game.
/// GET /api/steam/random-game/details?userId=... OR ?vanityUrl=...
/// </summary>
[HttpGet("random-game/details")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(GameDetails))]
public async Task<IActionResult> GetRandomGameDetails(
string provider,
[FromQuery] long? userId,
[FromQuery] string? vanityUrl,
[FromQuery] bool unplayedOnly = false)
{
var result = await _gameOperations.GetRandomGameDetailsAsync(
provider, userId, vanityUrl, GameRequestContext.From(HttpContext), unplayedOnly, ct: HttpContext.RequestAborted);
return result.Match(Ok, Problem);
}
private async Task PublishLibraryExportRejectedEventAsync(
string? provider,
string reason,
long? retryAfterSeconds,
DateTimeOffset occurredAt,
string correlationId)
{
try
{
await _missionControlClient.TryPublishAsync(
eventType: RandomSteamGameEventTypes.LibraryExportRejected,
payload: new LibraryExportRejectedEvent(
VisitorId: GetVisitorIdForTelemetry(),
Provider: provider,
IngressNetwork: RandomSteamIngressNetwork.FromHost(HttpContext.Request.Host.Host),
Reason: reason,
RetryAfterSeconds: retryAfterSeconds,
CommitSha: string.IsNullOrWhiteSpace(_applicationOptions.CommitSha)
? null
: _applicationOptions.CommitSha),
occurredAt: occurredAt,
payloadTypeInfo: RandomSteamGameJsonContext.Default.LibraryExportRejectedEvent,
correlationId: correlationId,
cancellationToken: CancellationToken.None);
}
catch (Exception exception)
{
_logger.LogWarning(
exception,
"Failed to publish library-export rejection event {CorrelationId}.",
correlationId);
}
}
private async Task PublishLibraryExportCompletedEventAsync(
string provider,
int gameCount,
long durationMilliseconds,
int verifiedCount,
int playableCount,
int unsupportedCount,
int unknownCount,
DateTimeOffset occurredAt,
string correlationId)
{
try
{
await _missionControlClient.TryPublishAsync(
eventType: RandomSteamGameEventTypes.LibraryExportCompleted,
payload: new LibraryExportCompletedEvent(
VisitorId: GetVisitorIdForTelemetry(),
Provider: provider,
IngressNetwork: RandomSteamIngressNetwork.FromHost(HttpContext.Request.Host.Host),
GameCount: gameCount,
DurationMilliseconds: durationMilliseconds,
VerifiedCount: verifiedCount,
PlayableCount: playableCount,
UnsupportedCount: unsupportedCount,
UnknownCount: unknownCount,
CommitSha: string.IsNullOrWhiteSpace(_applicationOptions.CommitSha)
? null
: _applicationOptions.CommitSha),
occurredAt: occurredAt,
payloadTypeInfo: RandomSteamGameJsonContext.Default.LibraryExportCompletedEvent,
correlationId: correlationId,
cancellationToken: CancellationToken.None);
}
catch (Exception exception)
{
_logger.LogWarning(
exception,
"Failed to publish library-export event {CorrelationId}.",
correlationId);
}
}
/// <summary>
/// Utility: Resolves a vanity URL to a Steam ID.
/// GET /api/steam/resolve/{vanityUrl}
/// </summary>
[HttpGet("resolve/{vanityUrl}")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(long))]
public async Task<IActionResult> ResolveVanity(string provider, string vanityUrl)
{
var result = await _gameOperations.ResolveVanityAsync(provider, vanityUrl, HttpContext.RequestAborted);
return result.Match(value => Ok(value), Problem);
}
private bool TryGetProvider(
string provider,
[NotNullWhen(true)] out IGameProvider? service)
{
return _factory.TryGetProvider(provider, out service);
}
private static bool IsValidSteamId(long steamId) => GameApplicationService.IsValidSteamId(steamId);
private async Task TrackLibraryExportedAsync()
{
try
{
await _appStatsService.IncrementLibrariesExportedAsync();
}
catch (Exception exception)
{
// Stats must never prevent a successful export.
_logger.LogWarning(exception, "Failed to increment libraries exported counter.");
}
}
private string? GetVisitorIdForTelemetry()
{
try
{
var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
return string.IsNullOrWhiteSpace(ip)
? null
: _visitorIdProvider.GetVisitorId(ip);
}
catch (Exception exception)
{
_logger.LogWarning(
exception,
"Failed to generate visitor ID for game-pick telemetry.");
return null;
}
}
}