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