diff --git a/app/src/components/FilePreview.js b/app/src/components/FilePreview.js index a9e9fdb3..55e583ca 100644 --- a/app/src/components/FilePreview.js +++ b/app/src/components/FilePreview.js @@ -442,6 +442,9 @@ export function FilePreviewProvider({children}) { const [previewQuery, setPreviewQuery] = useOneQuery('preview'); const [errorModalOpen, setErrorModalOpen] = React.useState(false); const location = useLocation(); + // The path of the open preview that has been marked viewed. One opening is one view, however + // many times previewFile is replaced while it is open (re-fetching after tagging, for example). + const trackedPathRef = React.useRef(null); // Determine if tracking should be skipped based on current route const skipTracking = shouldSkipTracking(location.pathname); @@ -471,7 +474,8 @@ export function FilePreviewProvider({children}) { const initPreviewFile = async () => { // Get simple information about the file, preview the file. try { - const file = await getFile(previewQuery, skipTracking); + // Not a view; the preview effect marks the file viewed once it is displayed. + const file = await getFile(previewQuery, true); setPreviewFile(file); } catch (e) { console.error(e); @@ -496,7 +500,7 @@ export function FilePreviewProvider({children}) { // Get the file again with its Tags. const {path, primary_path} = previewFile; try { - const file = await getFile(primary_path ?? path, skipTracking); + const file = await getFile(primary_path ?? path, true); setPreviewFile(file); } finally { await handleCallbacks(); @@ -586,6 +590,9 @@ export function FilePreviewProvider({children}) { React.useEffect(() => { setPreviewModal(null); + if (_.isEmpty(previewFile)) { + trackedPathRef.current = null; + } if (previewFile && !_.isObject(previewFile)) { console.error(`Unknown previewFile type: ${typeof previewFile}`); toast({ @@ -650,7 +657,8 @@ export function FilePreviewProvider({children}) { } // Trigger tracking for the file view (unless on an excluded route) - if (!skipTracking) { + if (!skipTracking && trackedPathRef.current !== path) { + trackedPathRef.current = path; getFile(path).catch(e => { console.error(e); console.error('Failed to get file to set FileGroup.viewed'); diff --git a/app/src/components/FilePreviewTracking.test.js b/app/src/components/FilePreviewTracking.test.js new file mode 100644 index 00000000..0ae1583d --- /dev/null +++ b/app/src/components/FilePreviewTracking.test.js @@ -0,0 +1,80 @@ +import React from 'react'; +import {act, waitFor} from '@testing-library/react'; +import {renderWithProviders} from '../test-utils'; +import {FilePreviewContext, FilePreviewProvider} from './FilePreview'; +import {getFile} from '../api'; + +jest.mock('../api', () => ({ + ...jest.requireActual('../api'), + getFile: jest.fn(), + tagFileGroup: jest.fn(), + untagFileGroup: jest.fn(), +})); + +const imageFile = {primary_path: 'pictures/cat.png', mimetype: 'image/png', size: 100, taggable: true, tags: []}; + +/** getFile calls that would mark the file viewed (skipTracking not set). */ +const trackedCalls = () => getFile.mock.calls.filter(([, skipTracking]) => !skipTracking); + +/** Exposes the provider's context so a test can open a preview the way PreviewLink does. */ +let context; +const ContextSpy = () => { + context = React.useContext(FilePreviewContext); + return null; +}; + +const renderProvider = (preview = null) => renderWithProviders( + , + { + route: '/files', + query: {searchParams: new URLSearchParams(preview ? {preview} : {}), updateQuery: jest.fn()}, + }, +); + +describe('FilePreview view tracking', () => { + beforeEach(() => { + getFile.mockReset(); + getFile.mockResolvedValue(imageFile); + context = null; + }); + + test('opening a preview from the URL marks the file viewed once', async () => { + renderProvider(imageFile.primary_path); + + await waitFor(() => expect(getFile).toHaveBeenCalled()); + await waitFor(() => expect(context.previewModal).not.toBeNull()); + expect(trackedCalls()).toHaveLength(1); + }); + + test('opening a preview from a link marks the file viewed once', async () => { + renderProvider(); + + act(() => context.setPreviewFile(imageFile)); + + await waitFor(() => expect(trackedCalls()).toHaveLength(1)); + expect(getFile).toHaveBeenCalledTimes(1); + }); + + test('refreshing the open file (after tagging) is not another view', async () => { + renderProvider(); + act(() => context.setPreviewFile(imageFile)); + await waitFor(() => expect(trackedCalls()).toHaveLength(1)); + + // localFetchFile replaces previewFile with the re-fetched file after a tag change. + act(() => context.setPreviewFile({...imageFile, tags: ['animals']})); + await waitFor(() => expect(context.previewFile.tags).toEqual(['animals'])); + + expect(trackedCalls()).toHaveLength(1); + }); + + test('closing and reopening the same file is another view', async () => { + renderProvider(); + act(() => context.setPreviewFile(imageFile)); + await waitFor(() => expect(trackedCalls()).toHaveLength(1)); + + act(() => context.setPreviewFile(null)); + act(() => context.setPreviewFile(imageFile)); + + await waitFor(() => expect(trackedCalls()).toHaveLength(2)); + }); +}); diff --git a/modules/docs/api.py b/modules/docs/api.py index 3178e7ed..41de7356 100644 --- a/modules/docs/api.py +++ b/modules/docs/api.py @@ -30,7 +30,8 @@ async def statistics(request: Request): @openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse) async def get_doc(request: Request, file_group_id: int): session = request.ctx.session - doc = _get_doc(session, file_group_id) + skip_viewed = request.args.get('skip_viewed', '').lower() == 'true' + doc = _get_doc(session, file_group_id, skip_viewed=skip_viewed) return json_response(_doc_response(doc)) diff --git a/modules/docs/lib.py b/modules/docs/lib.py index d28db9fe..a24317a0 100644 --- a/modules/docs/lib.py +++ b/modules/docs/lib.py @@ -338,11 +338,13 @@ def _doc_response(doc) -> dict: } -def _get_doc(session, file_group_id: int): +def _get_doc(session, file_group_id: int, skip_viewed: bool = False): from .models import Doc doc = session.query(Doc).options(*Doc.json_options()).filter_by(file_group_id=file_group_id).one_or_none() if not doc: raise ValidationError(f'Doc with file_group_id {file_group_id} not found') + if not skip_viewed: + doc.file_group.set_viewed() return doc diff --git a/modules/docs/test/test_api.py b/modules/docs/test/test_api.py index 0ffc7204..d0ed5507 100644 --- a/modules/docs/test/test_api.py +++ b/modules/docs/test/test_api.py @@ -54,6 +54,24 @@ async def test_get_doc(async_client, test_session, test_directory, example_epub, assert response.json['file_group'] +@pytest.mark.asyncio +async def test_get_doc_marks_viewed(async_client, test_session, doc_factory): + """Getting a doc marks it viewed, unless skip_viewed is requested.""" + doc = doc_factory() + file_group_id = doc.file_group_id + test_session.commit() + + request, response = await async_client.get(f'/api/docs/{file_group_id}?skip_viewed=true') + assert response.status_code == HTTPStatus.OK + test_session.expire_all() + assert test_session.query(Doc).filter_by(file_group_id=file_group_id).one().file_group.viewed is None + + request, response = await async_client.get(f'/api/docs/{file_group_id}') + assert response.status_code == HTTPStatus.OK + test_session.expire_all() + assert test_session.query(Doc).filter_by(file_group_id=file_group_id).one().file_group.viewed is not None + + @pytest.mark.asyncio async def test_docs_search_by_tag(async_client, test_session, doc_factory, tag_factory): """Docs can be searched by tag."""