cloud189-sdk 1.0.9 → 1.0.10-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,720 +0,0 @@
1
- "use strict";
2
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
- };
7
- var __importDefault = (this && this.__importDefault) || function (mod) {
8
- return (mod && mod.__esModule) ? mod : { "default": mod };
9
- };
10
- var _CloudClient_instances, _CloudClient_valid, _CloudClient_getAccessTokenBySsKey, _CloudClient_generateRsaKey, _CloudClient_isFamily, _CloudClient_partUpload, _CloudClient_singleUpload, _CloudClient_multiUpload;
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.CloudClient = void 0;
13
- const fs_1 = __importDefault(require("fs"));
14
- const path_1 = __importDefault(require("path"));
15
- const got_1 = __importDefault(require("got"));
16
- const types_1 = require("./types");
17
- const log_1 = require("./log");
18
- const util_1 = require("./util");
19
- const const_1 = require("./const");
20
- const signature_1 = require("./signature");
21
- const CloudAuthClient_1 = require("./CloudAuthClient");
22
- const hook_1 = require("./hook");
23
- const store_1 = require("./store");
24
- const config = {
25
- clientId: '538135150693412',
26
- model: 'KB2000',
27
- version: '9.0.6'
28
- };
29
- /**
30
- * 天翼网盘客户端
31
- * @public
32
- */
33
- class CloudClient {
34
- constructor(_options) {
35
- _CloudClient_instances.add(this);
36
- _CloudClient_valid.set(this, (options) => {
37
- if (options.ssonCookie) {
38
- return;
39
- }
40
- if (options.token) {
41
- return;
42
- }
43
- if (options.username && options.password) {
44
- return;
45
- }
46
- if (options.onQRCodeReady) {
47
- return;
48
- }
49
- log_1.logger.error('valid');
50
- throw new Error('Please provide username and password or token or ssonCooike or onQRCodeReady !');
51
- });
52
- __classPrivateFieldGet(this, _CloudClient_valid, "f").call(this, _options);
53
- this.username = _options.username;
54
- this.password = _options.password;
55
- this.ssonCookie = _options.ssonCookie;
56
- this.onQRCodeReady = _options.onQRCodeReady;
57
- this.qrLoginOptions = _options.qrLoginOptions;
58
- this.tokenStore = _options.token || new store_1.MemoryStore();
59
- this.authClient = new CloudAuthClient_1.CloudAuthClient();
60
- this.session = {
61
- accessToken: '',
62
- sessionKey: ''
63
- };
64
- this.rsaKey = null;
65
- this.request = got_1.default.extend({
66
- retry: {
67
- limit: 2,
68
- statusCodes: [408, 413, 429],
69
- errorCodes: ['ETIMEDOUT', 'ECONNRESET']
70
- },
71
- headers: {
72
- 'User-Agent': const_1.UserAgent,
73
- Referer: `${const_1.WEB_URL}/web/main/`,
74
- Accept: 'application/json;charset=UTF-8'
75
- },
76
- hooks: {
77
- beforeRequest: [
78
- async (options) => {
79
- if (options.url.href.includes(const_1.API_URL)) {
80
- const accessToken = await this.getAccessToken();
81
- (0, signature_1.signatureAccesstoken)(options, accessToken);
82
- }
83
- else if (options.url.href.includes(const_1.WEB_URL)) {
84
- if (options.url.href.includes('/open')) {
85
- const appkey = '600100422';
86
- (0, signature_1.signatureAppKey)(options, appkey);
87
- }
88
- const sessionKey = await this.getSessionKey();
89
- options.url.searchParams.set('sessionKey', sessionKey);
90
- }
91
- else if (options.url.href.includes(const_1.UPLOAD_URL)) {
92
- const sessionKey = await this.getSessionKey();
93
- const rsaKey = await this.generateRsaKey();
94
- (0, signature_1.signatureUpload)(options, rsaKey, sessionKey);
95
- }
96
- }
97
- ],
98
- afterResponse: [
99
- hook_1.logHook,
100
- async (response, retryWithMergedOptions) => {
101
- if (response.statusCode === 400) {
102
- try {
103
- const { errorCode, errorMsg } = JSON.parse(response.body.toString());
104
- if (errorCode === 'InvalidAccessToken') {
105
- log_1.logger.debug(`InvalidAccessToken retry..., errorMsg: ${errorMsg}`);
106
- log_1.logger.debug('Refresh AccessToken');
107
- this.session.accessToken = '';
108
- return retryWithMergedOptions({});
109
- }
110
- else if (errorCode === 'InvalidSessionKey') {
111
- log_1.logger.debug(`InvalidSessionKey retry..., errorMsg: ${errorMsg}`);
112
- log_1.logger.debug('Refresh InvalidSessionKey');
113
- this.session.sessionKey = '';
114
- return retryWithMergedOptions({});
115
- }
116
- }
117
- catch (e) {
118
- log_1.logger.error(e);
119
- }
120
- }
121
- return response;
122
- }
123
- ]
124
- }
125
- });
126
- }
127
- async getSession() {
128
- const { accessToken, expiresIn, refreshToken } = await this.tokenStore.get();
129
- if (accessToken && expiresIn && expiresIn > Date.now()) {
130
- try {
131
- return await this.authClient.loginByAccessToken(accessToken);
132
- }
133
- catch (e) {
134
- log_1.logger.error(e);
135
- }
136
- }
137
- if (refreshToken) {
138
- try {
139
- const refreshTokenSession = await this.authClient.refreshToken(refreshToken);
140
- await this.tokenStore.update({
141
- accessToken: refreshTokenSession.accessToken,
142
- refreshToken: refreshTokenSession.refreshToken,
143
- expiresIn: new Date(Date.now() + refreshTokenSession.expiresIn * 1000).getTime()
144
- });
145
- return await this.authClient.loginByAccessToken(refreshTokenSession.accessToken);
146
- }
147
- catch (e) {
148
- log_1.logger.error(e);
149
- }
150
- }
151
- if (this.ssonCookie) {
152
- try {
153
- const loginToken = await this.authClient.loginBySsoCooike(this.ssonCookie);
154
- await this.tokenStore.update({
155
- accessToken: loginToken.accessToken,
156
- refreshToken: loginToken.refreshToken,
157
- expiresIn: new Date(Date.now() + 6 * 24 * 60 * 60 * 1000).getTime()
158
- });
159
- return loginToken;
160
- }
161
- catch (e) {
162
- log_1.logger.error(e);
163
- }
164
- }
165
- if (this.username && this.password) {
166
- try {
167
- const loginToken = await this.authClient.loginByPassword(this.username, this.password);
168
- await this.tokenStore.update({
169
- accessToken: loginToken.accessToken,
170
- refreshToken: loginToken.refreshToken,
171
- expiresIn: new Date(Date.now() + 6 * 24 * 60 * 60 * 1000).getTime()
172
- });
173
- return loginToken;
174
- }
175
- catch (e) {
176
- log_1.logger.error(e);
177
- }
178
- }
179
- if (this.onQRCodeReady) {
180
- try {
181
- const loginToken = await this.authClient.loginByQRCode(this.onQRCodeReady, this.qrLoginOptions);
182
- await this.tokenStore.update({
183
- accessToken: loginToken.accessToken,
184
- refreshToken: loginToken.refreshToken,
185
- expiresIn: new Date(Date.now() + 6 * 24 * 60 * 60 * 1000).getTime()
186
- });
187
- return loginToken;
188
- }
189
- catch (e) {
190
- log_1.logger.error(e);
191
- }
192
- }
193
- throw new Error('Can not get session.');
194
- }
195
- /**
196
- * 获取 sessionKey
197
- * @returns sessionKey
198
- */
199
- async getSessionKey() {
200
- if (this.session.sessionKey) {
201
- return this.session.sessionKey;
202
- }
203
- if (!this.sessionKeyPromise) {
204
- this.sessionKeyPromise = this.getSession()
205
- .then((result) => {
206
- this.session.sessionKey = result.sessionKey;
207
- return result.sessionKey;
208
- })
209
- .finally(() => {
210
- this.sessionKeyPromise = null;
211
- });
212
- }
213
- const result = await this.sessionKeyPromise;
214
- return result;
215
- }
216
- /**
217
- * 获取 accessToken
218
- * @returns accessToken
219
- */
220
- async getAccessToken() {
221
- if (this.session.accessToken) {
222
- return this.session.accessToken;
223
- }
224
- if (!this.accessTokenPromise) {
225
- this.accessTokenPromise = __classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_getAccessTokenBySsKey).call(this)
226
- .then((result) => {
227
- this.session.accessToken = result.accessToken;
228
- return result;
229
- })
230
- .finally(() => {
231
- this.accessTokenPromise = null;
232
- });
233
- }
234
- const result = await this.accessTokenPromise;
235
- return result.accessToken;
236
- }
237
- /**
238
- * 获取 RSA key
239
- * @returns RSAKey
240
- */
241
- async generateRsaKey() {
242
- if (this.rsaKey && new Date(this.rsaKey.expire).getTime() > Date.now()) {
243
- return this.rsaKey;
244
- }
245
- if (!this.generateRsaKeyPromise) {
246
- this.generateRsaKeyPromise = __classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_generateRsaKey).call(this)
247
- .then((res) => {
248
- this.rsaKey = {
249
- expire: res.expire,
250
- pubKey: res.pubKey,
251
- pkId: res.pkId,
252
- ver: res.ver
253
- };
254
- return res;
255
- })
256
- .finally(() => {
257
- this.generateRsaKeyPromise = null;
258
- });
259
- }
260
- const result = await this.generateRsaKeyPromise;
261
- return result;
262
- }
263
- /**
264
- * 获取用户网盘存储容量信息
265
- * @returns 账号容量结果
266
- */
267
- getUserSizeInfo() {
268
- return this.request.get(`${const_1.WEB_URL}/api/portal/getUserSizeInfo.action`).json();
269
- }
270
- /**
271
- * 个人签到任务
272
- * @returns 签到结果
273
- */
274
- userSign() {
275
- return this.request
276
- .get(`${const_1.WEB_URL}/mkt/userSign.action?rand=${new Date().getTime()}&clientType=TELEANDROID&version=${config.version}&model=${config.model}`)
277
- .json();
278
- }
279
- /**
280
- * 获取家庭信息
281
- * @returns 家庭列表信息
282
- */
283
- getFamilyList() {
284
- return this.request.get(`${const_1.API_URL}/open/family/manage/getFamilyList.action`).json();
285
- }
286
- /**
287
- * 家庭签到任务
288
- * @param familyId - 家庭id
289
- * @returns 签到结果
290
- * @deprecated 已无效
291
- */
292
- familyUserSign(familyId) {
293
- return this.request
294
- .get(`${const_1.API_URL}/open/family/manage/exeFamilyUserSign.action?familyId=${familyId}`)
295
- .json();
296
- }
297
- /**
298
- * 获取文件列表
299
- * @param pageQuery - 查询参数
300
- * @returns
301
- */
302
- getListFiles(pageQuery, familyId) {
303
- const defaultQuery = {
304
- pageNum: 1,
305
- pageSize: 60,
306
- mediaType: types_1.MediaType.ALL.toString(),
307
- orderBy: types_1.OrderByType.LAST_OP_TIME.toString(),
308
- descending: true,
309
- folderId: '',
310
- iconOption: 5
311
- };
312
- const query = Object.assign(Object.assign({}, defaultQuery), pageQuery);
313
- if (familyId) {
314
- return this.request
315
- .get(`${const_1.API_URL}/open/family/file/listFiles.action`, {
316
- searchParams: Object.assign(Object.assign({}, query), { familyId })
317
- })
318
- .json();
319
- }
320
- else {
321
- return this.request
322
- .get(`${const_1.API_URL}/open/file/listFiles.action`, {
323
- searchParams: Object.assign({}, query)
324
- })
325
- .json();
326
- }
327
- }
328
- /**
329
- * 创建文件夹
330
- * @param createFolderRequest - 创建文件夹请求
331
- * @returns
332
- */
333
- createFolder(createFolderRequest) {
334
- const url = __classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_isFamily).call(this, createFolderRequest)
335
- ? `${const_1.API_URL}/open/family/file/createFolder.action`
336
- : `${const_1.API_URL}/open/file/createFolder.action`;
337
- return this.request
338
- .post(url, {
339
- form: createFolderRequest
340
- })
341
- .json();
342
- }
343
- /**
344
- * 重命名文件夹
345
- * @param renameFolderRequest - 重名文件夹请求
346
- * @returns
347
- */
348
- renameFolder(renameFolderRequest) {
349
- let url = `${const_1.API_URL}/open/file/renameFolder.action`;
350
- let form = {
351
- destFolderName: renameFolderRequest.folderName,
352
- folderId: renameFolderRequest.folderId
353
- };
354
- if (__classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_isFamily).call(this, renameFolderRequest)) {
355
- url = `${const_1.API_URL}/open/family/file/renameFolder.action`;
356
- form = Object.assign(form, {
357
- familyId: renameFolderRequest.familyId
358
- });
359
- }
360
- return this.request
361
- .post(url, {
362
- form
363
- })
364
- .json();
365
- }
366
- /**
367
- * 初始化上传
368
- * @param initMultiUploadRequest - 初始化请求
369
- * @returns
370
- */
371
- async initMultiUpload(initMultiUploadRequest) {
372
- const { parentFolderId, fileName, fileSize, sliceSize, fileMd5, sliceMd5 } = initMultiUploadRequest;
373
- let initParams = Object.assign({ parentFolderId,
374
- fileName,
375
- fileSize,
376
- sliceSize }, (fileMd5 && sliceMd5 ? { fileMd5, sliceMd5 } : { lazyCheck: 1 }));
377
- let url = `${const_1.UPLOAD_URL}/person/initMultiUpload`;
378
- if (__classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_isFamily).call(this, initMultiUploadRequest)) {
379
- url = `${const_1.UPLOAD_URL}/family/initMultiUpload`;
380
- initParams = Object.assign(initParams, {
381
- familyId: initMultiUploadRequest.familyId
382
- });
383
- }
384
- return await this.request
385
- .get(url, {
386
- searchParams: Object.assign({}, initParams)
387
- })
388
- .json();
389
- }
390
- /**
391
- * 提交上传
392
- * @param commitMultiUploadRequest - 提交请求
393
- * @returns
394
- */
395
- commitMultiUpload(commitMultiUploadRequest) {
396
- const url = __classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_isFamily).call(this, commitMultiUploadRequest)
397
- ? `${const_1.UPLOAD_URL}/family/commitMultiUploadFile`
398
- : `${const_1.UPLOAD_URL}/person/commitMultiUploadFile`;
399
- return this.request
400
- .get(url, {
401
- searchParams: Object.assign({}, commitMultiUploadRequest)
402
- })
403
- .json();
404
- }
405
- /**
406
- * 检测秒传
407
- * @param params - 检查参数
408
- * @returns
409
- */
410
- checkTransSecond(params) {
411
- const url = __classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_isFamily).call(this, params)
412
- ? `${const_1.UPLOAD_URL}/family/checkTransSecond`
413
- : `${const_1.UPLOAD_URL}/person/checkTransSecond`;
414
- return this.request
415
- .get(url, {
416
- searchParams: params
417
- })
418
- .json();
419
- }
420
- /**
421
- * 文件上传
422
- * @param param - 上传参数
423
- * @param callbacks - 上传回调
424
- * @returns
425
- */
426
- async upload(param, callbacks = {}) {
427
- const { filePath, parentFolderId, familyId } = param;
428
- const { size } = await fs_1.default.promises.stat(filePath);
429
- const fileName = encodeURIComponent(path_1.default.basename(filePath));
430
- const sliceSize = (0, util_1.partSize)(size);
431
- const { fileMd5, chunkMd5s } = await (0, util_1.calculateFileAndChunkMD5)(filePath, sliceSize);
432
- if (chunkMd5s.length === 1) {
433
- log_1.logger.debug('single file upload');
434
- return __classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_singleUpload).call(this, {
435
- parentFolderId,
436
- filePath,
437
- fileName,
438
- fileSize: size,
439
- sliceSize,
440
- fileMd5,
441
- familyId
442
- }, callbacks);
443
- }
444
- else {
445
- log_1.logger.debug('multi file upload');
446
- return __classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_multiUpload).call(this, {
447
- parentFolderId,
448
- filePath,
449
- fileName,
450
- fileSize: size,
451
- sliceSize,
452
- fileMd5,
453
- chunkMd5s,
454
- familyId
455
- }, callbacks);
456
- }
457
- }
458
- /**
459
- * 检测任务状态
460
- * @param type - 任务类型
461
- * @param taskId - 任务Id
462
- * @param maxAttempts - 重试次数
463
- * @param interval - 重试间隔
464
- * @returns
465
- */
466
- async checkTaskStatus(type, taskId, maxAttempts = 120, interval = 500) {
467
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
468
- try {
469
- const { taskStatus, successedFileIdList } = await this.request
470
- .post(`${const_1.API_URL}/open/batch/checkBatchTask.action`, {
471
- form: { type, taskId }
472
- })
473
- .json();
474
- if (taskStatus === -1) {
475
- log_1.logger.error('创建任务异常');
476
- return {
477
- taskId,
478
- taskStatus
479
- };
480
- }
481
- //重名
482
- if (taskStatus === 2) {
483
- log_1.logger.error('文件重名任务异常');
484
- return {
485
- taskId,
486
- taskStatus
487
- };
488
- }
489
- //成功
490
- if (taskStatus === 4) {
491
- return { successedFileIdList, taskId, taskStatus };
492
- }
493
- }
494
- catch (e) {
495
- log_1.logger.error(`Check task status attempt ${attempt + 1} failed:` + e);
496
- }
497
- await new Promise((resolve) => setTimeout(resolve, interval));
498
- }
499
- }
500
- /**
501
- * 创建任务
502
- * @param createBatchTaskRequest - 创建任务参数
503
- * @returns
504
- */
505
- async createBatchTask(createBatchTaskRequest) {
506
- let form = {
507
- type: createBatchTaskRequest.type,
508
- taskInfos: JSON.stringify(createBatchTaskRequest.taskInfos)
509
- };
510
- if (createBatchTaskRequest.targetFolderId) {
511
- form = Object.assign(form, {
512
- targetFolderId: createBatchTaskRequest.targetFolderId
513
- });
514
- }
515
- if (__classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_isFamily).call(this, createBatchTaskRequest)) {
516
- form = Object.assign(form, {
517
- familyId: createBatchTaskRequest.familyId
518
- });
519
- }
520
- try {
521
- const { taskId } = await this.request
522
- .post(`${const_1.API_URL}/open/batch/createBatchTask.action`, {
523
- form
524
- })
525
- .json();
526
- return await this.checkTaskStatus(createBatchTaskRequest.type, taskId);
527
- }
528
- catch (error) {
529
- log_1.logger.error('Batch task creation failed:' + error);
530
- throw error;
531
- }
532
- }
533
- /**
534
- * 获取文件下载路径
535
- * @param params - 文件参数
536
- * @returns
537
- */
538
- getFileDownloadUrl(params) {
539
- const url = params.familyId
540
- ? `${const_1.API_URL}/open/family/file/getFileDownloadUrl.action`
541
- : `${const_1.API_URL}/open/file/getFileDownloadUrl.action`;
542
- return this.request(url, {
543
- searchParams: params
544
- }).json();
545
- }
546
- }
547
- exports.CloudClient = CloudClient;
548
- _CloudClient_valid = new WeakMap(), _CloudClient_instances = new WeakSet(), _CloudClient_getAccessTokenBySsKey = function _CloudClient_getAccessTokenBySsKey() {
549
- return this.request.get(`${const_1.WEB_URL}/api/open/oauth2/getAccessTokenBySsKey.action`).json();
550
- }, _CloudClient_generateRsaKey = function _CloudClient_generateRsaKey() {
551
- return this.request.get(`${const_1.WEB_URL}/api/security/generateRsaKey.action`).json();
552
- }, _CloudClient_isFamily = function _CloudClient_isFamily(request) {
553
- return 'familyId' in request && request.familyId !== undefined;
554
- }, _CloudClient_partUpload = async function _CloudClient_partUpload({ partNumber, md5, buffer, uploadFileId, familyId }, callbacks = {}) {
555
- const partInfo = `${partNumber}-${(0, util_1.hexToBase64)(md5)}`;
556
- log_1.logger.debug(`upload part: ${partNumber}`);
557
- const multiUploadUrParams = {
558
- partInfo,
559
- uploadFileId
560
- };
561
- const url = familyId
562
- ? `${const_1.UPLOAD_URL}/family/getMultiUploadUrls`
563
- : `${const_1.UPLOAD_URL}/person/getMultiUploadUrls`;
564
- const urls = await this.request
565
- .get(url, {
566
- searchParams: multiUploadUrParams
567
- })
568
- .json();
569
- const { requestURL, requestHeader } = urls.uploadUrls[`partNumber_${partNumber}`];
570
- const headers = requestHeader.split('&').reduce((acc, pair) => {
571
- const key = pair.split('=')[0];
572
- const value = pair.match(/=(.*)/)[1];
573
- acc[key] = value;
574
- return acc;
575
- }, {});
576
- log_1.logger.debug(`Upload URL: ${requestURL}`);
577
- log_1.logger.debug(`Upload Headers: ${JSON.stringify(headers)}`);
578
- await got_1.default
579
- .put(requestURL, {
580
- headers,
581
- body: buffer
582
- })
583
- .on('uploadProgress', (progress) => {
584
- var _a;
585
- (_a = callbacks.onProgress) === null || _a === void 0 ? void 0 : _a.call(callbacks, (progress.transferred * 100) / progress.total);
586
- });
587
- }, _CloudClient_singleUpload =
588
- /**
589
- * 单个小文件上传
590
- */
591
- async function _CloudClient_singleUpload({ parentFolderId, filePath, fileName, fileSize, fileMd5, sliceSize, familyId }, callbacks = {}) {
592
- var _a, _b, _c;
593
- const sliceMd5 = fileMd5;
594
- const initParams = {
595
- parentFolderId,
596
- fileName,
597
- fileSize,
598
- sliceSize,
599
- fileMd5,
600
- sliceMd5,
601
- familyId
602
- };
603
- let fd;
604
- try {
605
- // md5校验
606
- const res = await this.initMultiUpload(initParams);
607
- const { uploadFileId, fileDataExists } = res.data;
608
- if (!fileDataExists) {
609
- fd = await fs_1.default.promises.open(filePath, 'r');
610
- const buffer = Buffer.alloc(fileSize);
611
- await fd.read(buffer, 0, fileSize);
612
- await __classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_partUpload).call(this, {
613
- partNumber: 1,
614
- md5: fileMd5,
615
- buffer,
616
- uploadFileId,
617
- familyId
618
- }, {
619
- onProgress: callbacks.onProgress,
620
- onError: callbacks.onError
621
- });
622
- }
623
- else {
624
- log_1.logger.debug(`单文件 ${filePath} 秒传: ${uploadFileId}`);
625
- (_a = callbacks.onProgress) === null || _a === void 0 ? void 0 : _a.call(callbacks, 100); // 秒传直接显示100%
626
- }
627
- const commitResult = Object.assign(Object.assign({}, (await this.commitMultiUpload({
628
- fileMd5,
629
- sliceMd5,
630
- uploadFileId,
631
- familyId
632
- }))), { fileDataExists });
633
- (_b = callbacks.onComplete) === null || _b === void 0 ? void 0 : _b.call(callbacks, commitResult);
634
- return commitResult;
635
- }
636
- catch (e) {
637
- (_c = callbacks.onError) === null || _c === void 0 ? void 0 : _c.call(callbacks, e);
638
- throw e;
639
- }
640
- finally {
641
- fd === null || fd === void 0 ? void 0 : fd.close();
642
- }
643
- }, _CloudClient_multiUpload =
644
- /**
645
- * 大文件分块上传
646
- */
647
- async function _CloudClient_multiUpload({ parentFolderId, filePath, fileName, fileSize, fileMd5, sliceSize, chunkMd5s, familyId }, callbacks = {}) {
648
- var _a, _b, _c;
649
- const sliceMd5 = (0, util_1.md5)(chunkMd5s.join('\n'));
650
- const initParams = {
651
- parentFolderId,
652
- fileName,
653
- fileSize,
654
- sliceSize,
655
- familyId
656
- };
657
- let fd;
658
- try {
659
- const res = await this.initMultiUpload(initParams);
660
- const { uploadFileId } = res.data;
661
- const checkTransSecondParams = {
662
- fileMd5,
663
- sliceMd5,
664
- uploadFileId,
665
- familyId
666
- };
667
- // md5校验
668
- const checkRes = await this.checkTransSecond(checkTransSecondParams);
669
- const { fileDataExists } = checkRes.data;
670
- if (!fileDataExists) {
671
- fd = await fs_1.default.promises.open(filePath, 'r');
672
- const chunkCount = chunkMd5s.length;
673
- const progressMap = {};
674
- await (0, util_1.asyncPool)(5, [...Array(chunkCount).keys()], async (i) => {
675
- const partNumber = i + 1;
676
- const position = i * sliceSize;
677
- const length = Math.min(sliceSize, fileSize - position);
678
- const buffer = Buffer.alloc(length);
679
- await fd.read(buffer, 0, length, position);
680
- await __classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_partUpload).call(this, {
681
- partNumber: partNumber,
682
- md5: chunkMd5s[i],
683
- buffer,
684
- uploadFileId,
685
- familyId
686
- }, {
687
- onProgress: (chunkProgress) => {
688
- if (callbacks.onProgress) {
689
- // 计算整体进度
690
- progressMap[`partNumber_${partNumber}`] = chunkProgress;
691
- const totalProgress = Object.values(progressMap).reduce((sum, p) => sum + p, 0) / chunkCount;
692
- callbacks.onProgress(totalProgress);
693
- }
694
- },
695
- onError: callbacks.onError
696
- });
697
- });
698
- }
699
- else {
700
- log_1.logger.debug(`多块文件 ${filePath} 秒传: ${uploadFileId}`);
701
- (_a = callbacks.onProgress) === null || _a === void 0 ? void 0 : _a.call(callbacks, 100); // 秒传直接显示100%
702
- }
703
- const commitResult = Object.assign(Object.assign({}, (await this.commitMultiUpload({
704
- fileMd5,
705
- sliceMd5,
706
- uploadFileId,
707
- lazyCheck: 1,
708
- familyId
709
- }))), { fileDataExists });
710
- (_b = callbacks.onComplete) === null || _b === void 0 ? void 0 : _b.call(callbacks, commitResult);
711
- return commitResult;
712
- }
713
- catch (e) {
714
- (_c = callbacks.onError) === null || _c === void 0 ? void 0 : _c.call(callbacks, e);
715
- throw e;
716
- }
717
- finally {
718
- fd === null || fd === void 0 ? void 0 : fd.close();
719
- }
720
- };