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