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