9583b7a4ebd749ffaa2898ad176830c4214f8573
[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 href = getTagValue(element, 'D:href', '');
32             const url = customDecodeURI(href);
33             const nameSuffix = name;
34             const collectionUuidMatch = collectionUrlPrefix.exec(url);
35             const collectionUuid = collectionUuidMatch ? collectionUuidMatch.pop() : '';
36             const directory = url
37                 .replace(collectionUrlPrefix, '')
38                 .replace(nameSuffix, '')
39                 .replace(/\/\//g, '/');
40
41             const parentPath = directory.replace(/\/$/, '');
42             const data = {
43                 url,
44                 id: [
45                     collectionUuid ? collectionUuid : '',
46                     directory ? parentPath : '',
47                     '/' + name
48                 ].join(''),
49                 name,
50                 path: parentPath,
51             };
52
53             const result = getTagValue(element, 'D:resourcetype', '')
54                 ? createCollectionDirectory(data)
55                 : createCollectionFile({ ...data, size });
56
57             return result;
58         });
59 };
60
61 export const getFileFullPath = ({ name, path }: CollectionFile | CollectionDirectory) => {
62     return `${path}/${name}`;
63 };