43041ccd91cc2e3103a54860ad0930e826a50e0b
[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 import { customEncodeURI } from "common/url";
14 import { FilterBuilder } from "services/api/filter-builder";
15
16 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
17
18 export class CollectionService extends TrashableResourceService<CollectionResource> {
19     constructor(serverApi: AxiosInstance, private webdavClient: WebDAV, private authService: AuthService, actions: ApiActions) {
20         super(serverApi, "collections", actions, [
21             'fileCount',
22             'fileSizeTotal',
23             'replicationConfirmed',
24             'replicationConfirmedAt',
25             'storageClassesConfirmed',
26             'storageClassesConfirmedAt',
27             'unsignedManifestText',
28             'version',
29         ]);
30     }
31
32     async get(uuid: string, showErrors?: boolean) {
33         super.validateUuid(uuid);
34         // We use a filtered list request to avoid getting the manifest text
35         const filters = new FilterBuilder().addEqual('uuid', uuid).getFilters();
36         const lst = await super.list({filters}, showErrors);
37         return lst.items[0];
38     }
39
40     create(data?: Partial<CollectionResource>) {
41         return super.create({ ...data, preserveVersion: true });
42     }
43
44     update(uuid: string, data: Partial<CollectionResource>) {
45         const select = [...Object.keys(data), 'version', 'modifiedAt'];
46         return super.update(uuid, { ...data, preserveVersion: true }, select);
47     }
48
49     async files(uuid: string) {
50         const request = await this.webdavClient.propfind(`c=${uuid}`);
51         if (request.responseXML != null) {
52             return extractFilesData(request.responseXML);
53         }
54         return Promise.reject();
55     }
56
57     async deleteFiles(collectionUuid: string, filePaths: string[]) {
58         const sortedUniquePaths = Array.from(new Set(filePaths))
59             .sort((a, b) => a.length - b.length)
60             .reduce((acc, currentPath) => {
61                 const parentPathFound = acc.find((parentPath) => currentPath.indexOf(`${parentPath}/`) > -1);
62
63                 if (!parentPathFound) {
64                     return [...acc, currentPath];
65                 }
66
67                 return acc;
68             }, []);
69
70         for (const path of sortedUniquePaths) {
71             if (path.indexOf(collectionUuid) === -1) {
72                 await this.webdavClient.delete(`c=${collectionUuid}${path}`);
73             } else {
74                 await this.webdavClient.delete(`c=${path}`);
75             }
76         }
77         await this.update(collectionUuid, { preserveVersion: true });
78     }
79
80     async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
81         if (collectionUuid === "" || files.length === 0) { return; }
82         // files have to be uploaded sequentially
83         for (let idx = 0; idx < files.length; idx++) {
84             await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
85         }
86         await this.update(collectionUuid, { preserveVersion: true });
87     }
88
89     async moveFile(collectionUuid: string, oldPath: string, newPath: string) {
90         await this.webdavClient.move(
91             `c=${collectionUuid}${oldPath}`,
92             `c=${collectionUuid}/${customEncodeURI(newPath)}`
93         );
94         await this.update(collectionUuid, { preserveVersion: true });
95     }
96
97     extendFileURL = (file: CollectionDirectory | CollectionFile) => {
98         const baseUrl = this.webdavClient.defaults.baseURL.endsWith('/')
99             ? this.webdavClient.defaults.baseURL.slice(0, -1)
100             : this.webdavClient.defaults.baseURL;
101         const apiToken = this.authService.getApiToken();
102         const encodedApiToken = apiToken ? encodeURI(apiToken) : '';
103         const userApiToken = `/t=${encodedApiToken}/`;
104         const splittedPrevFileUrl = file.url.split('/');
105         const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join('/')}`;
106         return {
107             ...file,
108             url
109         };
110     }
111
112     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
113         const fileURL = `c=${collectionUuid}/${file.name}`;
114         const requestConfig = {
115             headers: {
116                 'Content-Type': 'text/octet-stream'
117             },
118             onUploadProgress: (e: ProgressEvent) => {
119                 onProgress(fileId, e.loaded, e.total, Date.now());
120             },
121         };
122         return this.webdavClient.upload(fileURL, [file], requestConfig);
123     }
124 }