Video downloads have many more options. Downloads are migrated.

Storing video settings in session storage to help user start downloads consistently.

Applying channel tag name to new channels when download videos or channels.

Initializing map tiles when importing and resetting map.
This commit is contained in:
Roland 2024-11-02 15:14:02 -06:00
parent a385d4f709
commit 5621d47309
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
77 changed files with 5878 additions and 2541 deletions

View file

@ -27,7 +27,6 @@ import {
HelpHeader,
humanFileSize,
isoDatetimeToAgoPopup,
isoDatetimeToString,
mimetypeColor,
PageContainer,
PreviewPath,
@ -49,6 +48,7 @@ import {Button, Card, CardIcon, darkTheme, Header, Loader, Placeholder, Popup, S
import {SortableTable} from "./SortableTable";
import {taggedImageLabel, TagsSelector} from "../Tags";
import {toast} from "react-semantic-toasts-2";
import {Downloaders} from "./Vars";
function archiveFileLink(path, directory = false) {
if (path) {
@ -111,7 +111,8 @@ function ArchivePage() {
}
const localUpdateArchive = async () => {
const response = await postDownload([archiveFile.url], 'archive');
const downloadData = {urls: [archiveFile.url], downloader: Downloaders.Archive};
const response = await postDownload(downloadData);
if (response.ok) {
toast({
type: 'success',
@ -170,11 +171,11 @@ function ArchivePage() {
await fetchArchive();
}
const archivedDatetimeString = isoDatetimeToString(archiveFile.download_datetime, true);
const publishedDatetimeString = archiveFile.published_datetime ? isoDatetimeToString(archiveFile.published_datetime, true)
const archivedDatetimeString = isoDatetimeToAgoPopup(archiveFile.download_datetime, true);
const publishedDatetimeString = archiveFile.published_datetime ? isoDatetimeToAgoPopup(archiveFile.published_datetime, true)
: 'unknown';
const modifiedDatetimeString = archiveFile.published_modified_datetime
? isoDatetimeToString(archiveFile.published_modified_datetime, true)
? isoDatetimeToAgoPopup(archiveFile.published_modified_datetime, true)
: 'unknown';
const aboutPane = {
@ -568,15 +569,15 @@ export function ArchiveRowCells({file}) {
poster = <FileIcon file={file} size='large'/>;
}
let dataCell = file.published_datetime ? isoDatetimeToString(file.published_datetime) : '';
let dataCell = file.published_datetime ? isoDatetimeToAgoPopup(file.published_datetime) : '';
if (sort === 'published_modified_datetime') {
dataCell = file.published_modified_datetime ? isoDatetimeToString(file.published_modified_datetime) : '';
dataCell = file.published_modified_datetime ? isoDatetimeToAgoPopup(file.published_modified_datetime) : '';
} else if (sort === 'download_datetime') {
dataCell = file.download_datetime ? isoDatetimeToString(file.download_datetime) : '';
dataCell = file.download_datetime ? isoDatetimeToAgoPopup(file.download_datetime) : '';
} else if (sort === 'size') {
dataCell = humanFileSize(file.size);
} else if (sort === 'viewed') {
dataCell = isoDatetimeToString(file.viewed);
dataCell = isoDatetimeToAgoPopup(file.viewed);
}
// Fragment for SelectableRow

View file

@ -1,6 +1,6 @@
import React from "react";
import {Breadcrumbs, useTitle} from "./Common";
import {Button, Icon, Segment} from "./Theme";
import {Button, Icon} from "./Theme";
import {useCalcQuery} from "../hooks/customHooks";
import {TemperatureCalculator} from "./calculators/TemperatureCalculator";
import {ElectricalCalculators} from "./calculators/ElectricalCalculators";

View file

@ -0,0 +1,58 @@
import React from "react";
import {ChannelPage} from "./Channels";
describe(' Channels Page', () => {
beforeEach(() => {
// Do not return directories for these tests.
cy.intercept('POST', '**/api/files/search_directories', {
statusCode: 200,
body: {
is_dir: true, channel_directories: [], domain_directories: [],
directories: [{path: "some directory", name: "some directory"}],
},
}).as('searchDirectories');
});
it('New Channel page can be rendered', () => {
cy.mountWithTags(
<ChannelPage create={true}/>,
{initialEntries: ['/videos/channels/new']}
);
cy.get('input[name="name"]').should('be.visible');
cy.wait('@searchDirectories');
});
it('Edit Channel page can be rendered', () => {
cy.intercept('GET', '**/api/videos/channels/1', {
statusCode: 200,
body: {
channel: {
name: 'Editing Channel',
tag_name: 'Automotive',
id: 1,
directory: 'some directory',
rss_url: 'https://example.com/rss-feed',
downloads: [],
statistics: {
size: 1,
largest_video: 2,
video_count: 3,
length: 4,
video_tags: 5,
}
}
},
}).as('channelFetch');
cy.mountWithTags(
<ChannelPage create={false}/>,
{initialEntries: ['/videos/channels/1']}
);
cy.wait('@channelFetch');
cy.wait('@searchDirectories'); // Needed for CircleCi.
cy.wait(500);
cy.get('input[name="name"]').should('be.visible');
cy.get('input[name="name"]').should('have.value', 'Editing Channel');
cy.get('div.ui.label.large').contains('Automotive').should('be.visible');
});
});

View file

@ -1,44 +1,27 @@
import React, {useState} from "react";
import {Dimmer, Dropdown, Grid, Input, StatisticLabel, StatisticValue, TableCell, TableRow,} from "semantic-ui-react";
import {
createChannel,
createChannelDownload,
deleteChannel,
deleteDownload,
refreshChannel,
tagChannel,
tagChannelInfo,
updateChannel,
updateChannelDownload
} from "../api";
import {Grid, Input, StatisticLabel, StatisticValue, TableCell, TableRow,} from "semantic-ui-react";
import {createChannel, deleteChannel, refreshChannel, tagChannel, tagChannelInfo, updateChannel} from "../api";
import {
APIButton,
BackButton,
DirectorySearch,
ErrorMessage,
frequencyOptions,
HelpHeader,
humanFileSize,
humanNumber,
RequiredAsterisk,
SearchInput,
secondsToFrequency,
secondsToFullDuration,
SimpleAccordion,
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 {useChannel, useChannels, useOneQuery, useWROLMode} from "../hooks/customHooks";
import {useChannel, useChannels, useOneQuery} from "../hooks/customHooks";
import _ from "lodash";
import {
Button,
Form,
FormField,
FormGroup,
FormInput,
Header,
Loader,
Modal,
@ -53,6 +36,8 @@ import {SortableTable} from "./SortableTable";
import {toast} from "react-semantic-toasts-2";
import {RecurringDownloadsTable} from "./admin/Downloads";
import {TagsContext, TagsSelector} from "../Tags";
import {InputForm} from "../hooks/useForm";
import {ChannelDownloadForm, DestinationForm, DownloadTagsSelector} from "./Download";
function ChannelStatistics({statistics}) {
@ -86,17 +71,17 @@ function ChannelStatistics({statistics}) {
}
function ChannelPage({create, header}) {
const [disabled, setDisabled] = useState(false);
export function ChannelPage({create, header}) {
// Used to display messages to maintainer.
const [error, setError] = useState(false);
const [success, setSuccess] = useState(false);
const [messageHeader, setMessageHeader] = useState();
const [messageContent, setMessageContent] = useState();
const [downloadModalOpen, setDownloadModalOpen] = useState(false);
const navigate = useNavigate();
const {channelId} = useParams();
const {channel, ready: channelReady, changeValue, fetchChannel} = useChannel(channelId);
const {SingleTag} = React.useContext(TagsContext);
const [tagEditModalOpen, setTagEditModalOpen] = useState(false);
@ -104,24 +89,21 @@ function ChannelPage({create, header}) {
const [moveToTagDirectory, setMoveToTagDirectory] = useState(true);
const [newTagDirectory, setNewTagDirectory] = useState('');
const {channel, form, fetchChannel} = useChannel(channelId);
useTitle(_.isEmpty(channel) ? null : `${channel.name} Channel`);
React.useEffect(() => {
setNewTagName(channel.tag_name);
}, [channel.tag_name]);
if (channel && channel.tag_name !== newTagName) {
setNewTagName(channel.tag_name);
}
}, [channel]);
if (!create && !channelReady) {
if (!create && !form.ready) {
// Waiting for editing Channel to be fetched.
return <Loader active/>;
}
const handleInputChange = (e, {name, value}) => {
if (e) {
e.preventDefault();
}
changeValue(name, value);
}
const setErrorMessage = (header, message) => {
setError(true);
setSuccess(false);
@ -136,18 +118,13 @@ function ChannelPage({create, header}) {
setMessageContent(message);
}
const handleSubmit = async (e) => {
if (e) {
e.preventDefault();
}
const handleSubmit = async () => {
const body = {
name: channel.name,
directory: channel.directory,
url: channel.url,
};
setDisabled(true);
let response = null;
try {
if (create !== undefined) {
@ -166,8 +143,6 @@ function ChannelPage({create, header}) {
time: 5000,
});
return;
} finally {
setDisabled(false);
}
if (response && response.ok) {
@ -237,7 +212,12 @@ function ChannelPage({create, header}) {
let downloads = channel && channel.downloads ? channel.downloads : null;
const afterNewDownloadSave = async () => {
await fetchChannel();
setDownloadModalOpen(false);
await form.fetcher();
}
const onDelete = async () => {
await form.fetcher();
setDownloadModalOpen(false);
}
@ -318,6 +298,54 @@ function ChannelPage({create, header}) {
</Modal>;
}
let channelUrlRow;
if (channel && channel.url) {
channelUrlRow = <Grid.Row columns={1}>
<Grid.Column>
<Header as='h4'>URL</Header>
<a href={channel.url}>{channel.url}</a>
</Grid.Column>
</Grid.Row>;
}
let channelRssUrlRow;
if (channel && channel.rss_url) {
channelRssUrlRow = <Grid.Row columns={1}>
<Grid.Column>
<Header as='h4'>RSS URL</Header>
<a href={channel.rss_url}>{channel.rss_url}</a>
</Grid.Column>
</Grid.Row>;
}
let channelTagRow;
if (channel && channel.tag_name) {
channelTagRow = <Grid.Row columns={1}>
<Grid.Column>
{channel.tag_name && !create && <SingleTag name={channel.tag_name}/>}
</Grid.Column>
</Grid.Row>;
}
let messageRow;
if (error || success) {
messageRow = <Grid.Row columns={1}>
<Grid.Column>
{error &&
<Message negative
header={messageHeader}
content={messageContent}
/>}
{success &&
<Message positive
header={messageHeader}
content={messageContent}
/>}
</Grid.Column>
</Grid.Row>
}
return <>
<BackButton/>
{!create &&
@ -334,56 +362,37 @@ function ChannelPage({create, header}) {
success={success}
autoComplete="off"
>
<FormGroup>
<FormField width={8}>
<FormInput required
label="Channel Name"
name="name"
type="text"
placeholder="Short Channel Name"
disabled={disabled}
value={channel.name}
onChange={(e, {value}) => changeValue('name', value)}
/>
</FormField>
<FormField width={8}>
<label>
Directory <RequiredAsterisk/>
</label>
<DirectorySearch
value={channel.directory}
onSelect={value => changeValue('directory', value)}
placeholder='videos/channel directory'
/>
</FormField>
</FormGroup>
<FormGroup>
<FormField width={16}>
<FormInput
label="URL"
name="url"
type="url"
placeholder='https://example.com/channel/videos'
value={channel.url}
onChange={handleInputChange}
/>
</FormField>
</FormGroup>
{channel.tag_name && !create && <SingleTag name={channel.tag_name}/>}
<Message error
header={messageHeader}
content={messageContent}
/>
<Message success
header={messageHeader}
content={messageContent}
/>
<Grid stackable columns={2}>
<Grid.Row style={{marginTop: '1em'}}>
<Grid.Row>
<Grid.Column>
<InputForm
form={form}
label="Channel Name"
name="name"
placeholder="Short Channel Name"
required={true}
/>
</Grid.Column>
<Grid.Column>
<DestinationForm
form={form}
label='Directory'
name='directory'
path='directory'
required={true}
/>
</Grid.Column>
</Grid.Row>
{channelTagRow}
{!create && (channel.url || channel.rss_url) &&
<SimpleAccordion title='Details'>
<Grid>
{channelUrlRow}
{channelRssUrlRow}
</Grid>
</SimpleAccordion>}
{messageRow}
<Grid.Row>
<Grid.Column width={8}>
{!create ?
<>
@ -411,14 +420,12 @@ function ChannelPage({create, header}) {
>Tag</Button>
{tagEditModal}
</>
: <>
<TagsSelector
limit={1}
selectedTagNames={channel.tag_name ? [channel.tag_name] : []}
onAdd={i => changeValue('tag_name', i)}
onRemove={() => changeValue('tag_name', null)}
/>
</>
: <DownloadTagsSelector
form={form}
limit={1}
path='tag_name'
name='tag_name'
/>
}
</Grid.Column>
<Grid.Column>
@ -427,7 +434,7 @@ function ChannelPage({create, header}) {
size='big'
floated='right'
onClick={handleSubmit}
disabled={disabled}
disabled={form.disabled}
obeyWROLMode={true}
>Save</APIButton>
</Grid.Column>
@ -457,190 +464,20 @@ function ChannelPage({create, header}) {
<Header as='h2'>New Channel Download</Header>
<ChannelDownloadForm
channel_id={channelId}
afterSave={afterNewDownloadSave}
closeModal={() => setDownloadModalOpen(false)}
onSuccess={afterNewDownloadSave}
onCancel={() => setDownloadModalOpen(false)}
onDelete={onDelete}
/>
</ModalContent>
</Modal>
<RecurringDownloadsTable downloads={downloads} fetchDownloads={fetchChannel}/>
<RecurringDownloadsTable downloads={downloads} fetchDownloads={fetchChannel} onDelete={onDelete}/>
</Segment>}
<div style={{marginTop: '2em'}}>
{channel.statistics && <ChannelStatistics statistics={channel.statistics}/>}
</div>
{channel && channel.statistics && <ChannelStatistics statistics={channel.statistics}/>}
</>
}
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({
frequency: download.frequency ? download.frequency : 604800,
title_exclude: settings.title_exclude ? settings.title_exclude : '',
title_include: settings.title_include ? settings.title_include : '',
url: download ? download.url : '',
})
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_include,
state.title_exclude,
tagNames,
);
} else {
response = await createChannelDownload(
channel_id,
state.url,
state.frequency,
state.title_include,
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 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_include"
type="text"
disabled={disabled}
placeholder='Shelter,Solar Power'
value={state.title_include}
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} onChange={(i, j) => setTagNames(i)}/>
</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}/>;
}

View file

@ -1,5 +1,7 @@
import React, {useContext, useEffect, useState} from "react";
import {
AccordionContent,
AccordionTitle,
BreadcrumbSection,
Button as SButton,
ButtonGroup,
@ -29,6 +31,7 @@ import {
} from "../hooks/customHooks";
import {Media, SettingsContext, StatusContext, ThemeContext} from "../contexts/contexts";
import {
Accordion,
Breadcrumb,
BreadcrumbDivider,
Button,
@ -52,21 +55,7 @@ import {
import {FilePreviewContext} from "./FilePreview";
import _ from "lodash";
import {killDownloads, startDownloads} from "../api";
export const API_URI = process.env && process.env.REACT_APP_API_URI ? process.env.REACT_APP_API_URI : `https://${window.location.host}/api`;
export const VIDEOS_API = `${API_URI}/videos`;
export const ARCHIVES_API = `${API_URI}/archive`;
export const OTP_API = `${API_URI}/otp`;
export const ZIM_API = `${API_URI}/zim`;
export const DEFAULT_LIMIT = 20;
export const NAME = process.env && process.env.REACT_APP_NAME ? process.env.REACT_APP_NAME : null;
// Other services on a WROLPi.
const port = window.location.port ? `${window.location.port}` : '';
export const FILES_MEDIA_URI = `https://${window.location.hostname}${port}/media/`;
export const MAP_VIEWER_URI = `https://${window.location.hostname}:8084`;
export const ZIM_VIEWER_URI = `https://${window.location.hostname}:8085`;
export const HELP_VIEWER_URI = `https://${window.location.hostname}:8086`;
import {allFrequencyOptions, NAME, semanticUIColorMap, validUrlRegex} from "./Vars";
export function Paginator({activePage, onPageChange, totalPages, showFirstAndLast, size = 'mini'}) {
const handlePageChange = (e, {activePage}) => {
@ -105,7 +94,7 @@ export function divmod(x, y) {
return [Math.floor(x / y), x % y];
}
export function secondsElapsed(seconds, short = true) {
export function secondsToHumanElapsed(seconds, short = true) {
// Convert the provided seconds into a human-readable string of the time elapsed between the provided timestamp
// and now.
if (!seconds || seconds < 0) {
@ -158,7 +147,7 @@ export function secondsElapsed(seconds, short = true) {
export function secondsToElapsedPopup(seconds) {
// Return a Popup which allows the user see a more detailed timestamp when hovering.
const elapsed = secondsElapsed(seconds);
const elapsed = secondsToHumanElapsed(seconds);
if (!elapsed) {
return <></>;
}
@ -177,7 +166,7 @@ export function isoDatetimeToElapsedPopup(dt) {
export function isoDatetimeToAgoPopup(dt, short = true) {
const seconds = (new Date(dt)).getTime() / 1000;
// Return a Popup which allows the user see a more detailed timestamp when hovering.
const elapsed = secondsElapsed(seconds, short);
const elapsed = secondsToHumanElapsed(seconds, short);
if (seconds === 0 || !elapsed) {
return <></>;
}
@ -271,31 +260,9 @@ export function RequiredAsterisk() {
return <span style={{color: '#db2828'}}> *</span>
}
export let defaultFileOrder = '-published_datetime';
export let defaultSearchOrder = 'rank';
export const frequencyOptions = [{key: null, text: '', value: null}, {
key: 'daily', text: 'Daily', value: 86400
}, {key: 'weekly', text: 'Weekly', value: 604800}, {key: 'biweekly', text: 'Biweekly', value: 1209600}, {
key: '30days', text: '30 Days', value: 2592000
}, {key: '90days', text: '90 Days', value: 7776000},];
export const rssFrequencyOptions = [{key: 'once', text: 'Once', value: 0}, {
key: 'hourly', text: 'Hourly', value: 3600
}, {key: '3hours', text: '3 hours', value: 10800}, {key: '12hours', text: '12 hours', value: 43200}, {
key: 'daily', text: 'Daily', value: 86400
}, {key: 'weekly', text: 'Weekly', value: 604800}, {key: 'biweekly', text: 'Biweekly', value: 1209600}, {
key: '30days', text: '30 Days', value: 2592000
}, {key: '90days', text: '90 Days', value: 7776000}, {key: '180days', text: '180 Days', value: 15552000}];
export function secondsToFrequency(seconds) {
for (let i = 0; i < Object.keys(rssFrequencyOptions).length; i++) {
let d = rssFrequencyOptions[i];
if (d.value === seconds) {
return d.text;
}
}
return null;
const option = allFrequencyOptions[seconds];
return option ? option.text : null;
}
const secondsToYears = 31536000;
@ -782,10 +749,14 @@ export function HelpHeader({
iconSize,
headerContent,
popupContent,
popupPosition = 'top center'
popupPosition = null,
for_ = null,
required = false,
}) {
return <div className='inline-header'>
<Header as={headerSize}>{headerContent}</Header>
<label for={for_}>
<Header as={headerSize}>{headerContent} {required && <RequiredAsterisk/>}</Header>
</label>
<span>
<HelpPopup content={popupContent} size={iconSize} icon={icon} position={popupPosition}/>
</span>
@ -1205,7 +1176,7 @@ export function useTitle(title) {
}, [title]);
}
export function DirectorySearch({onSelect, value, ...props}) {
export function DirectorySearch({onSelect, value, disabled, required, ...props}) {
const {
directoryName,
setDirectoryName,
@ -1280,6 +1251,7 @@ export function DirectorySearch({onSelect, value, ...props}) {
loading={loading}
value={directoryName}
results={results}
disabled={disabled}
{...props}
/>
}
@ -1289,21 +1261,6 @@ export const BackButton = ({...props}) => {
return <Button icon='arrow left' content='Back' onClick={() => navigate(-1)} {...props}/>;
}
export const semanticUIColorMap = {
red: '#db2828',
orange: '#f2711c',
yellow: '#fbbd08',
olive: '#b5cc18',
green: '#21ba45',
teal: '#00b5ad',
blue: '#2185d0',
violet: '#6435c9',
purple: '#a333c8',
pink: '#e03997',
brown: '#a5673f',
grey: '#767676',
}
export const ColorToSemanticHexColor = (color) => {
return semanticUIColorMap[color] || null;
}
@ -1456,13 +1413,15 @@ export function useAPIButton(
themed = true,
obeyWROLMode = false,
icon = null,
type = 'button',
id = null,
props
) {
props = props || {};
const ref = React.useRef();
const [confirmOpen, setConfirmOpen] = React.useState(false);
const [pending, setPending] = React.useState(false);
const [loading, setLoading] = React.useState(false);
const [animation, setAnimation] = React.useState('jiggle');
const [animationVisible, setAnimationVisible] = React.useState(true);
const [showSuccess, setShowSuccess] = React.useState(false);
@ -1471,7 +1430,7 @@ export function useAPIButton(
const wrolModeEnabled = useWROLMode();
// Disable when API call is pending, or button is disabled.
disabled = pending || disabled;
disabled = loading || disabled;
// Disable when WROL Mode is enabled, otherwise normal disabled.
disabled = obeyWROLMode ? wrolModeEnabled || disabled : disabled;
@ -1496,15 +1455,16 @@ export function useAPIButton(
const handleAPICall = async () => {
// Handle when user clicks button, or clicks confirm.
setPending(true);
setLoading(true);
try {
await onClick();
setSuccess();
} catch (e) {
console.error(e);
setFailure();
} finally {
setLoading(false);
}
setPending(false);
}
const localOnClick = async (e) => {
@ -1533,7 +1493,14 @@ export function useAPIButton(
}
// Create button with or without theme. Pass all props to the <Button/> (except props.children).
const buttonArgs = {color, onClick: localOnClick, disabled, loading: pending, size, floated, ...props};
const buttonArgs = {
color, onClick: localOnClick, disabled, loading, size, floated, type,
...props
};
if (id) {
buttonArgs['id'] = id;
}
let buttonContent = props.children || null;
if (icon) {
@ -1587,6 +1554,8 @@ export function APIButton({
themed,
obeyWROLMode,
icon,
type = 'button',
id = null,
...props
}) {
const {button} = useAPIButton(
@ -1601,6 +1570,8 @@ export function APIButton({
themed,
obeyWROLMode,
icon,
type,
id,
props
);
@ -1811,12 +1782,24 @@ export function Breadcrumbs({crumbs, size = undefined}) {
</Breadcrumb>
}
const validUrlRegex = /^(http|https):\/\/[^ "]+$/;
export function validURL(url) {
return !(url && !validUrlRegex.test(url));
}
export function validURLs(urls) {
if (!!!urls) {
// Invalid while empty.
return false;
}
urls = urls.split(/\r?\n/);
for (let i = 0; i < urls.length; i++) {
if (!validURL(urls[i])) {
return false;
}
}
return true;
}
export function useLocalStorage(key, initialValue, decode = JSON.parse, encode = JSON.stringify) {
// Use localstorage to store some JSON encode-able.
@ -1852,3 +1835,43 @@ export function useLocalStorageInt(key, initialValue) {
const [storedValue, setStoredValue] = useLocalStorage(key, initialValue, parseInt, (num) => num.toString());
return [storedValue, setStoredValue];
}
export function SimpleAccordion({title = 'Advanced', ...props}) {
const [active, setActive] = React.useState(false);
return <Accordion>
<AccordionTitle
active={active}
onClick={() => setActive(!active)}
>
<Icon name='dropdown'/>
{title}
</AccordionTitle>
<AccordionContent active={active}>
{props.children}
</AccordionContent>
</Accordion>
}
export function mergeDeep(target, source) {
if (_.isEmpty(source)) {
return target;
}
// Initialize the result as target
let result = Object.assign({}, target);
for (let key of Object.keys(source)) {
if (Array.isArray(source[key])) {
// source overwrites target if it is a list with values.
result[key] = source[key] || target[key];
} else if (typeof source[key] === 'object' && typeof target[key] === 'object') {
result[key] = mergeDeep(target[key] || {}, source[key]);
} else {
result[key] = source[key] !== undefined ? source[key] : target[key];
}
}
return result;
}

View file

@ -1,100 +0,0 @@
import React from "react";
import {getByTestId, queryByTestId, render, screen} from '@testing-library/react';
import {CPUTemperatureIcon, DisableDownloadsToggle} from "./Common";
import {StatusContext} from "../contexts/contexts";
import {startDownloads} from "../components/Common";
import {BrowserRouter} from "react-router-dom";
const mockedUseHref = jest.fn();
jest.mock("react-router-dom", () => ({
...(jest.requireActual("react-router-dom")),
useHref: () => mockedUseHref
}));
test('DownloadsToggle is off when loading', async () => {
const statusValue = {status: null, fetchStatus: null};
const {container} = render(<StatusContext.Provider value={statusValue}>
<DisableDownloadsToggle/>
</StatusContext.Provider>);
let toggle = screen.getByRole('checkbox');
expect(toggle).not.toBeChecked();
// Disabled while loading.
expect(toggle).toHaveClass('disabled');
// Text is "disabled" when downloading is On.
const label = getByTestId(container, 'toggle-label');
expect(label).toHaveTextContent('Downloading Disabled');
});
test('DownloadsToggle is off if downloading is Off', async () => {
const statusValue = {
status: {downloads: {disabled: true, stopped: true}},
fetchStatus: null,
}
const {container} = render(<StatusContext.Provider value={statusValue}>
<DisableDownloadsToggle/>
</StatusContext.Provider>);
const toggle = screen.getByRole('checkbox');
expect(toggle).not.toBeChecked();
// Not disabled when loaded.
expect(toggle).not.toHaveClass('disabled');
// Text is "disabled" when downloading is On.
const label = getByTestId(container, 'toggle-label');
expect(label).toHaveTextContent('Downloading Disabled');
});
test('DownloadsToggle is on if downloading is On', async () => {
const statusValue = {
status: {downloads: {disabled: false, stopped: false}},
fetchStatus: null,
}
const {container} = render(<StatusContext.Provider value={statusValue}>
<DisableDownloadsToggle/>
</StatusContext.Provider>);
const toggle = screen.getByRole('checkbox');
expect(toggle).toBeChecked();
// Not disabled when loaded.
expect(toggle).not.toHaveClass('disabled');
// Text is "enabled" when downloading is On.
const label = getByTestId(container, 'toggle-label');
expect(label).toHaveTextContent('Downloading Enabled');
});
test('CPUTemperatureIcon high', async () => {
const statusValue = {status: {cpu_info: {temperature: 80, high_temperature: 75, critical_temperature: 90}}};
const {container} = render(<StatusContext.Provider value={statusValue}>
<BrowserRouter>
<CPUTemperatureIcon/>
</BrowserRouter>
</StatusContext.Provider>);
const icon = getByTestId(container, 'cpuTemperatureIcon');
expect(icon).toHaveClass('thermometer');
expect(icon).toHaveClass('half');
});
test('CPUTemperatureIcon critical', async () => {
const statusValue = {status: {cpu_info: {temperature: 100, high_temperature: 75, critical_temperature: 90}}};
const {container} = render(<StatusContext.Provider value={statusValue}>
<BrowserRouter>
<CPUTemperatureIcon/>
</BrowserRouter>
</StatusContext.Provider>);
const icon = getByTestId(container, 'cpuTemperatureIcon');
expect(icon).toHaveClass('thermometer');
expect(icon).not.toHaveClass('half');
});
test('CPUTemperatureIcon hidden', async () => {
const statusValue = {status: {cpu_info: {temperature: 35, high_temperature: 75, critical_temperature: 90}}};
const {container} = render(<StatusContext.Provider value={statusValue}>
<CPUTemperatureIcon/>
</StatusContext.Provider>);
const icon = queryByTestId(container, 'cpuTemperatureIcon');
expect(icon).toBeNull();
});

View file

@ -0,0 +1,68 @@
import React from 'react';
import {ArchiveDownloadForm, ChannelDownloadForm} from './Download';
import 'semantic-ui-offline/semantic.min.css';
describe('<ArchiveDownloadForm />', () => {
beforeEach(() => {
cy.mountWithTags(<ArchiveDownloadForm/>);
});
it('displays error for invalid URL', () => {
cy.get('#urls_textarea').type('invalid-url').wait(500);
cy.get('#urls_textarea').should('have.attr', 'error');
});
it('enables download button for valid URL', () => {
cy.get('#urls_textarea').type('https://wrolpi.org').wait(500);
cy.get('#urls_textarea').should('not.have.attr', 'error');
cy.get('#download_form_download_button').should('be.visible').and('not.have.attr', 'disabled');
});
it('disables download button for invalid URL', () => {
cy.get('#urls_textarea').type('invalid-url').wait(500);
cy.get('#urls_textarea').should('have.attr', 'error');
cy.get('#download_form_download_button').should('be.visible').and('have.attr', 'disabled');
});
it('initially has download button disabled', () => {
cy.get('#download_form_download_button').should('be.visible').and('have.attr', 'disabled');
});
it('clears error when switching from invalid to valid URL', () => {
cy.get('#urls_textarea').type('invalid-url').wait(500);
cy.get('#urls_textarea').should('have.attr', 'error');
cy.get('#urls_textarea').clear();
cy.get('#urls_textarea').type('https://wrolpi.org').wait(500);
cy.get('#urls_textarea').should('not.have.attr', 'error');
});
});
describe('<ChannelDownloadForm/>', () => {
beforeEach(() => {
// Do not return directories for these tests.
cy.intercept('POST', '**/api/files/search_directories', {
statusCode: 200,
body: {
is_dir: true, channel_directories: [], domain_directories: [],
directories: [{path: "some directory", name: "some directory"}],
},
}).as('searchDirectories');
cy.mountWithTags(<ChannelDownloadForm/>);
});
it('displays error for invalid URL', () => {
cy.get('#url_input').type('invalid-url').wait(500);
cy.get('#url_input').should('have.attr', 'error');
});
it('Can choose different options', () => {
cy.get('#download_frequency_selector').click()
.get('.item').contains('Once').click();
cy.get('#download_frequency_selector').click()
.get('.item').contains('Daily').click();
cy.get('#download_frequency_selector').click()
.get('.item').contains('180 Days').click();
});
});

File diff suppressed because it is too large Load diff

View file

@ -20,7 +20,6 @@ import {
ErrorMessage,
ExternalCardLink,
FileIcon,
FILES_MEDIA_URI,
findPosterPath,
HandPointMessage,
humanFileSize,
@ -69,6 +68,7 @@ import {useSubscribeEventName} from "../Events";
import {TagsSelector} from "../Tags";
import {Headlines} from "./Headline";
import {useSearch} from "./Search";
import {FILES_MEDIA_URI} from "./Vars";
function EbookCard({file}) {
const {s} = useContext(ThemeContext);

View file

@ -29,7 +29,6 @@ import _ from 'lodash';
import {ThemeContext} from "../contexts/contexts";
import {useInventory} from "../hooks/customHooks";
import {Button, FormGroup, FormInput, Header, Segment, Table} from "./Theme";
import {toast} from "react-semantic-toasts-2";
function InventorySummary() {
const {t} = useContext(ThemeContext);

View file

@ -7,7 +7,6 @@ import {
humanFileSize,
IframeViewer,
InfoMessage,
MAP_VIEWER_URI,
PageContainer,
TabLinks,
useTitle,
@ -32,6 +31,7 @@ import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {Header, Loader, Placeholder, Segment, Table} from "./Theme";
import {StatusContext} from "../contexts/contexts";
import _ from "lodash";
import {MAP_VIEWER_URI} from "./Vars";
function DockerMapImportWarning() {
const {status} = useContext(StatusContext);

View file

@ -5,9 +5,7 @@ import {Media, SettingsContext, StatusContext, ThemeContext} from "../contexts/c
import {
CPUTemperatureIcon,
DarkModeToggle,
HELP_VIEWER_URI,
HotspotStatusIcon,
NAME,
SystemLoadIcon,
useLocalStorage
} from "./Common";
@ -15,6 +13,7 @@ import {ShareButton} from "./Share";
import {useWROLMode} from "../hooks/customHooks";
import {SearchIconButton} from "./Search";
import {Icon} from "./Theme";
import {HELP_VIEWER_URI, NAME} from "./Vars";
const links = [
{text: 'Videos', to: '/videos', key: 'videos'},

127
app/src/components/Vars.js Normal file
View file

@ -0,0 +1,127 @@
export const API_URI = process.env && process.env.REACT_APP_API_URI ? process.env.REACT_APP_API_URI : `https://${window.location.host}/api`;
export const VIDEOS_API = `${API_URI}/videos`;
export const ARCHIVES_API = `${API_URI}/archive`;
export const OTP_API = `${API_URI}/otp`;
export const ZIM_API = `${API_URI}/zim`;
export const DEFAULT_LIMIT = 20;
export const NAME = process.env && process.env.REACT_APP_NAME ? process.env.REACT_APP_NAME : null;
// Other services on a WROLPi.
const port = window.location.port ? `${window.location.port}` : '';
export const FILES_MEDIA_URI = `https://${window.location.hostname}${port}/media/`;
export const MAP_VIEWER_URI = `https://${window.location.hostname}:8084`;
export const ZIM_VIEWER_URI = `https://${window.location.hostname}:8085`;
export const HELP_VIEWER_URI = `https://${window.location.hostname}:8086`;
export let defaultFileOrder = '-published_datetime'; // Most recently published files first.
export let defaultSearchOrder = 'rank'; // Most relevant files first.
// Download frequencies.
export const nullOption = {key: null, text: '', value: null};
export const onceOption = {key: 0, text: 'Once', value: 0};
export const hourlyOption = {key: 3600, text: 'Hourly', value: 3600};
export const threeHoursOption = {key: 10800, text: '3 hours', value: 10800};
export const twelveHoursOption = {key: 43200, text: '12 hours', value: 43200};
export const dailyOption = {key: 86400, text: 'Daily', value: 86400};
export const weeklyOption = {key: 604800, text: 'Weekly', value: 604800};
export const biweeklyOption = {key: 1209600, text: 'Biweekly', value: 1209600};
export const days30Option = {key: 2592000, text: '30 Days', value: 2592000};
export const days90Option = {key: 7776000, text: '90 Days', value: 7776000};
export const days180Option = {key: 15552000, text: '180 Days', value: 15552000};
export const frequencyOptions = [
dailyOption,
weeklyOption,
biweeklyOption,
days30Option,
days90Option,
];
export const longFrequencyOptions = [
dailyOption,
weeklyOption,
biweeklyOption,
days30Option,
days90Option,
days180Option,
];
export const channelFrequencyOptions = [
onceOption, // A Channel/Playlist can be downloaded once.
...longFrequencyOptions,
]
export const extendedFrequencyOptions = [
onceOption,
hourlyOption,
threeHoursOption,
twelveHoursOption,
...longFrequencyOptions,
];
export const allFrequencyOptions = {
[nullOption.value]: nullOption,
[onceOption.value]: onceOption,
[hourlyOption.value]: hourlyOption,
[threeHoursOption.value]: threeHoursOption,
[twelveHoursOption.value]: twelveHoursOption,
[dailyOption.value]: dailyOption,
[weeklyOption.value]: weeklyOption,
[biweeklyOption.value]: biweeklyOption,
[days30Option.value]: days30Option,
[days90Option.value]: days90Option,
[days180Option.value]: days180Option,
};
export const semanticUIColorMap = {
red: '#db2828',
orange: '#f2711c',
yellow: '#fbbd08',
olive: '#b5cc18',
green: '#21ba45',
teal: '#00b5ad',
blue: '#2185d0',
violet: '#6435c9',
purple: '#a333c8',
pink: '#e03997',
brown: '#a5673f',
grey: '#767676',
}
export const validUrlRegex = /^(http|https):\/\/[^ "]+$/;
export const downloadOrderOptions = [
{key: 'newest', text: 'Newest', value: 'newest'},
{key: 'oldest', text: 'Oldest', value: 'oldest'},
{key: 'views', text: 'Most Views', value: 'views'},
];
export const downloadResolutionOptions = [
{key: '360p', text: '360p', value: '360p'},
{key: '480p', text: '480p', value: '480p'},
{key: '720p', text: '720p', value: '720p'},
{key: '1080p', text: '1080p', value: '1080p'},
{key: '1440p', text: '1440p', value: '1440p'},
{key: '2160p', text: '2160p', value: '2160p'},
{key: 'maximum', text: 'Maximum', value: 'maximum'},
]
export const defaultVideoResolutionOptions = ['1080p', '720p', '480p', 'maximum'];
export const downloadFormatOptions = [
{key: 'mp4', text: '.mp4', value: 'mp4'},
{key: 'mkv', text: '.mkv', value: 'mkv'},
]
export const defaultVideoFormatOption = 'mp4';
export const Downloaders = {
Archive: 'archive',
File: 'file',
KiwixCatalog: 'kiwix_catalog',
KiwixZim: 'kiwix_zim',
RSS: 'rss',
ScrapeHtml: 'scrape_html',
Video: 'video',
VideoChannel: 'video_channel',
};

View file

@ -8,8 +8,8 @@ import {
encodeMediaPath,
getParentDirectory,
humanFileSize,
humanNumber, isoDatetimeToAgoPopup,
isoDatetimeToString,
humanNumber,
isoDatetimeToAgoPopup,
MultilineText,
PageContainer,
PreviewPath,
@ -110,7 +110,7 @@ const VideoComment = ({comment, children}) => {
specialIcon = <Icon name='heart' color='red'/>;
}
const dateElm = <div {...t}>{isoDatetimeToString(timestamp * 1000)}</div>;
const dateElm = <div {...t}>{isoDatetimeToAgoPopup(timestamp * 1000)}</div>;
const likesElm = like_count && <div {...t}>
<Icon name='thumbs up'/>{humanNumber(comment['like_count'])}
</div>;
@ -303,7 +303,7 @@ function VideoPage({videoFile, prevFile, nextFile, fetchVideo, ...props}) {
</Grid.Column>
<Grid.Column>
<h3>Censored</h3>
<p>{video.censored ? 'Yes' : 'No'}</p>
<p>{videoFile.censored ? 'Yes' : 'No'}</p>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={1}>

View file

@ -4,8 +4,6 @@ import {
APIButton,
CardLink,
CardPoster,
defaultFileOrder,
defaultSearchOrder,
Duration,
encodeMediaPath,
ErrorMessage,
@ -14,7 +12,6 @@ import {
humanFileSize,
humanNumber,
isoDatetimeToAgoPopup,
isoDatetimeToString,
mimetypeColor,
PageContainer,
PreviewLink,
@ -32,6 +29,7 @@ import {
CardDescription,
CardHeader,
Container,
Form,
Image,
PlaceholderHeader,
PlaceholderLine,
@ -45,9 +43,12 @@ import {FileRowTagIcon, FilesView} from "./Files";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {Button, Card, Header, Loader, Placeholder, Popup, Segment, Statistic, StatisticGroup} from "./Theme";
import {deleteVideos} from "../api";
import {deleteVideos, fetchVideoDownloaderConfig, saveVideoDownloaderConfig} from "../api";
import {Media, QueryContext, ThemeContext} from "../contexts/contexts";
import _ from "lodash";
import {defaultFileOrder, defaultSearchOrder} from "./Vars";
import {InputForm, ToggleForm, useForm} from "../hooks/useForm";
import {VideoResolutionSelectorForm} from "./Download";
export function VideoWrapper() {
const {videoId} = useParams();
@ -221,6 +222,114 @@ function VideosPage() {
</>
}
function VideosSettings() {
useTitle('Videos Settings');
const emptyFormData = {
video_resolutions: ['1080p', '720p', '480p', 'maximum'],
yt_dlp_options: {
file_name_format: '%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s',
nooverwrites: true,
writeautomaticsub: true,
writesubtitles: true,
writethumbnail: true,
},
};
const fetcher = async () => {
return await fetchVideoDownloaderConfig();
}
const submitter = async () => {
return await saveVideoDownloaderConfig(form.formData);
}
const form = useForm({
fetcher,
submitter,
emptyFormData,
});
return <Segment>
<Header as='h3'>Video Downloader Settings</Header>
<Form>
<Grid>
<Grid.Row>
<Grid.Column>
<VideoResolutionSelectorForm
form={form}
name='video_resolutions'
path='video_resolutions'
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<InputForm
form={form}
name='file_name_format'
path='yt_dlp_options.file_name_format'
label='Video File Format'
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<ToggleForm
form={form}
label='Do not overwrite existing files'
name='nooverwrites'
path='yt_dlp_options.nooverwrites'
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<ToggleForm
form={form}
label='Download automatic subtitles'
name='writeautomaticsub'
path='yt_dlp_options.writeautomaticsub'
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<ToggleForm
form={form}
label='Download subtitles'
name='writesubtitles'
path='yt_dlp_options.writesubtitles'
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<ToggleForm
form={form}
label='Download thumbnail'
name='writethumbnail'
path='yt_dlp_options.writethumbnail'
/>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={1}>
<Grid.Column textAlign='right'>
<APIButton
disabled={form.disabled || !form.ready}
type='submit'
style={{marginTop: '0.5em'}}
onClick={form.onSubmit}
id='video_settings_save_button'
>Save</APIButton>
</Grid.Column>
</Grid.Row>
</Grid>
</Form>
</Segment>
}
function VideosStatistics() {
useTitle('Video Statistics');
@ -286,6 +395,7 @@ export function VideosRoute(props) {
const links = [
{text: 'Videos', to: '/videos', key: 'videos', end: true},
{text: 'Channels', to: '/videos/channel', key: 'channel'},
{text: 'Settings', to: '/videos/settings', key: 'settings'},
{text: 'Statistics', to: '/videos/statistics', key: 'statistics'},
];
@ -294,6 +404,7 @@ export function VideosRoute(props) {
<Routes>
<Route path='/' exact element={<VideosPage/>}/>
<Route path='channel' exact element={<ChannelsPage/>}/>
<Route path='settings' exact element={<VideosSettings/>}/>
<Route path='statistics' exact element={<VideosStatistics/>}/>
<Route path='channel/new' exact element={<ChannelNewPage/>}/>
<Route path='channel/:channelId/edit' exact element={<ChannelEditPage/>}/>
@ -384,7 +495,7 @@ export function VideoRowCells({file}) {
poster = <FileIcon file={file} size='large'/>;
}
let dataCell = file.published_datetime ? isoDatetimeToString(file.published_datetime) : '';
let dataCell = file.published_datetime ? isoDatetimeToAgoPopup(file.published_datetime) : '';
if (sort === 'length') {
dataCell = secondsToFullDuration(file.length || 0);
} else if (sort === 'size') {
@ -392,7 +503,7 @@ export function VideoRowCells({file}) {
} else if (sort === 'view_count') {
dataCell = humanNumber(video.view_count || 0);
} else if (sort === 'viewed') {
dataCell = isoDatetimeToString(file.viewed);
dataCell = isoDatetimeToAgoPopup(file.viewed);
}
// Fragment for SelectableRow

View file

@ -43,8 +43,7 @@ import {
TabLinks,
TagIcon,
useTitle,
WarningMessage,
ZIM_VIEWER_URI
WarningMessage
} from "./Common";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {TagsSelector} from "../Tags";
@ -66,6 +65,7 @@ import {Link, Route, Routes} from "react-router-dom";
import {SortableTable} from "./SortableTable";
import {toast} from "react-semantic-toasts-2";
import _ from "lodash";
import {ZIM_VIEWER_URI} from "./Vars";
export const OutdatedZimsMessage = ({onClick}) => {
const [open, setOpen] = React.useState(false);

View file

@ -1,17 +1,7 @@
import {useConfigs} from "../../hooks/customHooks";
import {APIButton, PageContainer} from "../Common";
import {Header, Icon, Popup, Table} from "../Theme";
import {APIButton} from "../Common";
import {Icon, Table} from "../Theme";
import React from "react";
import {
Grid,
GridColumn,
GridRow,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableRow
} from "semantic-ui-react";
import {TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {TableRowPlaceholder} from "../Placeholder";
import {useNavigate} from "react-router-dom";

View file

@ -4,7 +4,6 @@ import {
deleteDownload,
deleteOnceDownloads,
killDownload,
putDownload,
restartDownload,
retryOnceDownloads
} from "../../api";
@ -13,18 +12,13 @@ import {
APIButton,
DisableDownloadsToggle,
ErrorMessage,
frequencyOptions,
isoDatetimeToElapsedPopup,
secondsToFrequency,
useTitle,
validURL,
WROLModeMessage
} from "../Common";
import {
Button as SButton,
Dimmer,
Dropdown,
Grid,
Label,
Loader,
PlaceholderLine,
@ -35,23 +29,10 @@ import {
TableHeaderCell,
TableRow
} from "semantic-ui-react";
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";
import {Button, Header, Modal, ModalActions, ModalContent, ModalHeader, Placeholder, Segment, Table} from "../Theme";
import {useDownloads} from "../../hooks/customHooks";
import {EditChannelDownloadForm, EditRSSDownloadForm, EditZimDownloadForm} from "../Download";
import {Downloaders} from "../Vars";
function ClearDownloadsButton({callback}) {
async function localClearDownloads() {
@ -112,251 +93,142 @@ function DeleteOnceDownloadsButton({callback}) {
}
export function DownloadEditForm({afterSave, closeModal, download}) {
const [state, setState] = React.useState({
url: download.url || '',
frequency: download.frequency,
excluded_urls: download.settings ? download.settings.excluded_urls : '',
destination: download.settings ? download.settings.destination : '',
})
const [disabled, setDisabled] = React.useState(useWROLMode());
const [loading, setLoading] = React.useState(false);
const [urlValid, setUrlValid] = React.useState(true);
function RecurringDownloadRow({download, fetchDownloads, onDelete}) {
const [errorModalOpen, setErrorModalOpen] = React.useState(false);
const [editModalOpen, setEditModalOpen] = React.useState(false);
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';
}
if (afterSave) {
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 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.Column>
<FormInput
label='Destination'
name='destination'
type='text'
value={state.destination}
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,
}
}
handleRestart = async () => {
const {id} = this.props;
const handleRestart = async () => {
const {id} = download;
try {
await restartDownload(id);
} finally {
if (this.props.fetchDownloads) {
this.props.fetchDownloads();
if (fetchDownloads) {
await fetchDownloads();
}
}
}
render() {
let {
url,
frequency,
last_successful_download,
status,
location,
next_download,
error,
downloader,
} = this.props;
const {errorModalOpen} = this.state;
const handleEditOpen = () => setEditModalOpen(true);
const handleEditClose = () => setEditModalOpen(false);
const handleErrorOpen = () => setErrorModalOpen(true);
const handleErrorClose = () => setErrorModalOpen(false);
const link = location ?
(text) => <Link to={location}>{text}</Link> :
(text) => <a href={url} target='_blank' rel='noopener noreferrer'>{text}</a>;
let {
url,
frequency,
last_successful_download,
status,
location,
next_download,
error,
downloader,
} = download;
const errorModal = <Modal
closeIcon
onClose={() => this.setState({errorModalOpen: false})}
onOpen={() => this.setState({errorModalOpen: true})}
open={errorModalOpen}
trigger={<Button icon='exclamation circle' color='orange'/>}
>
<ModalHeader>Download Error</ModalHeader>
<ModalContent>
<pre style={{overflowX: 'scroll'}}>{error}</pre>
</ModalContent>
<ModalActions>
<SButton onClick={() => this.setState({errorModalOpen: false})}>Close</SButton>
</ModalActions>
</Modal>;
const link = location ?
(text) => <Link to={location}>{text}</Link> :
(text) => <a href={url} target='_blank' rel='noopener noreferrer'>{text}</a>;
const editButton = <>
<Button icon='edit' onClick={() => this.setState({editModalOpen: true})}/>
</>
const errorModal = <Modal
closeIcon
onClose={handleErrorClose}
onOpen={handleErrorOpen}
open={errorModalOpen}
trigger={<Button icon='exclamation circle' color='orange'/>}
>
<ModalHeader>Download Error</ModalHeader>
<ModalContent>
<pre style={{overflowX: 'scroll'}}>{error}</pre>
</ModalContent>
<ModalActions>
<SButton onClick={handleEditClose}>Close</SButton>
</ModalActions>
</Modal>;
const restartButton = <>
<APIButton
color='green'
icon='redo'
confirmContent='Are you sure you want to restart this download?'
confirmButton='Restart'
onClick={this.handleRestart}
obeyWROLMode={true}
/>
</>;
const editButton = <Button icon='edit' onClick={handleEditOpen}/>;
// Show "now" if we have passed the next_download.
let next = 'now';
if (next_download && new Date() < new Date(next_download)) {
next = isoDatetimeToElapsedPopup(next_download);
}
const restartButton = <APIButton
color='green'
icon='redo'
confirmContent='Are you sure you want to restart this download?'
confirmButton='Restart'
onClick={handleRestart}
obeyWROLMode={true}
/>;
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)}
</TableCell>
<TableCell>{secondsToFrequency(frequency)}</TableCell>
<TableCell>
{last_successful_download ? isoDatetimeToElapsedPopup(last_successful_download) : null}
{status === 'pending' ? <Loader active inline size='tiny'/> : null}
</TableCell>
<TableCell>{next}</TableCell>
<TableCell textAlign='right'>
{error && errorModal}
{editButton}
{restartButton}
</TableCell>
{editModal}
</TableRow>
// Show "now" if we have passed the next_download.
let next = 'now';
if (next_download && new Date() < new Date(next_download)) {
next = isoDatetimeToElapsedPopup(next_download);
}
const onSuccess = async () => {
if (fetchDownloads) {
await fetchDownloads();
}
handleEditClose();
}
const localOnDelete = async () => {
try {
await deleteDownload(download.id);
await onDelete();
} finally {
await fetchDownloads();
handleEditClose();
}
}
let editForm;
if (downloader === Downloaders.VideoChannel) {
editForm = <EditChannelDownloadForm
download={download}
onCancel={handleEditClose}
onSuccess={onSuccess}
onDelete={localOnDelete}
/>;
} else if (downloader === Downloaders.RSS) {
editForm = <EditRSSDownloadForm
download={download}
onDelete={localOnDelete}
onCancel={handleEditClose}
onSuccess={onSuccess}
/>;
} else if (downloader === Downloaders.KiwixCatalog) {
editForm = <EditZimDownloadForm
download={download}
onDelete={localOnDelete}
onCancel={handleEditClose}
onSuccess={onSuccess}
/>;
}
const editModal = <Modal closeIcon
open={editModalOpen}
onClose={handleEditClose}
>
<ModalHeader>Edit Download</ModalHeader>
<ModalContent>
{editForm}
</ModalContent>
</Modal>;
return <TableRow>
<TableCell className='column-ellipsis'>
{link(url)}
</TableCell>
<TableCell>{secondsToFrequency(frequency)}</TableCell>
<TableCell>
{last_successful_download && isoDatetimeToElapsedPopup(last_successful_download)}
{status === 'pending' && <Loader active inline size='tiny'/>}
</TableCell>
<TableCell>{next}</TableCell>
<TableCell textAlign='right'>
{error && errorModal}
{editButton}
{restartButton}
</TableCell>
{editModal}
</TableRow>
}
class OnceDownloadRow extends React.Component {
@ -365,28 +237,27 @@ class OnceDownloadRow extends React.Component {
}
handleDelete = async () => {
await deleteDownload(this.props.id);
await this.props.fetchDownloads();
try {
await deleteDownload(this.props.id);
} finally {
await this.props.fetchDownloads();
}
};
handleStop = async () => {
await killDownload(this.props.id);
await this.props.fetchDownloads();
try {
await killDownload(this.props.id);
} finally {
await this.props.fetchDownloads();
}
};
handleRestart = async () => {
try {
await restartDownload(this.props.id);
} catch (e) {
toast({
type: 'error',
title: 'Error',
description: 'Unable to restart download',
time: 5000,
})
throw e;
} finally {
await this.props.fetchDownloads();
}
await this.props.fetchDownloads();
};
render() {
@ -502,7 +373,7 @@ export function OnceDownloadsTable({downloads, fetchDownloads}) {
</Placeholder>
}
export function RecurringDownloadsTable({downloads, fetchDownloads}) {
export function RecurringDownloadsTable({downloads, fetchDownloads, onDelete}) {
if (downloads && downloads.length >= 1) {
return <Table compact className='table-ellipsis'>
<TableHeader>
@ -515,7 +386,14 @@ export function RecurringDownloadsTable({downloads, fetchDownloads}) {
</TableRow>
</TableHeader>
<TableBody>
{downloads.map(i => <RecurringDownloadRow key={i.id} fetchDownloads={fetchDownloads} {...i}/>)}
{downloads.map(i => {
return <RecurringDownloadRow
key={i.id}
fetchDownloads={fetchDownloads}
download={i}
onDelete={onDelete}
/>
})}
</TableBody>
</Table>
} else if (downloads) {

View file

@ -21,7 +21,6 @@ import {
ErrorMessage,
HelpPopup,
HotspotToggle,
semanticUIColorMap,
ThrottleToggle,
Toggle,
WROLModeMessage
@ -32,6 +31,7 @@ import {toast} from "react-semantic-toasts-2";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {SettingsContext} from "../../contexts/contexts";
import {ConfigsTable} from "./Configs";
import {semanticUIColorMap} from "../Vars";
export function ShutdownButton() {
const dockerized = useDockerized();
@ -388,7 +388,7 @@ export function SettingsPage() {
<ButtonGroup>
<Button color={state.nav_color} onClick={e => e.preventDefault()}>Navbar Color</Button>
<Dropdown
id='settings_navbar_color_dropdown'
id='settings_navbar_color_dropdown'
className='button icon'
floating
options={navColorOptions}