5e6891c8ed417254f451cd2e640bdf80ca510222
[arvados-workbench2.git] / src / services / collection-files-service / collection-files-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { CollectionService } from "../collection-service/collection-service";
6 import { parseKeepManifestText, stringifyKeepManifest } from "./collection-manifest-parser";
7 import { mapManifestToCollectionFilesTree } from "./collection-manifest-mapper";
8 import { CommonResourceService } from "../../common/api/common-resource-service";
9 import * as _ from "lodash";
10
11 export class CollectionFilesService {
12
13     constructor(private collectionService: CollectionService) { }
14
15     getFiles(collectionUuid: string) {
16         return this.collectionService
17             .get(collectionUuid)
18             .then(collection =>
19                 mapManifestToCollectionFilesTree(
20                     parseKeepManifestText(
21                         collection.manifestText
22                     )
23                 )
24             );
25     }
26
27     async renameFile(collectionUuid: string, file: { name: string, path: string }, newName: string) {
28         const collection = await this.collectionService.get(collectionUuid);
29         const manifest = parseKeepManifestText(collection.manifestText);
30         const updatedManifest = manifest.map(
31             stream => stream.name === file.path
32                 ? {
33                     ...stream,
34                     files: stream.files.map(
35                         f => f.name === file.name
36                             ? { ...f, name: newName }
37                             : f
38                     )
39                 }
40                 : stream
41         );
42         const manifestText = stringifyKeepManifest(updatedManifest);
43         const data = { ...collection, manifestText };
44         return this.collectionService.update(collectionUuid, CommonResourceService.mapKeys(_.snakeCase)(data));
45     }
46
47     async deleteFile(collectionUuid: string, file: { name: string, path: string }) {
48         const collection = await this.collectionService.get(collectionUuid);
49         const manifest = parseKeepManifestText(collection.manifestText);
50         const updatedManifest = manifest.map(stream =>
51             stream.name === file.path
52                 ? {
53                     ...stream,
54                     files: stream.files.filter(f => f.name !== file.name)
55                 }
56                 : stream
57         );
58         const manifestText = stringifyKeepManifest(updatedManifest);
59         return this.collectionService.update(collectionUuid, { manifestText });
60     }
61
62     renameTest() {
63         const u = this.renameFile('qr1hi-4zz18-n0sx074erl4p0ph', {
64             name: 'extracted2.txt.png',
65             path: ''
66         }, 'extracted-new.txt.png');
67     }
68 }