From bdc29dace1b8e4a0b0aea5324f616a8120a96a91 Mon Sep 17 00:00:00 2001 From: Roland Date: Sat, 28 Feb 2026 08:39:10 -0700 Subject: [PATCH] Skipping recent file tracking for ignored directories, and video and archive pages. --- app/src/api.js | 4 +-- app/src/components/FilePreview.js | 34 +++++++++++++----- wrolpi/files/api.py | 3 +- wrolpi/files/lib.py | 10 +++++- wrolpi/files/schema.py | 1 + wrolpi/files/test/test_api.py | 58 +++++++++++++++++++++++++++++++ 6 files changed, 97 insertions(+), 13 deletions(-) diff --git a/app/src/api.js b/app/src/api.js index 6b53c594..ec367a73 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -1289,8 +1289,8 @@ export async function getFiles(directories) { return files; } -export async function getFile(path) { - let body = {file: path}; +export async function getFile(path, skipTracking = false) { + let body = {file: path, skip_tracking: skipTracking}; const response = await apiPost(`${API_URI}/files/file`, body); if (response.ok) { const {file} = await response.json(); diff --git a/app/src/components/FilePreview.js b/app/src/components/FilePreview.js index 0eb493b9..860a57f2 100644 --- a/app/src/components/FilePreview.js +++ b/app/src/components/FilePreview.js @@ -12,6 +12,18 @@ import {useOneQuery} from "../hooks/customHooks"; import {ShareButton} from "./Share"; import {pathDirectory} from "./FileBrowser"; import {InlineErrorBoundary} from "./ErrorBoundary"; +import {useLocation} from "react-router"; + +// Routes where file views should not be tracked +const EXCLUDED_TRACKING_ROUTES = [ + /^\/videos\/video\//, + /^\/videos\/channel\/[^/]+\/video\//, + /^\/archive\/\d+/ +]; + +function shouldSkipTracking(pathname) { + return EXCLUDED_TRACKING_ROUTES.some(pattern => pattern.test(pathname)); +} function getMediaPathURL(previewFile) { if (previewFile['primary_path']) { @@ -157,6 +169,10 @@ export function FilePreviewProvider({children}) { // The file path from the `preview` URL query. const [previewQuery, setPreviewQuery] = useOneQuery('preview'); const [errorModalOpen, setErrorModalOpen] = React.useState(false); + const location = useLocation(); + + // Determine if tracking should be skipped based on current route + const skipTracking = shouldSkipTracking(location.pathname); const handleErrorModalClose = () => { setPreviewQuery(null); @@ -184,7 +200,7 @@ export function FilePreviewProvider({children}) { const initPreviewFile = async () => { // Get simple information about the file, preview the file. try { - const file = await getFile(previewQuery); + const file = await getFile(previewQuery, skipTracking); setPreviewFile(file); } catch (e) { console.error(e); @@ -209,7 +225,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); + const file = await getFile(primary_path ?? path, skipTracking); setPreviewFile(file); } finally { await handleCallbacks(); @@ -349,15 +365,15 @@ export function FilePreviewProvider({children}) { setModalContent(getGenericPreviewModal(previewFile), url, downloadURL, path, taggable); } - // Fetch the file so `FileGroup.viewed` is set. - try { - getFile(path); - } catch (e) { - console.error(e); - console.error('Failed to get file to set FileGroup.viewed'); + // Trigger tracking for the file view (unless on an excluded route) + if (!skipTracking) { + getFile(path).catch(e => { + console.error(e); + console.error('Failed to get file to set FileGroup.viewed'); + }); } } - }, [previewFile]); + }, [previewFile, skipTracking]); const value = {previewFile, setPreviewFile, previewModal, setPreviewModal, setCallbacks}; diff --git a/wrolpi/files/api.py b/wrolpi/files/api.py index 1dc8b3ab..6a58b9b6 100644 --- a/wrolpi/files/api.py +++ b/wrolpi/files/api.py @@ -51,7 +51,8 @@ async def get_file(request: Request, body: schema.FileRequest): except FileNotFoundError: raise InvalidFile() - background_task(lib.set_file_viewed(session, get_media_directory() / body.file)) + if not body.skip_tracking: + background_task(lib.set_file_viewed(session, get_media_directory() / body.file)) return json_response({'file': file}) diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index 553292de..9e8e9b81 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -131,7 +131,15 @@ def get_file_dict(session: Session, file: str) -> Dict: async def set_file_viewed(session: Session, file: pathlib.Path): - """Change FileGroup.viewed to the current datetime.""" + """Change FileGroup.viewed to the current datetime. + + Files in ignored directories are not tracked. + """ + # Check if file is in an ignored directory + remaining = remove_files_in_ignored_directories([file]) + if not remaining: + return + try: fg = FileGroup.find_by_path(session, file) except UnknownFile: diff --git a/wrolpi/files/schema.py b/wrolpi/files/schema.py index c9da0b17..ef6719f3 100644 --- a/wrolpi/files/schema.py +++ b/wrolpi/files/schema.py @@ -12,6 +12,7 @@ class FilesRequest: @dataclass class FileRequest: file: str + skip_tracking: bool = False @dataclass diff --git a/wrolpi/files/test/test_api.py b/wrolpi/files/test/test_api.py index 0c712cd9..76426fcd 100644 --- a/wrolpi/files/test/test_api.py +++ b/wrolpi/files/test/test_api.py @@ -1246,3 +1246,61 @@ async def test_bulk_tag_progress_api(test_session, async_client): assert 'total' in response.json assert 'completed' in response.json assert 'queued_jobs' in response.json + + +# --- File Tracking Tests --- + + +@pytest.mark.asyncio +async def test_get_file_skip_tracking(test_session, async_client, test_directory, make_files_structure, refresh_files): + """Can get info about a single file without tracking the view.""" + make_files_structure({'foo/bar.txt': 'foo contents'}) + await refresh_files() + + # Request the file with skip_tracking=True + content = dict(file='foo/bar.txt', skip_tracking=True) + request, response = await 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' + + # FileGroup.viewed should not be set + fg, = test_session.query(FileGroup).all() + assert fg.primary_path == test_directory / 'foo/bar.txt' + assert fg.viewed is None, "FileGroup.viewed should not be set when skip_tracking=True" + + +@pytest.mark.asyncio +async def test_get_file_ignored_directory_not_tracked(test_session, async_client, test_directory, make_files_structure, + refresh_files, test_wrolpi_config, await_switches): + """Files in ignored directories do not get their viewed timestamp set.""" + # Create files in a directory that will be ignored + foo, bar = make_files_structure({'config/settings.txt': 'settings', 'normal/file.txt': 'contents'}) + + # Ignore the config directory + get_wrolpi_config().ignored_directories = [str(test_directory / 'config')] + await await_switches() + + # Refresh only the normal directory (config is ignored) + await refresh_files() + + # The normal file should be in the database + normal_fg = test_session.query(FileGroup).filter(FileGroup.primary_path.like('%normal%')).one() + assert normal_fg.viewed is None + + # Request the normal file - it should be tracked + content = dict(file='normal/file.txt') + request, response = await async_client.post('/api/files/file', content=json.dumps(content)) + assert response.status_code == HTTPStatus.OK + test_session.refresh(normal_fg) + assert normal_fg.viewed is not None, "Normal files should be tracked" + + # Request a file in the ignored directory - it should return the file data + # but should not be tracked (since it's in an ignored directory) + content = dict(file='config/settings.txt') + request, response = await async_client.post('/api/files/file', content=json.dumps(content)) + assert response.status_code == HTTPStatus.OK + + # Verify the ignored file is not in the database (because it was never refreshed) + ignored_fgs = test_session.query(FileGroup).filter(FileGroup.primary_path.like('%config%')).all() + assert len(ignored_fgs) == 0, "Files in ignored directories should not be in the database"