Channels now have Channel.channel_downloads. A Channel can have many Downloads.

This commit is contained in:
Roland 2024-06-25 22:12:13 -06:00
parent 91d4d0d15b
commit 50d95dad19
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
43 changed files with 1401 additions and 658 deletions

View file

@ -0,0 +1,55 @@
"""Channel.channel_downloads
Revision ID: 8d0d81bc9c34
Revises: 00f11f309c53
Create Date: 2024-06-25 22:13:23.885687
"""
import os
from alembic import op
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
# revision identifiers, used by Alembic.
revision = '8d0d81bc9c34'
down_revision = '00f11f309c53'
branch_labels = None
depends_on = None
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
Base = declarative_base()
def upgrade():
bind = op.get_bind()
session = Session(bind=bind)
session.execute('ALTER TABLE download ADD CONSTRAINT download_url_unique UNIQUE (url)')
session.execute('''
CREATE TABLE channel_download (
channel_id INTEGER REFERENCES channel (id),
download_url TEXT REFERENCES download (url),
primary key (channel_id, download_url)
)''')
# Migration is separated for testing. See `test_channel_channel_downloads_migration`
from wrolpi.migration import migrate_channel_downloads
migrate_channel_downloads(session)
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS match_regex')
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS download_frequency')
if not DOCKERIZED:
session.execute('ALTER TABLE public.channel_download OWNER TO wrolpi')
def downgrade():
bind = op.get_bind()
session = Session(bind=bind)
session.execute('DROP TABLE IF EXISTS channel_download')
session.execute('ALTER TABLE channel ADD COLUMN IF NOT EXISTS match_regex TEXT')
session.execute('ALTER TABLE channel ADD COLUMN IF NOT EXISTS download_frequency INTEGER')
session.execute('ALTER TABLE download DROP CONSTRAINT IF EXISTS download_url_unique')

View file

@ -314,7 +314,8 @@ export function AddTagsButton({
selectedTagNames = [],
onToggle = _.noop,
onAdd = _.noop,
onRemove = _.noop
onRemove = _.noop,
limit = null,
}) {
// A button which displays a modal in which the user can add or remove tags.
@ -334,6 +335,9 @@ export function AddTagsButton({
setLoading(true);
try {
const newTags = [...localTags, name];
if (limit !== null && newTags.length > limit) {
return;
}
setLocalTags(newTags);
onToggle(newTags);
onAdd(name);
@ -375,6 +379,7 @@ export function AddTagsButton({
const selectedTagsGroup = <TagsGroup tagNames={localTags} onClick={removeTag}/>;
const unusedTags = _.difference(tagNames, localTags);
const unusedTagsGroup = <TagsGroup tagNames={unusedTags} onClick={addTag}/>;
const emptySelectedTags = limit === 1 ? 'Add only one tag below' : 'Add one or more tags below';
return <>
<Button icon={active ? 'tags' : 'tag'} onClick={handleOpen} primary={!!active}/>
@ -386,7 +391,7 @@ export function AddTagsButton({
{loading && <Dimmer active><Loader/></Dimmer>}
<Header as='h4'>Applied Tags</Header>
{localTags && localTags.length > 0 ? selectedTagsGroup : 'Add one or more tags below'}
{localTags && localTags.length > 0 ? selectedTagsGroup : emptySelectedTags}
<Divider/>
@ -418,7 +423,8 @@ export const TagsSelector = ({
selectedTagNames = [],
onToggle = _.noop,
onAdd = _.noop,
onRemove = _.noop
onRemove = _.noop,
limit = null,
}) => {
// Provides a button to add tags to a list. Displays the tags of that list.
const {TagsLinkGroup} = React.useContext(TagsContext);
@ -435,6 +441,7 @@ export const TagsSelector = ({
onToggle={onToggle}
onAdd={onAdd}
onRemove={onRemove}
limit={limit}
/>;
if (hideGroup) {

View file

@ -251,10 +251,19 @@ export async function getVideosStatistics() {
}
}
export async function downloadChannel(channelId) {
let url = `${VIDEOS_API}/channels/download/${channelId}`;
let response = await apiPost(url);
if (response.status === 400) {
export async function createChannelDownload(channelId, url, frequency, title_match, title_exclude, tag_names) {
const body = {
url: url,
frequency: frequency,
settings: {
title_match: title_match,
title_exclude: title_exclude,
tag_names: tag_names,
},
}
url = `${VIDEOS_API}/channels/${channelId}/download`;
let response = await apiPost(url, body);
if (!response.ok) {
const json = await response.json();
if (json['code'] === 'INVALID_DOWNLOAD') {
toast({
@ -263,6 +272,46 @@ export async function downloadChannel(channelId) {
description: 'This channel does not have a download record. Modify the frequency.',
time: 5000,
});
} else {
toast({
type: 'error',
title: 'Failed to Download!',
description: 'Failed to create download. See server logs.',
time: 5000,
});
}
}
return response;
}
export async function updateChannelDownload(channelId, downloadId, url, frequency, title_match, title_exclude, tag_names) {
const body = {
url: url,
frequency: frequency,
settings: {
title_match: title_match,
title_exclude: title_exclude,
tag_names: tag_names,
},
}
url = `${VIDEOS_API}/channels/${channelId}/download/${downloadId}`;
let response = await apiPut(url, body);
if (!response.ok) {
const json = await response.json();
if (json['code'] === 'INVALID_DOWNLOAD') {
toast({
type: 'error',
title: 'Cannot Download!',
description: 'This channel does not have a download record. Modify the frequency.',
time: 5000,
});
} else {
toast({
type: 'error',
title: 'Failed to Download!',
description: 'Failed to update download. See server logs.',
time: 5000,
});
}
}
return response;
@ -456,6 +505,18 @@ export async function getArchive(archiveId) {
}
}
function getDownloadSettings(excludedURLs, depth, suffix, tagNames, downloadMetadataOnly, destination, max_pages) {
let settings = {};
if (excludedURLs) settings['excluded_urls'] = excludedURLs;
if (depth) settings['depth'] = depth;
if (suffix) settings['suffix'] = suffix;
if (tagNames) settings['tag_names'] = tagNames;
if (downloadMetadataOnly) settings['download_metadata_only'] = downloadMetadataOnly;
if (destination) settings['destination'] = destination;
if (max_pages) settings['max_pages'] = max_pages;
return settings;
}
export async function postDownload(
urls,
downloader,
@ -467,7 +528,7 @@ export async function postDownload(
depth,
suffix,
max_pages,
doNotDownload,
downloadMetadataOnly,
) {
if (!downloader) {
toast({
@ -479,29 +540,49 @@ export async function postDownload(
throw new Error('downloader is required, but was not provided');
}
let settings = getDownloadSettings(excludedURLs, depth, suffix, tagNames, downloadMetadataOnly, destination,
max_pages);
let body = {
urls: urls,
downloader: downloader,
sub_downloader: sub_downloader,
frequency: frequency || null,
excluded_urls: excludedURLs,
destination: destination || null,
depth: depth || null,
suffix: suffix || null,
max_pages: max_pages || null,
settings: settings,
};
if (sub_downloader) {
body['sub_downloader'] = sub_downloader;
}
if (tagNames) {
body['tag_names'] = tagNames;
}
if (doNotDownload) {
body['do_not_download'] = doNotDownload;
}
const response = await apiPost(`${API_URI}/download`, body);
return response;
}
export async function putDownload(
urls,
download_id,
downloader,
sub_downloader,
frequency,
excludedURLs,
) {
if (!downloader) {
toast({
type: 'error',
title: 'Failed to submit download',
description: 'downloader is required, but was not provided',
time: 5000,
})
throw new Error('downloader is required, but was not provided');
}
let settings = getDownloadSettings(excludedURLs)
let body = {
urls: urls,
downloader: downloader,
sub_downloader: sub_downloader,
frequency: frequency || null,
settings: settings,
};
const response = await apiPut(`${API_URI}/download`, body);
return response;
}
export async function killDownload(download_id) {
let response = await apiPost(`${API_URI}/download/${download_id}/kill`);
return response;

View file

@ -1,20 +1,21 @@
import React, {useState} from "react";
import {Dimmer, Dropdown, Grid, StatisticLabel, StatisticValue, TableCell, TableRow,} from "semantic-ui-react";
import {
AccordionContent,
AccordionTitle,
Grid,
StatisticLabel,
StatisticValue,
TableCell,
TableRow,
} from "semantic-ui-react";
import {createChannel, deleteChannel, downloadChannel, refreshChannel, updateChannel, validateRegex} from "../api";
createChannel,
createChannelDownload,
deleteChannel,
deleteDownload,
refreshChannel,
updateChannel,
updateChannelDownload
} from "../api";
import {
APIButton,
BackButton,
DirectoryInput,
ErrorMessage,
frequencyOptions,
HelpHeader,
humanFileSize,
RequiredAsterisk,
SearchInput,
@ -22,18 +23,31 @@ import {
secondsToFullDuration,
Toggle,
useTitle,
validURL,
WROLModeMessage
} from "./Common";
import {Link, useNavigate, useParams} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {useChannel, useChannels, useOneQuery} from "../hooks/customHooks";
import {useChannel, useChannels, useOneQuery, useWROLMode} from "../hooks/customHooks";
import _ from "lodash";
import {Accordion, Button, Form, FormField, FormGroup, FormInput, Header, Loader, Segment, Statistic} from "./Theme";
import Dropdown from "semantic-ui-react/dist/commonjs/modules/Dropdown";
import {
Button,
Form,
FormField,
FormGroup,
FormInput,
Header,
Loader,
Modal,
ModalContent,
Segment,
Statistic
} from "./Theme";
import {Media, ThemeContext} from "../contexts/contexts";
import {SortableTable} from "./SortableTable";
import {toast} from "react-semantic-toasts-2";
import {RecurringDownloadsTable} from "./admin/Downloads";
import {TagsSelector, useTags} from "../Tags";
function ChannelStatistics({statistics}) {
@ -65,13 +79,13 @@ function ChannelStatistics({statistics}) {
function ChannelPage({create, header}) {
const [disabled, setDisabled] = useState(false);
const [validRegex, setValidRegex] = useState(true);
const [activeIndex, setActiveIndex] = useState(-1);
const [errors, setErrors] = useState({});
const [error, setError] = useState(false);
const [success, setSuccess] = useState(false);
const [messageHeader, setMessageHeader] = useState();
const [messageContent, setMessageContent] = useState();
const [downloadModalOpen, setDownloadModalOpen] = useState(false);
const [rssDownloadOpen, setRssDownloadOpen] = useState(false);
const navigate = useNavigate();
const {channelId} = useParams();
@ -87,12 +101,6 @@ function ChannelPage({create, header}) {
return <Loader active/>;
}
const checkRegex = async (e, {value}) => {
changeValue('match_regex', value);
const valid = await validateRegex(value);
setValidRegex(valid);
}
const handleCheckbox = (e, {name, checked}) => {
if (e) {
e.preventDefault();
@ -130,8 +138,6 @@ function ChannelPage({create, header}) {
directory: channel.directory,
mkdir: channel.mkdir,
url: channel.url,
download_frequency: channel.download_frequency,
match_regex: channel.match_regex,
};
setDisabled(true);
@ -208,29 +214,6 @@ function ChannelPage({create, header}) {
}
}
const handleAdvancedClick = (e, {index}) => {
setActiveIndex(activeIndex === index ? -1 : index);
}
const handleDownloadChannel = async (e) => {
if (e) {
e.preventDefault();
}
try {
const response = await downloadChannel(channelId);
if (response.status === 204) {
toast({
type: 'success',
title: 'Download Created',
description: 'Channel download has been started.',
time: 5000,
});
}
} catch (e) {
console.error(e);
}
}
const handleRefreshChannel = async (e) => {
if (e) {
e.preventDefault();
@ -257,6 +240,13 @@ function ChannelPage({create, header}) {
}
}
let channelDownloads = channel && channel.channel_downloads ? channel.channel_downloads : null;
const afterNewDownloadSave = async () => {
await fetchChannel();
setDownloadModalOpen(false);
}
return <>
<BackButton/>
{!create &&
@ -326,7 +316,6 @@ function ChannelPage({create, header}) {
label="URL"
name="url"
type="url"
disabled={disabled}
placeholder='https://example.com/channel/videos'
error={errors.url}
value={channel.url}
@ -335,51 +324,6 @@ function ChannelPage({create, header}) {
</FormField>
</FormGroup>
<FormGroup>
<FormField>
<label>Download Frequency</label>
<Dropdown selection clearable
name='download_frequency'
placeholder='Frequency'
error={errors.download_frequency}
value={channel.download_frequency}
disabled={disabled || !channel.url}
options={frequencyOptions}
onChange={handleInputChange}
/>
</FormField>
</FormGroup>
<Accordion style={{marginBottom: '1em'}}>
<AccordionTitle
onClick={handleAdvancedClick}
index={0}
active={activeIndex === 0}
>
<Icon name='dropdown'/>
Advanced Settings
</AccordionTitle>
<AccordionContent active={activeIndex === 0}>
<Segment secondary>
<Header as="h4">
The following settings are encouraged by default, modify them at your own risk.
</Header>
<FormField>
<FormInput
label="Title Match Regex"
name="match_regex"
type="text"
disabled={disabled}
error={!validRegex}
placeholder='.*([Nn]ame Matching).*'
value={channel.match_regex}
onChange={checkRegex}
/>
</FormField>
</Segment>
</AccordionContent>
</Accordion>
<Message error
header={messageHeader}
content={messageContent}
@ -401,18 +345,14 @@ function ChannelPage({create, header}) {
confirmButton='Delete'
onClick={handleDelete}
obeyWROLMode={true}
style={{marginTop: '1em'}}
>Delete</APIButton>
<APIButton
color='green'
size='small'
onClick={handleDownloadChannel}
obeyWROLMode={true}
>Download</APIButton>
<APIButton
color='blue'
size='small'
onClick={handleRefreshChannel}
obeyWROLMode={true}
style={{marginTop: '1em'}}
>Refresh</APIButton>
</>
}
@ -433,12 +373,218 @@ function ChannelPage({create, header}) {
</Form>
</Segment>
{!create && <Segment>
<Grid columns={2}>
<Grid.Row>
<Grid.Column>
<Header as='h1'>Downloads</Header>
</Grid.Column>
<Grid.Column>
<Button floated='right'
onClick={() => setDownloadModalOpen(!downloadModalOpen)}
>
New Download
</Button>
</Grid.Column>
</Grid.Row>
</Grid>
<Modal open={downloadModalOpen} closeIcon onClose={() => setDownloadModalOpen(false)}>
<ModalContent>
<Header as='h2'>New Channel Download</Header>
<ChannelDownloadForm
channel_id={channelId}
afterSave={afterNewDownloadSave}
closeModal={() => setDownloadModalOpen(false)}
/>
</ModalContent>
</Modal>
<RecurringDownloadsTable downloads={channelDownloads} fetchDownloads={fetchChannel}/>
</Segment>}
<div style={{marginTop: '2em'}}>
{channel.statistics && <ChannelStatistics statistics={channel.statistics}/>}
</div>
</>
}
export function ChannelDownloadForm({channel_id, afterSave, closeModal, download}) {
download = download || {};
channel_id = download ? download.channel_id || channel_id : channel_id;
const editing = download && !_.isEmpty(download);
const settings = download.settings ? download.settings : {};
const oldTagNames = download && download.settings && download.settings.tag_names ? download.settings.tag_names : [];
const [state, setState] = React.useState({
url: download ? download.url : '',
frequency: download.frequency ? download.frequency : 604800,
title_match: settings.title_match ? settings.title_match : '',
title_exclude: settings.title_exclude ? settings.title_exclude : '',
})
const [disabled, setDisabled] = React.useState(useWROLMode());
const [loading, setLoading] = React.useState(false);
const [urlValid, setUrlValid] = React.useState(true);
const [tagNames, setTagNames] = React.useState(oldTagNames);
const handleInputChange = (e, {name, value}) => {
if (e) {
e.preventDefault();
}
if (name === 'url') {
setUrlValid(validURL(value));
}
setState({...state, [name]: value});
}
const handleSubmit = async () => {
setLoading(true);
setDisabled(true);
try {
let response;
if (editing) {
response = await updateChannelDownload(
channel_id,
download.id,
state.url,
state.frequency,
state.title_match,
state.title_exclude,
tagNames,
);
} else {
response = await createChannelDownload(
channel_id,
state.url,
state.frequency,
state.title_match,
state.title_exclude,
tagNames,
);
}
if (!response.ok) {
throw 'Creating download failed';
}
if (afterSave) {
await afterSave();
}
} finally {
setLoading(false);
setDisabled(false);
}
}
const handleClose = (e) => {
if (e) e.preventDefault();
closeModal();
}
const handleDelete = async () => {
await deleteDownload(download.id);
if (afterSave) {
afterSave();
}
if (closeModal) {
closeModal();
}
};
const handleAddTag = (tagName) => {
setTagNames([...tagNames, tagName]);
}
const handleUntag = (tagName) => {
setTagNames(tagNames.filter(i => i !== tagName));
}
const deleteDownloadButton = <APIButton
color='red'
floated='left'
onClick={handleDelete}
confirmContent='Are you sure you want to delete this download?'
confirmButton='Delete'
disabled={disabled}
obeyWROLMode={true}
>Delete</APIButton>;
return <Form onSubmit={handleSubmit}>
{loading && <Dimmer active><Loader/></Dimmer>}
<Grid columns={2} stackable>
<Grid.Row>
<Grid.Column width={12}>
<FormInput
label='URL'
name='url'
type='url'
value={state.url}
placeholder='https://example.com/videos'
onChange={handleInputChange}
error={!urlValid}
/>
</Grid.Column>
<Grid.Column width={4}>
<FormField>
<label>Download Frequency</label>
<Dropdown selection
name='frequency'
placeholder='Frequency'
value={state.frequency}
disabled={disabled}
options={frequencyOptions.slice(1)}
onChange={handleInputChange}
/>
</FormField>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<HelpHeader
headerSize='h4'
headerContent='Title Match Words'
popupContent='List of words, separated by commas, that Video titles must contain to be downloaded.'
popupPosition='bottom center'
/>
<FormInput
name="title_match"
type="text"
disabled={disabled}
placeholder='Shelter,Solar Power'
value={state.title_match}
onChange={handleInputChange}
/>
</Grid.Column>
<Grid.Column>
<HelpHeader
headerSize='h4'
headerContent='Title Exclusion Words'
popupContent='List of words, separated by commas, that may not appear in video titles to be downloaded.'
popupPosition='bottom center'
/>
<FormInput
name="title_exclude"
type="text"
disabled={disabled}
placeholder='Giveaway,Prize'
value={state.title_exclude}
onChange={handleInputChange}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={1}>
<Grid.Column>
<TagsSelector selectedTagNames={tagNames} onAdd={handleAddTag} onRemove={handleUntag}/>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={1}>
<Grid.Column textAlign='right'>
{editing && deleteDownloadButton}
<Button onClick={handleClose}>Cancel</Button>
<Button color='violet' disabled={!urlValid}>Save</Button>
</Grid.Column>
</Grid.Row>
</Grid>
</Form>
}
export function ChannelEditPage(props) {
return <ChannelPage header="Edit Channel" {...props}/>;
}
@ -463,7 +609,7 @@ function ChannelRow({channel}) {
{channel.video_count}
</TableCell>
<TableCell>
{channel.url && channel.download_frequency ? secondsToFrequency(channel.download_frequency) : null}
{channel.url && channel.minimum_frequency ? secondsToFrequency(channel.minimum_frequency) : null}
</TableCell>
<TableCell>
{channel.size ? humanFileSize(channel.size) : null}
@ -532,7 +678,7 @@ export function ChannelsPage() {
const headers = [
{key: 'name', text: 'Name', sortBy: 'name', width: 8},
{key: 'video_count', text: 'Videos', sortBy: 'video_count', width: 2},
{key: 'download_frequency', text: 'Download Frequency', sortBy: 'download_frequency', width: 2},
{key: 'download_frequency', text: 'Download Frequency', sortBy: 'minimum_frequency', width: 2},
{key: 'size', text: 'Size', sortBy: 'size', width: 2},
{key: 'manage', text: 'Manage', width: 2},
];

View file

@ -735,23 +735,23 @@ export function CardPoster({to, file}) {
}
}
export function HelpPopup({icon, size, content, position, iconSize = 'small'}) {
export function HelpPopup({icon = 'question', size = null, content, position = 'left center', iconSize = 'small'}) {
return <Popup
content={content}
size={size || null}
position={position || 'left center'}
trigger={<Icon circular link name={icon || 'question'} size={iconSize}
size={size}
position={position}
trigger={<Icon circular link name={icon} size={iconSize}
style={{marginLeft: '0.25em', marginRight: '0.25em'}}
/>}
/>
}
export function HelpHeader({icon, headerSize, iconSize, headerContent, popupContent}) {
export function HelpHeader({icon, headerSize = 'h2', iconSize, headerContent, popupContent, popupPosition = 'top center'}) {
return <div className='inline-header'>
<Header as={headerSize || 'h2'}>{headerContent}</Header>
<Header as={headerSize}>{headerContent}</Header>
<span>
<HelpPopup content={popupContent} size={iconSize} icon={icon}/>
</span>
<HelpPopup content={popupContent} size={iconSize} icon={icon} position={popupPosition}/>
</span>
</div>
}
@ -1788,3 +1788,9 @@ export function Breadcrumbs({crumbs, size = undefined}) {
))}
</Breadcrumb>
}
const validUrlRegex = /^(http|https):\/\/[^ "]+$/;
export function validURL(url) {
return !(url && !validUrlRegex.test(url));
}

View file

@ -1,6 +1,14 @@
import React, {useContext, useState} from "react";
import {getDownloaders, postDownload} from "../api";
import {APIButton, DirectorySearch, frequencyOptions, HelpPopup, rssFrequencyOptions, WROLModeMessage} from "./Common";
import {
APIButton,
DirectorySearch,
frequencyOptions,
HelpPopup,
rssFrequencyOptions,
validURL,
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";
@ -11,8 +19,6 @@ import {TagsSelector} from "../Tags";
import {toast} from "react-semantic-toasts-2";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
const validUrl = /^(http|https):\/\/[^ "]+$/;
class Downloader extends React.Component {
constructor(props) {
super(props);
@ -58,9 +64,7 @@ class Downloader extends React.Component {
let urls = this.state.urls.split(/\r?\n/);
let valid = true;
urls.forEach((url) => {
if (valid && url && !validUrl.test(url)) {
valid = false;
}
valid = validURL(url);
})
this.setState({valid});
}
@ -192,7 +196,7 @@ class ChannelDownload extends React.Component {
handleUrlChange = (e, {value}) => {
e.preventDefault();
let ready = value && validUrl.test(value);
let ready = value && validURL(value);
this.setState({url: value, ready, success: false});
}

View file

@ -242,7 +242,7 @@ function VideosStatistics() {
];
const commentsNames = [
{key: 'have_comments', label: 'Have Comments'},
{key: 'no_comments', label: 'Missing Comments'},
{key: 'missing_comments', label: 'Missing Comments'},
{key: 'failed_comments', label: 'Failed Comments'},
];
const historicalNames = [

View file

@ -4,6 +4,7 @@ import {
deleteDownload,
deleteOnceDownloads,
killDownload,
putDownload,
restartDownload,
retryOnceDownloads
} from "../../api";
@ -12,13 +13,18 @@ import {
APIButton,
DisableDownloadsToggle,
ErrorMessage,
frequencyOptions,
isoDatetimeToElapsedPopup,
secondsToFrequency,
useTitle,
validURL,
WROLModeMessage
} from "../Common";
import {
Button as SButton,
Dimmer,
Dropdown,
Grid,
Label,
Loader,
PlaceholderLine,
@ -29,9 +35,23 @@ import {
TableHeaderCell,
TableRow
} from "semantic-ui-react";
import {Button, Header, Modal, ModalActions, ModalContent, ModalHeader, Placeholder, Segment, Table} from "../Theme";
import {useDownloads} from "../../hooks/customHooks";
import {
Button,
Form,
FormField,
FormInput,
Header,
Modal,
ModalActions,
ModalContent,
ModalHeader,
Placeholder,
Segment,
Table
} from "../Theme";
import {useDownloads, useWROLMode} from "../../hooks/customHooks";
import {toast} from "react-semantic-toasts-2";
import {ChannelDownloadForm} from "../Channels";
function ClearDownloadsButton({callback}) {
async function localClearDownloads() {
@ -91,11 +111,134 @@ function DeleteOnceDownloadsButton({callback}) {
>Delete</APIButton>
}
export function DownloadEditForm({afterSave, closeModal, download}) {
const [state, setState] = React.useState({
url: download.url || '',
frequency: download.frequency,
excluded_urls: download.excluded_urls || '',
})
const [disabled, setDisabled] = React.useState(useWROLMode());
const [loading, setLoading] = React.useState(false);
const [urlValid, setUrlValid] = React.useState(true);
const handleInputChange = (e, {name, value}) => {
if (e) {
e.preventDefault();
}
if (name === 'url') {
setUrlValid(validURL(value));
}
setState({...state, [name]: value});
}
const handleSubmit = async () => {
setLoading(true);
setDisabled(true);
try {
const response = await putDownload(
[state.url],
download.id,
download.downloader,
download.sub_downloader,
state.frequency,
state.excluded_urls,
);
if (!response.ok) {
throw 'Updating download failed';
}
} finally {
setLoading(false);
setDisabled(false);
if (afterSave) {
afterSave();
}
}
}
const handleClose = (e) => {
if (e) e.preventDefault();
closeModal();
}
const handleDelete = async () => {
await deleteDownload(download.id);
if (afterSave) {
afterSave();
}
if (closeModal) {
closeModal();
}
};
const deleteDownloadButton = <APIButton
color='red'
floated='left'
onClick={handleDelete}
confirmContent='Are you sure you want to delete this download?'
confirmButton='Delete'
disabled={disabled}
obeyWROLMode={true}
>Delete</APIButton>;
return <Form onSubmit={handleSubmit}>
{loading && <Dimmer active><Loader/></Dimmer>}
<Grid columns={2} stackable>
<Grid.Row>
<Grid.Column width={12}>
<FormInput
label='URL'
name='url'
type='url'
value={state.url}
placeholder='https://example.com/videos'
onChange={handleInputChange}
error={!urlValid}
/>
</Grid.Column>
<Grid.Column width={4}>
<FormField>
<label>Download Frequency</label>
<Dropdown selection
name='frequency'
placeholder='Frequency'
value={state.frequency}
disabled={disabled}
options={frequencyOptions.slice(1)}
onChange={handleInputChange}
/>
</FormField>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<FormInput
label='Excluded URLs'
name='excluded_urls'
type='text'
value={state.excluded_urls}
onChange={handleInputChange}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={1}>
<Grid.Column textAlign='right'>
{deleteDownloadButton}
<Button onClick={handleClose}>Cancel</Button>
<Button color='violet' disabled={!urlValid}>Save</Button>
</Grid.Column>
</Grid.Row>
</Grid>
</Form>
}
class RecurringDownloadRow extends React.Component {
constructor(props) {
super(props);
this.state = {
errorModalOpen: false,
editModalOpen: false,
}
}
@ -133,7 +276,17 @@ class RecurringDownloadRow extends React.Component {
}
render() {
let {url, frequency, last_successful_download, status, location, next_download, error} = this.props;
let {
url,
frequency,
last_successful_download,
status,
location,
next_download,
error,
downloader,
channel_id
} = this.props;
const {errorModalOpen} = this.state;
const link = location ?
@ -167,6 +320,10 @@ class RecurringDownloadRow extends React.Component {
/>
</>;
const editButton = <>
<Button icon='edit' onClick={() => this.setState({editModalOpen: true})}/>
</>
const restartButton = <>
<APIButton
color='green'
@ -184,6 +341,28 @@ class RecurringDownloadRow extends React.Component {
next = isoDatetimeToElapsedPopup(next_download);
}
const handleClose = () => this.setState({editModalOpen: false});
const afterSave = () => {
if (this.props.fetchDownloads) {
this.props.fetchDownloads();
}
handleClose();
}
const editModal = <Modal closeIcon
open={this.state.editModalOpen}
onClose={handleClose}
>
<ModalHeader>Edit Download</ModalHeader>
<ModalContent>
{downloader === 'video_channel' ?
<ChannelDownloadForm download={this.props} closeModal={handleClose}
afterSave={afterSave}/>
: <DownloadEditForm download={this.props} closeModal={handleClose}
afterSave={afterSave}/>
}
</ModalContent>
</Modal>;
return <TableRow>
<TableCell className='column-ellipsis'>
{link(url)}
@ -194,11 +373,12 @@ class RecurringDownloadRow extends React.Component {
{status === 'pending' ? <Loader active inline size='tiny'/> : null}
</TableCell>
<TableCell>{next}</TableCell>
<TableCell>
<TableCell textAlign='right'>
{error && errorModal}
{deleteButton}
{editButton}
{restartButton}
</TableCell>
{editModal}
</TableRow>
}
}
@ -348,14 +528,14 @@ export function OnceDownloadsTable({downloads, fetchDownloads}) {
export function RecurringDownloadsTable({downloads, fetchDownloads}) {
if (downloads && downloads.length >= 1) {
return <Table className='table-ellipsis'>
return <Table compact className='table-ellipsis'>
<TableHeader>
<TableRow>
<TableHeaderCell width={8}>URL</TableHeaderCell>
<TableHeaderCell width={2}>Download Frequency</TableHeaderCell>
<TableHeaderCell width={2}>Completed At</TableHeaderCell>
<TableHeaderCell width={1}>Next</TableHeaderCell>
<TableHeaderCell width={3}>Control</TableHeaderCell>
<TableHeaderCell width={3} textAlign='right'>Control</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>

View file

@ -17,12 +17,12 @@ class MapFile(Base, ModelHelper):
def __repr__(self):
return f'<MapFile {self.path} imported={self.imported}>'
def __json__(self):
return {
'id': self.id,
'imported': self.imported,
'path': self.path,
'seconds_to_import': (seconds := lib.seconds_to_import(self.size)),
'size': self.size,
'time_to_import': dates.seconds_to_timestamp(seconds),
}
def __json__(self) -> dict:
return dict(
id=self.id,
imported=self.imported,
path=self.path,
seconds_to_import=(seconds := lib.seconds_to_import(self.size)),
size=self.size,
time_to_import=dates.seconds_to_timestamp(seconds),
)

View file

@ -1,7 +1,7 @@
import asyncio
from typing import List, Tuple
from modules.videos.models import Video, Channel
from modules.videos.models import Video
from wrolpi.common import logger, limit_concurrent, register_modeler, register_refresh_cleanup
from wrolpi.db import get_db_curs, get_db_session
from wrolpi.files.models import FileGroup

View file

@ -15,9 +15,10 @@ from wrolpi.events import Events
from wrolpi.schema import JSONErrorResponse
from wrolpi.vars import PYTEST
from . import lib
from .. import schema, Channel
from .. import schema
from ..errors import UnknownChannel
from ..lib import save_channels_config
from ..models import Channel
channel_bp = Blueprint('Channel', url_prefix='/api/videos/channels')
@ -109,13 +110,29 @@ def channel_refresh(_: Request, channel_id: int):
return response.empty()
@channel_bp.post('/download/<channel_id:int>')
@openapi.description('Download the latest catalog for a Channel, download any missing videos.')
@channel_bp.post('/<channel_id:int>/download', name='post_channel_download')
@channel_bp.put('/<channel_id:int>/download/<download_id:int>', name='put_channel_download')
@openapi.description('Create or update a Channel Download record')
@validate(schema.ChannelDownloadRequest)
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@wrol_mode_check
def channel_download(_: Request, channel_id: int):
lib.download_channel(channel_id, reset_attempts=True)
if download_manager.disabled.is_set():
async def channel_download(_: Request, channel_id: int, body: schema.ChannelDownloadRequest, download_id: int = None):
if download_id:
await lib.update_channel_download(
channel_id,
download_id,
body.url,
body.frequency,
body.settings,
)
else:
await lib.create_channel_download(
channel_id,
body.url,
body.frequency,
body.settings,
)
if download_manager.is_disabled:
# Warn the user that downloads are disabled.
Events.send_downloads_disabled('Channel download created. But downloads are disabled.')
return response.empty()

View file

@ -8,13 +8,12 @@ from sqlalchemy.orm.exc import NoResultFound
from wrolpi.common import run_after, logger, \
get_media_directory
from wrolpi.db import get_db_curs, optional_session, get_db_session
from wrolpi.downloader import download_manager
from wrolpi.errors import UnknownDirectory, APIError, ValidationError
from wrolpi.errors import UnknownDirectory, APIError, ValidationError, InvalidDownload
from .. import schema
from ..common import check_for_channel_conflicts
from ..errors import UnknownChannel
from ..lib import save_channels_config
from ..models import Channel, Video
from ..models import Channel, Video, ChannelDownload
logger = logger.getChild(__name__)
@ -24,17 +23,24 @@ async def get_minimal_channels() -> List[dict]:
Get the minimum amount of information necessary about all channels.
"""
with get_db_curs() as curs:
# Get all channels, even if they don't have videos.
# Get all channels, even if they don't have videos. Also get the minimum frequency download because this is the
# one that will consume the most resources.
stmt = '''
SELECT
c.id, name, directory, c.url, download_frequency,
c.id, name, directory, c.url,
COUNT(v.id) as video_count,
SUM(fg.size)::BIGINT AS size
SUM(fg.size)::BIGINT AS size,
(
select min(d.frequency)
from download d
left join channel_download cd on cd.download_url = d.url
where cd.channel_id = c.id
) AS minimum_frequency
FROM
channel AS c
LEFT JOIN video v on c.id = v.channel_id
LEFT JOIN file_group fg on fg.id = v.file_group_id
GROUP BY 1, 2, 3, 4, 5
GROUP BY 1, 2, 3, 4
'''
curs.execute(stmt)
channels = sorted([dict(i) for i in curs.fetchall()], key=lambda i: i['name'].lower())
@ -183,24 +189,6 @@ def delete_channel(session: Session, *, channel_id: int):
return channel_dict
def download_channel(id_: int, reset_attempts: bool = False):
"""Create a Download record for a Channel's entire catalog. Start downloading."""
from modules.videos.downloader import ChannelDownloader, VideoDownloader
channel: Channel = get_channel(channel_id=id_, return_dict=False)
with get_db_session(commit=True) as session:
download = channel.get_download()
if not download and channel.url:
# Channel does not have recurring download, schedule a once-download.
download = download_manager.create_download(
session=session,
url=channel.url,
downloader_name=ChannelDownloader.name,
sub_downloader_name=VideoDownloader.name,
reset_attempts=reset_attempts,
)
logger.info(f'Created download for {channel} with {download}')
@optional_session
async def search_channels_by_name(name: str, limit: int = 5, session: Session = None,
order_by_video_count: bool = False) -> List[Channel]:
@ -227,3 +215,34 @@ async def search_channels_by_name(name: str, limit: int = 5, session: Session =
.limit(limit)
channels = stmt.all()
return channels
async def create_channel_download(channel_id: int, url: str, frequency: int, settings: dict) -> ChannelDownload:
"""Create ChannelDownload."""
with get_db_session(commit=True) as session:
channel = get_channel(session, channel_id=channel_id, return_dict=False)
cd = channel.get_or_create_download(url, session, reset_attempts=True)
cd.download.frequency = cd.download.frequency or frequency
cd.download.settings = settings
save_channels_config()
return cd
async def update_channel_download(channel_id: int, download_id: int, url: str, frequency: int, settings: dict) \
-> ChannelDownload:
"""Fetch ChannelDownload, update its properties."""
with get_db_session(commit=True) as session:
channel = get_channel(session, channel_id=channel_id, return_dict=False)
cd = channel.get_download(download_id=download_id)
if not cd:
raise InvalidDownload('No Download with that ID on this Channel')
cd.download.url = url
cd.download.frequency = cd.download.frequency or frequency
cd.download.settings = settings
save_channels_config()
return cd

View file

@ -2,15 +2,14 @@ import asyncio
import json
import pathlib
import tempfile
import time
from datetime import timedelta
from http import HTTPStatus
import mock
import pytest
from modules.videos.channel.lib import delete_channel
from modules.videos.models import Channel
from modules.videos.downloader import ChannelDownloader
from modules.videos.models import Channel, ChannelDownload
from wrolpi.dates import now
from wrolpi.db import get_db_session
from wrolpi.downloader import download_manager, Download, DownloadResult
@ -60,116 +59,28 @@ def test_channel_no_download_frequency(test_client, test_session, test_directory
# Get the Channel
request, response = test_client.get('/api/videos/channels/1')
channel = response.json['channel']
assert channel['download_frequency'] is None
assert not channel['channel_downloads']
# Update the Channel with a frequency.
new_channel = dict(
directory=channel['directory'],
name=channel['name'],
url=channel['url'],
download_frequency=10,
)
request, response = test_client.put(f'/api/videos/channels/{simple_channel.id}',
content=json.dumps(new_channel))
new_download = {'urls': [simple_channel.url], 'frequency': 10, 'downloader': ChannelDownloader.name}
request, response = test_client.post('/api/download', json=new_download)
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
# Download is scheduled.
# Download is scheduled. ChannelDownload was created.
assert len(download_manager.get_downloads(test_session)) == 1
request, response = test_client.get('/api/videos/channels/1')
channel = response.json['channel']
assert channel['channel_downloads']
channel_downloads = channel['channel_downloads']
assert len(channel_downloads) == 1 and channel_downloads[0]['url'] == simple_channel.url
assert test_session.query(ChannelDownload).one()
download_id = channel['channel_downloads'][0]['id']
# Remove the frequency.
new_channel = dict(
directory=channel['directory'],
name=channel['name'],
url=channel['url'],
download_frequency=None,
)
request, response = test_client.put(f'/api/videos/channels/{simple_channel.id}',
content=json.dumps(new_channel))
# Deleting the Download deletes the ChannelDownload.
request, response = test_client.delete(f'/api/download/{download_id}')
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
@pytest.mark.asyncio
async def test_channel_frequency_update(download_channel, test_async_client, test_session, test_download_manager):
"""
A Channel's Download record is updated when the Channel's frequency is updated.
"""
old_frequency = download_channel.get_download().frequency
assert old_frequency
data = dict(
directory=str(download_channel.directory),
name=download_channel.name,
url=download_channel.url,
download_frequency=100,
)
request, response = await test_async_client.put(f'/api/videos/channels/{download_channel.id}', json=data)
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
download = download_channel.get_download()
assert download.frequency == 100
# Only one download
downloads = test_session.query(Download).all()
assert len(list(downloads)) == 1
@pytest.mark.asyncio
async def test_channel_download_crud(test_session, simple_channel, test_downloader_config):
"""Modifying a Channel modifies its Download."""
assert simple_channel.url
assert simple_channel.download_frequency is None
simple_channel.update({'download_frequency': 1000})
test_session.commit()
download: Download = test_session.query(Download).one()
assert simple_channel.get_download() == download
assert simple_channel.url == download.url
assert simple_channel.download_frequency == download.frequency
# Increase the frequency to 1 second.
simple_channel.update({'download_frequency': 1})
test_session.commit()
assert simple_channel.url == download.url
assert simple_channel.download_frequency == download.frequency == 1
assert test_session.query(Download).count() == 1
# Changing the Channel's URL changes the download's URL.
simple_channel.update({'url': 'https://example.com/new url'})
test_session.commit()
assert simple_channel.url == 'https://example.com/new url'
assert simple_channel.download_frequency == download.frequency == 1
assert test_session.query(Download).count() == 1
# Removing the Channel's frequency removes the download.
simple_channel.update({'download_frequency': None})
test_session.commit()
assert test_session.query(Download).count() == 0
# Removing the URL is supported.
simple_channel.update({'url': None})
test_session.commit()
# Adding a URL is supported.
simple_channel.update({'url': 'https://example.com'})
test_session.commit()
# Adding a frequency adds a Download.
simple_channel.update({'download_frequency': 1})
test_session.commit()
assert test_session.query(Download).count() == 1
next_download = simple_channel.get_download().next_download
assert next_download
# Next download isn't overwritten.
time.sleep(1)
simple_channel.update({'name': 'new name'})
test_session.commit()
assert simple_channel.get_download().next_download == next_download
# Deleting a Channel deletes it's Download.
delete_channel(channel_id=simple_channel.id)
assert test_session.query(Download).count() == 0
assert not download_manager.get_downloads(test_session)
assert not test_session.query(ChannelDownload).all()
def test_video_file_name(test_session, simple_video, test_client):
@ -185,7 +96,6 @@ def test_channel_conflicts(test_client, test_session, test_directory):
pathlib.Path(channel_directory).mkdir()
new_channel = dict(
directory=channel_directory,
match_regex='asdf',
name='Example Channel 1',
url='https://example.com/channel1',
)
@ -271,13 +181,14 @@ def test_channel_empty_url_doesnt_conflict(test_client, test_session, test_direc
@pytest.mark.asyncio
async def test_channel_download_requires_refresh(
test_async_client, test_session, download_channel, video_download_manager, video_factory, events_history):
test_async_client, test_session, mock_video_extract_info, download_channel, video_download_manager,
video_factory, events_history):
"""A Channel cannot be downloaded until it has been refreshed.
Videos already downloaded are not downloaded again."""
vid = video_factory(channel_id=download_channel.id, with_video_file=True, with_poster_ext='jpg')
vid.file_group.url = 'https://example.com/1'
d = download_channel.get_download()
d = download_channel.channel_downloads[0].download
d.next_download = None
test_session.commit()
assert not d.next_download
@ -299,15 +210,14 @@ async def test_channel_download_requires_refresh(
downloaded_urls.append(download.url)
return DownloadResult(success=True)
with mock.patch('modules.videos.downloader.YDL.extract_info') as mock_extract_info, \
mock.patch('modules.videos.downloader.VideoDownloader.do_download', do_download), \
with mock.patch('modules.videos.downloader.VideoDownloader.do_download', do_download), \
mock.patch('wrolpi.files.lib.apply_indexers'): # TODO why does apply_indexers break this test?
entries = [
dict(id=vid.source_id, view_count=0, webpage_url='https://example.com/1'), # Already downloaded.
dict(id='not downloaded', view_count=0, webpage_url='https://example.com/2'),
]
mock_extract_info.return_value = {'entries': entries, 'url': 'foo', 'uploader': 'some uploader',
'channel_id': 'the id', 'id': 'the id'}
mock_video_extract_info.return_value = dict(entries=entries, url=download_channel.url, uploader='some uploader',
channel_id='the id', id='the id')
await video_download_manager.do_downloads()
await video_download_manager.wait_for_all_downloads()
# Give time for background tasks to finish. :(
@ -356,7 +266,6 @@ async def test_channel_crud(test_session, test_async_client, test_directory, tes
new_channel = dict(
directory=str(channel_directory),
match_regex='asdf',
name=' Example Channel 1 ',
url='https://example.com/channel1',
)
@ -367,7 +276,7 @@ async def test_channel_crud(test_session, test_async_client, test_directory, tes
# Create it
request, response = await test_async_client.post('/api/videos/channels', content=json.dumps(new_channel))
assert response.status_code == HTTPStatus.CREATED, response.json
assert response.status_code == HTTPStatus.CREATED, response.content
location = response.headers['Location']
request, response = await test_async_client.get(location)
@ -376,7 +285,6 @@ async def test_channel_crud(test_session, test_async_client, test_directory, tes
assert created
assert created['id']
# No frequency was provided. No download exists.
assert not created['download_frequency']
assert test_session.query(Download).count() == 0
# Channel name leading/trailing whitespace should be stripped
@ -391,7 +299,7 @@ async def test_channel_crud(test_session, test_async_client, test_directory, tes
assert response.status_code == HTTPStatus.BAD_REQUEST
async def put_and_fetch(new_channel_):
request, response = await test_async_client.put(location, content=json.dumps(new_channel))
request, response = await test_async_client.put(location, content=json.dumps(new_channel_))
assert response.status_code == HTTPStatus.NO_CONTENT, response.status_code
request, response = await test_async_client.get(location)
assert response.status_code == HTTPStatus.OK
@ -401,24 +309,11 @@ async def test_channel_crud(test_session, test_async_client, test_directory, tes
# Update it
new_channel['name'] = 'Example Channel 2'
new_channel['directory'] = str(new_channel['directory']) # noqa
new_channel['download_frequency'] = 60
channel = await put_and_fetch(new_channel)
assert channel['id'] == 1
assert channel['name'] == 'Example Channel 2'
assert channel['directory'] == channel_directory.name
assert channel['match_regex'] == 'asdf'
assert channel['url'] == 'https://example.com/channel1'
# Download was created.
assert channel['download_frequency']
assert (downloads := test_download_manager.get_downloads(test_session)) and len(downloads) == 1 and downloads[
0].url == new_channel['url']
# Update with no download frequency.
new_channel['download_frequency'] = None
channel = await put_and_fetch(new_channel)
assert channel['download_frequency'] is None
# Download was deleted.
assert len(test_download_manager.get_downloads(test_session)) == 0
# Can't update channel that doesn't exist
request, response = await test_async_client.put('/api/videos/channels/doesnt_exist',
@ -428,29 +323,13 @@ async def test_channel_crud(test_session, test_async_client, test_directory, tes
# Delete the new channel
request, response = await test_async_client.delete(location)
assert response.status_code == HTTPStatus.NO_CONTENT
assert test_session.query(Download).count() == 0
# Cant delete it again
request, response = await test_async_client.delete(location)
assert response.status_code == HTTPStatus.NOT_FOUND
def test_channel_creation_with_download(test_client, test_session, test_directory):
"""A Download is created when a Channel is created."""
new_channel = dict(
directory=str(test_directory),
name='Download this one',
url='https://example.com/channel1',
download_frequency=60,
)
request, response = test_client.post('/api/videos/channels', content=json.dumps(new_channel))
assert response.status_code == HTTPStatus.CREATED
download = test_session.query(Download).one()
assert download.url == 'https://example.com/channel1'
assert download.downloader == 'video_channel'
assert download.sub_downloader == 'video'
@pytest.mark.asyncio
async def test_change_channel_url(test_async_client, test_session, test_download_manager, download_channel,
test_download_manager_config):
@ -458,12 +337,8 @@ async def test_change_channel_url(test_async_client, test_session, test_download
download_channel.update({'url': 'https://example.com/new-url'})
test_session.commit()
download = test_session.query(Download).one()
assert download.url == download_channel.url == 'https://example.com/new-url', \
"Channel's download URL was not changed."
download_channel.update({'download_frequency': None})
assert not list(test_session.query(Download).all())
channel = test_session.query(Channel).one()
assert channel.url == 'https://example.com/new-url', "Channel's URL was not changed."
def test_search_videos_channel(test_client, test_session, video_factory):
@ -532,3 +407,45 @@ def test_get_channel_videos_pagination(test_session, simple_channel, video_facto
current_ids = [i['id'] for i in response.json['file_groups']]
assert current_ids != last_ids, f'IDs are unchanged current_ids={current_ids}'
last_ids = current_ids
@pytest.mark.asyncio
async def test_create_channel_download(test_async_client, test_session, simple_channel, tag_factory):
tag = tag_factory()
# Create ChannelDownload (which includes a Download).
body = {'url': 'https://example.com/1', 'frequency': 42}
request, response = await test_async_client.post(
f'/api/videos/channels/{simple_channel.id}/download', json=body)
assert response.status_code == HTTPStatus.NO_CONTENT, response.content
download: Download = test_session.query(Download).one()
assert download.url == 'https://example.com/1' and not download.settings.get('tag_names')
# Create another ChannelDownload. Previous ChannelDownload/Download are untouched.
body = {'url': 'https://example.com/2', 'frequency': 55, 'settings': {'tag_names': [tag.name]}}
request, response = await test_async_client.post(
f'/api/videos/channels/{simple_channel.id}/download', json=body)
assert response.status_code == HTTPStatus.NO_CONTENT, response.content
download1, download2 = test_session.query(Download).order_by(Download.url).all()
assert download1.url == 'https://example.com/1' and not download1.settings.get('tag_names')
assert download2.url == 'https://example.com/2' and download2.settings.get('tag_names') == [tag.name, ]
test_session.flush(simple_channel)
assert len(simple_channel.channel_downloads) == 2
# Change frequency of first ChannelDownload.
body = {'url': 'https://example.com/1', 'frequency': 123, 'settings': {'title_include': 'foo,bar'}}
request, response = await test_async_client.put(
f'/api/videos/channels/{simple_channel.id}/download/{download1.id}', json=body)
assert response.status_code == HTTPStatus.NO_CONTENT, response.content
download1, download2 = test_session.query(Download).order_by(Download.url).all()
assert download1.url == 'https://example.com/1'
assert download1.settings == {'title_include': 'foo,bar'}
assert download2.url == 'https://example.com/2' and download2.settings.get('tag_names') == [tag.name, ]
test_session.flush(simple_channel)
assert len(simple_channel.channel_downloads) == 2
# Deleting Download delets ChannelDownload.
request, response = await test_async_client.delete(f'/api/download/{download1.id}')
assert response.status_code == HTTPStatus.NO_CONTENT
assert test_session.query(ChannelDownload).count() == 1
assert test_session.query(Download).count() == 1

View file

@ -64,7 +64,8 @@ def test_get_channel(test_session, test_directory, channel_factory):
assert lib.get_channel(**p)
def test_channels_no_url(test_session, test_directory, test_channels_config):
@pytest.mark.asyncio
async def test_channels_no_url(test_async_client, test_session, test_directory, test_channels_config):
"""Test that a Channel's URL is coerced to None if it is empty."""
channel1_directory = test_directory / 'channel1'
channel1_directory.mkdir()

View file

@ -3,7 +3,9 @@ from http import HTTPStatus
import pytest
from modules.videos.models import Channel, ChannelDownload
from modules.videos.models import Video
from wrolpi.downloader import Download, DownloadFrequency
def test_delete_channel_no_url(test_session, test_client, channel_factory):
@ -66,3 +68,42 @@ async def test_nested_channel_directories(test_session, test_async_client, test_
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json['cause'] and \
response.json['cause']['message'] == 'The directory is already used by another channel.'
@pytest.mark.asyncio()
async def test_channel_download_relationships(test_session, download_channel):
"""Test relationships of ChannelDownload."""
test_session.flush()
download = test_session.query(Download).one()
cd = test_session.query(ChannelDownload).one()
channel = test_session.query(Channel).one()
assert len(channel.channel_downloads) == 1
assert channel.channel_downloads[0] == cd
assert channel.channel_downloads[0].download == download
test_session.commit()
download = test_session.query(Download).one()
cd = test_session.query(ChannelDownload).one()
channel = test_session.query(Channel).one()
assert len(channel.channel_downloads) == 1
assert channel.channel_downloads[0] == cd
assert channel.channel_downloads[0].download == download \
and channel.channel_downloads[0].download.url == 'https://example.com/channel1'
assert download.frequency == DownloadFrequency.weekly
# Deleting Download deletes the ChannelDownload, but not the Channel.
download.delete()
assert not test_session.query(Download).all()
assert not test_session.query(ChannelDownload).all()
assert test_session.query(Channel).one(), 'Channel should not have been deleted.'
# Create a Download again.
download_channel.get_or_create_download('https://example.com/1', test_session, reset_attempts=True)
assert test_session.query(Download).count() == 1
assert test_session.query(ChannelDownload).count() == 1
# Delete the Channel, and any relationships.
download_channel.delete_with_videos()
assert test_session.query(Download).count() == 0
assert test_session.query(ChannelDownload).count() == 0

View file

@ -14,7 +14,7 @@ from modules.videos.downloader import VideoDownloader, ChannelDownloader
from modules.videos.lib import set_test_channels_config, set_test_downloader_config
from modules.videos.models import Channel, Video
from wrolpi.api_utils import api_app
from wrolpi.downloader import DownloadFrequency, DownloadManager, Download
from wrolpi.downloader import DownloadFrequency, DownloadManager
from wrolpi.files.models import FileGroup
from wrolpi.vars import PROJECT_DIR
@ -26,7 +26,6 @@ def simple_channel(test_session, test_directory) -> Channel:
directory=test_directory,
name='Simple Channel',
url='https://example.com/channel1',
download_frequency=None, # noqa
)
test_session.add(channel)
test_session.commit()
@ -35,7 +34,7 @@ def simple_channel(test_session, test_directory) -> Channel:
@pytest.fixture
def channel_factory(test_session, test_directory):
"""Create a random Channel with a directory, but no frequency."""
"""Create a random Channel with a directory, ChannelDownload, and Download."""
def factory(source_id: str = None, download_frequency: DownloadFrequency = None, url: str = None, name: str = None,
directory: pathlib.Path = None):
@ -47,10 +46,16 @@ def channel_factory(test_session, test_directory):
directory=directory, # noqa
name=name,
url=url or f'https://example.com/{name}',
download_frequency=download_frequency,
source_id=source_id,
)
test_session.add(channel)
test_session.flush([channel])
assert channel.id and channel.url
if download_frequency:
cd = channel.get_or_create_download(channel.url)
cd.download.frequency = download_frequency
assert cd and cd.download_url == channel.url
assert channel.channel_downloads
test_session.commit()
return channel
@ -61,22 +66,21 @@ def channel_factory(test_session, test_directory):
def download_channel(test_session, test_directory, video_download_manager) -> Channel:
"""Get a test Channel that has a download frequency."""
# Add a frequency to the test channel, then give it a download.
channel = Channel(
directory=test_directory,
name='Download Channel',
url='https://example.com/channel1',
download_frequency=DownloadFrequency.weekly,
)
download = Download(url=channel.url, downloader='video_channel', frequency=channel.download_frequency,
sub_downloader='video')
test_session.add_all([channel, download])
channel = Channel(directory=test_directory, name='Download Channel', url='https://example.com/channel1',
source_id='channel1')
test_session.add(channel)
test_session.flush([channel, ])
assert channel and channel.id and channel.url
cd = channel.get_or_create_download(channel.url, test_session)
assert cd.download_url == channel.url
cd.download.frequency = DownloadFrequency.weekly
test_session.commit()
return channel
@pytest.fixture
def simple_video(test_session, test_directory, simple_channel, video_file) -> Video:
"""A Video with an empty video file whose channel is the Simple Channel."""
"""A Video with a video file, the channel is `simple_channel`."""
video_path = test_directory / 'simple_video.mp4'
video_file.rename(video_path)
video = Video.from_paths(test_session, video_path)
@ -180,6 +184,12 @@ def test_downloader_config(test_directory):
@pytest.fixture
def mock_video_extract_info():
with mock.patch('modules.videos.downloader.extract_info') as mock_extract_info:
# Add some simple data so the function can be called.
mock_extract_info.return_value = dict(
entries=[],
uploader='mock_video_extract_info',
id='mock_video_extract_info',
)
yield mock_extract_info

View file

@ -1,7 +1,6 @@
#! /usr/bin/env python3
import json
import pathlib
import re
import traceback
from abc import ABC
from typing import Tuple, List, Dict
@ -23,7 +22,8 @@ from wrolpi.files.lib import glob_shared_stem
from wrolpi.files.models import FileGroup
from wrolpi.vars import PYTEST, YTDLP_CACHE_DIR
from .channel.lib import create_channel, get_channel
from .common import get_no_channel_directory, get_videos_directory, update_view_counts_and_censored, ffmpeg_video_complete
from .common import get_no_channel_directory, get_videos_directory, update_view_counts_and_censored, \
ffmpeg_video_complete
from .errors import UnknownChannel
from .lib import get_downloader_config, YDL, ydl_logger
from .models import Video, Channel
@ -54,6 +54,9 @@ PREFERRED_POSTER_FORMAT = 'jpg'
def extract_info(url: str, ydl: YoutubeDL = YDL, process=False) -> dict:
"""Get info about a video. Separated for testing."""
if PYTEST:
raise RuntimeError(f'Refusing to download {url} during testing! {ydl}')
return ydl.extract_info(url, download=False, process=process)
@ -111,6 +114,10 @@ class ChannelDownloader(Downloader, ABC):
destination = download.settings.get('destination') if download.settings else None
if destination:
settings['destination'] = destination
# A Download may have applied tags, send any to the VideoDownloader.
tag_names = download.settings.get('tag_names') if download.settings else None
if tag_names:
settings['tag_names'] = tag_names
is_a_playlist = self.is_a_playlist(info)
try:
@ -119,7 +126,7 @@ class ChannelDownloader(Downloader, ABC):
else:
logger.debug('Not updating channel because this is a playlist')
downloads = self.get_missing_videos(download, channel)
downloads = self.get_missing_videos(download)
return DownloadResult(
success=True,
location=location,
@ -155,15 +162,40 @@ class ChannelDownloader(Downloader, ABC):
session.refresh(channel)
@staticmethod
def get_missing_videos(download: Download, channel: Channel) -> List[str]:
def get_missing_videos(download: Download) -> List[str]:
"""
Return all URLs of Videos in the `info_json` which need to be downloaded.
"""
downloads = download.info_json['entries']
if channel.match_regex:
# Only download Videos that have matching titles.
match_regex = re.compile(channel.match_regex)
downloads = [i for i in downloads if (title := i.get('title')) and match_regex.match(title)]
total_downloads = len(downloads)
title_match = download.settings.get('title_match') if download.settings else None
if title_match:
# Only download Videos that have title match words in title.
title_match = [i.strip() for i in title_match.split(',')]
new_downloads = []
for i in downloads:
if (title := i.get('title', '')) and any(j for j in title_match if j in title):
logger.debug(f'Video with title {title} matches {title_match}')
new_downloads.append(i)
downloads = new_downloads
title_exclude = download.settings.get('title_exclude') if download.settings else None
if title_exclude:
# Do not download any videos that contain the exclude words.
title_exclude = [i.strip() for i in title_exclude.split(',')]
new_downloads = list()
for i in downloads:
if (title := i.get('title', '')) and any(j for j in title_exclude if j in title):
logger.debug(f'Video with title {title} matches EXCLUDE {title_exclude}')
continue
else:
new_downloads.append(i)
downloads = new_downloads
filtered_entries = len(downloads)
if filtered_entries != total_downloads:
logger.info(f'Downloaded channel. Total downloaded reduced to {filtered_entries} from {total_downloads}')
# Prefer `webpage_url` before `url` for all entries.
downloads = [i.get('webpage_url') or i.get('url') for i in downloads]
@ -296,7 +328,7 @@ class VideoDownloader(Downloader, ABC):
try:
video_path, entry = self.prepare_filename(url, out_dir)
if settings.get('do_not_download'):
if settings.get('download_metadata_only'):
# User has requested refresh of video metadata, skip the rest of the video downloader.
return await self.download_info_json(download, video_path)
@ -349,6 +381,10 @@ class VideoDownloader(Downloader, ABC):
if not video_path.is_file():
error = f'{stdout}\n\n\n{stderr}\n\n' \
f'Video file could not be found! {video_path}'
if '!is_live' in stdout:
error = f'{stdout}\n\nVideo was live and did not finish downloading.'
if ' live event ' in stdout:
error = f'{stdout}\n\nVideo will be live and did not finish downloading.'
return DownloadResult(
success=False,
error=error,

View file

@ -15,12 +15,13 @@ from wrolpi.captions import extract_captions
from wrolpi.common import ConfigFile, get_media_directory, register_refresh_cleanup, limit_concurrent
from wrolpi.dates import Seconds, from_timestamp
from wrolpi.db import get_db_curs, get_db_session, optional_session
from wrolpi.downloader import Download
from wrolpi.errors import UnknownDirectory
from wrolpi.vars import PYTEST, YTDLP_CACHE_DIR
from .common import is_valid_poster, convert_image, \
generate_video_poster, logger, REQUIRED_OPTIONS, ConfigError, \
get_video_duration
from .models import Channel, Video
from .models import Channel, Video, ChannelDownload
logger = logger.getChild(__name__)
@ -358,6 +359,20 @@ def get_channels_config_from_db(session: Session) -> dict:
@optional_session()
def save_channels_config(session: Session = None):
"""Get the Channel information from the DB, save it to the config."""
# Create any missing ChannelDownload for any Channel.url that has a Download.
results = session.query(Channel, Download, ChannelDownload) \
.outerjoin(ChannelDownload, ChannelDownload.download_url == Download.url) \
.outerjoin(Channel, Channel.url == Download.url) \
.all()
need_commit = False
for channel, download, cd in results:
if channel and download and not cd:
# Channel.url matches Download.url but there is no ChannelDownload.
channel.get_or_create_download(download.url, session)
need_commit = True
if need_commit:
session.commit()
config = get_channels_config_from_db(session)
channels_config = get_channels_config()
@ -439,7 +454,6 @@ def import_channels_config():
f' url={channel.url}'
f' source_id={channel.source_id}'
f' directory={channel.directory}'
f' download_frequency={channel.download_frequency}'
)
with get_db_session(commit=True) as session:
@ -488,8 +502,9 @@ async def get_statistics():
COALESCE(MAX(fg.size), 0) AS "max_size",
-- Videos may or may not have comments.
COUNT(v.id) FILTER ( WHERE v.have_comments = TRUE ) AS "have_comments",
COUNT(v.id) FILTER ( WHERE v.have_comments = FALSE ) AS "no_comments",
COUNT(v.id) FILTER ( WHERE v.comments_failed = TRUE ) AS "failed_comments"
COUNT(v.id) FILTER ( WHERE v.have_comments = FALSE AND v.comments_failed = FALSE
and fg.censored = false and fg.url is not null) AS "missing_comments",
COUNT(v.id) FILTER ( WHERE v.comments_failed = TRUE ) AS "failed_comments"
FROM
video v
LEFT JOIN file_group fg on v.file_group_id = fg.id

View file

@ -11,7 +11,7 @@ from modules.videos.errors import UnknownVideo, UnknownChannel
from wrolpi.captions import read_captions
from wrolpi.common import Base, ModelHelper, logger, get_media_directory, background_task, replace_file
from wrolpi.db import get_db_curs, get_db_session, optional_session
from wrolpi.downloader import Download, download_manager
from wrolpi.downloader import Download, download_manager, DownloadFrequency
from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix
from wrolpi.files.models import FileGroup
from wrolpi.media_path import MediaPathType
@ -20,7 +20,7 @@ from wrolpi.vars import PYTEST
logger = logger.getChild(__name__)
__all__ = ['Video', 'Channel']
__all__ = ['Video', 'Channel', 'ChannelDownload']
class Video(ModelHelper, Base):
@ -75,7 +75,9 @@ class Video(ModelHelper, Base):
codec_names=codec_names,
codec_types=codec_types,
comments=comments,
comments_failed=self.comments_failed,
description=self.file_group.c_text or self.get_video_description(),
have_comments=self.have_comments,
id=self.id,
info_json_file=self.info_json_file,
info_json_path=self.info_json_path,
@ -494,31 +496,58 @@ class Video(ModelHelper, Base):
self.file_group.append_files(info_json_path)
class ChannelDownload(Base):
"""One-to-many join table between Channel and Download. Expects to link using Download.url."""
__tablename__ = 'channel_download'
channel_id = Column(Integer, ForeignKey('channel.id'), primary_key=True)
channel = relationship('Channel', primaryjoin='ChannelDownload.channel_id==Channel.id',
back_populates='channel_downloads')
download_url = Column(String, ForeignKey('download.url'), primary_key=True)
download = relationship('Download', primaryjoin='ChannelDownload.download_url==Download.url')
def __repr__(self):
return f'<ChannelDownload url={self.download_url} channel_id={self.channel_id}>'
def __json__(self) -> dict:
d = self.download.__json__()
d['channel_id'] = self.channel_id
return d
@staticmethod
def get_by_id(id: int, session: Session) -> Optional['ChannelDownload']:
return session.query(ChannelDownload).filter(ChannelDownload.channel_id == id).one_or_none()
@staticmethod
def get_by_url(url: str, session: Session) -> Optional['ChannelDownload']:
return session.query(ChannelDownload).filter(ChannelDownload.download_url == url).one_or_none()
def delete(self):
session = Session.object_session(self)
if self.download:
self.download.delete(skip=False)
session.delete(self)
class Channel(ModelHelper, Base):
__tablename__ = 'channel'
id = Column(Integer, primary_key=True)
name = Column(String)
url = Column(String, unique=True)
match_regex = Column(String)
url = Column(String, unique=True) # will only be downloaded if ChannelDownload exists.
directory: pathlib.Path = Column(MediaPathType)
generate_posters = Column(Boolean, default=False) # generating posters may delete files, and can be slow.
calculate_duration = Column(Boolean, default=True)
download_frequency = Column(Integer)
source_id = Column(String)
refreshed = Column(Boolean, default=False)
calculate_duration = Column(Boolean, default=True) # use ffmpeg to extract duration (slower than info json).
source_id = Column(String) # the ID from the source website.
refreshed = Column(Boolean, default=False) # The files in the Channel have been refreshed.
info_json = deferred(Column(JSON))
info_date = Column(Date)
videos: InstrumentedList = relationship('Video', primaryjoin='Channel.id==Video.channel_id')
channel_downloads: InstrumentedList = \
relationship('ChannelDownload', primaryjoin='ChannelDownload.channel_id==Channel.id')
def __repr__(self):
return f'<Channel id={self.id} name={repr(self.name)} directory={self.directory}>'
def __eq__(self, other):
if isinstance(other, Channel):
return self.id == other.id
return False
return f'<Channel id={self.id} name={repr(self.name)} url={self.url} directory={self.directory}>'
def delete_with_videos(self):
"""Delete all Video records (but not video files) related to this Channel. Then delete the Channel."""
@ -529,22 +558,27 @@ class Channel(ModelHelper, Base):
for video in videos:
video.channel = None
if self.url and (download := self.get_download()):
session.delete(download)
for cd in self.channel_downloads:
cd: ChannelDownload
cd.delete()
# Must commit before final deletion.
# TODO why?
session.commit()
session.delete(self)
def update(self, data: dict):
"""
Update the attributes of this Channel. Will also update the Channel's Download, if it has one.
"""
# Get the download before we change the URL.
download = self.get_download()
data = data.copy()
# URL should not be empty string.
if 'url' in data:
data['url'] = data['url'] or None
channel_downloads = data.pop('channel_downloads', [])
for key, value in data.items():
setattr(self, key, value)
@ -554,25 +588,18 @@ class Channel(ModelHelper, Base):
elif isinstance(self.directory, str) and not pathlib.Path(self.directory).is_absolute():
self.directory = get_media_directory() / self.directory
# All channels with a URL and download_frequency should have a download.
session: Session = Session.object_session(self)
if download and not self.download_frequency:
download_manager.delete_download(download.id, session)
elif download and self.download_frequency:
download.frequency = self.download_frequency
download.url = self.url
# Keep next_download if available.
download.next_download = download.next_download or download_manager.calculate_next_download(download,
session)
download.sub_downloader = 'video'
elif not download and self.download_frequency and self.url:
download = Download(frequency=self.download_frequency, url=self.url,
downloader='video_channel',
sub_downloader='video',
)
session.add(download)
session.flush()
download.next_download = download_manager.calculate_next_download(download, session)
for cd in channel_downloads:
# `cd` may be string from config file.
url = cd['url'] if isinstance(cd, dict) else cd
cd_ = ChannelDownload.get_by_url(url, session=session)
if not cd_:
cd_ = self.get_or_create_download(url, session=session)
# If `cd` is dict, use that frequency. Try to keep the currently set frequency, finally 30 days.
frequency = cd['frequency'] if isinstance(cd, dict) else cd_.download.frequency or DownloadFrequency.days30
cd_.download.frequency = frequency
session.flush()
def config_view(self) -> dict:
@ -582,12 +609,11 @@ class Channel(ModelHelper, Base):
config = dict(
calculate_duration=self.calculate_duration,
directory=str(self.directory),
download_frequency=self.download_frequency,
generate_posters=self.generate_posters,
match_regex=self.match_regex or '',
name=self.name,
source_id=self.source_id,
url=self.url or None,
channel_downloads=[i.download_url for i in self.channel_downloads]
)
return config
@ -597,31 +623,23 @@ class Channel(ModelHelper, Base):
raise FileNotFoundError(f'{path} does not exist!')
return path
def get_download(self) -> Optional[Download]:
"""
Get the Download row for this Channel. If there isn't a Download, return None.
"""
if not self.url:
return None
session: Session = Session.object_session(self)
download = download_manager.get_download(session, url=self.url)
return download
def __json__(self):
def __json__(self) -> dict:
d = dict(
channel_downloads=self.channel_downloads,
directory=self.directory,
id=self.id,
name=self.name,
directory=self.directory,
url=self.url,
)
return d
def dict(self, with_statistics: bool = False):
def dict(self, with_statistics: bool = False, with_downloads: bool = True) -> dict:
d = super(Channel, self).dict()
d['directory'] = self.directory.relative_to(get_media_directory()) if self.directory else None
if with_statistics:
d['statistics'] = self.get_statistics()
if with_downloads:
d['channel_downloads'] = self.channel_downloads
return d
def get_statistics(self):
@ -649,7 +667,7 @@ class Channel(ModelHelper, Base):
async def refresh_files(self, send_events: bool = True):
"""Refresh all files within this Channel's directory. Mark this channel as refreshed."""
logger.debug('Channel.refresh_files refresh_files')
logger.debug(f'{self}.refresh_files')
# Get this Channel's ID for later. Refresh may take a long time.
self_id = self.id
@ -698,3 +716,41 @@ class Channel(ModelHelper, Base):
return matching_entries[0]
elif len(matching_entries) > 1:
raise RuntimeError(f'More than one info_json entry matches {video_source_id}')
def get_download(self, url: str = None, download_id: int = None) -> Optional[ChannelDownload]:
"""Attempt to get the ChannelDownload that matches the provided parameters."""
if not url and not download_id:
raise RuntimeError('Must provide either url or download_id')
for cd in self.channel_downloads:
if download_id and cd.download.id == download_id:
return cd
if url and cd.download.url == url:
return cd
@optional_session
def get_or_create_download(self, url: str, session: Session = None, reset_attempts: bool = False) \
-> ChannelDownload:
"""Get a ChannelDownload record, if it does not exist, create it."""
from modules.videos.downloader import ChannelDownloader, VideoDownloader
if not url:
raise RuntimeError(f'Cannot get ChannelDownload without url')
cd = ChannelDownload.get_by_url(url, session)
if not cd:
# A Channel is downloaded using the ChannelDownloader first. Then, any missing videos are passed to
# VideoDownloader.
download = session.query(Download).filter_by(url=url).one_or_none()
if not download:
download_manager.create_download(url, ChannelDownloader.name, session=session,
sub_downloader_name=VideoDownloader.name,
reset_attempts=reset_attempts,
)
cd = ChannelDownload.get_by_url(url, session)
if not cd:
cd = ChannelDownload(channel_id=self.id, download_url=url)
session.add(cd)
logger.debug(f'Created {cd} for {self}')
return cd

View file

@ -2,6 +2,7 @@ from dataclasses import dataclass, field
from typing import List, Optional
from modules.videos.video.lib import DEFAULT_VIDEO_ORDER, VIDEO_QUERY_LIMIT
from wrolpi.errors import ValidationError
@dataclass
@ -9,9 +10,7 @@ class ChannelPostRequest:
name: str
directory: str
calculate_duration: Optional[bool] = None
download_frequency: Optional[int] = None
generate_posters: Optional[bool] = None
match_regex: Optional[str] = None
mkdir: Optional[bool] = None
url: Optional[str] = None
source_id: Optional[str] = None
@ -27,9 +26,7 @@ class ChannelPostRequest:
class ChannelPutRequest:
calculate_duration: Optional[bool] = None
directory: Optional[str] = None
download_frequency: Optional[int] = None
generate_posters: Optional[bool] = None
match_regex: Optional[str] = None
mkdir: Optional[bool] = None
name: Optional[str] = None
url: Optional[str] = None
@ -38,7 +35,22 @@ class ChannelPutRequest:
self.name = self.name.strip() or None
self.directory = self.directory.strip() or None
self.url = self.url.strip() if self.url else None
self.match_regex = None if self.match_regex in ('None', '') else self.match_regex
@dataclass
class ChannelDownloadRequest:
url: str
frequency: int
settings: dict = field(default_factory=dict)
def __post_init__(self):
self.url = self.url.strip()
if not self.url:
raise ValidationError('url cannot be empty')
# Validate settings contents. Remove empty values.
from wrolpi.schema import DownloadSettings
self.settings = {k: v for k, v in DownloadSettings(**self.settings).__dict__.items() if v not in ([], None)}
@dataclass
@ -51,7 +63,6 @@ class ChannelModel:
id: int
url: str
name: str
match_regex: str
directory: str
@ -171,6 +182,9 @@ class VideoStatistics:
sum_duration: int
sum_size: int
max_size: int
have_comments: int
missing_comments: int
failed_comments: int
@dataclass

View file

@ -7,7 +7,7 @@ import pytest
from modules.videos.models import Video, Channel
from modules.videos.video import lib as video_lib
from wrolpi.db import get_db_curs
from wrolpi.downloader import DownloadFrequency, Download
from wrolpi.downloader import Download
from wrolpi.files.lib import refresh_files
from wrolpi.files.models import FileGroup
@ -145,22 +145,10 @@ def test_channels_with_videos(test_session, test_client, test_directory, channel
assert vid3.channel is None
def test_api_download_channel(test_session, test_client, simple_channel):
"""A Channel download (a catalog update) can be triggered via the API."""
assert test_session.query(Download).count() == 0
# Add a download frequency to the channel, this should also create a download.
simple_channel.update(dict(download_frequency=DownloadFrequency.daily))
test_session.commit()
request, response = test_client.post(f'/api/videos/channels/download/{simple_channel.id}')
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
assert test_session.query(Download).count() == 1
def test_api_download(test_session, test_client, test_directory):
"""A video can be downloaded."""
content = {'urls': ['https://example.com/video1', ], 'downloader': 'video', 'destination': 'dest',
'excluded_urls': 'example.com'}
content = dict(urls=['https://example.com/video1', ], downloader='video',
settings=dict(excluded_urls='example.com', destination='dest'))
request, response = test_client.post('/api/download', content=json.dumps(content))
assert response.status_code == HTTPStatus.NO_CONTENT
@ -169,7 +157,7 @@ def test_api_download(test_session, test_client, test_directory):
assert download.downloader == 'video'
assert download.settings['excluded_urls'] == ['example.com']
assert download.settings['destination'] == str(test_directory / 'dest')
assert download.settings['tag_names'] == []
assert not download.settings.get('tag_names')
def test_api_download_video_tags(test_session, test_client, tag_factory):
@ -177,7 +165,8 @@ def test_api_download_video_tags(test_session, test_client, tag_factory):
tag1 = tag_factory()
tag2 = tag_factory()
content = {'urls': ['https://example.com/video1', ], 'downloader': 'video', 'tag_names': [tag1.name, tag2.name]}
content = dict(urls=['https://example.com/video1', ], downloader='video',
settings={'tag_names': [tag1.name, tag2.name]})
request, response = test_client.post('/api/download', content=json.dumps(content))
assert response.status_code == HTTPStatus.NO_CONTENT

View file

@ -6,13 +6,14 @@ from unittest import mock
import pytest
from PIL import Image
from modules.videos.models import Channel, Video
from modules.videos.models import Channel, Video, ChannelDownload
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.vars import PROJECT_DIR
from .. import common
from ..common import convert_image, update_view_counts_and_censored, get_video_duration, generate_video_poster, is_valid_poster
from ..common import convert_image, update_view_counts_and_censored, get_video_duration, generate_video_poster, \
is_valid_poster
from ..lib import save_channels_config, get_channels_config, import_channels_config, ChannelsConfig
@ -134,15 +135,10 @@ def test_generate_video_poster(video_file):
def test_import_channel_downloads(test_async_client, test_session, channel_factory, test_channels_config):
"""Importing the Channels' config should create any missing download records"""
channel1 = channel_factory(source_id='foo')
channel2 = channel_factory(source_id='bar')
# channel2 has no url, but has a frequency. Import should not create a download record.
channel2.url = None
channel2.download_frequency = DownloadFrequency.biweekly
test_session.commit()
assert channel1.download_frequency is None
channel1 = channel_factory(source_id='foo', url='https://example.com/channel1')
channel2 = channel_factory(source_id='bar', url='https://example.com/channel2')
assert len(test_session.query(Channel).all()) == 2
assert test_session.query(Download).all() == []
test_session.commit()
def update_channel_config(conf: ChannelsConfig, source_id, d):
# Creat a copy of the old config, replace the data of the provided Channel.
@ -156,38 +152,68 @@ def test_import_channel_downloads(test_async_client, test_session, channel_facto
# Config has no channels with a download_frequency.
save_channels_config()
import_channels_config()
assert channel1.download_frequency is None
assert not channel1.channel_downloads
assert len(test_session.query(Channel).all()) == 2
assert test_session.query(Download).all() == []
# Add a frequency to the Channel.
channels_config = get_channels_config()
update_channel_config(channels_config, 'foo', {'download_frequency': DownloadFrequency.biweekly})
update_channel_config(channels_config, 'foo',
{'channel_downloads': [
{'url': 'https://example.com/channel1', 'frequency': DownloadFrequency.weekly}
]})
# Download record is created on import.
import_channels_config()
assert channel1.download_frequency is not None
assert channel1.channel_downloads
assert len(test_session.query(Channel).all()) == 2
download: Download = test_session.query(Download).one()
assert download.url == channel1.url
assert download.frequency == channel1.download_frequency
# Download frequency is adjusted when config file changes.
update_channel_config(channels_config,
'foo', {'download_frequency': DownloadFrequency.weekly})
import_channels_config()
assert len(test_session.query(Channel).all()) == 2
assert download.url == channel1.url
assert download.frequency == channel1.download_frequency
assert download.downloader == 'video_channel'
assert download.next_download
assert not download.error
assert download.frequency
next_download = str(download.next_download)
import_channels_config()
download: Download = test_session.query(Download).one()
assert next_download == str(download.next_download)
# Creating Download that matches Channel2's URL creates a ChannelDownload on save.
download = Download(url=channel2.url, frequency=DownloadFrequency.weekly)
test_session.add(download)
test_session.commit()
save_channels_config()
channel2: Channel = test_session.query(Channel).filter_by(id=channel2.id).one()
cds = test_session.query(ChannelDownload).all()
assert len(cds) == 2, cds
assert channel2.channel_downloads and len(channel2.channel_downloads) == 1
assert channel1.channel_downloads and len(channel1.channel_downloads) == 1
# Add a Download to Channel2 which does not match Channel.url.
channel2.get_or_create_download('https://example.org')
test_session.commit()
save_channels_config()
# Check config is written to match new URLs.
config = get_channels_config()
assert len(config.channels) == 2
for channel_config in config.channels:
if channel_config['source_id'] == channel2.source_id:
assert channel_config['source_id'] == 'bar'
assert len(channel_config['channel_downloads']) == 2
assert set(channel_config['channel_downloads']) == {'https://example.com/channel2', 'https://example.org'}
else:
assert channel_config['source_id'] == 'foo'
# Reset Downloads. Downloads and ChannelDownloads should be recreated.
[i.delete(skip=False) for i in test_session.query(Download).all()]
[i.delete() for i in test_session.query(ChannelDownload).all()]
import_channels_config()
channel1, channel2 = test_session.query(Channel).order_by(Channel.url).all()
assert channel1.url == 'https://example.com/channel1'
assert channel2.url == 'https://example.com/channel2'
assert {i.download.url for i in channel1.channel_downloads} == {'https://example.com/channel1'}
assert {i.download.url for i in channel2.channel_downloads} == {'https://example.com/channel2',
'https://example.org'}
def test_import_channel_delete_missing_channels(test_session, channel_factory, test_channels_config):
"""The Channel import function deletes any Channels that are not in the config."""
@ -255,7 +281,7 @@ def test_check_for_video_corruption(video_file, test_directory):
@pytest.mark.asyncio
async def test_ffprobe_json(video_file, corrupted_video_file):
async def test_ffprobe_json(test_async_client, video_file, corrupted_video_file):
content = await common.ffprobe_json(video_file)
assert not content['chapters']
assert content['format']['duration'] == '5.312000'

View file

@ -5,13 +5,11 @@ from unittest import mock
import pytest
from modules.videos.channel.lib import download_channel
from modules.videos.downloader import VideoDownloader, \
get_or_create_channel, channel_downloader, video_downloader
from modules.videos.models import Channel, Video
from modules.videos.models import Channel, Video, ChannelDownload
from wrolpi.downloader import Download, DownloadResult
from wrolpi.errors import InvalidDownload
from wrolpi.test.common import skip_circleci
from wrolpi.vars import PROJECT_DIR
example_video_json = {
@ -124,7 +122,6 @@ async def test_download_video_tags(test_session, video_download_manager, video_f
assert [i.tag.name for i in video.file_group.tag_files] == [tag1.name, tag2.name]
@skip_circleci
@pytest.mark.asyncio
async def test_download_channel(test_session, simple_channel, video_download_manager, video_file,
mock_video_extract_info, mock_video_prepare_filename,
@ -134,18 +131,20 @@ async def test_download_channel(test_session, simple_channel, video_download_man
If a Channel has `match_regex` only those videos with matching titles will be downloaded."""
url = 'https://www.youtube.com/c/LearningSelfReliance/videos'
channel_downloader, video_downloader = video_download_manager.instances
mock_video_prepare_filename.return_value = video_file
mock_video_extract_info.return_value = example_channel_json
with mock.patch('modules.videos.downloader.get_channel') as mock_get_channel:
mock_get_channel.return_value = simple_channel
video_download_manager.create_download(url, channel_downloader.name, sub_downloader_name=video_downloader.name)
simple_channel.get_or_create_download(url, test_session)
# Download channel.
await video_download_manager.wait_for_all_downloads()
# Download videos.
await video_download_manager.wait_for_all_downloads()
def reset_downloads():
[i.delete() for i in test_session.query(ChannelDownload)]
[i.delete(skip=False) for i in test_session.query(Download)]
# Let background tasks run.
await asyncio.sleep(0)
@ -156,17 +155,35 @@ async def test_download_channel(test_session, simple_channel, video_download_man
{'https://youtube.com/watch?v=video_2_url', 'https://youtube.com/watch?v=video_1_url'}
assert all(i.status_code == 'complete' for i in downloads)
# A channel with `match_regex` only returns matching video URLs.
simple_channel.match_regex = '.*(2).*'
test_session.query(Download).delete()
reset_downloads()
# A channel with `title_match` only returns matching video URLs.
test_session.commit()
with mock.patch('modules.videos.downloader.get_channel') as mock_get_channel:
mock_get_channel.return_value = simple_channel
video_download_manager.recurring_download(url, 100, channel_downloader.name,
sub_downloader_name=video_downloader.name)
cd = simple_channel.get_or_create_download(url, test_session)
cd.download.frequency = 100
cd.download.settings = {'title_match': '2'}
await video_download_manager.wait_for_all_downloads()
downloads = video_download_manager.get_once_downloads(test_session)
assert [i.url for i in downloads] == ['https://youtube.com/watch?v=video_2_url']
assert {i.url for i in downloads} == {'https://youtube.com/watch?v=video_2_url'}
assert downloads[0].settings == {
'channel_id': 1,
'channel_url': 'https://www.youtube.com/c/LearningSelfReliance/videos',
}
reset_downloads()
# A channel with `title_exclude` only returns non-matching video URLs.
test_session.commit()
with mock.patch('modules.videos.downloader.get_channel') as mock_get_channel:
mock_get_channel.return_value = simple_channel
cd = simple_channel.get_or_create_download(url, test_session)
cd.download.frequency = 100
cd.download.settings = {'title_exclude': '2'}
await video_download_manager.wait_for_all_downloads()
downloads = video_download_manager.get_once_downloads(test_session)
assert {i.url for i in downloads} == {'https://youtube.com/watch?v=video_1_url'}
assert downloads[0].settings == {
'channel_id': 1,
'channel_url': 'https://www.youtube.com/c/LearningSelfReliance/videos',
@ -227,19 +244,8 @@ def test_bad_downloader(test_session, video_download_manager):
@pytest.mark.asyncio
async def test_channel_download_no_frequency(test_session, video_download_manager, simple_channel):
"""
A Channel without a download frequency creates a once-download.
"""
# simple_channel has no download record.
assert video_download_manager.get_downloads(test_session) == []
download_channel(simple_channel.id)
@pytest.mark.asyncio
async def test_video_download(test_session, test_directory, simple_channel, video_download_manager,
mock_video_process_runner, image_file):
async def test_video_download(test_session, test_directory, mock_video_extract_info, simple_channel,
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']
simple_channel.directory = test_directory / 'videos/channel name'
@ -252,9 +258,8 @@ async def test_video_download(test_session, test_directory, simple_channel, vide
image_file.rename(poster_path)
url = 'https://www.youtube.com/watch?v=31jPEBiAC3c'
with mock.patch('modules.videos.downloader.YDL.extract_info') as mock_extract_info, \
mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
mock_extract_info.return_value = example_video_json
with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
mock_video_extract_info.return_value = example_video_json
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
video_download_manager.create_download(url, video_downloader.name)

View file

@ -0,0 +1,40 @@
import pytest
from modules.videos.downloader import ChannelDownloader
from modules.videos.models import ChannelDownload
from wrolpi.downloader import Download, RSSDownloader
from wrolpi.migration import migrate_channel_downloads
@pytest.mark.asyncio
def test_channel_channel_downloads_migration(test_async_client, test_session, channel_factory, test_download_manager):
"""Test the 8d0d81bc9c34_channel_channel_downloads.py migration."""
# A simple Channel which has a download for its URL.
channel1 = channel_factory(url='https://example.com/channel1')
# A Channel which has two Downloads. One for it's URL, another which is an RSS feed in its directory.
channel2 = channel_factory(url='https://example.com/channel2')
download1 = Download(url=channel1.url, downloader=ChannelDownloader.name)
download2a = Download(url='https://example.com/channel2/rss', downloader=RSSDownloader.name,
settings=dict(destination=str(channel2.directory)))
download2b = Download(url='https://example.com/channel2', downloader=ChannelDownloader.name,
settings=dict(destination=str(channel2.directory)))
# A Channel which has a URL, but no Downloads.
channel3 = channel_factory()
test_session.add_all([download1, download2a, download2b])
test_session.commit()
assert not channel1.channel_downloads
assert channel2.directory and not channel2.channel_downloads
assert not channel3.channel_downloads
migrate_channel_downloads(test_session)
assert channel1.channel_downloads
assert channel2.channel_downloads
assert not channel3.channel_downloads
assert test_session.query(ChannelDownload).count() == 3
cd1, cd2a, cd2b = test_session.query(ChannelDownload).order_by(ChannelDownload.download_url).all()
assert cd1.download_url == channel1.url
assert cd2a.download_url == 'https://example.com/channel2'
assert cd2b.download_url == 'https://example.com/channel2/rss'

View file

@ -198,11 +198,11 @@ async def get_missing_videos_comments(limit: int = VIDEO_COMMENTS_FETCH_COUNT):
with get_db_session() as session:
videos = session.query(Video).filter(
# Have yet to get comments.
Video.have_comments == False,
Video.comments_failed == False,
# Need a URL to try to get comments.
Video.have_comments != True,
Video.comments_failed != True,
# Needs to be downloadable.
FileGroup.url != None, # noqa
FileGroup.censored != True, # noqa
FileGroup.censored != True,
# We want old videos (time for comments to accumulate), or those which we don't know the published date.
or_(
one_month_ago > FileGroup.published_datetime,
@ -225,8 +225,6 @@ async def get_missing_videos_comments(limit: int = VIDEO_COMMENTS_FETCH_COUNT):
logger.debug(f'add_video_to_skip_list: {video_url=} {censored=}')
for url in video_urls:
logger.info(f'Getting comments for: {url}')
# Sleep to catch cancel.
await asyncio.sleep(0)
@ -250,6 +248,8 @@ async def get_missing_videos_comments(limit: int = VIDEO_COMMENTS_FETCH_COUNT):
download_manager.add_to_skip_list(url)
continue
logger.info(f'Getting comments for: {url}')
try:
# Get info json about the video.
info = download_video_info_json(url)
@ -295,6 +295,7 @@ async def get_missing_videos_comments(limit: int = VIDEO_COMMENTS_FETCH_COUNT):
if video.video_path.is_file():
video.replace_info_json(info)
video.have_comments = True
video.comments_failed = False
else:
logger.error(f'Attempting to replace comments for non-existent video! {video}')
if len(videos) == 1:

View file

@ -173,13 +173,10 @@ async def test_wrol_mode(test_async_client, simple_channel, simple_video, wrol_m
assert resp.status_code == HTTPStatus.FORBIDDEN
assert resp.json['code'] == 'WROL_MODE_ENABLED'
# Can't refresh or download
# Can't refresh
_, resp = await test_async_client.post('/api/files/refresh')
assert resp.status_code == HTTPStatus.FORBIDDEN
assert resp.json['code'] == 'WROL_MODE_ENABLED'
_, resp = await test_async_client.post(f'/api/videos/channels/download/{simple_channel.id}')
assert resp.status_code == HTTPStatus.FORBIDDEN
assert resp.json['code'] == 'WROL_MODE_ENABLED'
# THE REST OF THESE METHODS ARE ALLOWED
content = dict(file_group_id=simple_video.file_group_id, tag_name=tag.name)

View file

@ -335,7 +335,7 @@ class ZimSubscription(Base):
download_id = self.download_id
return f'<ZimSubscription id={self.id} {name=} {language=} {download_id=}>'
def __json__(self):
def __json__(self) -> dict:
d = dict(
id=self.id,
name=self.name,

View file

@ -15,7 +15,6 @@ psycopg2-binary==2.9.6
pypdf==3.17.0
pytest-asyncio==0.21.0
pytest==7.3.1
python-dateutil==2.8.2
python-docx==1.1.0
python-dotenv==1.0.0
python-magic~=0.4.27

View file

@ -12,7 +12,7 @@ import re
from difflib import SequenceMatcher
from typing import List, Generator, Optional, Dict
from modules.videos import Video, Channel
from modules.videos.models import Video, Channel
from modules.videos.lib import parse_video_file_name
from wrolpi.common import get_relative_to_media_directory, chain
from wrolpi.db import get_db_curs, get_db_session

View file

@ -103,10 +103,7 @@ def json_error_handler(request: Request, exception: Exception):
if isinstance(exception, SanicException):
return json_response(body, exception.status_code)
if PYTEST:
logger.error('Unexpected error', exc_info=exception)
else:
logger.debug('Unexpected error', exc_info=exception)
logger.error('Unexpected error', exc_info=exception)
# Some unknown error, use internal error code.
return json_response(body, HTTPStatus.INTERNAL_SERVER_ERROR)

View file

@ -3,7 +3,6 @@ from datetime import datetime, timezone, timedelta
from enum import Enum
from typing import Union, List
import dateutil.parser
import pytz
from sqlalchemy import types
@ -46,25 +45,25 @@ def strftime(dt: datetime) -> str:
def strpdate(dt: str) -> datetime:
"""
Attempt to parse a datetime string. Tries to find a Timezone, if possible. DB requires timezone.
TODO replace this in Python 3.11 https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat
"""
try:
if dt.count('/') == 2:
# No timezone info.
try:
a, b, c = dt.split('/')
if len(c) == 4:
# Assume m/d/Y
return datetime.strptime(dt, '%m/%d/%Y')
if len(a) == 4:
# Y/m/d
return datetime.strptime(dt, '%Y/%m/%d')
if len(a) == 2 and len(b) == 2 and len(c) == 13:
# Assume d/m/Y HH:MM:SS
a, b, c = dt.split('/')
if len(c) == 4:
# Assume m/d/Y
return datetime.strptime(dt, '%m/%d/%Y')
if len(a) == 4:
# Y/m/d
return datetime.strptime(dt, '%Y/%m/%d')
if len(a) in (1, 2) and len(b) in (1, 2):
# Day/Month may or may not have 0 prefix.
if len(c) == 13:
# d/m/Y HH:MM:SS
return datetime.strptime(dt, '%m/%d/%Y %H:%M:%S')
except ValueError:
pass
elif len(c) == 15:
# d/m/Y HH:MM:SS PM
return datetime.strptime(dt, '%m/%d/%Y %H:%M:%S %p')
elif dt.count('-') == 2 and len(dt) <= 10:
# No timezone info.
a, b, c = dt.split('-')
@ -82,20 +81,13 @@ def strpdate(dt: str) -> datetime:
return datetime.strptime(dt2, "D:%Y%m%d%H%M%S")
if dt.count('-') == 0 and dt.count('/') == 0 and dt.isdigit() and len(dt) == 8:
# Assume %Y%m%d date
return datetime.strptime(dt, '%Y%m%d')
if dt.count('.') == 2 and len(dt) <= 9:
# yyyy.mm.dd or dd.mm.yyyy
try:
a, b, c = dt.split('.')
if len(a) == 4:
return datetime.strptime(dt, '%Y.%m.%d')
if len(c) == 4:
return datetime.strptime(dt, '%d.%m.%Y')
except ValueError:
pass
a, b, c = dt.split('.')
if len(a) == 4:
return datetime.strptime(dt, '%Y.%m.%d')
if len(c) == 4:
return datetime.strptime(dt, '%d.%m.%Y')
try:
# Fri Jun 17 2022 19:24:52 (from Singlefile)
@ -121,7 +113,7 @@ def strpdate(dt: str) -> datetime:
pass
# Last, try third-party module to parse ISO 8601 datetime.
return dateutil.parser.isoparse(dt)
return datetime.fromisoformat(dt)
except Exception as e:
raise InvalidDatetime(f'Unable to parse datetime string: {dt}') from e

View file

@ -98,14 +98,14 @@ class Download(ModelHelper, Base): # noqa
"""Model that is used to schedule downloads."""
__tablename__ = 'download' # noqa
id = Column(Integer, primary_key=True)
url = Column(String, nullable=False)
url = Column(String, nullable=False, unique=True)
attempts = Column(Integer, default=0)
downloader = Column(Text) # 'videos', 'archive', 'kiwix_zim', etc.
sub_downloader = Column(Text) # The downloader any returned downloads should be sent.
error = Column(Text) # traceback from an error during downloading.
frequency = Column(Integer) # seconds between re-downloading.
info_json = Column(JSONB) # information retrieve WHILE downloading (from yt-dlp)
info_json = Column(JSONB) # information retrieved WHILE downloading (from yt-dlp)
last_successful_download = Column(TZDateTime)
location = Column(Text) # Relative App URL where the item is downloaded
next_download = Column(TZDateTime)
@ -124,7 +124,7 @@ class Download(ModelHelper, Base): # noqa
return f'<Download id={self.id} status={self.status} url={repr(self.url)} attempts={self.attempts} ' \
f'error={bool(self.error)}>'
def __json__(self):
def __json__(self) -> dict:
d = dict(
downloader=self.downloader,
frequency=self.frequency,
@ -208,14 +208,23 @@ class Download(ModelHelper, Base): # noqa
def add_to_skip_list(self):
download_manager.add_to_skip_list(self.url)
def delete(self):
def delete(self, skip: bool = True):
# Do not download this automatically again. This saves the config.
self.add_to_skip_list()
if skip:
self.add_to_skip_list()
session = Session.object_session(self)
# Delete ChannelDownload, if any exists.
from modules.videos.models import ChannelDownload
cds = session.query(ChannelDownload).filter(ChannelDownload.download == self).all()
for cd in cds:
session.delete(cd)
session.delete(self)
session.commit()
# Save download config again because this download is now removed from the download lists.
save_downloads_config(session=session)
api_app.add_task(save_downloads_config())
class Downloader:
@ -235,7 +244,7 @@ class Downloader:
download_manager.register_downloader(self)
def __json__(self):
def __json__(self) -> dict:
return dict(name=self.name, pretty_name=self.pretty_name)
def __repr__(self):
@ -464,7 +473,21 @@ class DownloadManager:
f'Refusing to download {url} because it is in the download_manager.yaml skip list')
download = Download(url=url, status='new')
session.add(download)
session.flush()
from modules.videos.models import Channel, ChannelDownload
channel: Channel = session.query(Channel).filter(Channel.url == url).one_or_none()
if channel:
# This Download needs to be associated with the Channel.
cd = ChannelDownload.get_by_url(url, session)
if not cd:
cd = ChannelDownload(channel=channel, download=download)
session.add(cd)
else:
cd.download = download
if cd not in channel.channel_downloads:
channel.channel_downloads.append(cd)
session.flush([cd, channel])
return download
@optional_session
@ -479,12 +502,14 @@ class DownloadManager:
# Throws an error if no downloader is found.
self.get_downloader_by_name(downloader_name)
skipped = list()
for url in urls:
if url in get_download_manager_config().skip_urls and reset_attempts:
# User manually entered this download, remove it from the skip list.
self.remove_from_skip_list(url)
elif url in get_download_manager_config().skip_urls:
self.log_warning(f'Skipping {url} because it is in the download_manager.yaml skip list.')
skipped.append(url)
continue
download = self.get_or_create_download(url, session, reset_attempts=reset_attempts)
@ -495,6 +520,11 @@ class DownloadManager:
download.settings = settings if settings is not None else download.settings
downloads.append(download)
download_urls = [i.url for i in downloads]
logger.debug(f'Creating downloads: {download_urls}')
if not downloads:
raise RuntimeError(f'Failed to create downloads because they were all in skip list: {skipped}')
try:
# Start downloading ASAP.
api_app.add_task(self.dispatch_downloads())
@ -716,6 +746,7 @@ class DownloadManager:
"""Delete a Download. Returns True if a Download was deleted, otherwise return False."""
download = self.get_download(session, id_=download_id)
if download:
# This saves the config twice.
download.delete()
return True
return False
@ -806,15 +837,19 @@ class DownloadManager:
stmt = f'''
SELECT
downloader,
error,
frequency,
id,
last_successful_download,
next_download,
status,
url,
location,
error
next_download,
settings,
status,
sub_downloader,
url,
cd.channel_id
FROM download
LEFT OUTER JOIN channel_download cd on download.url = cd.download_url
WHERE frequency IS NOT NULL
ORDER BY
{self._status_order},

View file

@ -53,7 +53,7 @@ class EBookData:
def __bool__(self):
return bool(self.cover) or bool(self.author) or bool(self.text) or bool(self.title)
def __json__(self):
def __json__(self) -> dict:
d = {}
if self.author:
d['author'] = self.author

View file

@ -1026,7 +1026,7 @@ class RefreshProgress:
total_file_groups: int = 0
unindexed: int = 0
def __json__(self):
def __json__(self) -> dict:
d = dict(
counted_files=self.counted_files,
counting=self.counting,

View file

@ -104,33 +104,34 @@ class FileGroup(ModelHelper, Base):
m = f'model={self.model}' if self.model else f'mimetype={self.mimetype}'
return f'<FileGroup id={self.id} {m} primary_path={repr(str(self.primary_path))}>'
def __json__(self):
def __json__(self) -> dict:
from wrolpi.files.lib import split_path_stem_and_suffix
_, suffix = split_path_stem_and_suffix(self.primary_path)
tags = sorted([i.tag.name for i in self.tag_files])
d = {
'author': self.author,
'data': self.data,
'directory': self.primary_path.parent,
'download_datetime': self.download_datetime,
'files': self.my_files(),
'id': self.id,
'key': self.primary_path,
'length': self.length,
'mimetype': self.mimetype,
'model': self.model,
'modified': self.modification_datetime or None,
'name': self.primary_path.name,
'primary_path': self.primary_path,
'published_datetime': self.published_datetime,
'published_modified_datetime': self.published_modified_datetime,
'size': self.size,
'suffix': suffix,
'tags': tags,
'title': self.title,
'url': self.url,
'viewed': self.viewed,
}
d = dict(
author=self.author,
censored=self.censored,
data=self.data,
directory=self.primary_path.parent,
download_datetime=self.download_datetime,
files=self.my_files(),
id=self.id,
key=self.primary_path,
length=self.length,
mimetype=self.mimetype,
model=self.model,
modified=self.modification_datetime or None,
name=self.primary_path.name,
primary_path=self.primary_path,
published_datetime=self.published_datetime,
published_modified_datetime=self.published_modified_datetime,
size=self.size,
suffix=suffix,
tags=tags,
title=self.title,
url=self.url,
viewed=self.viewed,
)
return d
@property
@ -360,7 +361,7 @@ class Directory(ModelHelper, Base):
name: str = Column(String, nullable=False)
idempotency = Column(TZDateTime, default=lambda: now())
def __json__(self):
def __json__(self) -> dict:
d = dict(
path=self.path,
name=self.name,

32
wrolpi/migration.py Normal file
View file

@ -0,0 +1,32 @@
from modules.videos.models import Channel, ChannelDownload
from wrolpi.downloader import Download
def migrate_channel_downloads(session):
channels_by_url = {i.url: i for i in session.query(Channel).all()}
downloads = session.query(Download).all()
need_commit = False
for download in downloads:
channel = channels_by_url.get(download.url)
if channel:
cd = session.query(ChannelDownload).filter_by(download_url=download.url).one_or_none()
if not cd:
cd = ChannelDownload(channel_id=channel.id, download_url=download.url)
session.add(cd)
need_commit = True
for download in downloads:
destination = download.settings.get('destination') if download.settings else None
if not destination:
continue
channel = session.query(Channel).filter_by(directory=destination).one_or_none()
if channel:
cd = session.query(ChannelDownload).filter_by(download_url=download.url).one_or_none()
if not cd:
cd = ChannelDownload(channel_id=channel.id, download_url=download.url)
session.add(cd)
need_commit = True
if need_commit:
session.commit()

View file

@ -253,25 +253,13 @@ async def post_download(_: Request, body: schema.DownloadRequest):
if not downloader:
raise InvalidDownload(f'Cannot find downloader with name {body.downloader}')
excluded_urls = [i.strip() for i in body.excluded_urls.split(',')] if body.excluded_urls else None
destination = str(get_media_directory() / body.destination) if body.destination else None
if body.suffix and not body.suffix.startswith('.'):
raise InvalidDownload(f'Suffix must start with a "."')
# Don't overwrite settings if restarting download.
settings = None
if excluded_urls or destination or body.tag_names or body.suffix or body.depth or body.do_not_download:
settings = dict(excluded_urls=excluded_urls, destination=destination, tag_names=body.tag_names,
suffix=body.suffix, do_not_download=body.do_not_download, depth=body.depth)
if body.frequency:
download_manager.recurring_download(body.urls[0], body.frequency, downloader_name=body.downloader,
sub_downloader_name=body.sub_downloader, reset_attempts=True,
settings=settings)
settings=body.settings)
else:
download_manager.create_downloads(body.urls, downloader_name=body.downloader, reset_attempts=True,
sub_downloader_name=body.sub_downloader, settings=settings)
sub_downloader_name=body.sub_downloader, settings=body.settings)
if download_manager.disabled.is_set() or download_manager.stopped.is_set():
# Downloads are disabled, warn the user.
Events.send_downloads_disabled('Download created. But, downloads are disabled.')
@ -279,6 +267,32 @@ async def post_download(_: Request, body: schema.DownloadRequest):
return response.empty()
@api_bp.put('/download/<download_id:int>')
@openapi.description('Update properties of the Download')
@validate(schema.DownloadRequest)
@wrol_mode_check
async def put_download(_: Request, download_id: int, body: schema.DownloadRequest):
downloader = download_manager.get_downloader_by_name(body.downloader)
if not downloader:
raise InvalidDownload(f'Cannot find downloader with name {body.downloader}')
download_manager.create_downloads(body.urls, downloader_name=body.downloader, reset_attempts=True,
sub_downloader_name=body.sub_downloader, settings=body.settings)
if download_manager.disabled.is_set() or download_manager.stopped.is_set():
# Downloads are disabled, warn the user.
Events.send_downloads_disabled('Download created. But, downloads are disabled.')
return response.empty()
@api_bp.delete('/download/<download_id:int>')
@openapi.description('Delete a download')
@wrol_mode_check
async def delete_download(_: Request, download_id: int):
deleted = download_manager.delete_download(download_id)
return response.empty(HTTPStatus.NO_CONTENT if deleted else HTTPStatus.NOT_FOUND)
@api_bp.post('/download/<download_id:int>/restart')
@openapi.description('Restart a download.')
async def restart_download(_: Request, download_id: int):
@ -343,14 +357,6 @@ async def delete_once(_: Request):
return response.empty()
@api_bp.delete('/download/<download_id:[0-9,]+>')
@openapi.description('Delete a download')
@wrol_mode_check
async def delete_download(_: Request, download_id: int):
deleted = download_manager.delete_download(download_id)
return response.empty(HTTPStatus.NO_CONTENT if deleted else HTTPStatus.NOT_FOUND)
@api_bp.get('/downloaders')
@openapi.description('List all Downloaders that can be specified by the user.')
async def get_downloaders(_: Request):

View file

@ -1,7 +1,7 @@
from dataclasses import dataclass, field
from typing import Optional, List
from wrolpi.errors import InvalidDownload
from wrolpi.errors import InvalidDownload, ValidationError
@dataclass
@ -54,19 +54,34 @@ class EchoResponse:
method: str
@dataclass
class DownloadSettings:
depth: Optional[int] = None
destination: Optional[str] = None
excluded_urls: Optional[str] = None
max_pages: Optional[int] = None
suffix: Optional[str] = None
tag_names: List[str] = field(default_factory=lambda: list())
title_exclude: str = None
title_include: str = None
def __post_init__(self):
from wrolpi.common import get_media_directory
self.tag_names = [i.strip() for i in self.tag_names] if self.tag_names else []
self.excluded_urls = [i.strip() for i in self.excluded_urls.split(',')] if self.excluded_urls else None
self.destination = str(get_media_directory() / self.destination) if self.destination else None
if self.suffix and not self.suffix.startswith('.'):
raise ValidationError('suffix must start with .')
@dataclass
class DownloadRequest:
urls: List[str]
downloader: str
frequency: Optional[int] = None
sub_downloader: Optional[str] = None
excluded_urls: Optional[str] = None
destination: Optional[str] = None
tag_names: List[str] = field(default_factory=lambda: list())
suffix: Optional[str] = None
depth: Optional[int] = None
max_pages: Optional[int] = None
do_not_download: Optional[bool] = False
settings: Optional[dict] = field(default_factory=lambda: dict())
download_metadata_only: Optional[bool] = False
def __post_init__(self):
urls = [j for i in self.urls if (j := i.strip())]
@ -75,6 +90,9 @@ class DownloadRequest:
# Get unique URLs, preserve order.
self.urls = list(dict.fromkeys(urls))
# Validate settings contents. Remove empty values.
self.settings = {k: v for k, v in DownloadSettings(**self.settings).__dict__.items() if v not in ([], None)}
@dataclass
class JSONErrorResponse:
@ -121,7 +139,7 @@ class VIN:
transmission: str = None
serial: str = None
def __json__(self):
def __json__(self) -> dict:
d = dict(
country=self.country,
manufacturer=self.manufacturer,

View file

@ -34,7 +34,7 @@ class SystemLoad:
minute_5: Decimal = 0
minute_15: Decimal = 0
def __json__(self):
def __json__(self) -> dict:
return dict(
minute_1=str(round(self.minute_1, 2)),
minute_5=str(round(self.minute_5, 2)),
@ -74,7 +74,7 @@ class CPUInfo:
high_temperature: Optional[int] = None
critical_temperature: Optional[int] = None
def __json__(self):
def __json__(self) -> dict:
return dict(
cores=self.cores,
cur_frequency=self.cur_frequency,
@ -187,7 +187,7 @@ class MemoryStats:
free: int = None
cached: int = None
def __json__(self):
def __json__(self) -> dict:
return dict(
total=self.total,
used=self.used,
@ -236,7 +236,7 @@ class DriveInfo:
size: int = 0
used: int = 0
def __json__(self):
def __json__(self) -> dict:
return dict(
mount=self.mount,
percent=self.percent,
@ -320,7 +320,7 @@ class NICBandwidthInfo:
name: str = None
speed: int = None
def __json__(self):
def __json__(self) -> dict:
return dict(
bytes_recv=self.bytes_recv,
bytes_sent=self.bytes_sent,
@ -358,7 +358,7 @@ class DiskBandwidthInfo:
maximum_read_ps: int = None
maximum_write_ps: int = None
def __json__(self):
def __json__(self) -> dict:
return dict(
bytes_read_ps=self.bytes_read_ps,
bytes_write_ps=self.bytes_write_ps,

View file

@ -42,7 +42,7 @@ class Tag(ModelHelper, Base):
color = self.color
return f'<Tag {name=} {color=}>'
def __json__(self):
def __json__(self) -> dict:
return dict(
id=self.id,
name=self.name,

View file

@ -2,7 +2,6 @@ from datetime import datetime, timedelta, timezone
import pytest
import pytz
from dateutil.tz import tzoffset
from sqlalchemy import Column, Integer
from wrolpi import dates
@ -100,8 +99,8 @@ def test_timedelta_to_timestamp(td, expected):
('2022/8/1', datetime(2022, 8, 1)),
('2022-8-1', datetime(2022, 8, 1)),
('2023-08-22T02:45:59+0000', datetime(2023, 8, 22, 2, 45, 59, tzinfo=pytz.UTC)),
('2023-08-29T15:29-0400', datetime(2023, 8, 29, 15, 29, tzinfo=tzoffset(None, -14400))),
('2023-08-29T15:29+0400', datetime(2023, 8, 29, 15, 29, tzinfo=tzoffset(None, 14400))),
('2023-08-29T15:29-0400', datetime(2023, 8, 29, 15, 29, tzinfo=timezone(timedelta(hours=-4)))),
('2023-08-29T15:29+0400', datetime(2023, 8, 29, 15, 29, tzinfo=timezone(timedelta(hours=4)))),
('2011-11-04', datetime(2011, 11, 4, 0, 0)),
('20111104', datetime(2011, 11, 4, 0, 0)),
('2011-11-04T00:05:23', datetime(2011, 11, 4, 0, 5, 23)),
@ -115,13 +114,14 @@ def test_timedelta_to_timestamp(td, expected):
('Tuesday, October 19, 1999 3:41:01 PM', datetime(1999, 10, 19, 15, 41, 1)),
('Tue, October 19, 1999 3:41:01 PM', datetime(1999, 10, 19, 15, 41, 1)),
('Tue, October 19, 1999 03:41:01 PM', datetime(1999, 10, 19, 15, 41, 1)),
('04/27/2024 18:52:55', datetime(2024, 4, 27, 18, 52, 55)),
('6/24/2024 6:49:02 PM', datetime(2024, 6, 24, 6, 49, 2)),
# From SingleFile.
('Fri Jun 17 2022 19:24:52', datetime(2022, 6, 17, 19, 24, 52)),
# PDFs are the Wild West...
("D:20221226113758-07'00", datetime(2022, 12, 26, 11, 37, 58, tzinfo=timezone(timedelta(days=-1, seconds=61200)))),
('D:20200205184724', datetime(2020, 2, 5, 18, 47, 24)),
('D:20091019120104+', datetime(2009, 10, 19, 12, 1, 4)),
('04/27/2024 18:52:55', datetime(2024, 4, 27, 18, 52, 55)),
])
def test_strpdate(dt, expected):
assert dates.strpdate(dt) == expected

View file

@ -60,21 +60,6 @@ async def test_delete_old_once_downloads(test_session, test_download_manager, te
assert_dict_contains(download.dict(), expected)
@pytest.mark.asyncio
async def test_create_download(test_session, test_download_manager, test_downloader):
assert len(test_download_manager.get_downloads(test_session)) == 0
test_downloader.set_test_success()
test_download_manager.create_download('https://example.com', test_downloader.name)
download = test_download_manager.get_download(test_session, 'https://example.com')
assert download.url == 'https://example.com'
assert len(test_download_manager.get_downloads(test_session)) == 1
assert test_download_manager.get_download(test_session, 'https://example.com') is not None
assert test_download_manager.get_download(test_session, 'https://example.com/not downloading') is None
@pytest.mark.asyncio
async def test_create_downloads(test_session, test_download_manager, test_downloader, assert_download_urls):
"""Multiple downloads can be scheduled using DownloadManager.create_downloads."""
@ -326,7 +311,7 @@ async def test_crud_download(test_async_client, test_session, test_download_mana
urls=['https://example.com', ],
downloader=test_downloader.name,
frequency=DownloadFrequency.weekly,
excluded_urls='example.org,something',
settings=dict(excluded_urls='example.org,something'),
)
request, response = await test_async_client.post('/api/download', content=json.dumps(body))
assert response.status_code == HTTPStatus.NO_CONTENT, response.body

View file

@ -131,8 +131,8 @@ async def test_downloads_sorter_recurring(test_async_client, test_session):
dict(status='failed', frequency=1),
dict(status='failed', frequency=1),
]
for download in downloads:
test_session.add(Download(url='https://example.com', **download))
for idx, download in enumerate(downloads):
test_session.add(Download(url=f'https://example.com/{idx}', **download))
test_session.commit()
expected = [
@ -164,8 +164,8 @@ async def test_downloads_sorter(test_async_client, test_session):
dict(status='failed'),
dict(status='failed', last_successful_download='2020-01-01T00:00:01+00:00'),
]
for download in downloads:
test_session.add(Download(url=download.pop('url', 'https://example.com'), **download))
for idx, download in enumerate(downloads):
test_session.add(Download(url=download.pop('url', f'https://example.com/{idx}'), **download))
test_session.commit()
expected = [
@ -389,8 +389,9 @@ async def test_get_status(test_async_client, test_session):
assert 'flags' in response.json and isinstance(response.json['flags'], dict)
def test_post_download(test_session, test_client, test_download_manager_config):
def test_download_crud(test_session, test_client, test_download_manager_config, tag_factory):
"""Test creating once-downloads and recurring downloads."""
tag1, tag2 = tag_factory(), tag_factory()
async def dispatch_downloads(*a, **kw):
pass
@ -407,16 +408,33 @@ def test_post_download(test_session, test_client, test_download_manager_config):
assert {i.url for i in test_session.query(Download)} == {'https://example.com/1', }
# Create to once-downloads.
# Create two once-downloads.
content = dict(
urls=['https://example.com/2', 'https://example.com/3'],
downloader='archive',
)
request, response = test_client.post('/api/download', content=json.dumps(content))
request, response = test_client.post('/api/download', json=content)
assert response.status_code == HTTPStatus.NO_CONTENT
assert {i.url for i in test_session.query(Download)} == {f'https://example.com/{i}' for i in range(1, 4)}
download1, download2, download3 = test_session.query(Download).order_by(Download.url).all()
assert not download1.settings
expected_download1 = dict(download1.__json__()).copy()
# Update a download.
content = dict(
urls=['https://example.com/1'],
downloader='archive',
settings={'tag_names': [tag1.name, tag2.name]},
)
expected_download1.update({'url': 'https://example.com/1', 'settings': {'tag_names': [tag1.name, tag2.name]}})
request, response = test_client.put(f'/api/download/{download1.id}', json=content)
assert response.status_code == HTTPStatus.NO_CONTENT
test_session.flush([download2])
download2 = test_session.query(Download).filter_by(id=expected_download1['id']).first()
assert download2.__json__() == expected_download1
def test_get_downloaders(test_client):
"""A list of Downloaders the user can use can be gotten."""
@ -516,12 +534,10 @@ async def test_search_suggestions(test_session, test_async_client, channel_facto
await assert_results(
dict(search_str='foo'),
[{'directory': 'Fool',
'id': 2,
'name': 'Fool',
'url': 'https://example.com/Fool'},
{'directory': 'Foo', 'id': 1, 'name': 'Foo', 'url': 'https://example.com/Foo'},
],
[
{'directory': 'Fool', 'id': 2, 'name': 'Fool', 'url': 'https://example.com/Fool', 'channel_downloads': []},
{'directory': 'Foo', 'id': 1, 'name': 'Foo', 'url': 'https://example.com/Foo', 'channel_downloads': []},
],
[{'directory': 'archive/foo.com', 'domain': 'foo.com', 'id': 1}],
)
@ -529,16 +545,15 @@ async def test_search_suggestions(test_session, test_async_client, channel_facto
await assert_results(
dict(search_str='foo l'),
[
{'directory': 'Fool',
'id': 2,
'name': 'Fool',
'url': 'https://example.com/Fool'}],
{'directory': 'Fool', 'id': 2, 'name': 'Fool', 'url': 'https://example.com/Fool', 'channel_downloads': []}],
[],
)
await assert_results(
dict(search_str='bar'),
[{'directory': 'Bar', 'id': 3, 'name': 'Bar', 'url': 'https://example.com/Bar'}],
[
{'directory': 'Bar', 'id': 3, 'name': 'Bar', 'url': 'https://example.com/Bar', 'channel_downloads': []}
],
[{'directory': 'archive/bar.com', 'domain': 'bar.com', 'id': 2}],
)