Merge branch 'master' into 14431-metadata
[arvados-workbench2.git] / src / store / tree-picker / tree-picker-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { unionize, ofType, UnionOf } from "~/common/unionize";
6 import { TreeNode, initTreeNode, getNodeDescendants, TreeNodeStatus, getNode, TreePickerId } from '~/models/tree';
7 import { Dispatch } from 'redux';
8 import { RootState } from '~/store/store';
9 import { ServiceRepository } from '~/services/services';
10 import { FilterBuilder } from '~/services/api/filter-builder';
11 import { pipe, values } from 'lodash/fp';
12 import { ResourceKind } from '~/models/resource';
13 import { GroupContentsResource } from '~/services/groups-service/groups-service';
14 import { CollectionDirectory, CollectionFile } from '~/models/collection-file';
15 import { getTreePicker, TreePicker } from './tree-picker';
16 import { ProjectsTreePickerItem } from '~/views-components/projects-tree-picker/generic-projects-tree-picker';
17 import { OrderBuilder } from '~/services/api/order-builder';
18 import { ProjectResource } from '~/models/project';
19
20 export const treePickerActions = unionize({
21     LOAD_TREE_PICKER_NODE: ofType<{ id: string, pickerId: string }>(),
22     LOAD_TREE_PICKER_NODE_SUCCESS: ofType<{ id: string, nodes: Array<TreeNode<any>>, pickerId: string }>(),
23     TOGGLE_TREE_PICKER_NODE_COLLAPSE: ofType<{ id: string, pickerId: string }>(),
24     ACTIVATE_TREE_PICKER_NODE: ofType<{ id: string, pickerId: string }>(),
25     DEACTIVATE_TREE_PICKER_NODE: ofType<{ pickerId: string }>(),
26     TOGGLE_TREE_PICKER_NODE_SELECTION: ofType<{ id: string, pickerId: string }>(),
27     SELECT_TREE_PICKER_NODE: ofType<{ id: string | string[], pickerId: string }>(),
28     DESELECT_TREE_PICKER_NODE: ofType<{ id: string | string[], pickerId: string }>(),
29     EXPAND_TREE_PICKER_NODES: ofType<{ ids: string[], pickerId: string }>(),
30     RESET_TREE_PICKER: ofType<{ pickerId: string }>()
31 });
32
33 export type TreePickerAction = UnionOf<typeof treePickerActions>;
34
35 export const getProjectsTreePickerIds = (pickerId: string) => ({
36     home: `${pickerId}_home`,
37     shared: `${pickerId}_shared`,
38     favorites: `${pickerId}_favorites`,
39 });
40
41 export const getAllNodes = <Value>(pickerId: string, filter = (node: TreeNode<Value>) => true) => (state: TreePicker) =>
42     pipe(
43         () => values(getProjectsTreePickerIds(pickerId)),
44
45         ids => ids
46             .map(id => getTreePicker<Value>(id)(state)),
47
48         trees => trees
49             .map(getNodeDescendants(''))
50             .reduce((allNodes, nodes) => allNodes.concat(nodes), []),
51
52         allNodes => allNodes
53             .reduce((map, node) =>
54                 filter(node)
55                     ? map.set(node.id, node)
56                     : map, new Map<string, TreeNode<Value>>())
57             .values(),
58
59         uniqueNodes => Array.from(uniqueNodes),
60     )();
61 export const getSelectedNodes = <Value>(pickerId: string) => (state: TreePicker) =>
62     getAllNodes<Value>(pickerId, node => node.selected)(state);
63     
64 export const initProjectsTreePicker = (pickerId: string) =>
65     async (dispatch: Dispatch, _: () => RootState, services: ServiceRepository) => {
66         const { home, shared, favorites } = getProjectsTreePickerIds(pickerId);
67         dispatch<any>(initUserProject(home));
68         dispatch<any>(initSharedProject(shared));
69         dispatch<any>(initFavoritesProject(favorites));
70     };
71
72 interface ReceiveTreePickerDataParams<T> {
73     data: T[];
74     extractNodeData: (value: T) => { id: string, value: T, status?: TreeNodeStatus };
75     id: string;
76     pickerId: string;
77 }
78
79 export const receiveTreePickerData = <T>(params: ReceiveTreePickerDataParams<T>) =>
80     (dispatch: Dispatch) => {
81         const { data, extractNodeData, id, pickerId, } = params;
82         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
83             id,
84             nodes: data.map(item => initTreeNode(extractNodeData(item))),
85             pickerId,
86         }));
87         dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
88     };
89
90 interface LoadProjectParams {
91     id: string;
92     pickerId: string;
93     includeCollections?: boolean;
94     includeFiles?: boolean;
95     loadShared?: boolean;
96 }
97 export const loadProject = (params: LoadProjectParams) =>
98     async (dispatch: Dispatch, _: () => RootState, services: ServiceRepository) => {
99         const { id, pickerId, includeCollections = false, includeFiles = false, loadShared = false } = params;
100
101         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId }));
102
103         const filters = pipe(
104             (fb: FilterBuilder) => includeCollections
105                 ? fb.addIsA('uuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
106                 : fb.addIsA('uuid', [ResourceKind.PROJECT]),
107             fb => fb.getFilters(),
108         )(new FilterBuilder());
109
110         const { items } = await services.groupsService.contents(loadShared ? '' : id, { filters, excludeHomeProject: loadShared || undefined });
111
112         dispatch<any>(receiveTreePickerData<GroupContentsResource>({
113             id,
114             pickerId,
115             data: items,
116             extractNodeData: item => ({
117                 id: item.uuid,
118                 value: item,
119                 status: item.kind === ResourceKind.PROJECT
120                     ? TreeNodeStatus.INITIAL
121                     : includeFiles
122                         ? TreeNodeStatus.INITIAL
123                         : TreeNodeStatus.LOADED
124             }),
125         }));
126     };
127
128 export const loadCollection = (id: string, pickerId: string) =>
129     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
130         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId }));
131
132         const picker = getTreePicker<ProjectsTreePickerItem>(pickerId)(getState().treePicker);
133         if (picker) {
134
135             const node = getNode(id)(picker);
136             if (node && 'kind' in node.value && node.value.kind === ResourceKind.COLLECTION) {
137
138                 const files = await services.collectionService.files(node.value.portableDataHash);
139                 const data = getNodeDescendants('')(files).map(node => node.value);
140
141                 dispatch<any>(receiveTreePickerData<CollectionDirectory | CollectionFile>({
142                     id,
143                     pickerId,
144                     data,
145                     extractNodeData: value => ({
146                         id: value.id,
147                         status: TreeNodeStatus.LOADED,
148                         value,
149                     }),
150                 }));
151             }
152         }
153     };
154
155
156 export const initUserProject = (pickerId: string) =>
157     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
158         const uuid = services.authService.getUuid();
159         if (uuid) {
160             dispatch(receiveTreePickerData({
161                 id: '',
162                 pickerId,
163                 data: [{ uuid, name: 'Projects' }],
164                 extractNodeData: value => ({
165                     id: value.uuid,
166                     status: TreeNodeStatus.INITIAL,
167                     value,
168                 }),
169             }));
170         }
171     };
172 export const loadUserProject = (pickerId: string, includeCollections = false, includeFiles = false) =>
173     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
174         const uuid = services.authService.getUuid();
175         if (uuid) {
176             dispatch(loadProject({ id: uuid, pickerId, includeCollections, includeFiles }));
177         }
178     };
179
180
181 export const initSharedProject = (pickerId: string) =>
182     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
183         dispatch(receiveTreePickerData({
184             id: '',
185             pickerId,
186             data: [{ uuid: 'Shared with me', name: 'Shared with me' }],
187             extractNodeData: value => ({
188                 id: value.uuid,
189                 status: TreeNodeStatus.INITIAL,
190                 value,
191             }),
192         }));
193     };
194
195 export const initFavoritesProject = (pickerId: string) =>
196     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
197         dispatch(receiveTreePickerData({
198             id: '',
199             pickerId,
200             data: [{ uuid: 'Favorites', name: 'Favorites' }],
201             extractNodeData: value => ({
202                 id: value.uuid,
203                 status: TreeNodeStatus.INITIAL,
204                 value,
205             }),
206         }));
207     };
208
209 interface LoadFavoritesProjectParams {
210     pickerId: string;
211     includeCollections?: boolean;
212     includeFiles?: boolean;
213 }
214
215 export const loadFavoritesProject = (params: LoadFavoritesProjectParams) =>
216     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
217         const { pickerId, includeCollections = false, includeFiles = false } = params;
218         const uuid = services.authService.getUuid();
219         if (uuid) {
220
221             const filters = pipe(
222                 (fb: FilterBuilder) => includeCollections
223                     ? fb.addIsA('headUuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
224                     : fb.addIsA('headUuid', [ResourceKind.PROJECT]),
225                 fb => fb.getFilters(),
226             )(new FilterBuilder());
227
228             const { items } = await services.favoriteService.list(uuid, { filters });
229
230             dispatch<any>(receiveTreePickerData<GroupContentsResource>({
231                 id: 'Favorites',
232                 pickerId,
233                 data: items,
234                 extractNodeData: item => ({
235                     id: item.uuid,
236                     value: item,
237                     status: item.kind === ResourceKind.PROJECT
238                         ? TreeNodeStatus.INITIAL
239                         : includeFiles
240                             ? TreeNodeStatus.INITIAL
241                             : TreeNodeStatus.LOADED
242                 }),
243             }));
244         }
245     };
246
247 export const receiveTreePickerProjectsData = (id: string, projects: ProjectResource[], pickerId: string) =>
248     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
249         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
250             id,
251             nodes: projects.map(project => initTreeNode({ id: project.uuid, value: project })),
252             pickerId,
253         }));
254
255         dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
256     };
257
258 export const loadProjectTreePickerProjects = (id: string) =>
259     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
260         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.PROJECTS }));
261
262         const ownerUuid = id.length === 0 ? services.authService.getUuid() || '' : id;
263         const { items } = await services.projectService.list(buildParams(ownerUuid));
264
265         dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.PROJECTS));
266     };
267
268 export const loadFavoriteTreePickerProjects = (id: string) =>
269     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
270         const parentId = services.authService.getUuid() || '';
271
272         if (id === '') {
273             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: parentId, pickerId: TreePickerId.FAVORITES }));
274             const { items } = await services.favoriteService.list(parentId);
275             dispatch<any>(receiveTreePickerProjectsData(parentId, items as ProjectResource[], TreePickerId.FAVORITES));
276         } else {
277             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.FAVORITES }));
278             const { items } = await services.projectService.list(buildParams(id));
279             dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.FAVORITES));
280         }
281
282     };
283
284 const buildParams = (ownerUuid: string) => {
285     return {
286         filters: new FilterBuilder()
287             .addEqual('ownerUuid', ownerUuid)
288             .getFilters(),
289         order: new OrderBuilder<ProjectResource>()
290             .addAsc('name')
291             .getOrder()
292     };
293 };