From 1bb333e43bba4ed03fd11a81788c1c4cbe2d5ed7 Mon Sep 17 00:00:00 2001 From: Roland Date: Sat, 17 Feb 2024 14:52:46 -0700 Subject: [PATCH] Adding preview URL query which allows sharing of a specific file. --- app/src/DashboardPage.js | 3 ++ app/src/api.js | 11 ++++++ app/src/components/FilePreview.js | 59 +++++++++++++++++++++++++++++-- app/src/components/Search.js | 1 + app/src/hooks/customHooks.js | 2 ++ wrolpi/files/api.py | 5 ++- wrolpi/files/test/test_api.py | 12 +++++++ 7 files changed, 89 insertions(+), 4 deletions(-) diff --git a/app/src/DashboardPage.js b/app/src/DashboardPage.js index 72d9dd73..d8017ea7 100644 --- a/app/src/DashboardPage.js +++ b/app/src/DashboardPage.js @@ -26,6 +26,7 @@ import {SearchView, useSearch, useSearchSuggestions} from "./components/Search"; import {KiwixRestartMessage, OutdatedZimsMessage} from "./components/Zim"; import {useSettings, useWROLMode} from "./hooks/customHooks"; import {FileSearchFilterButton} from "./components/Files"; +import {FilePreviewContext} from "./components/FilePreview"; function FlagsMessages({flags}) { const {settings, fetchSettings} = useSettings(); @@ -172,6 +173,8 @@ export function DashboardPage() { } = useSearchSuggestions(searchStr, activeTags); const {status} = useContext(StatusContext); + const {setPreviewFile} = React.useContext(FilePreviewContext); + React.useEffect(() => { setSuggestionSearchStr(localSearchStr); }, [localSearchStr]); diff --git a/app/src/api.js b/app/src/api.js index d6ed09a5..0155ca5f 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -593,6 +593,17 @@ export async function getFiles(directories) { return files; } +export async function getFile(path) { + let body = {file: path}; + let response = await apiPost(`${API_URI}/files/file`, body); + if (response.ok) { + const {file} = await response.json(); + return file; + } else { + throw new Error('Failed to get file data'); + } +} + export async function deleteFile(paths) { let body = {paths: paths}; const response = await apiPost(`${API_URI}/files/delete`, body); diff --git a/app/src/components/FilePreview.js b/app/src/components/FilePreview.js index 58dce63e..5b8b8695 100644 --- a/app/src/components/FilePreview.js +++ b/app/src/components/FilePreview.js @@ -4,10 +4,12 @@ import {Grid, Header as SHeader, Image,} from "semantic-ui-react"; import {TagsSelector} from "../Tags"; import {Media} from "../contexts/contexts"; import {encodeMediaPath} from "./Common"; -import {fetchFile, tagFileGroup, untagFileGroup} from "../api"; +import {fetchFile, getFile, tagFileGroup, untagFileGroup} from "../api"; import {StlViewer} from "react-stl-viewer"; import {Button, Modal, ModalActions, ModalContent, ModalHeader} from "./Theme"; import {toast} from "react-semantic-toasts-2"; +import {useOneQuery} from "../hooks/customHooks"; +import {ShareButton} from "./Share"; function getMediaPathURL(previewFile) { if (previewFile['primary_path']) { @@ -143,9 +145,56 @@ export const FilePreviewContext = React.createContext({ const MAXIMUM_TEXT_SIZE = 5_000_000; export function FilePreviewProvider({children}) { + // Data about the file that is being previewed. const [previewFile, setPreviewFile] = React.useState(null); + // A modal is only displayed once we have data about the file. const [previewModal, setPreviewModal] = React.useState(null); const [callbacks, setCallbacks] = React.useState(null); + // The file path from the `preview` URL query. + const [previewQuery, setPreviewQuery] = useOneQuery('preview'); + const [errorModalOpen, setErrorModalOpen] = React.useState(false); + + const handleErrorModalClose = () => { + setPreviewQuery(null); + setErrorModalOpen(false); + } + + const errorModal = + Unknown File + Cannot display preview, no such file exists: {previewQuery} + + + + + + React.useEffect(() => { + if (!_.isEmpty(previewFile)) { + // Change URL to match the file that is being previewed. + setPreviewQuery(previewFile['primary_path'] || previewFile['path']); + } + }, [previewFile]); + + const initPreviewFile = async () => { + // Get simple information about the file, preview the file. + try { + const file = await getFile(previewQuery); + setPreviewFile(file); + } catch (e) { + console.error(e); + setPreviewModal(errorModal); + setErrorModalOpen(true); + } + } + + React.useEffect(() => { + // Navigated to a page which has a file preview active, fetch the information about the file, then display it. + if (previewQuery && !previewFile) { + initPreviewFile(); + } + }, []); const localFetchFile = async () => { // Get the file again with its Tags. @@ -164,6 +213,7 @@ export function FilePreviewProvider({children}) { } setPreviewModal(null); setPreviewFile(null); + setPreviewQuery(null); } const handleCallbacks = async () => { @@ -220,7 +270,8 @@ export function FilePreviewProvider({children}) { {closeButton} - {tagsDisplay} + + {tagsDisplay} @@ -228,7 +279,8 @@ export function FilePreviewProvider({children}) { {downloadButton} - {tagsDisplay} + + {tagsDisplay} {openButton} {closeButton} @@ -292,5 +344,6 @@ export function FilePreviewProvider({children}) { return {children} {previewModal} + {errorModal} } diff --git a/app/src/components/Search.js b/app/src/components/Search.js index da959c40..717b6b95 100644 --- a/app/src/components/Search.js +++ b/app/src/components/Search.js @@ -249,6 +249,7 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames) { // User clicked on a result in the dropdown. const handleResultSelect = ({result}) => { if (result.location) { + console.info(`useSearchSuggestions Navigating: ${result.location}`) navigate(result.location); } else { console.error('No location to navigate'); diff --git a/app/src/hooks/customHooks.js b/app/src/hooks/customHooks.js index 418bbbd4..789f5af3 100644 --- a/app/src/hooks/customHooks.js +++ b/app/src/hooks/customHooks.js @@ -9,6 +9,7 @@ import { getChannels, getDirectories, getDownloads, + getFile, getFiles, getInventory, getOutdatedZims, @@ -109,6 +110,7 @@ export const useQuery = () => { const [searchParams, setSearchParams] = useSearchParams(); const setQuery = (obj, replace = true) => { + console.debug(`setQuery`, obj); setSearchParams(createSearchParams(obj), {replace: replace}); } diff --git a/wrolpi/files/api.py b/wrolpi/files/api.py index adde7cf0..bf401840 100644 --- a/wrolpi/files/api.py +++ b/wrolpi/files/api.py @@ -41,7 +41,10 @@ async def get_files(_: Request, body: schema.FilesRequest): ) @validate(schema.FileRequest) async def get_file(_: Request, body: schema.FileRequest): - file = lib.get_file_dict(body.file) + try: + file = lib.get_file_dict(body.file) + except FileNotFoundError: + raise InvalidFile() return json_response({'file': file}) diff --git a/wrolpi/files/test/test_api.py b/wrolpi/files/test/test_api.py index 3610ad99..e23fa212 100644 --- a/wrolpi/files/test/test_api.py +++ b/wrolpi/files/test/test_api.py @@ -587,3 +587,15 @@ 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_get_file(test_session, test_async_client, test_directory, make_files_structure): + """Can get info about a single file.""" + make_files_structure({'foo/bar.txt': 'foo contents'}) + await lib.refresh_files() + + content = dict(file='foo/bar.txt') + request, response = await test_async_client.post('/api/files/file', content=json.dumps(content)) + assert response.status_code == HTTPStatus.OK + assert response.json['file'] + assert response.json['file']['path'] == 'foo/bar.txt'