-
Notifications
You must be signed in to change notification settings - Fork 0
/
DownloadTask.cs
1938 lines (1607 loc) · 74.8 KB
/
DownloadTask.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Security;
using System.Text;
using Blake3;
using Dalamud.Interface.ImGuiNotification;
using DequeNet;
using gfoidl.Base64;
using Heliosphere.Exceptions;
using Heliosphere.Model;
using Heliosphere.Model.Api;
using Heliosphere.Model.Generated;
using Heliosphere.Model.Penumbra;
using Heliosphere.Ui;
using Heliosphere.Ui.Dialogs;
using Heliosphere.Util;
using Microsoft.VisualBasic.FileIO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Penumbra.Api.Enums;
using StrawberryShake;
using ZstdSharp;
namespace Heliosphere;
internal class DownloadTask : IDisposable {
#if LOCAL
internal const string ApiBase = "http://192.168.174.246:42011";
#else
internal const string ApiBase = "https://heliosphere.app/api";
#endif
internal Guid TaskId { get; } = Guid.NewGuid();
internal required Plugin Plugin { get; init; }
internal required string ModDirectory { get; init; }
internal required Guid PackageId { get; init; }
internal required Guid VariantId { get; init; }
internal required Guid VersionId { get; init; }
internal required Dictionary<string, List<string>> Options { get; init; }
internal required bool Full { get; init; }
internal required string? DownloadKey { get; init; }
internal required bool IncludeTags { get; init; }
internal required bool OpenInPenumbra { get; init; }
internal required Guid? PenumbraCollection { get; init; }
internal required IActiveNotification? Notification { get; set; }
private string? PenumbraModPath { get; set; }
private string? FilesPath { get; set; }
private string? HashesPath { get; set; }
internal string? PackageName { get; private set; }
internal string? VariantName { get; private set; }
internal CancellationTokenSource CancellationToken { get; } = new();
internal State State { get; private set; } = State.NotStarted;
private uint _stateData;
internal uint StateData => Interlocked.CompareExchange(ref this._stateData, 0, 0);
internal uint StateDataMax { get; private set; }
internal Exception? Error { get; private set; }
private ConcurrentDeque<Measurement> Entries { get; } = new();
private Util.SentryTransaction? Transaction { get; set; }
private bool SupportsHardLinks { get; set; }
private SemaphoreSlim DuplicateMutex { get; } = new(1, 1);
private bool RequiresDuplicateMutex { get; set; }
private HashSet<string> ExistingHashes { get; } = [];
/// <summary>
/// A list of files expected by the group jsons made by this task. These
/// paths should be relative to the files directory.
/// </summary>
private HashSet<string> ExpectedFiles { get; } = [];
private const double Window = 5;
private const string DefaultFolder = "_default";
internal double BytesPerSecond {
get {
if (this.Entries.Count == 0) {
return 0;
}
var total = 0u;
var removeTo = 0;
foreach (var entry in this.Entries) {
if (Stopwatch.GetElapsedTime(entry.Ticks) > TimeSpan.FromSeconds(Window)) {
removeTo += 1;
continue;
}
total += entry.Data;
}
for (var i = 0; i < removeTo; i++) {
this.Entries.TryPopLeft(out _);
}
return total / Window;
}
}
private bool _disposed;
/// This is non-null when a directory exists in the Penumbra directory that
/// starts with hs- and ends with the variant/package IDs, and it does not
/// equal the expected mod installation path. Essentially only true for
/// version updates (not reinstalls).
private string? _oldModName;
private bool _reinstall;
~DownloadTask() {
this.Dispose();
}
public void Dispose() {
if (this._disposed) {
return;
}
this._disposed = true;
GC.SuppressFinalize(this);
this.CancellationToken.Dispose();
this.DuplicateMutex.Dispose();
}
internal Task Start() {
return Task.Run(this.Run, this.CancellationToken.Token);
}
private async Task Run() {
using var setNull = new OnDispose(() => this.Transaction = null);
using var transaction = SentryHelper.StartTransaction(
this.GetType().Name,
nameof(this.Run)
);
this.Transaction = transaction;
this.Transaction?.Inner.SetExtras(new Dictionary<string, object?> {
[nameof(this.VersionId)] = this.VersionId.ToCrockford(),
[nameof(this.Options)] = this.Options,
[nameof(this.Full)] = this.Full,
["HasDownloadKey"] = this.DownloadKey != null,
[nameof(this.IncludeTags)] = this.IncludeTags,
});
SentrySdk.AddBreadcrumb("Started download", "user", data: new Dictionary<string, string> {
[nameof(this.VersionId)] = this.VersionId.ToCrockford(),
[nameof(this.PenumbraModPath)] = this.PenumbraModPath ?? "<null>",
[nameof(this.PenumbraCollection)] = this.PenumbraCollection?.ToString("N") ?? "<null>",
});
try {
var info = await this.GetPackageInfo();
if (this.Full) {
foreach (var group in GroupsUtil.Convert(info.Groups)) {
this.Options[group.Name] = [];
foreach (var option in group.Options) {
this.Options[group.Name].Add(option.Name);
}
}
}
this.Transaction?.Inner.SetExtra("Package", info.Variant.Package.Id.ToCrockford());
this.Transaction?.Inner.SetExtra("Variant", info.Variant.Id.ToCrockford());
this.PackageName = info.Variant.Package.Name;
this.VariantName = info.Variant.Name;
this.GenerateModDirectoryPath(info);
this.DetermineIfUpdate(info);
this.CreateDirectories();
await this.TestHardLinks();
this.CheckOutputPaths(info);
await this.HashExistingFiles();
await this.DownloadFiles(info);
await this.ConstructModPack(info);
this.RemoveWorkingDirectories();
this.RemoveOldFiles();
await this.AddMod(info);
// before setting state to finished, set the directory name
this.State = State.Finished;
Interlocked.Exchange(ref this._stateData, 1);
this.StateDataMax = 1;
if (!this.Plugin.Config.UseNotificationProgress) {
this.Notification = this.Notification.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Success,
title: "Install successful",
content: $"{this.PackageName} was installed in Penumbra.",
autoDuration: true
);
this.Notification.Click += async _ => await this.OpenModInPenumbra();
}
SentrySdk.AddBreadcrumb("Finished download", data: new Dictionary<string, string> {
[nameof(this.VersionId)] = this.VersionId.ToCrockford(),
});
if (this.OpenInPenumbra) {
await this.OpenModInPenumbra();
}
// refresh the manager package list after install finishes
using (this.Transaction?.StartChild(nameof(this.Plugin.State.UpdatePackages))) {
await this.Plugin.State.UpdatePackages(this.CancellationToken.Token);
}
} catch (Exception ex) when (ex is TaskCanceledException or OperationCanceledException) {
this.State = State.Cancelled;
Interlocked.Exchange(ref this._stateData, 0);
this.StateDataMax = 0;
if (this.Transaction?.Inner is { } inner) {
inner.Status = SpanStatus.Cancelled;
}
} catch (Exception ex) {
this.State = State.Errored;
Interlocked.Exchange(ref this._stateData, 0);
this.StateDataMax = 0;
this.Error = ex;
this.Notification = this.Notification.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Error,
title: "Install failed",
content: $"Failed to install {this.PackageName ?? "mod"}.",
autoDuration: true
);
if (this.Transaction?.Inner is { } inner) {
inner.Status = SpanStatus.InternalError;
}
this.Transaction?.Inner?.SetExtra("WasAntivirus", false);
// probably antivirus (ioexception is being used by other process or
// access denied)
if (ex.IsAntiVirus()) {
this.Plugin.PluginUi.OpenAntiVirusWarning();
Plugin.Log.Warning(ex, $"[AV] Error downloading version {this.VersionId}");
this.Transaction?.Inner?.SetExtra("WasAntivirus", true);
} else if (ex is MultipleModDirectoriesException multiple) {
await this.Plugin.PluginUi.AddToDrawAsync(new MultipleModDirectoriesDialog(
this.Plugin,
multiple
));
} else {
ErrorHelper.Handle(ex, $"Error downloading version {this.VersionId}", this.Transaction?.LatestChild()?.Inner ?? this.Transaction?.Inner);
}
}
}
private void SetStateData(uint current, uint max) {
Interlocked.Exchange(ref this._stateData, current);
this.StateDataMax = max;
}
internal static async Task<HttpResponseMessage> GetImage(Guid id, int imageId, CancellationToken token = default) {
var resp = await Plugin.Client.GetAsync2($"{ApiBase}/web/package/{id:N}/image/{imageId}", HttpCompletionOption.ResponseHeadersRead, token);
resp.EnsureSuccessStatusCode();
return resp;
}
private async Task<IDownloadTask_GetVersion> GetPackageInfo() {
using var span = this.Transaction?.StartChild(nameof(this.GetPackageInfo));
this.State = State.DownloadingPackageInfo;
this.SetStateData(0, 1);
var downloadKind = DownloadKind.Install;
var installed = await this.Plugin.State.GetInstalled(this.CancellationToken.Token);
if (installed.TryGetValue(this.PackageId, out var pkg)) {
if (pkg.Variants.Any(meta => meta.VariantId == this.VariantId)) {
downloadKind = DownloadKind.Update;
}
}
var resp = await Plugin.GraphQl.DownloadTask.ExecuteAsync(this.VersionId, this.Options, this.DownloadKey, this.Full, downloadKind, this.CancellationToken.Token);
resp.EnsureNoErrors();
var version = resp.Data?.GetVersion ?? throw new MissingVersionException(this.VersionId);
// sort needed files for dedupe consistency
foreach (var files in version.NeededFiles.Files.Files.Values) {
files.Sort((a, b) => string.Compare(string.Join(':', a), string.Join(':', b), StringComparison.Ordinal));
}
if (this.DownloadKey != null) {
this.Plugin.DownloadCodes.TryInsert(version.Variant.Package.Id, this.DownloadKey);
this.Plugin.DownloadCodes.Save();
}
Interlocked.Increment(ref this._stateData);
return version;
}
private void GenerateModDirectoryPath(IDownloadTask_GetVersion info) {
var dirName = HeliosphereMeta.ModDirectoryName(info.Variant.Package.Id, info.Variant.Package.Name, info.Version, info.Variant.Id);
this.PenumbraModPath = Path.Join(this.ModDirectory, dirName);
}
private void CreateDirectories() {
this.FilesPath = Path.GetFullPath(Path.Join(this.PenumbraModPath, "files"));
this.HashesPath = Path.GetFullPath(Path.Join(this.PenumbraModPath, ".hs-hashes"));
Plugin.Resilience.Execute(() => Directory.CreateDirectory(this.FilesPath));
Plugin.Resilience.Execute(() => {
try {
Directory.Delete(this.HashesPath, true);
} catch (DirectoryNotFoundException) {
// ignore
}
});
var di = Plugin.Resilience.Execute(() => Directory.CreateDirectory(this.HashesPath));
di.Attributes |= FileAttributes.Hidden;
}
private async Task TestHardLinks() {
string? a = null;
string? b = null;
try {
a = Path.Join(this.PenumbraModPath, Path.GetRandomFileName());
await FileHelper.Create(a, true).DisposeAsync();
b = Path.Join(this.PenumbraModPath, Path.GetRandomFileName());
FileHelper.CreateHardLink(a, b);
this.SupportsHardLinks = true;
} catch (InvalidOperationException) {
this.SupportsHardLinks = false;
} finally {
if (a != null) {
try {
File.Delete(a);
} catch (Exception ex) {
Plugin.Log.Warning(ex, "Could not delete temp files");
}
}
if (b != null) {
try {
File.Delete(b);
} catch (Exception ex) {
Plugin.Log.Warning(ex, "Could not delete temp files");
}
}
}
}
private void DetermineIfUpdate(IDownloadTask_GetVersion info) {
var directories = Directory.EnumerateDirectories(this.ModDirectory)
.Select(Path.GetFileName)
.Where(path => !string.IsNullOrEmpty(path))
.Cast<string>()
.Where(path =>
HeliosphereMeta.ParseDirectory(path) is { PackageId: var packageId, VariantId: var variantId }
&& packageId == info.Variant.Package.Id
&& variantId == info.Variant.Id
)
.ToArray();
if (directories.Length == 1) {
var oldName = Path.Join(this.ModDirectory, directories[0]!);
if (oldName == this.PenumbraModPath) {
// the path found is what we expect it to be, so this is not a
// version change but a reinstall
this._reinstall = true;
} else {
// the path found is not what we expect it to be, so the version
// has changed. rename the directory to the new version
this._oldModName = directories[0];
Directory.Move(oldName, this.PenumbraModPath!);
}
} else if (directories.Length > 1) {
var rejoined = directories
.Select(name => Path.Join(this.ModDirectory, name))
.ToArray();
throw new MultipleModDirectoriesException(
info.Variant.Package.Name,
info.Variant.Name,
info.Version,
rejoined
);
}
}
private void CheckOutputPaths(IDownloadTask_GetVersion info) {
var neededFiles = info.NeededFiles.Files.Files;
var outputToHash = new Dictionary<string, string>();
foreach (var (hash, file) in neededFiles) {
foreach (var outputPath in GetOutputPaths(file)) {
if (outputToHash.TryGetValue(outputPath, out var stored) && stored != hash) {
Plugin.Log.Warning($"V:{this.VersionId.ToCrockford()} has the same output path linked to multiple hashes, will use slow duplication");
this.RequiresDuplicateMutex = true;
return;
}
outputToHash[outputPath] = hash;
}
}
}
private async Task HashExistingFiles() {
this.State = State.CheckingExistingFiles;
this.SetStateData(0, 0);
if (this.FilesPath == null) {
throw new Exception("files path was null");
}
// hash => path
var hashes = new ConcurrentDictionary<string, string>();
var allFiles = DirectoryHelper.GetFilesRecursive(this.FilesPath).ToList();
this.StateDataMax = (uint) allFiles.Count;
await Parallel.ForEachAsync(
allFiles,
new ParallelOptions {
CancellationToken = this.CancellationToken.Token,
},
async (path, token) => {
using var blake3 = new Blake3HashAlgorithm();
blake3.Initialize();
await using var file = FileHelper.OpenSharedReadIfExists(path);
if (file == null) {
return;
}
await blake3.ComputeHashAsync(file, token);
var hash = Base64.Url.Encode(blake3.Hash);
hashes.TryAdd(hash, path);
Interlocked.Increment(ref this._stateData);
}
);
this.State = State.SettingUpExistingFiles;
this.SetStateData(0, (uint) hashes.Count);
Action<string, string> action = this.SupportsHardLinks
? FileHelper.CreateHardLink
: File.Move;
using var mutex = new SemaphoreSlim(1, 1);
await Parallel.ForEachAsync(
hashes,
new ParallelOptions {
CancellationToken = this.CancellationToken.Token,
},
async (entry, token) => {
var (hash, path) = entry;
// move/link each path to the hashes path
Plugin.Resilience.Execute(() => action(
path,
Path.Join(this.HashesPath, hash)
));
// ReSharper disable once AccessToDisposedClosure
using (await SemaphoreGuard.WaitAsync(mutex, token)) {
this.ExistingHashes.Add(hash);
}
Interlocked.Increment(ref this._stateData);
}
);
}
private async Task DownloadFiles(IDownloadTask_GetVersion info) {
using var span = this.Transaction?.StartChild(nameof(this.DownloadFiles));
var task = info.Batched
? this.DownloadBatchedFiles(info.NeededFiles, info.Batches, this.FilesPath!)
: this.DownloadNormalFiles(info.NeededFiles, this.FilesPath!);
await task;
}
private Task DownloadNormalFiles(IDownloadTask_GetVersion_NeededFiles neededFiles, string filesPath) {
using var span = this.Transaction?.StartChild(nameof(this.DownloadNormalFiles));
this.State = State.DownloadingFiles;
this.SetStateData(0, (uint) neededFiles.Files.Files.Count);
return Parallel.ForEachAsync(
neededFiles.Files.Files,
new ParallelOptions {
CancellationToken = this.CancellationToken.Token,
},
async (pair, token) => {
var (hash, files) = pair;
var outputPaths = GetOutputPaths(files);
using (await SemaphoreGuard.WaitAsync(Plugin.DownloadSemaphore, token)) {
await this.DownloadFile(new Uri(neededFiles.BaseUri), filesPath, outputPaths, hash);
}
}
);
}
private Task DownloadBatchedFiles(IDownloadTask_GetVersion_NeededFiles neededFiles, BatchList batches, string filesPath) {
using var span = this.Transaction?.StartChild(nameof(this.DownloadBatchedFiles));
this.State = State.DownloadingFiles;
this.SetStateData(0, 0);
var neededHashes = neededFiles.Files.Files.Keys.ToList();
var clonedBatches = batches.Files.ToDictionary(pair => pair.Key, pair => pair.Value.ToDictionary(pair => pair.Key, pair => pair.Value));
var seenHashes = new List<string>();
foreach (var (batch, files) in batches.Files) {
// remove any hashes that aren't needed
foreach (var hash in files.Keys) {
if (neededHashes.Contains(hash) && !seenHashes.Contains(hash)) {
seenHashes.Add(hash);
} else {
clonedBatches[batch].Remove(hash);
}
}
// remove any empty batches
if (clonedBatches[batch].Count == 0) {
clonedBatches.Remove(batch);
}
}
this.StateDataMax = (uint) neededFiles.Files.Files.Count;
return Parallel.ForEachAsync(
clonedBatches,
new ParallelOptions {
CancellationToken = this.CancellationToken.Token,
},
async (pair, token) => {
var (batch, batchedFiles) = pair;
// find which files from this batch we already have a hash for
var toDuplicate = new HashSet<string>();
foreach (var hash in batchedFiles.Keys) {
if (!this.ExistingHashes.Contains(hash)) {
continue;
}
toDuplicate.Add(hash);
}
// sort files in batch by offset, removing already-downloaded files
var listOfFiles = batchedFiles
.Select(pair => (Hash: pair.Key, Info: pair.Value))
.Where(pair => !this.ExistingHashes.Contains(pair.Hash))
.OrderBy(pair => pair.Info.Offset).ToList();
if (listOfFiles.Count > 0) {
// calculate ranges
var ranges = new List<(ulong, ulong)>();
var begin = 0ul;
var end = 0ul;
var chunk = new List<string>();
var chunks = new List<List<string>>();
foreach (var (hash, info) in listOfFiles) {
if (begin == 0 && end == 0) {
// first item, so set begin and end
begin = info.Offset;
end = info.Offset + info.SizeCompressed;
// add the hash to this chunk
chunk.Add(hash);
continue;
}
if (info.Offset == end) {
// there's no gap, so extend the end of this range
end += info.SizeCompressed;
// add the hash to this chunk
chunk.Add(hash);
continue;
}
// there is a gap
// add this chunk to the list of chunks
chunks.Add(chunk);
// make a new chunk
chunk = [];
// add the range to the list of ranges
ranges.Add((begin, end));
// start a new range after the gap
begin = info.Offset;
end = info.Offset + info.SizeCompressed;
// add the hash to the new chunk
chunk.Add(hash);
}
if (end != 0) {
// add the last range if necessary
ranges.Add((begin, end));
if (chunk.Count > 0) {
chunks.Add(chunk);
}
}
// check if we're just downloading the whole file - cf cache
// won't kick in for range requests
var totalBatchSize = batchedFiles.Values
.Select(file => file.SizeCompressed)
// no Sum function for ulong
.Aggregate((total, size) => total + size);
RangeHeaderValue? rangeHeader;
if (ranges is [{ Item1: 0, Item2: var rangeEnd }] && rangeEnd == totalBatchSize) {
rangeHeader = null;
} else {
// construct the header
rangeHeader = new RangeHeaderValue();
foreach (var (from, to) in ranges) {
rangeHeader.Ranges.Add(new RangeItemHeaderValue((long) from, (long) to));
}
}
// construct the uri
var baseUri = new Uri(new Uri(neededFiles.BaseUri), "../batches/");
var uri = new Uri(baseUri, batch);
using (await SemaphoreGuard.WaitAsync(Plugin.DownloadSemaphore, token)) {
var counter = new StateCounter();
await Plugin.Resilience.ExecuteAsync(
async _ => {
// if we're retrying, remove the files that this task added
Interlocked.Add(ref this._stateData, UintHelper.OverflowSubtractValue(counter.Added));
counter.Added = 0;
await this.DownloadBatchedFile(neededFiles, filesPath, uri, rangeHeader, chunks, batchedFiles, counter);
},
token
);
}
}
foreach (var hash in toDuplicate) {
var joined = Path.Join(this.HashesPath, hash);
if (!File.Exists(joined)) {
Plugin.Log.Warning($"{joined} was supposed to be duplicated but no longer exists");
continue;
}
var gamePaths = neededFiles.Files.Files[hash];
var outputPaths = GetOutputPaths(gamePaths);
await this.DuplicateFile(filesPath, outputPaths, joined);
Interlocked.Increment(ref this._stateData);
}
}
);
}
private class StateCounter {
internal uint Added { get; set; }
}
private async Task DownloadBatchedFile(
IDownloadTask_GetVersion_NeededFiles neededFiles,
string filesPath,
Uri uri,
RangeHeaderValue? rangeHeader,
IReadOnlyList<List<string>> chunks,
IReadOnlyDictionary<string, BatchedFile> batchedFiles,
StateCounter counter
) {
using var span = this.Transaction?.StartChild(nameof(this.DownloadBatchedFile), true);
span?.Inner.SetExtras(new Dictionary<string, object?> {
[nameof(uri)] = uri,
[nameof(rangeHeader)] = rangeHeader,
[nameof(chunks)] = chunks,
[nameof(batchedFiles)] = batchedFiles,
});
// construct the request
using var req = new HttpRequestMessage(HttpMethod.Get, uri);
req.Headers.Range = rangeHeader;
// send the request
using var resp = await Plugin.Client.SendAsync2(req, HttpCompletionOption.ResponseHeadersRead, this.CancellationToken.Token);
resp.EnsureSuccessStatusCode();
// if only one chunk is requested, it's not multipart, so check
// for that
IMultipartProvider multipart;
if (resp.Content.IsMimeMultipartContent()) {
var boundary = resp.Content.Headers.ContentType
?.Parameters
.Find(p => p.Name == "boundary")
?.Value;
if (boundary == null) {
throw new Exception("missing boundary in multipart response");
}
multipart = new StandardMultipartProvider(boundary, resp.Content);
} else {
multipart = new SingleMultipartProvider(resp.Content);
}
using var disposeMultipart = new OnDispose(multipart.Dispose);
foreach (var chunk in chunks) {
await using var rawStream = await multipart.GetNextStreamAsync(this.CancellationToken.Token);
if (rawStream == null) {
throw new Exception("did not download correct number of chunks");
}
await using var stream = new GloballyThrottledStream(
rawStream,
this.Entries
);
// now we're going to read each file in the chunk out,
// decompress it, and write it to the disk
var buffer = new byte[81_920];
foreach (var hash in chunk) {
// firstly, we now need to figure out which extensions and
// discriminators to use for this specific file
var gamePaths = neededFiles.Files.Files[hash];
var outputPaths = GetOutputPaths(gamePaths);
if (outputPaths.Length == 0) {
Plugin.Log.Warning($"file with hash {hash} has no output paths");
continue;
}
var batchedFileInfo = batchedFiles[hash];
var path = Path.Join(filesPath, outputPaths[0]);
await using var file = FileHelper.Create(path, true);
// make a stream that's only capable of reading the
// amount of compressed bytes
await using var limited = new LimitedStream(stream, (int) batchedFileInfo.SizeCompressed);
await using var decompressor = new DecompressionStream(limited);
// make sure we only read *this* file - one file is only
// part of the multipart chunk
var total = 0ul;
while (total < batchedFileInfo.SizeUncompressed) {
var leftToRead = Math.Min(
(ulong) buffer.Length,
batchedFileInfo.SizeUncompressed - total
);
var read = await decompressor.ReadAsync(buffer.AsMemory(0, (int) leftToRead), this.CancellationToken.Token);
total += (ulong) read;
if (read == 0) {
break;
}
await file.WriteAsync(buffer.AsMemory()[..read], this.CancellationToken.Token);
}
// make sure we read all the bytes before moving on to
// the next file
limited.ReadToEnd(buffer);
// flush the file and close it
await file.FlushAsync(this.CancellationToken.Token);
// ReSharper disable once DisposeOnUsingVariable
await file.DisposeAsync();
// the file is now fully written to, so duplicate it if
// necessary
await this.DuplicateFile(filesPath, outputPaths, path);
Interlocked.Increment(ref this._stateData);
counter.Added += 1;
}
}
}
private static string MakePathPartsSafe(string input) {
var cleaned = input
.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, '\\', '/')
.Select(MakeFileNameSafe);
return string.Join(Path.DirectorySeparatorChar, cleaned);
}
private static string MakeFileNameSafe(string input) {
var invalid = Path.GetInvalidFileNameChars();
var sb = new StringBuilder(input.Length);
foreach (var ch in input) {
sb.Append(
Array.IndexOf(invalid, ch) == -1
? ch
: '-'
);
}
var path = sb.ToString();
return path.TrimEnd('.', ' ');
}
private static string[] GetOutputPaths(IReadOnlyCollection<List<string?>> files) {
return files
.Select(file => {
var outputPath = file[3];
if (outputPath != null) {
if (Path.GetExtension(outputPath) == string.Empty) {
// we need to add an extension or this can cause a crash
outputPath = Path.ChangeExtension(outputPath, Path.GetExtension(file[2]!));
}
return MakePathPartsSafe(outputPath);
}
var group = MakeFileNameSafe(file[0] ?? DefaultFolder);
var option = MakeFileNameSafe(file[1] ?? DefaultFolder);
var gamePath = MakePathPartsSafe(file[2]!);
return Path.Join(group, option, gamePath);
})
.Where(file => !string.IsNullOrEmpty(file))
.ToArray();
}
private async Task DuplicateFile(string filesDir, IEnumerable<string> outputPaths, string path) {
using var guard = this.RequiresDuplicateMutex
? await SemaphoreGuard.WaitAsync(this.DuplicateMutex, this.CancellationToken.Token)
: null;
if (!this.SupportsHardLinks) {
// If hard links aren't supported, copy the path to the first output
// path.
// This is done because things reference the first output path
// assuming it will exist. A copy is made to not mess up the
// validity of the ExistingPathHashes and ExistingHashPaths
// dictionaries. The old file will be removed in the remove step if
// necessary.
var firstPath = outputPaths.FirstOrDefault();
if (firstPath == null) {
return;
}
var dest = Path.Join(filesDir, firstPath);
if (dest.Equals(path, StringComparison.InvariantCultureIgnoreCase)) {
return;
}
var parent = PathHelper.GetParent(dest);
Plugin.Resilience.Execute(() => Directory.CreateDirectory(parent));
if (!await PathHelper.WaitForDelete(dest)) {
throw new DeleteFileException(dest);
}
// ReSharper disable once AccessToModifiedClosure
Plugin.Resilience.Execute(() => File.Copy(path, dest));
return;
}
foreach (var outputPath in outputPaths) {
await DuplicateInner(outputPath);
}
return;
async Task DuplicateInner(string dest) {
dest = Path.Join(filesDir, dest);
if (path.Equals(dest, StringComparison.InvariantCultureIgnoreCase)) {
return;
}
if (!Path.IsPathFullyQualified(path) || !Path.IsPathFullyQualified(dest)) {
throw new Exception($"{path} or {dest} was not fully qualified");
}
if (!await PathHelper.WaitForDelete(dest)) {
throw new DeleteFileException(dest);
}
var parent = PathHelper.GetParent(dest);
Plugin.Resilience.Execute(() => Directory.CreateDirectory(parent));
Plugin.Resilience.Execute(() => FileHelper.CreateHardLink(path, dest));
}
}
private void RemoveOldFiles() {
using var span = this.Transaction?.StartChild(nameof(this.RemoveOldFiles));
this.State = State.RemovingOldFiles;
this.SetStateData(0, 0);
// find old, normal files no longer being used to remove
var presentFiles = DirectoryHelper.GetFilesRecursive(this.FilesPath!)
.Select(path => PathHelper.MakeRelativeSub(this.FilesPath!, path))
.Where(path => !string.IsNullOrEmpty(path))
.Cast<string>()
.Select(path => path.ToLowerInvariant())
.ToHashSet();
// remove the files that we expect from the list of already-existing
// files - these are the files to remove now
presentFiles.ExceptWith(this.ExpectedFiles);
var total = (uint) presentFiles.Count;
this.SetStateData(0, total);
var done = 0u;
Parallel.ForEach(
presentFiles,
extra => {
var extraPath = Path.Join(this.FilesPath, extra);
Plugin.Log.Info($"removing extra file {extraPath}");
Plugin.Resilience.Execute(() => {
if (this.Plugin.Config.UseRecycleBin) {
try {
FileSystem.DeleteFile(extraPath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
} catch (Exception ex) when (ex is IOException { HResult: Consts.UsedByAnotherProcess } io) {
var procs = RestartManager.GetLockingProcesses(extraPath);
throw new AlreadyInUseException(io, extraPath, procs);
}
} else {
FileHelper.Delete(extraPath);
}
});
done += 1;
this.SetStateData(done, total);
}
);
// remove any empty directories
DirectoryHelper.RemoveEmptyDirectories(this.FilesPath!);
}
private async Task DownloadFile(Uri baseUri, string filesPath, string[] outputPaths, string hash) {
using var span = this.Transaction?.StartChild(nameof(this.DownloadFile), true);
span?.Inner.SetExtras(new Dictionary<string, object?> {
[nameof(hash)] = hash,
[nameof(outputPaths)] = outputPaths,
});
if (outputPaths.Length == 0) {
return;
}
// check each path for containment breaks when joining
foreach (var outputPath in outputPaths) {
var joined = Path.GetFullPath(Path.Join(filesPath, outputPath));
// check that this path is under the files path still
if (PathHelper.MakeRelativeSub(filesPath, joined) == null) {
throw new SecurityException($"path from mod was attempting to leave the files directory: '{joined}' is not within '{filesPath}'");
}
}
// find an existing path that has this hash
string validPath;
if (this.ExistingHashes.Contains(hash)) {
validPath = Path.Join(this.HashesPath, hash);
goto Duplicate;
}
// no valid, existing file, so download instead
var path = Path.Join(filesPath, outputPaths[0]);
validPath = path;
await Plugin.Resilience.ExecuteAsync(
async _ => {
var uri = new Uri(baseUri, hash).ToString();
using var resp = await Plugin.Client.GetAsync2(uri, HttpCompletionOption.ResponseHeadersRead, this.CancellationToken.Token);
resp.EnsureSuccessStatusCode();
await using var file = FileHelper.Create(path, true);
await using var stream = new GloballyThrottledStream(
await resp.Content.ReadAsStreamAsync(this.CancellationToken.Token),
this.Entries
);
await using var decompress = new DecompressionStream(stream);
await decompress.CopyToAsync(file, this.CancellationToken.Token);
span?.Inner.SetMeasurement("Decompressed", file.Position, MeasurementUnit.Information.Byte);
},
this.CancellationToken.Token
);
Duplicate:
await this.DuplicateFile(filesPath, outputPaths, validPath);
Interlocked.Increment(ref this._stateData);
}
private async Task ConstructModPack(IDownloadTask_GetVersion info) {
using var span = this.Transaction?.StartChild(nameof(this.ConstructModPack));
this.State = State.ConstructingModPack;