This repository has been archived by the owner on Jan 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
service.ts
576 lines (518 loc) · 15.3 KB
/
service.ts
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
/* eslint-disable @typescript-eslint/ban-types */
import Status from "./core/status";
import HttpClient from "./http/xhr";
import WorkerClient from "./http/worker";
import QeTag from "./qetag/index";
import QETagBase from './qetag/base';
import QeTagNormal from "./qetag/normal";
import QeTagWorker from "./qetag/worker";
import WorkerProvider from "./worker/index";
import QeTagWorkerScript from './qetag/worker-script';
import uploaderWorkerScript from './http/worker-script';
import QZFile from "./core/file";
import Http from "./http/index";
import { createThrottle, log, makePromiseChain, sizeToStr } from "./core/utils";
import { STATUS } from "./constants/status";
import Ctx from "./core/ctx";
import Chunk from "./core/chunk";
import { merge } from "./third-parts/merge";
import { HttpClientProps } from "./interface";
import sharedInternal from "./shared/index";
const {
qetagWorkers,
uploaderWorkers
} = sharedInternal;
export type AdapterType = 'Normal' | 'Worker';
export interface UplaodConfig {
/**
* adapter
*/
adapter?: AdapterType;
// eslint-disable-next-line @typescript-eslint/ban-types
onStatusChange?: Function;
debug?: boolean;
}
export type FileProps = {
path?: string;
parent?: string;
op?: number;
};
export interface BPutResponse{
ctx: string;
checksum: string;
crc32: number;
offset: number;
code?: string;
message?: string;
}
export interface CreateFileResInfo {
code?: string;
hash: string;
response?: string;
message?: string;
}
export interface UploadedFileInfo {
identity: string;
hash: string;
userIdentity: string;
path: string;
name: string;
ext: string;
size: string;
mime: string;
deleted: boolean;
parent: string;
type: number;
directory: boolean;
atime: string;
ctime: string;
mtime: string;
version: number;
locking: boolean;
op: number;
preview: boolean;
previewType: number;
flag: number;
uniqueIdentity: string;
share: boolean;
downloadAddress: string;
unlockTime: string;
}
export interface TokenInfo {
uploadToken: string;
createInfo: UploadedFileInfo;
type: string;
filePath: string;
created: boolean;
partUploadUrl: string;
directUploadUrl: string;
}
export default class Service extends Status {
/**
* @description httpClient
* @type {(HttpClient | WorkerClient)}
* @memberof Service
*/
http?: HttpClient | WorkerClient;
/**
* @description qeTag 计算工具
* @type {(QeTagNormal | QeTagWorker)}
* @memberof Service
*/
qetag?: QeTagNormal | QeTagWorker;
/**
* @description 存储的file对象
* @type {QZFile}
* @memberof Service
*/
file: QZFile;
/**
* @description 配置项
* @type {{ adapter: AdapterType; onStatusChange: Function }}
* @memberof Service
*/
config: { adapter: AdapterType; onStatusChange: Function; debug?: boolean };
/**
* @description 文件属性
* @type {FileProps}
* @memberof Service
*/
props: FileProps;
/**
* @description 文件上传进度属性
* @memberof Service
*/
progress = 0;
/**
* @description 文件大小 / 1.00MB
* @type {string}
* @memberof Service
*/
sizeStr: string;
/**
* @description 提供能力以操作分片上传返回的ctx
* @type {Ctx}
* @memberof Service
*/
ctx: Ctx;
/**
* @description hash计算进度
* @memberof Service
*/
hashCalcProgress = 0;
/**
* @description 已上传大小记录
* @type {{
* size: number;
* time: any;
* }}
* @memberof Service
*/
lastProgress: {
size: number;
time: any;
} = {
time: null,
size: 0
};
/**
* @description 上传速率(format)
* @memberof Service
*/
rate = '0KB/S';
/**
* @description 上传速率
* @memberof Service
*/
bytesPreSecond = 0;
/**
* @description 上传需要的token信息
* @type {TokenInfo}
* @memberof Service
*/
tokenInfo: TokenInfo = {
uploadToken: "",
createInfo: {} as UploadedFileInfo,
type: "",
filePath: "",
created: false,
partUploadUrl: "https://upload-v1.6pan.cn",
directUploadUrl: "https://upload-v1.6pan.cn/file/upload"
};
/**
* @description 上传完成返回的文件信息
* @type {UploadedFileInfo}
* @memberof Service
*/
normalFile?: UploadedFileInfo;
log: any;
/**
*Creates an instance of Service.
* @param {File} file
* @param {FileProps} [fileProps={} as FileProps]
* @param {UplaodConfig} [config={}]
* @memberof Service
*/
constructor(file: File, fileProps: FileProps = {}, config: UplaodConfig = {}) {
super();
this.file = new QZFile({
file,
blockSize: Service.default.blockSize,
chunkSize: Service.default.chunkSize
})
this.props = fileProps;
if (config.adapter) {
if (!(config.adapter in QeTag)) {
delete config.adapter
}
}
this.config = Object.assign({
adapter: 'Normal',
// eslint-disable-next-line @typescript-eslint/no-empty-function
onStatusChange: function () {}
}, config);
this.log = log(Boolean(this.config.debug))
this.sizeStr = sizeToStr(this.file.size);
this.ctx = new Ctx()
this._setStatusHandler();
}
/**
* @description 用于判断是否在上传token期间获取到文件信息
* @returns {boolean}
* @memberof Service
*/
isExisted(): boolean {
if (this.normalFile) {
return true;
}
return false;
}
/**
* @description 设置文件信息或者token信息,判断token请求返回是否有created字段,如有,则设置文件信息
* @param {TokenInfo} info
* @memberof Service
*/
setFileInfo(info: TokenInfo): void {
if (info.created) {
this.setNormalFile(info.createInfo)
}
else {
this.tokenInfo = info
}
}
isUploadInfoExist(): boolean {
return Boolean(this.normalFile) || Boolean(this.tokenInfo.uploadToken)
}
/**
* @description 直接设置接口返回的文件信息
* @param {UploadedFileInfo} file
* @memberof Service
*/
setNormalFile(file: UploadedFileInfo): void {
this.normalFile = file;
}
/**
* @description 提供qetag服务(lazy)
* @returns {(QeTagNormal | QeTagWorker)}
* @memberof Service
*/
_qetag(): QeTagNormal | QeTagWorker {
if (!this.qetag) {
if (!qetagWorkers.current && this.config.adapter === 'Worker') {
qetagWorkers.current = new WorkerProvider(WorkerProvider.asyncFnMover(QeTagWorkerScript), Service.default.taskConcurrencyInWorkers);
}
this.qetag = new QeTag[this.config.adapter](this.file, {
workers: qetagWorkers.current as WorkerProvider
});
this.qetag.on(QeTag.Base.Events.UpdateProgress, (progress: number) => {
this.hashCalcProgress = progress;
this.config.onStatusChange(this, this.status);
})
}
return this.qetag;
}
/**
* @description 提供http服务(lazy)
* @returns {(HttpClient | WorkerClient)}
* @memberof Service
*/
_http(): HttpClient | WorkerClient {
if (!this.http) {
if (!uploaderWorkers.current && this.config.adapter === 'Worker') {
uploaderWorkers.current = new WorkerProvider(WorkerProvider.asyncFnMover(uploaderWorkerScript), Service.default.taskConcurrencyInWorkers);
}
this.http = new Http[this.config.adapter]({
workers: uploaderWorkers.current as WorkerProvider
});
const throttle = createThrottle(1000)
this.http.on(Http.Base.Events.UpdateProgress, () => {
throttle(() => {
this.setProgress()
});
})
}
return this.http;
}
/**
* @description 计算文件上传进度
* @memberof Service
*/
setProgress(): void {
const now = new Date().getTime();
const { chunkSize } = Service.default;
const bytesUploaded = this.ctx.size * chunkSize;
if (this.lastProgress.time) {
this.bytesPreSecond = Math.floor((bytesUploaded - this.lastProgress.size) / ((now - this.lastProgress.time) / 1000));
this.rate = sizeToStr(this.bytesPreSecond) + '/S';
}
this.lastProgress = {
time: now,
size: bytesUploaded
}
let progress = parseFloat((bytesUploaded * 100 / this.file.size).toFixed(2));
if (progress > 100) {
progress = 100
}
this.progress = progress
if (
this.bytesPreSecond >= 0 &&
this.isUploading()
) {
this.setStatus(STATUS.UPLOADING);
}
}
/**
* @description 设置文件状态handler
* @memberof Service
*/
_setStatusHandler(): void {
const onChange = () => {
this.config.onStatusChange(this, this.status)
}
this.addStatusHandler(STATUS.CALCULATING, onChange)
.addStatusHandler(STATUS.CANCEL, () => {
this.http?.removeAllListeners();
this.qetag?.emit('race-to-stop');
this.qetag?.removeAllListeners();
onChange()
})
.addStatusHandler(STATUS.DONE, () => {
this.progress = 100;
this.qetag?.removeAllListeners();
this.http?.removeAllListeners();
onChange()
})
.addStatusHandler(STATUS.FAILED, onChange)
.addStatusHandler(STATUS.PAUSE, () => {
this.tryCount = 0;
this.qetag?.emit('race-to-stop');
onChange()
})
.addStatusHandler(STATUS.PENDING, () => {
this.tryCount = 0;
onChange()
})
.addStatusHandler(STATUS.PREPARING, onChange)
.addStatusHandler(STATUS.UPLOADING, onChange)
}
/**
* @description 提供片上传服务
* @param {Chunk} chunk
* @param {string} [ctx]
* @returns {Promise<BPutResponse>}
* @memberof Service
*/
chunkUpload(chunk: Chunk, ctx?: string): Promise<BPutResponse> {
const http = this._http();
const {
clientConfig,
apis
} = Service.default;
const config = {
url: '',
data: chunk.blob,
credentials: 'omit',
config: merge(
{},
clientConfig,
{
baseURL: this.tokenInfo.partUploadUrl,
headers: {
'Authorization': this.tokenInfo.uploadToken,
'UploadBatch': this.file.batch,
'Content-Type': 'application/octet-stream'
}
}
)
};
if (chunk.index === 0) {
config.url = `${apis.mkblk}${chunk.block.size}/${chunk.block.index}`;
}
else {
config.url = `${apis.bput}${ctx}/${chunk.startByte}`;
}
config.url = this.tokenInfo.partUploadUrl + config.url;
return http.post<any>(config as HttpClientProps, {
isTransferablesSupported: WorkerProvider.isTransferablesSupported(),
isEmitEvent: true
})
}
/**
* @description 提供创建文件服务
* @returns {Promise<CreateFileResInfo>}
* @memberof Service
*/
createFile(): Promise<CreateFileResInfo> {
const http = this._http();
const {
clientConfig,
apis
} = Service.default;
return http.post<any>({
url: this.tokenInfo.partUploadUrl + apis.mkfile + this.file.size,
data: this.ctx.toCtxString(),
credentials: 'omit',
config: merge(
{},
clientConfig,
{
baseURL: this.tokenInfo.partUploadUrl,
headers: {
'Authorization': this.tokenInfo.uploadToken,
'UploadBatch': this.file.batch,
'Content-Type': 'text/plain;charset=UTF-8'
}
}
)
})
}
/**
* @description 提供获取hash值服务
* @return {*} {Promise<QETagBase>}
* @memberof Service
*/
calcHash(): Promise<QETagBase> {
const qetag = this._qetag();
if (qetag.isExist()) {
return Promise.resolve(qetag);
}
const config = {
isTransferablesSupported: WorkerProvider.isTransferablesSupported(),
isEmitEvent: true,
tag: qetag
}
return makePromiseChain<Promise<QETagBase>>(
config,
qetag.calc.bind(qetag),
Service.interceptors.qetag
);
}
/**
* @description 提供同步获取hash值服务
* @returns {string}
* @memberof Service
*/
getHash(): string {
const qetag = this._qetag();
return qetag.get();
}
/**
* @description 提供直接设置hash值服务
* @param {string} hash
* @memberof Service
*/
setHash(hash: string): void {
const qetag = this._qetag();
qetag.set(hash);
}
/**
* @description 生成携带Auth信息的请求头
* @returns {*}
* @memberof Service
*/
_getDefaultRequestHeader(): any {
const { AuthorizationTokenKey, AuthorizationStorageKey } = Service.default;
const token = localStorage.getItem(AuthorizationStorageKey);
if (token) {
return {
headers: {
[AuthorizationTokenKey]: token
}
}
}
return {};
}
/**
* @description 请求并获取上传token信息, 只获取一次,复用token
* @returns {Promise<TokenInfo>}
* @memberof Service
*/
async getTokenInfo(): Promise<TokenInfo> {
const http = this._http();
const params: {
[key: string]: any;
} = {
hash: this.getHash(),
name: this.file.name,
op: this.props.op || 0
}
if (this.props.path) {
params.path = this.props.path
}
if (this.props.parent) {
params.parent = this.props.parent
}
const result = await http.post<any>({
url: Service.default.clientConfig.baseURL + Service.default.apis.token,
data: JSON.stringify(params),
credentials: 'include',
config: merge({}, Service.default.clientConfig, this._getDefaultRequestHeader())
}).then(json => {
if (json.success === false) {
throw new Error(json.message)
}
return json
})
return result
}
}