fixed-removing-selected-files
[arvados.git] / src / store / sharing-dialog / sharing-dialog-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { dialogActions } from "~/store/dialog/dialog-actions";
6 import { withDialog } from "~/store/dialog/with-dialog";
7 import { SHARING_DIALOG_NAME, SharingPublicAccessFormData, SHARING_PUBLIC_ACCESS_FORM_NAME, SHARING_INVITATION_FORM_NAME, SharingManagementFormData, SharingInvitationFormData, VisibilityLevel, getSharingMangementFormData, getSharingPublicAccessFormData } from './sharing-dialog-types';
8 import { Dispatch } from 'redux';
9 import { ServiceRepository } from "~/services/services";
10 import { FilterBuilder } from '~/services/api/filter-builder';
11 import { initialize, getFormValues, reset } from 'redux-form';
12 import { SHARING_MANAGEMENT_FORM_NAME } from '~/store/sharing-dialog/sharing-dialog-types';
13 import { RootState } from '~/store/store';
14 import { getDialog } from '~/store/dialog/dialog-reducer';
15 import { PermissionLevel } from '~/models/permission';
16 import { getPublicGroupUuid } from "~/store/workflow-panel/workflow-panel-actions";
17 import { PermissionResource } from '~/models/permission';
18 import { differenceWith } from "lodash";
19 import { withProgress } from "~/store/progress-indicator/with-progress";
20 import { progressIndicatorActions } from '~/store/progress-indicator/progress-indicator-actions.ts';
21 import { snackbarActions, SnackbarKind } from "../snackbar/snackbar-actions";
22 import { extractUuidKind, ResourceKind } from "~/models/resource";
23 import { LinkClass } from "~/models/link";
24
25 export const openSharingDialog = (resourceUuid: string) =>
26     (dispatch: Dispatch) => {
27         dispatch(dialogActions.OPEN_DIALOG({ id: SHARING_DIALOG_NAME, data: resourceUuid }));
28         dispatch<any>(loadSharingDialog);
29     };
30
31 export const closeSharingDialog = () =>
32     dialogActions.CLOSE_DIALOG({ id: SHARING_DIALOG_NAME });
33
34 export const connectSharingDialog = withDialog(SHARING_DIALOG_NAME);
35 export const connectSharingDialogProgress = withProgress(SHARING_DIALOG_NAME);
36
37
38 export const saveSharingDialogChanges = async (dispatch: Dispatch) => {
39     dispatch(progressIndicatorActions.START_WORKING(SHARING_DIALOG_NAME));
40     await dispatch<any>(savePublicPermissionChanges);
41     await dispatch<any>(saveManagementChanges);
42     await dispatch<any>(sendInvitations);
43     dispatch(reset(SHARING_INVITATION_FORM_NAME));
44     await dispatch<any>(loadSharingDialog);
45 };
46
47 export const sendSharingInvitations = async (dispatch: Dispatch) => {
48     dispatch(progressIndicatorActions.START_WORKING(SHARING_DIALOG_NAME));
49     await dispatch<any>(sendInvitations);
50     dispatch(closeSharingDialog());
51     dispatch(snackbarActions.OPEN_SNACKBAR({
52         message: 'Resource has been shared',
53         kind: SnackbarKind.SUCCESS,
54     }));
55     dispatch(progressIndicatorActions.STOP_WORKING(SHARING_DIALOG_NAME));
56 };
57
58 const loadSharingDialog = async (dispatch: Dispatch, getState: () => RootState, { permissionService }: ServiceRepository) => {
59
60     const dialog = getDialog<string>(getState().dialog, SHARING_DIALOG_NAME);
61     if (dialog) {
62         dispatch(progressIndicatorActions.START_WORKING(SHARING_DIALOG_NAME));
63         try {
64             const { items } = await permissionService.listResourcePermissions(dialog.data);
65             dispatch<any>(initializePublicAccessForm(items));
66             await dispatch<any>(initializeManagementForm(items));
67             dispatch(progressIndicatorActions.STOP_WORKING(SHARING_DIALOG_NAME));
68         } catch (e) {
69             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'You do not have access to share this item', hideDuration: 2000, kind: SnackbarKind.ERROR }));
70             dispatch(dialogActions.CLOSE_DIALOG({ id: SHARING_DIALOG_NAME }));
71             dispatch(progressIndicatorActions.STOP_WORKING(SHARING_DIALOG_NAME));
72         }
73     }
74 };
75
76 const initializeManagementForm = (permissionLinks: PermissionResource[]) =>
77     async (dispatch: Dispatch, getState: () => RootState, { userService }: ServiceRepository) => {
78
79         const filters = new FilterBuilder()
80             .addIn('uuid', permissionLinks.map(({ tailUuid }) => tailUuid))
81             .getFilters();
82
83         const { items: users } = await userService.list({ filters });
84
85         const getEmail = (tailUuid: string) => {
86             const user = users.find(({ uuid }) => uuid === tailUuid);
87             return user
88                 ? user.email
89                 : tailUuid;
90         };
91
92         const managementPermissions = permissionLinks
93             .filter(item =>
94                 item.tailUuid !== getPublicGroupUuid(getState()))
95             .map(({ tailUuid, name, uuid }) => ({
96                 email: getEmail(tailUuid),
97                 permissions: name as PermissionLevel,
98                 permissionUuid: uuid,
99             }));
100
101         const managementFormData: SharingManagementFormData = {
102             permissions: managementPermissions,
103             initialPermissions: managementPermissions,
104         };
105
106         dispatch(initialize(SHARING_MANAGEMENT_FORM_NAME, managementFormData));
107     };
108
109 const initializePublicAccessForm = (permissionLinks: PermissionResource[]) =>
110     (dispatch: Dispatch, getState: () => RootState, ) => {
111
112         const [publicPermission] = permissionLinks
113             .filter(item => item.tailUuid === getPublicGroupUuid(getState()));
114
115         const publicAccessFormData: SharingPublicAccessFormData = publicPermission
116             ? {
117                 visibility: VisibilityLevel.PUBLIC,
118                 permissionUuid: publicPermission.uuid,
119             }
120             : {
121                 visibility: permissionLinks.length > 0
122                     ? VisibilityLevel.SHARED
123                     : VisibilityLevel.PRIVATE,
124                 permissionUuid: '',
125             };
126
127         dispatch(initialize(SHARING_PUBLIC_ACCESS_FORM_NAME, publicAccessFormData));
128     };
129
130 const savePublicPermissionChanges = async (_: Dispatch, getState: () => RootState, { permissionService }: ServiceRepository) => {
131     const state = getState();
132     const { user } = state.auth;
133     const dialog = getDialog<string>(state.dialog, SHARING_DIALOG_NAME);
134     if (dialog && user) {
135         const { permissionUuid, visibility } = getSharingPublicAccessFormData(state);
136
137         if (permissionUuid) {
138             if (visibility === VisibilityLevel.PUBLIC) {
139                 await permissionService.update(permissionUuid, {
140                     name: PermissionLevel.CAN_READ
141                 });
142             } else {
143                 await permissionService.delete(permissionUuid);
144             }
145
146         } else if (visibility === VisibilityLevel.PUBLIC) {
147
148             await permissionService.create({
149                 ownerUuid: user.uuid,
150                 headUuid: dialog.data,
151                 tailUuid: getPublicGroupUuid(state),
152                 name: PermissionLevel.CAN_READ,
153             });
154         }
155     }
156 };
157
158 const saveManagementChanges = async (_: Dispatch, getState: () => RootState, { permissionService }: ServiceRepository) => {
159     const state = getState();
160     const { user } = state.auth;
161     const dialog = getDialog<string>(state.dialog, SHARING_DIALOG_NAME);
162     if (dialog && user) {
163
164         const { initialPermissions, permissions } = getSharingMangementFormData(state);
165         const { visibility } = getSharingPublicAccessFormData(state);
166
167
168         if (visibility === VisibilityLevel.PRIVATE) {
169
170             for (const permission of initialPermissions) {
171                 await permissionService.delete(permission.permissionUuid);
172             }
173
174         } else {
175
176             const cancelledPermissions = differenceWith(
177                 initialPermissions,
178                 permissions,
179                 (a, b) => a.permissionUuid === b.permissionUuid
180             );
181
182             for (const { permissionUuid } of cancelledPermissions) {
183                 await permissionService.delete(permissionUuid);
184             }
185
186             for (const permission of permissions) {
187                 await permissionService.update(permission.permissionUuid, { name: permission.permissions });
188             }
189
190         }
191     }
192 };
193
194 const sendInvitations = async (_: Dispatch, getState: () => RootState, { permissionService, userService }: ServiceRepository) => {
195     const state = getState();
196     const { user } = state.auth;
197     const dialog = getDialog<string>(state.dialog, SHARING_DIALOG_NAME);
198     if (dialog && user) {
199         const invitations = getFormValues(SHARING_INVITATION_FORM_NAME)(state) as SharingInvitationFormData;
200
201         const getGroupsFromForm = invitations.invitedPeople.filter((invitation) => extractUuidKind(invitation.uuid) === ResourceKind.GROUP);
202         const getUsersFromForm = invitations.invitedPeople.filter((invitation) => extractUuidKind(invitation.uuid) === ResourceKind.USER);
203         const uuids = getGroupsFromForm.map(group => group.uuid);
204
205         const permissions = await permissionService.list({
206             filters: new FilterBuilder()
207                 .addIn('tailUuid', uuids)
208                 .addEqual('linkClass', LinkClass.PERMISSION)
209                 .getFilters()
210         });
211
212         const usersFromGroups = await userService.list({
213             filters: new FilterBuilder()
214                 .addIn('uuid', permissions.items.map(item => item.headUuid))
215                 .getFilters()
216
217         });
218
219         const invitationDataUsers = getUsersFromForm
220             .map(person => ({
221                 ownerUuid: user.uuid,
222                 headUuid: dialog.data,
223                 tailUuid: person.uuid,
224                 name: invitations.permissions
225             }));
226
227         const invitationsDataGroups = usersFromGroups.items.map(
228             person => ({
229                 ownerUuid: user.uuid,
230                 headUuid: dialog.data,
231                 tailUuid: person.uuid,
232                 name: invitations.permissions
233             })
234         );
235
236         const data = invitationDataUsers.concat(invitationsDataGroups);
237
238         for (const invitation of data) {
239             await permissionService.create(invitation);
240         }
241     }
242 };