diff --git a/app/src/api.js b/app/src/api.js index 0808aed8..d6ed09a5 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -1003,8 +1003,8 @@ export async function fetchDecoded(vinNumber) { } } -export async function searchSuggestions(search_str, tagNames) { - const body = {search_str: search_str, tag_names: tagNames}; +export async function searchSuggestions(search_str, tagNames, mimetypes) { + const body = {search_str: search_str, tag_names: tagNames, mimetypes: mimetypes}; const response = await apiPost(`${API_URI}/search_suggestions`, body); if (response.ok) { const content = await response.json(); diff --git a/app/src/components/Search.js b/app/src/components/Search.js index 249c69f7..784dfca1 100644 --- a/app/src/components/Search.js +++ b/app/src/components/Search.js @@ -1,10 +1,10 @@ import React, {useState} from "react"; import {createSearchParams, Route, Routes, useNavigate} from "react-router-dom"; import {FilesSearchView} from "./Files"; -import {useLatestRequest, usePages, useQuery} from "../hooks/customHooks"; +import {useLatestRequest, usePages, useQuery, useSearchFilter} from "../hooks/customHooks"; import {ZimSearchView} from "./Zim"; import {searchEstimateZims, searchSuggestions} from "../api"; -import {fuzzyMatch, normalizeEstimate, SearchResultsInput, TabLinks} from "./Common"; +import {filterToMimetypes, fuzzyMatch, normalizeEstimate, SearchResultsInput, TabLinks} from "./Common"; import _ from "lodash"; import {TagsContext} from "../Tags"; import {Button as SButton, Header as SHeader, Label} from "semantic-ui-react"; @@ -93,7 +93,7 @@ export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false } } -export function useSuggestions(searchStr, tagNames) { +export function useSuggestions(searchStr, tagNames, filter) { const defaultSuggestions = { fileGroups: [], channels: [], @@ -108,7 +108,8 @@ export function useSuggestions(searchStr, tagNames) { React.useEffect(() => { if ((searchStr && searchStr.length > 0) || (tagNames && tagNames.length > 0)) { - sendRequest(async () => await searchSuggestions(searchStr, tagNames)); + const mimetypes = filterToMimetypes(filter); + sendRequest(async () => await searchSuggestions(searchStr, tagNames, mimetypes)); sendZimRequest(async () => await searchEstimateZims(searchStr, tagNames)); } }, [searchStr, sendRequest, sendZimRequest, JSON.stringify(tagNames)]); @@ -136,16 +137,20 @@ export function useSuggestions(searchStr, tagNames) { export function useSearchSuggestions(defaultSearchStr, defaultTagNames) { const navigate = useNavigate(); + const {filter} = useSearchFilter(); const [searchStr, setSearchStr] = React.useState(defaultSearchStr || ''); const [searchTags, setSearchTags] = React.useState(defaultTagNames); const {SingleTag, fuzzyMatchTagsByName} = React.useContext(TagsContext); - const {suggestions, loading} = useSuggestions(searchStr, searchTags); + const {suggestions, loading} = useSuggestions(searchStr, searchTags, filter); + const {getLocationStr} = useQuery(); // The results that will be displayed by . const [suggestionsResults, setSuggestionsResults] = useState({}); // The results summarized. const [suggestionsSums, setSuggestionsSums] = useState({}); + const noResults = [{title: 'No results'}]; + const normalizeSuggestionsResults = (newSuggestions) => { // Convert the suggestions from the Backend to what the Semantic expects. const lowerSearchStr = searchStr ? searchStr.toLowerCase() : ''; @@ -159,10 +164,13 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames) { { title: newSuggestions.fileGroups.toString(), type: 'files', - location: `/search?q=${encodeURIComponent(searchStr)}` + location: getLocationStr({q: searchStr}) } ] }; + } else if (newSuggestions.fileGroups === 0) { + // Tell the user there are no files. + results.fileGroups = {name: 'Files', results: noResults}; } const zimSum = newSuggestions.zimsEstimates && newSuggestions.zimsEstimates.length > 0 @@ -173,7 +181,9 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames) { name: 'Zims', results: [ {title: zimSum.toString(), type: 'zims', location: `/search/zim?q=${encodeURIComponent(searchStr)}`} ], - } + }; + } else if (newSuggestions && zimSum === 0) { + results.zimsSum = {name: 'Zims', results: noResults}; } if (newSuggestions.channels && newSuggestions.channels.length > 0) { results.channels = { @@ -235,7 +245,13 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames) { }, [JSON.stringify(suggestions)]); // User clicked on a result in the dropdown. - const handleResultSelect = ({result}) => navigate(result.location); + const handleResultSelect = ({result}) => { + if (result.location) { + navigate(result.location); + } else { + console.error('No location to navigate'); + } + } const resultRenderer = ({type, title, description}) => { if (type === 'tag') { diff --git a/app/src/hooks/customHooks.js b/app/src/hooks/customHooks.js index 8e8bb4bb..7e6634c1 100644 --- a/app/src/hooks/customHooks.js +++ b/app/src/hooks/customHooks.js @@ -26,7 +26,7 @@ import { setHotspot, setThrottle, } from "../api"; -import {createSearchParams, useSearchParams} from "react-router-dom"; +import {createSearchParams, useLocation, useSearchParams} from "react-router-dom"; import {enumerate, filterToMimetypes, humanFileSize, secondsToFullDuration} from "../components/Common"; import {StatusContext} from "../contexts/contexts"; import {toast} from "react-semantic-toasts-2"; @@ -105,13 +105,14 @@ export const useLatestRequest = (delay = 300, defaultLoading = false) => { export const useQuery = () => { + const location = useLocation(); const [searchParams, setSearchParams] = useSearchParams(); - const setQuery = (obj) => { - setSearchParams(createSearchParams(obj), {replace: true}); + const setQuery = (obj, replace = true) => { + setSearchParams(createSearchParams(obj), {replace: replace}); } - const updateQuery = (obj) => { + const getQuery = (obj) => { const newQuery = {}; for (const entry of searchParams.entries()) { newQuery[entry[0]] = entry[1]; @@ -123,10 +124,21 @@ export const useQuery = () => { newQuery[key] = value; } }) + return newQuery; + } + + const updateQuery = (obj) => { + const newQuery = getQuery(obj); setQuery(newQuery); } - return {searchParams, setSearchParams, setQuery, updateQuery} + const getLocationStr = (newSearchParams) => { + // Get the current location, but with new params appended. + const newQuery = createSearchParams(getQuery(newSearchParams)); + return `${location.pathname}?${newQuery.toString()}` + } + + return {searchParams, setSearchParams, setQuery, updateQuery, getLocationStr} } export const useOneQuery = (name) => { diff --git a/wrolpi/files/api.py b/wrolpi/files/api.py index 85c8dae2..adde7cf0 100644 --- a/wrolpi/files/api.py +++ b/wrolpi/files/api.py @@ -372,17 +372,3 @@ async def post_upload(request: Request): # Request the next chunk. return json_response({'expected_chunk': expected_chunk_num}, HTTPStatus.OK) - - -@bp.post('/search_estimates') -@validate(json=schema.SearchEstimateRequest) -async def post_search_estimates(_: Request, body: schema.SearchEstimateRequest): - """Get an estimated count of FileGroups which may or may not have been tagged.""" - if not body.search_str and not body.tag_names: - return response.empty(HTTPStatus.BAD_REQUEST) - - file_groups = await lib.estimate_search(body.search_str, body.tag_names) - ret = dict( - file_groups=file_groups, - ) - return json_response(ret) diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index ba8762b0..5b0607b0 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -700,17 +700,9 @@ def search_files(search_str: str, limit: int, offset: int, mimetypes: List[str] selects.append('ts_rank(textsearch, websearch_to_tsquery(%(search_str)s))') order_by = '2 DESC' - if mimetypes: - mimetype_wheres = [] - for idx, mimetype in enumerate(mimetypes): - key = f'mimetype{idx}' - if len(mimetype.split('/')) == 1: - params[key] = f'{mimetype}/%' - else: - params[key] = f'{mimetype}%' - mimetype_wheres.append(f'mimetype LIKE %({key})s') - mimetype_wheres = ' OR '.join(mimetype_wheres) - wheres.append(f'({mimetype_wheres})') + mimetype_wheres, params = mimetypes_to_sql_wheres(mimetypes, params) + if mimetype_wheres: + wheres.append(mimetype_wheres) if model: params['model'] = model @@ -1060,31 +1052,48 @@ def get_refresh_progress() -> RefreshProgress: return progress -async def estimate_search(search_str: str, tag_names: List[str]): +def mimetypes_to_sql_wheres(mimetypes: List[str], params: dict): + if mimetypes: + mimetype_wheres = [] + for idx, mimetype in enumerate(mimetypes): + key = f'mimetype{idx}' + if len(mimetype.split('/')) == 1: + params[key] = f'{mimetype}/%' + else: + params[key] = f'{mimetype}%' + mimetype_wheres.append(f'mimetype LIKE %({key})s') + mimetype_wheres = ' OR '.join(mimetype_wheres) + return f'({mimetype_wheres})', params + return '', params + + +async def estimate_search(search_str: str, tag_names: List[str], mimetypes: List[str]): + """ + Return FileGroup count of what will be returned if the search is actually performed. + """ + wheres = ['textsearch @@ websearch_to_tsquery(%(search_str)s)'] + joins = list() + params = dict(search_str=search_str, tag_names=tag_names, mimetypes=mimetypes) + + if tag_names: + joins.append('LEFT JOIN tag_file tf on file_group.id = tf.file_group_id') + wheres.append('tf.tag_id IN (select id from tag where name = ANY(%(tag_names)s))') + + mimetype_wheres, params = mimetypes_to_sql_wheres(mimetypes, params) + if mimetype_wheres: + wheres.append(mimetype_wheres) + + joins = "\n".join(joins) + wheres = "\nAND ".join(wheres) + stmt = f''' + SELECT COUNT(*) OVER() AS estimate + FROM file_group + {joins} + WHERE {wheres} + ''' + logger.debug(stmt, params) + with get_db_curs() as curs: - if search_str and tag_names: - params = dict(search_str=search_str, tag_names=tag_names) - stmt = ''' - SELECT COUNT(*) OVER() AS estimate - FROM file_group - LEFT JOIN tag_file tf on file_group.id = tf.file_group_id - WHERE textsearch @@ websearch_to_tsquery(%(search_str)s) - AND tf.tag_id IN (select id from tag where name = ANY(%(tag_names)s)) - ''' - elif tag_names: - params = dict(tag_names=tag_names) - stmt = ''' - SELECT COUNT(*) OVER() AS estimate - FROM file_group - LEFT JOIN tag_file tf on file_group.id = tf.file_group_id - WHERE tf.tag_id IN (select id from tag where name = ANY(%(tag_names)s))''' - else: - params = dict(search_str=search_str) - stmt = ''' - SELECT COUNT(*) OVER() AS estimate - FROM file_group - WHERE textsearch @@ websearch_to_tsquery(%(search_str)s) - ''' curs.execute(stmt, params) result = curs.fetchone() if result: diff --git a/wrolpi/files/test/test_api.py b/wrolpi/files/test/test_api.py index 923ae03e..8e79862d 100644 --- a/wrolpi/files/test/test_api.py +++ b/wrolpi/files/test/test_api.py @@ -585,15 +585,3 @@ async def test_delete_directory_recursive(test_session, test_directory, make_fil empty = test_session.query(FileGroup).one() assert empty.primary_path.name == 'empty' - - -@pytest.mark.asyncio -async def test_search_estimates(test_session, test_async_client, archive_factory): - archive_factory(domain='foo.com', contents='contents of foo') - archive_factory(domain='bar.com', contents='contents of bar') - test_session.commit() - - body = dict(search_str='one') - request, response = await test_async_client.post('/api/files/search_estimates', json=body) - assert response.status_code == HTTPStatus.OK - assert response.json['file_groups'] == 0 diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index 232a8170..bdd951fe 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -514,7 +514,7 @@ async def post_search_suggestions(_: Request, body: schema.SearchSuggestionsRequ from modules.archive.lib import search_domains_by_name file_groups, channels, domains = await asyncio.gather( - estimate_search(body.search_str, body.tag_names), + estimate_search(body.search_str, body.tag_names, body.mimetypes), search_channels_by_name(body.search_str), search_domains_by_name(body.search_str), ) diff --git a/wrolpi/schema.py b/wrolpi/schema.py index e73b8711..60a7e728 100644 --- a/wrolpi/schema.py +++ b/wrolpi/schema.py @@ -140,4 +140,5 @@ class VINDecoderResponse: @dataclass class SearchSuggestionsRequest: search_str: Optional[str] = None + mimetypes: List[str] = field(default_factory=lambda: list()) tag_names: List[str] = field(default_factory=lambda: list()) diff --git a/wrolpi/test/test_root_api.py b/wrolpi/test/test_root_api.py index 83e9ac39..716350f3 100644 --- a/wrolpi/test/test_root_api.py +++ b/wrolpi/test/test_root_api.py @@ -468,13 +468,15 @@ async def test_post_vin_number_decoder(test_async_client): @pytest.mark.asyncio -async def test_search_suggestions(test_session, test_async_client, channel_factory, archive_factory, tag_factory): +async def test_search_suggestions(test_session, test_async_client, channel_factory, archive_factory, tag_factory, + video_factory): # WARNING results are cached, this test uses unique queries to avoid conflicts. channel_factory(name='Foo') channel_factory(name='Fool') channel_factory(name='Bar') - archive_factory(domain='foo.com', contents='contents of foo') + archive_factory(domain='foo.com', contents='contents of foo with bunny') archive_factory(domain='bar.com', contents='contents of bar') + video_factory(with_caption_file=True) test_session.commit() body = dict(search_str='foo') @@ -502,6 +504,18 @@ async def test_search_suggestions(test_session, test_async_client, channel_facto assert response.json['domains'] == [] assert response.json['file_groups'] == 0 + # "foo" archive and video both contain bunny. + body = dict(search_str='bunny') + request, response = await test_async_client.post('/api/search_suggestions', json=body) + assert response.status_code == HTTPStatus.OK + assert response.json['file_groups'] == 2 + + # Filtering with mimetypes removes archive result. + body = dict(search_str='bunny', mimetypes=['video']) + request, response = await test_async_client.post('/api/search_suggestions', json=body) + assert response.status_code == HTTPStatus.OK + assert response.json['file_groups'] == 1 + def test_recursive_errors(): """Errors are reported recursively."""