diff --git a/app/src/components/Zim.js b/app/src/components/Zim.js
index 587bd1a9..8d5421e3 100644
--- a/app/src/components/Zim.js
+++ b/app/src/components/Zim.js
@@ -58,10 +58,16 @@ import {HeadlineText} from "./Headline";
export const OutdatedZimsMessage = ({onClick}) => {
const [open, setOpen] = React.useState(false);
- const {outdated, current} = useOutdatedZims();
+ const {outdated, current, fetchOutdatedZims} = useOutdatedZims();
const onClose = () => setOpen(false);
+ const onOpen = async () => {
+ setOpen(true);
+ // The list must reflect disk now, not page load.
+ await fetchOutdatedZims();
+ }
+
const handleDelete = async () => {
try {
const success = await deleteOutdatedZims();
@@ -102,13 +108,17 @@ export const OutdatedZimsMessage = ({onClick}) => {
{current.map(i =>
{i})}
>
+ } else if (outdated && outdated.length === 0) {
+ modalContent =
+ No outdated Zim files were found. Click Delete to clear this message.
+
}
return
New Zim files have been downloaded. Outdated Zim files can be removed.
-
+
{
expect(screen.getByPlaceholderText('Language')).toBeInTheDocument();
});
});
+
+// The Dashboard's "Outdated Zim Files" banner: its modal must always show a fresh scan, and say when it is empty.
+import {OutdatedZimsMessage} from './Zim';
+import {fireEvent, waitFor} from '@testing-library/react';
+import {getOutdatedZims} from '../api';
+
+jest.mock('../api', () => ({
+ ...jest.requireActual('../api'),
+ getOutdatedZims: jest.fn(),
+ deleteOutdatedZims: jest.fn(),
+}));
+
+describe('the outdated Zims banner', () => {
+ beforeEach(() => getOutdatedZims.mockReset());
+
+ it('tells the user when the live scan finds nothing to delete', async () => {
+ getOutdatedZims.mockResolvedValue({outdated: [], current: ['zims/wikipedia_en_all_maxi_2024-01.zim']});
+ render();
+
+ fireEvent.click(screen.getByRole('button', {name: 'Delete'}));
+
+ await waitFor(() => expect(screen.getByText(/No outdated Zim files were found/)).toBeInTheDocument());
+ });
+
+ it('re-scans when the modal is opened, so the list is not the one from page load', async () => {
+ getOutdatedZims.mockResolvedValue({outdated: [], current: []});
+ render();
+ await waitFor(() => expect(getOutdatedZims).toHaveBeenCalledTimes(1));
+
+ getOutdatedZims.mockResolvedValue({
+ outdated: ['zims/wikipedia_en_all_maxi_2023-12.zim'],
+ current: ['zims/wikipedia_en_all_maxi_2024-01.zim'],
+ });
+ fireEvent.click(screen.getByRole('button', {name: 'Delete'}));
+
+ await waitFor(() => expect(getOutdatedZims).toHaveBeenCalledTimes(2));
+ expect(await screen.findByText('zims/wikipedia_en_all_maxi_2023-12.zim')).toBeInTheDocument();
+ expect(screen.getByText('zims/wikipedia_en_all_maxi_2024-01.zim')).toBeInTheDocument();
+ });
+});
diff --git a/app/src/hooks/customHooks.js b/app/src/hooks/customHooks.js
index d8f9dcf1..f6ab0065 100644
--- a/app/src/hooks/customHooks.js
+++ b/app/src/hooks/customHooks.js
@@ -1981,7 +1981,7 @@ export const useOutdatedZims = () => {
localFetchOutdatedZims();
}, []);
- return {outdated, current}
+ return {outdated, current, fetchOutdatedZims: localFetchOutdatedZims}
}
export const useVINDecoder = (defaultVINNumber = '') => {
diff --git a/main.py b/main.py
index 0fd1647b..2b84c729 100755
--- a/main.py
+++ b/main.py
@@ -282,16 +282,18 @@ async def start_single_tasks(app: Sanic):
get_download_cache_config().import_config()
logger.debug('download cache config imported')
- from modules.zim.lib import flag_outdated_zim_files
- try:
- flag_outdated_zim_files()
- except Exception as e:
- logger.error('Failed to flag outdated Zims', exc_info=e)
-
logger.debug('start_single_tasks waiting for db...')
async with flags.db_up.wait_for():
logger.debug('start_single_tasks db is up')
+ # The disk scan must overwrite the DB-restored `outdated_zims` value, so restore first (idempotent), then scan.
+ from modules.zim.lib import flag_outdated_zim_files
+ try:
+ flags.init_flags()
+ flag_outdated_zim_files()
+ except Exception as e:
+ logger.error('Failed to flag outdated Zims', exc_info=e)
+
# Import configs that require the database.
if wrolpi_config.successful_import and not wrolpi_config.wrol_mode:
from wrolpi.common import import_all_db_configs
diff --git a/modules/zim/api.py b/modules/zim/api.py
index 2aaf240b..17403e66 100644
--- a/modules/zim/api.py
+++ b/modules/zim/api.py
@@ -200,9 +200,12 @@ async def get_outdated_zims(_: Request):
summary='Remove all outdated Zims, if any.'
)
async def delete_outdated_zims(_: Request):
- deleted_count = await lib.remove_outdated_zim_files()
- if deleted_count:
+ try:
+ deleted_count = await lib.remove_outdated_zim_files()
+ finally:
+ # The flag must match disk whether or not the delete succeeded.
lib.flag_outdated_zim_files()
+ if deleted_count:
Events.send_deleted(f'Deleted {deleted_count} outdated Zims')
return response.empty(HTTPStatus.NO_CONTENT)
diff --git a/modules/zim/lib.py b/modules/zim/lib.py
index abf16ad8..3d32328c 100644
--- a/modules/zim/lib.py
+++ b/modules/zim/lib.py
@@ -593,11 +593,12 @@ async def remove_outdated_zim_files(path: pathlib.Path = None) -> int:
file.unlink()
deleted_count += 1
- # Refresh synchronously to clean up DB before returning.
- await file_worker.refresh_sync(list(outdated))
+ if deleted_count:
+ # Refresh synchronously to clean up DB before returning.
+ await file_worker.refresh_sync(list(outdated))
- # Trigger Kiwix restart so the deleted zim files are no longer served.
- restart_kiwix_handler.activate_switch()
+ # Trigger Kiwix restart so the deleted zim files are no longer served.
+ restart_kiwix_handler.activate_switch()
return deleted_count
diff --git a/modules/zim/test/test_api.py b/modules/zim/test/test_api.py
index 3fe4b699..0f9d574c 100644
--- a/modules/zim/test/test_api.py
+++ b/modules/zim/test/test_api.py
@@ -5,6 +5,7 @@ import pytest
from modules.zim import lib
from modules.zim.models import Zim
+from wrolpi import flags
from wrolpi.downloader import Download
@@ -249,6 +250,23 @@ async def test_find_outdated_zim_files(test_session, test_directory, test_zim_by
assert empty.is_file()
+@pytest.mark.asyncio
+async def test_delete_outdated_zims_clears_stale_flag(test_session, test_directory, test_zim_bytes, async_client,
+ flags_lock):
+ """Deleting outdated Zims always leaves the `outdated_zims` flag matching disk, even when nothing was deleted."""
+ (test_directory / 'zims').mkdir(parents=True)
+ (test_directory / 'zims/wikipedia_en_all_maxi_2023-02.zim').write_bytes(test_zim_bytes)
+ flags.outdated_zims.set()
+
+ request, response = await async_client.get('/api/zim/outdated')
+ assert response.status_code == HTTPStatus.OK
+ assert response.json['outdated'] == []
+
+ request, response = await async_client.delete('/api/zim/outdated')
+ assert response.status_code == HTTPStatus.NO_CONTENT
+ assert not flags.outdated_zims.is_set(), 'Flag should be recomputed even when nothing was deleted'
+
+
@pytest.mark.asyncio
async def test_search_estimates(test_session, async_client, zim_factory):
zim_factory('test zim')
diff --git a/modules/zim/test/test_restart_kiwix.py b/modules/zim/test/test_restart_kiwix.py
index ad310e60..e66fdec9 100644
--- a/modules/zim/test/test_restart_kiwix.py
+++ b/modules/zim/test/test_restart_kiwix.py
@@ -128,3 +128,20 @@ async def test_remove_outdated_zim_files_triggers_restart(async_client, test_ses
# Verify the switch was activated
switches = dict(api_app.shared_ctx.switches) if api_app.shared_ctx.switches else {}
assert 'restart_kiwix' in switches
+
+
+@pytest.mark.asyncio
+async def test_remove_outdated_zim_files_no_restart_when_nothing_deleted(async_client, test_session, test_directory,
+ zim_path_factory, await_switches):
+ """Clearing a stale flag must not restart Kiwix when no file was deleted."""
+ zim_dir = test_directory / 'zims'
+ zim_dir.mkdir(exist_ok=True)
+ (zim_dir / 'wikipedia_en_all_maxi_2020-02.zim').write_bytes(zim_path_factory().read_bytes())
+
+ await await_switches()
+
+ deleted_count = await lib.remove_outdated_zim_files(zim_dir)
+
+ assert deleted_count == 0
+ switches = dict(api_app.shared_ctx.switches) if api_app.shared_ctx.switches else {}
+ assert 'restart_kiwix' not in switches