-
Notifications
You must be signed in to change notification settings - Fork 23
/
service-way.component.ts
71 lines (62 loc) · 2.38 KB
/
service-way.component.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
import { Component, inject, Injectable, OnDestroy, OnInit } from '@angular/core';
import { IdService, Tus, UploadState, UploadxOptions, UploadxService } from 'ngx-uploadx';
import { Observable, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { AuthService } from '../auth.service';
import { serverUrl } from '../config';
import { hasher, injectTusChecksumHeader } from '../digest';
@Injectable()
export class CustomId implements IdService {
async generateId(uploader: Tus): Promise<string> {
if (uploader.file.size < 256 || !hasher.isSupported) {
return new Date().getTime().toString(36);
}
const blob = uploader.file.slice(0, 256);
return hasher.digestHex(blob);
}
}
@Component({
selector: 'app-service-way',
templateUrl: './service-way.component.html',
providers: [UploadxService, { provide: IdService, useClass: CustomId }]
})
export class ServiceWayComponent implements OnDestroy, OnInit {
state$!: Observable<UploadState>;
uploads: UploadState[] = [];
private unsubscribe$ = new Subject<void>();
private authService = inject(AuthService);
options: UploadxOptions = {
endpoint: `${serverUrl}/files?uploadType=tus`,
uploaderClass: Tus,
token: this.authService.getAccessToken
// prerequest: injectTusChecksumHeader
};
constructor(private uploadxService: UploadxService) {}
ngOnInit(): void {
this.state$ = this.uploadxService.init(this.options);
this.state$.pipe(takeUntil(this.unsubscribe$)).subscribe(state => {
const target = this.uploads.find(item => item.uploadId === state.uploadId);
target ? Object.assign(target, state) : this.uploads.push(state);
});
this.uploadxService.ajax
.request({ method: 'OPTIONS', url: this.options.endpoint as string })
.then(({ headers }) => {
if (hasher.isSupported && headers['tus-checksum-algorithm']?.includes('sha1')) {
this.uploadxService.options.prerequest = injectTusChecksumHeader;
}
}, console.error);
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
cancel(uploadId?: string): void {
this.uploadxService.control({ action: 'cancel', uploadId });
}
pause(uploadId?: string): void {
this.uploadxService.control({ action: 'pause', uploadId });
}
upload(uploadId?: string): void {
this.uploadxService.control({ action: 'upload', uploadId });
}
}