1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { CollectionResource, defaultCollectionSelectedFields } 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 { Session } from "models/session";
14 import { CommonService } from "services/common-service/common-service";
16 export type UploadProgress = (fileId: number, loaded: number, total: number, currentTime: number) => void;
18 export const emptyCollectionUuid = 'd41d8cd98f00b204e9800998ecf8427e+0';
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 const selectParam = select || defaultCollectionSelectedFields;
37 return super.get(uuid, showErrors, selectParam, session);
40 create(data?: Partial<CollectionResource>, showErrors?: boolean) {
41 return super.create({ ...data, preserveVersion: true }, showErrors);
44 update(uuid: string, data: Partial<CollectionResource>, showErrors?: boolean) {
45 const select = [...Object.keys(data), 'version', 'modifiedAt'];
46 return super.update(uuid, { ...data, preserveVersion: true }, showErrors, select);
49 async files(uuid: string) {
50 const request = await this.webdavClient.propfind(`c=${uuid}`);
51 if (request.responseXML != null) {
52 return extractFilesData(request.responseXML);
54 return Promise.reject();
57 private combineFilePath(parts: string[]) {
58 return parts.reduce((path, part) => {
59 // Trim leading and trailing slashes
60 const trimmedPart = part.split('/').filter(Boolean).join('/');
61 if (trimmedPart.length) {
62 const separator = path.endsWith('/') ? '' : '/';
63 return `${path}${separator}${trimmedPart}`;
70 private replaceFiles(collectionUuid: string, fileMap: {}, showErrors?: boolean) {
73 preserve_version: true
75 replace_files: fileMap
78 return CommonService.defaultResponse(
80 .put<CollectionResource>(`/${this.resourceType}/${collectionUuid}`, payload),
87 async uploadFiles(collectionUuid: string, files: File[], onProgress?: UploadProgress, targetLocation: string = '') {
88 if (collectionUuid === "" || files.length === 0) { return; }
89 // files have to be uploaded sequentially
90 for (let idx = 0; idx < files.length; idx++) {
91 await this.uploadFile(collectionUuid, files[idx], idx, onProgress, targetLocation);
93 await this.update(collectionUuid, { preserveVersion: true });
96 async renameFile(collectionUuid: string, collectionPdh: string, oldPath: string, newPath: string) {
97 return this.replaceFiles(collectionUuid, {
98 [this.combineFilePath([newPath])]: `${collectionPdh}${this.combineFilePath([oldPath])}`,
99 [this.combineFilePath([oldPath])]: '',
103 extendFileURL = (file: CollectionDirectory | CollectionFile) => {
104 const baseUrl = this.webdavClient.getBaseUrl().endsWith('/')
105 ? this.webdavClient.getBaseUrl().slice(0, -1)
106 : this.webdavClient.getBaseUrl();
107 const apiToken = this.authService.getApiToken();
108 const encodedApiToken = apiToken ? encodeURI(apiToken) : '';
109 const userApiToken = `/t=${encodedApiToken}/`;
110 const splittedPrevFileUrl = file.url.split('/');
111 const url = `${baseUrl}/${splittedPrevFileUrl[1]}${userApiToken}${splittedPrevFileUrl.slice(2).join('/')}`;
118 async getFileContents(file: CollectionFile) {
119 return (await this.webdavClient.get(`c=${file.id}`)).response;
122 private async uploadFile(collectionUuid: string, file: File, fileId: number, onProgress: UploadProgress = () => { return; }, targetLocation: string = '') {
123 const fileURL = `c=${targetLocation !== '' ? targetLocation : collectionUuid}/${file.name}`.replace('//', '/');
124 const requestConfig = {
126 'Content-Type': 'text/octet-stream'
128 onUploadProgress: (e: ProgressEvent) => {
129 onProgress(fileId, e.loaded, e.total, Date.now());
132 return this.webdavClient.upload(fileURL, [file], requestConfig);
135 deleteFiles(collectionUuid: string, files: string[], showErrors?: boolean) {
136 const optimizedFiles = files
137 .sort((a, b) => a.length - b.length)
138 .reduce((acc, currentPath) => {
139 const parentPathFound = acc.find((parentPath) => currentPath.indexOf(`${parentPath}/`) > -1);
141 if (!parentPathFound) {
142 return [...acc, currentPath];
148 const fileMap = optimizedFiles.reduce((obj, filePath) => {
151 [this.combineFilePath([filePath])]: ''
155 return this.replaceFiles(collectionUuid, fileMap, showErrors);
158 copyFiles(sourcePdh: string, files: string[], destinationCollectionUuid: string, destinationPath: string, showErrors?: boolean) {
159 const fileMap = files.reduce((obj, sourceFile) => {
160 const sourceFileName = sourceFile.split('/').filter(Boolean).slice(-1).join("");
163 [this.combineFilePath([destinationPath, sourceFileName])]: `${sourcePdh}${this.combineFilePath([sourceFile])}`
167 return this.replaceFiles(destinationCollectionUuid, fileMap, showErrors);
170 moveFiles(sourceUuid: string, sourcePdh: string, files: string[], destinationCollectionUuid: string, destinationPath: string, showErrors?: boolean) {
171 if (sourceUuid === destinationCollectionUuid) {
172 const fileMap = files.reduce((obj, sourceFile) => {
173 const sourceFileName = sourceFile.split('/').filter(Boolean).slice(-1).join("");
176 [this.combineFilePath([destinationPath, sourceFileName])]: `${sourcePdh}${this.combineFilePath([sourceFile])}`,
177 [this.combineFilePath([sourceFile])]: '',
181 return this.replaceFiles(sourceUuid, fileMap, showErrors)
183 return this.copyFiles(sourcePdh, files, destinationCollectionUuid, destinationPath, showErrors)
185 return this.deleteFiles(sourceUuid, files, showErrors);
190 createDirectory(collectionUuid: string, path: string, showErrors?: boolean) {
191 const fileMap = {[this.combineFilePath([path])]: emptyCollectionUuid};
193 return this.replaceFiles(collectionUuid, fileMap, showErrors);