1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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";
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<{}>()
44 export type SearchBarActions = UnionOf<typeof searchBarActions>;
46 export const SEARCH_BAR_ADVANCED_FORM_NAME = 'searchBarAdvancedFormName';
48 export const SEARCH_BAR_ADVANCED_FORM_PICKER_ID = 'searchBarAdvancedFormPickerId';
50 export const DEFAULT_SEARCH_DEBOUNCE = 1000;
52 export const goToView = (currentView: string) => searchBarActions.SET_CURRENT_VIEW(currentView);
54 export const saveRecentQuery = (query: string) =>
55 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) =>
56 services.searchService.saveRecentQuery(query);
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));
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));
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));
90 export const setSearchValueFromAdvancedData = (data: SearchBarAdvancedFormData, prevData?: SearchBarAdvancedFormData) =>
91 (dispatch: Dispatch, getState: () => RootState) => {
92 if (data.projectObject) {
93 data.projectUuid = data.projectObject.uuid;
95 const searchValue = getState().searchBar.searchValue;
96 const value = getQueryFromAdvancedData({
100 dispatch(searchBarActions.SET_SEARCH_VALUE(value));
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);
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 }));
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;
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 }));
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 }));
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 || [];
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));
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());
158 export const closeSearchView = () =>
159 (dispatch: Dispatch<any>) => {
160 dispatch(searchBarActions.SET_SELECTED_ITEM(''));
161 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
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));
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));
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;
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));
190 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
191 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
192 dispatch(searchBarActions.SELECT_FIRST_ITEM());
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));
206 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
207 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
208 dispatch(searchResultsPanelActions.CLEAR());
209 dispatch(navigateToSearchResults(searchValue));
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;
218 if (cancelTokens.length > 0 && useCancel) {
219 cancelTokens.forEach(cancelToken => (cancelToken as any).cancel('New search request triggered.'));
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('', {
234 }, session, cancelTokens[index].token);
239 const items = lists.reduce((items, list) => items.concat(list.items), [] as GroupContentsResource[]);
241 if (lists.filter(list => !!(list as any).items).length !== lists.length) {
242 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
244 dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
250 const buildQueryFromKeyMap = (data: any, keyMap: string[][]) => {
251 let value = data.searchValue;
253 const addRem = (field: string, key: string) => {
255 // Remove previous search expression.
256 if (data.hasOwnProperty(key)) {
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*`;
266 pattern = `${field.replace(':', '\\:\\s*')}\\:\\s*[\\w|\\#|\\-|\\/]*\\s*`;
268 value = value.replace(new RegExp(pattern), '');
270 // Re-add it with the current search value.
272 const nv = v === true
275 // Always append to the end to keep user-entered text at the start.
276 value = value + ' ' + nv;
279 keyMap.forEach(km => addRem(km[0], km[1]));
283 export const getQueryFromAdvancedData = (data: SearchBarAdvancedFormData, prevData?: SearchBarAdvancedFormData) => {
286 const flatData = (data: SearchBarAdvancedFormData) => {
288 searchValue: data.searchValue,
290 cluster: data.cluster,
291 projectUuid: data.projectUuid,
292 inTrash: data.inTrash,
293 pastVersions: data.pastVersions,
294 dateFrom: data.dateFrom,
297 (data.properties || []).forEach(p =>
298 fo[`prop-"${p.keyID || p.key}":"${p.valueID || p.value}"`] = `"${p.valueID || p.value}"`
305 ['cluster', 'cluster'],
306 ['project', 'projectUuid'],
307 [`is:${parser.States.TRASHED}`, 'inTrash'],
308 [`is:${parser.States.PAST_VERSION}`, 'pastVersions'],
309 ['from', 'dateFrom'],
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}"`]
317 const modified = getModifiedKeysValues(flatData(data), prevData ? flatData(prevData) : {});
318 value = buildQueryFromKeyMap(
319 { searchValue: data.searchValue, ...modified } as SearchBarAdvancedFormData, keyMap);
321 value = value.trim();
325 export const getAdvancedDataFromQuery = (query: string, vocabulary?: Vocabulary): SearchBarAdvancedFormData => {
326 const { tokens, searchString } = parser.parseSearchQuery(query);
327 const getValue = parser.getValue(tokens);
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(
342 key: getTagKeyLabel(p.key, vocabulary),
344 value: getTagValueLabel(p.key, p.value, vocabulary),
347 : parser.getProperties(tokens),
353 export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => {
354 return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
357 export const queryToFilters = (query: string, apiRevision: number) => {
358 const data = getAdvancedDataFromQuery(query);
359 const filter = new FilterBuilder();
360 const resourceKind = data.type;
362 if (data.searchValue) {
363 filter.addFullTextSearch(data.searchValue);
366 if (data.projectUuid) {
367 filter.addEqual('owner_uuid', data.projectUuid);
371 filter.addGte('modified_at', buildDateFilter(data.dateFrom));
375 filter.addLte('modified_at', buildDateFilter(data.dateTo));
378 data.properties.forEach(p => {
380 if (apiRevision < 20200212) {
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);
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);
392 filter.addExists(p.key);
396 .addIsA("uuid", buildUuidFilter(resourceKind))
400 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
401 return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
404 const buildDateFilter = (date?: string): string => {
405 return date ? date : '';
408 export const initAdvancedFormProjectsTree = () =>
409 (dispatch: Dispatch) => {
410 dispatch<any>(initUserProject(SEARCH_BAR_ADVANCED_FORM_PICKER_ID));
413 export const changeAdvancedFormProperty = (propertyField: string, value: PropertyValue[] | string = '') =>
414 (dispatch: Dispatch) => {
415 dispatch(change(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField, value));
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));
424 export const moveUp = () =>
425 (dispatch: Dispatch) => {
426 dispatch(searchBarActions.MOVE_UP());
429 export const moveDown = () =>
430 (dispatch: Dispatch) => {
431 dispatch(searchBarActions.MOVE_DOWN());