Merge branch '21128-toolbar-context-menu'
[arvados-workbench2.git] / src / store / search-bar / search-bar-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import axios from "axios";
6 import { ofType, unionize, UnionOf } from "common/unionize";
7 import { GroupContentsResource, GroupContentsResourcePrefix } from 'services/groups-service/groups-service';
8 import { Dispatch } from 'redux';
9 import { change, initialize, untouch } from 'redux-form';
10 import { RootState } from 'store/store';
11 import { initUserProject, treePickerActions } from 'store/tree-picker/tree-picker-actions';
12 import { ServiceRepository } from 'services/services';
13 import { FilterBuilder } from "services/api/filter-builder";
14 import { ResourceKind, RESOURCE_UUID_REGEX, COLLECTION_PDH_REGEX } from 'models/resource';
15 import { SearchView } from 'store/search-bar/search-bar-reducer';
16 import { navigateTo, navigateToSearchResults } from 'store/navigation/navigation-action';
17 import { snackbarActions, SnackbarKind } from 'store/snackbar/snackbar-actions';
18 import { PropertyValue, SearchBarAdvancedFormData } from 'models/search-bar';
19 import { union } from "lodash";
20 import { getModifiedKeysValues } from "common/objects";
21 import { activateSearchBarProject } from "store/search-bar/search-bar-tree-actions";
22 import { Session } from "models/session";
23 import { searchResultsPanelActions } from "store/search-results-panel/search-results-panel-actions";
24 import { ListResults } from "services/common-service/common-service";
25 import * as parser from './search-query/arv-parser';
26 import { Keywords } from './search-query/arv-parser';
27 import { Vocabulary, getTagKeyLabel, getTagValueLabel } from "models/vocabulary";
28
29 export const searchBarActions = unionize({
30     SET_CURRENT_VIEW: ofType<string>(),
31     OPEN_SEARCH_VIEW: ofType<{}>(),
32     CLOSE_SEARCH_VIEW: ofType<{}>(),
33     SET_SEARCH_RESULTS: ofType<GroupContentsResource[]>(),
34     SET_SEARCH_VALUE: ofType<string>(),
35     SET_SAVED_QUERIES: ofType<SearchBarAdvancedFormData[]>(),
36     SET_RECENT_QUERIES: ofType<string[]>(),
37     UPDATE_SAVED_QUERY: ofType<SearchBarAdvancedFormData[]>(),
38     SET_SELECTED_ITEM: ofType<string>(),
39     MOVE_UP: ofType<{}>(),
40     MOVE_DOWN: ofType<{}>(),
41     SELECT_FIRST_ITEM: ofType<{}>()
42 });
43
44 export type SearchBarActions = UnionOf<typeof searchBarActions>;
45
46 export const SEARCH_BAR_ADVANCED_FORM_NAME = 'searchBarAdvancedFormName';
47
48 export const SEARCH_BAR_ADVANCED_FORM_PICKER_ID = 'searchBarAdvancedFormPickerId';
49
50 export const DEFAULT_SEARCH_DEBOUNCE = 1000;
51
52 export const goToView = (currentView: string) => searchBarActions.SET_CURRENT_VIEW(currentView);
53
54 export const saveRecentQuery = (query: string) =>
55     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) =>
56         services.searchService.saveRecentQuery(query);
57
58
59 export const loadRecentQueries = () =>
60     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
61         const recentQueries = services.searchService.getRecentQueries();
62         dispatch(searchBarActions.SET_RECENT_QUERIES(recentQueries));
63         return recentQueries;
64     };
65
66 export const searchData = (searchValue: string, useCancel = false) =>
67     async (dispatch: Dispatch, getState: () => RootState) => {
68         const currentView = getState().searchBar.currentView;
69         dispatch(searchResultsPanelActions.CLEAR());
70         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
71         if (searchValue.length > 0) {
72             dispatch<any>(searchGroups(searchValue, 5, useCancel));
73             if (currentView === SearchView.BASIC) {
74                 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
75                 dispatch(navigateToSearchResults(searchValue));
76             }
77         }
78     };
79
80 export const searchAdvancedData = (data: SearchBarAdvancedFormData) =>
81     async (dispatch: Dispatch, getState: () => RootState) => {
82         dispatch<any>(saveQuery(data));
83         const searchValue = getState().searchBar.searchValue;
84         dispatch(searchResultsPanelActions.CLEAR());
85         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
86         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
87         dispatch(navigateToSearchResults(searchValue));
88     };
89
90 export const setSearchValueFromAdvancedData = (data: SearchBarAdvancedFormData, prevData?: SearchBarAdvancedFormData) =>
91     (dispatch: Dispatch, getState: () => RootState) => {
92         if (data.projectObject) {
93             data.projectUuid = data.projectObject.uuid;
94         }
95         const searchValue = getState().searchBar.searchValue;
96         const value = getQueryFromAdvancedData({
97             ...data,
98             searchValue
99         }, prevData);
100         dispatch(searchBarActions.SET_SEARCH_VALUE(value));
101     };
102
103 export const setAdvancedDataFromSearchValue = (search: string, vocabulary: Vocabulary) =>
104     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
105         const data = getAdvancedDataFromQuery(search, vocabulary);
106         if (data.projectUuid) {
107             data.projectObject = await services.projectService.get(data.projectUuid);
108         }
109         dispatch<any>(initialize(SEARCH_BAR_ADVANCED_FORM_NAME, data));
110         if (data.projectUuid) {
111             await dispatch<any>(activateSearchBarProject(data.projectUuid));
112             dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCED_FORM_PICKER_ID, id: data.projectUuid }));
113         }
114     };
115
116 const saveQuery = (data: SearchBarAdvancedFormData) =>
117     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
118         const savedQueries = services.searchService.getSavedQueries();
119         if (data.saveQuery && data.queryName) {
120             const filteredQuery = savedQueries.find(query => query.queryName === data.queryName);
121             data.searchValue = getState().searchBar.searchValue;
122             if (filteredQuery) {
123                 services.searchService.editSavedQueries(data);
124                 dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries));
125                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
126             } else {
127                 services.searchService.saveQuery(data);
128                 dispatch(searchBarActions.SET_SAVED_QUERIES(savedQueries));
129                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
130             }
131         }
132     };
133
134 export const deleteSavedQuery = (id: number) =>
135     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
136         services.searchService.deleteSavedQuery(id);
137         const savedSearchQueries = services.searchService.getSavedQueries();
138         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
139         return savedSearchQueries || [];
140     };
141
142 export const editSavedQuery = (data: SearchBarAdvancedFormData) =>
143     (dispatch: Dispatch<any>) => {
144         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
145         dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data)));
146         dispatch<any>(initialize(SEARCH_BAR_ADVANCED_FORM_NAME, data));
147     };
148
149 export const openSearchView = () =>
150     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
151         const savedSearchQueries = services.searchService.getSavedQueries();
152         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
153         dispatch(loadRecentQueries());
154         dispatch(searchBarActions.OPEN_SEARCH_VIEW());
155         dispatch(searchBarActions.SELECT_FIRST_ITEM());
156     };
157
158 export const closeSearchView = () =>
159     (dispatch: Dispatch<any>) => {
160         dispatch(searchBarActions.SET_SELECTED_ITEM(''));
161         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
162     };
163
164 export const closeAdvanceView = () =>
165     (dispatch: Dispatch<any>) => {
166         dispatch(searchBarActions.SET_SEARCH_VALUE(''));
167         dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCED_FORM_PICKER_ID }));
168         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
169     };
170
171 export const navigateToItem = (uuid: string) =>
172     (dispatch: Dispatch<any>) => {
173         dispatch(searchBarActions.SET_SELECTED_ITEM(''));
174         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
175         dispatch(navigateTo(uuid));
176     };
177
178 export const changeData = (searchValue: string) =>
179     (dispatch: Dispatch, getState: () => RootState) => {
180         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
181         const currentView = getState().searchBar.currentView;
182         const searchValuePresent = searchValue.length > 0;
183
184         if (currentView === SearchView.ADVANCED) {
185             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
186         } else if (searchValuePresent) {
187             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
188             dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
189         } else {
190             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
191             dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
192             dispatch(searchBarActions.SELECT_FIRST_ITEM());
193         }
194     };
195
196 export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
197     (dispatch: Dispatch, getState: () => RootState) => {
198         event.preventDefault();
199         const searchValue = getState().searchBar.searchValue;
200         dispatch<any>(saveRecentQuery(searchValue));
201         dispatch<any>(loadRecentQueries());
202         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
203         if (RESOURCE_UUID_REGEX.exec(searchValue) || COLLECTION_PDH_REGEX.exec(searchValue)) {
204             dispatch<any>(navigateTo(searchValue));
205         } else {
206             dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
207             dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
208             dispatch(searchResultsPanelActions.CLEAR());
209             dispatch(navigateToSearchResults(searchValue));
210         }
211     };
212
213 let cancelTokens: any[] = [];
214 const searchGroups = (searchValue: string, limit: number, useCancel = false) =>
215     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
216         const currentView = getState().searchBar.currentView;
217
218         if (cancelTokens.length > 0 && useCancel) {
219             cancelTokens.forEach(cancelToken => (cancelToken as any).cancel('New search request triggered.'));
220             cancelTokens = [];
221         }
222
223         setTimeout(async () => {
224             if (searchValue || currentView === SearchView.ADVANCED) {
225                 const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue);
226                 const sessions = getSearchSessions(clusterId, getState().auth.sessions);
227                 const lists: ListResults<GroupContentsResource>[] = await Promise.all(sessions.map((session, index) => {
228                     cancelTokens.push(axios.CancelToken.source());
229                     const filters = queryToFilters(searchValue, session.apiRevision);
230                     return services.groupsService.contents('', {
231                         filters,
232                         limit,
233                         recursive: true
234                     }, session, cancelTokens[index].token);
235                 }));
236
237                 cancelTokens = [];
238
239                 const items = lists.reduce((items, list) => items.concat(list.items), [] as GroupContentsResource[]);
240
241                 if (lists.filter(list => !!(list as any).items).length !== lists.length) {
242                     dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
243                 } else {
244                     dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
245                 }
246             }
247         }, 10);
248     };
249
250 const buildQueryFromKeyMap = (data: any, keyMap: string[][]) => {
251     let value = data.searchValue;
252
253     const addRem = (field: string, key: string) => {
254         const v = data[key];
255         // Remove previous search expression.
256         if (data.hasOwnProperty(key)) {
257             let pattern: string;
258             if (v === false) {
259                 pattern = `${field.replace(':', '\\:\\s*')}\\s*`;
260             } else if (key.startsWith('prop-')) {
261                 // On properties, only remove key:value duplicates, allowing
262                 // multiple properties with the same key.
263                 const oldValue = key.slice(5).split(':')[1];
264                 pattern = `${field.replace(':', '\\:\\s*')}\\:\\s*${oldValue}\\s*`;
265             } else {
266                 pattern = `${field.replace(':', '\\:\\s*')}\\:\\s*[\\w|\\#|\\-|\\/]*\\s*`;
267             }
268             value = value.replace(new RegExp(pattern), '');
269         }
270         // Re-add it with the current search value.
271         if (v) {
272             const nv = v === true
273                 ? `${field}`
274                 : `${field}:${v}`;
275             // Always append to the end to keep user-entered text at the start.
276             value = value + ' ' + nv;
277         }
278     };
279     keyMap.forEach(km => addRem(km[0], km[1]));
280     return value;
281 };
282
283 export const getQueryFromAdvancedData = (data: SearchBarAdvancedFormData, prevData?: SearchBarAdvancedFormData) => {
284     let value = '';
285
286     const flatData = (data: SearchBarAdvancedFormData) => {
287         const fo = {
288             searchValue: data.searchValue,
289             type: data.type,
290             cluster: data.cluster,
291             projectUuid: data.projectUuid,
292             inTrash: data.inTrash,
293             pastVersions: data.pastVersions,
294             dateFrom: data.dateFrom,
295             dateTo: data.dateTo,
296         };
297         (data.properties || []).forEach(p =>
298             fo[`prop-"${p.keyID || p.key}":"${p.valueID || p.value}"`] = `"${p.valueID || p.value}"`
299         );
300         return fo;
301     };
302
303     const keyMap = [
304         ['type', 'type'],
305         ['cluster', 'cluster'],
306         ['project', 'projectUuid'],
307         [`is:${parser.States.TRASHED}`, 'inTrash'],
308         [`is:${parser.States.PAST_VERSION}`, 'pastVersions'],
309         ['from', 'dateFrom'],
310         ['to', 'dateTo']
311     ];
312     union(data.properties, prevData ? prevData.properties : [])
313         .forEach(p => keyMap.push(
314             [`has:"${p.keyID || p.key}"`, `prop-"${p.keyID || p.key}":"${p.valueID || p.value}"`]
315         ));
316
317     const modified = getModifiedKeysValues(flatData(data), prevData ? flatData(prevData) : {});
318     value = buildQueryFromKeyMap(
319         { searchValue: data.searchValue, ...modified } as SearchBarAdvancedFormData, keyMap);
320
321     value = value.trim();
322     return value;
323 };
324
325 export const getAdvancedDataFromQuery = (query: string, vocabulary?: Vocabulary): SearchBarAdvancedFormData => {
326     const { tokens, searchString } = parser.parseSearchQuery(query);
327     const getValue = parser.getValue(tokens);
328     return {
329         searchValue: searchString,
330         type: getValue(Keywords.TYPE) as ResourceKind,
331         cluster: getValue(Keywords.CLUSTER),
332         projectUuid: getValue(Keywords.PROJECT),
333         inTrash: parser.isTrashed(tokens),
334         pastVersions: parser.isPastVersion(tokens),
335         dateFrom: getValue(Keywords.FROM) || '',
336         dateTo: getValue(Keywords.TO) || '',
337         properties: vocabulary
338             ? parser.getProperties(tokens).map(
339                 p => {
340                     return {
341                         keyID: p.key,
342                         key: getTagKeyLabel(p.key, vocabulary),
343                         valueID: p.value,
344                         value: getTagValueLabel(p.key, p.value, vocabulary),
345                     };
346                 })
347             : parser.getProperties(tokens),
348         saveQuery: false,
349         queryName: ''
350     };
351 };
352
353 export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => {
354     return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
355 };
356
357 export const queryToFilters = (query: string, apiRevision: number) => {
358     const data = getAdvancedDataFromQuery(query);
359     const filter = new FilterBuilder();
360     const resourceKind = data.type;
361
362     if (data.searchValue) {
363         filter.addFullTextSearch(data.searchValue);
364     }
365
366     if (data.projectUuid) {
367         filter.addEqual('owner_uuid', data.projectUuid);
368     }
369
370     if (data.dateFrom) {
371         filter.addGte('modified_at', buildDateFilter(data.dateFrom));
372     }
373
374     if (data.dateTo) {
375         filter.addLte('modified_at', buildDateFilter(data.dateTo));
376     }
377
378     data.properties.forEach(p => {
379         if (p.value) {
380             if (apiRevision < 20200212) {
381                 filter
382                     .addEqual(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT)
383                     .addEqual(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION)
384                     .addEqual(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROCESS);
385             } else {
386                 filter
387                     .addContains(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT)
388                     .addContains(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION)
389                     .addContains(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROCESS);
390             }
391         }
392         filter.addExists(p.key);
393     });
394
395     return filter
396         .addIsA("uuid", buildUuidFilter(resourceKind))
397         .getFilters();
398 };
399
400 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
401     return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
402 };
403
404 const buildDateFilter = (date?: string): string => {
405     return date ? date : '';
406 };
407
408 export const initAdvancedFormProjectsTree = () =>
409     (dispatch: Dispatch) => {
410         dispatch<any>(initUserProject(SEARCH_BAR_ADVANCED_FORM_PICKER_ID));
411     };
412
413 export const changeAdvancedFormProperty = (propertyField: string, value: PropertyValue[] | string = '') =>
414     (dispatch: Dispatch) => {
415         dispatch(change(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField, value));
416     };
417
418 export const resetAdvancedFormProperty = (propertyField: string) =>
419     (dispatch: Dispatch) => {
420         dispatch(change(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField, null));
421         dispatch(untouch(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField));
422     };
423
424 export const moveUp = () =>
425     (dispatch: Dispatch) => {
426         dispatch(searchBarActions.MOVE_UP());
427     };
428
429 export const moveDown = () =>
430     (dispatch: Dispatch) => {
431         dispatch(searchBarActions.MOVE_DOWN());
432     };