mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-26 01:46:18 -05:00
Adding Download.settings column in alembic migration.
Reformatting. Switching excluded_urls to a generic Download.settings json. Download workers filter excluded urls.
This commit is contained in:
parent
e7fe65258c
commit
287edad9e6
13 changed files with 186 additions and 37 deletions
29
alembic/versions/c72d305cf11e_download_settings.py
Normal file
29
alembic/versions/c72d305cf11e_download_settings.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
"""Download settings
|
||||
|
||||
Revision ID: c72d305cf11e
|
||||
Revises: d2eace02f5b9
|
||||
Create Date: 2022-10-14 13:00:30.333384
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'c72d305cf11e'
|
||||
down_revision = 'd2eace02f5b9'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE download ADD COLUMN settings JSONB')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE download DROP COLUMN IF EXISTS settings')
|
||||
|
|
@ -461,8 +461,8 @@ export async function getArchive(archiveId) {
|
|||
}
|
||||
}
|
||||
|
||||
export async function postDownload(urls, downloader, frequency, sub_downloader) {
|
||||
let body = {urls: urls, downloader: downloader, frequency: frequency || null};
|
||||
export async function postDownload(urls, downloader, frequency, sub_downloader, excludedURLs) {
|
||||
let body = {urls: urls, downloader: downloader, frequency: frequency || null, excluded_urls: excludedURLs};
|
||||
if (sub_downloader) {
|
||||
body['sub_downloader'] = sub_downloader;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import {Card, Container, Image, Input, Pagination, Responsive, TableCell, TableR
|
|||
import {Link, NavLink} from "react-router-dom";
|
||||
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
|
||||
import {useDownloaders, useHotspot, useThrottle} from "../hooks/customHooks";
|
||||
import {getSettings} from "../api";
|
||||
import {darkTheme, SettingsContext, ThemeContext} from "../contexts/contexts";
|
||||
import {Button, CardIcon, Form, Header, Icon, Menu, Popup, Statistic} from "./Theme";
|
||||
|
||||
|
|
|
|||
|
|
@ -155,7 +155,6 @@ export function FormInput(props) {
|
|||
return <FORM_INPUT {...props}/>
|
||||
}
|
||||
|
||||
|
||||
export function Icon(props) {
|
||||
const {i} = useContext(ThemeContext);
|
||||
props = {...i, ...props};
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import React, {useState} from "react";
|
||||
import React, {useContext, useState} from "react";
|
||||
import {getDownloaders, postDownload} from "../api";
|
||||
import {frequencyOptions, rssFrequencyOptions, WROLModeMessage} from "./Common";
|
||||
import {frequencyOptions, HelpPopup, rssFrequencyOptions, WROLModeMessage} from "./Common";
|
||||
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
|
||||
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
|
||||
import {ThemeContext} from "../contexts/contexts";
|
||||
import {Button, Form, FormInput, Header, Loader, TextArea} from "./Theme";
|
||||
import {ButtonGroup, FormDropdown} from "semantic-ui-react";
|
||||
import {Accordion, Button, Form, FormInput, Header, Loader, TextArea} from "./Theme";
|
||||
import {AccordionContent, AccordionTitle, FormDropdown} from "semantic-ui-react";
|
||||
|
||||
const validUrl = /^(http|https):\/\/[^ "]+$/;
|
||||
|
||||
|
|
@ -160,20 +160,31 @@ class ChannelDownload extends React.Component {
|
|||
}
|
||||
}
|
||||
|
||||
function ExcludedURLsLabel() {
|
||||
const {t} = useContext(ThemeContext);
|
||||
const excludedURLsHelp = <HelpPopup content='A comma-separated list of words that should not be downloaded.'/>
|
||||
return <div style={{marginBottom: '0.5em'}} {...t}>
|
||||
Excluded URLs
|
||||
{excludedURLsHelp}
|
||||
</div>
|
||||
}
|
||||
|
||||
class RSSDownload extends ChannelDownload {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
url: '',
|
||||
disabled: false,
|
||||
downloader: null,
|
||||
downloaders: [],
|
||||
error: null,
|
||||
excludedURLs: '',
|
||||
frequency: 604800,
|
||||
pending: false,
|
||||
disabled: false,
|
||||
ready: false,
|
||||
error: null,
|
||||
success: null,
|
||||
downloaders: [],
|
||||
downloader: null,
|
||||
sub_downloader: null,
|
||||
success: null,
|
||||
url: '',
|
||||
activeIndex: -1,
|
||||
};
|
||||
this.freqOptions = rssFrequencyOptions;
|
||||
}
|
||||
|
|
@ -197,12 +208,12 @@ class RSSDownload extends ChannelDownload {
|
|||
handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
this.setState({disabled: true, pending: true, success: null, error: null});
|
||||
const {url, frequency, sub_downloader} = this.state;
|
||||
const {url, frequency, sub_downloader, excludedURLs} = this.state;
|
||||
if (!url) {
|
||||
this.setState({error: 'URL is required'});
|
||||
return;
|
||||
}
|
||||
let response = await postDownload(url, 'rss', frequency, sub_downloader);
|
||||
let response = await postDownload(url, 'rss', frequency, sub_downloader, excludedURLs);
|
||||
if (response.status === 204) {
|
||||
this.setState({pending: false, disabled: false, success: true, url: '', ready: false});
|
||||
} else {
|
||||
|
|
@ -212,8 +223,19 @@ class RSSDownload extends ChannelDownload {
|
|||
}
|
||||
}
|
||||
|
||||
handleAdvancedClick = async (e, {index}) => {
|
||||
const {activeIndex} = this.state;
|
||||
const newIndex = activeIndex === index ? -1 : index;
|
||||
this.setState({activeIndex: newIndex});
|
||||
}
|
||||
|
||||
handleExcludedURLsChange = async (e, {value}) => {
|
||||
e.preventDefault();
|
||||
this.setState({excludedURLs: value});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {ready, disabled, url, error, frequency, pending, success} = this.state;
|
||||
const {ready, disabled, url, error, frequency, pending, success, activeIndex, excludedURLs} = this.state;
|
||||
const buttonDisabled = !ready || disabled;
|
||||
|
||||
const onceMessage = (<Message>
|
||||
|
|
@ -253,6 +275,25 @@ class RSSDownload extends ChannelDownload {
|
|||
placeholder='Select a downloader'
|
||||
onChange={this.handleInputChange}
|
||||
/>
|
||||
<Accordion style={{paddingBottom: '1em'}}>
|
||||
<AccordionTitle
|
||||
active={activeIndex === 0}
|
||||
index={0}
|
||||
onClick={this.handleAdvancedClick}
|
||||
>
|
||||
<Icon name='dropdown'/>
|
||||
Advanced
|
||||
</AccordionTitle>
|
||||
<AccordionContent active={activeIndex === 0}>
|
||||
<FormInput
|
||||
label={<ExcludedURLsLabel/>}
|
||||
placeholder='example.com,example.org'
|
||||
value={excludedURLs}
|
||||
error={error}
|
||||
onChange={this.handleExcludedURLsChange}
|
||||
/>
|
||||
</AccordionContent>
|
||||
</Accordion>
|
||||
|
||||
<Button content='Cancel' onClick={this.props.clearSelected}/>
|
||||
<Button
|
||||
|
|
|
|||
|
|
@ -78,7 +78,7 @@ export function BandwidthProgressGroup({bandwidth, ...props}) {
|
|||
</Grid>
|
||||
}
|
||||
|
||||
export function BandwidthProgressCombined({bandwidth , ...props}) {
|
||||
export function BandwidthProgressCombined({bandwidth, ...props}) {
|
||||
const maxBytes = bandwidth['speed'] ? bandwidth['speed'] * 125_000 : 125_000_000;
|
||||
const combined = bandwidth['bytes_recv'] + bandwidth['bytes_sent']
|
||||
return <BandwidthProgress label={bandwidth['name']} bytes={combined} maxBytes={maxBytes} {...props}/>
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ from dataclasses import dataclass, field
|
|||
from datetime import timedelta, datetime
|
||||
from enum import Enum
|
||||
from functools import partial
|
||||
from itertools import filterfalse
|
||||
from operator import attrgetter
|
||||
from queue import Empty
|
||||
from typing import List, Dict, Generator
|
||||
|
|
@ -63,6 +64,7 @@ class Download(ModelHelper, Base): # noqa
|
|||
last_successful_download = Column(TZDateTime)
|
||||
location = Column(Text)
|
||||
next_download = Column(TZDateTime)
|
||||
settings = Column(JSONB)
|
||||
status = Column(String, default='new')
|
||||
sub_downloader = Column(Text)
|
||||
_manager = None
|
||||
|
|
@ -138,6 +140,15 @@ class Download(ModelHelper, Base): # noqa
|
|||
def manager(self, value):
|
||||
self._manager = value
|
||||
|
||||
def filter_excluded(self, urls: List[str]) -> List[str]:
|
||||
"""Return any URLs that do not match my excluded_urls."""
|
||||
if self.settings and (excluded_urls := self.settings.get('excluded_urls')):
|
||||
def excluded(url: str):
|
||||
return any(i in url for i in excluded_urls)
|
||||
|
||||
return list(filterfalse(excluded, urls))
|
||||
return urls
|
||||
|
||||
|
||||
class Downloader:
|
||||
name: str = None
|
||||
|
|
@ -370,7 +381,7 @@ class DownloadManager:
|
|||
|
||||
with get_db_session(commit=True) as session:
|
||||
# Modify the download in a new session because downloads may take a long time.
|
||||
download = session.query(Download).filter_by(id=download_id).one()
|
||||
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
|
||||
|
|
@ -380,7 +391,8 @@ class DownloadManager:
|
|||
|
||||
if result.downloads:
|
||||
worker_logger.info(f'Adding {len(result.downloads)} downloads from result of {download.url}')
|
||||
self.create_downloads(result.downloads, session, downloader=download.sub_downloader)
|
||||
urls = download.filter_excluded(result.downloads)
|
||||
self.create_downloads(urls, session, downloader=download.sub_downloader)
|
||||
|
||||
if try_again is False and not download.frequency:
|
||||
# Only once-downloads can fail.
|
||||
|
|
@ -495,15 +507,15 @@ class DownloadManager:
|
|||
|
||||
@optional_session
|
||||
def create_download(self, url: str, session: Session = None, downloader: str = None, reset_attempts: bool = False,
|
||||
sub_downloader: str = None) -> Download:
|
||||
sub_downloader: str = None, excluded_urls: List[str] = None) -> Download:
|
||||
"""Schedule a URL for download. If the URL failed previously, it may be retried."""
|
||||
downloads = self.create_downloads([url], session=session, downloader=downloader,
|
||||
downloads = self.create_downloads([url], session=session, downloader=downloader, excluded_urls=excluded_urls,
|
||||
reset_attempts=reset_attempts, sub_downloader=sub_downloader)
|
||||
return downloads[0]
|
||||
|
||||
@optional_session
|
||||
def create_downloads(self, urls: List[str], session: Session = None, downloader: str = None,
|
||||
reset_attempts: bool = False, sub_downloader: str = None) \
|
||||
reset_attempts: bool = False, sub_downloader: str = None, excluded_urls: List[str] = None) \
|
||||
-> List[Download]:
|
||||
"""Schedule all URLs for download. If one cannot be downloaded, none will be added."""
|
||||
if not all(urls):
|
||||
|
|
@ -537,6 +549,7 @@ class DownloadManager:
|
|||
download.downloader = local_downloader.name
|
||||
download.info_json = info_json or download.info_json
|
||||
download.sub_downloader = sub_downloader
|
||||
download.settings = {'excluded_urls': excluded_urls}
|
||||
downloads.append(download)
|
||||
|
||||
# Start downloading ASAP.
|
||||
|
|
@ -550,14 +563,16 @@ class DownloadManager:
|
|||
return downloads
|
||||
|
||||
def recurring_download(self, url: str, frequency: int, downloader: str = None,
|
||||
sub_downloader: str = None, reset_attempts: bool = False) -> Download:
|
||||
sub_downloader: str = None, reset_attempts: bool = False,
|
||||
excluded_urls: List[str] = None) -> Download:
|
||||
"""Schedule a recurring download."""
|
||||
if not frequency:
|
||||
raise ValueError('Recurring download must have a frequency!')
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
download, = self.create_downloads([url, ], session=session, downloader=downloader,
|
||||
sub_downloader=sub_downloader, reset_attempts=reset_attempts)
|
||||
sub_downloader=sub_downloader, reset_attempts=reset_attempts,
|
||||
excluded_urls=excluded_urls)
|
||||
download.frequency = frequency
|
||||
|
||||
return download
|
||||
|
|
@ -575,13 +590,13 @@ class DownloadManager:
|
|||
return
|
||||
|
||||
# Find download whose domain isn't already being downloaded.
|
||||
new_downloads = session.query(Download).filter(
|
||||
new_downloads = list(session.query(Download).filter(
|
||||
Download.status == 'new',
|
||||
Download.domain not in self.data['processing_domains'],
|
||||
).order_by(
|
||||
Download.frequency.is_(None),
|
||||
Download.frequency,
|
||||
Download.id) # noqa
|
||||
Download.id)) # noqa
|
||||
count = 0
|
||||
for download in new_downloads:
|
||||
download.manager = self # Assign this Download to this manager.
|
||||
|
|
|
|||
|
|
@ -264,7 +264,8 @@ async def refresh_directory_files_recursively(directory: Union[pathlib.Path, str
|
|||
refresh_logger.info(f'Done refreshing files in {directory}')
|
||||
|
||||
|
||||
def file_search(search_str: str, limit: int, offset: int, mimetype: str = None, model: str = None) -> Tuple[List[dict], int]:
|
||||
def file_search(search_str: str, limit: int, offset: int, mimetype: str = None, model: str = None) -> Tuple[
|
||||
List[dict], int]:
|
||||
"""
|
||||
Search the Files table. Order the returned Files by their rank if `search_str` is provided. Return all files if
|
||||
`search_str` is empty.
|
||||
|
|
|
|||
|
|
@ -196,15 +196,17 @@ def valid_regex(_: Request, body: RegexRequest):
|
|||
async def post_download(_: Request, body: DownloadRequest):
|
||||
# URLs are provided in a textarea, lets split all lines.
|
||||
urls = [i.strip() for i in str(body.urls).strip().splitlines()]
|
||||
excluded_urls = [i.strip() for i in body.excluded_urls.split(',')] if body.excluded_urls else None
|
||||
downloader = body.downloader
|
||||
if not downloader or downloader in ('auto', 'None', 'null'):
|
||||
downloader = None
|
||||
if body.frequency:
|
||||
download_manager.recurring_download(urls[0], body.frequency, downloader=downloader,
|
||||
sub_downloader=body.sub_downloader, reset_attempts=True)
|
||||
sub_downloader=body.sub_downloader, reset_attempts=True,
|
||||
excluded_urls=excluded_urls)
|
||||
else:
|
||||
download_manager.create_downloads(urls, downloader=downloader, sub_downloader=body.sub_downloader,
|
||||
reset_attempts=True)
|
||||
reset_attempts=True, excluded_urls=excluded_urls)
|
||||
return response.empty()
|
||||
|
||||
|
||||
|
|
@ -250,7 +252,7 @@ async def clear_failed(_: Request):
|
|||
return response.empty()
|
||||
|
||||
|
||||
@api_bp.delete('/download/<download_id:integer>')
|
||||
@api_bp.delete('/download/<download_id:[0-9]+>')
|
||||
@openapi.description('Delete a download')
|
||||
@wrol_mode_check
|
||||
async def delete_download(_: Request, download_id: int):
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ class DownloadRequest:
|
|||
downloader: Optional[str] = None
|
||||
frequency: Optional[int] = None
|
||||
sub_downloader: Optional[str] = None
|
||||
excluded_urls: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
|
|||
|
|
@ -112,7 +112,7 @@ TOP_REGEX = re.compile(r'^%Cpu\(s\):\s+(\d+\.\d+)', re.MULTILINE)
|
|||
|
||||
def get_cpu_info_psutil() -> CPUInfo:
|
||||
cpu_freq = psutil.cpu_freq()
|
||||
percent = psutil.cpu_percent(interval=1)
|
||||
percent = psutil.cpu_percent(interval=0.1)
|
||||
|
||||
# Prefer "coretemp", fallback to the first temperature.
|
||||
temp = psutil.sensors_temperatures()
|
||||
|
|
|
|||
|
|
@ -1,17 +1,14 @@
|
|||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from abc import ABC
|
||||
from datetime import datetime
|
||||
from http import HTTPStatus
|
||||
from itertools import zip_longest
|
||||
from typing import Tuple, Optional
|
||||
from unittest import mock
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from wrolpi.dates import local_timezone, Seconds, now
|
||||
from wrolpi.dates import local_timezone, Seconds
|
||||
from wrolpi.db import get_db_context
|
||||
from wrolpi.downloader import Downloader, Download, DownloadFrequency, DownloadResult
|
||||
from wrolpi.errors import UnrecoverableDownloadError, InvalidDownload, WROLModeEnabled
|
||||
|
|
@ -368,3 +365,33 @@ async def test_process_runner_timeout(test_directory):
|
|||
elapsed = datetime.now() - start
|
||||
assert 2 < elapsed.total_seconds() < 4
|
||||
|
||||
|
||||
def test_crud_download(test_client, test_session, test_download_manager):
|
||||
"""Test the ways that Downloads can be created."""
|
||||
http_downloader = HTTPDownloader()
|
||||
test_download_manager.register_downloader(http_downloader)
|
||||
|
||||
body = dict(
|
||||
urls='https://example.com',
|
||||
downloader=http_downloader.name,
|
||||
frequency=DownloadFrequency.weekly,
|
||||
excluded_urls='example.org,something',
|
||||
)
|
||||
request, response = test_client.post('/api/download', content=json.dumps(body))
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.body
|
||||
|
||||
download: Download = test_session.query(Download).one()
|
||||
assert download.id
|
||||
assert download.url == 'https://example.com'
|
||||
assert download.downloader == 'http'
|
||||
assert download.frequency == DownloadFrequency.weekly
|
||||
assert download.settings['excluded_urls'] == ['example.org', 'something']
|
||||
|
||||
request, response = test_client.get('/api/download')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert 'recurring_downloads' in response.json
|
||||
assert [i['url'] for i in response.json['recurring_downloads']] == ['https://example.com']
|
||||
|
||||
request, response = test_client.delete(f'/api/download/{download.id}')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
assert test_session.query(Download).count() == 0
|
||||
|
|
|
|||
|
|
@ -2,15 +2,17 @@ import json
|
|||
from http import HTTPStatus
|
||||
from itertools import zip_longest
|
||||
|
||||
import pytest
|
||||
from mock import mock
|
||||
|
||||
from wrolpi.admin import HotspotStatus
|
||||
from wrolpi.common import get_config
|
||||
from wrolpi.dates import strptime
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.downloader import Download
|
||||
from wrolpi.downloader import Download, RSSDownloader, DownloadResult
|
||||
from wrolpi.root_api import api_app
|
||||
from wrolpi.test.common import TestAPI, wrap_test_db, skip_circleci
|
||||
from wrolpi.test.test_downloader import HTTPDownloader
|
||||
|
||||
|
||||
class TestRootAPI(TestAPI):
|
||||
|
|
@ -346,3 +348,36 @@ def test_get_downloaders(test_client):
|
|||
assert 'downloaders' in response.json, 'Downloaders not returned'
|
||||
assert isinstance(response.json['downloaders'], list) and len(response.json['downloaders']), \
|
||||
'No downloaders returned'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_excluded_urls(test_client, test_session, test_download_manager):
|
||||
"""Test that URLs that have been excluded are ignored by the download worker."""
|
||||
http_downloader = HTTPDownloader()
|
||||
http_downloader.already_downloaded = lambda *i, **kw: []
|
||||
http_downloader.do_download = lambda *i, **kw: DownloadResult(success=True)
|
||||
test_download_manager.register_downloader(http_downloader)
|
||||
rss_downloader = RSSDownloader()
|
||||
test_download_manager.register_downloader(rss_downloader)
|
||||
|
||||
with mock.patch('wrolpi.downloader.parse_feed') as mock_parse_feed:
|
||||
mock_parse_feed.return_value = dict(
|
||||
bozo=0,
|
||||
entries=[
|
||||
dict(link='https://example.com/a'),
|
||||
dict(link='https://example.org/b'), # this should be ignored
|
||||
dict(link='https://example.com/c'),
|
||||
dict(link='https://example.gov/d'),
|
||||
]
|
||||
)
|
||||
feed_download: Download = test_download_manager.create_download('https://example.com/feed',
|
||||
test_session, sub_downloader='http',
|
||||
downloader=RSSDownloader.name,
|
||||
excluded_urls=['example.org', 'example.gov'])
|
||||
await test_download_manager.wait_for_all_downloads()
|
||||
|
||||
downloads = list(test_download_manager.get_downloads(test_session))
|
||||
assert not feed_download.error, f'Feed download had error {feed_download.error}'
|
||||
assert len(downloads) == 3, 'Domain was not ignored'
|
||||
assert [i.url for i in downloads] == \
|
||||
['https://example.com/feed', 'https://example.com/a', 'https://example.com/c'], f'Domain was not ignored'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue