28784a8ae63db32018b19e73c22aaeb8a40869d3
[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
9 export const sortFilesTree = (tree: Tree<CollectionDirectory | CollectionFile>) => {
10     return mapTree<CollectionDirectory | CollectionFile>(node => {
11         const children = getNodeChildren(node.id)(tree);
12
13         children.sort((a, b) =>
14             a.value.type !== b.value.type
15                 ? a.value.type === CollectionFileType.DIRECTORY ? -1 : 1
16                 : a.value.name.localeCompare(b.value.name)
17         );
18         return { ...node, children: children.map(child => child.id) };
19     })(tree);
20 };
21
22 export const extractFilesData = (document: Document) => {
23     const collectionUrlPrefix = /\/c=([^\/]*)/;
24     return Array
25         .from(document.getElementsByTagName('D:response'))
26         .slice(1) // omit first element which is collection itself
27         .map(element => {
28             const name = getTagValue(element, 'D:displayname', '', true); // skip decoding as value should be already decoded
29             const size = parseInt(getTagValue(element, 'D:getcontentlength', '0', true), 10);
30             const url = getTagValue(element, 'D:href', '', true);
31             const collectionUuidMatch = collectionUrlPrefix.exec(url);
32             const collectionUuid = collectionUuidMatch ? collectionUuidMatch.pop() : '';
33             const pathArray = url.split(`/`);
34             if (!pathArray.pop()) {
35                 pathArray.pop();
36             }
37             const directory = pathArray.join('/')
38                 .replace(collectionUrlPrefix, '')
39                 .replace(/\/\//g, '/');
40
41             const parentPath = directory.replace(/\/$/, '');
42             const data = {
43                 url,
44                 id: [
45                     collectionUuid ? collectionUuid : '',
46                     directory ? decodeURIComponent(parentPath) : '',
47                     '/' + name
48                 ].join(''),
49                 name,
50                 path: decodeURIComponent(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 };