Merge branch 'master' into 14275-structured-search-basic-view
[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 { mapTreeValues } from "~/models/tree";
11 import { parseFilesResponse } from "./collection-service-files-response";
12 import { fileToArrayBuffer } from "~/common/file";
13 import { TrashableResourceService } from "~/services/common-service/trashable-resource-service";
14 import { ApiActions } from "~/services/api/api-actions";
15 import { snakeCase } from 'lodash';
16
17 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
18
19 export class CollectionService extends TrashableResourceService<CollectionResource> {
20     constructor(serverApi: AxiosInstance, private webdavClient: WebDAV, private authService: AuthService, actions: ApiActions) {
21         super(serverApi, "collections", actions);
22     }
23
24     async files(uuid: string) {
25         const request = await this.webdavClient.propfind(`c=${uuid}`);
26         if (request.responseXML != null) {
27             const filesTree = parseFilesResponse(request.responseXML);
28             return mapTreeValues(this.extendFileURL)(filesTree);
29         }
30         return Promise.reject();
31     }
32
33     async deleteFiles(collectionUuid: string, filePaths: string[]) {
34         for (const path of filePaths) {
35             await this.webdavClient.delete(`c=${collectionUuid}${path}`);
36         }
37     }
38
39     async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress) {
40         // files have to be uploaded sequentially
41         for (let idx = 0; idx < files.length; idx++) {
42             await this.uploadFile(collectionUuid, files[idx], idx, onProgress);
43         }
44     }
45
46     moveFile(collectionUuid: string, oldPath: string, newPath: string) {
47         return this.webdavClient.move(
48             `c=${collectionUuid}${oldPath}`,
49             `c=${collectionUuid}${encodeURI(newPath)}`
50         );
51     }
52
53     private extendFileURL = (file: CollectionDirectory | CollectionFile) => ({
54         ...file,
55         url: this.webdavClient.defaults.baseURL + file.url + '?api_token=' + this.authService.getApiToken()
56     })
57
58     private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
59         const fileURL = `c=${collectionUuid}/${file.name}`;
60         const fileContent = await fileToArrayBuffer(file);
61         const requestConfig = {
62             headers: {
63                 'Content-Type': 'text/octet-stream'
64             },
65             onUploadProgress: (e: ProgressEvent) => {
66                 onProgress(fileId, e.loaded, e.total, Date.now());
67             }
68         };
69         return this.webdavClient.put(fileURL, fileContent, requestConfig);
70
71     }
72
73     update(uuid: string, data: Partial<CollectionResource>) {
74         if (uuid && data && data.properties) {
75             const { properties } = data;
76             const mappedData = {
77                 ...TrashableResourceService.mapKeys(snakeCase)(data),
78                 properties,
79             };
80             return TrashableResourceService
81                 .defaultResponse(
82                     this.serverApi
83                         .put<CollectionResource>(this.resourceType + uuid, mappedData),
84                     this.actions,
85                     false
86                 );
87         }
88         return TrashableResourceService
89             .defaultResponse(
90                 this.serverApi
91                     .put<CollectionResource>(this.resourceType + uuid, data && TrashableResourceService.mapKeys(snakeCase)(data)),
92                 this.actions
93             );
94     }
95 }