-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSophonPatchAsset.Download.cs
More file actions
376 lines (336 loc) · 16.5 KB
/
SophonPatchAsset.Download.cs
File metadata and controls
376 lines (336 loc) · 16.5 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
using Hi3Helper.Sophon.Helper;
using Hi3Helper.Sophon.Infos;
using Hi3Helper.Sophon.Structs;
using System;
using System.Buffers;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
// ReSharper disable IdentifierTypo
// ReSharper disable CommentTypo
// ReSharper disable AccessToModifiedClosure
using TaskExtensions = Hi3Helper.Sophon.Helper.TaskExtensions;
using ZstdStream = ZstdNet.DecompressionStream;
namespace Hi3Helper.Sophon
{
public enum SophonPatchMethod
{
CopyOver,
DownloadOver,
Patch,
Remove
}
public partial class SophonPatchAsset : SophonIdentifiableProperty
{
internal const int BufferSize = 64 << 10;
public SophonAsset MainAssetInfo { get; set; }
public SophonChunksInfo PatchInfo { get; set; }
public SophonPatchMethod PatchMethod { get; set; }
public string PatchNameSource { get; set; }
public string PatchHash { get; set; }
public long PatchOffset { get; set; }
public long PatchSize { get; set; }
public long PatchChunkLength { get; set; }
public string OriginalFilePath { get; set; }
public string OriginalFileHash { get; set; }
public long OriginalFileSize { get; set; }
public string TargetFilePath { get; set; }
public string TargetFileHash { get; set; }
public long TargetFileSize { get; set; }
public override string ToString() => TargetFilePath;
#nullable enable
public async Task<bool> DownloadPatchAsync(HttpClient client,
string inputDir,
string patchOutputDir,
bool forceVerification = false,
Action<long>? downloadReadDelegate = null,
SophonDownloadSpeedLimiter? downloadSpeedLimiter = null,
CancellationToken token = default)
{
// Ignore SophonPatchMethod.Remove and SophonPatchMethod.DownloadOver assets
if (PatchMethod is SophonPatchMethod.Remove or
SophonPatchMethod.DownloadOver)
{
return true;
}
FileInfo patchFilePathHashedFileInfo = this.GetLegacyOrHoyoPlayPatchChunkPath(patchOutputDir);
if (!PatchNameSource.TryGetChunkXxh64Hash(out byte[] patchHash))
{
patchHash = Extension.HexToBytes(PatchHash.AsSpan());
}
SophonChunk patchAsChunk = new()
{
ChunkHashDecompressed = patchHash,
ChunkName = PatchNameSource,
ChunkOffset = 0,
ChunkOldOffset = 0,
ChunkSize = PatchSize,
ChunkSizeDecompressed = PatchSize,
IsSkipHashCheckOnWrite = true
};
bool isPatchFileExist = patchFilePathHashedFileInfo.Exists;
FileStream? fileStream = isPatchFileExist
? patchFilePathHashedFileInfo
.Open(new FileStreamOptions
{
// Use pre-check for file mode to prevent overhead over OS API.
Mode = FileMode.Open,
Access = FileAccess.Read,
Share = FileShare.Read, // Only share and open for read access to enable OS-level file caching.
BufferSize = PatchSize.GetFileStreamBufferSize()
})
: null;
try
{
bool isPatchMatched = fileStream != null && fileStream.Length == PatchSize;
if (forceVerification && fileStream != null)
{
isPatchMatched = patchHash.Length > 8
? await patchAsChunk.CheckChunkMd5HashAsync(fileStream,
true,
token)
: await patchAsChunk.CheckChunkXxh64HashAsync(fileStream,
patchHash,
true,
token);
}
if (isPatchMatched)
{
#if DEBUG
this.PushLogDebug($"Skipping patch {PatchNameSource} for: {TargetFilePath}");
#endif
downloadReadDelegate?.Invoke(PatchSize);
return true;
}
if (fileStream != null)
{
#if NET6_0_OR_GREATER
await fileStream.DisposeAsync();
#else
fileStream?.Dispose();
#endif
}
fileStream = patchFilePathHashedFileInfo.Open(new FileStreamOptions
{
Mode = FileMode.Create,
Access = FileAccess.ReadWrite,
Share = FileShare.ReadWrite,
BufferSize = PatchSize.GetFileStreamBufferSize()
});
await InnerWriteChunkCopyAsync(client,
fileStream,
patchAsChunk,
PatchInfo,
PatchInfo,
writeInfoDelegate: null,
downloadInfoDelegate: (_, y) =>
{
downloadReadDelegate?.Invoke(y);
},
downloadSpeedLimiter: downloadSpeedLimiter,
token: token);
return true;
}
finally
{
if (fileStream != null)
{
#if NET6_0_OR_GREATER
await fileStream.DisposeAsync();
#else
fileStream?.Dispose();
#endif
}
}
}
private async
Task
InnerWriteChunkCopyAsync(HttpClient client,
Stream outStream,
SophonChunk chunk,
SophonChunksInfo currentSophonChunkInfo,
SophonChunksInfo altSophonChunkInfo,
DelegateWriteStreamInfo? writeInfoDelegate,
DelegateWriteDownloadInfo? downloadInfoDelegate,
SophonDownloadSpeedLimiter? downloadSpeedLimiter,
CancellationToken token)
{
const int retryCount = TaskExtensions.DefaultRetryAttempt;
int currentRetry = 0;
long currentWriteOffset = 0;
#if !NOSTREAMLOCK
if (outStream is FileStream fs)
{
fs.Lock(chunk.ChunkOffset, chunk.ChunkSizeDecompressed);
this.PushLogDebug($"Locked data stream from pos: 0x{chunk.ChunkOffset:x8}" +
$" -> L: 0x{chunk.ChunkSizeDecompressed:x8} for chunk: {chunk.ChunkName}" +
$" by asset: {TargetFilePath}");
}
#endif
while (true)
{
bool allowDispose = false;
HttpResponseMessage? httpResponseMessage = null;
Stream? httpResponseStream = null;
Stream? sourceStream = null;
byte[] buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
{
try
{
CancellationTokenSource innerTimeoutToken =
new(TimeSpan.FromSeconds(TaskExtensions.DefaultTimeoutSec)
#if NET8_0_OR_GREATER
, TimeProvider.System
#endif
);
CancellationTokenSource cooperatedToken =
CancellationTokenSource.CreateLinkedTokenSource(token, innerTimeoutToken.Token);
#if DEBUG
this.PushLogDebug($"Init. by offset: 0x{chunk.ChunkOffset:x8}" +
$" -> L: 0x{chunk.ChunkSizeDecompressed:x8} for chunk: {chunk.ChunkName}");
#endif
outStream.Position = 0;
httpResponseMessage = await client
.GetChunkAndIfAltAsync(chunk.ChunkName,
currentSophonChunkInfo,
altSophonChunkInfo,
cooperatedToken.Token);
httpResponseStream = await httpResponseMessage
.EnsureSuccessStatusCode()
.Content
.ReadAsStreamAsync(
#if NET6_0_OR_GREATER
cooperatedToken.Token
#endif
);
sourceStream = httpResponseStream;
#if DEBUG
this.PushLogDebug($"[Complete init.] by offset: 0x{chunk.ChunkOffset:x8}" +
$" -> L: 0x{chunk.ChunkSizeDecompressed:x8} for chunk: {chunk.ChunkName}");
#endif
int read;
while ((read = await sourceStream.ReadAsync(
#if NET6_0_OR_GREATER
buffer
#else
buffer, 0, buffer.Length
#endif
, cooperatedToken.Token)
.ConfigureAwait(false)) > 0)
{
await (downloadSpeedLimiter?.AddBytesOrWaitAsync(read, token) ?? ValueTask.CompletedTask);
#if NET6_0_OR_GREATER
await outStream.WriteAsync(buffer.AsMemory(0, read), cooperatedToken.Token).ConfigureAwait(false);
#else
await outStream.WriteAsync(buffer, 0, read, cooperatedToken.Token).ConfigureAwait(false);
#endif
currentWriteOffset += read;
writeInfoDelegate?.Invoke(read);
downloadInfoDelegate?.Invoke(read, read);
currentRetry = 0;
innerTimeoutToken.Dispose();
cooperatedToken.Dispose();
innerTimeoutToken =
new CancellationTokenSource(TimeSpan.FromSeconds(TaskExtensions.DefaultTimeoutSec)
#if NET8_0_OR_GREATER
, TimeProvider.System
#endif
);
cooperatedToken =
CancellationTokenSource.CreateLinkedTokenSource(token, innerTimeoutToken.Token);
}
if (chunk.IsSkipHashCheckOnWrite)
{
return;
}
outStream.Position = 0;
Stream checkHashStream = outStream;
bool isHashVerified;
if (chunk.ChunkName.TryGetChunkXxh64Hash(out byte[] outHash))
{
isHashVerified =
await chunk.CheckChunkXxh64HashAsync(checkHashStream,
outHash,
true,
cooperatedToken.Token);
}
else
{
if (PatchInfo.IsUseCompression)
{
checkHashStream = new ZstdStream(checkHashStream);
}
isHashVerified =
await chunk.CheckChunkMd5HashAsync(checkHashStream,
true,
cooperatedToken.Token);
}
if (!isHashVerified)
{
writeInfoDelegate?.Invoke(-chunk.ChunkSizeDecompressed);
downloadInfoDelegate?.Invoke(-chunk.ChunkSizeDecompressed, 0);
this.PushLogWarning("Output data seems to be corrupted at transport.\r\n" +
$"Restarting download for chunk: {chunk.ChunkName} | 0x{chunk.ChunkOffset:x8}" +
$" -> L: 0x{chunk.ChunkSizeDecompressed:x8} for: {TargetFilePath}");
continue;
}
#if DEBUG
this.PushLogDebug($"Download completed! Chunk: {chunk.ChunkName}" +
$" | 0x{chunk.ChunkOffset:x8} -> L: 0x{chunk.ChunkSizeDecompressed:x8}" +
$" for: {TargetFilePath}");
#endif
return;
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
allowDispose = true;
throw;
}
catch (Exception ex)
{
if (currentRetry < retryCount)
{
writeInfoDelegate?.Invoke(-currentWriteOffset);
downloadInfoDelegate?.Invoke(-currentWriteOffset, 0);
currentWriteOffset = 0;
currentRetry++;
this.PushLogWarning("An error has occurred while" +
$" downloading chunk: {chunk.ChunkName}" +
$" | 0x{chunk.ChunkOffset:x8} -> L: 0x{chunk.ChunkSizeDecompressed:x8}" +
$" for: {TargetFilePath}\r\n{ex}");
await Task.Delay(TimeSpan.FromSeconds(1), token);
continue;
}
allowDispose = true;
this.PushLogError($"An unhandled error has occurred while downloading chunk:" +
$" {chunk.ChunkName} | 0x{chunk.ChunkOffset:x8} ->" +
$" L: 0x{chunk.ChunkSizeDecompressed:x8} for: {TargetFilePath}\r\n{ex}");
throw;
}
finally
{
if (allowDispose)
{
httpResponseMessage?.Dispose();
#if NET6_0_OR_GREATER
if (httpResponseStream != null)
{
await httpResponseStream.DisposeAsync();
}
if (sourceStream != null)
{
await sourceStream.DisposeAsync();
}
#else
sourceStream?.Dispose();
httpResponseStream?.Dispose();
#endif
}
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
}
}
}