1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { unionize, ofType, UnionOf } from "common/unionize";
6 import { TreeNode, initTreeNode, getNodeDescendants, TreeNodeStatus, getNode, TreePickerId, Tree, setNode, createTree } from 'models/tree';
7 import { CollectionFileType, createCollectionFilesTree, getCollectionResourceCollectionUuid } from "models/collection-file";
8 import { Dispatch } from 'redux';
9 import { RootState } from 'store/store';
10 import { getUserUuid } from "common/getuser";
11 import { ServiceRepository } from 'services/services';
12 import { FilterBuilder } from 'services/api/filter-builder';
13 import { pipe, values } from 'lodash/fp';
14 import { ResourceKind } from 'models/resource';
15 import { GroupContentsResource } from 'services/groups-service/groups-service';
16 import { getTreePicker, TreePicker } from './tree-picker';
17 import { ProjectsTreePickerItem } from './tree-picker-middleware';
18 import { OrderBuilder } from 'services/api/order-builder';
19 import { ProjectResource } from 'models/project';
20 import { mapTree } from '../../models/tree';
21 import { LinkResource, LinkClass } from "models/link";
22 import { mapTreeValues } from "models/tree";
23 import { sortFilesTree } from "services/collection-service/collection-service-files-response";
24 import { GroupClass, GroupResource } from "models/group";
25 import { CollectionResource } from "models/collection";
27 export const treePickerActions = unionize({
28 LOAD_TREE_PICKER_NODE: ofType<{ id: string, pickerId: string }>(),
29 LOAD_TREE_PICKER_NODE_SUCCESS: ofType<{ id: string, nodes: Array<TreeNode<any>>, pickerId: string }>(),
30 APPEND_TREE_PICKER_NODE_SUBTREE: ofType<{ id: string, subtree: Tree<any>, pickerId: string }>(),
31 TOGGLE_TREE_PICKER_NODE_COLLAPSE: ofType<{ id: string, pickerId: string }>(),
32 EXPAND_TREE_PICKER_NODE: ofType<{ id: string, pickerId: string }>(),
33 ACTIVATE_TREE_PICKER_NODE: ofType<{ id: string, pickerId: string, relatedTreePickers?: string[] }>(),
34 DEACTIVATE_TREE_PICKER_NODE: ofType<{ pickerId: string }>(),
35 TOGGLE_TREE_PICKER_NODE_SELECTION: ofType<{ id: string, pickerId: string }>(),
36 SELECT_TREE_PICKER_NODE: ofType<{ id: string | string[], pickerId: string }>(),
37 DESELECT_TREE_PICKER_NODE: ofType<{ id: string | string[], pickerId: string }>(),
38 EXPAND_TREE_PICKER_NODES: ofType<{ ids: string[], pickerId: string }>(),
39 RESET_TREE_PICKER: ofType<{ pickerId: string }>()
42 export type TreePickerAction = UnionOf<typeof treePickerActions>;
44 export interface LoadProjectParams {
45 includeCollections?: boolean;
46 includeDirectories?: boolean;
47 includeFiles?: boolean;
48 includeFilterGroups?: boolean;
49 options?: { showOnlyOwned: boolean; showOnlyWritable: boolean; };
52 export const treePickerSearchActions = unionize({
53 SET_TREE_PICKER_PROJECT_SEARCH: ofType<{ pickerId: string, projectSearchValue: string }>(),
54 SET_TREE_PICKER_COLLECTION_FILTER: ofType<{ pickerId: string, collectionFilterValue: string }>(),
55 SET_TREE_PICKER_LOAD_PARAMS: ofType<{ pickerId: string, params: LoadProjectParams }>(),
56 REFRESH_TREE_PICKER: ofType<{ pickerId: string }>(),
59 export type TreePickerSearchAction = UnionOf<typeof treePickerSearchActions>;
61 export const getProjectsTreePickerIds = (pickerId: string) => ({
62 home: `${pickerId}_home`,
63 shared: `${pickerId}_shared`,
64 favorites: `${pickerId}_favorites`,
65 publicFavorites: `${pickerId}_publicFavorites`,
66 search: `${pickerId}_search`,
69 export const getAllNodes = <Value>(pickerId: string, filter = (node: TreeNode<Value>) => true) => (state: TreePicker) =>
71 () => values(getProjectsTreePickerIds(pickerId)),
74 .map(id => getTreePicker<Value>(id)(state)),
77 .map(getNodeDescendants(''))
78 .reduce((allNodes, nodes) => allNodes.concat(nodes), []),
81 .reduce((map, node) =>
83 ? map.set(node.id, node)
84 : map, new Map<string, TreeNode<Value>>())
87 uniqueNodes => Array.from(uniqueNodes),
89 export const getSelectedNodes = <Value>(pickerId: string) => (state: TreePicker) =>
90 getAllNodes<Value>(pickerId, node => node.selected)(state);
92 export const initProjectsTreePicker = (pickerId: string, selectedItemUuid?: string) =>
93 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
94 const { home, shared, favorites, publicFavorites, search } = getProjectsTreePickerIds(pickerId);
95 dispatch<any>(initUserProject(home));
96 dispatch<any>(initSharedProject(shared));
97 dispatch<any>(initFavoritesProject(favorites));
98 dispatch<any>(initPublicFavoritesProject(publicFavorites));
99 dispatch<any>(initSearchProject(search));
101 if (selectedItemUuid) {
102 dispatch<any>(loadInitialValue(selectedItemUuid, pickerId));
106 interface ReceiveTreePickerDataParams<T> {
108 extractNodeData: (value: T) => { id: string, value: T, status?: TreeNodeStatus };
113 export const receiveTreePickerData = <T>(params: ReceiveTreePickerDataParams<T>) =>
114 (dispatch: Dispatch) => {
115 const { data, extractNodeData, id, pickerId, } = params;
116 dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
118 nodes: data.map(item => initTreeNode(extractNodeData(item))),
121 dispatch(treePickerActions.EXPAND_TREE_PICKER_NODE({ id, pickerId }));
124 interface LoadProjectParamsWithId extends LoadProjectParams {
127 loadShared?: boolean;
128 searchProjects?: boolean;
131 export const loadProject = (params: LoadProjectParamsWithId) =>
132 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
136 includeCollections = false,
137 includeDirectories = false,
138 includeFiles = false,
139 includeFilterGroups = false,
142 searchProjects = false
145 dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId }));
147 let filterB = new FilterBuilder();
149 filterB = (includeCollections && !searchProjects)
150 ? filterB.addIsA('uuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
151 : filterB.addIsA('uuid', [ResourceKind.PROJECT]);
153 const state = getState();
155 if (state.treePickerSearch.collectionFilterValues[pickerId]) {
156 filterB = filterB.addFullTextSearch(state.treePickerSearch.collectionFilterValues[pickerId], 'collections');
158 filterB = filterB.addNotIn("collections.properties.type", ["intermediate", "log"]);
161 if (searchProjects && state.treePickerSearch.projectSearchValues[pickerId]) {
162 filterB = filterB.addFullTextSearch(state.treePickerSearch.projectSearchValues[pickerId], 'groups');
165 const filters = filterB.getFilters();
167 const itemLimit = 200;
169 const { items, itemsAvailable } = await services.groupsService.contents((loadShared || searchProjects) ? '' : id, { filters, excludeHomeProject: loadShared || undefined, limit: itemLimit });
171 if (itemsAvailable > itemLimit) {
173 uuid: "more-items-available",
174 kind: ResourceKind.WORKFLOW,
175 name: `*** Not all items listed (${items.length} out of ${itemsAvailable}), reduce item count with search or filter ***`,
180 modifiedByClientUuid: "",
181 modifiedByUserUuid: "",
188 dispatch<any>(receiveTreePickerData<GroupContentsResource>({
191 data: items.filter((item) => {
192 if (!includeFilterGroups && (item as GroupResource).groupClass && (item as GroupResource).groupClass === GroupClass.FILTER) {
196 if (options && options.showOnlyWritable && item.hasOwnProperty('frozenByUuid') && (item as ProjectResource).frozenByUuid) {
202 extractNodeData: item => (
203 item.uuid === "more-items-available" ?
207 status: TreeNodeStatus.LOADED
212 status: item.kind === ResourceKind.PROJECT
213 ? TreeNodeStatus.INITIAL
214 : includeDirectories || includeFiles
215 ? TreeNodeStatus.INITIAL
216 : TreeNodeStatus.LOADED
221 export const loadCollection = (id: string, pickerId: string, includeDirectories?: boolean, includeFiles?: boolean) =>
222 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
223 dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId }));
225 const picker = getTreePicker<ProjectsTreePickerItem>(pickerId)(getState().treePicker);
228 const node = getNode(id)(picker);
229 if (node && 'kind' in node.value && node.value.kind === ResourceKind.COLLECTION) {
230 const files = (await services.collectionService.files(node.value.uuid))
233 (includeDirectories && file.type === CollectionFileType.DIRECTORY)
235 const tree = createCollectionFilesTree(files);
236 const sorted = sortFilesTree(tree);
237 const filesTree = mapTreeValues(services.collectionService.extendFileURL)(sorted);
240 treePickerActions.APPEND_TREE_PICKER_NODE_SUBTREE({
243 subtree: mapTree(node => ({ ...node, status: TreeNodeStatus.LOADED }))(filesTree)
246 dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
251 export const HOME_PROJECT_ID = 'Home Projects';
252 export const initUserProject = (pickerId: string) =>
253 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
254 const uuid = getUserUuid(getState());
256 dispatch(receiveTreePickerData({
259 data: [{ uuid, name: HOME_PROJECT_ID }],
260 extractNodeData: value => ({
262 status: TreeNodeStatus.INITIAL,
268 export const loadUserProject = (pickerId: string, includeCollections = false, includeDirectories = false, includeFiles = false, options?: { showOnlyOwned: boolean, showOnlyWritable: boolean }) =>
269 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
270 const uuid = getUserUuid(getState());
272 dispatch(loadProject({ id: uuid, pickerId, includeCollections, includeDirectories, includeFiles, options }));
276 export const SHARED_PROJECT_ID = 'Shared with me';
277 export const initSharedProject = (pickerId: string) =>
278 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
279 dispatch(receiveTreePickerData({
282 data: [{ uuid: SHARED_PROJECT_ID, name: SHARED_PROJECT_ID }],
283 extractNodeData: value => ({
285 status: TreeNodeStatus.INITIAL,
291 export const loadInitialValue = (initialValue: string, pickerId: string) =>
292 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
293 const { home, shared } = getProjectsTreePickerIds(pickerId);
294 const homeUuid = getUserUuid(getState());
295 const ancestors = (await services.ancestorsService.ancestors(initialValue, ''))
297 item.kind === ResourceKind.GROUP ||
298 item.kind === ResourceKind.COLLECTION
299 ) as (GroupResource | CollectionResource)[];
301 if (ancestors.length) {
302 const isUserHomeProject = !!(homeUuid && ancestors.some(item => item.ownerUuid === homeUuid));
303 const pickerTreeId = isUserHomeProject ? home : shared;
304 const pickerTreeRootUuid: string = (homeUuid && isUserHomeProject) ? homeUuid : SHARED_PROJECT_ID;
306 ancestors[0].ownerUuid = '';
307 const tree = createInitialLocationTree(ancestors, initialValue);
309 treePickerActions.APPEND_TREE_PICKER_NODE_SUBTREE({
310 id: pickerTreeRootUuid,
311 pickerId: pickerTreeId,
314 dispatch(treePickerActions.EXPAND_TREE_PICKER_NODES({ ids: [pickerTreeRootUuid], pickerId: pickerTreeId }));
315 dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ id: initialValue, pickerId: pickerTreeId }));
316 dispatch(treePickerSearchActions.REFRESH_TREE_PICKER({ pickerId: pickerTreeId }));
321 export const FAVORITES_PROJECT_ID = 'Favorites';
322 export const initFavoritesProject = (pickerId: string) =>
323 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
324 dispatch(receiveTreePickerData({
327 data: [{ uuid: FAVORITES_PROJECT_ID, name: FAVORITES_PROJECT_ID }],
328 extractNodeData: value => ({
330 status: TreeNodeStatus.INITIAL,
336 export const PUBLIC_FAVORITES_PROJECT_ID = 'Public Favorites';
337 export const initPublicFavoritesProject = (pickerId: string) =>
338 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
339 dispatch(receiveTreePickerData({
342 data: [{ uuid: PUBLIC_FAVORITES_PROJECT_ID, name: PUBLIC_FAVORITES_PROJECT_ID }],
343 extractNodeData: value => ({
345 status: TreeNodeStatus.INITIAL,
351 export const SEARCH_PROJECT_ID = 'Search all Projects';
352 export const initSearchProject = (pickerId: string) =>
353 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
354 dispatch(receiveTreePickerData({
357 data: [{ uuid: SEARCH_PROJECT_ID, name: SEARCH_PROJECT_ID }],
358 extractNodeData: value => ({
360 status: TreeNodeStatus.INITIAL,
367 interface LoadFavoritesProjectParams {
369 includeCollections?: boolean;
370 includeDirectories?: boolean;
371 includeFiles?: boolean;
372 options?: { showOnlyOwned: boolean, showOnlyWritable: boolean };
375 export const loadFavoritesProject = (params: LoadFavoritesProjectParams,
376 options: { showOnlyOwned: boolean, showOnlyWritable: boolean } = { showOnlyOwned: true, showOnlyWritable: false }) =>
377 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
378 const { pickerId, includeCollections = false, includeDirectories = false, includeFiles = false } = params;
379 const uuid = getUserUuid(getState());
381 const filters = pipe(
382 (fb: FilterBuilder) => includeCollections
383 ? fb.addIsA('head_uuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
384 : fb.addIsA('head_uuid', [ResourceKind.PROJECT]),
385 fb => fb.getFilters(),
386 )(new FilterBuilder());
388 const { items } = await services.favoriteService.list(uuid, { filters }, options.showOnlyOwned);
390 dispatch<any>(receiveTreePickerData<GroupContentsResource>({
393 data: items.filter((item) => {
394 if (options.showOnlyWritable && (item as GroupResource).writableBy && (item as GroupResource).writableBy.indexOf(uuid) === -1) {
398 if (options.showOnlyWritable && item.hasOwnProperty('frozenByUuid') && (item as ProjectResource).frozenByUuid) {
404 extractNodeData: item => ({
407 status: item.kind === ResourceKind.PROJECT
408 ? TreeNodeStatus.INITIAL
409 : includeDirectories || includeFiles
410 ? TreeNodeStatus.INITIAL
411 : TreeNodeStatus.LOADED
417 export const loadPublicFavoritesProject = (params: LoadFavoritesProjectParams) =>
418 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
419 const { pickerId, includeCollections = false, includeDirectories = false, includeFiles = false } = params;
420 const uuidPrefix = getState().auth.config.uuidPrefix;
421 const publicProjectUuid = `${uuidPrefix}-j7d0g-publicfavorites`;
423 const filters = pipe(
424 (fb: FilterBuilder) => includeCollections
425 ? fb.addIsA('head_uuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
426 : fb.addIsA('head_uuid', [ResourceKind.PROJECT]),
428 .addEqual('link_class', LinkClass.STAR)
429 .addEqual('owner_uuid', publicProjectUuid)
431 )(new FilterBuilder());
433 const { items } = await services.linkService.list({ filters });
435 dispatch<any>(receiveTreePickerData<LinkResource>({
436 id: 'Public Favorites',
438 data: items.filter(item => {
439 if (params.options && params.options.showOnlyWritable && item.hasOwnProperty('frozenByUuid') && (item as any).frozenByUuid) {
445 extractNodeData: item => ({
448 status: item.headKind === ResourceKind.PROJECT
449 ? TreeNodeStatus.INITIAL
450 : includeDirectories || includeFiles
451 ? TreeNodeStatus.INITIAL
452 : TreeNodeStatus.LOADED
457 export const receiveTreePickerProjectsData = (id: string, projects: ProjectResource[], pickerId: string) =>
458 (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
459 dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
461 nodes: projects.map(project => initTreeNode({ id: project.uuid, value: project })),
465 dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
468 export const loadProjectTreePickerProjects = (id: string) =>
469 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
470 dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.PROJECTS }));
473 const ownerUuid = id.length === 0 ? getUserUuid(getState()) || '' : id;
474 const { items } = await services.projectService.list(buildParams(ownerUuid));
476 dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.PROJECTS));
479 export const loadFavoriteTreePickerProjects = (id: string) =>
480 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
481 const parentId = getUserUuid(getState()) || '';
484 dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: parentId, pickerId: TreePickerId.FAVORITES }));
485 const { items } = await services.favoriteService.list(parentId);
486 dispatch<any>(receiveTreePickerProjectsData(parentId, items as ProjectResource[], TreePickerId.FAVORITES));
488 dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.FAVORITES }));
489 const { items } = await services.projectService.list(buildParams(id));
490 dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.FAVORITES));
495 export const loadPublicFavoriteTreePickerProjects = (id: string) =>
496 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
497 const parentId = getUserUuid(getState()) || '';
500 dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: parentId, pickerId: TreePickerId.PUBLIC_FAVORITES }));
501 const { items } = await services.favoriteService.list(parentId);
502 dispatch<any>(receiveTreePickerProjectsData(parentId, items as ProjectResource[], TreePickerId.PUBLIC_FAVORITES));
504 dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.PUBLIC_FAVORITES }));
505 const { items } = await services.projectService.list(buildParams(id));
506 dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.PUBLIC_FAVORITES));
511 const buildParams = (ownerUuid: string) => {
513 filters: new FilterBuilder()
514 .addEqual('owner_uuid', ownerUuid)
516 order: new OrderBuilder<ProjectResource>()
523 * Given a tree picker item, return collection uuid and path
524 * if the item represents a valid target/destination location
526 export type FileOperationLocation = {
530 export const getFileOperationLocation = (item: ProjectsTreePickerItem): FileOperationLocation | undefined => {
531 if ('kind' in item && item.kind === ResourceKind.COLLECTION) {
536 } else if ('type' in item && item.type === CollectionFileType.DIRECTORY) {
537 const uuid = getCollectionResourceCollectionUuid(item.id);
541 path: [item.path, item.name].join('/')
552 * Create an expanded tree picker subtree from array of nested projects/collection
553 * Assumes the root item of the subtree already has an empty string ownerUuid
555 export const createInitialLocationTree = (data: Array<GroupResource | CollectionResource>, tailUuid: string) => {
557 .reduce((tree, item) => setNode({
560 parent: item.ownerUuid,
564 expanded: item.uuid !== tailUuid,
565 status: item.uuid !== tailUuid ? TreeNodeStatus.LOADED : TreeNodeStatus.INITIAL,
566 })(tree), createTree<GroupResource | CollectionResource>());