mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-26 01:46:18 -05:00
Fix file view tracking: docs mark viewed, previews count one view (#786)
Opening a doc on its page never set FileGroup.viewed, so docs were missing from Recently Viewed. GET /api/docs/:id now marks the doc viewed, with the same skip_viewed parameter as archives and videos. The file preview marked a file viewed more than once: opening from a ?preview= URL sent two tracked requests, and every tag change re-fetched the file with tracking on. The fetches now skip tracking, and the preview marks each opening viewed once. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a1292005ce
commit
531721c157
5 changed files with 114 additions and 5 deletions
|
|
@ -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');
|
||||
|
|
|
|||
80
app/src/components/FilePreviewTracking.test.js
Normal file
80
app/src/components/FilePreviewTracking.test.js
Normal file
|
|
@ -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(
|
||||
<FilePreviewProvider><ContextSpy/></FilePreviewProvider>,
|
||||
{
|
||||
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));
|
||||
});
|
||||
});
|
||||
|
|
@ -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))
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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."""
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue