-
Notifications
You must be signed in to change notification settings - Fork 274
Expand file tree
/
Copy pathDownloadTask.ts
More file actions
535 lines (490 loc) Β· 16 KB
/
DownloadTask.ts
File metadata and controls
535 lines (490 loc) Β· 16 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
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 Pushy from 'librnupdate.so';
import { saveFileToSandbox } from './SaveFile';
import { util } from '@kit.ArkTS';
interface ZipEntry {
filename: string;
content: ArrayBuffer;
}
interface ZipFile {
entries: ZipEntry[];
}
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 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 {
const targetDir = params.targetFile.substring(
0,
params.targetFile.lastIndexOf('/'),
);
exists = fileIo.accessSync(targetDir);
if (!exists) {
await fileIo.mkdir(targetDir);
}
}
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.removeDirectory(params.unzipDirectory);
await fileIo.mkdir(params.unzipDirectory);
await zlib.decompressFile(params.targetFile, params.unzipDirectory);
}
private async processUnzippedFiles(directory: string): Promise<ZipFile> {
const entries: ZipEntry[] = [];
try {
const files = await fileIo.listFile(directory);
for (const file of files) {
if (file === '.' || file === '..') {
continue;
}
const filePath = `${directory}/${file}`;
const stat = await fileIo.stat(filePath);
if (!stat.isDirectory()) {
const reader = await fileIo.open(filePath, fileIo.OpenMode.READ_ONLY);
const fileSize = stat.size;
const content = new ArrayBuffer(fileSize);
try {
await fileIo.read(reader.fd, content);
entries.push({
filename: file,
content: content,
});
} finally {
await fileIo.close(reader);
}
}
}
return { entries };
} catch (error) {
error.message = 'Failed to process unzipped files:' + error.message;
console.error(error);
throw error;
}
}
private async doPatchFromApp(params: DownloadTaskParams): Promise<void> {
await this.downloadFile(params);
await this.removeDirectory(params.unzipDirectory);
await fileIo.mkdir(params.unzipDirectory);
let foundDiff = false;
let foundBundlePatch = false;
const copyList: Map<string, Array<any>> = new Map();
await zlib.decompressFile(params.targetFile, params.unzipDirectory);
const zipFile = await this.processUnzippedFiles(params.unzipDirectory);
for (const entry of zipFile.entries) {
const fn = entry.filename;
if (fn === '__diff.json') {
foundDiff = true;
const bufferArray = new Uint8Array(entry.content);
const obj = JSON.parse(
new util.TextDecoder().decodeToString(bufferArray),
);
const copies = obj.copies as Record<string, string>;
for (const [to, rawPath] of Object.entries(copies)) {
let from = rawPath.replace('resources/rawfile/', '');
if (from === '') {
from = to;
}
if (!copyList.has(from)) {
copyList.set(from, []);
}
const target = copyList.get(from);
if (target) {
const toFile = `${params.unzipDirectory}/${to}`;
target.push(toFile);
}
}
continue;
}
if (fn === 'bundle.harmony.js.patch') {
foundBundlePatch = true;
try {
const resourceManager = this.context.resourceManager;
const originContent = await resourceManager.getRawFileContent(
'bundle.harmony.js',
);
const patched = await Pushy.hdiffPatch(
new Uint8Array(originContent.buffer),
new Uint8Array(entry.content),
);
const outputFile = `${params.unzipDirectory}/bundle.harmony.js`;
const writer = await fileIo.open(
outputFile,
fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY,
);
const chunkSize = 4096;
let bytesWritten = 0;
const totalLength = patched.byteLength;
while (bytesWritten < totalLength) {
const chunk = patched.slice(bytesWritten, bytesWritten + chunkSize);
await fileIo.write(writer.fd, chunk);
bytesWritten += chunk.byteLength;
}
await fileIo.close(writer);
continue;
} catch (error) {
error.message = 'Failed to process bundle patch:' + error.message;
throw error;
}
}
}
if (!foundDiff) {
throw Error('diff.json not found');
}
if (!foundBundlePatch) {
throw Error('bundle patch not found');
}
await this.copyFromResource(copyList);
}
private async doPatchFromPpk(params: DownloadTaskParams): Promise<void> {
await this.downloadFile(params);
await this.removeDirectory(params.unzipDirectory);
await fileIo.mkdir(params.unzipDirectory);
let foundDiff = false;
let foundBundlePatch = false;
await zlib.decompressFile(params.targetFile, params.unzipDirectory);
const zipFile = await this.processUnzippedFiles(params.unzipDirectory);
for (const entry of zipFile.entries) {
const fn = entry.filename;
if (fn === '__diff.json') {
foundDiff = true;
await fileIo
.copyDir(params.originDirectory + '/', params.unzipDirectory + '/')
.catch(error => {
console.error('copy error:', error);
});
const bufferArray = new Uint8Array(entry.content);
const obj = JSON.parse(
new util.TextDecoder().decodeToString(bufferArray),
);
const { copies, deletes } = obj;
await Promise.all(
Object.entries(copies as Record<string, string>).map(([to, from]) =>
fileIo
.copyFile(
`${params.originDirectory}/${from}`,
`${params.unzipDirectory}/${to}`,
)
.catch(error => {
console.error('copy error:', error);
}),
),
);
await Promise.all(
Object.keys(deletes as Record<string, string>).map(fileToDelete =>
fileIo
.unlink(`${params.unzipDirectory}/${fileToDelete}`)
.catch(error => {
console.error('delete error:', error);
}),
),
);
continue;
}
if (fn === 'bundle.harmony.js.patch') {
foundBundlePatch = true;
const filePath = params.originDirectory + '/bundle.harmony.js';
const res = fileIo.accessSync(filePath);
if (res) {
const stat = await fileIo.stat(filePath);
const reader = await fileIo.open(filePath, fileIo.OpenMode.READ_ONLY);
const fileSize = stat.size;
const originContent = new ArrayBuffer(fileSize);
try {
await fileIo.read(reader.fd, originContent);
const patched = await Pushy.hdiffPatch(
new Uint8Array(originContent),
new Uint8Array(entry.content),
);
const outputFile = `${params.unzipDirectory}/bundle.harmony.js`;
const writer = await fileIo.open(
outputFile,
fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY,
);
const chunkSize = 4096;
let bytesWritten = 0;
const totalLength = patched.byteLength;
while (bytesWritten < totalLength) {
const chunk = patched.slice(
bytesWritten,
bytesWritten + chunkSize,
);
await fileIo.write(writer.fd, chunk);
bytesWritten += chunk.byteLength;
}
await fileIo.close(writer);
continue;
} finally {
await fileIo.close(reader);
}
}
}
}
if (!foundDiff) {
throw Error('diff.json not found');
}
if (!foundBundlePatch) {
throw Error('bundle patch not found');
}
console.info('Patch from PPK completed');
}
private async copyFromResource(
copyList: Map<string, Array<string>>,
): Promise<void> {
let currentFrom = '';
try {
const resourceManager = this.context.resourceManager;
for (const [from, targets] of copyList.entries()) {
currentFrom = from;
if (from.startsWith('resources/base/media/')) {
const mediaName = from
.replace('resources/base/media/', '')
.split('.')[0];
const mediaBuffer = await resourceManager.getMediaByName(mediaName);
for (const target of targets) {
const fileStream = fileIo.createStreamSync(target, 'w+');
fileStream.writeSync(mediaBuffer.buffer);
fileStream.close();
}
continue;
}
const fromContent = await resourceManager.getRawFd(from);
for (const target of targets) {
saveFileToSandbox(fromContent, 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> {
const DAYS_TO_KEEP = 7;
const now = Date.now();
const maxAge = DAYS_TO_KEEP * 24 * 60 * 60 * 1000;
try {
const files = await fileIo.listFile(params.unzipDirectory);
for (const file of files) {
if (file.startsWith('.')) {
continue;
}
const filePath = `${params.unzipDirectory}/${file}`;
const stat = await fileIo.stat(filePath);
if (
now - stat.mtime > maxAge &&
file !== params.hash &&
file !== params.originHash
) {
if (stat.isDirectory()) {
await this.removeDirectory(filePath);
} else {
await fileIo.unlink(filePath);
}
}
}
} 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;
}
}
}