17016: Fixed deleteFiles function
[arvados-workbench2.git] / src / services / collection-service / collection-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { CollectionResource } from "~/models/collection";
6 import { AxiosInstance } from "axios";
7 import { CollectionFile, CollectionDirectory } from "~/models/collection-file";
8 import { WebDAV } from "~/common/webdav";
9 import { AuthService } from "../auth-service/auth-service";
10 import { extractFilesData } from "./collection-service-files-response";
11 import { TrashableResourceService } from "~/services/common-service/trashable-resource-service";
12 import { ApiActions } from "~/services/api/api-actions";
13
14 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
15
16 export class CollectionService extends TrashableResourceService<CollectionResource> {
17     constructor(serverApi: AxiosInstance, private webdavClient: WebDAV, private authService: AuthService, actions: ApiActions) {
18         super(serverApi, "collections", actions, [
19             'fileCount',
20             'fileSizeTotal',
21             'replicationConfirmed',
22             'replicationConfirmedAt',
23             'storageClassesConfirmed',
24             'storageClassesConfirmedAt',
25             'unsignedManifestText',
26             'version',
27         ]);
28     }
29
30     async files(uuid: string) {
31         const request = await this.webdavClient.propfind(`c=${uuid}`);
32         if (request.responseXML != null) {
33             return extractFilesData(request.responseXML);
34         }
35         return Promise.reject();
36     }
37
38     async deleteFiles(collectionUuid: string, filePaths: string[]) {
39         const sortedUniquePaths = Array.from(new Set(filePaths))
40             .sort((a, b) => b.length - a.length);
41
42         for (const path of sortedUniquePaths) {
43             if (path.indexOf(collectionUuid) === -1) {
44                 await this.webdavClient.delete(`c=${collectionUuid}${path}`);
45             } else {
46                 await this.webdavClient.delete(`c=${path}`);
47             }
48         }
49     }
50
51     async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
52         // files have to be uploaded sequentially
53         for (let idx = 0; idx < files.length; idx++) {
54             await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
55         }
56     }
57
58     moveFile(collectionUuid: string, oldPath: string, newPath: string) {
59         return this.webdavClient.move(
60             `c=${collectionUuid}${oldPath}`,
61             `c=${collectionUuid}${encodeURI(newPath)}`
62         );
63     }
64
65     extendFileURL = (file: CollectionDirectory | CollectionFile) => {
66         const baseUrl = this.webdavClient.defaults.baseURL.endsWith('/')
67             ? this.webdavClient.defaults.baseURL.slice(0, -1)
68             : this.webdavClient.defaults.baseURL;
69         const apiToken = this.authService.getApiToken();
70         const encodedApiToken = apiToken ? encodeURI(apiToken) : '';
71         const userApiToken = `/t=${encodedApiToken}/`;
72         const splittedPrevFileUrl = file.url.split('/');
73         const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join('/')}`;
74         return {
75             ...file,
76             url
77         };
78     }
79
80     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
81         const fileURL = `c=${collectionUuid}/${file.name}`;
82         const requestConfig = {
83             headers: {
84                 'Content-Type': 'text/octet-stream'
85             },
86             onUploadProgress: (e: ProgressEvent) => {
87                 onProgress(fileId, e.loaded, e.total, Date.now());
88             }
89         };
90         return this.webdavClient.upload(fileURL, [file], requestConfig);
91     }
92 }