Add login in/out handling, fix async validation
[arvados-workbench2.git] / src / store / workbench / workbench-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Dispatch } from 'redux';
6 import { RootState } from "~/store/store";
7 import { loadDetailsPanel } from '~/store/details-panel/details-panel-action';
8 import { snackbarActions } from '~/store/snackbar/snackbar-actions';
9 import { loadFavoritePanel } from '~/store/favorite-panel/favorite-panel-action';
10 import { openProjectPanel, projectPanelActions, setIsProjectPanelTrashed } from '~/store/project-panel/project-panel-action';
11 import { activateSidePanelTreeItem, initSidePanelTree, SidePanelTreeCategory, loadSidePanelTreeProjects } from '~/store/side-panel-tree/side-panel-tree-actions';
12 import { loadResource, updateResources } from '~/store/resources/resources-actions';
13 import { favoritePanelActions } from '~/store/favorite-panel/favorite-panel-action';
14 import { projectPanelColumns } from '~/views/project-panel/project-panel';
15 import { favoritePanelColumns } from '~/views/favorite-panel/favorite-panel';
16 import { matchRootRoute } from '~/routes/routes';
17 import { setSidePanelBreadcrumbs, setProcessBreadcrumbs, setSharedWithMeBreadcrumbs, setTrashBreadcrumbs, setBreadcrumbs } from '~/store/breadcrumbs/breadcrumbs-actions';
18 import { navigateToProject } from '~/store/navigation/navigation-action';
19 import { MoveToFormDialogData } from '~/store/move-to-dialog/move-to-dialog';
20 import { ServiceRepository } from '~/services/services';
21 import { getResource } from '~/store/resources/resources';
22 import { getProjectPanelCurrentUuid } from '~/store/project-panel/project-panel-action';
23 import * as projectCreateActions from '~/store/projects/project-create-actions';
24 import * as projectMoveActions from '~/store/projects/project-move-actions';
25 import * as projectUpdateActions from '~/store/projects/project-update-actions';
26 import * as collectionCreateActions from '~/store/collections/collection-create-actions';
27 import * as collectionCopyActions from '~/store/collections/collection-copy-actions';
28 import * as collectionUpdateActions from '~/store/collections/collection-update-actions';
29 import * as collectionMoveActions from '~/store/collections/collection-move-actions';
30 import * as processesActions from '~/store/processes/processes-actions';
31 import * as processMoveActions from '~/store/processes/process-move-actions';
32 import * as processUpdateActions from '~/store/processes/process-update-actions';
33 import * as processCopyActions from '~/store/processes/process-copy-actions';
34 import { trashPanelColumns } from "~/views/trash-panel/trash-panel";
35 import { loadTrashPanel, trashPanelActions } from "~/store/trash-panel/trash-panel-action";
36 import { initProcessLogsPanel } from '~/store/process-logs-panel/process-logs-panel-actions';
37 import { loadProcessPanel } from '~/store/process-panel/process-panel-actions';
38 import { sharedWithMePanelActions } from '~/store/shared-with-me-panel/shared-with-me-panel-actions';
39 import { loadSharedWithMePanel } from '~/store/shared-with-me-panel/shared-with-me-panel-actions';
40 import { CopyFormDialogData } from '~/store/copy-dialog/copy-dialog';
41 import { loadWorkflowPanel, workflowPanelActions } from '~/store/workflow-panel/workflow-panel-actions';
42 import { loadSshKeysPanel } from '~/store/auth/auth-action-ssh';
43 import { loadSiteManagerPanel } from '~/store/auth/auth-action-session';
44 import { workflowPanelColumns } from '~/views/workflow-panel/workflow-panel-view';
45 import { progressIndicatorActions } from '~/store/progress-indicator/progress-indicator-actions';
46 import { getProgressIndicator } from '~/store/progress-indicator/progress-indicator-reducer';
47 import { ResourceKind, extractUuidKind } from '~/models/resource';
48 import { FilterBuilder } from '~/services/api/filter-builder';
49 import { GroupContentsResource } from '~/services/groups-service/groups-service';
50 import { unionize, ofType, UnionOf, MatchCases } from '~/common/unionize';
51 import { loadRunProcessPanel } from '~/store/run-process-panel/run-process-panel-actions';
52 import { loadCollectionFiles } from '~/store/collection-panel/collection-panel-files/collection-panel-files-actions';
53 import { SnackbarKind } from '~/store/snackbar/snackbar-actions';
54 import { collectionPanelActions } from "~/store/collection-panel/collection-panel-action";
55 import { CollectionResource } from "~/models/collection";
56 import { searchResultsPanelActions, loadSearchResultsPanel } from '~/store/search-results-panel/search-results-panel-actions';
57 import { searchResultsPanelColumns } from '~/views/search-results-panel/search-results-panel-view';
58 import { loadVirtualMachinesPanel } from '~/store/virtual-machines/virtual-machines-actions';
59 import { loadRepositoriesPanel } from '~/store/repositories/repositories-actions';
60 import { loadKeepServicesPanel } from '~/store/keep-services/keep-services-actions';
61 import { loadComputeNodesPanel } from '~/store/compute-nodes/compute-nodes-actions';
62
63 export const WORKBENCH_LOADING_SCREEN = 'workbenchLoadingScreen';
64
65 export const isWorkbenchLoading = (state: RootState) => {
66     const progress = getProgressIndicator(WORKBENCH_LOADING_SCREEN)(state.progressIndicator);
67     return progress ? progress.working : false;
68 };
69
70 const handleFirstTimeLoad = (action: any) =>
71     async (dispatch: Dispatch<any>, getState: () => RootState) => {
72         try {
73             await dispatch(action);
74         } finally {
75             if (isWorkbenchLoading(getState())) {
76                 dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
77             }
78         }
79     };
80
81
82 export const loadWorkbench = () =>
83     async (dispatch: Dispatch, getState: () => RootState) => {
84         dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
85         const { auth, router } = getState();
86         const { user } = auth;
87         if (user) {
88             const userResource = await dispatch<any>(loadResource(user.uuid));
89             if (userResource) {
90                 dispatch(projectPanelActions.SET_COLUMNS({ columns: projectPanelColumns }));
91                 dispatch(favoritePanelActions.SET_COLUMNS({ columns: favoritePanelColumns }));
92                 dispatch(trashPanelActions.SET_COLUMNS({ columns: trashPanelColumns }));
93                 dispatch(sharedWithMePanelActions.SET_COLUMNS({ columns: projectPanelColumns }));
94                 dispatch(workflowPanelActions.SET_COLUMNS({ columns: workflowPanelColumns }));
95                 dispatch(searchResultsPanelActions.SET_COLUMNS({ columns: searchResultsPanelColumns }));
96                 dispatch<any>(initSidePanelTree());
97                 if (router.location) {
98                     const match = matchRootRoute(router.location.pathname);
99                     if (match) {
100                         dispatch(navigateToProject(userResource.uuid));
101                     }
102                 }
103             } else {
104                 dispatch(userIsNotAuthenticated);
105             }
106         } else {
107             dispatch(userIsNotAuthenticated);
108         }
109     };
110
111 export const loadFavorites = () =>
112     handleFirstTimeLoad(
113         (dispatch: Dispatch) => {
114             dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.FAVORITES));
115             dispatch<any>(loadFavoritePanel());
116             dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.FAVORITES));
117         });
118
119 export const loadTrash = () =>
120     handleFirstTimeLoad(
121         (dispatch: Dispatch) => {
122             dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.TRASH));
123             dispatch<any>(loadTrashPanel());
124             dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.TRASH));
125         });
126
127 export const loadProject = (uuid: string) =>
128     handleFirstTimeLoad(
129         async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
130             const userUuid = services.authService.getUuid();
131             dispatch(setIsProjectPanelTrashed(false));
132             if (userUuid) {
133                 if (userUuid !== uuid) {
134                     const match = await loadGroupContentsResource({ uuid, userUuid, services });
135                     match({
136                         OWNED: async project => {
137                             await dispatch(activateSidePanelTreeItem(uuid));
138                             dispatch<any>(setSidePanelBreadcrumbs(uuid));
139                             dispatch(finishLoadingProject(project));
140                         },
141                         SHARED: project => {
142                             dispatch<any>(setSharedWithMeBreadcrumbs(uuid));
143                             dispatch(activateSidePanelTreeItem(uuid));
144                             dispatch(finishLoadingProject(project));
145                         },
146                         TRASHED: project => {
147                             dispatch<any>(setTrashBreadcrumbs(uuid));
148                             dispatch(setIsProjectPanelTrashed(true));
149                             dispatch(activateSidePanelTreeItem(SidePanelTreeCategory.TRASH));
150                             dispatch(finishLoadingProject(project));
151                         }
152                     });
153                 } else {
154                     await dispatch(activateSidePanelTreeItem(userUuid));
155                     dispatch<any>(setSidePanelBreadcrumbs(userUuid));
156                     dispatch(finishLoadingProject(userUuid));
157                 }
158             }
159         });
160
161 export const createProject = (data: projectCreateActions.ProjectCreateFormDialogData) =>
162     async (dispatch: Dispatch) => {
163         const newProject = await dispatch<any>(projectCreateActions.createProject(data));
164         if (newProject) {
165             dispatch(snackbarActions.OPEN_SNACKBAR({
166                 message: "Project has been successfully created.",
167                 hideDuration: 2000
168             }));
169             await dispatch<any>(loadSidePanelTreeProjects(newProject.ownerUuid));
170             dispatch<any>(reloadProjectMatchingUuid([newProject.ownerUuid]));
171         }
172     };
173
174 export const moveProject = (data: MoveToFormDialogData) =>
175     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
176         try {
177             const oldProject = getResource(data.uuid)(getState().resources);
178             const oldOwnerUuid = oldProject ? oldProject.ownerUuid : '';
179             const movedProject = await dispatch<any>(projectMoveActions.moveProject(data));
180             if (movedProject) {
181                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Project has been moved', hideDuration: 2000 }));
182                 if (oldProject) {
183                     await dispatch<any>(loadSidePanelTreeProjects(oldProject.ownerUuid));
184                 }
185                 dispatch<any>(reloadProjectMatchingUuid([oldOwnerUuid, movedProject.ownerUuid, movedProject.uuid]));
186             }
187         } catch (e) {
188             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
189         }
190     };
191
192 export const updateProject = (data: projectUpdateActions.ProjectUpdateFormDialogData) =>
193     async (dispatch: Dispatch) => {
194         const updatedProject = await dispatch<any>(projectUpdateActions.updateProject(data));
195         if (updatedProject) {
196             dispatch(snackbarActions.OPEN_SNACKBAR({
197                 message: "Project has been successfully updated.",
198                 hideDuration: 2000
199             }));
200             await dispatch<any>(loadSidePanelTreeProjects(updatedProject.ownerUuid));
201             dispatch<any>(reloadProjectMatchingUuid([updatedProject.ownerUuid, updatedProject.uuid]));
202         }
203     };
204
205 export const loadCollection = (uuid: string) =>
206     handleFirstTimeLoad(
207         async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
208             const userUuid = services.authService.getUuid();
209             if (userUuid) {
210                 const match = await loadGroupContentsResource({ uuid, userUuid, services });
211                 match({
212                     OWNED: async collection => {
213                         dispatch(collectionPanelActions.SET_COLLECTION(collection as CollectionResource));
214                         dispatch(updateResources([collection]));
215                         await dispatch(activateSidePanelTreeItem(collection.ownerUuid));
216                         dispatch(setSidePanelBreadcrumbs(collection.ownerUuid));
217                         dispatch(loadCollectionFiles(collection.uuid));
218                     },
219                     SHARED: collection => {
220                         dispatch(collectionPanelActions.SET_COLLECTION(collection as CollectionResource));
221                         dispatch(updateResources([collection]));
222                         dispatch<any>(setSharedWithMeBreadcrumbs(collection.ownerUuid));
223                         dispatch(activateSidePanelTreeItem(collection.ownerUuid));
224                         dispatch(loadCollectionFiles(collection.uuid));
225                     },
226                     TRASHED: collection => {
227                         dispatch(collectionPanelActions.SET_COLLECTION(collection as CollectionResource));
228                         dispatch(updateResources([collection]));
229                         dispatch(setTrashBreadcrumbs(''));
230                         dispatch(activateSidePanelTreeItem(SidePanelTreeCategory.TRASH));
231                         dispatch(loadCollectionFiles(collection.uuid));
232                     },
233
234                 });
235             }
236         });
237
238 export const createCollection = (data: collectionCreateActions.CollectionCreateFormDialogData) =>
239     async (dispatch: Dispatch) => {
240         const collection = await dispatch<any>(collectionCreateActions.createCollection(data));
241         if (collection) {
242             dispatch(snackbarActions.OPEN_SNACKBAR({
243                 message: "Collection has been successfully created.",
244                 hideDuration: 2000
245             }));
246             dispatch<any>(updateResources([collection]));
247             dispatch<any>(reloadProjectMatchingUuid([collection.ownerUuid]));
248         }
249     };
250
251 export const updateCollection = (data: collectionUpdateActions.CollectionUpdateFormDialogData) =>
252     async (dispatch: Dispatch) => {
253         const collection = await dispatch<any>(collectionUpdateActions.updateCollection(data));
254         if (collection) {
255             dispatch(snackbarActions.OPEN_SNACKBAR({
256                 message: "Collection has been successfully updated.",
257                 hideDuration: 2000
258             }));
259             dispatch<any>(updateResources([collection]));
260             dispatch<any>(reloadProjectMatchingUuid([collection.ownerUuid]));
261         }
262     };
263
264 export const copyCollection = (data: CopyFormDialogData) =>
265     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
266         try {
267             const copyToProject = getResource(data.ownerUuid)(getState().resources);
268             const collection = await dispatch<any>(collectionCopyActions.copyCollection(data));
269             if (copyToProject && collection) {
270                 dispatch<any>(reloadProjectMatchingUuid([copyToProject.uuid]));
271                 dispatch(snackbarActions.OPEN_SNACKBAR({
272                     message: 'Collection has been copied.',
273                     hideDuration: 3000,
274                     kind: SnackbarKind.SUCCESS,
275                     link: collection.ownerUuid
276                 }));
277             }
278         } catch (e) {
279             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000, kind: SnackbarKind.ERROR }));
280         }
281     };
282
283 export const moveCollection = (data: MoveToFormDialogData) =>
284     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
285         try {
286             const collection = await dispatch<any>(collectionMoveActions.moveCollection(data));
287             dispatch<any>(updateResources([collection]));
288             dispatch<any>(reloadProjectMatchingUuid([collection.ownerUuid]));
289             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Collection has been moved.', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
290         } catch (e) {
291             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
292         }
293     };
294
295 export const loadProcess = (uuid: string) =>
296     handleFirstTimeLoad(
297         async (dispatch: Dispatch, getState: () => RootState) => {
298             dispatch<any>(loadProcessPanel(uuid));
299             const process = await dispatch<any>(processesActions.loadProcess(uuid));
300             await dispatch<any>(activateSidePanelTreeItem(process.containerRequest.ownerUuid));
301             dispatch<any>(setProcessBreadcrumbs(uuid));
302             dispatch(loadDetailsPanel(uuid));
303         });
304
305 export const updateProcess = (data: processUpdateActions.ProcessUpdateFormDialogData) =>
306     async (dispatch: Dispatch) => {
307         try {
308             const process = await dispatch<any>(processUpdateActions.updateProcess(data));
309             if (process) {
310                 dispatch(snackbarActions.OPEN_SNACKBAR({
311                     message: "Process has been successfully updated.",
312                     hideDuration: 2000
313                 }));
314                 dispatch<any>(updateResources([process]));
315                 dispatch<any>(reloadProjectMatchingUuid([process.ownerUuid]));
316             }
317         } catch (e) {
318             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
319         }
320     };
321
322 export const moveProcess = (data: MoveToFormDialogData) =>
323     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
324         try {
325             const process = await dispatch<any>(processMoveActions.moveProcess(data));
326             dispatch<any>(updateResources([process]));
327             dispatch<any>(reloadProjectMatchingUuid([process.ownerUuid]));
328             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Process has been moved.', hideDuration: 2000 }));
329         } catch (e) {
330             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
331         }
332     };
333
334 export const copyProcess = (data: CopyFormDialogData) =>
335     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
336         try {
337             const process = await dispatch<any>(processCopyActions.copyProcess(data));
338             dispatch<any>(updateResources([process]));
339             dispatch<any>(reloadProjectMatchingUuid([process.ownerUuid]));
340             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Process has been copied.', hideDuration: 2000 }));
341         } catch (e) {
342             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
343         }
344     };
345
346 export const loadProcessLog = (uuid: string) =>
347     handleFirstTimeLoad(
348         async (dispatch: Dispatch) => {
349             const process = await dispatch<any>(processesActions.loadProcess(uuid));
350             dispatch<any>(setProcessBreadcrumbs(uuid));
351             dispatch<any>(initProcessLogsPanel(uuid));
352             await dispatch<any>(activateSidePanelTreeItem(process.containerRequest.ownerUuid));
353         });
354
355 export const resourceIsNotLoaded = (uuid: string) =>
356     snackbarActions.OPEN_SNACKBAR({
357         message: `Resource identified by ${uuid} is not loaded.`
358     });
359
360 export const userIsNotAuthenticated = snackbarActions.OPEN_SNACKBAR({
361     message: 'User is not authenticated'
362 });
363
364 export const couldNotLoadUser = snackbarActions.OPEN_SNACKBAR({
365     message: 'Could not load user'
366 });
367
368 export const reloadProjectMatchingUuid = (matchingUuids: string[]) =>
369     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
370         const currentProjectPanelUuid = getProjectPanelCurrentUuid(getState());
371         if (currentProjectPanelUuid && matchingUuids.some(uuid => uuid === currentProjectPanelUuid)) {
372             dispatch<any>(loadProject(currentProjectPanelUuid));
373         }
374     };
375
376 export const loadSharedWithMe = handleFirstTimeLoad(async (dispatch: Dispatch) => {
377     dispatch<any>(loadSharedWithMePanel());
378     await dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.SHARED_WITH_ME));
379     await dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.SHARED_WITH_ME));
380 });
381
382 export const loadRunProcess = handleFirstTimeLoad(
383     async (dispatch: Dispatch) => {
384         await dispatch<any>(loadRunProcessPanel());
385     }
386 );
387
388 export const loadWorkflow = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
389     dispatch(activateSidePanelTreeItem(SidePanelTreeCategory.WORKFLOWS));
390     await dispatch(loadWorkflowPanel());
391     dispatch(setSidePanelBreadcrumbs(SidePanelTreeCategory.WORKFLOWS));
392 });
393
394 export const loadSearchResults = handleFirstTimeLoad(
395     async (dispatch: Dispatch<any>) => {
396         await dispatch(loadSearchResultsPanel());
397     });
398
399 export const loadVirtualMachines = handleFirstTimeLoad(
400     async (dispatch: Dispatch<any>) => {
401         await dispatch(loadVirtualMachinesPanel());
402         dispatch(setBreadcrumbs([{ label: 'Virtual Machines' }]));
403     });
404
405 export const loadRepositories = handleFirstTimeLoad(
406     async (dispatch: Dispatch<any>) => {
407         await dispatch(loadRepositoriesPanel());
408         dispatch(setBreadcrumbs([{ label: 'Repositories' }]));
409     });
410
411 export const loadSshKeys = handleFirstTimeLoad(
412     async (dispatch: Dispatch<any>) => {
413         await dispatch(loadSshKeysPanel());
414     });
415
416 export const loadSiteManager = handleFirstTimeLoad(
417     async (dispatch: Dispatch<any>) => {
418         await dispatch(loadSiteManagerPanel());
419     });
420
421 export const loadKeepServices = handleFirstTimeLoad(
422     async (dispatch: Dispatch<any>) => {
423         await dispatch(loadKeepServicesPanel());
424     });
425
426 export const loadComputeNodes = handleFirstTimeLoad(
427     async (dispatch: Dispatch<any>) => {
428         await dispatch(loadComputeNodesPanel());
429     });
430
431 const finishLoadingProject = (project: GroupContentsResource | string) =>
432     async (dispatch: Dispatch<any>) => {
433         const uuid = typeof project === 'string' ? project : project.uuid;
434         dispatch(openProjectPanel(uuid));
435         dispatch(loadDetailsPanel(uuid));
436         if (typeof project !== 'string') {
437             dispatch(updateResources([project]));
438         }
439     };
440
441 const loadGroupContentsResource = async (params: {
442     uuid: string,
443     userUuid: string,
444     services: ServiceRepository
445 }) => {
446     const filters = new FilterBuilder()
447         .addEqual('uuid', params.uuid)
448         .getFilters();
449     const { items } = await params.services.groupsService.contents(params.userUuid, {
450         filters,
451         recursive: true,
452         includeTrash: true,
453     });
454     const resource = items.shift();
455     let handler: GroupContentsHandler;
456     if (resource) {
457         handler = (resource.kind === ResourceKind.COLLECTION || resource.kind === ResourceKind.PROJECT) && resource.isTrashed
458             ? groupContentsHandlers.TRASHED(resource)
459             : groupContentsHandlers.OWNED(resource);
460     } else {
461         const kind = extractUuidKind(params.uuid);
462         let resource: GroupContentsResource;
463         if (kind === ResourceKind.COLLECTION) {
464             resource = await params.services.collectionService.get(params.uuid);
465         } else if (kind === ResourceKind.PROJECT) {
466             resource = await params.services.projectService.get(params.uuid);
467         } else {
468             resource = await params.services.containerRequestService.get(params.uuid);
469         }
470         handler = groupContentsHandlers.SHARED(resource);
471     }
472     return (cases: MatchCases<typeof groupContentsHandlersRecord, GroupContentsHandler, void>) =>
473         groupContentsHandlers.match(handler, cases);
474
475 };
476
477 const groupContentsHandlersRecord = {
478     TRASHED: ofType<GroupContentsResource>(),
479     SHARED: ofType<GroupContentsResource>(),
480     OWNED: ofType<GroupContentsResource>(),
481 };
482
483 const groupContentsHandlers = unionize(groupContentsHandlersRecord);
484
485 type GroupContentsHandler = UnionOf<typeof groupContentsHandlers>;