-
Notifications
You must be signed in to change notification settings - Fork 274
Expand file tree
/
Copy pathDownloadTask.ts
More file actions
619 lines (565 loc) Β· 18 KB
/
DownloadTask.ts
File metadata and controls
619 lines (565 loc) Β· 18 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
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
import http from '@ohos.net.http';
import fileIo from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import { zlib } from '@kit.BasicServicesKit';
import { EventHub } from './EventHub';
import { DownloadTaskParams } from './DownloadTaskParams';
import { saveFileToSandbox } from './SaveFile';
import { util } from '@kit.ArkTS';
import NativePatchCore, {
ARCHIVE_PATCH_TYPE_FROM_PACKAGE,
ARCHIVE_PATCH_TYPE_FROM_PPK,
CopyGroupResult,
} from './NativePatchCore';
interface PatchManifestArrays {
copyFroms: string[];
copyTos: string[];
deletes: string[];
}
const DIFF_MANIFEST_ENTRY = '__diff.json';
const HARMONY_BUNDLE_PATCH_ENTRY = 'bundle.harmony.js.patch';
const TEMP_ORIGIN_BUNDLE_ENTRY = '.origin.bundle.harmony.js';
const FILE_COPY_BUFFER_SIZE = 64 * 1024;
export class DownloadTask {
private context: common.Context;
private hash: string;
private eventHub: EventHub;
constructor(context: common.Context) {
this.context = context;
this.eventHub = EventHub.getInstance();
}
private async removeDirectory(path: string): Promise<void> {
try {
const res = fileIo.accessSync(path);
if (res) {
const stat = await fileIo.stat(path);
if (stat.isDirectory()) {
const files = await fileIo.listFile(path);
for (const file of files) {
if (file === '.' || file === '..') {
continue;
}
await this.removeDirectory(`${path}/${file}`);
}
await fileIo.rmdir(path);
} else {
await fileIo.unlink(path);
}
}
} catch (error) {
console.error('Failed to delete directory:', error);
throw error;
}
}
private async ensureDirectory(path: string): Promise<void> {
if (!path || fileIo.accessSync(path)) {
return;
}
const parentPath = path.substring(0, path.lastIndexOf('/'));
if (parentPath && parentPath !== path) {
await this.ensureDirectory(parentPath);
}
if (!fileIo.accessSync(path)) {
try {
await fileIo.mkdir(path);
} catch (error) {
if (!fileIo.accessSync(path)) {
throw error;
}
}
}
}
private async ensureParentDirectory(filePath: string): Promise<void> {
const parentPath = filePath.substring(0, filePath.lastIndexOf('/'));
if (!parentPath) {
return;
}
await this.ensureDirectory(parentPath);
}
private async recreateDirectory(path: string): Promise<void> {
await this.removeDirectory(path);
await this.ensureDirectory(path);
}
private async readFileContent(filePath: string): Promise<ArrayBuffer> {
const stat = await fileIo.stat(filePath);
const reader = await fileIo.open(filePath, fileIo.OpenMode.READ_ONLY);
const content = new ArrayBuffer(stat.size);
try {
await fileIo.read(reader.fd, content);
return content;
} finally {
await fileIo.close(reader);
}
}
private async listEntryNames(directory: string): Promise<string[]> {
const files = await fileIo.listFile(directory);
const validFiles = files.filter(file => file !== '.' && file !== '..');
const stats = await Promise.all(
validFiles.map(file => fileIo.stat(`${directory}/${file}`)),
);
return validFiles.filter((_, index) => !stats[index].isDirectory());
}
private async writeFileContent(
targetFile: string,
content: ArrayBuffer | Uint8Array,
): Promise<void> {
const payload =
content instanceof Uint8Array ? content : new Uint8Array(content);
await this.ensureParentDirectory(targetFile);
if (fileIo.accessSync(targetFile)) {
await fileIo.unlink(targetFile);
}
let writer: fileIo.File | null = null;
try {
writer = await fileIo.open(
targetFile,
fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY,
);
const chunkSize = FILE_COPY_BUFFER_SIZE;
let bytesWritten = 0;
while (bytesWritten < payload.byteLength) {
const chunk = payload.subarray(bytesWritten, bytesWritten + chunkSize);
await fileIo.write(writer.fd, chunk);
bytesWritten += chunk.byteLength;
}
} finally {
if (writer) {
await fileIo.close(writer);
}
}
}
private parseJsonEntry(content: ArrayBuffer): Record<string, any> {
return JSON.parse(
new util.TextDecoder().decodeToString(new Uint8Array(content)),
) as Record<string, any>;
}
private async readManifestArrays(
directory: string,
normalizeResourceCopies: boolean,
): Promise<PatchManifestArrays> {
const manifestPath = `${directory}/${DIFF_MANIFEST_ENTRY}`;
if (!fileIo.accessSync(manifestPath)) {
return {
copyFroms: [],
copyTos: [],
deletes: [],
};
}
return this.manifestToArrays(
this.parseJsonEntry(await this.readFileContent(manifestPath)),
normalizeResourceCopies,
);
}
private manifestToArrays(
manifest: Record<string, any>,
normalizeResourceCopies: boolean,
): PatchManifestArrays {
const copyFroms: string[] = [];
const copyTos: string[] = [];
const deletesValue = manifest.deletes;
const deletes = Array.isArray(deletesValue)
? deletesValue.map(item => String(item))
: deletesValue && typeof deletesValue === 'object'
? Object.keys(deletesValue)
: [];
const copies = (manifest.copies || {}) as Record<string, string>;
for (const [to, rawFrom] of Object.entries(copies)) {
let from = String(rawFrom || '');
if (normalizeResourceCopies) {
from = from.replace('resources/rawfile/', '');
if (!from) {
from = to;
}
}
copyFroms.push(from);
copyTos.push(to);
}
return {
copyFroms,
copyTos,
deletes,
};
}
private async applyBundlePatchFromFileSource(
originContent: ArrayBuffer,
workingDirectory: string,
bundlePatchPath: string,
outputFile: string,
): Promise<void> {
const originBundlePath = `${workingDirectory}/${TEMP_ORIGIN_BUNDLE_ENTRY}`;
try {
await this.writeFileContent(originBundlePath, originContent);
NativePatchCore.applyPatchFromFileSource({
copyFroms: [],
copyTos: [],
deletes: [],
sourceRoot: workingDirectory,
targetRoot: workingDirectory,
originBundlePath,
bundlePatchPath,
bundleOutputPath: outputFile,
enableMerge: false,
});
} catch (error) {
error.message = `Failed to process bundle patch: ${error.message}`;
throw error;
} finally {
if (fileIo.accessSync(originBundlePath)) {
await fileIo.unlink(originBundlePath);
}
}
}
private async copySandboxFile(
sourceFile: string,
targetFile: string,
): Promise<void> {
let reader: fileIo.File | null = null;
let writer: fileIo.File | null = null;
const buffer = new ArrayBuffer(FILE_COPY_BUFFER_SIZE);
let offset = 0;
try {
reader = await fileIo.open(sourceFile, fileIo.OpenMode.READ_ONLY);
await this.ensureParentDirectory(targetFile);
if (fileIo.accessSync(targetFile)) {
await fileIo.unlink(targetFile);
}
writer = await fileIo.open(
targetFile,
fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY,
);
while (true) {
const readLength = await fileIo.read(reader.fd, buffer, {
offset,
length: FILE_COPY_BUFFER_SIZE,
});
if (readLength <= 0) {
break;
}
await fileIo.write(writer.fd, new Uint8Array(buffer, 0, readLength));
offset += readLength;
if (readLength < FILE_COPY_BUFFER_SIZE) {
break;
}
}
} finally {
if (reader) {
await fileIo.close(reader);
}
if (writer) {
await fileIo.close(writer);
}
}
}
private async downloadFile(params: DownloadTaskParams): Promise<void> {
const httpRequest = http.createHttp();
this.hash = params.hash;
let writer: fileIo.File | null = null;
let contentLength = 0;
let received = 0;
let writeError: Error | null = null;
let writeQueue = Promise.resolve();
const closeWriter = async () => {
if (writer) {
await fileIo.close(writer);
writer = null;
}
};
const dataEndPromise = new Promise<void>((resolve, reject) => {
httpRequest.on('dataEnd', () => {
writeQueue
.then(async () => {
if (writeError) {
throw writeError;
}
await closeWriter();
resolve();
})
.catch(async error => {
await closeWriter();
reject(error);
});
});
});
try {
let exists = fileIo.accessSync(params.targetFile);
if (exists) {
await fileIo.unlink(params.targetFile);
} else {
await this.ensureParentDirectory(params.targetFile);
}
writer = await fileIo.open(
params.targetFile,
fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE,
);
httpRequest.on('headersReceive', (header: Record<string, string>) => {
if (!header) {
return;
}
const lengthKey = Object.keys(header).find(
key => key.toLowerCase() === 'content-length',
);
if (!lengthKey) {
return;
}
const length = parseInt(header[lengthKey], 10);
if (!Number.isNaN(length)) {
contentLength = length;
}
});
httpRequest.on('dataReceive', (data: ArrayBuffer) => {
if (writeError) {
return;
}
received += data.byteLength;
writeQueue = writeQueue.then(async () => {
if (!writer || writeError) {
return;
}
try {
await fileIo.write(writer.fd, data);
} catch (error) {
writeError = error as Error;
}
});
this.onProgressUpdate(received, contentLength);
});
httpRequest.on(
'dataReceiveProgress',
(data: http.DataReceiveProgressInfo) => {
if (data.totalSize > 0) {
contentLength = data.totalSize;
}
if (data.receiveSize > received) {
received = data.receiveSize;
}
this.onProgressUpdate(received, contentLength);
},
);
const responseCode = await httpRequest.requestInStream(params.url, {
method: http.RequestMethod.GET,
readTimeout: 60000,
connectTimeout: 60000,
header: {
'Content-Type': 'application/octet-stream',
},
});
if (responseCode > 299) {
throw Error(`Server error: ${responseCode}`);
}
await dataEndPromise;
const stats = await fileIo.stat(params.targetFile);
const fileSize = stats.size;
if (contentLength > 0 && fileSize !== contentLength) {
throw Error(
`Download incomplete: expected ${contentLength} bytes but got ${stats.size} bytes`,
);
}
} catch (error) {
console.error('Download failed:', error);
throw error;
} finally {
try {
await closeWriter();
} catch (closeError) {
console.error('Failed to close file:', closeError);
}
httpRequest.off('headersReceive');
httpRequest.off('dataReceive');
httpRequest.off('dataReceiveProgress');
httpRequest.off('dataEnd');
httpRequest.destroy();
}
}
private onProgressUpdate(received: number, total: number): void {
this.eventHub.emit('RCTPushyDownloadProgress', {
received,
total,
hash: this.hash,
});
}
private async doFullPatch(params: DownloadTaskParams): Promise<void> {
await this.downloadFile(params);
await this.recreateDirectory(params.unzipDirectory);
await zlib.decompressFile(params.targetFile, params.unzipDirectory);
}
private async doPatchFromApp(params: DownloadTaskParams): Promise<void> {
await this.downloadFile(params);
await this.recreateDirectory(params.unzipDirectory);
await zlib.decompressFile(params.targetFile, params.unzipDirectory);
const [entryNames, manifestArrays] = await Promise.all([
this.listEntryNames(params.unzipDirectory),
this.readManifestArrays(params.unzipDirectory, true),
]);
NativePatchCore.buildArchivePatchPlan(
ARCHIVE_PATCH_TYPE_FROM_PACKAGE,
entryNames,
manifestArrays.copyFroms,
manifestArrays.copyTos,
manifestArrays.deletes,
HARMONY_BUNDLE_PATCH_ENTRY,
);
const bundlePatchPath = `${params.unzipDirectory}/${HARMONY_BUNDLE_PATCH_ENTRY}`;
if (!fileIo.accessSync(bundlePatchPath)) {
throw Error('bundle patch not found');
}
const resourceManager = this.context.resourceManager;
const originContent = await resourceManager.getRawFileContent(
'bundle.harmony.js',
);
await this.applyBundlePatchFromFileSource(
originContent,
params.unzipDirectory,
bundlePatchPath,
`${params.unzipDirectory}/bundle.harmony.js`,
);
await this.copyFromResource(
NativePatchCore.buildCopyGroups(
manifestArrays.copyFroms,
manifestArrays.copyTos,
),
params.unzipDirectory,
);
}
private async doPatchFromPpk(params: DownloadTaskParams): Promise<void> {
await this.downloadFile(params);
await this.recreateDirectory(params.unzipDirectory);
await zlib.decompressFile(params.targetFile, params.unzipDirectory);
const [entryNames, manifestArrays] = await Promise.all([
this.listEntryNames(params.unzipDirectory),
this.readManifestArrays(params.unzipDirectory, false),
]);
const plan = NativePatchCore.buildArchivePatchPlan(
ARCHIVE_PATCH_TYPE_FROM_PPK,
entryNames,
manifestArrays.copyFroms,
manifestArrays.copyTos,
manifestArrays.deletes,
HARMONY_BUNDLE_PATCH_ENTRY,
);
NativePatchCore.applyPatchFromFileSource({
copyFroms: manifestArrays.copyFroms,
copyTos: manifestArrays.copyTos,
deletes: manifestArrays.deletes,
sourceRoot: params.originDirectory,
targetRoot: params.unzipDirectory,
originBundlePath: `${params.originDirectory}/bundle.harmony.js`,
bundlePatchPath: `${params.unzipDirectory}/${HARMONY_BUNDLE_PATCH_ENTRY}`,
bundleOutputPath: `${params.unzipDirectory}/bundle.harmony.js`,
mergeSourceSubdir: plan.mergeSourceSubdir,
enableMerge: plan.enableMerge,
});
console.info('Patch from PPK completed');
}
private async copyFromResource(
copyGroups: CopyGroupResult[],
targetRoot: string,
): Promise<void> {
let currentFrom = '';
try {
const resourceManager = this.context.resourceManager;
for (const group of copyGroups) {
currentFrom = group.from;
const targets = group.toPaths.map(path => `${targetRoot}/${path}`);
if (targets.length === 0) {
continue;
}
if (currentFrom.startsWith('resources/base/media/')) {
const mediaName = currentFrom
.replace('resources/base/media/', '')
.split('.')[0];
const mediaBuffer = await resourceManager.getMediaByName(mediaName);
const parentDirs = [
...new Set(
targets.map(t => t.substring(0, t.lastIndexOf('/'))).filter(Boolean),
),
];
for (const dir of parentDirs) {
await this.ensureDirectory(dir);
}
await Promise.all(
targets.map(target => this.writeFileContent(target, mediaBuffer.buffer)),
);
continue;
}
const fromContent = await resourceManager.getRawFd(currentFrom);
const [firstTarget, ...restTargets] = targets;
const parentDirs = [
...new Set(
targets.map(t => t.substring(0, t.lastIndexOf('/'))).filter(Boolean),
),
];
for (const dir of parentDirs) {
await this.ensureDirectory(dir);
}
if (fileIo.accessSync(firstTarget)) {
await fileIo.unlink(firstTarget);
}
saveFileToSandbox(fromContent, firstTarget);
await Promise.all(
restTargets.map(target => this.copySandboxFile(firstTarget, target)),
);
}
} catch (error) {
error.message =
'Copy from resource failed:' +
currentFrom +
',' +
error.code +
',' +
error.message;
console.error(error);
throw error;
}
}
private async doCleanUp(params: DownloadTaskParams): Promise<void> {
try {
NativePatchCore.cleanupOldEntries(
params.unzipDirectory,
params.hash || '',
params.originHash || '',
7,
);
} catch (error) {
error.message = 'Cleanup failed:' + error.message;
console.error(error);
throw error;
}
}
public async execute(params: DownloadTaskParams): Promise<void> {
try {
switch (params.type) {
case DownloadTaskParams.TASK_TYPE_PATCH_FULL:
await this.doFullPatch(params);
break;
case DownloadTaskParams.TASK_TYPE_PATCH_FROM_APP:
await this.doPatchFromApp(params);
break;
case DownloadTaskParams.TASK_TYPE_PATCH_FROM_PPK:
await this.doPatchFromPpk(params);
break;
case DownloadTaskParams.TASK_TYPE_CLEANUP:
await this.doCleanUp(params);
break;
case DownloadTaskParams.TASK_TYPE_PLAIN_DOWNLOAD:
await this.downloadFile(params);
break;
default:
throw Error(`Unknown task type: ${params.type}`);
}
} catch (error) {
console.error('Task execution failed:', error.message);
if (params.type !== DownloadTaskParams.TASK_TYPE_CLEANUP) {
try {
if (params.type === DownloadTaskParams.TASK_TYPE_PLAIN_DOWNLOAD) {
await fileIo.unlink(params.targetFile);
} else {
await this.removeDirectory(params.unzipDirectory);
}
} catch (cleanupError) {
console.error('Cleanup after error failed:', cleanupError.message);
}
}
throw error;
}
}
}