mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-29 19:36:20 -05:00
Zim/Kiwix (Wikipedia) feature
* A new zim module has been added, this module allows several things to interact with Zim files. * Allow searching of Zim files using libzim. * Allow downloading of Kiwix projects (wikipedia, wikibooks, etc) on a schedule which replaces the outdated files. * Creation of a new zim docker container which allows viewing of the Zim file contents. * This commit also adds move/rename/mkdir features in the File Browser. * File tags are preserved when moving/renaming.
This commit is contained in:
parent
cc5ab4e339
commit
03a2df217d
117 changed files with 6393 additions and 1100 deletions
|
|
@ -0,0 +1,6 @@
|
|||
from .archive import api
|
||||
from .inventory import api
|
||||
from .map import api
|
||||
from .otp import api
|
||||
from .videos import api
|
||||
from .zim import api, test
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import asyncio
|
||||
import json
|
||||
from abc import ABC
|
||||
from typing import Tuple, List
|
||||
from typing import List
|
||||
|
||||
from sqlalchemy import not_
|
||||
from sqlalchemy.orm import Session
|
||||
|
|
|
|||
|
|
@ -20,7 +20,8 @@ from wrolpi.common import get_media_directory, logger, extract_domain, chdir, es
|
|||
from wrolpi.dates import now, Seconds
|
||||
from wrolpi.db import get_db_session, get_db_curs, optional_session
|
||||
from wrolpi.errors import UnknownArchive, InvalidOrderBy
|
||||
from wrolpi.files.lib import handle_file_group_search_results, tag_names_to_sub_select
|
||||
from wrolpi.files.lib import handle_file_group_search_results
|
||||
from wrolpi.tags import tag_names_to_file_group_sub_select
|
||||
from wrolpi.vars import DOCKERIZED, PYTEST
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
|
@ -417,7 +418,7 @@ def search_archives(search_str: str, domain: str, limit: int, offset: int, order
|
|||
|
||||
if tag_names:
|
||||
# Filter all FileGroups by those that have been tagged with the provided tag names.
|
||||
tags_stmt, params_ = tag_names_to_sub_select(tag_names)
|
||||
tags_stmt, params_ = tag_names_to_file_group_sub_select(tag_names)
|
||||
params.update(params_)
|
||||
wheres.append(f'fg.id = ANY({tags_stmt})')
|
||||
|
||||
|
|
|
|||
|
|
@ -509,10 +509,10 @@ def test_refresh_archives(test_session, test_directory, test_client, make_files_
|
|||
assert response.json['file_groups'], 'No files matched "text"'
|
||||
assert response.json['file_groups'][0]['model'] == 'archive', 'Returned file was not an archive'
|
||||
assert response.json['file_groups'][0]['data'].get('readability_path') == \
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.readability.html',\
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.readability.html', \
|
||||
'Could not find readability html file'
|
||||
assert response.json['file_groups'][0]['data'].get('readability_txt_path') == \
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.readability.txt',\
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.readability.txt', \
|
||||
'Could not find readability text file containing "text"'
|
||||
assert response.json['file_groups'][0]['data']['archive_datetime'], 'Archive has no datetime'
|
||||
|
||||
|
|
|
|||
|
|
@ -3,8 +3,6 @@ from datetime import datetime
|
|||
from decimal import Decimal
|
||||
from typing import Union, Optional
|
||||
|
||||
from wrolpi.dates import from_timestamp
|
||||
|
||||
|
||||
@dataclass
|
||||
class ItemPostRequest:
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import json
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.inventory import Item
|
||||
from modules.inventory.inventory import save_item
|
||||
|
||||
|
|
@ -73,33 +75,34 @@ def test_item_api(test_session, init_test_inventory, test_client):
|
|||
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
|
||||
|
||||
|
||||
def test_inventory_api(test_session, test_client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_inventory_api(test_session, test_async_client):
|
||||
"""An Inventory can be created."""
|
||||
inventory = dict(name='foo')
|
||||
request, response = test_client.post('/api/inventory', content=json.dumps(inventory))
|
||||
request, response = await test_async_client.post('/api/inventory', content=json.dumps(inventory))
|
||||
assert response.status_code == HTTPStatus.CREATED, response.status_code
|
||||
|
||||
request, response = test_client.get('/api/inventory')
|
||||
request, response = await test_async_client.get('/api/inventory')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
inventory = response.json['inventories'][0]
|
||||
inventory_id = inventory['id']
|
||||
|
||||
request, response = test_client.get(f'/api/inventory/{inventory_id}')
|
||||
request, response = await test_async_client.get(f'/api/inventory/{inventory_id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
request, response = test_client.get('/api/inventory/categories')
|
||||
request, response = await test_async_client.get('/api/inventory/categories')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
request, response = test_client.get('/api/inventory/brands')
|
||||
request, response = await test_async_client.get('/api/inventory/brands')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
inventory = dict(name='new name')
|
||||
request, response = test_client.put(f'/api/inventory/{inventory_id}', content=json.dumps(inventory))
|
||||
request, response = await test_async_client.put(f'/api/inventory/{inventory_id}', content=json.dumps(inventory))
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.status_code
|
||||
|
||||
request, response = test_client.delete(f'/api/inventory/{inventory_id}')
|
||||
request, response = await test_async_client.delete(f'/api/inventory/{inventory_id}')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.status_code
|
||||
|
||||
request, response = test_client.get('/api/inventory')
|
||||
request, response = await test_async_client.get('/api/inventory')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert len(response.json['inventories']) == 0
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import pathlib
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Union
|
||||
|
||||
|
|
|
|||
|
|
@ -332,7 +332,8 @@ def test_channel_by_id(test_session, test_client, simple_channel, simple_video):
|
|||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
|
||||
def test_channel_crud(test_session, test_client, test_directory, test_download_manager):
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_crud(test_session, test_async_client, test_directory, test_download_manager):
|
||||
channel_directory = test_directory / 'channel directory'
|
||||
channel_directory.mkdir()
|
||||
|
||||
|
|
@ -344,15 +345,15 @@ def test_channel_crud(test_session, test_client, test_directory, test_download_m
|
|||
)
|
||||
|
||||
# Channel doesn't exist
|
||||
request, response = test_client.get('/api/videos/channels/examplechannel1')
|
||||
request, response = await test_async_client.get('/api/videos/channels/examplechannel1')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND, f'Channel exists: {response.json}'
|
||||
|
||||
# Create it
|
||||
request, response = test_client.post('/api/videos/channels', content=json.dumps(new_channel))
|
||||
request, response = await test_async_client.post('/api/videos/channels', content=json.dumps(new_channel))
|
||||
assert response.status_code == HTTPStatus.CREATED, response.json
|
||||
location = response.headers['Location']
|
||||
|
||||
request, response = test_client.get(location)
|
||||
request, response = await test_async_client.get(location)
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
created = response.json['channel']
|
||||
assert created
|
||||
|
|
@ -369,13 +370,13 @@ def test_channel_crud(test_session, test_client, test_directory, test_download_m
|
|||
f'Channel directory is absolute: {created["directory"]}'
|
||||
|
||||
# Can't create it again
|
||||
request, response = test_client.post('/api/videos/channels', content=json.dumps(new_channel))
|
||||
request, response = await test_async_client.post('/api/videos/channels', content=json.dumps(new_channel))
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
||||
def put_and_fetch(new_channel_):
|
||||
request, response = test_client.put(location, content=json.dumps(new_channel))
|
||||
async def put_and_fetch(new_channel_):
|
||||
request, response = await test_async_client.put(location, content=json.dumps(new_channel))
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.status_code
|
||||
request, response = test_client.get(location)
|
||||
request, response = await test_async_client.get(location)
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
channel = response.json['channel']
|
||||
return channel
|
||||
|
|
@ -384,7 +385,7 @@ def test_channel_crud(test_session, test_client, test_directory, test_download_m
|
|||
new_channel['name'] = 'Example Channel 2'
|
||||
new_channel['directory'] = str(new_channel['directory']) # noqa
|
||||
new_channel['download_frequency'] = 60
|
||||
channel = put_and_fetch(new_channel)
|
||||
channel = await put_and_fetch(new_channel)
|
||||
assert channel['id'] == 1
|
||||
assert channel['name'] == 'Example Channel 2'
|
||||
assert channel['directory'] == channel_directory.name
|
||||
|
|
@ -397,22 +398,22 @@ def test_channel_crud(test_session, test_client, test_directory, test_download_m
|
|||
|
||||
# Update with no download frequency.
|
||||
new_channel['download_frequency'] = None
|
||||
channel = put_and_fetch(new_channel)
|
||||
channel = await put_and_fetch(new_channel)
|
||||
assert channel['download_frequency'] is None
|
||||
# Download was deleted.
|
||||
assert len(test_download_manager.get_downloads(test_session)) == 0
|
||||
|
||||
# Can't update channel that doesn't exist
|
||||
request, response = test_client.put('/api/videos/channels/doesnt_exist',
|
||||
content=json.dumps(new_channel))
|
||||
request, response = await test_async_client.put('/api/videos/channels/doesnt_exist',
|
||||
content=json.dumps(new_channel))
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
# Delete the new channel
|
||||
request, response = test_client.delete(location)
|
||||
request, response = await test_async_client.delete(location)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# Cant delete it again
|
||||
request, response = test_client.delete(location)
|
||||
request, response = await test_async_client.delete(location)
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
|
|
@ -433,8 +434,9 @@ def test_channel_creation_with_download(test_client, test_session, test_director
|
|||
assert download.sub_downloader == 'video'
|
||||
|
||||
|
||||
def test_change_channel_url(test_client, test_session, test_download_manager, download_channel,
|
||||
test_download_manager_config):
|
||||
@pytest.mark.asyncio
|
||||
async def test_change_channel_url(test_async_client, test_session, test_download_manager, download_channel,
|
||||
test_download_manager_config):
|
||||
# Change the Channel's URL.
|
||||
download_channel.update({'url': 'https://example.com/new-url'})
|
||||
test_session.commit()
|
||||
|
|
|
|||
|
|
@ -1,14 +1,10 @@
|
|||
import asyncio
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.videos import schema
|
||||
from modules.videos.channel import lib
|
||||
from modules.videos.lib import save_channels_config, import_channels_config
|
||||
from modules.videos.models import Channel, Video
|
||||
from modules.videos.models import Channel
|
||||
from wrolpi.errors import UnknownChannel
|
||||
from wrolpi.files.lib import refresh_files
|
||||
|
||||
|
||||
@pytest.mark.parametrize('params', [
|
||||
|
|
|
|||
|
|
@ -1,8 +1,3 @@
|
|||
import pytest
|
||||
|
||||
from modules.videos import Channel
|
||||
|
||||
|
||||
def test_delete_channel_no_url(test_session, test_client, channel_factory):
|
||||
"""
|
||||
A Channel can be deleted even if it has no URL.
|
||||
|
|
|
|||
|
|
@ -4,14 +4,13 @@ import pathlib
|
|||
import re
|
||||
import traceback
|
||||
from abc import ABC
|
||||
from typing import Tuple, List, Optional, Dict
|
||||
from typing import Tuple, List, Dict
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import yt_dlp.utils
|
||||
from sqlalchemy.orm import Session
|
||||
from yt_dlp import YoutubeDL
|
||||
from yt_dlp.extractor import YoutubeTabIE # noqa
|
||||
from yt_dlp.utils import UnsupportedError, DownloadError
|
||||
|
||||
from wrolpi.cmd import YT_DLP_BIN
|
||||
from wrolpi.common import logger, get_media_directory, escape_file_name, resolve_generators, background_task
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import contextlib
|
||||
import datetime
|
||||
import functools
|
||||
import html
|
||||
import pathlib
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import pathlib
|
|||
from pathlib import Path
|
||||
from typing import Optional, Dict, List, Union
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Boolean, JSON, Date, ARRAY, ForeignKey, BigInteger, any_
|
||||
from sqlalchemy import Column, Integer, String, Boolean, JSON, Date, ARRAY, ForeignKey, BigInteger
|
||||
from sqlalchemy.orm import relationship, Session, deferred
|
||||
from sqlalchemy.orm.collections import InstrumentedList
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from datetime import date
|
||||
from typing import List, Optional
|
||||
|
||||
from modules.videos.video.lib import DEFAULT_VIDEO_ORDER, VIDEO_QUERY_LIMIT
|
||||
|
|
|
|||
|
|
@ -2,14 +2,13 @@ import json
|
|||
from http import HTTPStatus
|
||||
from pathlib import Path
|
||||
|
||||
import mock.mock
|
||||
import pytest
|
||||
|
||||
from modules.videos.models import Video, Channel
|
||||
from modules.videos.video import lib as video_lib
|
||||
from wrolpi.db import get_db_curs
|
||||
from wrolpi.downloader import DownloadFrequency, Download
|
||||
from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix
|
||||
from wrolpi.files.lib import refresh_files
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
|
||||
|
|
@ -53,12 +52,12 @@ def test_refresh_videos(test_client, test_session, test_directory, simple_channe
|
|||
with_info_json=True, with_poster_ext='jpg')
|
||||
test_session.commit()
|
||||
video1.file_group.size = video1.file_group.data = None
|
||||
video1.file_group.files = list()
|
||||
video1.file_group.paths = list()
|
||||
# video2 is in the test directory.
|
||||
video2 = video_factory(channel_id=simple_channel.id, with_video_file=True, with_info_json=True,
|
||||
with_poster_ext='jpg')
|
||||
video2.file_group.data = None
|
||||
video2.file_group.files = []
|
||||
video2.file_group.paths = []
|
||||
test_session.commit()
|
||||
|
||||
assert not video1.file_group.size, 'video1 should not have size during creation'
|
||||
|
|
|
|||
|
|
@ -1,17 +1,13 @@
|
|||
import pathlib
|
||||
import subprocess
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
from typing import List
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
import pytz
|
||||
from PIL import Image
|
||||
|
||||
from modules.videos.models import Channel, Video
|
||||
from wrolpi.common import get_absolute_media_path, sanitize_link
|
||||
from wrolpi.dates import now
|
||||
from wrolpi.common import get_absolute_media_path
|
||||
from wrolpi.downloader import Download, DownloadFrequency
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
from .. import common
|
||||
|
|
|
|||
|
|
@ -158,6 +158,7 @@ async def test_download_video_tags(test_session, video_download_manager, video_f
|
|||
|
||||
|
||||
@skip_circleci
|
||||
@pytest.mark.skip # TODO this test fails when running multiple tests.
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_channel(test_session, simple_channel, video_download_manager, video_file,
|
||||
mock_video_extract_info, mock_video_prepare_filename,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import pytest
|
||||
|
||||
from modules.videos.models import Video
|
||||
from wrolpi.dates import now
|
||||
from wrolpi.errors import FileGroupIsTagged
|
||||
from wrolpi.files import lib as files_lib
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ from modules.videos.models import Video
|
|||
from wrolpi.common import run_after, logger
|
||||
from wrolpi.db import get_db_session, optional_session
|
||||
from wrolpi.errors import UnknownVideo
|
||||
from wrolpi.files.lib import handle_file_group_search_results, tag_names_to_sub_select
|
||||
from wrolpi.files.lib import handle_file_group_search_results, tag_names_to_file_group_sub_select
|
||||
from ..lib import save_channels_config
|
||||
|
||||
logger.getChild(__name__)
|
||||
|
|
@ -103,7 +103,7 @@ def search_videos(
|
|||
|
||||
if tag_names:
|
||||
# Filter all FileGroups by those that have been tagged with the provided tag names.
|
||||
tags_stmt, params_ = tag_names_to_sub_select(tag_names)
|
||||
tags_stmt, params_ = tag_names_to_file_group_sub_select(tag_names)
|
||||
params.update(params_)
|
||||
wheres.append(f'fg.id = ANY({tags_stmt})')
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ from modules.videos.models import Video
|
|||
from modules.videos.video.lib import get_video_for_app
|
||||
from wrolpi.dates import now
|
||||
from wrolpi.errors import API_ERRORS, WROLModeEnabled
|
||||
from wrolpi.root_api import api_app
|
||||
|
||||
|
||||
def test_get_video_prev_next(test_session, channel_factory, video_factory):
|
||||
|
|
@ -121,7 +120,10 @@ def test_video_delete(test_client, test_session, test_directory, channel_factory
|
|||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
||||
|
||||
def test_wrol_mode(test_directory, simple_channel, simple_video, wrol_mode_fixture, test_download_manager, tag_factory):
|
||||
@pytest.mark.asyncio
|
||||
async def test_wrol_mode(test_async_client, test_directory, simple_channel, simple_video, wrol_mode_fixture,
|
||||
test_download_manager,
|
||||
tag_factory):
|
||||
"""Many methods are blocked when WROL Mode is enabled."""
|
||||
channel = dumps(dict(name=simple_channel.name, directory=str(simple_channel.directory)))
|
||||
tag = tag_factory()
|
||||
|
|
@ -129,32 +131,32 @@ def test_wrol_mode(test_directory, simple_channel, simple_video, wrol_mode_fixtu
|
|||
wrol_mode_fixture(True)
|
||||
|
||||
# Can't create, update, or delete a channel.
|
||||
_, resp = api_app.test_client.post('/api/videos/channels', content=channel)
|
||||
_, resp = await test_async_client.post('/api/videos/channels', content=channel)
|
||||
assert resp.status_code == HTTPStatus.FORBIDDEN
|
||||
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
|
||||
_, resp = api_app.test_client.put(f'/api/videos/channels/{simple_channel.id}', content=channel)
|
||||
_, resp = await test_async_client.put(f'/api/videos/channels/{simple_channel.id}', content=channel)
|
||||
assert resp.status_code == HTTPStatus.FORBIDDEN
|
||||
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
|
||||
_, resp = api_app.test_client.delete(f'/api/videos/channels/{simple_channel.id}')
|
||||
_, resp = await test_async_client.delete(f'/api/videos/channels/{simple_channel.id}')
|
||||
assert resp.status_code == HTTPStatus.FORBIDDEN
|
||||
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
|
||||
|
||||
# Can't delete a video
|
||||
_, resp = api_app.test_client.delete(f'/api/videos/video/{simple_video.id}')
|
||||
_, resp = await test_async_client.delete(f'/api/videos/video/{simple_video.id}')
|
||||
assert resp.status_code == HTTPStatus.FORBIDDEN
|
||||
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
|
||||
|
||||
# Can't refresh or download
|
||||
_, resp = api_app.test_client.post('/api/files/refresh')
|
||||
_, resp = await test_async_client.post('/api/files/refresh')
|
||||
assert resp.status_code == HTTPStatus.FORBIDDEN
|
||||
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
|
||||
_, resp = api_app.test_client.post(f'/api/videos/channels/download/{simple_channel.id}')
|
||||
_, resp = await test_async_client.post(f'/api/videos/channels/download/{simple_channel.id}')
|
||||
assert resp.status_code == HTTPStatus.FORBIDDEN
|
||||
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
|
||||
|
||||
# THE REST OF THESE METHODS ARE ALLOWED
|
||||
content = dict(video_id=simple_video.id, tag_name=tag.name)
|
||||
_, resp = api_app.test_client.post('/api/videos/tag', content=json.dumps(content))
|
||||
_, resp = await test_async_client.post('/api/videos/tag', content=json.dumps(content))
|
||||
assert resp.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
assert test_download_manager.stopped.is_set()
|
||||
|
|
|
|||
3
modules/zim/__init__.py
Normal file
3
modules/zim/__init__.py
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
from .downloader import KiwixCatalogDownloader # noqa
|
||||
|
||||
__all__ = []
|
||||
156
modules/zim/api.py
Normal file
156
modules/zim/api.py
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
import urllib.parse
|
||||
from http import HTTPStatus
|
||||
|
||||
from sanic import Request, response
|
||||
from sanic_ext import validate
|
||||
from sanic_ext.extensions.openapi import openapi
|
||||
|
||||
from wrolpi import lang
|
||||
from wrolpi.common import logger
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.downloader import download_manager
|
||||
from wrolpi.events import Events
|
||||
from wrolpi.root_api import get_blueprint, json_response
|
||||
from . import lib, schema
|
||||
|
||||
bp = get_blueprint('Zim', '/api/zim')
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
||||
@bp.get('/')
|
||||
@openapi.definition(
|
||||
summary='List all known Zim files',
|
||||
response=schema.GetZimsResponse,
|
||||
)
|
||||
async def get_zims(_: Request):
|
||||
with get_db_session() as session:
|
||||
zims = lib.get_zims(session=session)
|
||||
resp = {
|
||||
'zims': [i.__json__() for i in zims],
|
||||
}
|
||||
return json_response(resp)
|
||||
|
||||
|
||||
@bp.delete('/<zim_ids:[0-9,]+>')
|
||||
@openapi.definition(
|
||||
summary='Delete all Zim files',
|
||||
)
|
||||
async def delete_zims(_: Request, zim_ids: str):
|
||||
zim_ids = [int(i) for i in zim_ids.split(',')]
|
||||
lib.delete_zims(zim_ids)
|
||||
return response.empty()
|
||||
|
||||
|
||||
@bp.post('/search/<zim_id:[0-9]+>')
|
||||
@openapi.definition(
|
||||
summary='Search all entries of a Zim',
|
||||
body=schema.ZimSearchRequest,
|
||||
response=schema.ZimSearchResponse,
|
||||
)
|
||||
@validate(schema.ZimSearchRequest)
|
||||
async def search_zim(_: Request, zim_id: int, body: schema.ZimSearchRequest):
|
||||
headlines = lib.headline_zim(body.search_str, zim_id, tag_names=body.tag_names, offset=body.offset,
|
||||
limit=body.limit)
|
||||
return json_response({'zim': headlines})
|
||||
|
||||
|
||||
@bp.get('/<zim_id:[0-9]+>/entry/<zim_path:[ -~/]*>')
|
||||
@openapi.definition(
|
||||
summary='Read the entry at `zim_path` from the Zim file',
|
||||
)
|
||||
async def get_zim_entry(_: Request, zim_id: int, zim_path: str):
|
||||
zim_path = urllib.parse.unquote(zim_path)
|
||||
entry = lib.get_entry(zim_path, zim_id=zim_id)
|
||||
content = bytes(entry.get_item().content)
|
||||
try:
|
||||
resp = response.html(content.decode('UTF-8'))
|
||||
logger.debug(f'Returning ZIM HTML response {repr(str(zim_path))}')
|
||||
except UnicodeDecodeError:
|
||||
resp = response.raw(content)
|
||||
logger.debug(f'Returning ZIM raw response {repr(str(zim_path))}')
|
||||
|
||||
return resp
|
||||
|
||||
|
||||
@bp.post('/tag')
|
||||
@openapi.definition(
|
||||
summary='Tag a Zim entry',
|
||||
body=schema.TagZimEntry,
|
||||
)
|
||||
@validate(schema.TagZimEntry)
|
||||
async def post_zim_tag(_: Request, body: schema.TagZimEntry):
|
||||
await lib.add_tag(body.tag_name, body.zim_id, body.zim_entry)
|
||||
return response.empty(HTTPStatus.CREATED)
|
||||
|
||||
|
||||
@bp.post('/untag')
|
||||
@openapi.definition(
|
||||
summary='Untag a Zim entry',
|
||||
body=schema.TagZimEntry,
|
||||
)
|
||||
@validate(schema.TagZimEntry)
|
||||
async def post_zim_untag(_: Request, body: schema.TagZimEntry):
|
||||
await lib.untag(body.tag_name, body.zim_id, body.zim_entry)
|
||||
return response.empty(HTTPStatus.NO_CONTENT)
|
||||
|
||||
|
||||
@bp.get('/subscribe')
|
||||
@openapi.definition(
|
||||
summary='Retrieve Zim subscriptions',
|
||||
response=schema.ZimSubscriptions,
|
||||
)
|
||||
async def get_zim_subscriptions(_: Request):
|
||||
catalog = lib.get_kiwix_catalog()
|
||||
with get_db_session() as session:
|
||||
subscriptions = {i: j.__json__() for i, j in lib.get_kiwix_subscriptions(session).items()}
|
||||
resp = dict(
|
||||
catalog=catalog,
|
||||
iso_639_codes=lang.ISO_639_CODES,
|
||||
subscriptions=subscriptions,
|
||||
)
|
||||
return json_response(resp)
|
||||
|
||||
|
||||
@bp.post('/subscribe')
|
||||
@openapi.definition(
|
||||
summary='Subscribe to a particular Kiwix Zim',
|
||||
body=schema.TagZimSubscribe,
|
||||
)
|
||||
@validate(schema.TagZimSubscribe)
|
||||
async def post_zim_subscribe(_: Request, body: schema.TagZimSubscribe):
|
||||
await lib.subscribe(body.name, body.language)
|
||||
if download_manager.disabled.is_set() or download_manager.stopped.is_set():
|
||||
# Downloads are disabled, warn the user.
|
||||
Events.send_downloads_disabled('Download created. But, downloads are disabled.')
|
||||
return response.empty(HTTPStatus.CREATED)
|
||||
|
||||
|
||||
@bp.delete('/subscribe/<subscription_id:[0-9]+>')
|
||||
@openapi.definition(
|
||||
summary='Unsubscribe to a particular Kiwix Zim',
|
||||
)
|
||||
async def delete_zim_subscription(_: Request, subscription_id: int):
|
||||
await lib.unsubscribe(subscription_id)
|
||||
return response.empty(HTTPStatus.NO_CONTENT)
|
||||
|
||||
|
||||
@bp.get('/outdated')
|
||||
@openapi.definition(
|
||||
summary='Returns the outdated and current Zim files',
|
||||
response=schema.OutdatedZims,
|
||||
)
|
||||
async def get_outdated_zims(_: Request):
|
||||
outdated, current = lib.find_outdated_zim_files()
|
||||
d = dict(outdated=outdated, current=current)
|
||||
return json_response(d)
|
||||
|
||||
|
||||
@bp.delete('/outdated')
|
||||
@openapi.definition(
|
||||
summary='Remove all outdated Zims, if any.'
|
||||
)
|
||||
async def delete_outdated_zims(_: Request):
|
||||
await lib.remove_outdated_zim_files()
|
||||
lib.flag_outdated_zim_files()
|
||||
return response.empty(HTTPStatus.NO_CONTENT)
|
||||
130
modules/zim/conftest.py
Normal file
130
modules/zim/conftest.py
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
from http import HTTPStatus
|
||||
from itertools import zip_longest
|
||||
from typing import List, Dict
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from mock import mock
|
||||
|
||||
from modules.zim.downloader import KiwixCatalogDownloader, KiwixZimDownloader
|
||||
from modules.zim.models import Zim
|
||||
from wrolpi.common import DownloadFileInfo
|
||||
from wrolpi.downloader import DownloadManager
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kiwix_download_manager(test_download_manager) -> DownloadManager:
|
||||
kiwix_downloader = KiwixCatalogDownloader()
|
||||
kiwix_zim_downloader = KiwixZimDownloader()
|
||||
|
||||
test_download_manager.register_downloader(kiwix_downloader)
|
||||
test_download_manager.register_downloader(kiwix_zim_downloader)
|
||||
|
||||
yield test_download_manager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kiwix_download_zim(test_directory, kiwix_download_manager, test_zim_bytes):
|
||||
async def do_download(download_info: DownloadFileInfo = None, expected_url: str = None,
|
||||
download_file_side_effect=None, hrefs: List[str] = None):
|
||||
async def _download_file(url: str, output_path: pathlib.Path = None, info: DownloadFileInfo = None):
|
||||
if expected_url:
|
||||
assert url == expected_url
|
||||
if download_info:
|
||||
assert info == download_info
|
||||
output_path.write_bytes(test_zim_bytes)
|
||||
|
||||
with mock.patch('modules.zim.downloader.fetch_hrefs') as mock_fetch_hrefs, \
|
||||
mock.patch('modules.zim.downloader.get_download_info') as mock_get_download_info, \
|
||||
mock.patch('modules.zim.downloader.download_file') as mock_download_file:
|
||||
# Fake the download, but make sure it is called correctly. Also creates a Zim file at the output_path.
|
||||
mock_download_file.side_effect = download_file_side_effect or _download_file
|
||||
# These are the links in the parent directory of the url.
|
||||
mock_fetch_hrefs.return_value = hrefs or ['?C=N;O=D', '?C=M;O=A', '?C=S;O=A', '?C=D;O=A', '/zim/',
|
||||
'wikipedia_es_all_maxi_2023-05.zim',
|
||||
'wikipedia_es_all_maxi_2023-06.zim',
|
||||
'wikipedia_es_all_nopic_2023-05.zim',
|
||||
'wikipedia_es_all_nopic_2023-06.zim']
|
||||
# This is the DownloadInfo for the latest Zim file that was selected.
|
||||
mock_get_download_info.return_value = download_info or DownloadFileInfo(
|
||||
status=HTTPStatus.OK,
|
||||
name='wikipedia_es_all_maxi_2023-06.zim',
|
||||
size=len(test_zim_bytes),
|
||||
)
|
||||
|
||||
await kiwix_download_manager.wait_for_all_downloads()
|
||||
# Async download are hard to test, sleep to let tasks finish.
|
||||
await asyncio.sleep(0.1)
|
||||
await kiwix_download_manager.wait_for_all_downloads()
|
||||
|
||||
return do_download
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def test_zim_bytes():
|
||||
"""Read the byte contents of the test Zim (test/zim.zim)."""
|
||||
path = PROJECT_DIR / 'test/zim.zim'
|
||||
return path.read_bytes()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def zim_path_factory(test_zim_bytes, test_directory):
|
||||
"""Copy the test Zim into the test directory."""
|
||||
|
||||
def _(name: str = None) -> pathlib.Path:
|
||||
name = name if name else f'{uuid4()}.zim'
|
||||
path = test_directory / name
|
||||
path.write_bytes(test_zim_bytes)
|
||||
return path
|
||||
|
||||
return _
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_zim(test_session, zim_path_factory, test_directory) -> Zim:
|
||||
zim = Zim.from_paths(test_session, zim_path_factory())
|
||||
return zim
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def zim_factory(test_session, zim_path_factory, test_directory):
|
||||
def _(name: str) -> Zim:
|
||||
zim = Zim.from_paths(test_session, zim_path_factory(name))
|
||||
return zim
|
||||
|
||||
return _
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def assert_zim_search(test_client, test_directory):
|
||||
from http import HTTPStatus
|
||||
|
||||
def _(search_str: str, zim_id: int, expected: Dict, tag_names: List[str] = [],
|
||||
expected_status_code: int = HTTPStatus.OK):
|
||||
content = dict(search_str=search_str, tag_names=tag_names)
|
||||
assert isinstance(zim_id, int), 'This fixture only supports Zim ids of type integer'
|
||||
request, response = test_client.post(f'api/zim/search/{zim_id}', content=json.dumps(content))
|
||||
assert response.status_code == expected_status_code
|
||||
|
||||
result = response.json['zim']
|
||||
|
||||
if path := expected.get('path'):
|
||||
assert result['path'] == str(path.relative_to(test_directory))
|
||||
|
||||
if estimate := expected.get('estimate'):
|
||||
assert result['estimate'] == estimate
|
||||
|
||||
for response_entry, expected_entry in zip_longest(result['search'], expected['search']):
|
||||
if response_entry and not expected_entry:
|
||||
raise AssertionError(f'Response contained more entries than expected: {response_entry}')
|
||||
elif not response_entry and expected_entry:
|
||||
raise AssertionError(f'Response did not contain the expected entry: {expected_entry}')
|
||||
assert response_entry['path'] == expected_entry['path']
|
||||
assert response_entry['headline'] == expected_entry['headline']
|
||||
assert response_entry['rank'] == expected_entry['rank']
|
||||
|
||||
return _
|
||||
115
modules/zim/downloader.py
Normal file
115
modules/zim/downloader.py
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
from http import HTTPStatus
|
||||
from typing import List
|
||||
|
||||
import bs4
|
||||
|
||||
from modules.zim import lib
|
||||
from wrolpi.common import logger, aiohttp_get, get_download_info, download_file, background_task
|
||||
from wrolpi.downloader import Downloader, Download, DownloadResult
|
||||
|
||||
__all__ = ['KiwixCatalogDownloader', 'KiwixZimDownloader', 'kiwix_zim_downloader', 'kiwix_catalog_downloader']
|
||||
|
||||
from wrolpi.files.lib import refresh_files
|
||||
from wrolpi.vars import PYTEST
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
||||
async def fetch_hrefs(url: str) -> List[str]:
|
||||
content, status = await aiohttp_get(url, timeout=20)
|
||||
if status != HTTPStatus.OK:
|
||||
raise RuntimeError(f'Failed to fetch file catalog')
|
||||
|
||||
soup = bs4.BeautifulSoup(content, 'html.parser')
|
||||
downloads = list()
|
||||
for a_ in soup.find_all('a'):
|
||||
downloads.append(a_['href'])
|
||||
return downloads
|
||||
|
||||
|
||||
class KiwixCatalogDownloader(Downloader):
|
||||
"""
|
||||
Downloads the catalog of Zim files from Kiwix. Searches for the latest Zim that matches the provided URL.
|
||||
|
||||
If a newer file exists and has not been downloaded, schedule a Download.
|
||||
"""
|
||||
|
||||
name = 'kiwix_catalog'
|
||||
listable = False
|
||||
|
||||
async def do_download(self, download: Download) -> DownloadResult:
|
||||
url = download.url
|
||||
|
||||
# Get the parent directory of the file to be downloaded
|
||||
*parents, name = url.split('/')
|
||||
parent_url = '/'.join(parents)
|
||||
|
||||
# Find the latest Zim that has the correct name.
|
||||
downloadable_files = await fetch_hrefs(parent_url)
|
||||
matching_zims = sorted([i for i in downloadable_files if i.startswith(name) and i.endswith('.zim')])
|
||||
if not matching_zims:
|
||||
return DownloadResult(success=False, error=f'No Zim files match {str(repr(url))}')
|
||||
|
||||
logger.debug(f'Found matching Zims: {matching_zims}')
|
||||
latest_zim = f'{parent_url}/{matching_zims[-1]}'
|
||||
|
||||
return DownloadResult(
|
||||
success=True,
|
||||
downloads=[latest_zim, ],
|
||||
)
|
||||
|
||||
|
||||
kiwix_catalog_downloader = KiwixCatalogDownloader()
|
||||
|
||||
|
||||
class KiwixZimDownloader(Downloader):
|
||||
"""Downloads a Zim file to the zim directory."""
|
||||
name = 'kiwix_zim'
|
||||
listable = False
|
||||
|
||||
async def do_download(self, download: Download) -> DownloadResult:
|
||||
url = download.url
|
||||
|
||||
download_info = await get_download_info(url)
|
||||
|
||||
zim_directory = lib.get_zim_directory()
|
||||
zim_directory.mkdir(parents=True, exist_ok=True)
|
||||
output_path = zim_directory / f'{download_info.name}'
|
||||
|
||||
if output_path.is_file():
|
||||
output_size = output_path.stat().st_size
|
||||
if download_info.size and download_info.size == output_size:
|
||||
# File is already downloaded.
|
||||
return DownloadResult(success=True)
|
||||
|
||||
logger.info(f'Downloading Zim {url} to {output_path} of size {download_info.size}')
|
||||
await download_file(url, output_path=output_path, info=download_info)
|
||||
|
||||
# Notify the maintainer if outdated Zim files are lying around.
|
||||
lib.flag_outdated_zim_files()
|
||||
# Notify the maintainer to restart Kiwix container.
|
||||
lib.flag_kiwix_restart()
|
||||
|
||||
output_size = output_path.stat().st_size
|
||||
if download_info.size and output_size != download_info.size:
|
||||
return DownloadResult(
|
||||
success=False,
|
||||
error=f'Download size does not match: {output_size} != {download_info.size}')
|
||||
|
||||
return_code = await lib.check_zim(output_path)
|
||||
if return_code == 127:
|
||||
logger.warning(f'Not validating {output_path} because zimcheck is not installed')
|
||||
elif return_code > 0:
|
||||
return DownloadResult(success=False, error=f'Zim file is invalid')
|
||||
|
||||
# Add the new Zim to the FileGroups, model it.
|
||||
if PYTEST:
|
||||
await refresh_files([output_path, ])
|
||||
else:
|
||||
background_task(refresh_files([output_path, ]))
|
||||
|
||||
# Location is just the generic Kiwix viewer.
|
||||
return DownloadResult(success=True, location='/zim')
|
||||
|
||||
|
||||
kiwix_zim_downloader = KiwixZimDownloader()
|
||||
134
modules/zim/kiwix.py
Normal file
134
modules/zim/kiwix.py
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
WIKIPEDIA_LANGUAGES = ['ab', 'ace', 'ady', 'af', 'alt', 'am', 'ami', 'an', 'ang', 'anp', 'ar', 'arc', 'ary', 'arz',
|
||||
'as', 'ast', 'atj', 'av', 'avk', 'awa', 'ay', 'az', 'azb', 'ba', 'ban', 'bar', 'bcl', 'be',
|
||||
'be-tarask', 'bg', 'bho', 'bi', 'bjn', 'blk', 'bm', 'bn', 'bo', 'bpy', 'br', 'bs', 'bug', 'bxr',
|
||||
'ca', 'cbk', 'cdo', 'ce', 'ceb', 'ch', 'chr', 'chy', 'ckb', 'co', 'cr', 'crh', 'cs', 'csb', 'cu',
|
||||
'cv', 'cy', 'da', 'dag', 'de', 'din', 'diq', 'dsb', 'dty', 'dv', 'dz', 'ee', 'el', 'eml', 'en',
|
||||
'eo', 'es', 'et', 'eu', 'ext', 'fa', 'fat', 'ff', 'fi', 'fj', 'fo', 'fr', 'frp', 'frr', 'fur',
|
||||
'fy', 'ga', 'gag', 'gan', 'gcr', 'gd', 'gl', 'glk', 'gn', 'gom', 'gor', 'got', 'gsw', 'gu',
|
||||
'guc', 'gur', 'guw', 'gv', 'ha', 'hak', 'haw', 'he', 'hi', 'hif', 'hr', 'hsb', 'ht', 'hu', 'hy',
|
||||
'hyw', 'ia', 'id', 'ie', 'ig', 'ik', 'ilo', 'inh', 'io', 'is', 'it', 'iu', 'ja', 'jam', 'jbo',
|
||||
'jv', 'ka', 'kaa', 'kab', 'kbd', 'kbp', 'kcg', 'kg', 'ki', 'kk', 'kl', 'km', 'kn', 'ko', 'koi',
|
||||
'krc', 'ks', 'ksh', 'ku', 'kv', 'kw', 'ky', 'la', 'lad', 'lb', 'lbe', 'lez', 'lfn', 'lg', 'li',
|
||||
'lij', 'lld', 'lmo', 'ln', 'lo', 'lt', 'ltg', 'lv', 'lzh', 'mad', 'mai', 'map-bms', 'mdf', 'mg',
|
||||
'mhr', 'mi', 'min', 'mk', 'ml', 'mn', 'mni', 'mnw', 'mr', 'mrj', 'ms', 'mt', 'mwl', 'my', 'myv',
|
||||
'mzn', 'na', 'nah', 'nan', 'nap', 'nb', 'nds', 'nds-nl', 'ne', 'new', 'nia', 'nl', 'nn', 'nov',
|
||||
'nrm', 'nso', 'nv', 'ny', 'oc', 'olo', 'om', 'or', 'os', 'pa', 'pag', 'pam', 'pap', 'pcd', 'pdc',
|
||||
'pfl', 'pi', 'pih', 'pl', 'pms', 'pnb', 'pnt', 'ps', 'pt', 'pwn', 'qu', 'rm', 'rmy', 'rn', 'ro',
|
||||
'roa-tara', 'ru', 'rue', 'rup', 'rw', 'sa', 'sah', 'sat', 'sc', 'scn', 'sco', 'sd', 'se', 'sg',
|
||||
'sgs', 'sh', 'shi', 'shn', 'si', 'sk', 'skr', 'sl', 'sm', 'smn', 'sn', 'so', 'sq', 'sr', 'srn',
|
||||
'ss', 'st', 'stq', 'su', 'sv', 'sw', 'szl', 'szy', 'ta', 'tay', 'tcy', 'te', 'tet', 'tg', 'th',
|
||||
'ti', 'tk', 'tl', 'tn', 'to', 'tpi', 'tr', 'trv', 'ts', 'tt', 'tum', 'tw', 'ty', 'tyv', 'udm',
|
||||
'ug', 'uk', 'ur', 'uz', 've', 'vec', 'vep', 'vi', 'vls', 'vo', 'vro', 'wa', 'war', 'wo', 'wuu',
|
||||
'xal', 'xh', 'xmf', 'yi', 'yo', 'yue', 'za', 'zea', 'zh', 'zu']
|
||||
|
||||
WIKITIONARY_LANGUAGES = ['af', 'am', 'an', 'ang', 'ar', 'ast', 'ay', 'az', 'be', 'bg', 'bn', 'br', 'bs', 'ca', 'chr',
|
||||
'co', 'cs', 'csb', 'cy', 'da', 'de', 'dv', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fa', 'fi',
|
||||
'fj', 'fo', 'fr', 'fy', 'ga', 'gd', 'gl', 'gn', 'gu', 'guw', 'gv', 'he', 'hi', 'hif', 'hr',
|
||||
'hsb', 'hu', 'hy', 'ia', 'id', 'ie', 'io', 'is', 'it', 'iu', 'ja', 'jbo', 'jv', 'ka', 'kk',
|
||||
'kl', 'km', 'kn', 'ko', 'ks', 'ku', 'kw', 'ky', 'la', 'lb', 'li', 'ln', 'lo', 'lt', 'lv', 'mg',
|
||||
'mi', 'mk', 'ml', 'mn', 'mr', 'ms', 'mt', 'my', 'na', 'nah', 'nan', 'nb', 'nds', 'ne', 'nl',
|
||||
'nn', 'oc', 'or', 'pa', 'pl', 'pnb', 'ps', 'pt', 'qu', 'ro', 'ru', 'rup', 'rw', 'sa', 'scn',
|
||||
'sd', 'sg', 'sh', 'si', 'sk', 'sl', 'sm', 'so', 'sq', 'sr', 'ss', 'st', 'su', 'sv', 'sw', 'ta',
|
||||
'te', 'tg', 'th', 'ti', 'tk', 'tl', 'tn', 'tpi', 'tr', 'ts', 'tt', 'ug', 'uk', 'ur', 'uz',
|
||||
'vec', 'vi', 'vo', 'wa', 'wo', 'yi', 'zh', 'zu']
|
||||
|
||||
WIKIBOOKS_LANGAUGES = ['af', 'ar', 'az', 'ba', 'be', 'bg', 'bn', 'bs', 'ca', 'cs', 'cv', 'cy', 'da', 'de', 'el', 'en',
|
||||
'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fr', 'fy', 'gl', 'he', 'hi', 'hr', 'hu', 'hy', 'ia', 'id',
|
||||
'is', 'it', 'ja', 'ka', 'kk', 'km', 'ko', 'ku', 'ky', 'la', 'li', 'lt', 'mg', 'mk', 'ml', 'mr',
|
||||
'ms', 'nb', 'ne', 'nl', 'oc', 'pa', 'pl', 'pt', 'ro', 'ru', 'sa', 'si', 'sk', 'sl', 'sq', 'sr',
|
||||
'sv', 'ta', 'te', 'tg', 'th', 'tl', 'tr', 'tt', 'uk', 'ur', 'vi', 'zh']
|
||||
|
||||
KIWIX_CATALOG = [
|
||||
{
|
||||
'name': 'Wikibooks (with images)',
|
||||
'languages': WIKIBOOKS_LANGAUGES,
|
||||
'size': 4.3 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Wikibooks (no images)',
|
||||
'languages': WIKIBOOKS_LANGAUGES,
|
||||
'size': 3.4 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Wikipedia (with images)',
|
||||
'languages': WIKIPEDIA_LANGUAGES,
|
||||
'size': 94 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Wikipedia (mini)',
|
||||
'languages': WIKIPEDIA_LANGUAGES,
|
||||
'size': 13 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Wikipedia (no images)',
|
||||
'languages': WIKIPEDIA_LANGUAGES,
|
||||
'size': 50 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Wikiversity (with images)',
|
||||
'languages': ['ar', 'cs', 'de', 'el', 'en', 'es', 'fi', 'fr', 'hi', 'it', 'ja', 'ko', 'pt', 'ru', 'sl', 'sv',
|
||||
'zh'],
|
||||
'size': 2.3 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Wikiversity (no images)',
|
||||
'languages': ['ar', 'cs', 'de', 'el', 'en', 'es', 'fi', 'fr', 'hi', 'it', 'ja', 'ko', 'pt', 'ru', 'sl', 'sv',
|
||||
'zh'],
|
||||
'size': 1.8 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Wikitionary (no images)',
|
||||
'languages': WIKITIONARY_LANGUAGES,
|
||||
'size': 7.3 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Wikitionary (with images)',
|
||||
'languages': WIKITIONARY_LANGUAGES,
|
||||
'size': 8.0 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Wikisource',
|
||||
'languages': ['ang', 'ar', 'as', 'az', 'be', 'bg', 'bn', 'br', 'bs', 'ca', 'cs', 'cy', 'da', 'de', 'el', 'en',
|
||||
'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fo', 'fr', 'gl', 'gu', 'he', 'hr', 'ht', 'hu', 'hy', 'id',
|
||||
'is', 'it', 'ja', 'kn', 'ko', 'la', 'li', 'lt', 'mk', 'ml', 'mr', 'nan', 'nb', 'nl', 'or', 'pa',
|
||||
'pl', 'pms', 'pt', 'ro', 'ru', 'sa', 'sah', 'sk', 'sl', 'sr', 'sv', 'ta', 'te', 'th', 'tr', 'uk',
|
||||
'vec', 'vi', 'yi', 'zh', 'zh-min-nan'],
|
||||
'size': 16 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Raspberry Pi (Stack Exchange)',
|
||||
'languages': ['en'],
|
||||
'size': 300 * 1048576,
|
||||
},
|
||||
{
|
||||
'name': 'Vikidia',
|
||||
'languages': ['ca', 'en', 'es', 'eu', 'fr', 'it', 'ru', 'scn'],
|
||||
'size': 711 * 1048576,
|
||||
},
|
||||
{
|
||||
'name': 'Stackoverflow (Stack Exchange)',
|
||||
'languages': ['en', 'es', 'ja', 'pt', 'ru'],
|
||||
'size': 76 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Superuser (Stack Exchange)',
|
||||
'languages': ['en'],
|
||||
'size': 3 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'iFixit',
|
||||
'languages': ['de', 'en', 'es', 'fr', 'it', 'ja', 'ko', 'nl', 'pt', 'ru', 'tr', 'zh'],
|
||||
'size': 3 * 1073741824,
|
||||
},
|
||||
{
|
||||
'name': 'Gutenberg',
|
||||
'languages': ['af', 'ale', 'ang', 'ar', 'arp', 'bg', 'bgs', 'bo', 'br', 'brx', 'ca', 'ceb', 'cs', 'csb', 'cy',
|
||||
'da', 'de', 'el', 'en', 'enm', 'eo', 'es', 'et', 'fa', 'fi', 'fr', 'fur', 'fy', 'ga', 'gl', 'gla',
|
||||
'grc', 'he', 'hu', 'ia', 'ilo', 'is', 'it', 'iu', 'ja', 'kha', 'kld', 'ko', 'la', 'mi', 'mul',
|
||||
'myn', 'nah', 'nai', 'nap', 'nav', 'nl', 'no', 'oc', 'oji', 'pl', 'pt', 'rmr', 'ro', 'ru', 'sa',
|
||||
'sl', 'sr', 'sv', 'te', 'tl', 'zh'],
|
||||
'size': 70 * 1073741824,
|
||||
},
|
||||
]
|
||||
|
||||
KIWIX_CATALOG_BY_NAME = {i['name']: i for i in KIWIX_CATALOG}
|
||||
484
modules/zim/lib.py
Normal file
484
modules/zim/lib.py
Normal file
|
|
@ -0,0 +1,484 @@
|
|||
import asyncio
|
||||
import functools
|
||||
import pathlib
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import List, Tuple, Dict
|
||||
|
||||
from libzim import Entry
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm.exc import NoResultFound # noqa
|
||||
|
||||
from modules.zim import kiwix
|
||||
from modules.zim.kiwix import KIWIX_CATALOG
|
||||
from modules.zim.models import Zim, Zims, TagZimEntry, ZimSubscription
|
||||
from wrolpi import flags
|
||||
from wrolpi.common import register_modeler, logger, extract_html_text, extract_headlines, get_media_directory, walk, \
|
||||
register_refresh_cleanup, background_task
|
||||
from wrolpi.db import get_db_session, optional_session, get_db_curs
|
||||
from wrolpi.downloader import DownloadFrequency
|
||||
from wrolpi.errors import UnknownZim, UnknownZimSubscription
|
||||
from wrolpi.files.lib import refresh_files
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.vars import PYTEST, DOCKERIZED
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
__all__ = [
|
||||
'flag_outdated_zim_files',
|
||||
'get_all_entries_tags',
|
||||
'get_entries_tags',
|
||||
'get_entry',
|
||||
'get_kiwix_catalog',
|
||||
'get_unique_paths',
|
||||
'get_zim',
|
||||
'get_zims',
|
||||
'zim_modeler',
|
||||
'zim_download_url_to_name',
|
||||
]
|
||||
|
||||
|
||||
@register_modeler
|
||||
async def zim_modeler():
|
||||
while True:
|
||||
with get_db_session(commit=True) as session:
|
||||
file_groups = session.query(FileGroup, Zim) \
|
||||
.filter(FileGroup.indexed != True, # noqa
|
||||
FileGroup.primary_path.ilike('%.zim'),
|
||||
) \
|
||||
.outerjoin(Zim, Zim.file_group_id == FileGroup.id) \
|
||||
.limit(10)
|
||||
file_groups: List[Tuple[FileGroup, Zim]] = list(file_groups)
|
||||
|
||||
processed = 0
|
||||
for file_group, zim in file_groups:
|
||||
processed += 1
|
||||
|
||||
zim_id = None
|
||||
try:
|
||||
if not zim:
|
||||
zim = Zim(file_group=file_group, path=file_group.primary_path)
|
||||
session.add(zim)
|
||||
session.flush([zim])
|
||||
zim_id = zim.id
|
||||
file_group.indexed = True
|
||||
except Exception as e:
|
||||
if PYTEST:
|
||||
raise
|
||||
logger.error(f'Unable to model Zim {zim_id=} {file_group.primary_path=}', exc_info=e)
|
||||
|
||||
logger.debug(f'Modeled {processed} zim files')
|
||||
|
||||
if processed < 10:
|
||||
# Did not reach limit, do not query again.
|
||||
break
|
||||
|
||||
# Sleep to catch cancel.
|
||||
await asyncio.sleep(0)
|
||||
|
||||
|
||||
def get_all_entries_tags():
|
||||
"""Returns a dict of dicts which contain the names of all Tags of each Entry's path.
|
||||
|
||||
Example:
|
||||
{
|
||||
1: {
|
||||
'path1': ['tag1', 'tag2'],
|
||||
},
|
||||
2: {
|
||||
'path2': ['tag1'],
|
||||
},
|
||||
"""
|
||||
stmt = '''
|
||||
SELECT tz.zim_id, tz.zim_entry, array_agg(t.name)::TEXT[]
|
||||
FROM
|
||||
tag t
|
||||
LEFT JOIN tag_zim tz on t.id = tz.tag_id
|
||||
GROUP BY 1, 2
|
||||
'''
|
||||
with get_db_curs() as curs:
|
||||
curs.execute(stmt)
|
||||
entries = dict()
|
||||
for zim_id, zim_entry, tag_names in curs.fetchall():
|
||||
if not zim_id:
|
||||
continue
|
||||
try:
|
||||
entries[zim_id][zim_entry] = tag_names
|
||||
except KeyError:
|
||||
entries[zim_id] = {zim_entry: tag_names}
|
||||
return entries
|
||||
|
||||
|
||||
def get_entries_tags(paths: List[str], zim_id: int):
|
||||
all_entries_tags = get_all_entries_tags()
|
||||
entries = dict()
|
||||
for path in paths:
|
||||
zim_tag_entries = all_entries_tags.get(zim_id, dict())
|
||||
entries[path] = zim_tag_entries.get(path, list())
|
||||
|
||||
return entries
|
||||
|
||||
|
||||
def get_unique_paths(*paths: str) -> List[str]:
|
||||
"""Return a new list which contains unique Zim paths."""
|
||||
new_paths = list()
|
||||
simple_paths = list()
|
||||
for path in paths:
|
||||
simple_path = path.replace('-', '').replace('_', '').replace('/', '').lower()
|
||||
if simple_path not in simple_paths:
|
||||
new_paths.append(path)
|
||||
simple_paths.append(simple_path)
|
||||
return new_paths
|
||||
|
||||
|
||||
@optional_session
|
||||
def headline_zim(search_str: str, zim_id: int, tag_names: List[str] = None, offset: int = 0, limit: int = 10,
|
||||
session: Session = None) -> Dict:
|
||||
zim_id = int(zim_id)
|
||||
zim = get_zim(zim_id, session=session)
|
||||
|
||||
if tag_names:
|
||||
# TODO what is the count goes over the limit?
|
||||
entries = zim.entries_with_tags(tag_names, offset=offset, limit=1_000, session=session)
|
||||
estimate = 0
|
||||
elif search_str:
|
||||
# Get suggested results (this searches titles).
|
||||
results = zim.suggest(search_str, offset, limit)
|
||||
search_results = zim.search(search_str, offset, limit)
|
||||
# Remove duplicate entries (disambiguation or redirect).
|
||||
results = get_unique_paths(*results, *search_results)
|
||||
results = results[:limit]
|
||||
entries = [zim.get_entry(i) for i in results]
|
||||
estimate = zim.estimate(search_str)
|
||||
else:
|
||||
raise RuntimeError('Must provide search_str or tag_names.')
|
||||
|
||||
articles = [bytes(i.get_item().content).decode('UTF-8') for i in entries]
|
||||
articles = [extract_html_text(i) for i in articles]
|
||||
|
||||
entries_tag_names = get_entries_tags([i.path for i in entries], zim_id)
|
||||
|
||||
# Always get headlines even if there is no search_str. This is because Postgres will return the start of each
|
||||
# article.
|
||||
headlines = extract_headlines(articles, search_str)
|
||||
|
||||
search = list()
|
||||
if search_str:
|
||||
# `search_str` allows us to headline the title.
|
||||
titles = [i.title for i in entries]
|
||||
headline_titles = extract_headlines(titles, search_str)
|
||||
|
||||
for entry in entries:
|
||||
title_headline, title_rank = headline_titles.pop(0)
|
||||
headline, rank = headlines.pop(0)
|
||||
if rank > 0 or title_rank > 0:
|
||||
# The result for each Entry.
|
||||
path = entry.path
|
||||
entry_tag_names = entries_tag_names[path] if path in entries_tag_names else list()
|
||||
search.append(dict(
|
||||
headline=headline,
|
||||
path=path,
|
||||
rank=max(rank, title_rank),
|
||||
tag_names=entry_tag_names,
|
||||
title=title_headline,
|
||||
))
|
||||
if tag_names:
|
||||
estimate += 1
|
||||
else:
|
||||
# No `search_str`, we return all entries.
|
||||
for entry in entries:
|
||||
headline, _ = headlines.pop(0)
|
||||
path = entry.path
|
||||
entry_tag_names = entries_tag_names[path] if path in entries_tag_names else list()
|
||||
search.append(dict(
|
||||
headline=headline,
|
||||
path=path,
|
||||
rank=0,
|
||||
tag_names=entry_tag_names,
|
||||
title=entry.title,
|
||||
))
|
||||
estimate = len(entries)
|
||||
|
||||
results = dict(
|
||||
path=zim.path,
|
||||
metadata=zim.zim_metadata,
|
||||
search=search,
|
||||
estimate=estimate,
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
@optional_session
|
||||
def get_zim(zim_id: int, session: Session = None) -> Zim:
|
||||
"""Return the Zim record of the provided path.
|
||||
|
||||
@raise UnknownZim: When no record exists with the id.
|
||||
@warning: Results are cached."""
|
||||
try:
|
||||
zim: Zim = session.query(Zim) \
|
||||
.join(FileGroup, FileGroup.id == Zim.file_group_id) \
|
||||
.filter(Zim.id == zim_id) \
|
||||
.one()
|
||||
return zim
|
||||
except Exception as e:
|
||||
raise UnknownZim() from e
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=1_000)
|
||||
def get_entry(path: str, zim_id: int) -> Entry:
|
||||
with get_db_session() as session:
|
||||
zim = get_zim(zim_id, session=session)
|
||||
entry = zim.get_entry(path, throw=True)
|
||||
return entry
|
||||
|
||||
|
||||
@optional_session
|
||||
def get_zims(ids: List[int] = None, session: Session = None) -> List[Zim]:
|
||||
if ids:
|
||||
zims = session.query(Zim).filter(Zim.id.in_(ids)).all()
|
||||
else:
|
||||
zims = Zims.get_all(session=session)
|
||||
|
||||
return zims
|
||||
|
||||
|
||||
@optional_session(commit=True)
|
||||
def delete_zims(ids: List[int], session: Session = None):
|
||||
zims = get_zims(ids, session=session)
|
||||
for zim in zims:
|
||||
zim.delete()
|
||||
|
||||
|
||||
@optional_session
|
||||
async def add_tag(tag_name: str, zim_id: int, zim_entry: str, session: Session = None) -> TagZimEntry:
|
||||
zim = session.query(Zim).filter_by(id=zim_id).one()
|
||||
tag_zim_entry = zim.tag_entry(tag_name, zim_entry)
|
||||
session.commit()
|
||||
return tag_zim_entry
|
||||
|
||||
|
||||
@optional_session
|
||||
async def untag(tag_name: str, zim_id: int, zim_entry: str, session: Session = None):
|
||||
zim: Zim = session.query(Zim).filter_by(id=zim_id).one()
|
||||
zim.untag_entry(tag_name, zim_entry)
|
||||
session.commit()
|
||||
|
||||
|
||||
def get_kiwix_catalog():
|
||||
return KIWIX_CATALOG.copy()
|
||||
|
||||
|
||||
@optional_session
|
||||
def get_kiwix_subscriptions(session: Session = None) -> Dict[str, ZimSubscription]:
|
||||
subscriptions = session.query(ZimSubscription)
|
||||
subscriptions_by_name = {i.name: i for i in subscriptions}
|
||||
return subscriptions_by_name
|
||||
|
||||
|
||||
@optional_session(commit=True)
|
||||
async def subscribe(name: str, language: str, session: Session = None,
|
||||
frequency: int = DownloadFrequency.days180) -> ZimSubscription:
|
||||
subscription = ZimSubscription.get_or_create(name, session=session)
|
||||
subscription.language = language
|
||||
|
||||
if name == 'Wikipedia (with images)':
|
||||
url = f'https://download.kiwix.org/zim/wikipedia/wikipedia_{language}_all_maxi_'
|
||||
elif name == 'Wikipedia (mini)':
|
||||
url = f'https://download.kiwix.org/zim/wikipedia/wikipedia_{language}_all_mini_'
|
||||
elif name == 'Wikipedia (no images)':
|
||||
url = f'https://download.kiwix.org/zim/wikipedia/wikipedia_{language}_all_nopic_'
|
||||
elif name == 'Wikiversity (with images)':
|
||||
url = f'https://download.kiwix.org/zim/wikiversity/wikiversity_{language}_all_maxi_'
|
||||
elif name == 'Wikiversity (no images)':
|
||||
url = f'https://download.kiwix.org/zim/wikiversity/wikiversity_{language}_all_nopic_'
|
||||
elif name == 'Wikitionary (no images)':
|
||||
url = f'https://download.kiwix.org/zim/wiktionary/wiktionary_{language}_all_nopic_'
|
||||
elif name == 'Wikitionary (with images)':
|
||||
url = f'https://download.kiwix.org/zim/wikiversity/wikiversity_{language}_all_maxi_'
|
||||
elif name == 'Wikibooks (no images)':
|
||||
url = f'https://download.kiwix.org/zim/wikibooks/wikibooks_{language}_all_nopic_'
|
||||
elif name == 'Wikibooks (with images)':
|
||||
url = f'https://download.kiwix.org/zim/wikibooks/wikibooks_{language}_all_maxi_'
|
||||
elif name == 'Wikisource':
|
||||
url = f'https://download.kiwix.org/zim/wikisource/wikisource_{language}_all_maxi_'
|
||||
elif name == 'Raspberry Pi (Stack Exchange)':
|
||||
url = f'https://download.kiwix.org/zim/stack_exchange/raspberrypi.stackexchange.com_{language}_all_'
|
||||
elif name == 'Vikidia':
|
||||
url = f'https://download.kiwix.org/zim/vikidia/vikidia_{language}_all_maxi_'
|
||||
elif name == 'Stackoverflow (Stack Exchange)':
|
||||
url = f'https://download.kiwix.org/zim/stack_exchange/{language}.stackoverflow.com_{language}_all_'
|
||||
elif name == 'Superuser (Stack Exchange)':
|
||||
url = f'https://download.kiwix.org/zim/stack_exchange/superuser.com_{language}_all_'
|
||||
elif name == 'iFixit':
|
||||
url = f'https://download.kiwix.org/zim/ifixit/ifixit_{language}_all_'
|
||||
elif name == 'Gutenberg':
|
||||
url = f'https://download.kiwix.org/zim/gutenberg/gutenberg_{language}_all_'
|
||||
else:
|
||||
raise ValueError(f'{name} not a valid Kiwix subscription name!')
|
||||
|
||||
if language not in kiwix.KIWIX_CATALOG_BY_NAME[name]['languages']:
|
||||
raise ValueError(f'Language {repr(str(language))} is invalid for {name}')
|
||||
|
||||
subscription.change_download(url, frequency, session=session)
|
||||
session.add(subscription)
|
||||
session.flush([subscription])
|
||||
session.commit()
|
||||
return subscription
|
||||
|
||||
|
||||
@optional_session
|
||||
async def unsubscribe(subscription_id: int, session: Session = None):
|
||||
subscription: ZimSubscription = session.query(ZimSubscription).filter_by(id=subscription_id).one_or_none()
|
||||
if subscription:
|
||||
session.delete(subscription)
|
||||
if subscription.download:
|
||||
session.delete(subscription.download)
|
||||
session.commit()
|
||||
else:
|
||||
raise UnknownZimSubscription(f'{subscription_id=}')
|
||||
|
||||
|
||||
KIWIX_URL_PARSER = re.compile(r'https:\/\/download\.kiwix\.org\/zim\/(.+?)\/(.+?)_(\w{2,3})(_.+)')
|
||||
|
||||
|
||||
def zim_download_url_to_name(url: str) -> Tuple[str, str]:
|
||||
_, project, language, flavor = KIWIX_URL_PARSER.match(url).groups()
|
||||
if project == 'wikipedia' and flavor == '_all_maxi_':
|
||||
name = 'Wikipedia (with images)'
|
||||
elif project == 'wikipedia' and flavor == '_all_nopic_':
|
||||
name = 'Wikipedia (no images)'
|
||||
elif project == 'wikipedia' and flavor == '_all_mini_':
|
||||
name = 'Wikipedia (mini)'
|
||||
elif project == 'wikiversity' and flavor == '_all_maxi_':
|
||||
name = 'Wikiversity (with images)'
|
||||
elif project == 'wikiversity' and flavor == '_all_nopic_':
|
||||
name = 'Wikiversity (no images)'
|
||||
elif project == 'wiktionary' and flavor == '_all_maxi_':
|
||||
name = 'Wikitionary (with images)'
|
||||
elif project == 'wiktionary' and flavor == '_all_nopic_':
|
||||
name = 'Wikitionary (no images)'
|
||||
elif project == 'wikibooks' and flavor == '_all_maxi_':
|
||||
name = 'Wikibooks (with images)'
|
||||
elif project == 'wikibooks' and flavor == '_all_nopic_':
|
||||
name = 'Wikibooks (no images)'
|
||||
elif project == 'wikisource' and flavor == '_all_maxi_':
|
||||
name = 'Wikisource'
|
||||
elif project == 'raspberrypi.stackexchange.com' and flavor == '_all_':
|
||||
name = 'Raspberry Pi (Stack Exchange)'
|
||||
elif project == 'vikidia' and flavor == '_all_maxi_':
|
||||
name = 'Vikidia'
|
||||
elif 'stackoverflow.com' in project and flavor == '_all_':
|
||||
name = 'Stackoverflow (Stack Exchange)'
|
||||
elif project == 'superuser.com' and flavor == '_all_':
|
||||
name = 'Superuser (Stack Exchange)'
|
||||
elif project == 'ifixit' and flavor == '_all_':
|
||||
name = 'iFixit'
|
||||
elif project == 'gutenberg' and flavor == '_all_':
|
||||
name = 'Gutenberg'
|
||||
else:
|
||||
raise RuntimeError(f'Could not find name for Zim URL: {url} {project=} {flavor=}')
|
||||
|
||||
if language not in kiwix.KIWIX_CATALOG_BY_NAME[name]['languages']:
|
||||
raise ValueError(f'Language {repr(str(language))} is invalid for {name}')
|
||||
|
||||
return name, language
|
||||
|
||||
|
||||
def get_zim_directory() -> pathlib.Path:
|
||||
media_directory = get_media_directory()
|
||||
zim_directory = media_directory / 'zims'
|
||||
return zim_directory
|
||||
|
||||
|
||||
async def check_zim(path: pathlib.Path) -> int:
|
||||
"""
|
||||
Runs `zimcheck` against the Zim file. Zim is valid only if this returns `0`.
|
||||
|
||||
@warning: Only performs the checksum check!
|
||||
"""
|
||||
cmd = f'zimcheck -C {path.absolute()}'
|
||||
proc = await asyncio.create_subprocess_shell(cmd)
|
||||
stdout, stderr = await proc.communicate()
|
||||
logger.debug(f'zimcheck returned {proc.returncode}')
|
||||
if proc.returncode != 0 and stderr:
|
||||
logger.debug(stderr)
|
||||
return proc.returncode
|
||||
|
||||
|
||||
ZIM_NAME_PARSER = re.compile(r'(.+?)_(\d{4}-\d{2}).zim')
|
||||
|
||||
|
||||
def parse_name(path: pathlib.Path) -> Tuple[str, datetime]:
|
||||
name, date = ZIM_NAME_PARSER.match(path.name).groups()
|
||||
date = datetime.strptime(date, '%Y-%m')
|
||||
return name, date
|
||||
|
||||
|
||||
def find_outdated_zim_files(path: pathlib.Path = None) -> Tuple[List[pathlib.Path], List[pathlib.Path]]:
|
||||
"""Search the Zim directory for outdated Zim files. Returns a list of outdated, and a list of current Zim files."""
|
||||
path = path or get_zim_directory()
|
||||
if not path.is_dir():
|
||||
logger.error(f'Cannot search for outdated Zim files because the directory does not exist: {path}')
|
||||
return list(), list()
|
||||
|
||||
# Find all non-empty Zim files.
|
||||
files = [i for i in walk(path) if i.is_file() and i.stat().st_size and i.suffix == '.zim']
|
||||
zims = list()
|
||||
for file in files:
|
||||
try:
|
||||
name, date = parse_name(file)
|
||||
except Exception as e:
|
||||
logger.warning(f'Found Zim {file} but its name does not match.', exc_info=e)
|
||||
continue
|
||||
|
||||
zims.append((name, date, file))
|
||||
|
||||
# Order by newest first.
|
||||
zims = sorted(zims, key=lambda i: i[1], reverse=True)
|
||||
outdated_files = list()
|
||||
current_files = list()
|
||||
newest_names = list()
|
||||
for name, date, file in zims:
|
||||
if name in newest_names:
|
||||
# Already saw this name, this date is older.
|
||||
outdated_files.append(file)
|
||||
else:
|
||||
newest_names.append(name)
|
||||
current_files.append(file)
|
||||
|
||||
return sorted(outdated_files), sorted(current_files)
|
||||
|
||||
|
||||
async def remove_outdated_zim_files(path: pathlib.Path = None):
|
||||
"""Deletes all old Zim files."""
|
||||
outdated, _ = find_outdated_zim_files(path)
|
||||
logger.info(f'Deleting {len(outdated)} outdated Zim files: {outdated}')
|
||||
for file in outdated:
|
||||
file.unlink()
|
||||
|
||||
if PYTEST:
|
||||
await refresh_files(outdated)
|
||||
else:
|
||||
background_task(refresh_files(outdated))
|
||||
|
||||
flag_kiwix_restart()
|
||||
|
||||
|
||||
@register_refresh_cleanup
|
||||
def flag_outdated_zim_files():
|
||||
"""Set the `outdated_zims` Flag if outdated Zim files can be found, otherwise clear it."""
|
||||
outdated, _ = find_outdated_zim_files()
|
||||
if outdated:
|
||||
logger.info('Outdated Zims were found')
|
||||
flags.outdated_zims.set()
|
||||
else:
|
||||
logger.info('Outdated Zims were not found')
|
||||
flags.outdated_zims.clear()
|
||||
|
||||
|
||||
def flag_kiwix_restart():
|
||||
"""Set `kiwix_restart` Flag only if running in Docker."""
|
||||
if DOCKERIZED:
|
||||
flags.kiwix_restart.set()
|
||||
else:
|
||||
logger.debug(f'Not setting kiwix_restart flag because this is not Dockerized')
|
||||
370
modules/zim/models.py
Normal file
370
modules/zim/models.py
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
import dataclasses
|
||||
import functools
|
||||
import pathlib
|
||||
from collections import OrderedDict
|
||||
from datetime import datetime
|
||||
from typing import List, Tuple, OrderedDict as OrderedDictType, Dict, Optional, Set
|
||||
|
||||
from libzim import Archive, Searcher, Query, Entry, SuggestionSearcher
|
||||
from sqlalchemy import Column, Integer, BigInteger, ForeignKey, Text, tuple_
|
||||
from sqlalchemy.orm import relationship, Session
|
||||
from sqlalchemy.orm.exc import NoResultFound # noqa
|
||||
|
||||
from wrolpi import dates, tags
|
||||
from wrolpi.common import Base, extract_html_text, logger, get_relative_to_media_directory
|
||||
from wrolpi.dates import TZDateTime
|
||||
from wrolpi.db import optional_session, get_db_curs
|
||||
from wrolpi.downloader import Download, download_manager
|
||||
from wrolpi.errors import UnknownZimEntry, UnknownZimTagEntry
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.media_path import MediaPathType
|
||||
from wrolpi.tags import Tag, tag_names_to_zim_sub_select
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class ZimMetadata:
|
||||
date: str
|
||||
creator: str
|
||||
description: str
|
||||
name: str
|
||||
publisher: str
|
||||
tags: str
|
||||
title: str
|
||||
|
||||
def __json__(self) -> Dict:
|
||||
d = dict(
|
||||
date=self.date,
|
||||
creator=self.creator,
|
||||
description=self.description,
|
||||
name=self.name,
|
||||
publisher=self.publisher,
|
||||
tags=self.tags,
|
||||
title=self.title,
|
||||
)
|
||||
return d
|
||||
|
||||
|
||||
class EntrySummary:
|
||||
zim_id: int
|
||||
path: str
|
||||
title: str
|
||||
|
||||
def __json__(self) -> Dict:
|
||||
d = dict(
|
||||
zim_id=self.zim_id,
|
||||
path=self.path,
|
||||
title=self.title,
|
||||
)
|
||||
return d
|
||||
|
||||
|
||||
class Zim(Base):
|
||||
"""Records of Zim files.
|
||||
|
||||
Zim files stores wiki content (and much more) for offline usage. Zim files are compressed data that can be searched.
|
||||
"""
|
||||
|
||||
__tablename__ = 'zim'
|
||||
id = Column(Integer, primary_key=True)
|
||||
path: pathlib.Path = Column(MediaPathType, nullable=False)
|
||||
|
||||
file_group_id = Column(BigInteger, ForeignKey('file_group.id', ondelete='CASCADE'), unique=True, nullable=False)
|
||||
file_group: FileGroup = relationship('FileGroup')
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Zim id={self.id} file_group_id={self.file_group_id} path={self.path}>'
|
||||
|
||||
def __json__(self) -> dict:
|
||||
d = dict(
|
||||
id=self.id,
|
||||
path=self.path,
|
||||
file_group_id=self.file_group_id,
|
||||
metadata=self.zim_metadata,
|
||||
size=self.file_group.size,
|
||||
)
|
||||
return d
|
||||
|
||||
@staticmethod
|
||||
def from_paths(session: Session, *paths: pathlib.Path) -> 'Zim':
|
||||
file_group = FileGroup.from_paths(session, *paths)
|
||||
zim = Zim(path=file_group.primary_path, file_group=file_group)
|
||||
session.add(zim)
|
||||
session.flush([file_group, zim])
|
||||
return zim
|
||||
|
||||
def get_zim(self) -> Archive:
|
||||
if not self.path or not self.path.is_file():
|
||||
raise FileNotFoundError(f'{self} does not exist!')
|
||||
|
||||
if not self.path.suffix != 'zim':
|
||||
raise FileNotFoundError(f'{self} is not a valid zim file!')
|
||||
|
||||
zim = Archive(self.path)
|
||||
return zim
|
||||
|
||||
def delete(self):
|
||||
session: Session = Session.object_session(self)
|
||||
self.path.unlink(missing_ok=True)
|
||||
session.delete(self)
|
||||
|
||||
@functools.cached_property
|
||||
def zim_metadata(self) -> ZimMetadata:
|
||||
zim = self.get_zim()
|
||||
|
||||
def _get_metadata(path: str):
|
||||
try:
|
||||
return zim.get_metadata(path).decode()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
metadata = ZimMetadata(
|
||||
date=_get_metadata('Date'),
|
||||
creator=_get_metadata('Creator'),
|
||||
description=_get_metadata('Description'),
|
||||
name=_get_metadata('Name'),
|
||||
publisher=_get_metadata('Publisher'),
|
||||
tags=_get_metadata('Tags'),
|
||||
title=_get_metadata('Title'),
|
||||
)
|
||||
return metadata
|
||||
|
||||
def get_searcher(self) -> Searcher:
|
||||
searcher = Searcher(self.get_zim())
|
||||
return searcher
|
||||
|
||||
def get_search(self, search_str: str):
|
||||
query = Query().set_query(search_str)
|
||||
searcher = self.get_searcher()
|
||||
search = searcher.search(query)
|
||||
return search
|
||||
|
||||
def get_suggestion_searcher(self) -> SuggestionSearcher:
|
||||
searcher = SuggestionSearcher(self.get_zim())
|
||||
return searcher
|
||||
|
||||
def estimate(self, search_str: str) -> int:
|
||||
"""Count the number of Entry(s) that contain the `search_str`."""
|
||||
search = self.get_search(search_str)
|
||||
count = search.getEstimatedMatches()
|
||||
return count
|
||||
|
||||
def search(self, search_str: str, offset: int = 0, limit: int = 10) -> List[str]:
|
||||
"""Return the paths of the Entry(s) that contain the `search_str`."""
|
||||
search = self.get_search(search_str)
|
||||
results = list(search.getResults(offset, limit))
|
||||
return results
|
||||
|
||||
def suggest(self, search_str: str, offset: int = 0, limit: int = 10) -> List[str]:
|
||||
"""Return the paths of the Entry(s) that contain the `search_str`. Also searches the titles."""
|
||||
searcher = self.get_suggestion_searcher()
|
||||
suggestions = searcher.suggest(search_str)
|
||||
results = list(suggestions.getResults(offset, limit))
|
||||
return results
|
||||
|
||||
def get_entry(self, path: str, throw: bool = True) -> Optional[Entry]:
|
||||
"""Search this Zim file for the provided Entry at the `path`."""
|
||||
zim = self.get_zim()
|
||||
try:
|
||||
entry = zim.get_entry_by_path(path)
|
||||
except KeyError:
|
||||
if throw:
|
||||
raise UnknownZimEntry(f'Cannot find entry at {path=}')
|
||||
else:
|
||||
return None
|
||||
return entry
|
||||
|
||||
def get_entry_html(self, path: str) -> Optional[str]:
|
||||
"""Search this Zim file for the provided Entry at `path`, read its contents and return the HTML."""
|
||||
content = bytes(self.get_entry(path).get_item().content).decode('UTF-8')
|
||||
return content
|
||||
|
||||
def get_entry_text(self, path: str) -> Optional[str]:
|
||||
"""Search this Zim file for the provided Entry at `path`, read its contents and return the text in the HTML."""
|
||||
html = self.get_entry_html(path)
|
||||
content = extract_html_text(html)
|
||||
return content
|
||||
|
||||
def tag_entry(self, tag_name: str, zim_entry: str) -> 'TagZimEntry':
|
||||
"""Create a TagZimEntry for this Zim at the provided entry (path) for the provided Tag."""
|
||||
session = Session.object_session(self)
|
||||
tag = Tag.find_by_name(tag_name, session=session)
|
||||
tag_zim_entry = TagZimEntry(tag=tag, zim=self, zim_entry=zim_entry)
|
||||
session.add(tag_zim_entry)
|
||||
tags.schedule_save()
|
||||
return tag_zim_entry
|
||||
|
||||
def untag_entry(self, tag_name: str, zim_entry: str):
|
||||
"""Removes any TagZimEntry of the Zim entry at the provided path for the provided Tag.
|
||||
|
||||
@raise UnknownZimTagEntry: No entry exists to remove."""
|
||||
session = Session.object_session(self)
|
||||
tag = Tag.find_by_name(tag_name, session=session)
|
||||
tag_zim_entry = session.query(TagZimEntry).filter_by(
|
||||
tag_id=tag.id,
|
||||
zim_id=self.id,
|
||||
zim_entry=zim_entry,
|
||||
).one_or_none()
|
||||
if tag_zim_entry:
|
||||
session.delete(tag_zim_entry)
|
||||
else:
|
||||
raise UnknownZimTagEntry(f'Could not find at {repr(str(zim_entry))}')
|
||||
tags.schedule_save()
|
||||
|
||||
@optional_session
|
||||
def entries_with_tags(self, tag_names: List[str], offset: int = 0, limit: int = 10, session: Session = None) \
|
||||
-> List[Entry]:
|
||||
"""Return Zim Entries tagged with the provided names."""
|
||||
tags_sub_select, params = tag_names_to_zim_sub_select(tag_names, zim_id=self.id)
|
||||
|
||||
with get_db_curs() as curs:
|
||||
curs.execute(tags_sub_select, params)
|
||||
zim_ids_entries: List[Tuple[int, int]] = list(curs.fetchall())
|
||||
|
||||
tag_zim_entries = session.query(TagZimEntry, Zim) \
|
||||
.join(Zim, Zim.id == TagZimEntry.zim_id) \
|
||||
.filter(tuple_(TagZimEntry.zim_id, TagZimEntry.zim_entry).in_(zim_ids_entries)) \
|
||||
.order_by(TagZimEntry.zim_id, TagZimEntry.zim_entry) \
|
||||
.offset(offset).limit(limit) \
|
||||
.distinct(TagZimEntry.zim_id, TagZimEntry.zim_entry)
|
||||
|
||||
entries = list()
|
||||
for tag_zim_entry, zim in tag_zim_entries:
|
||||
entry = zim.get_entry(tag_zim_entry.zim_entry)
|
||||
entries.append(entry)
|
||||
|
||||
return entries
|
||||
|
||||
@functools.cached_property
|
||||
def all_entries(self) -> Set[EntrySummary]:
|
||||
"""
|
||||
Iterates over all Entries in the Archive. Ignores non-article entries (javascript, images, etc).
|
||||
"""
|
||||
zim = self.get_zim()
|
||||
zim_id = self.id
|
||||
entry_count = zim.all_entry_count
|
||||
entries = set()
|
||||
for entry_id in range(entry_count):
|
||||
entry: Entry = zim._get_entry_by_id(entry_id)
|
||||
title = entry.title
|
||||
if title.startswith('m/') or title.startswith('-/') or title.startswith('I/'):
|
||||
continue
|
||||
|
||||
summary = EntrySummary()
|
||||
summary.zim_id = zim_id
|
||||
summary.path = entry.path
|
||||
summary.title = title
|
||||
entries.add(summary)
|
||||
return entries
|
||||
|
||||
def parse_name(self):
|
||||
from modules.zim import lib
|
||||
name, date = lib.parse_name(self.path)
|
||||
return name, date
|
||||
|
||||
|
||||
class Zims:
|
||||
"""Convenience class which searches all known Zim files."""
|
||||
|
||||
@staticmethod
|
||||
@optional_session
|
||||
def get_all(session: Session = None) -> List[Zim]:
|
||||
"""Returns all Zim records."""
|
||||
zims = list()
|
||||
for zim in session.query(Zim).order_by(Zim.path):
|
||||
try:
|
||||
# It may not be possible to read the Zim file (drive not mounted), report and ignore.
|
||||
zim.get_zim()
|
||||
zims.append(zim)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to read Zim: {zim}', exc_info=e)
|
||||
return zims
|
||||
|
||||
@classmethod
|
||||
@optional_session
|
||||
def estimate(cls, search_str: str, session: Session = None) -> OrderedDictType[Zim, int]:
|
||||
zims = cls.get_all(session=session)
|
||||
results = OrderedDict()
|
||||
for zim in zims:
|
||||
results[zim] = zim.estimate(search_str)
|
||||
return results
|
||||
|
||||
@classmethod
|
||||
@optional_session
|
||||
def entries_with_tags(cls, tag_names: List[str], session: Session = None) -> OrderedDictType[Zim, int]:
|
||||
zims = cls.get_all(session=session)
|
||||
results = OrderedDict()
|
||||
for zim in zims:
|
||||
results[zim] = len(zim.entries_with_tags(tag_names, session=session))
|
||||
return results
|
||||
|
||||
|
||||
class TagZimEntry(Base):
|
||||
__tablename__ = 'tag_zim'
|
||||
|
||||
tag_id = Column(Integer, ForeignKey('tag.id', ondelete='CASCADE'), primary_key=True)
|
||||
tag: Tag = relationship('Tag')
|
||||
zim_id = Column(Integer, ForeignKey('zim.id', ondelete='CASCADE'), primary_key=True)
|
||||
zim: Zim = relationship('Zim')
|
||||
zim_entry: str = Column(Text, nullable=False, primary_key=True)
|
||||
created_at: datetime = Column(TZDateTime, default=dates.now)
|
||||
|
||||
def __repr__(self):
|
||||
tag = self.tag_id
|
||||
if self.tag:
|
||||
tag = self.tag.name
|
||||
zim = self.zim_id
|
||||
if self.zim:
|
||||
zim = get_relative_to_media_directory(self.zim.path)
|
||||
return f'<TagZimEntry {tag=} {zim=} zim_entry={self.zim_entry}>'
|
||||
|
||||
|
||||
class ZimSubscription(Base):
|
||||
__tablename__ = 'zim_subscription'
|
||||
|
||||
id: int = Column(Integer, primary_key=True)
|
||||
name: str = Column(Text, unique=True, nullable=False)
|
||||
language: str = Column(Text, nullable=False)
|
||||
download_id: int = Column(Integer, ForeignKey('download.id', ondelete='CASCADE'), nullable=False)
|
||||
download: Download = relationship('Download', primaryjoin='ZimSubscription.download_id==Download.id')
|
||||
|
||||
def __repr__(self):
|
||||
name = self.name
|
||||
language = self.language
|
||||
download_id = self.download_id
|
||||
return f'<ZimSubscription id={self.id} {name=} {language=} {download_id=}>'
|
||||
|
||||
def __json__(self):
|
||||
d = dict(
|
||||
id=self.id,
|
||||
name=self.name,
|
||||
language=self.language,
|
||||
download_id=self.download_id,
|
||||
download_url=self.download.url if self.download else None,
|
||||
)
|
||||
return d
|
||||
|
||||
def change_download(self, url: str, frequency: int, session: Session):
|
||||
# A Zim file is found using the KiwixCatalogDownloader, then handled by the KiwixZimDownloader.
|
||||
old_url = self.download.url if self.download else url
|
||||
download = download_manager.get_or_create_download(old_url, session=session, reset_attempts=True)
|
||||
download.url = url
|
||||
download.frequency = frequency
|
||||
download.downloader = 'kiwix_catalog'
|
||||
download.sub_downloader = 'kiwix_zim'
|
||||
download.attempts = 0
|
||||
download.info_json = {'language': self.language, 'name': self.name}
|
||||
session.flush([download, ])
|
||||
self.download_id = download.id
|
||||
return download
|
||||
|
||||
@staticmethod
|
||||
@optional_session
|
||||
def get_or_create(name: str, session: Session = None) -> 'ZimSubscription':
|
||||
subscription = session.query(ZimSubscription).filter_by(name=name).one_or_none()
|
||||
if subscription:
|
||||
return subscription
|
||||
|
||||
subscription = ZimSubscription(name=name)
|
||||
return subscription
|
||||
95
modules/zim/schema.py
Normal file
95
modules/zim/schema.py
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
from dataclasses import dataclass, field
|
||||
from typing import Optional, List, Dict
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZimSearchRequest:
|
||||
search_str: Optional[str] = None
|
||||
tag_names: List[str] = field(default_factory=lambda: list())
|
||||
offset: Optional[int] = 0
|
||||
limit: Optional[int] = 10
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZimMetadata:
|
||||
path: str
|
||||
creator: str
|
||||
description: str
|
||||
name: str
|
||||
publisher: str
|
||||
tags: str
|
||||
title: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Zim:
|
||||
id: int
|
||||
path: str
|
||||
file_group_id: int
|
||||
metadata: ZimMetadata
|
||||
size: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class GetZimsResponse:
|
||||
zims: List[Zim]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZimSearchHeadline:
|
||||
headline: str
|
||||
rank: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZimSearchResult:
|
||||
path: str
|
||||
metadata: ZimMetadata
|
||||
search: List[ZimSearchHeadline]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZimSearchResponse:
|
||||
zim: ZimSearchResult
|
||||
|
||||
|
||||
@dataclass
|
||||
class TagZimEntry:
|
||||
tag_name: str
|
||||
zim_id: int
|
||||
zim_entry: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZimSubscription:
|
||||
id: int
|
||||
name: str
|
||||
language: str
|
||||
download_id: int
|
||||
download_url: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZimProject:
|
||||
name: str
|
||||
languages: List[str]
|
||||
size: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZimSubscriptions:
|
||||
subscriptions: Dict[str, ZimSubscription]
|
||||
catalog: List[ZimProject]
|
||||
iso_639_codes: Dict[str, str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class TagZimSubscribe:
|
||||
name: str
|
||||
language: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class OutdatedZims:
|
||||
outdated: List[str]
|
||||
current: List[str]
|
||||
0
modules/zim/test/__init__.py
Normal file
0
modules/zim/test/__init__.py
Normal file
Binary file not shown.
245
modules/zim/test/test_api.py
Normal file
245
modules/zim/test/test_api.py
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
import json
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.zim import lib
|
||||
from modules.zim.models import Zim
|
||||
from wrolpi.downloader import Download
|
||||
|
||||
|
||||
def test_zim_search(test_client, test_session, test_zim, tag_factory, assert_zim_search):
|
||||
"""Entries can be tagged and retrieved using their containing Zim."""
|
||||
tag1, tag2 = tag_factory(), tag_factory()
|
||||
test_zim.tag_entry(tag1.name, 'one')
|
||||
test_zim.tag_entry(tag2.name, 'one')
|
||||
test_zim.tag_entry(tag1.name, 'two')
|
||||
test_session.commit()
|
||||
|
||||
# Test searching with only `search_str`.
|
||||
assert_zim_search('one', 1, {
|
||||
'path': test_zim.path,
|
||||
'search': [
|
||||
# Entry "One" contains a 'one' in the title, and the text.
|
||||
{'path': 'one', 'headline': 'This is the first item', 'rank': 0.06079271},
|
||||
# Home only contains one 'one'.
|
||||
{'path': 'home', 'rank': 0.06079271, 'headline': 'file for testing.\n<b>One</b>', },
|
||||
],
|
||||
'estimate': 2,
|
||||
})
|
||||
assert_zim_search('two', 1, {
|
||||
'path': test_zim.path,
|
||||
'search': [{'path': 'two', 'headline': 'This is the second item', 'rank': 0.06079271},
|
||||
{'path': 'home', 'headline': 'testing.\nOne\n<b>Two</b>', 'rank': 0.06079271}],
|
||||
'estimate': 2,
|
||||
})
|
||||
assert_zim_search('item', 1, {
|
||||
'path': test_zim.path,
|
||||
'search': [{'path': 'one', 'headline': 'first <b>item</b>', 'rank': 0.06079271},
|
||||
{'path': 'two', 'headline': 'second <b>item</b>', 'rank': 0.06079271}],
|
||||
'estimate': 2,
|
||||
})
|
||||
|
||||
# Test searching with `search_str` and `tag_names`.
|
||||
assert_zim_search('one', 1, tag_names=[tag2.name, ], expected={
|
||||
'search': [
|
||||
# Only entry "One" is tagged with Tag 2.
|
||||
{'path': 'one', 'headline': 'This is the first item', 'rank': 0.06079271},
|
||||
],
|
||||
'estimate': 1,
|
||||
})
|
||||
assert_zim_search('one', 1, tag_names=[tag1.name, tag2.name], expected={
|
||||
'search': [
|
||||
# Only "One" is tagged with Tag 1 and contains "one".
|
||||
{'path': 'one', 'headline': 'This is the first item', 'rank': 0.06079271},
|
||||
],
|
||||
'estimate': 1,
|
||||
})
|
||||
assert_zim_search('two', 1, tag_names=[tag1.name, ], expected={
|
||||
'search': [
|
||||
# Only "Two" was tagged with Tag 1 and contains "two".
|
||||
{'path': 'two', 'headline': 'This is the second item', 'rank': 0.06079271},
|
||||
],
|
||||
'estimate': 1,
|
||||
})
|
||||
assert_zim_search('two', 1, tag_names=[tag2.name, ], expected={
|
||||
# Two was not tagged with Tag 1.
|
||||
'search': [],
|
||||
'estimate': 0,
|
||||
})
|
||||
|
||||
# Test search with only `tag_names`.
|
||||
assert_zim_search('', 1, tag_names=[tag1.name, tag2.name], expected={
|
||||
'search': [
|
||||
# Return all entries that are tagged with the Tags.
|
||||
{'path': 'one', 'headline': 'This is the first item', 'rank': 0.0, 'tag_names': ['one', 'two']},
|
||||
],
|
||||
'estimate': 1,
|
||||
})
|
||||
|
||||
|
||||
def test_entries_by_tag(test_client, test_session, test_zim, tag_factory):
|
||||
"""Entries can be tagged and retrieved using their containing Zim."""
|
||||
tag1, tag2 = tag_factory(), tag_factory()
|
||||
test_zim.tag_entry(tag1.name, 'one')
|
||||
test_zim.tag_entry(tag2.name, 'one')
|
||||
test_zim.tag_entry(tag1.name, 'two')
|
||||
test_session.commit()
|
||||
|
||||
result = test_zim.entries_with_tags([tag1.name, tag2.name])
|
||||
assert [(i.path, i.title) for i in result] == [('one', 'One'), ]
|
||||
|
||||
result = test_zim.entries_with_tags([tag1.name, ])
|
||||
assert [(i.path, i.title) for i in result] == [('one', 'One'), ('two', 'Two')]
|
||||
|
||||
result = test_zim.entries_with_tags([tag2.name, ])
|
||||
assert [(i.path, i.title) for i in result] == [('one', 'One'), ]
|
||||
|
||||
|
||||
def test_zim_crud(test_client, test_session, test_directory, test_zim):
|
||||
request, response = test_client.get('/api/zim')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert len(response.json['zims']) == 1
|
||||
assert response.json['zims'][0]['path'] == test_zim.path.name
|
||||
|
||||
request, response = test_client.delete('/api/zim/1')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
assert not test_zim.path.exists()
|
||||
assert test_session.query(Zim).count() == 0
|
||||
|
||||
|
||||
def test_zim_tag_estimate(test_client, test_session, test_zim, tag_factory):
|
||||
"""Global search estimate returns Zim estimates."""
|
||||
tag1, tag2 = tag_factory(), tag_factory()
|
||||
test_session.commit()
|
||||
|
||||
content = dict(search_str=None, tag_names=[tag1.name, ])
|
||||
request, response = test_client.post('/api/search_estimate', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['zims'] and response.json['zims'][0]['estimate'] == 0
|
||||
|
||||
# Entries can be tagged in the API.
|
||||
content = dict(tag_name=tag1.name, zim_id=test_zim.id, zim_entry='home')
|
||||
request, response = test_client.post('/api/zim/tag', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.CREATED
|
||||
# Create other Tags directly.
|
||||
test_zim.tag_entry(tag2.name, 'one')
|
||||
test_zim.tag_entry(tag1.name, 'two')
|
||||
test_session.commit()
|
||||
|
||||
content = dict(search_str=None, tag_names=[tag1.name, ])
|
||||
request, response = test_client.post('/api/search_estimate', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['zims'] and response.json['zims'][0]['estimate'] == 2
|
||||
|
||||
|
||||
def test_zim_tag_and_untag(test_client, test_session, test_zim, tag_factory):
|
||||
"""Zim entries can be Tagged and Untagged."""
|
||||
tag1, tag2 = tag_factory(), tag_factory()
|
||||
test_session.commit()
|
||||
|
||||
# Entries can be tagged in the API.
|
||||
content = dict(tag_name=tag1.name, zim_id=test_zim.id, zim_entry='home')
|
||||
request, response = test_client.post('/api/zim/tag', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.CREATED
|
||||
|
||||
# Entries can be untagged in the API.
|
||||
content = dict(tag_name=tag1.name, zim_id=test_zim.id, zim_entry='home')
|
||||
request, response = test_client.post('/api/zim/untag', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# Cannot untag twice.
|
||||
content = dict(tag_name=tag1.name, zim_id=test_zim.id, zim_entry='home')
|
||||
request, response = test_client.post('/api/zim/untag', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
def test_zim_subscribe(test_session, test_client):
|
||||
"""A Kiwix subscription can be scheduled in the API. The language can be changed."""
|
||||
# Subscribe to English.
|
||||
content = dict(name='Wikipedia (mini)', language='en')
|
||||
request, response = test_client.post('/api/zim/subscribe', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.CREATED
|
||||
|
||||
download: Download = test_session.query(Download).one()
|
||||
assert download.url == 'https://download.kiwix.org/zim/wikipedia/wikipedia_en_all_mini_'
|
||||
assert download.info_json == {'language': 'en', 'name': 'Wikipedia (mini)'}
|
||||
assert download.frequency
|
||||
request, response = test_client.get('/api/zim/subscribe')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['subscriptions'] == {
|
||||
'Wikipedia (mini)': {'download_id': 1,
|
||||
'download_url': 'https://download.kiwix.org/zim/wikipedia/wikipedia_en_all_mini_',
|
||||
'id': 1,
|
||||
'language': 'en',
|
||||
'name': 'Wikipedia (mini)'}}
|
||||
|
||||
# Change subscription to French.
|
||||
content = dict(name='Wikipedia (mini)', language='fr')
|
||||
request, response = test_client.post('/api/zim/subscribe', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.CREATED
|
||||
assert test_session.query(Download).count() == 1
|
||||
|
||||
download: Download = test_session.query(Download).one()
|
||||
assert download.url == 'https://download.kiwix.org/zim/wikipedia/wikipedia_fr_all_mini_'
|
||||
assert download.info_json == {'language': 'fr', 'name': 'Wikipedia (mini)'}
|
||||
assert download.frequency
|
||||
request, response = test_client.get('/api/zim/subscribe')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['subscriptions'] == {
|
||||
'Wikipedia (mini)': {'download_id': 1,
|
||||
'download_url': 'https://download.kiwix.org/zim/wikipedia/wikipedia_fr_all_mini_',
|
||||
'id': 1,
|
||||
'language': 'fr',
|
||||
'name': 'Wikipedia (mini)'}}
|
||||
|
||||
# Delete subscription.
|
||||
request, response = test_client.delete('/api/zim/subscribe/1')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
request, response = test_client.get('/api/zim/subscribe')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['subscriptions'] == {}
|
||||
# No subscriptions or downloads.
|
||||
assert test_session.query(lib.ZimSubscription).count() == 0
|
||||
assert test_session.query(Download).count() == 0
|
||||
|
||||
|
||||
def test_get_zim_entry(test_session, test_client, test_zim):
|
||||
request, response = test_client.get('/api/zim/1/entry/home')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
request, response = test_client.get('/api/zim/1/entry/does not exist')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_find_outdated_zim_files(test_session, test_directory, test_zim_bytes, test_async_client):
|
||||
"""Outdated Zim files are found and reported. They can automatically be deleted."""
|
||||
# Can search empty directory.
|
||||
outdated, current = lib.find_outdated_zim_files()
|
||||
assert not outdated and not current
|
||||
|
||||
(test_directory / 'zims/books').mkdir(parents=True)
|
||||
|
||||
wikibooks_one = test_directory / 'zims/books/wikibooks_en_nopic_maxi_2023-01.zim' # unique
|
||||
wikipedia_one = test_directory / 'zims/wikipedia_en_all_maxi_2023-01.zim' # outdated
|
||||
wikipedia_two = test_directory / 'zims/wikipedia_en_all_maxi_2023-02.zim' # keep this one
|
||||
asdf = test_directory / 'zims/asdf.zim' # Name cannot be parsed.
|
||||
wikibooks_one.write_bytes(test_zim_bytes)
|
||||
wikipedia_one.write_bytes(test_zim_bytes)
|
||||
wikipedia_two.write_bytes(test_zim_bytes)
|
||||
asdf.write_bytes(test_zim_bytes)
|
||||
empty = test_directory / 'zims/wikipedia_en_all_maxi_2023-03.zim' # empty files should be ignored.
|
||||
empty.touch()
|
||||
request, response = await test_async_client.get('/api/zim/outdated')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['outdated'] == [str(wikipedia_one.relative_to(test_directory)), ]
|
||||
|
||||
request, response = await test_async_client.delete('/api/zim/outdated')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
# Only the outdated was deleted.
|
||||
assert wikibooks_one.is_file()
|
||||
assert not wikipedia_one.exists()
|
||||
assert wikipedia_two.is_file()
|
||||
assert asdf.is_file()
|
||||
assert empty.is_file()
|
||||
300
modules/zim/test/test_lib.py
Normal file
300
modules/zim/test/test_lib.py
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
import datetime
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
from libzim import Entry
|
||||
|
||||
from modules.zim import lib
|
||||
from modules.zim.models import TagZimEntry, ZimSubscription
|
||||
from wrolpi import tags, flags
|
||||
from wrolpi.common import DownloadFileInfo
|
||||
from wrolpi.downloader import Download, import_downloads_config, save_downloads_config
|
||||
from wrolpi.errors import UnknownZim
|
||||
from wrolpi.files import lib as files_lib
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_zim(test_session, zim_path_factory):
|
||||
zim_path_factory()
|
||||
await files_lib.refresh_files()
|
||||
|
||||
assert lib.get_zim(1)
|
||||
|
||||
with pytest.raises(UnknownZim):
|
||||
assert lib.get_zim(2)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_zim_get_entry(test_session, zim_path_factory):
|
||||
zim_path_factory()
|
||||
await files_lib.refresh_files()
|
||||
|
||||
entry: Entry = lib.get_entry('one', 1)
|
||||
assert entry.path == 'one'
|
||||
assert entry.title == 'One'
|
||||
assert bytes(entry.get_item().content).decode('UTF-8') == '''
|
||||
<html>
|
||||
<head>
|
||||
<title>One</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>This is the first item</h1>
|
||||
</body>
|
||||
</html>
|
||||
'''
|
||||
|
||||
entry: Entry = lib.get_entry('home', 1)
|
||||
assert entry.path == 'home'
|
||||
assert entry.title == 'Homepage'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_zim_get_entries_tags(test_session, test_zim, tag_factory):
|
||||
tag1, tag2 = tag_factory('tag1'), tag_factory('tag2')
|
||||
test_zim.tag_entry(tag1.name, 'one')
|
||||
test_zim.tag_entry(tag2.name, 'one')
|
||||
test_zim.tag_entry(tag1.name, 'two')
|
||||
test_session.commit()
|
||||
|
||||
assert lib.get_entries_tags(['one', 'two', 'home'], 1) \
|
||||
== dict(one=['tag1', 'tag2'], two=['tag1'], home=[])
|
||||
|
||||
|
||||
def test_get_unique_paths():
|
||||
paths = ['A/Prickly_Pear', 'A/Prickly_pear', 'A/Prickly-pear', 'A/Arborescent_Prickly_Pear',
|
||||
'A/Arborescent_prickly_pear', 'A/Beavertail_prickly_pear', 'A/Brittle_prickly-pear',
|
||||
'A/Chenille_prickly-pear', 'A/Coastal_Prickly_Pear', 'A/Coastal_prickly_pear',
|
||||
'A/Prickly_pears_in_South_Africa', 'A/Prickly_Pear_Cays', 'A/Prickly_pears_in_Australia', 'A/Opuntia',
|
||||
'A/Prickly_Pear_(British_Virgin_Islands)', 'A/Prickly_Pear_Island', 'A/Prickly_Pears_(film)',
|
||||
'A/Invasive_succulent_plants_in_South_Africa', 'A/Cactoblastis_Memorial_Hall', 'A/Thomas_Harvey_Johnston']
|
||||
assert lib.get_unique_paths(*paths) == ['A/Prickly_Pear',
|
||||
'A/Arborescent_Prickly_Pear',
|
||||
'A/Beavertail_prickly_pear',
|
||||
'A/Brittle_prickly-pear',
|
||||
'A/Chenille_prickly-pear',
|
||||
'A/Coastal_Prickly_Pear',
|
||||
'A/Prickly_pears_in_South_Africa',
|
||||
'A/Prickly_Pear_Cays',
|
||||
'A/Prickly_pears_in_Australia',
|
||||
'A/Opuntia',
|
||||
'A/Prickly_Pear_(British_Virgin_Islands)',
|
||||
'A/Prickly_Pear_Island',
|
||||
'A/Prickly_Pears_(film)',
|
||||
'A/Invasive_succulent_plants_in_South_Africa',
|
||||
'A/Cactoblastis_Memorial_Hall',
|
||||
'A/Thomas_Harvey_Johnston']
|
||||
|
||||
|
||||
def test_zim_tags_config(test_session, test_directory, test_zim, tag_factory, test_tags_config, fake_now):
|
||||
fake_now(datetime.datetime(2000, 1, 1, 0, 0, 0, 1))
|
||||
config = tags.get_tags_config()
|
||||
assert not config.tag_zims
|
||||
|
||||
# Tag three Zim entries.
|
||||
tag1, tag2 = tag_factory('Tag1'), tag_factory('Tag2')
|
||||
test_zim.tag_entry(tag1.name, 'one')
|
||||
test_zim.tag_entry(tag2.name, 'one')
|
||||
test_zim.tag_entry(tag1.name, 'two')
|
||||
test_session.commit()
|
||||
# Tags are created in empty database.
|
||||
assert {i[0] for i in test_session.query(tags.Tag.id)} == {1, 2}
|
||||
|
||||
config = tags.get_tags_config()
|
||||
assert config.tag_zims == [
|
||||
['Tag1', test_zim.path.name, 'one', '2000-01-01T00:00:00.000001+00:00'],
|
||||
['Tag2', test_zim.path.name, 'one', '2000-01-01T00:00:00.000001+00:00'],
|
||||
['Tag1', test_zim.path.name, 'two', '2000-01-01T00:00:00.000001+00:00'],
|
||||
]
|
||||
|
||||
# Remove a tag, the config should change.
|
||||
test_zim.untag_entry(tag1.name, 'one')
|
||||
test_session.commit()
|
||||
|
||||
config = tags.get_tags_config()
|
||||
assert config.tag_zims == [
|
||||
['Tag2', test_zim.path.name, 'one', '2000-01-01T00:00:00.000001+00:00'],
|
||||
['Tag1', test_zim.path.name, 'two', '2000-01-01T00:00:00.000001+00:00'],
|
||||
]
|
||||
|
||||
# Delete all Tags so they are recreated.
|
||||
test_session.query(tags.Tag).delete()
|
||||
# Delete all TagFileEntry(s), import them again.
|
||||
test_session.query(TagZimEntry).delete()
|
||||
test_session.commit()
|
||||
|
||||
tags.import_tags_config()
|
||||
|
||||
tag_zim_entries = test_session.query(TagZimEntry) \
|
||||
.order_by(TagZimEntry.zim_id, TagZimEntry.zim_entry)
|
||||
assert [(i.tag.name, i.zim.path, i.zim_entry) for i in tag_zim_entries] \
|
||||
== [('Tag2', test_zim.path, 'one'), ('Tag1', test_zim.path, 'two')]
|
||||
|
||||
# Tags were recreated.
|
||||
assert {i[0] for i in test_session.query(tags.Tag.id)} == {3, 4}
|
||||
|
||||
|
||||
def test_zim_all_entries(test_session, test_zim):
|
||||
entries = [i.__json__() for i in test_zim.all_entries]
|
||||
assert len(entries) == 12
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_zim_download(test_session, kiwix_download_zim, test_directory, test_zim_bytes, flags_lock):
|
||||
await lib.subscribe('Wikipedia (with images)', 'es')
|
||||
|
||||
# Downloading the catalog should lead to a new Zim file being downloaded.
|
||||
await kiwix_download_zim(expected_url='https://download.kiwix.org/zim/wikipedia/wikipedia_es_all_maxi_2023-06.zim')
|
||||
recurring_download, once_download = test_session.query(Download).order_by(Download.id).all()
|
||||
recurring_download: Download
|
||||
once_download: Download
|
||||
assert recurring_download.attempts == 1 and recurring_download.status == 'complete', \
|
||||
'Recurring download should have succeeded'
|
||||
assert not any([i[0] for i in test_session.query(Download.error)]), 'All downloads should have succeeded'
|
||||
assert (test_directory / 'zims/wikipedia_es_all_maxi_2023-06.zim').is_file()
|
||||
assert (test_directory / 'zims/wikipedia_es_all_maxi_2023-06.zim').stat().st_size
|
||||
assert once_download.attempts == 1
|
||||
|
||||
# Download catalog again, should not re-download the existing file.
|
||||
recurring_download.status = 'new'
|
||||
test_session.commit()
|
||||
await kiwix_download_zim(expected_url='https://download.kiwix.org/zim/wikipedia/wikipedia_es_all_maxi_2023-06.zim',
|
||||
download_file_side_effect=Exception('should not be called twice'))
|
||||
recurring_download, once_download = test_session.query(Download).order_by(Download.id).all()
|
||||
assert recurring_download.attempts == 2 and recurring_download.status == 'complete', \
|
||||
'Recurring download should have happened again'
|
||||
assert not any([i[0] for i in test_session.query(Download.error)]), 'All downloads should have succeeded'
|
||||
# New file was modeled into a FileGroup.
|
||||
assert test_session.query(FileGroup).count() == 1
|
||||
# No outdated files exist.
|
||||
assert not flags.outdated_zims.is_set()
|
||||
|
||||
# Download catalog again, should fetch the latest file.
|
||||
recurring_download.status = 'new'
|
||||
test_session.commit()
|
||||
await kiwix_download_zim(expected_url='https://download.kiwix.org/zim/wikipedia/wikipedia_es_all_maxi_2024-01.zim',
|
||||
download_info=DownloadFileInfo(
|
||||
status=HTTPStatus.OK,
|
||||
name='wikipedia_es_all_maxi_2024-01.zim',
|
||||
size=len(test_zim_bytes),
|
||||
),
|
||||
hrefs=['?C=N;O=D', '?C=M;O=A', '?C=S;O=A', '?C=D;O=A', '/zim/',
|
||||
'wikipedia_es_all_maxi_2023-05.zim',
|
||||
'wikipedia_es_all_maxi_2023-06.zim',
|
||||
'wikipedia_es_all_maxi_2024-01.zim', # The new Zim.
|
||||
'wikipedia_es_all_nopic_2023-05.zim',
|
||||
'wikipedia_es_all_nopic_2023-06.zim', ]
|
||||
)
|
||||
recurring_download, first_download, second_download = test_session.query(Download).order_by(Download.id).all()
|
||||
assert recurring_download.attempts == 3 and recurring_download.status == 'complete', \
|
||||
'Recurring download should have happened again'
|
||||
assert not any([i[0] for i in test_session.query(Download.error)]), 'All downloads should have succeeded'
|
||||
assert (test_directory / 'zims/wikipedia_es_all_maxi_2023-06.zim').is_file()
|
||||
assert (test_directory / 'zims/wikipedia_es_all_maxi_2023-06.zim').stat().st_size
|
||||
assert (test_directory / 'zims/wikipedia_es_all_maxi_2024-01.zim').is_file()
|
||||
assert (test_directory / 'zims/wikipedia_es_all_maxi_2024-01.zim').stat().st_size
|
||||
# New file was modeled.
|
||||
assert test_session.query(FileGroup).count() == 2
|
||||
# But old file is now outdated.
|
||||
assert flags.outdated_zims.is_set()
|
||||
|
||||
# Delete the outdated file.
|
||||
await lib.remove_outdated_zim_files()
|
||||
assert test_session.query(FileGroup).count() == 1
|
||||
# No longer outdated
|
||||
assert not flags.outdated_zims.is_set()
|
||||
|
||||
|
||||
def test_zim_tag_migration(test_session, test_directory, zim_factory, tag_factory, test_tags_config):
|
||||
"""When an outdated Zim file is deleted, the Tags should be moved to the latest Zim."""
|
||||
zim1 = zim_factory('wikipedia_en_all_maxi_2020-01.zim') # The outdated Zim.
|
||||
zim2 = zim_factory('wikipedia_en_all_maxi_2020-02.zim')
|
||||
zim3 = zim_factory('wikipedia_en_all_maxi_2020-03.zim') # The latest Zim.
|
||||
tag1, tag2 = tag_factory('tag1'), tag_factory('tag2')
|
||||
# Tag outdated Zim entries.
|
||||
zim1.tag_entry(tag1.name, 'home')
|
||||
zim1.tag_entry(tag2.name, 'one')
|
||||
# This should not be migrated.
|
||||
zim2.tag_entry(tag2.name, 'two')
|
||||
# Tag the latest Zim as well.
|
||||
zim3.tag_entry(tag2.name, 'one')
|
||||
test_session.commit()
|
||||
assert test_session.query(TagZimEntry).count() == 4
|
||||
|
||||
# All Zims have been tagged.
|
||||
tags_config = tags.get_tags_config()
|
||||
tags_config.save_tags(session=test_session)
|
||||
assert 'wikipedia_en_all_maxi_2020-01.zim' in (config_text := tags_config.get_file().read_text())
|
||||
assert 'wikipedia_en_all_maxi_2020-02.zim' in config_text
|
||||
assert 'wikipedia_en_all_maxi_2020-03.zim' in config_text
|
||||
|
||||
# Zim was deleted, as well as it's ZimTagEntry(s).
|
||||
zim1.delete()
|
||||
tags.import_tags_config(test_session)
|
||||
|
||||
tag_zim_entries = sorted([(i.tag.name, i.zim.path, i.zim_entry) for i in test_session.query(TagZimEntry)])
|
||||
assert tag_zim_entries == [
|
||||
('tag1', zim3.path, 'home'),
|
||||
('tag2', zim2.path, 'two'),
|
||||
('tag2', zim3.path, 'one'), # Both "one" tags were combined.
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'url,expected',
|
||||
[
|
||||
('https://download.kiwix.org/zim/wikipedia/wikipedia_arz_all_maxi_', ('Wikipedia (with images)', 'arz')),
|
||||
('https://download.kiwix.org/zim/wikipedia/wikipedia_arz_all_nopic_', ('Wikipedia (no images)', 'arz')),
|
||||
('https://download.kiwix.org/zim/wikipedia/wikipedia_ar_all_mini_', ('Wikipedia (mini)', 'ar')),
|
||||
('https://download.kiwix.org/zim/wikiversity/wikiversity_zh_all_maxi_', ('Wikiversity (with images)', 'zh')),
|
||||
('https://download.kiwix.org/zim/wikiversity/wikiversity_zh_all_nopic_', ('Wikiversity (no images)', 'zh')),
|
||||
('https://download.kiwix.org/zim/wiktionary/wiktionary_eo_all_maxi_', ('Wikitionary (with images)', 'eo')),
|
||||
('https://download.kiwix.org/zim/wiktionary/wiktionary_eo_all_nopic_', ('Wikitionary (no images)', 'eo')),
|
||||
('https://download.kiwix.org/zim/wikibooks/wikibooks_es_all_nopic_', ('Wikibooks (no images)', 'es')),
|
||||
('https://download.kiwix.org/zim/wikibooks/wikibooks_es_all_maxi_', ('Wikibooks (with images)', 'es')),
|
||||
('https://download.kiwix.org/zim/wikisource/wikisource_bn_all_maxi_', ('Wikisource', 'bn')),
|
||||
('https://download.kiwix.org/zim/vikidia/vikidia_ru_all_maxi_', ('Vikidia', 'ru')),
|
||||
('https://download.kiwix.org/zim/stack_exchange/raspberrypi.stackexchange.com_en_all_',
|
||||
('Raspberry Pi (Stack Exchange)', 'en')),
|
||||
('https://download.kiwix.org/zim/stack_exchange/stackoverflow.com_en_all_',
|
||||
('Stackoverflow (Stack Exchange)', 'en')),
|
||||
('https://download.kiwix.org/zim/stack_exchange/ja.stackoverflow.com_ja_all_',
|
||||
('Stackoverflow (Stack Exchange)', 'ja')),
|
||||
('https://download.kiwix.org/zim/stack_exchange/superuser.com_en_all_', ('Superuser (Stack Exchange)', 'en')),
|
||||
('https://download.kiwix.org/zim/ifixit/ifixit_nl_all_', ('iFixit', 'nl')),
|
||||
('https://download.kiwix.org/zim/gutenberg/gutenberg_ang_all_', ('Gutenberg', 'ang')),
|
||||
]
|
||||
)
|
||||
def test_zim_download_url_to_name(url, expected):
|
||||
assert lib.zim_download_url_to_name(url) == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_zim_subscription_download_import(test_session, test_downloader_config):
|
||||
# Subscription creates a ZimSubscription and Download
|
||||
await lib.subscribe('Wikisource', 'en', session=test_session)
|
||||
# Add a once-download. This should not be associated with a ZimSubscription.
|
||||
test_session.add(
|
||||
Download(url='https://download.kiwix.org/zim/wikibooks/wikibooks_en_all_maxi_2021-03.zim', status='complete'))
|
||||
test_session.commit()
|
||||
download = test_session.query(Download).filter(Download.frequency.isnot(None)).one()
|
||||
assert download.url == 'https://download.kiwix.org/zim/wikisource/wikisource_en_all_maxi_'
|
||||
|
||||
# Save config file, delete all entries.
|
||||
await save_downloads_config()
|
||||
test_session.query(Download).delete()
|
||||
test_session.query(ZimSubscription).delete()
|
||||
test_session.commit()
|
||||
|
||||
for _ in range(1): # Import twice.
|
||||
# Importing the config restores the Download and ZimSubscription.
|
||||
await import_downloads_config(session=test_session)
|
||||
recurring, once = test_session.query(Download).order_by(Download.frequency)
|
||||
assert once.url == 'https://download.kiwix.org/zim/wikibooks/wikibooks_en_all_maxi_2021-03.zim'
|
||||
assert test_session.query(Download).count() == 2
|
||||
assert recurring.url == 'https://download.kiwix.org/zim/wikisource/wikisource_en_all_maxi_'
|
||||
assert recurring.frequency
|
||||
subscription: ZimSubscription = test_session.query(ZimSubscription).one()
|
||||
assert subscription.download_id == recurring.id
|
||||
assert subscription.name == 'Wikisource'
|
||||
assert subscription.language == 'en'
|
||||
Loading…
Add table
Add a link
Reference in a new issue