1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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";
18 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
20 export class CollectionService extends TrashableResourceService<CollectionResource> {
21 constructor(serverApi: AxiosInstance, private webdavClient: WebDAV, private authService: AuthService, actions: ApiActions) {
22 super(serverApi, "collections", actions, [
25 'replicationConfirmed',
26 'replicationConfirmedAt',
27 'storageClassesConfirmed',
28 'storageClassesConfirmedAt',
29 'unsignedManifestText',
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};
40 listArgs.select = select;
44 const lst = await super.list(listArgs, showErrors);
47 return super.get(uuid, showErrors, session);
51 create(data?: Partial<CollectionResource>) {
52 return super.create({ ...data, preserveVersion: true });
55 update(uuid: string, data: Partial<CollectionResource>) {
56 const select = [...Object.keys(data), 'version', 'modifiedAt'];
57 return super.update(uuid, { ...data, preserveVersion: true }, select);
60 async files(uuid: string) {
61 const request = await this.webdavClient.propfind(`c=${uuid}`);
62 if (request.responseXML != null) {
63 return extractFilesData(request.responseXML);
65 return Promise.reject();
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);
74 if (!parentPathFound) {
75 return [...acc, currentPath];
81 for (const path of sortedUniquePaths) {
82 if (path.indexOf(collectionUuid) === -1) {
83 await this.webdavClient.delete(`c=${collectionUuid}${path}`);
85 await this.webdavClient.delete(`c=${path}`);
88 await this.update(collectionUuid, { preserveVersion: true });
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);
97 await this.update(collectionUuid, { preserveVersion: true });
100 async moveFile(collectionUuid: string, oldPath: string, newPath: string) {
101 await this.webdavClient.move(
102 `c=${collectionUuid}${oldPath}`,
103 `c=${collectionUuid}/${customEncodeURI(newPath)}`
105 await this.update(collectionUuid, { preserveVersion: true });
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('/')}`;
123 private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }) {
124 const fileURL = `c=${collectionUuid}/${file.name}`;
125 const requestConfig = {
127 'Content-Type': 'text/octet-stream'
129 onUploadProgress: (e: ProgressEvent) => {
130 onProgress(fileId, e.loaded, e.total, Date.now());
133 return this.webdavClient.upload(fileURL, [file], requestConfig);