17016: Code optimisation
[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) => a.length - b.length)
41             .reduce((acc, currentPath) => {
42                 const parentPathFound = acc.find((parentPath) => currentPath.indexOf(`${parentPath}/`) > -1);
43
44                 if (!parentPathFound) {
45                     return [...acc, currentPath];
46                 }
47
48                 return acc;
49             }, []);
50
51         for (const path of sortedUniquePaths) {
52             if (path.indexOf(collectionUuid) === -1) {
53                 await this.webdavClient.delete(`c=${collectionUuid}${path}`);
54             } else {
55                 await this.webdavClient.delete(`c=${path}`);
56             }
57         }
58     }
59
60     async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
61         // files have to be uploaded sequentially
62         for (let idx = 0; idx < files.length; idx++) {
63             await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
64         }
65     }
66
67     moveFile(collectionUuid: string, oldPath: string, newPath: string) {
68         return this.webdavClient.move(
69             `c=${collectionUuid}${oldPath}`,
70             `c=${collectionUuid}${encodeURI(newPath)}`
71         );
72     }
73
74     extendFileURL = (file: CollectionDirectory | CollectionFile) => {
75         const baseUrl = this.webdavClient.defaults.baseURL.endsWith('/')
76             ? this.webdavClient.defaults.baseURL.slice(0, -1)
77             : this.webdavClient.defaults.baseURL;
78         const apiToken = this.authService.getApiToken();
79         const encodedApiToken = apiToken ? encodeURI(apiToken) : '';
80         const userApiToken = `/t=${encodedApiToken}/`;
81         const splittedPrevFileUrl = file.url.split('/');
82         const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join('/')}`;
83         return {
84             ...file,
85             url
86         };
87     }
88
89     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
90         const fileURL = `c=${collectionUuid}/${file.name}`;
91         const requestConfig = {
92             headers: {
93                 'Content-Type': 'text/octet-stream'
94             },
95             onUploadProgress: (e: ProgressEvent) => {
96                 onProgress(fileId, e.loaded, e.total, Date.now());
97             }
98         };
99         return this.webdavClient.upload(fileURL, [file], requestConfig);
100     }
101 }