Adding edit button so user can edit downloads, currently supports videos and archives.

This commit is contained in:
Roland 2025-06-07 17:36:00 -06:00 • committed by lrnselfreliance
parent 2cca0dc778
commit 3725f0f39d
11 changed files with 396 additions and 81 deletions

View file

@ -271,8 +271,13 @@ function VideoDownloadCountLimit({form, name = 'video_count_limit', path = 'sett
/>
}
export function VideoResolutionSelectorForm({form, name = 'video_resolutions', path = 'settings.video_resolutions'}) {
const [inputProps, inputAttrs] = form.getSelectionProps({name, path, type: 'array'});
export function VideoResolutionSelectorForm({form, name = 'video_resolutions', path = 'settings.video_resolutions', onChange}) {
const [inputProps, inputAttrs] = form.getSelectionProps({
name,
path,
type: 'array',
afterChange: onChange
});
return <>
<InfoHeader
@ -382,13 +387,17 @@ export function UseBrowserProfile({form}) {
/>
}
export function VideosDownloadForm({singleDownload = true, onCancel}) {
export function VideosDownloadForm({singleDownload = true, onCancel, onSuccess: propOnSuccess, download, submitter: propSubmitter, actions}) {
const [showMessage, setShowMessage] = React.useState(false);
const [userChangedResolutions, setUserChangedResolutions] = React.useState(false);
const [config, setConfig] = React.useState(null);
// Keep video settings in session to help user start downloads consistently.
const [defaultVideoResolutions, setDefaultVideoResolutions] = useLocalStorage('video_resolutions', defaultVideoResolutionOptions);
// Keep video format in session to help user start downloads consistently.
const [defaultVideoFormat, setDefaultVideoFormat] = useLocalStorage('video_format', defaultVideoFormatOption);
// Use config video resolutions if available, otherwise use default
const configResolutions = config && config.video_resolutions ? config.video_resolutions : defaultVideoResolutionOptions;
const defaultFormData = {
urls: '', // Textarea, one URL per line.
destination: '',
@ -397,11 +406,11 @@ export function VideosDownloadForm({singleDownload = true, onCancel}) {
settings: {
use_browser_profile: false,
video_format: defaultVideoFormat,
video_resolutions: defaultVideoResolutions,
video_resolutions: configResolutions,
}
}
const submitter = async (formData) => {
const submitter = propSubmitter || (async (formData) => {
const downloadData = {
destination: formData.destination,
downloader: formData.downloader,
@ -410,24 +419,45 @@ export function VideosDownloadForm({singleDownload = true, onCancel}) {
urls: formData.urls.split(/r?\n/),
}
await postDownload(downloadData);
}
});
const onSuccess = () => {
setShowMessage(true);
form.reset();
if (propOnSuccess) {
propOnSuccess();
} else {
form.reset();
}
}
const form = useForm({
submitter,
defaultFormData,
defaultFormData: download ? mergeDeep(defaultFormData, download) : defaultFormData,
onSuccess,
});
// Fetch video downloader config when the modal opens
React.useEffect(() => {
const {video_resolutions, video_format} = form.formData.settings;
if (video_resolutions && video_resolutions !== defaultVideoResolutions) {
setDefaultVideoResolutions(video_resolutions);
}
const fetchConfig = async () => {
try {
const result = await fetchVideoDownloaderConfig();
setConfig(result);
// Update form with video resolutions from config only if user hasn't changed them
// and if no download object was provided (this is a new download, not an edit)
if (result && result.video_resolutions && !userChangedResolutions && !download) {
form.setValue('settings.video_resolutions', result.video_resolutions);
}
} catch (error) {
console.error('Failed to fetch video downloader config:', error);
}
};
fetchConfig();
}, []);
React.useEffect(() => {
const {video_format} = form.formData.settings;
if (video_format && video_format !== defaultVideoFormat) {
setDefaultVideoFormat(video_format);
}
@ -473,7 +503,10 @@ export function VideosDownloadForm({singleDownload = true, onCancel}) {
</Grid.Row>
<Grid.Row columns={2}>
<Grid.Column width={11}>
<VideoResolutionSelectorForm form={form}/>
<VideoResolutionSelectorForm
form={form}
onChange={() => setUserChangedResolutions(true)}
/>
</Grid.Column>
<Grid.Column width={4}>
<VideoFormatSelectorForm form={form}/>
@ -492,7 +525,7 @@ export function VideosDownloadForm({singleDownload = true, onCancel}) {
{showMessage && <SuccessfulDownloadSubmitMessage/>}
<Grid.Row>
<Grid.Column>
<DownloadFormButtons onCancel={localOnCancel} form={form}/>
{actions ? actions({onCancel: localOnCancel, form}) : <DownloadFormButtons onCancel={localOnCancel} form={form}/>}
</Grid.Column>
</Grid.Row>
</Grid>
@ -511,6 +544,40 @@ export function VideoMinimumDurationForm({form}) {
/>
}
export function EditVideosDownloadForm({
download,
onCancel,
onSuccess,
onDelete,
actions = EditDownloadFormButtons,
}) {
const submitter = async (formData) => {
// Create a copy of settings without channel_url and channel_id
const settings = {...formData.settings};
// These settings are created when downloading the video, we can't submit them again.
delete settings.channel_url;
delete settings.channel_id;
const downloadData = {
destination: formData.destination,
downloader: formData.downloader,
settings: settings,
tag_names: formData.tag_names,
urls: formData.urls.split(/r?\n/),
}
await putDownload(download.id, downloadData);
}
return <VideosDownloadForm
singleDownload={true}
onCancel={onCancel}
onSuccess={onSuccess}
download={download}
submitter={submitter}
actions={(props) => actions({...props, onDelete})}
/>
}
export function VideoMaximumDurationForm({form}) {
return <VideoDurationLimit
form={form}
@ -535,6 +602,9 @@ export function ChannelDownloadForm({
channel_id = null,
}) {
const [showMessage, setShowMessage] = React.useState(false);
const [config, setConfig] = React.useState(null);
const [isConfigLoaded, setIsConfigLoaded] = React.useState(false);
const [userChangedResolutions, setUserChangedResolutions] = React.useState(false);
// May have received submitter from EditChannelDownloadForm.
submitter = submitter || (async (formData) => {
@ -557,10 +627,12 @@ export function ChannelDownloadForm({
}
}
// Keep video settings in session to help user start downloads consistently.
const [defaultVideoResolutions, setDefaultVideoResolutions] = useLocalStorage('video_resolutions', defaultVideoResolutionOptions);
// Keep video format in session to help user start downloads consistently.
const [defaultVideoFormat, setDefaultVideoFormat] = useLocalStorage('video_format', defaultVideoFormatOption);
// Use config video resolutions if available, otherwise use default
const configResolutions = config && config.video_resolutions ? config.video_resolutions : defaultVideoResolutionOptions;
const emptyFormData = {
destination: '',
downloader: Downloaders.VideoChannel,
@ -577,7 +649,7 @@ export function ChannelDownloadForm({
use_browser_profile: false,
video_count_limit: null,
video_format: defaultVideoFormat,
video_resolutions: defaultVideoResolutions,
video_resolutions: configResolutions,
},
sub_downloader: Downloaders.Video,
tag_names: [],
@ -591,11 +663,30 @@ export function ChannelDownloadForm({
clearOnSuccess,
});
// Fetch video downloader config when the modal opens
React.useEffect(() => {
const {video_resolutions, video_format} = form.formData.settings;
if (video_resolutions && video_resolutions !== defaultVideoResolutions) {
setDefaultVideoResolutions(video_resolutions);
}
const fetchConfig = async () => {
try {
const result = await fetchVideoDownloaderConfig();
setConfig(result);
setIsConfigLoaded(true);
// Update form with video resolutions from config only if user hasn't changed them
// and if no download object was provided (this is a new download, not an edit)
if (result && result.video_resolutions && !userChangedResolutions && !download) {
form.setValue('settings.video_resolutions', result.video_resolutions);
}
} catch (error) {
console.error('Failed to fetch video downloader config:', error);
setIsConfigLoaded(true);
}
};
fetchConfig();
}, []);
React.useEffect(() => {
const {video_format} = form.formData.settings;
if (video_format && video_format !== defaultVideoFormat) {
setDefaultVideoFormat(video_format);
}
@ -656,7 +747,10 @@ export function ChannelDownloadForm({
</Grid.Row>
<Grid.Row columns={2}>
<Grid.Column width={11}>
<VideoResolutionSelectorForm form={form}/>
<VideoResolutionSelectorForm
form={form}
onChange={() => setUserChangedResolutions(true)}
/>
</Grid.Column>
<Grid.Column width={4}>
<VideoFormatSelectorForm form={form}/>
@ -730,17 +824,42 @@ function SuccessfulDownloadSubmitMessage() {
</Grid.Row>
}
export function ArchiveDownloadForm({download, onCancel}) {
const [showMessage, setShowMessage] = React.useState(false);
export function EditArchiveDownloadForm({
download,
onCancel,
onSuccess,
onDelete,
actions = EditDownloadFormButtons,
}) {
const submitter = async (formData) => {
const downloadData = {
downloader: formData.downloader,
tag_names: formData.tag_names,
urls: formData.urls.split(/\r?\n/),
}
await putDownload(download.id, downloadData);
}
return <ArchiveDownloadForm
download={download}
onCancel={onCancel}
onSuccess={onSuccess}
submitter={submitter}
actions={(props) => actions({...props, onDelete})}
/>
}
export function ArchiveDownloadForm({download, onCancel, onSuccess: propOnSuccess, submitter: propSubmitter, actions}) {
const [showMessage, setShowMessage] = React.useState(false);
const submitter = propSubmitter || (async (formData) => {
const downloadData = {
downloader: formData.downloader,
tag_names: formData.tag_names,
urls: formData.urls.split(/\r?\n/),
}
await postDownload(downloadData);
};
});
const emptyFormData = {
downloader: Downloaders.Archive,
@ -748,14 +867,28 @@ export function ArchiveDownloadForm({download, onCancel}) {
tag_names: [],
};
const onSuccess = () => {
setShowMessage(true);
if (propOnSuccess) {
propOnSuccess();
}
}
const form = useForm({
submitter,
defaultFormData: mergeDeep(emptyFormData, download),
emptyFormData,
clearOnSuccess: true,
onSuccess: async () => setShowMessage(true),
clearOnSuccess: !propOnSuccess,
onSuccess,
});
const localOnCancel = (e) => {
if (e) e.preventDefault();
if (onCancel) {
onCancel();
}
}
return <Form>
<Header as='h3'><Icon name='file text' color='green'/> Archives</Header>
<p>Create a Singlefile Archive for each of the URLs provided below.</p>
@ -774,7 +907,7 @@ export function ArchiveDownloadForm({download, onCancel}) {
{showMessage && <SuccessfulDownloadSubmitMessage/>}
<Grid.Row>
<Grid.Column textAlign='right'>
<DownloadFormButtons onCancel={onCancel} form={form}/>
{actions ? actions({onCancel: localOnCancel, form}) : <DownloadFormButtons onCancel={localOnCancel} form={form}/>}
</Grid.Column>
</Grid.Row>
</Grid>
@ -783,8 +916,10 @@ export function ArchiveDownloadForm({download, onCancel}) {
export function RSSDownloadForm({download, submitter, onDelete, onCancel, actions, clearOnSuccess = true}) {
const [showMessage, setShowMessage] = React.useState(false);
const [config, setConfig] = React.useState(null);
const [isConfigLoaded, setIsConfigLoaded] = React.useState(false);
const [userChangedResolutions, setUserChangedResolutions] = React.useState(false);
const [defaultVideoResolutions, setDefaultVideoResolutions] = useLocalStorage('video_resolutions', defaultVideoResolutionOptions);
const [defaultVideoFormat, setDefaultVideoFormat] = useLocalStorage('video_format', defaultVideoFormatOption);
submitter = submitter || (async (formData) => {
@ -800,6 +935,9 @@ export function RSSDownloadForm({download, submitter, onDelete, onCancel, action
await postDownload(downloadData);
});
// Use config video resolutions if available, otherwise use default
const configResolutions = config && config.video_resolutions ? config.video_resolutions : defaultVideoResolutionOptions;
const emptyFormData = {
destination: null,
downloader: Downloaders.RSS,
@ -809,7 +947,7 @@ export function RSSDownloadForm({download, submitter, onDelete, onCancel, action
excluded_urls: null,
title_exclude: null,
title_include: null,
video_resolutions: defaultVideoResolutions,
video_resolutions: configResolutions,
video_format: defaultVideoFormat,
},
tag_names: [],
@ -824,11 +962,30 @@ export function RSSDownloadForm({download, submitter, onDelete, onCancel, action
onSuccess: async () => setShowMessage(true),
});
// Fetch video downloader config when the modal opens
React.useEffect(() => {
const {video_resolutions, video_format} = form.formData.settings;
if (video_resolutions && video_resolutions !== defaultVideoResolutions) {
setDefaultVideoResolutions(video_resolutions);
}
const fetchConfig = async () => {
try {
const result = await fetchVideoDownloaderConfig();
setConfig(result);
setIsConfigLoaded(true);
// Update form with video resolutions from config only if user hasn't changed them
// and if no download object was provided (this is a new download, not an edit)
if (result && result.video_resolutions && !userChangedResolutions && !download) {
form.setValue('settings.video_resolutions', result.video_resolutions);
}
} catch (error) {
console.error('Failed to fetch video downloader config:', error);
setIsConfigLoaded(true);
}
};
fetchConfig();
}, []);
React.useEffect(() => {
const {video_format} = form.formData.settings;
if (video_format && video_format !== defaultVideoFormat) {
setDefaultVideoFormat(video_format);
}
@ -859,7 +1016,10 @@ export function RSSDownloadForm({download, submitter, onDelete, onCancel, action
</Grid.Row>
<Grid.Row columns={2}>
<Grid.Column mobile={16} computer={11}>
<VideoResolutionSelectorForm form={form}/>
<VideoResolutionSelectorForm
form={form}
onChange={() => setUserChangedResolutions(true)}
/>
</Grid.Column>
<Grid.Column mobile={8} computer={3}>
<VideoFormatSelectorForm form={form}/>

View file

@ -93,6 +93,7 @@ function VideosPage() {
{value: 'published_datetime', text: 'Published Date', short: 'P.Date'},
{value: 'length', text: 'Length'},
{value: 'size', text: 'Size'},
{value: 'size_to_duration', text: 'Size to Duration', short: 'S/Duration'},
{value: 'view_count', text: 'Views'},
{value: 'viewed', text: 'Recently Viewed', short: 'R.Viewed'},
{value: 'download_datetime', text: 'Download Date', short: 'D.Date'},

View file

@ -18,7 +18,7 @@ import {
WROLModeMessage
} from "../Common";
import {
Button as SButton,
Button as SButton, ButtonGroup,
Label,
Loader,
PlaceholderLine,
@ -35,7 +35,9 @@ import {
EditChannelDownloadForm,
EditRSSDownloadForm,
EditScrapeFilesDownloadForm,
EditZimDownloadForm
EditZimDownloadForm,
EditVideosDownloadForm,
EditArchiveDownloadForm
} from "../Download";
import {Downloaders} from "../Vars";
@ -246,6 +248,9 @@ function RecurringDownloadRow({download, fetchDownloads, onDelete}) {
class OnceDownloadRow extends React.Component {
constructor(props) {
super(props);
this.state = {
editModalOpen: false
};
}
handleDelete = async () => {
@ -272,8 +277,21 @@ class OnceDownloadRow extends React.Component {
}
};
handleEditOpen = () => {
this.setState({ editModalOpen: true });
};
handleEditClose = () => {
this.setState({ editModalOpen: false });
};
handleEditSuccess = async () => {
await this.props.fetchDownloads();
this.handleEditClose();
};
render() {
let {url, last_successful_download, status, location, error} = this.props;
let {url, last_successful_download, status, location, error, downloader, settings, id} = this.props;
// Open downloads (/download), or external links in an anchor.
const link = location && !location.startsWith('/download') ?
@ -297,6 +315,8 @@ class OnceDownloadRow extends React.Component {
} else if (status === 'failed' || status === 'deferred') {
buttonCell = (
<TableCell>
<ButtonGroup>
<APIButton
color='red'
icon='trash'
@ -305,6 +325,13 @@ class OnceDownloadRow extends React.Component {
confirmButton='Delete'
obeyWROLMode={true}
/>
{(downloader === Downloaders.Video || downloader === Downloaders.Archive) && status !== 'pending' && (
<Button
icon='edit'
color='blue'
onClick={this.handleEditOpen}
/>
)}
<APIButton
color='green'
icon='redo'
@ -313,6 +340,7 @@ class OnceDownloadRow extends React.Component {
onClick={this.handleRestart}
obeyWROLMode={true}
/>
</ButtonGroup>
</TableCell>
);
} else if (status === 'complete' && location) {
@ -336,6 +364,55 @@ class OnceDownloadRow extends React.Component {
)
}
// Create edit modal for video or archive downloads
let editModal = null;
if (downloader === Downloaders.Video) {
editModal = (
<Modal
closeIcon
open={this.state.editModalOpen}
onClose={this.handleEditClose}
>
<ModalHeader>Edit Video Download</ModalHeader>
<ModalContent>
<EditVideosDownloadForm
download={{
urls: url,
settings: settings || {},
id: id
}}
onCancel={this.handleEditClose}
onSuccess={this.handleEditSuccess}
onDelete={this.handleDelete}
/>
</ModalContent>
</Modal>
);
} else if (downloader === Downloaders.Archive) {
editModal = (
<Modal
closeIcon
open={this.state.editModalOpen}
onClose={this.handleEditClose}
>
<ModalHeader>Edit Archive Download</ModalHeader>
<ModalContent>
<EditArchiveDownloadForm
download={{
urls: url,
tag_names: settings?.tag_names || [],
id: id
}}
onCancel={this.handleEditClose}
onSuccess={this.handleEditSuccess}
onDelete={this.handleDelete}
/>
</ModalContent>
</Modal>
);
}
return <TableRow>
<TableCell className='column-ellipsis'>
{link(url)}
@ -345,6 +422,7 @@ class OnceDownloadRow extends React.Component {
{status === 'pending' ? <Loader active inline size='tiny'/> : null}
</TableCell>
{buttonCell}
{editModal}
</TableRow>
}
}

View file

@ -179,7 +179,7 @@ export function useForm({
patchFormData(_.set(formData, path, newValue));
}
const getCustomProps = ({name, validator, type = 'text', path, required = false}) => {
const getCustomProps = ({name, validator, type = 'text', path, required = false, afterChange}) => {
// Props for any other elements.
path = path || name;
@ -202,7 +202,12 @@ export function useForm({
type,
disabled,
value,
onChange: (newValue) => {setValue(path, newValue)},
onChange: (newValue) => {
setValue(path, newValue);
if (afterChange) {
afterChange(newValue);
}
},
'data-path': path,
}
// Attributes about the input, but should not be passed as properties.
@ -214,7 +219,15 @@ export function useForm({
return [inputProps, inputAttrs]
}
const getInputProps = ({name, validator, path, required = false, type = 'text', onChange = null}) => {
const getInputProps = ({
name,
validator,
path,
required = false,
type = 'text',
onChange = null,
afterChange = null
}) => {
// Props for <input/>
path = path || name;
@ -223,7 +236,7 @@ export function useForm({
validator = validURL;
}
const [customProps, inputAttrs] = getCustomProps({name, validator, path, type, required});
const [customProps, inputAttrs] = getCustomProps({name, validator, path, type, required, afterChange});
const localHandleInputEvent = async (e) => {
if (e) e.preventDefault();
@ -244,12 +257,15 @@ export function useForm({
return [inputProps, inputAttrs]
}
const getSelectionProps = ({name, validator, path, type, required = false}) => {
const getSelectionProps = ({name, validator, path, type, required = false, afterChange = null}) => {
// Props for Dropdowns.
path = path || name;
const [customProps, inputAttrs] = getCustomProps({name, validator, type, path, required});
const [customProps, inputAttrs] = getCustomProps({name, validator, type, path, required, afterChange});
customProps.onChange = (e, {value}) => {
patchFormData(_.set(formData, path, value))
patchFormData(_.set(formData, path, value));
if (afterChange) {
afterChange(value);
}
};
return [customProps, inputAttrs]
}
@ -388,50 +404,49 @@ export function UrlInput({form, required = true, name = 'url', path = 'url', dis
export function UrlsTextarea({name = 'urls', required, form}) {
required = required !== undefined;
const validator = (value) => {
if (!validURLs(value)) {
return 'Invalid URLs';
}
}
// Memoize input props to prevent recomputation during render
const [inputProps, inputAttrs] = React.useMemo(() => {
const [inputProps, inputAttrs] = form.getInputProps({name, validator, required});
const validator = (value) => {
if (!validURLs(value)) {
return 'Invalid URLs';
}
};
return form.getInputProps({name, validator, required});
}, [form, name, required]);
const handleDrop = (e) => {
if (e) e.preventDefault();
// Handle user dropping multiple URLs into the textarea. Assume each drop is a URL. Ensure each URL
// is on its own line.
const droppedUrl = e.dataTransfer.getData('text');
let urls = (inputProps.value || '').split('\n');
urls = [...urls, droppedUrl];
urls = urls.filter(i => !!i).join('\n');
// Leave trailing newline for user to type.
inputAttrs.setValue(`${urls}\n`)
inputAttrs.setValue(`${urls}\n`);
};
const handleKeyDown = (event) => {
// Check if Ctrl (or Cmd for Mac) + Enter are pressed
if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
event.preventDefault(); // Prevents the addition of a new line in textarea if necessary
form.onSubmit(); // Call your submit handler
event.preventDefault();
form.onSubmit();
}
};
return <FormInput required
error={inputProps.error}
label='URLs'
>
<TextArea
id='urls_textarea'
placeholder={'Enter one URL per line'}
name='urls'
onDrop={handleDrop}
onKeyDown={handleKeyDown}
{...inputProps}
/>
</FormInput>
return (
<FormInput required error={inputProps.error} label="URLs">
<TextArea
id="urls_textarea"
placeholder="Enter one URL per line"
name="urls"
onDrop={handleDrop}
onKeyDown={handleKeyDown}
{...inputProps}
/>
</FormInput>
);
}
export function ToggleForm({form, name, label, path, icon = null, iconSize = 'big', disabled=false}) {
export function ToggleForm({form, name, label, path, icon = null, iconSize = 'big', disabled = false}) {
const [inputProps, inputAttrs] = form.getCustomProps({name, path})
const iconElm = icon ? <Icon size={iconSize} name={icon}/> : null;

View file

@ -45,6 +45,7 @@ VIDEO_RESOLUTION_MAP = {
'134+bestaudio', '230+bestaudio', 'mp4-360p', 'res:360',
'hls-175+bestaudio', # 360p avc1 + best audio
'396+bestaudio', '243+bestaudio', # Vertical
'hls-655+bestaudio', 'hls-655',
],
'480p': [
'135+bestaudio', '231+bestaudio', '135+139', 'mp4-480p', 'res:480',
@ -56,12 +57,14 @@ VIDEO_RESOLUTION_MAP = {
'136+bestaudio', '22', '311+bestaudio', 'res:720',
'hls-517+bestaudio', 'hls-637+bestaudio', # 720p avc1 + best audio
'398+bestaudio', '247+bestaudio', # Vertical
'hls-2890+bestaudio', 'hls-2890',
],
'1080p': [
'299+bestaudio', '312+bestaudio', '270+bestaudio', # 1080@60 avc1 + best audio
'137+bestaudio', '614+bestaudio', 'res:1080',
'hls-899+bestaudio', 'hls-1271+bestaudio', # 1080p avc1 + best audio
'399+bestaudio', '616+bestaudio', # Vertical
'hls-4026+bestaudio', 'hls-4026',
],
'1440p': [
'639+bestaudio', # vp9, best audio, hdr

View file

@ -308,6 +308,43 @@ async def test_format_videos_description(async_client, test_session, test_direct
assert response.json['videos_destination'] == 'videos/one/example.com/Channel Name'
@pytest.mark.asyncio
async def test_size_to_duration_sort(test_session, video_factory, assert_video_search):
"""Test the 'size_to_duration' sort option."""
# Create videos with different size-to-duration ratios
# All videos will have the same size (from the test file) but different durations
# Video with 10 second duration (highest ratio)
vid1 = video_factory(with_video_file=True, title='vid1', with_info_json={'duration': 10})
# Video with 20 second duration (medium ratio)
vid2 = video_factory(with_video_file=True, title='vid2', with_info_json={'duration': 20})
# Video with 30 second duration (lowest ratio)
vid3 = video_factory(with_video_file=True, title='vid3', with_info_json={'duration': 30})
test_session.commit()
# Verify that the videos have the expected size and length values
vid1 = test_session.query(Video).filter_by(id=vid1.id).one()
vid2 = test_session.query(Video).filter_by(id=vid2.id).one()
vid3 = test_session.query(Video).filter_by(id=vid3.id).one()
# All videos should have the same size
assert vid1.file_group.size == vid2.file_group.size == vid3.file_group.size
# But different lengths
assert vid1.file_group.length == 10
assert vid2.file_group.length == 20
assert vid3.file_group.length == 30
# Test ascending order (lowest ratio first)
await assert_video_search(assert_total=3, assert_ids=[vid3.id, vid2.id, vid1.id], order_by='size_to_duration')
# Test descending order (highest ratio first)
await assert_video_search(assert_total=3, assert_ids=[vid1.id, vid2.id, vid3.id], order_by='-size_to_duration')
@pytest.mark.asyncio
async def test_video_file_format(async_client, test_session, fake_now):
body = dict(video_file_format='%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s')

View file

@ -56,6 +56,8 @@ VIDEO_ORDERS = {
'-size': 'fg.size DESC, LOWER(fg.primary_path) DESC',
'length': 'fg.length ASC, LOWER(fg.primary_path) ASC',
'-length': 'fg.length DESC, LOWER(fg.primary_path) DESC',
'size_to_duration': 'CASE WHEN fg.length > 0 THEN fg.size::float / fg.length ELSE fg.size END ASC, LOWER(fg.primary_path) ASC',
'-size_to_duration': 'CASE WHEN fg.length > 0 THEN fg.size::float / fg.length ELSE fg.size END DESC, LOWER(fg.primary_path) DESC',
'viewed': 'fg.viewed ASC',
'-viewed': 'fg.viewed DESC',
'view_count': 'v.view_count ASC',
@ -70,6 +72,8 @@ NO_NULL_ORDERS = {
'-length': 'fg.length IS NOT NULL',
'size': 'fg.size IS NOT NULL',
'-size': 'fg.size IS NOT NULL',
'size_to_duration': 'fg.size IS NOT NULL AND fg.length IS NOT NULL',
'-size_to_duration': 'fg.size IS NOT NULL AND fg.length IS NOT NULL',
'view_count': 'v.view_count IS NOT NULL',
'-view_count': 'v.view_count IS NOT NULL',
}

View file

@ -4,8 +4,8 @@
docker volume create --name=openstreetmap-data
docker volume create --name=openstreetmap-rendered-tiles
git submodule update --init
docker-compose pull
docker-compose build --parallel
docker-compose up -d db
docker-compose run --rm api db upgrade
docker-compose stop
docker compose pull
docker compose build --parallel
docker compose up -d db
docker compose run --rm api db upgrade
docker compose stop

View file

@ -689,6 +689,9 @@ class DownloadManager:
download.sub_downloader = sub_downloader or None
# Remove Channel relationship, if necessary.
download.channel_id = (settings or dict()).get('channel_id')
save_downloads_config.activate_switch()
return download
@wrol_mode_check

View file

@ -856,7 +856,6 @@ def search_files(search_str: str, limit: int, offset: int, mimetypes: List[str]
FROM file_group fg
{join}
{f"WHERE {wheres}" if wheres else ""}
GROUP BY fg.id
ORDER BY {order_by}
OFFSET %(offset)s LIMIT %(limit)s
'''

View file

@ -440,6 +440,12 @@ async def test_download_crud(test_session, async_client, test_download_manager_c
assert response.status_code == HTTPStatus.CREATED
assert {i.url for i in test_session.query(Download)} == {'https://example.com/1', }
# Assert that the config has been saved
config = get_download_manager_config()
assert len(config.downloads) == 1
assert config.downloads[0]['url'] == 'https://example.com/1'
assert config.downloads[0]['frequency'] == 1_000
assert config.downloads[0]['downloader'] == 'archive'
# Create two once-downloads.
body = dict(
@ -451,6 +457,10 @@ async def test_download_crud(test_session, async_client, test_download_manager_c
assert response.status_code == HTTPStatus.CREATED
assert {i.url for i in test_session.query(Download)} == {f'https://example.com/{i}' for i in range(1, 4)}
# Assert that the config has been saved
config = get_download_manager_config()
assert len(config.downloads) == 3
assert {d['url'] for d in config.downloads} == {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
@ -473,6 +483,11 @@ async def test_download_crud(test_session, async_client, test_download_manager_c
download2 = test_session.query(Download).filter_by(id=expected_download['id']).first()
assert download2.__json__() == expected_download
assert download2.tag_names == [tag1.name, tag2.name]
# Assert that the config has been saved
config = get_download_manager_config()
assert len(config.downloads) == 3
download_config = next(d for d in config.downloads if d['url'] == 'https://example.com/1')
assert download_config['tag_names'] == [tag1.name, tag2.name]
def test_get_downloaders(test_client):