17337: Added % sign handling in collection files
[arvados-workbench2.git] / src / services / collection-service / collection-service-files-response.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { CollectionDirectory, CollectionFile, CollectionFileType, createCollectionDirectory, createCollectionFile } from "../../models/collection-file";
6 import { getTagValue } from "~/common/xml";
7 import { getNodeChildren, Tree, mapTree } from '~/models/tree';
8 import { customDecodeURI } from "~/common/url";
9
10 export const sortFilesTree = (tree: Tree<CollectionDirectory | CollectionFile>) => {
11     return mapTree<CollectionDirectory | CollectionFile>(node => {
12         const children = getNodeChildren(node.id)(tree);
13
14         children.sort((a, b) =>
15             a.value.type !== b.value.type
16                 ? a.value.type === CollectionFileType.DIRECTORY ? -1 : 1
17                 : a.value.name.localeCompare(b.value.name)
18         );
19         return { ...node, children: children.map(child => child.id) };
20     })(tree);
21 };
22
23 export const extractFilesData = (document: Document) => {
24     const collectionUrlPrefix = /\/c=([^\/]*)/;
25     return Array
26         .from(document.getElementsByTagName('D:response'))
27         .slice(1) // omit first element which is collection itself
28         .map(element => {
29             const name = getTagValue(element, 'D:displayname', '');
30             const size = parseInt(getTagValue(element, 'D:getcontentlength', '0'), 10);
31             const url = customDecodeURI(getTagValue(element, 'D:href', ''));
32             const nameSuffix = name;
33             const collectionUuidMatch = collectionUrlPrefix.exec(url);
34             const collectionUuid = collectionUuidMatch ? collectionUuidMatch.pop() : '';
35             const directory = url
36                 .replace(collectionUrlPrefix, '')
37                 .replace(nameSuffix, '')
38                 .replace(/\/\//g, '/');
39
40             const parentPath = directory.replace(/\/$/, '');
41             const data = {
42                 url,
43                 id: [
44                     collectionUuid ? collectionUuid : '',
45                     directory ? parentPath : '',
46                     '/' + name
47                 ].join(''),
48                 name,
49                 path: parentPath,
50             };
51
52             const result = getTagValue(element, 'D:resourcetype', '')
53                 ? createCollectionDirectory(data)
54                 : createCollectionFile({ ...data, size });
55
56             return result;
57         });
58 };
59
60 export const getFileFullPath = ({ name, path }: CollectionFile | CollectionDirectory) => {
61     return `${path}/${name}`;
62 };