-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDecodeService.cs
More file actions
459 lines (408 loc) · 14.7 KB
/
DecodeService.cs
File metadata and controls
459 lines (408 loc) · 14.7 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
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
using dsstats.challenge.Services;
using dsstats.shared;
using Microsoft.Extensions.Options;
using pax.dsstats.parser;
using s2protocol.NET;
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
namespace dsstats.decode;
public partial class DecodeService(IOptions<DecodeSettings> decodeSettings,
IHttpClientFactory httpClientFactory,
ILogger<DecodeService> logger)
{
private readonly SemaphoreSlim ss = new(1, 1);
private readonly SemaphoreSlim ssRaw = new(1, 1);
private readonly SemaphoreSlim fileSemaphore = new SemaphoreSlim(1, 1);
private ReplayDecoder? replayDecoder;
private int queueCount = 0;
private ConcurrentBag<string> excludeReplays = [];
public EventHandler<DecodeEventArgs>? DecodeFinished;
public EventHandler<DecodeRawEventArgs>? DecodeRawFinished;
private async void OnDecodeFinished(DecodeEventArgs e)
{
var httpClient = httpClientFactory.CreateClient("callback");
try
{
var result = await httpClient.PostAsJsonAsync($"/api8/v1/upload/decoderesult/{e.Guid}", e.IhReplays);
result.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
logger.LogError("failed reporting decoderesult: {error}", ex.Message);
}
DecodeFinished?.Invoke(this, e);
}
private async void OnDecodeRawFinished(DecodeRawEventArgs e)
{
var httpClient = httpClientFactory.CreateClient("callback");
try
{
var result = await httpClient.PostAsJsonAsync($"/api8/v1/upload/decoderawresult/{e.Guid}", e.ChallengeResponses);
result.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
logger.LogError("failed reporting decoderesult: {error}", ex.Message);
}
DecodeRawFinished?.Invoke(this, e);
}
public async Task<int> SaveReplays(Guid guid, List<IFormFile> files)
{
return await SaveReplays(guid, files, decodeSettings.Value.ReplayFolders.ToDo);
}
public async Task<int> SaveReplaysRaw(Guid guid, List<IFormFile> files)
{
return await SaveReplays(guid, files, decodeSettings.Value.ReplayFolders.ToDoRaw);
}
private async Task<int> SaveReplays(Guid guid, List<IFormFile> files, string folder)
{
int filesSaved = 0;
try
{
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
string fileHash;
using (var md5 = MD5.Create())
{
using var stream = formFile.OpenReadStream();
fileHash = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLowerInvariant();
}
var destinationFile = Path.Combine(decodeSettings.Value.ReplayFolders.Done, $"{fileHash}.SC2Replay");
var todoFolder = folder;
if (!Directory.Exists(todoFolder))
{
Directory.CreateDirectory(todoFolder);
}
var todoFile = Path.Combine(todoFolder, $"{guid}_{fileHash}.SC2Replay");
if (File.Exists(destinationFile))
{
logger.LogInformation("File {FileName} already exists. Skipping upload.", formFile.FileName);
continue;
}
try
{
var tmpFile = todoFile + ".tmp";
using (var fileStream = File.Create(tmpFile))
{
await formFile.CopyToAsync(fileStream);
fileStream.Close();
}
File.Move(tmpFile, todoFile);
filesSaved++;
}
catch (Exception ex)
{
logger.LogError(ex, "Error saving file {FileName}.", formFile.FileName);
}
}
else
{
logger.LogWarning("File {FileName} is empty and will be skipped.", formFile.FileName);
}
}
if (folder.EndsWith("raw"))
{
_ = DecodeRaw();
}
else
{
_ = Decode();
}
}
catch (Exception ex)
{
logger.LogError(ex, "Unexpected error in SaveReplays.");
return -1;
}
logger.LogInformation("{FilesSaved} files saved for GUID {Guid}.", filesSaved, guid);
return filesSaved;
}
public async Task Decode()
{
Interlocked.Increment(ref queueCount);
await ss.WaitAsync();
ConcurrentDictionary<Guid, ConcurrentBag<IhReplay>> replays = [];
string? error = null;
try
{
var replayPaths = Directory.GetFiles(decodeSettings.Value.ReplayFolders.ToDo, "*SC2Replay");
replayPaths = replayPaths.Except(excludeReplays).ToArray();
if (replayPaths.Length == 0)
{
error = "No replays found.";
return;
}
if (replayDecoder is null)
{
replayDecoder = new();
}
var options = new ReplayDecoderOptions()
{
Initdata = true,
Details = true,
Metadata = true,
TrackerEvents = true,
};
using var md5 = MD5.Create();
await foreach (var result in
replayDecoder.DecodeParallelWithErrorReport(replayPaths, decodeSettings.Value.Threads, options))
{
if (result.Sc2Replay is null)
{
Error(result);
error = "failed decoding replays.";
continue;
}
var metaData = GetMetaData(result.Sc2Replay);
var sc2Replay = Parse.GetDsReplay(result.Sc2Replay);
if (sc2Replay is null)
{
Error(result);
error = "failed decoding replays.";
continue;
}
var replayDto = Parse.GetReplayDto(sc2Replay, md5);
if (replayDto is null)
{
Error(result);
error = "failed decoding replays.";
continue;
}
var destination = Path.Combine(decodeSettings.Value.ReplayFolders.Done,
Path.GetFileNameWithoutExtension(result.ReplayPath)[..36] +
"_" +
replayDto.ReplayHash +
Path.GetExtension(result.ReplayPath));
await fileSemaphore.WaitAsync();
try
{
if (!File.Exists(destination))
{
File.Move(result.ReplayPath, destination);
var groupId = GetGroupIdFromFilename(result.ReplayPath);
var ihReplay = new IhReplay() { Replay = replayDto, Metadata = metaData };
replays.AddOrUpdate(groupId, [ihReplay], (k, v) => { v.Add(ihReplay); return v; });
}
}
finally
{
fileSemaphore.Release();
}
}
}
catch (Exception ex)
{
logger.LogError("failed decoding replays: {error}", ex.Message);
error = "failed decoding replays.";
}
finally
{
ss.Release();
foreach (var ent in replays)
{
OnDecodeFinished(new()
{
Guid = ent.Key,
IhReplays = [.. ent.Value],
Error = error,
});
}
Interlocked.Decrement(ref queueCount);
}
}
public async Task DecodeRaw()
{
Interlocked.Increment(ref queueCount);
await ssRaw.WaitAsync();
ConcurrentDictionary<Guid, ConcurrentBag<ChallengeResponse>> challengeResponses = [];
string? error = null;
try
{
var replayPaths = Directory.GetFiles(Path.Combine(decodeSettings.Value.ReplayFolders.ToDoRaw), "*SC2Replay");
replayPaths = replayPaths.Except(excludeReplays).ToArray();
if (replayPaths.Length == 0)
{
error = "No replays found.";
return;
}
if (replayDecoder is null)
{
replayDecoder = new();
}
var options = new ReplayDecoderOptions()
{
Initdata = true,
Details = true,
Metadata = true,
TrackerEvents = true,
};
await foreach (var result in
replayDecoder.DecodeParallelWithErrorReport(replayPaths, decodeSettings.Value.Threads, options))
{
if (result.Sc2Replay is null)
{
Error(result);
error = "failed decoding replays.";
continue;
}
var challengeResponse = ChallengeService.GetChallengeResponse(result.Sc2Replay);
var destination = Path.Combine(decodeSettings.Value.ReplayFolders.Done, Path.GetFileName(result.ReplayPath));
await fileSemaphore.WaitAsync();
try
{
if (!File.Exists(destination))
{
File.Move(result.ReplayPath, destination);
var groupId = GetGroupIdFromFilename(result.ReplayPath);
challengeResponses.AddOrUpdate(groupId, [challengeResponse], (k, v) => { v.Add(challengeResponse); return v; });
}
}
finally
{
fileSemaphore.Release();
}
}
}
catch (Exception ex)
{
logger.LogError("failed decoding replays: {error}", ex.Message);
error = "failed decoding replays.";
}
finally
{
ssRaw.Release();
foreach (var ent in challengeResponses)
{
OnDecodeRawFinished(new()
{
Guid = ent.Key,
ChallengeResponses = [.. ent.Value],
Error = error,
});
}
Interlocked.Decrement(ref queueCount);
}
}
private void Error(DecodeParallelResult result)
{
logger.LogError("failed decoding replay: {path}, {error}", result.ReplayPath, result.Exception);
try
{
File.Move(result.ReplayPath, Path.Combine(decodeSettings.Value.ReplayFolders.Error, Path.GetFileName(result.ReplayPath)));
}
catch (Exception ex)
{
logger.LogWarning("failed moving error replay: {error}", ex.Message);
excludeReplays.Add(result.ReplayPath);
}
}
private ReplayMetadata GetMetaData(Sc2Replay replay)
{
List<ReplayMetadataPlayer> players = [];
if (replay.Initdata is null || replay.Details is null || replay.Metadata is null)
{
return new();
}
foreach (var player in replay.Initdata.LobbyState.Slots)
{
players.Add(new()
{
PlayerId = GetPlayerId(player.ToonHandle),
Observer = player.Observe == 1,
SlotId = player.WorkingSetSlotId
});
}
int i = 0;
foreach (var player in replay.Details.Players)
{
i++;
PlayerId playerId = GetPlayerId(player.Toon);
var metaPlayer = players.FirstOrDefault(f => f.PlayerId == playerId);
if (metaPlayer is null)
{
continue;
}
metaPlayer.Id = i;
metaPlayer.Name = player.Name;
metaPlayer.AssignedRace = GetRace(player.Race);
}
foreach (var player in replay.Metadata.Players)
{
var metaPlayer = players.FirstOrDefault(f => f.Id == player.PlayerID);
if (metaPlayer is null)
{
continue;
}
metaPlayer.SelectedRace = GetSelectedRace(player.SelectedRace);
}
return new()
{
Players = players
};
}
private static Guid GetGroupIdFromFilename(string replayPath)
{
var fileName = Path.GetFileNameWithoutExtension(replayPath);
var guids = fileName.Split('_', StringSplitOptions.RemoveEmptyEntries);
if (guids.Length > 0 && Guid.TryParse(guids[0], out var groupId)
&& groupId != Guid.Empty)
{
return groupId;
}
throw new Exception($"failed getting groupId from replayPath: {replayPath}");
}
private static Commander GetSelectedRace(string selectedRace)
{
var race = selectedRace switch
{
"Terr" => "Terran",
"Prot" => "Protoss",
"Rand" => "None",
_ => selectedRace
};
return GetRace(race);
}
private static PlayerId GetPlayerId(s2protocol.NET.Models.Toon toon)
{
return new(toon.Id, toon.Realm, toon.Region);
}
private static PlayerId GetPlayerId(string toonHandle)
{
Regex rx = PlayerIdRegex();
var match = rx.Match(toonHandle);
if (match.Success)
{
int regionId = int.Parse(match.Groups[1].Value);
int realmId = int.Parse(match.Groups[2].Value);
int toonId = int.Parse(match.Groups[3].Value);
return new(toonId, realmId, regionId);
}
return new();
}
private static Commander GetRace(string race)
{
if (Enum.TryParse(typeof(Commander), race, out var cmdrObj)
&& cmdrObj is Commander cmdr)
{
return cmdr;
}
return Commander.None;
}
[GeneratedRegex(@"(\d)-S2-(\d)-(\d+)")]
private static partial Regex PlayerIdRegex();
}
public class DecodeEventArgs : EventArgs
{
public Guid Guid { get; set; }
public List<IhReplay> IhReplays { get; set; } = [];
public string? Error { get; set; }
}
public class DecodeRawEventArgs : EventArgs
{
public Guid Guid { get; set; }
public List<ChallengeResponse> ChallengeResponses { get; set; } = [];
public string? Error { get; set; }
}