mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-26 18:06:17 -05:00
Adding TRACE level for logging beyond debug. Reworking async_client for tests, not all tests need the App to handle signals, so any test that needs signals can use the new await_switches fixture which primes the app.
This commit is contained in:
parent
376850ceeb
commit
7d6b7114a7
34 changed files with 416 additions and 357 deletions
|
|
@ -19,7 +19,7 @@ jobs:
|
|||
- run: sudo apt-get update
|
||||
- run: sudo apt-get install -y ffmpeg catdoc
|
||||
- restore_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-4
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-5
|
||||
- run:
|
||||
name: Install Requirements
|
||||
command: |
|
||||
|
|
@ -27,7 +27,7 @@ jobs:
|
|||
. venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
- save_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-4
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-5
|
||||
paths:
|
||||
- "venv"
|
||||
- run:
|
||||
|
|
@ -46,7 +46,7 @@ jobs:
|
|||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-4
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-5
|
||||
- run:
|
||||
name: Install Requirements
|
||||
command: |
|
||||
|
|
@ -54,7 +54,7 @@ jobs:
|
|||
. venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
- save_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-4
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-5
|
||||
paths:
|
||||
- "venv"
|
||||
- run:
|
||||
|
|
@ -73,7 +73,7 @@ jobs:
|
|||
- run: sudo apt-get update
|
||||
- run: sudo apt-get install -y ffmpeg catdoc
|
||||
- restore_cache:
|
||||
key: deps-3.12-{{ checksum "requirements.txt" }}-4
|
||||
key: deps-3.12-{{ checksum "requirements.txt" }}-5
|
||||
- run:
|
||||
name: Install Requirements
|
||||
command: |
|
||||
|
|
@ -81,7 +81,7 @@ jobs:
|
|||
. venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
- save_cache:
|
||||
key: deps-3.12-{{ checksum "requirements.txt" }}-4
|
||||
key: deps-3.12-{{ checksum "requirements.txt" }}-5
|
||||
paths:
|
||||
- "venv"
|
||||
- run:
|
||||
|
|
@ -92,7 +92,7 @@ jobs:
|
|||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-4
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-5
|
||||
- run:
|
||||
name: Install dependencies
|
||||
command: |
|
||||
|
|
|
|||
|
|
@ -129,7 +129,7 @@ export function ChannelPage({create, header}) {
|
|||
try {
|
||||
if (create !== undefined) {
|
||||
// Can create a Channel with a Tag.
|
||||
body.tag_name = channel.tag_name;
|
||||
body.tag_name = _.isEmpty(channel.tag_name) ? null : channel.tag_name[0];
|
||||
response = await createChannel(body);
|
||||
} else {
|
||||
response = await updateChannel(channelId, body);
|
||||
|
|
|
|||
|
|
@ -136,7 +136,7 @@ export function RestartButton() {
|
|||
}
|
||||
|
||||
const levelNameMap = {
|
||||
5: 'All',
|
||||
5: 'Trace',
|
||||
4: 'Debug',
|
||||
3: 'Info',
|
||||
2: 'Warning',
|
||||
|
|
@ -155,14 +155,14 @@ function fromApiLogLevel(logLevel) {
|
|||
30: 2,
|
||||
20: 3,
|
||||
10: 4,
|
||||
0: 5,
|
||||
5: 5,
|
||||
}[logLevel]
|
||||
}
|
||||
|
||||
function toApiLogLevel(logLevel) {
|
||||
// Reverse the above levels.
|
||||
return {
|
||||
5: 0,
|
||||
5: 5,
|
||||
4: 10,
|
||||
3: 20,
|
||||
2: 30,
|
||||
|
|
@ -380,7 +380,7 @@ export function SettingsPage() {
|
|||
<option value='2'>Warning</option>
|
||||
<option value='3'>Info</option>
|
||||
<option value='4'>Debug</option>
|
||||
<option value='5'>All</option>
|
||||
<option value='5'>Trace</option>
|
||||
</datalist>
|
||||
|
||||
<br/>
|
||||
|
|
|
|||
|
|
@ -806,12 +806,6 @@ export const useSettings = () => {
|
|||
setSettings(await getSettings())
|
||||
} catch (e) {
|
||||
setSettings({});
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Unexpected server response',
|
||||
description: 'Could not get directories',
|
||||
time: 5000,
|
||||
});
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
|
|
|
|||
20
help.sh
20
help.sh
|
|
@ -138,7 +138,7 @@ if [ -f /etc/systemd/system/wrolpi-api.service ]; then
|
|||
fi
|
||||
fi
|
||||
|
||||
if curl -s http://0.0.0.0:8081/api/echo | grep -i '"method":"GET"' >/dev/null; then
|
||||
if curl -s http://0.0.0.0:8081/api/echo --max-time 5 | grep -i '"method":"GET"' >/dev/null; then
|
||||
echo "OK: WROLPi API echoed correctly"
|
||||
else
|
||||
echo "FAILED: WROLPi API did not echo correctly"
|
||||
|
|
@ -173,13 +173,13 @@ if [ -f /etc/systemd/system/wrolpi-app.service ]; then
|
|||
fi
|
||||
fi
|
||||
|
||||
if curl -s http://0.0.0.0:3000 | grep -i wrolpi >/dev/null; then
|
||||
if curl -s http://0.0.0.0:3000 --max-time 5 | grep -i wrolpi >/dev/null; then
|
||||
echo "OK: WROLPi app responded with UI"
|
||||
else
|
||||
echo "FAILED: WROLPi app did not respond with UI"
|
||||
fi
|
||||
|
||||
if curl -s http://0.0.0.0:3000/epub/epub.html | grep -i epub.js >/dev/null; then
|
||||
if curl -s http://0.0.0.0:3000/epub/epub.html --max-time 5 | grep -i epub.js >/dev/null; then
|
||||
echo "OK: WROLPi app responded with ebook interface"
|
||||
else
|
||||
echo "FAILED: WROLPi app did not respond with ebook interface"
|
||||
|
|
@ -218,7 +218,7 @@ else
|
|||
echo "FAILED: renderd systemd does not exist"
|
||||
fi
|
||||
|
||||
if curl -k -s https://0.0.0.0:8084 2>/dev/null | grep -i openstreetmap >/dev/null; then
|
||||
if curl -k -s https://0.0.0.0:8084 --max-time 5 2>/dev/null | grep -i openstreetmap >/dev/null; then
|
||||
echo "OK: Map app responded"
|
||||
else
|
||||
echo "FAILED: Map app did not respond"
|
||||
|
|
@ -232,7 +232,7 @@ echo
|
|||
# Kiwix
|
||||
|
||||
check_file /media/wrolpi/zims/library.xml "The kiwix library file exists" "The kiwix library file does not exist at /media/wrolpi/zims/library.xml"
|
||||
if curl -k -s https://0.0.0.0:8085 2>/dev/null | grep -i kiwix >/dev/null; then
|
||||
if curl -k -s https://0.0.0.0:8085 --max-time 5 2>/dev/null | grep -i kiwix >/dev/null; then
|
||||
echo "OK: Kiwix app responded"
|
||||
else
|
||||
echo "FAILED: Kiwix app did not respond"
|
||||
|
|
@ -255,9 +255,9 @@ else
|
|||
echo "FAILED: Media directory is not a mounted drive. (This is fine if you don't have an external drive.)"
|
||||
fi
|
||||
|
||||
if curl -k -s https://0.0.0.0/media/ | grep "Index of /media/" >/dev/null; then
|
||||
if curl -k -s https://0.0.0.0/media/ --max-time 5 | grep "Index of /media/" >/dev/null; then
|
||||
echo "OK: Media directory files are served by nginx"
|
||||
if curl -k -s -I https://0.0.0.0/media/config/wrolpi.yaml | grep '200 OK' >/dev/null; then
|
||||
if curl -k -s -I https://0.0.0.0/media/config/wrolpi.yaml --max-time 5 | grep '200 OK' >/dev/null; then
|
||||
echo "OK: Config can be fetched from nginx"
|
||||
else
|
||||
echo "FAILED: Media directory files are not being served"
|
||||
|
|
@ -266,9 +266,9 @@ else
|
|||
echo "FAILED: Media directory files are not being served"
|
||||
fi
|
||||
|
||||
if curl -k -s https://0.0.0.0/download/ | grep "Index of /download/" >/dev/null; then
|
||||
if curl -k -s https://0.0.0.0/download/ --max-time 5 | grep "Index of /download/" >/dev/null; then
|
||||
echo "OK: Media download directory files are served by nginx"
|
||||
if curl -k -s -I https://0.0.0.0/download/config/wrolpi.yaml | grep '200 OK' >/dev/null; then
|
||||
if curl -k -s -I https://0.0.0.0/download/config/wrolpi.yaml --max-time 5 | grep '200 OK' >/dev/null; then
|
||||
echo "OK: Config can be downloaded from nginx"
|
||||
else
|
||||
echo "FAILED: Media download directory files are not being served"
|
||||
|
|
@ -337,7 +337,7 @@ else
|
|||
echo "FAILED: Help mkdocs cannot be run"
|
||||
fi
|
||||
|
||||
if curl -k -s https://0.0.0.0:8086/ | grep MkDocs 2>/dev/null >/dev/null; then
|
||||
if curl -k -s https://0.0.0.0:8086/ --max-time 5 | grep MkDocs 2>/dev/null >/dev/null; then
|
||||
echo "OK: Help service is running"
|
||||
else
|
||||
echo "FAILED: Help service is not running"
|
||||
|
|
|
|||
24
main.py
24
main.py
|
|
@ -18,7 +18,7 @@ from wrolpi import tags
|
|||
from wrolpi.api_utils import api_app, perpetual_signal
|
||||
from wrolpi.common import logger, check_media_directory, set_log_level, limit_concurrent, \
|
||||
cancel_refresh_tasks, cancel_background_tasks, get_wrolpi_config, can_connect_to_server, wrol_mode_enabled, \
|
||||
initialize_config_files
|
||||
create_empty_config_files, TRACE_LEVEL
|
||||
from wrolpi.contexts import attach_shared_contexts, reset_shared_contexts, initialize_configs_contexts
|
||||
from wrolpi.dates import Seconds
|
||||
from wrolpi.downloader import import_downloads_config, download_manager
|
||||
|
|
@ -131,7 +131,7 @@ def main():
|
|||
set_log_level(logging.DEBUG)
|
||||
elif args.verbose and args.verbose >= 3:
|
||||
# Log everything. Add SQLAlchemy debug logging.
|
||||
set_log_level(logging.NOTSET)
|
||||
set_log_level(TRACE_LEVEL)
|
||||
logger.info(get_version_string())
|
||||
|
||||
if DOCKERIZED:
|
||||
|
|
@ -171,12 +171,10 @@ async def main_process_startup(app: Sanic):
|
|||
attach_shared_contexts(app)
|
||||
logger.debug('main_process_startup done')
|
||||
|
||||
download_manager.disable()
|
||||
|
||||
try:
|
||||
initialize_config_files()
|
||||
create_empty_config_files()
|
||||
except Exception as e:
|
||||
logger.error('Failed to initialize config files', exc_info=e)
|
||||
logger.error('Failed to create initial config files', exc_info=e)
|
||||
|
||||
|
||||
@api_app.listener('after_server_start') # FileConfigs need to be initialized first.
|
||||
|
|
@ -259,7 +257,7 @@ async def start_single_tasks(app: Sanic):
|
|||
# Set all downloads to new.
|
||||
download_manager.retry_downloads()
|
||||
|
||||
if get_wrolpi_config().download_on_startup:
|
||||
if get_wrolpi_config().download_on_startup and download_manager.can_download:
|
||||
await download_manager.enable()
|
||||
|
||||
# Hotspot/throttle are not supported in Docker containers.
|
||||
|
|
@ -330,20 +328,16 @@ async def perpetual_start_video_missing_comments_download():
|
|||
# Wait for download manager to startup.
|
||||
await asyncio.sleep(5)
|
||||
|
||||
# Fetch comments for videos every hour.
|
||||
if download_manager.is_disabled or download_manager.is_stopped:
|
||||
logger.debug('Waiting for downloads to be enabled before downloading comments...')
|
||||
return
|
||||
elif not flags.have_internet.is_set():
|
||||
logger.debug('Waiting for internet before downloading comments...')
|
||||
return
|
||||
else:
|
||||
if download_manager.can_download:
|
||||
try:
|
||||
await get_missing_videos_comments()
|
||||
except Exception as e:
|
||||
logger.error('Failed to get missing video comments', exc_info=e)
|
||||
|
||||
# Sleep one hour.
|
||||
await asyncio.sleep(int(Seconds.hour))
|
||||
else:
|
||||
logger.debug('Waiting for downloads to be enabled before downloading comments...')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ from pint import Quantity
|
|||
|
||||
from wrolpi.common import Base
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.test.common import PytestCase
|
||||
from .. import init_inventory
|
||||
from ..common import sum_by_key, get_inventory_by_category, get_inventory_by_subcategory, get_inventory_by_name, \
|
||||
|
|
@ -274,7 +273,7 @@ def test_no_inventories(async_client, test_session, test_directory):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inventories_config(async_client, test_session, test_directory, init_test_inventory):
|
||||
async def test_inventories_config(await_switches, test_session, test_directory, init_test_inventory):
|
||||
for item in TEST_ITEMS:
|
||||
item = Item(**item)
|
||||
test_session.add(item)
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ from wrolpi import flags
|
|||
from wrolpi.common import logger, \
|
||||
get_media_directory, wrol_mode_check, background_task
|
||||
from wrolpi.db import get_db_curs, optional_session, get_db_session
|
||||
from wrolpi.downloader import save_downloads_config, download_manager
|
||||
from wrolpi.downloader import save_downloads_config, download_manager, Download
|
||||
from wrolpi.errors import APIError, ValidationError, RefreshConflict
|
||||
from wrolpi.vars import PYTEST
|
||||
from .. import schema
|
||||
|
|
@ -248,7 +248,7 @@ async def update_channel_download(channel_id: int, download_id: int, url: str, f
|
|||
with get_db_session(commit=True) as session:
|
||||
# Ensure that the Channel exists.
|
||||
Channel.find_by_id(channel_id, session=session)
|
||||
download = download_manager.get_download(session, id_=download_id)
|
||||
download = Download.find_by_id(download_id, session=session)
|
||||
download.url = url
|
||||
download.frequency = frequency
|
||||
download.settings = settings
|
||||
|
|
|
|||
|
|
@ -16,9 +16,8 @@ from modules.videos.models import Channel, Video
|
|||
from wrolpi.common import get_relative_to_media_directory, walk
|
||||
from wrolpi.dates import now
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.downloader import download_manager, Download, DownloadResult
|
||||
from wrolpi.downloader import Download, DownloadResult
|
||||
from wrolpi.files.models import Directory
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.test.common import assert_dict_contains
|
||||
|
||||
|
||||
|
|
@ -57,25 +56,26 @@ def test_get_video(test_client, test_session, simple_channel, video_factory):
|
|||
assert_dict_contains(response.json['next'], {'title': 'vid2'})
|
||||
|
||||
|
||||
def test_channel_no_download_frequency(test_client, test_session, test_directory, simple_channel):
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_no_download_frequency(async_client, test_session, test_directory, simple_channel, test_download_manager):
|
||||
"""A channel does not require a download frequency."""
|
||||
# No downloads are scheduled.
|
||||
assert len(download_manager.get_downloads(test_session)) == 0
|
||||
assert len(test_download_manager.get_downloads(test_session)) == 0
|
||||
|
||||
# Get the Channel
|
||||
request, response = test_client.get('/api/videos/channels/1')
|
||||
request, response = await async_client.get('/api/videos/channels/1')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
channel = response.json['channel']
|
||||
assert not channel['downloads']
|
||||
|
||||
# Update the Channel with a frequency.
|
||||
new_download = {'urls': [simple_channel.url], 'frequency': 10, 'downloader': ChannelDownloader.name}
|
||||
request, response = test_client.post('/api/download', json=new_download)
|
||||
request, response = await async_client.post('/api/download', json=new_download)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.json
|
||||
|
||||
# Download is scheduled. Download is related to Channel.
|
||||
assert len(download_manager.get_downloads(test_session)) == 1
|
||||
request, response = test_client.get('/api/videos/channels/1')
|
||||
assert len(test_download_manager.get_downloads(test_session)) == 1
|
||||
request, response = await async_client.get('/api/videos/channels/1')
|
||||
channel = response.json['channel']
|
||||
assert channel['downloads']
|
||||
downloads = channel['downloads']
|
||||
|
|
@ -84,9 +84,9 @@ def test_channel_no_download_frequency(test_client, test_session, test_directory
|
|||
download_id = channel['downloads'][0]['id']
|
||||
|
||||
# Deleting Download does not delete Channel.
|
||||
request, response = test_client.delete(f'/api/download/{download_id}')
|
||||
request, response = await async_client.delete(f'/api/download/{download_id}')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
|
||||
assert not download_manager.get_downloads(test_session)
|
||||
assert not test_download_manager.get_downloads(test_session)
|
||||
assert not test_session.query(Download).all()
|
||||
assert test_session.query(Channel).count() == 1
|
||||
|
||||
|
|
@ -191,7 +191,7 @@ def test_channel_empty_url_doesnt_conflict(test_client, test_session, test_direc
|
|||
@pytest.mark.asyncio
|
||||
async def test_channel_download_requires_refresh(
|
||||
async_client, test_session, mock_video_extract_info, download_channel, video_download_manager,
|
||||
video_factory, events_history):
|
||||
video_factory, events_history, await_switches):
|
||||
"""A Channel cannot be downloaded until it has been refreshed.
|
||||
|
||||
Videos already downloaded are not downloaded again."""
|
||||
|
|
@ -464,7 +464,7 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f
|
|||
tag = await tag_factory('Tag Name')
|
||||
v1, v2 = video_factory(title='video1', channel_id=channel.id), video_factory(title='video2', channel_id=channel.id)
|
||||
# Create recurring download which uses the Channel's directory.
|
||||
download = download_manager.recurring_download('https://example.com/1', 60, test_downloader.name,
|
||||
download = test_download_manager.recurring_download('https://example.com/1', 60, test_downloader.name,
|
||||
destination=str(test_directory / 'videos/Channel Name'))
|
||||
test_session.commit()
|
||||
save_channels_config()
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ from modules.videos.channel import lib
|
|||
from modules.videos.errors import UnknownChannel
|
||||
from modules.videos.lib import save_channels_config, import_channels_config
|
||||
from modules.videos.models import Channel
|
||||
from wrolpi.switches import await_switches
|
||||
|
||||
|
||||
@pytest.mark.parametrize('params', [
|
||||
|
|
@ -130,7 +129,7 @@ async def test_search_channels_by_name(test_session, channel_factory, video_fact
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tag_channel_existing(async_client, test_session, test_directory, channel_factory, tag_factory,
|
||||
video_factory, test_channels_config):
|
||||
video_factory, test_channels_config, await_switches):
|
||||
"""A Channel already in a Tag's directory can still be tagged."""
|
||||
channel_directory = test_directory / 'videos/one/Channel Name'
|
||||
channel = channel_factory(name='Channel Name', download_frequency=120, directory=channel_directory)
|
||||
|
|
|
|||
|
|
@ -605,7 +605,7 @@ class Channel(ModelHelper, Base):
|
|||
if isinstance(download, dict):
|
||||
url = download['url']
|
||||
# Use download frequency from downloads config before the channels config.
|
||||
if existing_download := download_manager.get_download(session, url):
|
||||
if existing_download := Download.get_by_url(url, session=session):
|
||||
frequency = existing_download.frequency
|
||||
else:
|
||||
frequency = download.get('frequency')
|
||||
|
|
@ -768,7 +768,7 @@ class Channel(ModelHelper, Base):
|
|||
|
||||
from modules.videos.downloader import ChannelDownloader, VideoDownloader
|
||||
|
||||
download = download_manager.get_download(session, url)
|
||||
download = Download.get_by_url(url, session=session)
|
||||
if not download:
|
||||
download = download_manager.recurring_download(url, frequency, ChannelDownloader.name, session=session,
|
||||
sub_downloader_name=VideoDownloader.name,
|
||||
|
|
|
|||
|
|
@ -11,13 +11,11 @@ from modules.videos.models import Channel, Video
|
|||
from wrolpi.common import get_absolute_media_path, get_wrolpi_config
|
||||
from wrolpi.downloader import Download, DownloadFrequency
|
||||
from wrolpi.files import lib as files_lib
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
from .. import common
|
||||
from ..common import convert_image, update_view_counts_and_censored, extract_video_duration, generate_video_poster, \
|
||||
is_valid_poster
|
||||
from ..lib import save_channels_config, get_channels_config, import_channels_config, ChannelsConfig, \
|
||||
convert_or_generate_poster
|
||||
from ..lib import save_channels_config, get_channels_config, import_channels_config, ChannelsConfig
|
||||
|
||||
|
||||
def test_get_absolute_media_path(test_directory):
|
||||
|
|
@ -137,7 +135,7 @@ def test_generate_video_poster(video_file):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_import_channel_downloads(async_client, test_session, channel_factory, test_channels_config,
|
||||
async def test_import_channel_downloads(await_switches, test_session, channel_factory, test_channels_config,
|
||||
tag_factory):
|
||||
"""Importing the Channels' config should create any missing download records"""
|
||||
channel1 = channel_factory(source_id='foo', url='https://example.com/channel1')
|
||||
|
|
@ -248,8 +246,8 @@ async def test_import_channel_downloads(async_client, test_session, channel_fact
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_import_channel_delete_missing_channels(
|
||||
async_client, test_session, channel_factory, test_channels_config):
|
||||
async def test_import_channel_delete_missing_channels(await_switches, test_session, channel_factory,
|
||||
test_channels_config):
|
||||
"""The Channel import function deletes any Channels that are not in the config."""
|
||||
# Create a DB and config with two Channels.
|
||||
channel1 = channel_factory(source_id='foo')
|
||||
|
|
|
|||
|
|
@ -10,10 +10,9 @@ import pytest
|
|||
from modules.videos.downloader import VideoDownloader, \
|
||||
get_or_create_channel, channel_downloader, video_downloader, preview_filename
|
||||
from modules.videos.models import Channel, Video
|
||||
from wrolpi.conftest import test_directory
|
||||
from wrolpi.conftest import test_directory, await_switches
|
||||
from wrolpi.downloader import Download, DownloadResult
|
||||
from wrolpi.errors import InvalidDownload
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
|
||||
example_video_json = {
|
||||
|
|
@ -78,7 +77,7 @@ example_channel_json = {
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_no_channel(test_session, video_download_manager, test_directory,
|
||||
async def test_download_no_channel(test_session, video_download_manager, test_directory, await_switches,
|
||||
mock_video_extract_info, mock_video_process_runner):
|
||||
"""A video can be downloaded even if it does not have a Channel."""
|
||||
channel_dir = test_directory / 'NO CHANNEL'
|
||||
|
|
@ -109,7 +108,7 @@ async def test_download_no_channel(test_session, video_download_manager, test_di
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_video_tags(test_session, video_download_manager, video_file_factory, test_directory,
|
||||
mock_video_extract_info, mock_video_process_runner, tag_factory):
|
||||
mock_video_extract_info, mock_video_process_runner, tag_factory, await_switches):
|
||||
"""A Video is tagged when Download record requires it."""
|
||||
video_path = video_file_factory()
|
||||
tag1, tag2 = await tag_factory(), await tag_factory()
|
||||
|
|
@ -130,7 +129,7 @@ async def test_download_video_tags(test_session, video_download_manager, video_f
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_channel(test_session, test_directory, simple_channel, video_download_manager, video_file,
|
||||
mock_video_extract_info, mock_video_prepare_filename,
|
||||
mock_video_extract_info, mock_video_prepare_filename, await_switches,
|
||||
mock_video_process_runner):
|
||||
"""Downloading (updating the catalog of) a Channel updates its info_json.
|
||||
|
||||
|
|
@ -198,7 +197,7 @@ async def test_download_channel(test_session, test_directory, simple_channel, vi
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_or_create_channel(async_client, test_session, test_directory, tag_factory):
|
||||
async def test_get_or_create_channel(async_client, test_session, test_directory, tag_factory, await_switches):
|
||||
"""A Channel may need to be created for an arbitrary download.
|
||||
|
||||
Attempt to use an existing Channel if we can match it.
|
||||
|
|
@ -269,7 +268,7 @@ def test_bad_downloader(test_session, video_download_manager):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_download(test_session, test_directory, mock_video_extract_info, simple_channel,
|
||||
async def test_video_download(test_session, test_directory, mock_video_extract_info, simple_channel, await_switches,
|
||||
video_download_manager, mock_video_process_runner, image_file):
|
||||
"""A video download is performed, files are grouped."""
|
||||
simple_channel.source_id = example_video_json['channel_id']
|
||||
|
|
@ -311,7 +310,7 @@ async def test_video_download(test_session, test_directory, mock_video_extract_i
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_result(test_session, test_directory, video_download_manager, mock_video_process_runner,
|
||||
mock_video_extract_info, image_file):
|
||||
mock_video_extract_info, image_file, await_switches):
|
||||
"""VideoDownloader returns a DownloadResult when complete."""
|
||||
channel_directory = test_directory / 'videos/channel name'
|
||||
channel_directory.mkdir(parents=True)
|
||||
|
|
@ -338,7 +337,7 @@ async def test_download_result(test_session, test_directory, video_download_mana
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_destination(test_session, test_directory, video_download_manager,
|
||||
async def test_download_destination(test_session, test_directory, video_download_manager, await_switches,
|
||||
mock_video_process_runner, mock_video_extract_info, mock_video_prepare_filename):
|
||||
"""A Video can be downloaded to a directory other than it's Channel's directory."""
|
||||
# yt-dlp would return the video json.
|
||||
|
|
|
|||
|
|
@ -108,7 +108,7 @@ def test_get_video_prev_next_no_upload_date(async_client, test_session, video_fa
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_delete(async_client, test_session, channel_factory, video_factory, test_download_manager):
|
||||
async def test_delete_video_api(async_client, test_session, channel_factory, video_factory, test_download_manager):
|
||||
"""Video.delete() removes the video's files, but leave the DB record."""
|
||||
channel1, channel2 = channel_factory(), channel_factory()
|
||||
vid1 = video_factory(channel_id=channel1.id, with_video_file=True, with_caption_file=True,
|
||||
|
|
|
|||
|
|
@ -121,7 +121,7 @@ async def get_zim_subscriptions(_: Request):
|
|||
@validate(schema.ZimSubscribeRequest)
|
||||
async def post_zim_subscribe(_: Request, body: schema.ZimSubscribeRequest):
|
||||
await lib.subscribe(body.name, body.language)
|
||||
if download_manager.disabled.is_set() or download_manager.stopped.is_set():
|
||||
if download_manager.disabled or download_manager.stopped:
|
||||
# Downloads are disabled, warn the user.
|
||||
Events.send_downloads_disabled('Download created. But, downloads are disabled.')
|
||||
Events.send_created(f'Zim subscription created')
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ from wrolpi.common import DownloadFileInfo, get_wrolpi_config
|
|||
from wrolpi.downloader import Download, import_downloads_config, save_downloads_config
|
||||
from wrolpi.files import lib as files_lib
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.switches import await_switches
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -128,7 +127,7 @@ def test_get_unique_paths():
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_zim_tags_config(async_client, test_session, test_directory, test_zim, tag_factory, test_tags_config,
|
||||
fake_now):
|
||||
fake_now, await_switches):
|
||||
fake_now(datetime.datetime(2000, 1, 1, 0, 0, 0, 1))
|
||||
config = tags.get_tags_config()
|
||||
assert not config.tag_zims
|
||||
|
|
@ -184,7 +183,8 @@ def test_zim_all_entries(test_session, test_zim):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_zim_download(test_session, kiwix_download_zim, test_directory, test_zim_bytes, flags_lock):
|
||||
async def test_zim_download(test_session, kiwix_download_zim, test_directory, test_zim_bytes, flags_lock,
|
||||
await_switches):
|
||||
await lib.subscribe('Wikipedia (with images)', 'es')
|
||||
|
||||
# Downloading the catalog should lead to a new Zim file being downloaded.
|
||||
|
|
@ -250,7 +250,7 @@ async def test_zim_download(test_session, kiwix_download_zim, test_directory, te
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_zim_tag_migration(async_client, test_session, test_directory, zim_factory, tag_factory,
|
||||
async def test_zim_tag_migration(await_switches, 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.
|
||||
|
|
|
|||
|
|
@ -133,7 +133,9 @@ systemctl enable renderd
|
|||
if grep -qs /media/wrolpi /proc/mounts && [ -z "$(ls -A /media/wrolpi)" ] && [ ! -d /media/wrolpi/config ]; then
|
||||
mkdir /media/wrolpi/config
|
||||
fi
|
||||
chown wrolpi:wrolpi /media/wrolpi
|
||||
|
||||
# Change owner of the media directory, ignore any errors because the drive may be fat/exfat/etc.
|
||||
chown wrolpi:wrolpi /media/wrolpi 2>/dev/null || echo "Ignoring failure to change media directory permissions."
|
||||
|
||||
chown -R wrolpi:wrolpi /home/wrolpi /opt/wrolpi*
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from pathlib import Path
|
|||
|
||||
from sanic import response, HTTPResponse, Request, Sanic, SanicException
|
||||
|
||||
from wrolpi.common import Base, get_media_directory, logger, LOGGING_CONFIG
|
||||
from wrolpi.common import Base, get_media_directory, logger, LOGGING_CONFIG, TRACE_LEVEL
|
||||
from wrolpi.errors import APIError
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
|
@ -102,7 +102,8 @@ def json_error_handler(request: Request, exception: Exception):
|
|||
message = repr(str(body["message"]))
|
||||
code = body['code']
|
||||
if logger.isEnabledFor(logging.DEBUG):
|
||||
logger.error(f'API returning JSON error {type(exception).__name__} {error=} {message=} {code=}', exc_info=exception)
|
||||
logger.error(f'API returning JSON error {type(exception).__name__} {error=} {message=} {code=}',
|
||||
exc_info=exception)
|
||||
else:
|
||||
logger.error(f'API returning JSON error {type(exception).__name__} {error=} {message=} {code=}')
|
||||
if isinstance(exception, SanicException):
|
||||
|
|
@ -150,8 +151,9 @@ def perpetual_signal(event: str = None, sleep: int | float = 1):
|
|||
# Wrap the function in a worker that will call it perpetually.
|
||||
@api_app.signal(event_)
|
||||
async def worker(*args, **kwargs):
|
||||
logger.log(logging.NOTSET, f'perpetual_signal {event_}')
|
||||
logger.trace(f'perpetual_signal {event_}')
|
||||
cancelled = False
|
||||
start = datetime.now()
|
||||
try:
|
||||
await func(*args, **kwargs)
|
||||
except CancelledError:
|
||||
|
|
@ -160,6 +162,9 @@ def perpetual_signal(event: str = None, sleep: int | float = 1):
|
|||
except Exception as e:
|
||||
logger.error(f'Perpetual worker {event_} had error', exc_info=e)
|
||||
finally:
|
||||
if logger.isEnabledFor(TRACE_LEVEL):
|
||||
elapsed = (datetime.now() - start).total_seconds()
|
||||
logger.trace(f'perpetual_signal {event_} took {elapsed} seconds')
|
||||
if not cancelled:
|
||||
await asyncio.sleep(sleep)
|
||||
await api_app.dispatch(event_)
|
||||
|
|
|
|||
|
|
@ -43,7 +43,62 @@ from sqlalchemy.orm import Session
|
|||
from wrolpi.dates import now, from_timestamp, seconds_to_timestamp
|
||||
from wrolpi.errors import WROLModeEnabled, NativeOnly, UnrecoverableDownloadError, LogLevelError, InvalidConfig, \
|
||||
ValidationError
|
||||
from wrolpi.vars import PYTEST, DOCKERIZED, CONFIG_DIR, MEDIA_DIRECTORY, DEFAULT_HTTP_HEADERS, LOG_LEVEL
|
||||
from wrolpi.vars import PYTEST, DOCKERIZED, CONFIG_DIR, MEDIA_DIRECTORY, DEFAULT_HTTP_HEADERS
|
||||
|
||||
|
||||
def add_logging_level(level_name: str, level_int: int, methodName=None):
|
||||
"""
|
||||
Comprehensively adds a new logging level to the `logging` module and the
|
||||
currently configured logging class.
|
||||
|
||||
`levelName` becomes an attribute of the `logging` module with the value
|
||||
`levelNum`. `methodName` becomes a convenience method for both `logging`
|
||||
itself and the class returned by `logging.getLoggerClass()` (usually just
|
||||
`logging.Logger`). If `methodName` is not specified, `levelName.lower()` is
|
||||
used.
|
||||
|
||||
To avoid accidental clobberings of existing attributes, this method will
|
||||
raise an `AttributeError` if the level name is already an attribute of the
|
||||
`logging` module or if the method name is already present
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> add_logging_level('TRACE', logging.DEBUG - 5)
|
||||
>>> logging.getLogger(__name__).setLevel("TRACE")
|
||||
>>> logging.getLogger(__name__).trace('that worked')
|
||||
>>> logging.trace('so did this')
|
||||
>>> logging.TRACE
|
||||
5
|
||||
|
||||
This function is taken directly from: https://stackoverflow.com/questions/2183233/how-to-add-a-custom-loglevel-to-pythons-logging-facility/35804945#35804945
|
||||
"""
|
||||
if not methodName:
|
||||
methodName = level_name.lower()
|
||||
|
||||
if hasattr(logging, level_name):
|
||||
raise AttributeError('{} already defined in logging module'.format(level_name))
|
||||
if hasattr(logging, methodName):
|
||||
raise AttributeError('{} already defined in logging module'.format(methodName))
|
||||
if hasattr(logging.getLoggerClass(), methodName):
|
||||
raise AttributeError('{} already defined in logger class'.format(methodName))
|
||||
|
||||
# This method was inspired by the answers to Stack Overflow post
|
||||
# http://stackoverflow.com/q/2183233/2988730, especially
|
||||
# http://stackoverflow.com/a/13638084/2988730
|
||||
def logForLevel(self, message, *args, **kwargs):
|
||||
if self.isEnabledFor(level_int):
|
||||
kwargs.setdefault('stacklevel', 3)
|
||||
self._log(level_int, message, args, **kwargs)
|
||||
|
||||
def logToRoot(message, *args, **kwargs):
|
||||
kwargs.setdefault('stacklevel', 3)
|
||||
logging.log(level_int, message, *args, **kwargs)
|
||||
|
||||
logging.addLevelName(level_int, level_name)
|
||||
setattr(logging, level_name, level_int)
|
||||
setattr(logging.getLoggerClass(), methodName, logForLevel)
|
||||
setattr(logging, methodName, logToRoot)
|
||||
|
||||
|
||||
LOGGING_CONFIG = {
|
||||
'version': 1,
|
||||
|
|
@ -99,14 +154,26 @@ LOGGING_CONFIG = {
|
|||
},
|
||||
'root': {
|
||||
'handlers': ['console'],
|
||||
'level': LOG_LEVEL
|
||||
'level': logging.DEBUG
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Used so IDE will suggest `logger.trace`
|
||||
class TraceLogger(logging.Logger):
|
||||
def trace(self, msg, *args, **kwargs):
|
||||
return self.log(TRACE_LEVEL, msg, *args, **kwargs)
|
||||
|
||||
|
||||
# Apply logging config.
|
||||
logger = logging.getLogger()
|
||||
logger: TraceLogger = logging.getLogger() # noqa Not really a TraceLogger, but I wanted IDE suggestions.
|
||||
logging.config.dictConfig(LOGGING_CONFIG)
|
||||
|
||||
# Add extra verbose debug level (-vvv)
|
||||
TRACE_LEVEL = logging.DEBUG - 5
|
||||
if not hasattr(logging, 'TRACE'):
|
||||
add_logging_level('TRACE', TRACE_LEVEL)
|
||||
|
||||
logger_ = logger.getChild(__name__)
|
||||
|
||||
|
||||
|
|
@ -129,10 +196,10 @@ def set_log_level(level: int, warn_level: bool = True):
|
|||
for handler in logger.handlers:
|
||||
handler.setLevel(level)
|
||||
|
||||
# Enable debug logging in SQLAlchemy when logging is NOTSET.
|
||||
# Enable debug logging in SQLAlchemy when logging is TRACE.
|
||||
sa_logger = logging.getLogger('sqlalchemy.engine')
|
||||
sa_level = logging.DEBUG if level == logging.NOTSET else logging.WARNING
|
||||
sa_logger.setLevel(sa_level)
|
||||
sa_level = logging.DEBUG if level == TRACE_LEVEL else logging.WARNING
|
||||
sa_logger.setLevel(logging.NOTSET)
|
||||
|
||||
# Hide sanic access logs when not at least "INFO".
|
||||
sanic_access = logging.getLogger('sanic.access')
|
||||
|
|
@ -395,7 +462,7 @@ class ConfigFile:
|
|||
|
||||
def initialize(self, multiprocessing_dict: Optional[DictProxy] = None):
|
||||
"""Initializes this config dict using the default config and the config file."""
|
||||
# Use the provided multiprocessing.Manager().dict(), or dict() for testing.
|
||||
# Use the provided multiprocessing.Manager().dict() when live, or, dict() for testing.
|
||||
self._config = multiprocessing_dict if multiprocessing_dict is not None else dict()
|
||||
# Use the default settings to initialize the config.
|
||||
self._config.update(deepcopy(self.default_config))
|
||||
|
|
@ -1640,14 +1707,15 @@ def timer(name, level: str = 'debug', logger__: logging.Logger = None):
|
|||
time.sleep(10)
|
||||
|
||||
"""
|
||||
level = level.lower()
|
||||
logger__ = logger__ or logger_
|
||||
before = datetime.now()
|
||||
log_method = getattr(logger__, level)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
elapsed = (datetime.now() - before).total_seconds()
|
||||
log_method(f'{name} elapsed {elapsed} seconds')
|
||||
msg = f'{name} elapsed {elapsed} seconds'
|
||||
getattr(logger__, level)(msg)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
|
|
@ -2190,7 +2258,7 @@ def cached_multiprocessing_result(func: callable):
|
|||
return wrapped
|
||||
|
||||
|
||||
def initialize_config_files() -> list[str]:
|
||||
def create_empty_config_files() -> list[str]:
|
||||
"""Creates config files only if they do not exist and will not conflict with the DB."""
|
||||
from modules.inventory.common import get_inventories_config
|
||||
from modules.videos.lib import get_channels_config, get_videos_downloader_config
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ from sqlalchemy.orm import Session, sessionmaker
|
|||
import wrolpi.root_api # noqa
|
||||
from wrolpi import flags
|
||||
from wrolpi.api_utils import api_app
|
||||
from wrolpi.common import iterify, log_level_context, enable_wrol_mode, disable_wrol_mode
|
||||
from wrolpi.common import iterify, log_level_context, enable_wrol_mode, disable_wrol_mode, timer, TRACE_LEVEL
|
||||
from wrolpi.common import logger
|
||||
from wrolpi.common import set_test_media_directory, Base, set_test_config
|
||||
from wrolpi.contexts import attach_shared_contexts, initialize_configs_contexts
|
||||
|
|
@ -45,7 +45,7 @@ from wrolpi.downloader import DownloadManager, DownloadResult, Download, Downloa
|
|||
downloads_manager_config_context
|
||||
from wrolpi.errors import UnrecoverableDownloadError
|
||||
from wrolpi.files.models import Directory, FileGroup
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.switches import await_switches as await_switches_
|
||||
from wrolpi.tags import Tag, upsert_tag
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
|
||||
|
|
@ -100,8 +100,17 @@ def test_session() -> Session:
|
|||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def test_debug_logger(level: int = logging.DEBUG):
|
||||
"""Tests use debug logging by default."""
|
||||
def test_debug_logger(request):
|
||||
"""Tests use debug logging by default. Use pytest's verbosity level if set."""
|
||||
level = logging.INFO
|
||||
verbose = request.config.option.verbose
|
||||
if verbose == 2:
|
||||
# -vv
|
||||
level = logging.DEBUG
|
||||
elif verbose == 3:
|
||||
# -vvv
|
||||
level = TRACE_LEVEL
|
||||
|
||||
with log_level_context(level):
|
||||
yield
|
||||
|
||||
|
|
@ -161,7 +170,7 @@ def test_client(test_directory) -> ReusableClient:
|
|||
@api_app.on_response
|
||||
async def background_task_listener(request, response):
|
||||
"""Wait for all background tasks to finish before returning API response while testing."""
|
||||
await await_switches()
|
||||
await await_switches_()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
|
@ -171,14 +180,10 @@ async def async_client(test_directory) -> SanicASGITestClient:
|
|||
attach_shared_contexts(api_app)
|
||||
initialize_configs_contexts(api_app)
|
||||
|
||||
# Call API so server actually starts.
|
||||
client = SanicASGITestClient(api_app)
|
||||
await client.get('/api/echo')
|
||||
|
||||
try:
|
||||
yield client
|
||||
# Do not remove, or tests will be significantly slower.
|
||||
# await switches.await_switches()
|
||||
finally:
|
||||
logger.debug('Destroying async_client')
|
||||
|
||||
|
|
@ -191,15 +196,23 @@ def test_download_manager_config(async_client, test_directory) -> pathlib.Path:
|
|||
yield config_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def await_switches(async_client):
|
||||
"""Returns the `switches.await_switches` function, but primes the Sanic App to actually handle signals."""
|
||||
await async_client.get('/api')
|
||||
return await_switches_
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def test_download_manager(
|
||||
async_client,
|
||||
test_session, # session is required because downloads can start without the test DB in place.
|
||||
test_download_manager_config,
|
||||
) -> DownloadManager:
|
||||
# Needed to use signals in
|
||||
manager = DownloadManager()
|
||||
await manager.enable()
|
||||
with timer('test_download_manager'):
|
||||
# Needed to use signals in
|
||||
manager = DownloadManager()
|
||||
await manager.enable()
|
||||
|
||||
yield manager
|
||||
|
||||
|
|
|
|||
|
|
@ -3,8 +3,11 @@ import multiprocessing
|
|||
|
||||
from sanic import Sanic
|
||||
|
||||
from wrolpi.common import logger
|
||||
from wrolpi.vars import LOG_LEVEL_INT
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
||||
def attach_shared_contexts(app: Sanic):
|
||||
"""Initializes Sanic's shared context with WROLPi's multiprocessing tools.
|
||||
|
|
@ -36,9 +39,12 @@ def attach_shared_contexts(app: Sanic):
|
|||
|
||||
# Download Manager
|
||||
app.shared_ctx.download_manager_data = manager.dict()
|
||||
app.shared_ctx.download_manager_queue = multiprocessing.Queue()
|
||||
app.shared_ctx.download_manager_disabled = multiprocessing.Event()
|
||||
app.shared_ctx.download_manager_stopped = multiprocessing.Event()
|
||||
# Downloads are only begun on startup using the wrolpi config's value. Do not start downloads before importing
|
||||
# config.
|
||||
app.shared_ctx.download_manager_disabled.set()
|
||||
app.shared_ctx.download_manager_stopped.set()
|
||||
|
||||
app.shared_ctx.single_tasks_started = multiprocessing.Event()
|
||||
app.shared_ctx.flags_initialized = multiprocessing.Event()
|
||||
|
|
@ -107,11 +113,11 @@ def reset_shared_contexts(app: Sanic):
|
|||
|
||||
# Events.
|
||||
app.shared_ctx.single_tasks_started.clear()
|
||||
app.shared_ctx.download_manager_stopped.clear()
|
||||
app.shared_ctx.flags_initialized.clear()
|
||||
app.shared_ctx.perpetual_tasks_started.clear()
|
||||
|
||||
# Do not start downloads when reloading.
|
||||
app.shared_ctx.download_manager_stopped.set()
|
||||
app.shared_ctx.download_manager_disabled.set()
|
||||
|
||||
|
||||
|
|
@ -123,9 +129,33 @@ def initialize_configs_contexts(app: Sanic):
|
|||
from wrolpi.common import WROLPI_CONFIG
|
||||
from wrolpi.tags import TAGS_CONFIG
|
||||
from wrolpi.downloader import DOWNLOAD_MANAGER_CONFIG
|
||||
INVENTORIES_CONFIG.initialize(app.shared_ctx.inventories_config)
|
||||
CHANNELS_CONFIG.initialize(app.shared_ctx.channels_config)
|
||||
VIDEOS_DOWNLOADER_CONFIG.initialize(app.shared_ctx.videos_downloader_config)
|
||||
WROLPI_CONFIG.initialize(app.shared_ctx.wrolpi_config)
|
||||
TAGS_CONFIG.initialize(app.shared_ctx.tags_config)
|
||||
DOWNLOAD_MANAGER_CONFIG.initialize(app.shared_ctx.download_manager_config)
|
||||
|
||||
try: # noqa
|
||||
INVENTORIES_CONFIG.initialize(app.shared_ctx.inventories_config)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to initialize in-memory inventories config: {e}')
|
||||
|
||||
try:
|
||||
CHANNELS_CONFIG.initialize(app.shared_ctx.channels_config)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to initialize in-memory channels config: {e}')
|
||||
|
||||
try:
|
||||
VIDEOS_DOWNLOADER_CONFIG.initialize(app.shared_ctx.videos_downloader_config)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to initialize in-memory videos downloader config: {e}')
|
||||
|
||||
try: # noqa
|
||||
WROLPI_CONFIG.initialize(app.shared_ctx.wrolpi_config)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to initialize in-memory wrolpi config config: {e}')
|
||||
|
||||
try:
|
||||
TAGS_CONFIG.initialize(app.shared_ctx.tags_config)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to initialize in-memory tags config: {e}')
|
||||
|
||||
try:
|
||||
DOWNLOAD_MANAGER_CONFIG.initialize(app.shared_ctx.download_manager_config)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to initialize in-memory download manager config: {e}')
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ from sqlalchemy.sql import Delete
|
|||
from wrolpi import flags
|
||||
from wrolpi.api_utils import api_app, perpetual_signal
|
||||
from wrolpi.common import Base, ModelHelper, logger, wrol_mode_check, zig_zag, ConfigFile, \
|
||||
wrol_mode_enabled, background_task, get_wrolpi_config, get_absolute_media_path
|
||||
wrol_mode_enabled, background_task, get_wrolpi_config, get_absolute_media_path, timer
|
||||
from wrolpi.dates import TZDateTime, now, Seconds
|
||||
from wrolpi.db import get_db_session, get_db_curs, optional_session
|
||||
from wrolpi.errors import InvalidDownload, UnrecoverableDownloadError, UnknownDownload, ValidationError
|
||||
|
|
@ -38,12 +38,17 @@ from wrolpi.vars import PYTEST, SIMULTANEOUS_DOWNLOAD_DOMAINS
|
|||
logger = logger.getChild(__name__)
|
||||
|
||||
|
||||
@perpetual_signal(sleep=1)
|
||||
@perpetual_signal(sleep=1 if PYTEST else 5)
|
||||
async def perpetual_download_worker():
|
||||
async with flags.db_up.wait_for():
|
||||
pass
|
||||
|
||||
if not get_download_manager_config().successful_import:
|
||||
logger.trace(f'Not starting perpetual download worker because config was not imported')
|
||||
return
|
||||
|
||||
if download_manager.is_stopped:
|
||||
logger.trace(f'Not starting perpetual download worker because download manager is stopped')
|
||||
return
|
||||
|
||||
try:
|
||||
|
|
@ -287,10 +292,6 @@ class Downloader:
|
|||
def already_downloaded(self, *urls: List[str], session: Session = None):
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def manager(self):
|
||||
return download_manager
|
||||
|
||||
async def process_runner(self, download_id: int, url: str, cmd: Tuple[str | pathlib.Path, ...], cwd: pathlib.Path,
|
||||
timeout: int = None, **kwargs) -> Tuple[int, dict, bytes]:
|
||||
"""
|
||||
|
|
@ -356,8 +357,7 @@ class Downloader:
|
|||
download_id = download.id
|
||||
task = asyncio.create_task(coro)
|
||||
while not task.done():
|
||||
if download_manager.download_is_killed(
|
||||
download_id) or download_manager.is_disabled or download_manager.is_stopped:
|
||||
if download_manager.download_is_killed(download_id) or not download_manager.can_download:
|
||||
logger.warning(f'Cancel download of {download.url}')
|
||||
task.cancel()
|
||||
try:
|
||||
|
|
@ -391,10 +391,6 @@ class DownloadManager:
|
|||
self.instances: Tuple[Downloader] = tuple()
|
||||
self._instances = dict()
|
||||
|
||||
self.workers: List[Dict] = []
|
||||
self.worker_count: int = 1
|
||||
self.worker_alive_frequency = timedelta(minutes=10)
|
||||
|
||||
def __repr__(self):
|
||||
return f'<DownloadManager pid={os.getpid()}>'
|
||||
|
||||
|
|
@ -407,6 +403,11 @@ class DownloadManager:
|
|||
def is_disabled(self) -> bool:
|
||||
return self.disabled.is_set()
|
||||
|
||||
def disable(self):
|
||||
"""Stop all downloads and downloaders."""
|
||||
if not self.disabled.is_set():
|
||||
self.disabled.set()
|
||||
|
||||
@property
|
||||
def stopped(self):
|
||||
# Server is stopping and perpetual download should stop.
|
||||
|
|
@ -416,9 +417,43 @@ class DownloadManager:
|
|||
def is_stopped(self) -> bool:
|
||||
return self.stopped.is_set()
|
||||
|
||||
def stop(self):
|
||||
"""Stop all downloads, downloaders and workers. This is called when the server is shutting down."""
|
||||
if not self.is_stopped:
|
||||
self.stopped.set()
|
||||
self.disable()
|
||||
|
||||
async def enable(self):
|
||||
"""Enable downloading.
|
||||
|
||||
perpetual_download_worker will start downloading.
|
||||
"""
|
||||
self.log_info('Enabling downloading')
|
||||
self.stopped.clear()
|
||||
self.disabled.clear()
|
||||
|
||||
@property
|
||||
def download_queue(self) -> multiprocessing.Queue:
|
||||
return api_app.shared_ctx.download_manager_queue
|
||||
def can_download(self) -> bool:
|
||||
"""Returns True only if all steps necessary for downloading have been met."""
|
||||
if PYTEST:
|
||||
return True
|
||||
if self.is_disabled:
|
||||
# DownloadManager has been disabled and should not download.
|
||||
return False
|
||||
if self.is_stopped:
|
||||
# DownloadManager has been stopped and system is probably restarting.
|
||||
return False
|
||||
if not flags.have_internet.is_set():
|
||||
# Do not download without internet.
|
||||
return False
|
||||
if wrol_mode_enabled():
|
||||
# Do not download with WROL Mode enabled.
|
||||
return False
|
||||
if get_download_manager_config().successful_import:
|
||||
# Finally, allow downloading because config was valid and imported.
|
||||
return True
|
||||
# Do not download by default.
|
||||
return False
|
||||
|
||||
@property
|
||||
def processing_domains(self):
|
||||
|
|
@ -458,22 +493,6 @@ class DownloadManager:
|
|||
def log_warning(self, message: str):
|
||||
return self.log(message, logging.WARNING)
|
||||
|
||||
@wrol_mode_check
|
||||
def start_workers(self, loop=None):
|
||||
"""Start all download worker tasks. Does nothing if they are already running."""
|
||||
if not self.workers:
|
||||
if not loop:
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
# Loop isn't running, start one. Probably testing.
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
for i in range(self.worker_count):
|
||||
coro = self.download_worker(i)
|
||||
task = loop.create_task(coro)
|
||||
self.workers.append(task)
|
||||
|
||||
def find_downloader_by_name(self, name: str) -> Optional[Downloader]:
|
||||
"""Attempt to find a registered Downloader by its name. Raises error if it cannot be found."""
|
||||
if downloader := self._instances.get(name):
|
||||
|
|
@ -485,17 +504,17 @@ class DownloadManager:
|
|||
if not url:
|
||||
raise ValueError('Download must have a URL')
|
||||
|
||||
download = self.get_download(session, url=url)
|
||||
if not download:
|
||||
if url in get_download_manager_config().skip_urls:
|
||||
if reset_attempts is True:
|
||||
self.remove_from_skip_list(url)
|
||||
else:
|
||||
raise InvalidDownload(
|
||||
f'Refusing to download {url} because it is in the download_manager.yaml skip list')
|
||||
download = Download(url=url, status='new')
|
||||
session.add(download)
|
||||
if download := Download.get_by_url(url, session=session):
|
||||
return download
|
||||
|
||||
if self.is_skipped(url):
|
||||
if reset_attempts is True:
|
||||
self.remove_from_skip_list(url)
|
||||
else:
|
||||
raise InvalidDownload(
|
||||
f'Refusing to download {url} because it is in the download_manager.yaml skip list')
|
||||
download = Download(url=url, status='new')
|
||||
session.add(download)
|
||||
return download
|
||||
|
||||
@optional_session
|
||||
|
|
@ -607,7 +626,7 @@ class DownloadManager:
|
|||
destination: str | pathlib.Path = None, tag_names: List[str] = None,
|
||||
sub_downloader: str | None = None, frequency: int = None,
|
||||
settings: Dict = None, session: Session = None) -> Download:
|
||||
download = self.find_download(session=session, id_=id_)
|
||||
download = Download.find_by_id(id_, session=session)
|
||||
if settings and settings.get('channel_id') and not frequency:
|
||||
raise InvalidDownload(f'A once-download cannot be associated with a Channel')
|
||||
download.url = url
|
||||
|
|
@ -628,7 +647,7 @@ class DownloadManager:
|
|||
async def dispatch_downloads(self, session: Session = None):
|
||||
"""Dispatch Sanic signals to start downloads. This only starts as many downloads as the
|
||||
SIMULTANEOUS_DOWNLOAD_DOMAINS variable."""
|
||||
if self.is_disabled or self.is_stopped:
|
||||
if not self.can_download:
|
||||
# Don't queue downloads when disabled.
|
||||
return
|
||||
|
||||
|
|
@ -661,7 +680,7 @@ class DownloadManager:
|
|||
|
||||
Warning: Downloads will still be running even after this returns! See `wait_for_all_downloads`.
|
||||
"""
|
||||
if self.disabled.is_set() or wrol_mode_enabled():
|
||||
if not self.can_download:
|
||||
return
|
||||
|
||||
try:
|
||||
|
|
@ -684,26 +703,27 @@ class DownloadManager:
|
|||
|
||||
@warning: THIS METHOD IS FOR TESTING.
|
||||
"""
|
||||
# Use real datetime.now to avoid `fake_now`.
|
||||
start = datetime.now()
|
||||
with timer('wait_for_all_downloads', level='trace'):
|
||||
# Use real datetime.now to avoid `fake_now`.
|
||||
start = datetime.now()
|
||||
|
||||
while (datetime.now() - start).total_seconds() < timeout:
|
||||
# Send out download signals.
|
||||
await self.dispatch_downloads()
|
||||
while (datetime.now() - start).total_seconds() < timeout:
|
||||
# Send out download signals.
|
||||
await self.dispatch_downloads()
|
||||
|
||||
# Wait for processes to start.
|
||||
await asyncio.sleep(1)
|
||||
# Wait for processes to start.
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
await await_switches()
|
||||
await await_switches()
|
||||
|
||||
# Break out of loop only when all downloads have been processed.
|
||||
with get_db_session() as session:
|
||||
statuses = {i.status for i in self.get_downloads(session)}
|
||||
if DownloadStatus.new not in statuses and DownloadStatus.pending not in statuses:
|
||||
# All downloads must be complete/deferred/failed.
|
||||
break
|
||||
else:
|
||||
raise TimeoutError('Downloads never finished!')
|
||||
# Break out of loop only when all downloads have been processed.
|
||||
with get_db_session() as session:
|
||||
statuses = {i.status for i in self.get_downloads(session)}
|
||||
if DownloadStatus.new not in statuses and DownloadStatus.pending not in statuses:
|
||||
# All downloads must be complete/deferred/failed.
|
||||
break
|
||||
else:
|
||||
raise TimeoutError('Downloads never finished!')
|
||||
|
||||
@staticmethod
|
||||
def retry_downloads(reset_attempts: bool = False):
|
||||
|
|
@ -788,36 +808,10 @@ class DownloadManager:
|
|||
downloads = list(session.query(Download).all())
|
||||
return downloads
|
||||
|
||||
@staticmethod
|
||||
def get_download(session: Session, url: str = None, id_: int = None) -> Download | None:
|
||||
"""Attempt to find a Download by its URL or by its id."""
|
||||
query = session.query(Download)
|
||||
if url:
|
||||
download = query.filter_by(url=url).one_or_none()
|
||||
elif id_:
|
||||
download = query.filter_by(id=id_).one_or_none()
|
||||
else:
|
||||
raise RuntimeError('Cannot find download without some params.')
|
||||
return download
|
||||
|
||||
@optional_session
|
||||
def find_download(self, url: str = None, id_: int = None, session: Session = None) -> Download:
|
||||
"""Find the requested Download, or raise an exception if not found.
|
||||
|
||||
@raise UnknownDownload: If the Download cannot be found."""
|
||||
download = self.get_download(session=session, url=url, id_=id_)
|
||||
if not download:
|
||||
if url:
|
||||
raise UnknownDownload(f'Cannot find Download with URL: {url}')
|
||||
raise UnknownDownload(f'Cannot find Download with id: {id}')
|
||||
|
||||
return download
|
||||
|
||||
@optional_session
|
||||
def delete_download(self, download_id: int, session: Session = None):
|
||||
"""Delete a Download. Returns True if a Download was deleted, otherwise return False."""
|
||||
download = self.get_download(session, id_=download_id)
|
||||
if download:
|
||||
if download := Download.get_by_id(download_id, session=session):
|
||||
# This saves the config twice.
|
||||
download.delete()
|
||||
return True
|
||||
|
|
@ -826,9 +820,7 @@ class DownloadManager:
|
|||
@optional_session
|
||||
def restart_download(self, download_id: int, session: Session = None) -> Download:
|
||||
"""Renews a download and resets its download attempts."""
|
||||
download = self.get_download(session, id_=download_id)
|
||||
if not download:
|
||||
raise InvalidDownload(f'No download with id {download_id}')
|
||||
download = Download.find_by_id(download_id, session=session)
|
||||
download.renew(reset_attempts=True)
|
||||
session.commit()
|
||||
|
||||
|
|
@ -842,7 +834,7 @@ class DownloadManager:
|
|||
api_app.shared_ctx.download_manager_data.update(download_manager_data)
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
if download := self.get_download(session, id_=download_id):
|
||||
if download := Download.get_by_id(download_id, session=session):
|
||||
download.error = 'User stopped this download'
|
||||
download.fail()
|
||||
|
||||
|
|
@ -858,23 +850,6 @@ class DownloadManager:
|
|||
def download_is_killed(download_id: int):
|
||||
return download_id in api_app.shared_ctx.download_manager_data['killed_downloads']
|
||||
|
||||
def disable(self):
|
||||
"""Stop all downloads and downloaders."""
|
||||
if not self.disabled.is_set():
|
||||
self.disabled.set()
|
||||
|
||||
def stop(self):
|
||||
"""Stop all downloads, downloaders and workers. This is called when the server is shutting down."""
|
||||
if not self.is_stopped:
|
||||
self.stopped.set()
|
||||
self.disable()
|
||||
|
||||
async def enable(self):
|
||||
"""Enable downloading. Start downloading."""
|
||||
self.log_info('Enabling downloading')
|
||||
self.stopped.clear()
|
||||
self.disabled.clear()
|
||||
|
||||
FINISHED_STATUSES = (DownloadStatus.complete, DownloadStatus.failed)
|
||||
|
||||
def delete_old_once_downloads(self):
|
||||
|
|
@ -1001,11 +976,6 @@ class DownloadManager:
|
|||
)
|
||||
return summary
|
||||
|
||||
@optional_session
|
||||
def get_pending_downloads(self, session: Session) -> List[Download]:
|
||||
downloads = session.query(Download).filter_by(status=DownloadStatus.pending).all()
|
||||
return downloads
|
||||
|
||||
@staticmethod
|
||||
@optional_session
|
||||
def calculate_next_download(download: Download, session: Session) -> Optional[datetime]:
|
||||
|
|
@ -1103,12 +1073,6 @@ class DownloadManager:
|
|||
def remove_from_skip_list(url: str):
|
||||
get_download_manager_config().skip_urls = [i for i in get_download_manager_config().skip_urls if i != url]
|
||||
|
||||
@staticmethod
|
||||
def get_download_by_url(url: str) -> Optional[Download]:
|
||||
with get_db_session() as session:
|
||||
download = session.query(Download).filter_by(url=url).one_or_none()
|
||||
return download
|
||||
|
||||
|
||||
# The global DownloadManager. This should be used everywhere!
|
||||
download_manager = DownloadManager()
|
||||
|
|
@ -1119,88 +1083,89 @@ async def signal_download_download(download_id: int, download_url: str):
|
|||
"""Calls Downloaders based on the download information provided, as well as what is in the DB."""
|
||||
from wrolpi.db import get_db_session
|
||||
|
||||
url = download_url
|
||||
download_domain = None
|
||||
with timer('signal_download_download', 'trace'):
|
||||
url = download_url
|
||||
download_domain = None
|
||||
|
||||
name = f'download_worker'
|
||||
worker_logger = logger.getChild(name)
|
||||
name = f'download_worker'
|
||||
worker_logger = logger.getChild(name)
|
||||
|
||||
try:
|
||||
worker_logger.debug(f'Got download {download_id}')
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
# Mark the download as started in new session so the change is committed.
|
||||
download = Download.find_by_id(download_id, session=session)
|
||||
download.started()
|
||||
download_domain = download.domain
|
||||
|
||||
downloader: Downloader = download.get_downloader()
|
||||
if not downloader:
|
||||
worker_logger.warning(f'Could not find downloader for {download.downloader=}')
|
||||
|
||||
try_again = True
|
||||
try:
|
||||
# Create download coroutine. Wrap it, so it can be canceled.
|
||||
if not inspect.iscoroutinefunction(downloader.do_download):
|
||||
raise RuntimeError(f'Coroutine expected from {downloader} do_download method.')
|
||||
coro = downloader.do_download(download)
|
||||
result = await downloader.cancel_wrapper(coro, download)
|
||||
except UnrecoverableDownloadError as e:
|
||||
# Download failed and should not be retried.
|
||||
worker_logger.warning(f'UnrecoverableDownloadError for {url}', exc_info=e)
|
||||
result = DownloadResult(success=False, error=str(traceback.format_exc()))
|
||||
try_again = False
|
||||
except Exception as e:
|
||||
worker_logger.warning(f'Failed to download {url}. Will be tried again later.', exc_info=e)
|
||||
result = DownloadResult(success=False, error=str(traceback.format_exc()))
|
||||
worker_logger.debug(f'Got download {download_id}')
|
||||
|
||||
# If download has error, and not Internet is available, tell the user!
|
||||
if result.error and not flags.have_internet.is_set():
|
||||
result.error = f'{result.error}\n\nNo internet available!'
|
||||
with get_db_session(commit=True) as session:
|
||||
# Mark the download as started in new session so the change is committed.
|
||||
download = Download.find_by_id(download_id, session=session)
|
||||
download.started()
|
||||
download_domain = download.domain
|
||||
|
||||
error_len = len(result.error) if result.error else 0
|
||||
worker_logger.debug(
|
||||
f'Got success={result.success} from {downloader} download_id={download.id} with {error_len=}')
|
||||
downloader: Downloader = download.get_downloader()
|
||||
if not downloader:
|
||||
worker_logger.warning(f'Could not find downloader for {download.downloader=}')
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
# Modify the download in a new session because downloads may take a long time.
|
||||
download: Download = session.query(Download).filter_by(id=download_id).one()
|
||||
# Use a new location if provided, keep the old location if no new location is provided, otherwise
|
||||
# clear out an outdated location.
|
||||
download.location = result.location or download.location or None
|
||||
# Clear any old errors if the download succeeded.
|
||||
download.error = result.error if result.error else None
|
||||
download.next_download = download_manager.calculate_next_download(download, session)
|
||||
try_again = True
|
||||
try:
|
||||
# Create download coroutine. Wrap it, so it can be canceled.
|
||||
if not inspect.iscoroutinefunction(downloader.do_download):
|
||||
raise RuntimeError(f'Coroutine expected from {downloader} do_download method.')
|
||||
coro = downloader.do_download(download)
|
||||
result = await downloader.cancel_wrapper(coro, download)
|
||||
except UnrecoverableDownloadError as e:
|
||||
# Download failed and should not be retried.
|
||||
worker_logger.warning(f'UnrecoverableDownloadError for {url}', exc_info=e)
|
||||
result = DownloadResult(success=False, error=str(traceback.format_exc()))
|
||||
try_again = False
|
||||
except Exception as e:
|
||||
worker_logger.warning(f'Failed to download {url}. Will be tried again later.', exc_info=e)
|
||||
result = DownloadResult(success=False, error=str(traceback.format_exc()))
|
||||
|
||||
urls = download.filter_excluded(result.downloads) if result.downloads else None
|
||||
if urls:
|
||||
worker_logger.info(f'Adding {len(result.downloads)} downloads from result of {download.url}')
|
||||
download_manager.create_downloads(urls, session, downloader_name=download.sub_downloader,
|
||||
settings=result.settings)
|
||||
# If download has error, and not Internet is available, tell the user!
|
||||
if result.error and not flags.have_internet.is_set():
|
||||
result.error = f'{result.error}\n\nNo internet available!'
|
||||
|
||||
if try_again is False and not download.frequency:
|
||||
# Only once-downloads can fail.
|
||||
download.fail()
|
||||
elif result.success:
|
||||
download.complete()
|
||||
else:
|
||||
download.defer()
|
||||
error_len = len(result.error) if result.error else 0
|
||||
worker_logger.debug(
|
||||
f'Got success={result.success} from {downloader} download_id={download.id} with {error_len=}')
|
||||
|
||||
# Remove this domain from the running list.
|
||||
download_manager._delete_processing_domain(download_domain)
|
||||
# Allow the download to resume.
|
||||
download_manager.unkill_download(download_id)
|
||||
# Save the config now that the Download has finished.
|
||||
save_downloads_config.activate_switch()
|
||||
except asyncio.CancelledError as e:
|
||||
worker_logger.warning('Canceled!', exc_info=e)
|
||||
return
|
||||
except Exception as e:
|
||||
worker_logger.warning(f'Unexpected error', exc_info=e)
|
||||
finally:
|
||||
# Remove this domain from the running list.
|
||||
if download_domain:
|
||||
with get_db_session(commit=True) as session:
|
||||
# Modify the download in a new session because downloads may take a long time.
|
||||
download: Download = session.query(Download).filter_by(id=download_id).one()
|
||||
# Use a new location if provided, keep the old location if no new location is provided, otherwise
|
||||
# clear out an outdated location.
|
||||
download.location = result.location or download.location or None
|
||||
# Clear any old errors if the download succeeded.
|
||||
download.error = result.error if result.error else None
|
||||
download.next_download = download_manager.calculate_next_download(download, session)
|
||||
|
||||
urls = download.filter_excluded(result.downloads) if result.downloads else None
|
||||
if urls:
|
||||
worker_logger.info(f'Adding {len(result.downloads)} downloads from result of {download.url}')
|
||||
download_manager.create_downloads(urls, session, downloader_name=download.sub_downloader,
|
||||
settings=result.settings)
|
||||
|
||||
if try_again is False and not download.frequency:
|
||||
# Only once-downloads can fail.
|
||||
download.fail()
|
||||
elif result.success:
|
||||
download.complete()
|
||||
else:
|
||||
download.defer()
|
||||
|
||||
# Remove this domain from the running list.
|
||||
download_manager._delete_processing_domain(download_domain)
|
||||
# Allow the download to resume.
|
||||
download_manager.unkill_download(download_id)
|
||||
# Save the config now that the Download has finished.
|
||||
save_downloads_config.activate_switch()
|
||||
except asyncio.CancelledError as e:
|
||||
worker_logger.warning('Canceled!', exc_info=e)
|
||||
return
|
||||
except Exception as e:
|
||||
worker_logger.warning(f'Unexpected error', exc_info=e)
|
||||
finally:
|
||||
# Remove this domain from the running list.
|
||||
if download_domain:
|
||||
download_manager._delete_processing_domain(download_domain)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ from wrolpi.common import Base, ModelHelper, tsvector, logger, recursive_map, ge
|
|||
get_relative_to_media_directory, unique_by_predicate
|
||||
from wrolpi.dates import TZDateTime, now, from_timestamp, strptime_ms, strftime
|
||||
from wrolpi.db import optional_session
|
||||
from wrolpi.downloader import Download
|
||||
from wrolpi.errors import FileGroupIsTagged, UnknownFile
|
||||
from wrolpi.files import indexers
|
||||
from wrolpi.media_path import MediaPathType
|
||||
|
|
@ -224,7 +225,7 @@ class FileGroup(ModelHelper, Base):
|
|||
|
||||
if session := Session.object_session(self):
|
||||
from wrolpi.downloader import download_manager
|
||||
if self.url and (download := download_manager.get_download(session, self.url)):
|
||||
if self.url and (download := Download.get_by_url(self.url, session=session)):
|
||||
download.delete(add_to_skip_list)
|
||||
elif self.url and add_to_skip_list is True:
|
||||
download_manager.add_to_skip_list(self.url)
|
||||
|
|
|
|||
|
|
@ -753,7 +753,8 @@ async def test_get_file(test_session, async_client, test_directory, make_files_s
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ignore_directory(test_session, async_client, test_directory, make_files_structure, test_wrolpi_config):
|
||||
async def test_ignore_directory(test_session, async_client, test_directory, make_files_structure, test_wrolpi_config,
|
||||
await_switches):
|
||||
"""A maintainer can ignore/un-ignore directories. The files in the directory should not be refreshed."""
|
||||
# Remove any default ignored directories.
|
||||
get_wrolpi_config().ignored_directories = []
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ from wrolpi.dates import now
|
|||
from wrolpi.errors import InvalidFile, UnknownDirectory, FileGroupIsTagged, NoPrimaryFile
|
||||
from wrolpi.files import lib, indexers
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.tags import TagFile
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
|
||||
|
|
@ -106,7 +105,7 @@ async def test_delete_file_link(async_client, test_session, test_directory):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_tagged(async_client, test_session, make_files_structure, tag_factory, video_bytes):
|
||||
async def test_delete_tagged(await_switches, test_session, make_files_structure, tag_factory, video_bytes):
|
||||
"""Cannot delete a file that has been tagged."""
|
||||
tag = await tag_factory()
|
||||
make_files_structure({'foo/bar.txt': 'asdf', 'foo/bar.mp4': video_bytes})
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import asyncio
|
||||
from http import HTTPStatus
|
||||
|
||||
import mock
|
||||
|
|
@ -8,7 +7,6 @@ from wrolpi.dates import Seconds
|
|||
from wrolpi.downloader import DownloadResult
|
||||
from wrolpi.files.downloader import FileDownloader
|
||||
from wrolpi.scrape_downloader import ScrapeHTMLDownloader
|
||||
from wrolpi.switches import await_switches
|
||||
|
||||
EXAMPLE_HTTP = '''
|
||||
<html>
|
||||
|
|
@ -32,7 +30,7 @@ async def fake_file_do_download(*a, **kwargs):
|
|||
return DownloadResult(success=True)
|
||||
|
||||
|
||||
async def test_scrape_html_downloader(test_directory, test_session, test_download_manager, assert_download_urls):
|
||||
async def test_scrape_html_downloader(test_directory, test_session, test_download_manager, assert_download_urls, await_switches):
|
||||
"""User can scrape for PDF files."""
|
||||
test_download_manager.register_downloader(ScrapeHTMLDownloader())
|
||||
test_download_manager.register_downloader(FileDownloader())
|
||||
|
|
@ -60,7 +58,8 @@ async def test_scrape_html_downloader(test_directory, test_session, test_downloa
|
|||
])
|
||||
|
||||
|
||||
async def test_scrape_html_downloader_html(test_directory, test_session, test_download_manager, assert_download_urls):
|
||||
async def test_scrape_html_downloader_html(test_directory, test_session, test_download_manager, assert_download_urls,
|
||||
await_switches):
|
||||
"""User can also scrape for HTML files."""
|
||||
test_download_manager.register_downloader(ScrapeHTMLDownloader())
|
||||
test_download_manager.register_downloader(FileDownloader())
|
||||
|
|
@ -73,7 +72,7 @@ async def test_scrape_html_downloader_html(test_directory, test_session, test_do
|
|||
with mock.patch('wrolpi.scrape_downloader.ScrapeHTMLDownloader.fetch_html', fake_fetch_html), \
|
||||
mock.patch('wrolpi.files.downloader.FileDownloader.do_download', fake_file_do_download):
|
||||
await test_download_manager.wait_for_all_downloads()
|
||||
await asyncio.sleep(1)
|
||||
await await_switches()
|
||||
|
||||
assert_download_urls([
|
||||
'https://example.com/dir',
|
||||
|
|
|
|||
|
|
@ -19,9 +19,8 @@ import pytz
|
|||
|
||||
import wrolpi.vars
|
||||
from wrolpi import common
|
||||
from wrolpi.common import cum_timer, TIMERS, print_timer, limit_concurrent, run_after, get_wrolpi_config
|
||||
from wrolpi.common import cum_timer, TIMERS, print_timer, limit_concurrent, run_after, get_wrolpi_config, TRACE_LEVEL
|
||||
from wrolpi.errors import InvalidConfig
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.test.common import build_test_directories, skip_circleci
|
||||
|
||||
|
||||
|
|
@ -871,11 +870,11 @@ async def test_log_level(async_client, test_wrolpi_config):
|
|||
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
|
||||
assert api_app.shared_ctx.log_level.value == 30
|
||||
|
||||
# Change log level to NOTSET.
|
||||
body = dict(log_level=0)
|
||||
# Change log level to TRACE.
|
||||
body = dict(log_level=5)
|
||||
request, response = await async_client.patch('/api/settings', json=body)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
|
||||
assert api_app.shared_ctx.log_level.value == 0
|
||||
assert api_app.shared_ctx.log_level.value == 5 == TRACE_LEVEL
|
||||
finally:
|
||||
# Reset log level to debug.
|
||||
body = dict(log_level=10)
|
||||
|
|
@ -917,7 +916,7 @@ def test_unique_by_predicate(iterable, predicate, expected):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_config_lifecycle(async_client, test_wrolpi_config):
|
||||
async def test_config_lifecycle(await_switches, test_wrolpi_config):
|
||||
"""Test importing, dumping, updating, saving a config."""
|
||||
config = get_wrolpi_config()
|
||||
# Config is not imported, default values are used.
|
||||
|
|
@ -1077,37 +1076,37 @@ async def test_initialize_config_files(async_client, test_session, test_director
|
|||
get_wrolpi_config().get_file().write_text('wrolpi')
|
||||
get_videos_downloader_config().get_file().write_text('video downloader')
|
||||
|
||||
assert common.initialize_config_files() == [], 'No configs should have been created.'
|
||||
assert common.create_empty_config_files() == [], 'No configs should have been created.'
|
||||
# Config files were not overwritten with real configs.
|
||||
assert get_wrolpi_config().get_file().read_text() == 'wrolpi'
|
||||
assert get_videos_downloader_config().get_file().read_text() == 'video downloader'
|
||||
|
||||
# WROLPi config can be created because it is now missing.
|
||||
get_wrolpi_config().get_file().unlink()
|
||||
assert common.initialize_config_files() == ['wrolpi.yaml'], 'WROLPi config should have been created.'
|
||||
assert common.create_empty_config_files() == ['wrolpi.yaml'], 'WROLPi config should have been created.'
|
||||
assert get_wrolpi_config().is_valid()
|
||||
|
||||
# Videos Downloader config can be created because it is now missing.
|
||||
get_videos_downloader_config().get_file().unlink()
|
||||
assert common.initialize_config_files() == ['videos_downloader.yaml'], \
|
||||
assert common.create_empty_config_files() == ['videos_downloader.yaml'], \
|
||||
'Videos Downloader config should have been created.'
|
||||
assert get_videos_downloader_config().is_valid()
|
||||
|
||||
# Channels config file does not exist, no conflicting Channels so the file is created.
|
||||
simple_channel.delete_with_videos()
|
||||
assert common.initialize_config_files() == ['channels.yaml'], 'Channels config should have been created.'
|
||||
assert common.create_empty_config_files() == ['channels.yaml'], 'Channels config should have been created.'
|
||||
assert get_channels_config().is_valid()
|
||||
|
||||
tag1.delete()
|
||||
tag2.delete()
|
||||
assert common.initialize_config_files() == ['tags.yaml'], 'Tags config should have been created.'
|
||||
assert common.create_empty_config_files() == ['tags.yaml'], 'Tags config should have been created.'
|
||||
assert get_tags_config().is_valid()
|
||||
|
||||
download.delete()
|
||||
assert common.initialize_config_files() == ['download_manager.yaml'], \
|
||||
assert common.create_empty_config_files() == ['download_manager.yaml'], \
|
||||
'Download Manager config should have been created.'
|
||||
assert get_download_manager_config().is_valid()
|
||||
|
||||
test_session.delete(test_inventory)
|
||||
assert common.initialize_config_files() == ['inventories.yaml'], 'Inventory config should have been created.'
|
||||
assert common.create_empty_config_files() == ['inventories.yaml'], 'Inventory config should have been created.'
|
||||
assert get_inventories_config().is_valid()
|
||||
|
|
|
|||
|
|
@ -3,13 +3,12 @@ from http import HTTPStatus
|
|||
import pytest
|
||||
|
||||
from wrolpi.common import get_wrolpi_config
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.tags import Tag
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_configs_crud(async_client, test_session, test_tags_config, tag_factory, test_wrolpi_config,
|
||||
test_channels_config):
|
||||
test_channels_config, await_switches):
|
||||
"""Configs can be imported or saved on demand."""
|
||||
# Create a tag, save it to config, delete it from the DB.
|
||||
one = await tag_factory()
|
||||
|
|
|
|||
|
|
@ -18,7 +18,6 @@ from wrolpi.db import get_db_context
|
|||
from wrolpi.downloader import Downloader, Download, DownloadFrequency, import_downloads_config, \
|
||||
get_download_manager_config, RSSDownloader
|
||||
from wrolpi.errors import InvalidDownload, WROLModeEnabled
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.test.common import assert_dict_contains
|
||||
|
||||
|
||||
|
|
@ -177,7 +176,7 @@ async def test_calculate_next_download(test_session, test_download_manager, fake
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recurring_downloads(test_session, test_download_manager, fake_now, test_downloader):
|
||||
async def test_recurring_downloads(test_session, test_download_manager, fake_now, test_downloader, await_switches):
|
||||
"""A recurring Download should be downloaded forever."""
|
||||
test_downloader.set_test_success()
|
||||
|
||||
|
|
@ -245,7 +244,7 @@ async def test_recurring_downloads(test_session, test_download_manager, fake_now
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_max_attempts(test_session, test_download_manager, test_downloader):
|
||||
async def test_max_attempts(test_session, test_download_manager, test_downloader, await_switches):
|
||||
"""A Download will only be attempted so many times, it will eventually be deleted."""
|
||||
_, session = get_db_context()
|
||||
|
||||
|
|
@ -271,7 +270,7 @@ async def test_max_attempts(test_session, test_download_manager, test_downloader
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skip_urls(test_session, test_download_manager, assert_download_urls, test_downloader,
|
||||
async def test_skip_urls(test_session, test_download_manager, assert_download_urls, test_downloader, await_switches,
|
||||
test_download_manager_config):
|
||||
"""The DownloadManager will not create downloads for URLs in its skip list."""
|
||||
_, session = get_db_context()
|
||||
|
|
@ -414,7 +413,7 @@ async def test_crud_download(async_client, test_session, test_download_manager,
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_downloads_config(test_session, test_download_manager, test_download_manager_config,
|
||||
test_downloader, assert_downloads, tag_factory):
|
||||
test_downloader, assert_downloads, tag_factory, await_switches):
|
||||
# Can import with an empty config.
|
||||
await import_downloads_config()
|
||||
assert_downloads([])
|
||||
|
|
@ -510,7 +509,7 @@ async def test_downloads_config(test_session, test_download_manager, test_downlo
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_excluded_urls(test_session, test_download_manager, test_downloader):
|
||||
async def test_download_excluded_urls(test_session, test_download_manager, test_downloader, await_switches):
|
||||
"""Test that URLs that have been excluded are ignored by the download worker."""
|
||||
test_downloader.already_downloaded = lambda *i, **kw: []
|
||||
test_downloader.set_test_success()
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ from wrolpi.api_utils import json_error_handler
|
|||
from wrolpi.common import get_wrolpi_config
|
||||
from wrolpi.downloader import Download, get_download_manager_config
|
||||
from wrolpi.errors import ValidationError, SearchEmpty
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.test.common import skip_circleci, assert_dict_contains
|
||||
|
||||
|
||||
|
|
@ -494,7 +493,7 @@ async def test_empty_post_download(async_client):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_restart_download(test_session, async_client, test_download_manager, test_downloader):
|
||||
async def test_restart_download(test_session, async_client, test_download_manager, test_downloader, await_switches):
|
||||
"""A Download can be restarted."""
|
||||
# Create a download, fail it, it should be restarted.
|
||||
download = test_download_manager.create_download('https://example.com', test_downloader.name)
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ class RSSHTTPDownloader(Downloader):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rss_download(test_session, test_download_manager):
|
||||
async def test_rss_download(test_session, test_download_manager, await_switches):
|
||||
"""An RSS Downloader will create new Downloads for every link in the feed."""
|
||||
rss_downloader = RSSDownloader()
|
||||
test_download_manager.register_downloader(rss_downloader)
|
||||
|
|
@ -81,7 +81,7 @@ async def test_rss_download(test_session, test_download_manager):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rss_no_entries(test_session, test_download_manager):
|
||||
async def test_rss_no_entries(test_session, test_download_manager, await_switches):
|
||||
"""An RSS feed with no entries is handled."""
|
||||
rss_downloader = RSSDownloader()
|
||||
test_download_manager.register_downloader(rss_downloader)
|
||||
|
|
|
|||
|
|
@ -20,13 +20,13 @@ async def switch_handler_test1(**context):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_switches1(async_client):
|
||||
async def test_switches1(await_switches):
|
||||
global expected_context
|
||||
|
||||
# Dispatch "test" switch, the switch handler should call the handler above, once.
|
||||
expected_context = {'foo': 'bar'}
|
||||
switches.activate_switch('test1', expected_context)
|
||||
await switches.await_switches(timeout=2)
|
||||
await await_switches(timeout=2)
|
||||
assert count1.value == 1
|
||||
|
||||
# Dispatching many times only causes switch handler to be called once because it is already pending.
|
||||
|
|
@ -38,7 +38,7 @@ async def test_switches1(async_client):
|
|||
switch_handler_test1.activate_switch(context={'foo': 'bar4'})
|
||||
switch_handler_test1.activate_switch(context={'foo': 'bar5'})
|
||||
switch_handler_test1.activate_switch(context=expected_context)
|
||||
await switches.await_switches(timeout=2)
|
||||
await await_switches(timeout=2)
|
||||
assert count1.value == 2
|
||||
|
||||
|
||||
|
|
@ -50,7 +50,7 @@ async def switch_handler_test2(**context):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_perpetual_signal(async_client):
|
||||
async def test_perpetual_signal(await_switches):
|
||||
"""Test that perpetual_signal survives errors."""
|
||||
# Signal event is dispatched again.
|
||||
switch_handler_test2.activate_switch()
|
||||
|
|
@ -69,7 +69,7 @@ async def test_perpetual_signal(async_client):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_activate_switch(async_client):
|
||||
async def test_invalid_activate_switch(await_switches):
|
||||
with pytest.raises(RuntimeError):
|
||||
switches.activate_switch('does not exist')
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ from wrolpi.common import is_hardlinked, walk
|
|||
from wrolpi.errors import FileGroupIsTagged, InvalidTag, UnknownTag, FileGroupAlreadyTagged, UsedTag
|
||||
from wrolpi.files import lib as files_lib
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.switches import await_switches
|
||||
from wrolpi.tags import TagFile, Tag
|
||||
|
||||
|
||||
|
|
@ -90,7 +89,7 @@ async def test_tags_file_group(async_client, test_session, make_files_structure,
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tags_config_file(async_client, test_session, test_directory, tag_factory, example_pdf, video_file,
|
||||
async def test_tags_config_file(test_session, test_directory, tag_factory, example_pdf, video_file, await_switches,
|
||||
test_tags_config):
|
||||
"""Test that the config is updated when a FileGroup is tagged."""
|
||||
await files_lib.refresh_files()
|
||||
|
|
@ -286,7 +285,7 @@ async def test_import_tags_config_missing_file(test_session, test_directory, tes
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_import_tags_delete_missing(test_session, test_directory, test_tags_config, make_files_structure,
|
||||
tag_factory, test_zim, async_client):
|
||||
tag_factory, test_zim, await_switches):
|
||||
"""Tags not in the config are deleted on import. Tags that are used will not be deleted."""
|
||||
from modules.zim import lib as zim_lib
|
||||
|
||||
|
|
@ -351,8 +350,7 @@ async def test_invalid_tag(async_client, test_session, test_directory):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tags_directory(async_client, test_session, test_directory, tag_factory, video_factory,
|
||||
example_pdf):
|
||||
async def test_tags_directory(test_session, test_directory, tag_factory, video_factory, example_pdf, await_switches):
|
||||
"""Test that Tag Directory is synchronized with database."""
|
||||
readme = test_directory / 'tags/README.txt'
|
||||
|
||||
|
|
@ -460,7 +458,7 @@ async def test_tags_directory(async_client, test_session, test_directory, tag_fa
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_tag(async_client, test_session, test_directory, video_factory, tag_factory):
|
||||
async def test_update_tag(test_session, test_directory, video_factory, tag_factory, await_switches):
|
||||
"""Linked files in the Tag Directory are moved when the tag is renamed."""
|
||||
# Create tagged Video.
|
||||
tag = await tag_factory()
|
||||
|
|
@ -485,8 +483,8 @@ async def test_update_tag(async_client, test_session, test_directory, video_fact
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tag_rename_with_channel(async_client, test_session, test_directory, video_factory, tag_factory,
|
||||
channel_factory):
|
||||
async def test_tag_rename_with_channel(test_session, test_directory, video_factory, tag_factory,
|
||||
channel_factory, await_switches):
|
||||
tag = await tag_factory()
|
||||
channel = channel_factory(name='Channel Name', tag_name=tag.name)
|
||||
video_factory(title='video', channel_id=channel.id)
|
||||
|
|
|
|||
|
|
@ -50,8 +50,7 @@ if '-vv' in sys.argv:
|
|||
LOG_LEVEL_INT = logging.DEBUG
|
||||
elif '-vvv' in sys.argv:
|
||||
# SQLAlchemy will increase logging.
|
||||
LOG_LEVEL_INT = logging.NOTSET
|
||||
LOG_LEVEL = logging.getLevelName(LOG_LEVEL_INT)
|
||||
LOG_LEVEL_INT = logging.DEBUG - 5
|
||||
|
||||
# Special environment variable set in the docker/api/Dockerfile.
|
||||
DOCKERIZED = truthy_arg(os.environ.get('DOCKER', ''))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue