A new start

Signed-off-by: Roland <roland@learningselfreliance.com>
This commit is contained in:
Roland 2021-11-01 16:42:52 -06:00
commit 9b899f6fc0
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
135 changed files with 15764 additions and 0 deletions

173
app/src/components/Admin.js Normal file
View file

@ -0,0 +1,173 @@
import React from 'react';
import {Button, Checkbox, Container, Divider, Form, Header, Loader, Tab} from "semantic-ui-react";
import {getConfig, saveConfig} from "../api";
import TimezoneSelect from 'react-timezone-select';
class Settings extends React.Component {
constructor(props) {
super(props);
this.state = {
disabled: false,
ready: false,
validTimezone: true,
timezone: '',
}
this.mediaDirectory = React.createRef();
this.handleSubmit = this.handleSubmit.bind(this);
}
async componentDidMount() {
let config = await getConfig();
this.setState({
ready: true,
disabled: config.wrol_mode,
timezone: config.timezone || '',
});
this.mediaDirectory.current.value = config.media_directory;
}
async handleSubmit(e) {
e.preventDefault();
let config = {
media_directory: this.mediaDirectory.current.value,
timezone: this.state.timezone.value,
};
this.setState({validTimezone: true});
let response = await saveConfig(config);
if (response.status !== 200) {
let json = await response.json();
if (json.api_error === 'Invalid timezone') {
this.setState({validTimezone: false});
}
}
}
handleTimezoneChange = async (timezone) => {
this.setState({timezone});
}
render() {
if (this.state.ready === false) {
return <Loader active inline='centered'/>
}
return (
<Container>
<p>
The global settings for your server.
</p>
<p className="text-muted">
When saved, these will be written to your <i>local.yaml</i> file. Storing these settings in your
local configuration file (rather than the database) allows your WROLPi to be rebuilt and save your
settings.
</p>
<Divider/>
<Form id="settings" onSubmit={this.handleSubmit}>
<Form.Field>
<label>Media Directory</label>
<input
disabled={this.state.disabled}
type="text"
placeholder="/some/absolute/path"
ref={this.mediaDirectory}
/>
</Form.Field>
<p>
<b>This directory must already exist</b>.
The directory in which your media will be stored. Typically, this will be some external
drive like <i>/media/wrolpi</i>.
</p>
<Divider/>
<Form.Field>
<label>Timezone</label>
<TimezoneSelect
value={this.state.timezone}
onChange={this.handleTimezoneChange}
/>
</Form.Field>
<Button color="blue" type="submit" disabled={this.state.disabled}>
Save
</Button>
</Form>
</Container>
)
}
}
class WROLMode extends React.Component {
constructor(props) {
super(props);
this.state = {
WROLMode: false,
}
}
async componentDidMount() {
let config = await getConfig();
this.setState({ready: true, WROLMode: config.wrol_mode});
}
toggleWROLMode = async () => {
// Handle WROL Mode toggling by itself so that other settings are not modified.
let config = {
wrol_mode: !this.state.WROLMode,
}
await saveConfig(config);
this.setState({disabled: !this.state.WROLMode, WROLMode: !this.state.WROLMode});
}
render() {
if (this.state.ready === false) {
return <Loader active inline='centered'/>
}
return (
<Container>
<Header as="h1">WROL Mode</Header>
<h4>
Enable read-only mode. No content can be deleted or modified. Enable this when the SHTF and you
want to prevent any potential loss of data.
</h4>
<p>
Note: User settings and favorites can still be modified.
</p>
<Checkbox toggle
checked={this.state.WROLMode}
onChange={this.toggleWROLMode}
label={this.state.WROLMode ? 'WROL Mode Enabled' : 'WROL Mode Disabled'}
/>
</Container>
)
}
}
class Admin extends React.Component {
render() {
const panes = [
{menuItem: 'Settings', render: () => <Tab.Pane><Settings/></Tab.Pane>},
{menuItem: 'WROL Mode', render: () => <Tab.Pane><WROLMode/></Tab.Pane>},
];
return (
<Container style={{marginTop: '2em'}}>
<Tab panes={panes}/>
</Container>
)
}
}
export default Admin;

156
app/src/components/Apps.js Normal file
View file

@ -0,0 +1,156 @@
import React from 'react';
import {Button, Divider, Segment, TextArea} from "semantic-ui-react";
import Container from "semantic-ui-react/dist/commonjs/elements/Container";
import {Route} from "react-router-dom";
import "../static/wrolpi.css";
import {decryptOTP, encryptOTP} from "../api";
class Encrypt extends React.Component {
constructor(props) {
super(props);
this.state = {
otp: '',
plaintext: '',
ciphertext: '',
}
}
handleSubmit = async (e) => {
e.preventDefault();
let {otp, plaintext, ciphertext} = await encryptOTP(this.state.otp, this.state.plaintext);
this.setState({otp, plaintext, ciphertext});
}
handleInputChange = async (event, {name, value}) => {
this.setState({[name]: value});
}
render() {
return (
<>
<h2>Encrypt</h2>
<Segment.Group>
<Segment>
<h3>Key</h3>
<TextArea
name='otp'
className='otp'
value={this.state.otp}
onChange={this.handleInputChange}
placeholder='The random letters from your One-Time Pad'
/>
</Segment>
<Segment>
<h3>Plaintext</h3>
<TextArea
name='plaintext'
className='otp'
value={this.state.plaintext}
onChange={this.handleInputChange}
placeholder='The message you want to send'
/>
</Segment>
<Segment>
<h3>Ciphertext</h3>
<pre>{this.state.ciphertext || 'Enter your message above'}</pre>
</Segment>
</Segment.Group>
<br/>
<Button onClick={this.handleSubmit}>Encrypt</Button>
</>
)
}
}
class Decrypt extends React.Component {
constructor(props) {
super(props);
this.state = {
otp: '',
plaintext: '',
ciphertext: '',
}
}
handleSubmit = async (e) => {
e.preventDefault();
let {otp, plaintext, ciphertext} = await decryptOTP(this.state.otp, this.state.ciphertext);
this.setState({otp, plaintext, ciphertext});
}
handleInputChange = async (event, {name, value}) => {
this.setState({[name]: value});
}
render() {
return (
<>
<h2>Decrypt</h2>
<Segment.Group>
<Segment>
<h3>Key</h3>
<TextArea
name='otp'
className='otp'
value={this.state.otp}
onChange={this.handleInputChange}
placeholder='The random letters from your One-Time Pad'
/>
</Segment>
<Segment>
<h3>Ciphertext</h3>
<TextArea
name='ciphertext'
className='otp'
value={this.state.ciphertext}
onChange={this.handleInputChange}
placeholder='The message you received'
/>
</Segment>
<Segment>
<h3>Plaintext</h3>
<pre>{this.state.plaintext || 'Enter the encrypted message above'}</pre>
</Segment>
</Segment.Group>
<br/>
<Button onClick={this.handleSubmit}>Decrypt</Button>
</>
)
}
}
class OTP extends React.Component {
render() {
let newPadURL = `http://${window.location.host}/api/otp/pdf`;
let cheatSheetURL = `${process.env.PUBLIC_URL}/one-time-pad-cheat-sheet.pdf`;
return (
<div>
<h1>One-Time Pad</h1>
<h4>One-Time Pads can be used to encrypt your communications. This can be done by hand (yes, really) or
in this app.</h4>
<p>These messages are never stored and cannot be retrieved.</p>
<Button primary href={newPadURL}>Generate New Pad</Button>
<Button secondary href={cheatSheetURL}>Cheat Sheet PDF</Button>
<Divider/>
<Encrypt/>
<Divider/>
<Decrypt/>
</div>
)
}
}
export class AppsRoute extends React.Component {
render() {
return (
<>
<Container style={{marginTop: '2em', marginBottom: '2em'}}>
<Route path='/apps/otp' exact component={OTP}/>
</Container>
</>
)
}
}

View file

@ -0,0 +1,460 @@
import React from "react";
import {Card, Confirm, Container, Form, Header, Icon, Image, Placeholder, Tab, Table} from "semantic-ui-react";
import Paginator, {APIForm, objectToQuery, scrollToTop, uploadDate} from "./Common";
import {deleteArchive, fetchDomains, postArchive, refreshArchives, searchURLs} from "../api";
import Button from "semantic-ui-react/dist/commonjs/elements/Button";
import {Link, NavLink} from "react-router-dom";
import * as QueryString from "query-string";
import {ArchivePlaceholder} from "./Placeholder";
function FailedUrlCard({url, syncURL, deleteURL}) {
let syncIcon = (
<Button onClick={() => syncURL(url.url)}>
<Icon name='sync' size='big'/>
</Button>
);
let trashIcon = (
<Button onClick={() => deleteURL(url.id)}>
<Icon name='trash' size='big'/>
</Button>
);
let externalIcon = (
<a href={url.url} target='_blank' rel='noopener noreferrer'>
<Icon name='sign-out' size='big'/>
</a>
);
return (
<Card>
<Card.Content>
<Card.Header>
{url.url}
</Card.Header>
<Card.Description>
<p>Failed!</p>
{syncIcon}
{trashIcon}
{externalIcon}
</Card.Description>
</Card.Content>
</Card>
);
}
class URLCard extends React.Component {
constructor(props) {
super(props);
this.state = {
latest: props.url ? props.url.latest : null,
deleteOpen: false,
syncOpen: false,
}
}
syncURL = async () => {
await postArchive(this.props.url.url);
await this.props.fetchURLs();
}
deleteURL = async () => {
await deleteArchive(this.props.url.id);
await this.props.fetchURLs();
}
render() {
let url = this.props.url;
let latest = url && url.latest ? url.latest : null;
let imageSrc = latest.screenshot_path ? `/media/${latest.screenshot_path}` : null;
let singlefileUrl = latest.singlefile_path ? `/media/${latest.singlefile_path}` : null;
if (latest == null || latest.status === 'failed') {
return <FailedUrlCard url={url} syncURL={this.syncURL} deleteURL={this.deleteURL}/>;
}
let readabilityUrl = latest.readability_path ? `/media/${latest.readability_path}` : null;
let readabilityIcon = <Button icon><Icon name='book' size='large' disabled/></Button>;
if (readabilityUrl) {
readabilityIcon = (
<Button icon href={readabilityUrl} target='_blank' rel='noopener noreferrer'>
<Icon name='book' size='large'/>
</Button>);
}
let syncIcon = (
<>
<Button icon onClick={() => this.setState({syncOpen: true})}>
<Icon name='sync' size='large'/>
</Button>
<Confirm
open={this.state.syncOpen}
content='Download the latest version of this URL?'
confirmButton='Confirm'
onCancel={() => this.setState({syncOpen: false})}
onConfirm={this.syncURL}
/>
</>
);
let deleteIcon = (
<>
<Button icon onClick={() => this.setState({deleteOpen: true})}>
<Icon name='trash' size='large'/>
</Button>
<Confirm
open={this.state.deleteOpen}
content='Are you sure you want to delete this URL? All files will be deleted.'
confirmButton='Delete'
onCancel={() => this.setState({deleteOpen: false})}
onConfirm={this.deleteURL}
/>
</>
)
;
let externalIcon = (
<Button icon href={url.url} target='_blank' rel='noopener noreferrer'>
<Icon name='sign-out' size='large'/>
</Button>
);
return (
<Card>
<Card.Content>
<a href={singlefileUrl} target='_blank' rel='noopener noreferrer'>
<Image src={imageSrc} wrapped style={{position: 'relative', width: '100%'}}/>
<Card.Header>
<Container textAlign='left'>
<p>{url.latest.title || url.url}</p>
</Container>
</Card.Header>
</a>
<Card.Meta>
{uploadDate(latest.archive_datetime)}
</Card.Meta>
<Card.Description>
<Container textAlign='left'>
{readabilityIcon}
{syncIcon}
{deleteIcon}
{externalIcon}
</Container>
</Card.Description>
</Card.Content>
</Card>
)
}
}
class URLCards extends React.Component {
render() {
return (
<Card.Group>
{this.props.urls.map((i) => {
return <URLCard key={i['id']} url={i} fetchURLs={this.props.fetchURLs}/>
})}
</Card.Group>
)
}
}
class Archives extends React.Component {
constructor(props) {
super(props);
const query = QueryString.parse(this.props.location.search);
let activePage = query.page ? parseInt(query.page) : 1;
let domain = query.domain || null;
this.state = {
activePage: activePage,
limit: 20,
urls: null,
totalPages: null,
domain: domain,
};
this.fetchURLs = this.fetchURLs.bind(this);
this.clearSearch = this.clearSearch.bind(this);
this.changePage = this.changePage.bind(this);
}
async componentDidMount() {
await this.fetchURLs();
}
async componentDidUpdate(prevProps, prevState, snapshot) {
if (prevProps.location.search !== this.props.location.search) {
await this.fetchURLs();
}
}
async fetchURLs() {
this.setState({urls: null});
let offset = this.state.limit * this.state.activePage - this.state.limit;
let [urls, total] = await searchURLs(offset, this.state.limit, this.state.domain);
let totalPages = Math.round(total / this.state.limit) || 1;
this.setState({urls, totalPages: totalPages});
}
clearSearch() {
this.setState({activePage: 1, domain: null}, this.changePage);
}
changePage(activePage) {
if (activePage) {
this.setState({activePage});
}
let {history, location} = this.props;
let search = {
page: activePage > 1 ? activePage : null,
domain: this.state.domain,
};
history.push({
pathname: location.pathname,
search: objectToQuery(search),
});
scrollToTop();
}
render() {
let {urls, activePage, totalPages} = this.state;
if (urls === null) {
return (<>
<Header as='h1'>Latest Archives</Header>
<ArchivePlaceholder/>
</>)
}
let pagination = null;
if (totalPages) {
pagination = (
<div style={{marginTop: '3em', textAlign: 'center'}}>
<Paginator
activePage={activePage}
changePage={this.changePage}
totalPages={totalPages}
/>
</div>
)
}
let domainButton = null;
if (this.state.domain) {
domainButton = (
<Button icon labelPosition='right' onClick={this.clearSearch} style={{marginBottom: '1em'}}>
Search: {this.state.domain}
<Icon name='close'/>
</Button>
)
}
return (
<>
<Header as='h1'>Latest Archives</Header>
{domainButton}
<URLCards urls={urls} fetchURLs={this.fetchURLs}/>
{pagination}
</>
)
}
}
class Domains extends React.Component {
constructor(props) {
super(props);
this.state = {
domains: null,
total: null,
};
this.fetchDomains = this.fetchDomains.bind(this);
}
async componentDidMount() {
await this.fetchDomains();
}
async fetchDomains() {
this.setState({domains: null});
let [domains, total] = await fetchDomains();
this.setState({domains, total});
}
row(domain) {
return <Table.Row key={domain['domain']}>
<Table.Cell>
<Link to={`/archive?domain=${domain['domain']}`}>
{domain['domain']}
</Link>
</Table.Cell>
<Table.Cell>{domain['url_count']}</Table.Cell>
</Table.Row>
}
render() {
if (this.state.domains) {
return (
<>
<Header as='h1'>Domains</Header>
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Domain</Table.HeaderCell>
<Table.HeaderCell>URLs</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{this.state.domains.map(this.row)}
</Table.Body>
</Table>
</>
)
}
return (<>
<Header as='h1'>Domains</Header>
<Placeholder>
<Placeholder.Header>
<Placeholder.Line/>
<Placeholder.Line/>
</Placeholder.Header>
</Placeholder>
</>)
}
}
class ArchiveAddForm extends APIForm {
constructor(props) {
super(props);
this.archivesRef = props.archivesRef;
this.state = {
...this.state,
inputs: {
url: '',
},
errors: {},
};
this.fetchURLs = this.fetchURLs.bind(this);
}
handleSubmit = async (e) => {
e.preventDefault();
await postArchive(this.state.inputs.url);
this.setState({inputs: {url: ''}}, this.fetchURLs);
}
fetchURLs = async (e) => {
await this.archivesRef.current.fetchURLs();
}
render() {
return (
<>
<Form onSubmit={this.handleSubmit}>
<label htmlFor='url'>Archive URL</label>
<Form.Group>
<Form.Input
name='url'
placeholder='https://wrolpi.org'
onChange={this.handleInputChange}
value={this.state.inputs.url}
/>
<Form.Button primary>Archive</Form.Button>
</Form.Group>
</Form>
</>
)
}
}
class ManageArchives extends React.Component {
async refresh() {
await refreshArchives();
}
render() {
return (<>
<Button secondary
onClick={this.refresh}>
Refresh Archive Files
</Button>
</>)
}
}
export class ArchiveRoute extends React.Component {
constructor(props) {
super(props);
this.panesTos = ['/archive', '/archive/domains', '/archive/manage'];
this.state = {
activeIndex: this.matchPaneTo(),
}
this.archivesRef = React.createRef();
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (prevProps.location.pathname !== this.props.location.pathname) {
this.setState({activeIndex: this.matchPaneTo()});
}
}
matchPaneTo = () => {
return this.panesTos.indexOf(this.props.location.pathname);
}
render() {
const panes = [
{
menuItem: {
as: NavLink,
content: 'Archives',
id: 'archive',
to: '/archive',
exact: true,
key: 'home',
},
render: () => <Tab.Pane><Archives {...this.props} ref={this.archivesRef}/></Tab.Pane>
},
{
menuItem: {
as: NavLink,
content: 'Domains',
id: 'domains',
to: '/archive/domains',
exact: true,
key: 'domains',
},
render: () => <Tab.Pane><Domains {...this.props}/></Tab.Pane>
},
{
menuItem: {
as: NavLink,
content: 'Manage',
id: 'manage',
to: '/archive/manage',
exact: true,
key: 'manage',
},
render: () => <Tab.Pane><ManageArchives {...this.props}/></Tab.Pane>
},
];
return (
<Container style={{marginTop: '2em', marginBottom: '2em'}}>
<ArchiveAddForm archivesRef={this.archivesRef}/>
<Tab panes={panes} activeIndex={this.state.activeIndex}/>
</Container>
)
}
}

View file

@ -0,0 +1,642 @@
import React from "react";
import {Accordion, Button, Checkbox, Form, Grid, Header, Input, Loader, Responsive, Segment} from "semantic-ui-react";
import {
createChannel,
deleteChannel,
downloadChannel,
getChannel,
getChannels,
getConfig,
getDirectories,
refreshChannel,
updateChannel,
validateRegex
} from "../api";
import _ from "lodash";
import Container from "semantic-ui-react/dist/commonjs/elements/Container";
import {APIForm, frequencyOptions, RequiredAsterisk, secondsToDate, secondsToFrequency} from "./Common";
import {Link} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import Confirm from "semantic-ui-react/dist/commonjs/addons/Confirm";
import Table from "semantic-ui-react/dist/commonjs/collections/Table";
import {ChannelPlaceholder} from "./Placeholder";
import Dropdown from "semantic-ui-react/dist/commonjs/modules/Dropdown";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
class DirectoryInput extends React.Component {
constructor(props) {
super(props);
this.state = {
directories: [],
mediaDirectory: null,
directory: '',
}
this.handleChange = this.handleChange.bind(this);
}
async componentDidMount() {
let global_config = await getConfig();
let directories = await getDirectories(this.state.directory);
this.setState({
directories,
mediaDirectory: global_config.media_directory,
directory: this.props.value,
});
}
async componentDidUpdate(prevProps, prevState, snapshot) {
if (prevState.directory !== this.state.directory) {
let directories = await getDirectories(this.state.directory);
this.setState({directories});
}
}
async handleChange(e, {name, value}) {
e.preventDefault();
this.setState({[name]: value}, () => this.props.setInput(e, {name, value}));
}
render() {
let {directories, mediaDirectory, directory} = this.state;
return (
<div>
<Input
disabled={this.props.disabled}
name='directory'
list='directories'
error={this.props.error}
label={mediaDirectory}
value={directory}
onChange={this.handleChange}
placeholder='videos/channel directory'
/>
<datalist id='directories'>
{directories.map((i) => <option key={i} value={i}>{i}</option>)}
</datalist>
</div>
);
}
}
class ChannelPage extends APIForm {
constructor(props) {
super(props);
this.state = {
...this.state,
deleteOpen: false,
validRegex: true,
original: {},
activeIndex: -1,
inputs: {
name: '',
directory: '',
mkdir: false,
url: '',
match_regex: '',
generate_posters: true,
calculate_duration: true,
download_frequency: 604800,
},
errors: {},
};
this.calculateDuration = React.createRef();
this.generatePosters = React.createRef();
this.mkdir = React.createRef();
}
async componentDidMount() {
if (!this.props.create) {
let channel_link = this.props.match.params.channel_link;
let channel = await getChannel(channel_link);
this.initFormValues(channel);
}
}
checkRegex = async (event, {name, value}) => {
event.persist();
await this.handleInputChange(event, {name, value});
let valid = await validateRegex(value);
this.setState({validRegex: valid});
}
handleConfirm = async () => {
this.setState({deleteOpen: false});
let response = await deleteChannel(this.props.match.params.channel_link);
if (response.status === 204) {
this.props.history.push({
pathname: '/videos/channel'
});
} else {
this.setError('Failed to delete', 'Failed to delete this channel, check logs.');
}
}
handleSubmit = async (e) => {
e.preventDefault();
let {inputs} = this.state;
let response = null;
try {
this.setLoading();
if (this.props.create) {
response = await createChannel(inputs);
} else {
response = await updateChannel(this.props.match.params.channel_link, inputs);
}
} finally {
this.clearLoading();
}
if (response === null) {
throw Error('Response was null');
}
if (response.status >= 200 && response.status < 300) {
let location = response.headers.get('Location');
let channelResponse = await fetch(location);
let data = await channelResponse.json();
let channel = data['channel'];
if (response.status === 201) {
this.setSuccess(
'Channel created',
<span>
Your channel was created. View it <Link to={`/videos/channel/${channel.link}/edit`}>here</Link>
</span>
);
} else {
this.initFormValues(channel);
this.setSuccess('Channel updated', 'Your channel was updated');
this.checkDirty();
}
} else {
// Some error occurred.
let error = await response.json();
let cause = error.cause;
if (error.code === 3 || (cause && cause.code === 3)) {
this.setError(
'Invalid directory',
'This directory does not exist.',
'directory',
);
} else if (cause && cause.code === 7) {
this.setError(
'Invalid directory',
'This directory is already used by another channel',
'directory',
);
} else if (cause && cause.code === 5) {
this.setError(
'Invalid name',
'This channel name is already taken',
'name',
);
} else {
this.setError('Invalid channel', 'Unable to save channel. See logs.');
}
}
}
handleAdvancedClick = (e, titleProps) => {
const {index} = titleProps
const {activeIndex} = this.state
const newIndex = activeIndex === index ? -1 : index
this.setState({activeIndex: newIndex})
}
downloadChannel = async (e) => {
e.preventDefault();
return await downloadChannel(this.props.match.params.channel_link);
}
refreshChannel = async (e) => {
e.preventDefault();
return await refreshChannel(this.props.match.params.channel_link);
}
handleDeleteButton = (e) => {
e.preventDefault();
this.setState({deleteOpen: true});
}
render() {
return (
<Container>
<Header as="h1">{this.props.header}</Header>
<Form
id="editChannel"
onSubmit={this.handleSubmit}
error={this.state.error}
success={this.state.success}
autoComplete="off"
>
<Form.Group>
<Form.Field width={8}>
<Form.Input
required
label="Channel Name"
name="name"
type="text"
placeholder="Short Channel Name"
disabled={this.state.disabled}
error={this.state.errors.name}
value={this.state.inputs.name}
onChange={this.handleInputChange}
/>
</Form.Field>
<Form.Field width={8}>
<label>
Directory <RequiredAsterisk/>
</label>
<DirectoryInput
disabled={!this.props.create}
value={this.state.inputs.directory}
setInput={this.handleInputChange}
/>
</Form.Field>
</Form.Group>
{
this.props.create &&
<Form.Group>
<Form.Field width={8}/>
<Form.Field width={8}>
<Form.Field>
<Checkbox
toggle
label="Create this directory, if it doesn't exist."
name="mkdir"
ref={this.mkdir}
disabled={this.state.disabled}
error={this.state.errors.mkdir}
checked={this.state.inputs.mkdir}
onClick={() => this.handleCheckbox(this.mkdir)}
/>
</Form.Field>
</Form.Field>
</Form.Group>
}
<Form.Group>
<Form.Field width={16}>
<Form.Input
label="URL"
name="url"
type="url"
disabled={this.state.disabled}
placeholder='https://example.com/channel/videos'
error={this.state.errors.url}
value={this.state.inputs.url}
onChange={this.handleInputChange}
/>
</Form.Field>
</Form.Group>
<Form.Group>
<Form.Field>
<label>Download Frequency</label>
<Dropdown selection
name='download_frequency'
disabled={this.state.disabled}
placeholder='Frequency'
error={this.state.errors.download_frequency}
value={this.state.inputs.download_frequency}
options={frequencyOptions}
onChange={this.handleInputChange}
/>
</Form.Field>
</Form.Group>
<Accordion>
<Accordion.Title
onClick={this.handleAdvancedClick}
index={0}
active={this.state.activeIndex === 0}
>
<Icon name='dropdown'/>
Advanced Settings
</Accordion.Title>
<Accordion.Content
active={this.state.activeIndex === 0}
>
<Segment secondary>
<Header as="h4">
The following settings are encouraged by default, modify them at your own risk.
</Header>
<Form.Field>
<Form.Input
label="Title Match Regex"
name="match_regex"
type="text"
disabled={this.state.disabled}
error={!this.state.validRegex}
placeholder='.*([Nn]ame Matching).*'
value={this.state.inputs.match_regex}
onChange={this.checkRegex}
/>
</Form.Field>
<Form.Field>
<Checkbox
toggle
label="Generate posters, if not found"
name="generate_posters"
disabled={this.state.disabled}
checked={this.state.inputs.generate_posters}
ref={this.generatePosters}
onClick={() => this.handleCheckbox(this.generatePosters)}
/>
</Form.Field>
<Form.Field>
<Checkbox
toggle
label="Calculate video duration"
name="calculate_duration"
disabled={this.state.disabled}
checked={this.state.inputs.calculate_duration}
ref={this.calculateDuration}
onClick={() => this.handleCheckbox(this.calculateDuration)}
/>
</Form.Field>
</Segment>
</Accordion.Content>
</Accordion>
<Container style={{marginTop: '2em'}}>
<Message error
header={this.state.message_header}
content={this.state.message_content}
/>
<Message success
header={this.state.message_header}
content={this.state.message_content}
/>
<Button
color="green"
type="submit"
disabled={this.state.disabled || !this.state.dirty}
floated='right'
>
{this.state.disabled ? <Loader active inline/> : 'Save'}
</Button>
<Button
secondary
floated='right'
onClick={() => this.props.history.goBack()}
>
Cancel
</Button>
{!this.props.create &&
<>
<Button color='red' onClick={this.handleDeleteButton}>
Delete
</Button>
<Confirm
open={this.state.deleteOpen}
content='Are you sure you want to delete this channel? No video files will be deleted.'
confirmButton='Delete'
onCancel={() => this.setState({deleteOpen: false})}
onConfirm={this.handleConfirm}
/>
<Button color='blue' onClick={this.downloadChannel}>
Download
</Button>
<Button color='inverted blue' onClick={this.refreshChannel}>
Refresh
</Button>
</>
}
</Container>
</Form>
</Container>
)
}
}
export function EditChannel(props) {
return (
<ChannelPage header="Edit Channel" {...props}/>
)
}
export function NewChannel(props) {
return (
<ChannelPage header='New Channel' {...props} create/>
)
}
class ChannelRow extends React.Component {
constructor(props) {
super(props);
this.editTo = `/videos/channel/${props.channel.link}/edit`;
this.videosTo = `/videos/channel/${props.channel.link}/video`;
}
render() {
let channel = this.props.channel;
return (
<Table.Row>
<Table.Cell>
<Link to={this.videosTo}>{channel.name}</Link>
</Table.Cell>
<Table.Cell>
{channel.video_count}
</Table.Cell>
<Table.Cell>
{channel.url ? secondsToDate(channel.info_date) : null}
</Table.Cell>
<Table.Cell>
{channel.url ? secondsToDate(channel.next_download) : null}
</Table.Cell>
<Table.Cell>
{channel.url ? secondsToFrequency(channel.download_frequency) : null}
</Table.Cell>
<Table.Cell textAlign='right'>
<Link className="ui button secondary" to={this.editTo}>Edit</Link>
</Table.Cell>
</Table.Row>
)
}
}
class MobileChannelRow extends ChannelRow {
render() {
let channel = this.props.channel;
return <Table.Row verticalAlign='top'>
<Table.Cell width={10} colSpan={2}>
<p>
<Link as='h3' to={this.videosTo}>
<h3>
{channel.name}
</h3>
</Link>
</p>
<p>
Last Update: {channel.url ? secondsToDate(channel.info_date) : null}
</p>
<p>
Next Update: {channel.url ? secondsToDate(channel.next_download) : null}
</p>
<p>
Videos: {channel.video_count}
</p>
<p>
Frequency: {channel.url ? secondsToFrequency(channel.download_frequency) : null}
</p>
</Table.Cell>
<Table.Cell width={6} colSpan={2} textAlign='right'>
<p>
<Link className="ui button secondary" to={this.editTo}>Edit</Link>
</p>
</Table.Cell>
</Table.Row>;
}
}
function NewChannelButton() {
return (
<Grid.Row>
<Grid.Column/>
<Grid.Column textAlign='right'>
<Link to='/videos/channel/new'>
<Button secondary>New Channel</Button>
</Link>
</Grid.Column>
</Grid.Row>
);
}
export class Channels extends React.Component {
initialState = {
channels: null,
value: '',
results: [],
};
constructor(props) {
super(props);
this.state = this.initialState;
}
async componentDidMount() {
let channels = await getChannels();
this.setState({channels, results: channels});
}
handleSearchChange = async (e, {value}) => {
this.setState({value});
setTimeout(() => {
if (this.state.value.length < 1) {
return this.setState({value, results: this.state.channels});
}
const re = new RegExp(_.escapeRegExp(this.state.value), 'i');
const isMatch = (result) => re.test(result.name);
this.setState({
results: _.filter(this.state.channels, isMatch),
});
}, 300);
};
render() {
let header = (
<Grid columns={2} style={{marginBottom: '1em'}}>
<Grid.Column>
<Header as='h1'>Channels</Header>
</Grid.Column>
<Grid.Column textAlign='right'>
<Form onSubmit={this.handleSearch}>
<Input
icon='search'
placeholder='Name filter...'
size="large"
name="filterStr"
value={this.state.value}
onChange={this.handleSearchChange}/>
</Form>
</Grid.Column>
<NewChannelButton/>
</Grid>
);
let tableHeader = (
<Table.Header>
<Table.Row>
<Table.HeaderCell width={8}>Name</Table.HeaderCell>
<Table.HeaderCell width={2}>Videos</Table.HeaderCell>
<Table.HeaderCell width={2}>Last Update</Table.HeaderCell>
<Table.HeaderCell width={2}>Next Update</Table.HeaderCell>
<Table.HeaderCell width={2}>Frequency</Table.HeaderCell>
<Table.HeaderCell width={2} colSpan={3} textAlign='center'>Manage</Table.HeaderCell>
</Table.Row>
</Table.Header>
);
let body;
if (this.state.channels === null) {
// Placeholders while fetching
body = <Table striped basic size='large'>
{tableHeader}
<Table.Body>
<Table.Row>
<Table.Cell><ChannelPlaceholder/></Table.Cell>
<Table.Cell/>
<Table.Cell/>
<Table.Cell/>
</Table.Row>
</Table.Body>
</Table>
} else if (this.state.channels.length === 0) {
body = <Message>
<Message.Header>No channels exist yet!</Message.Header>
<Message.Content><Link to='/videos/channel/new'>Create one.</Link></Message.Content>
</Message>
} else {
body = (
<>
<Responsive minWidth={770}>
<Table striped basic size='large'>
{tableHeader}
<Table.Body>
{this.state.results.map((channel) => <ChannelRow key={channel.link}
channel={channel}/>)}
</Table.Body>
</Table>
</Responsive>
<Responsive maxWidth={769}>
<Table striped basic unstackable size='medium'>
<Table.Body>
{this.state.results.map((channel) =>
<MobileChannelRow key={channel.link} channel={channel}/>)}
</Table.Body>
</Table>
</Responsive>
</>
)
}
return (
<>
{header}
{body}
</>
)
}
}

View file

@ -0,0 +1,462 @@
import React from "react";
import {Card, Container, Image, Pagination, Progress} from 'semantic-ui-react';
import {Link} from "react-router-dom";
export const API_URI = `http://${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 DEFAULT_LIMIT = 20;
export default class Paginator extends React.Component {
state = {
boundaryRange: 1,
siblingRange: 2,
showEllipsis: true,
showFirstAndLastNav: false,
showPreviousAndNextNav: true,
}
handlePaginationChange = (e, {activePage}) => {
this.props.changePage(activePage);
}
render() {
const {
boundaryRange,
siblingRange,
showEllipsis,
showFirstAndLastNav,
showPreviousAndNextNav,
} = this.state;
return (
<Pagination
activePage={this.props.activePage}
boundaryRange={boundaryRange}
onPageChange={this.handlePaginationChange}
size='mini'
siblingRange={siblingRange}
totalPages={this.props.totalPages}
// Heads up! All items are powered by shorthands, if you want to hide one of them, just pass `null` as value
ellipsisItem={showEllipsis ? undefined : null}
firstItem={showFirstAndLastNav ? undefined : null}
lastItem={showFirstAndLastNav ? undefined : null}
prevItem={showPreviousAndNextNav ? undefined : null}
nextItem={showPreviousAndNextNav ? undefined : null}
/>
)
}
}
export function secondsToDuration(video) {
let duration = video.duration;
let hours = Math.floor(duration / 3600);
duration -= hours * 3600;
let minutes = Math.floor(duration / 60);
let seconds = duration - (minutes * 60);
hours = String('00' + hours).slice(-2);
minutes = String('00' + minutes).slice(-2);
seconds = String('00' + seconds).slice(-2);
return [hours, minutes, seconds];
}
export function Duration({video}) {
let [hours, minutes, seconds] = secondsToDuration(video);
if (hours > 0) {
return <div className="duration-overlay">{hours}:{minutes}:{seconds}</div>
} else if (video.duration) {
return <div className="duration-overlay">{minutes}:{seconds}</div>
} else {
return <></>
}
}
export function uploadDate(d) {
// Convert a date integer to a human readable date format.
let upload_date = <></>;
if (d) {
upload_date = new Date(d * 1000);
upload_date = `${upload_date.getFullYear()}-${upload_date.getMonth() + 1}-${upload_date.getDate()}`;
}
return upload_date;
}
export function VideoCard({video}) {
let channel = video.channel;
let channel_url = `/videos/channel/${channel.link}/video`;
let upload_date = uploadDate(video.upload_date);
let video_url = `/videos/channel/${channel.link}/video/${video.id}`;
let poster_url = video.poster_path ? `/media/${channel.directory}/${encodeURIComponent(video.poster_path)}` : null;
return (
<Card style={{'width': '18em', 'margin': '1em'}}>
<Link to={video_url}>
<Image src={poster_url} wrapped style={{position: 'relative', width: '100%'}}/>
</Link>
<Duration video={video}/>
<Card.Content>
<Card.Header>
<Container textAlign='left'>
<Link to={video_url} className="no-link-underscore video-card-link">
<p>{video.title || video.video_path}</p>
</Link>
</Container>
</Card.Header>
<Card.Description>
<Container textAlign='left'>
<Link to={channel_url} className="no-link-underscore video-card-link">
<b>{channel.name}</b>
</Link>
<p>{upload_date}</p>
</Container>
</Card.Description>
</Card.Content>
</Card>
)
}
export class VideoCards extends React.Component {
render() {
return (
<Card.Group>
{this.props.videos.map((v) => {
return <VideoCard key={v['id']} video={v}/>
})}
</Card.Group>
)
}
}
export function RequiredAsterisk() {
return <span style={{color: '#db2828'}}> *</span>
}
export let defaultVideoOrder = '-upload_date';
export let defaultSearchOrder = 'rank';
export let videoOrders = [
{key: '-upload_date', value: '-upload_date', text: 'Newest', title: 'Newest Videos'},
{key: 'upload_date', value: 'upload_date', text: 'Oldest', title: 'Oldest Videos'},
{key: '-duration', value: '-duration', text: 'Longest', title: 'Longest Videos'},
{key: 'duration', value: 'duration', text: 'Shortest', title: 'Shortest Videos'},
{key: '-viewed', value: '-viewed', text: 'Recently viewed', title: 'Recently Viewed Videos'},
{key: '-size', value: '-size', text: 'Largest', title: 'Largest Videos'},
{key: 'size', value: 'size', text: 'Smallest', title: 'Smallest Videos'},
{key: '-view_count', value: '-view_count', text: 'Most Views', title: 'Most Views'},
{key: 'view_count', value: 'view_count', text: 'Least Views', title: 'Least Views'},
];
export let searchOrders = [
{key: 'rank', value: 'rank', text: 'Search Rank', title: 'Search Results'},
];
export const frequencyOptions = [
{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 function secondsToFrequency(seconds) {
for (let i = 0; i < Object.keys(frequencyOptions).length; i++) {
let d = frequencyOptions[i];
if (d.value === seconds) {
return d.text;
}
}
return null;
}
const secondsToYears = 31536000;
const secondsToDays = 86400;
const secondsToHours = 3600;
const secondsToMinutes = 60;
export function secondsToString(seconds) {
let s = '';
let numYears = Math.floor(seconds / secondsToYears);
if (numYears) {
s = `${numYears}Y`;
seconds -= numYears * secondsToYears;
}
let numDays = Math.floor(seconds / secondsToDays);
if (numDays) {
s = `${s} ${numDays}D`;
seconds -= numDays * secondsToDays;
}
let numHours = Math.floor(seconds / secondsToHours);
if (numHours) {
seconds -= numHours * secondsToHours;
}
let numMinutes = Math.floor(seconds / secondsToMinutes);
s = `${s} ${numHours}:${numMinutes}H`;
return s;
}
export function secondsToDate(seconds) {
let date = new Date(seconds * 1000);
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
export function humanFileSize(bytes, si = false, dp = 1) {
const thresh = si ? 1000 : 1024;
if (Math.abs(bytes) < thresh) {
return bytes + ' B';
}
const units = si
? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
let u = -1;
const r = 10 ** dp;
do {
bytes /= thresh;
++u;
} while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);
return bytes.toFixed(dp) + ' ' + units[u];
}
export class APIForm extends React.Component {
constructor(props) {
super(props);
this.state = {
dirty: false,
disabled: false,
error: false,
loading: false,
message_content: '',
message_header: '',
success: false,
}
}
setError = (header, content, errorName) => {
let errors = {...this.state.errors};
if (errorName) {
errors[errorName] = true;
}
this.setState({
error: true,
errors: errors,
message_content: content,
message_header: header,
success: false,
});
}
setSuccess = (header, content) => {
this.setState({
error: false,
message_content: content,
message_header: header,
success: true,
});
}
initFormValues = (original) => {
// Set the "original" values in state to the provided values. This will be used to compare against any form
// changes.
let inputs = {};
let errors = {};
let inputKeys = Object.keys(this.state.inputs);
for (let i = 0; i < inputKeys.length; i++) {
let key = inputKeys[i];
inputs[key] = original[key] || '';
errors[key] = false;
}
this.setState({original: {...original}, inputs: inputs, errors: errors});
}
isDirty = () => {
// Compare dictionaries "inputs" and "original". "original" should never change once it is set.
let inputKeys = Object.keys(this.state.inputs);
for (let i = 0; i < inputKeys.length; i++) {
let name = inputKeys[i];
if (!this.state.original && this.state.inputs[name]) {
// Form has changed from it's empty value.
return true;
} else if (this.state.original && this.state.original[name] !== this.state.inputs[name]) {
// Form has changed from it's initial value.
return true;
}
}
return false;
}
checkDirty = () => {
this.setState({dirty: this.isDirty()})
}
getEmptyErrors = () => {
let errors = {};
let inputKeys = Object.keys(this.state.inputs);
for (let i = 0; i < inputKeys.length; i++) {
let key = inputKeys[i];
errors[key] = false;
}
return errors;
}
setLoading = () => {
this.setState({
disabled: true,
error: false,
errors: this.getEmptyErrors,
loading: true,
success: false,
})
}
clearLoading = () => {
this.setState({
disabled: false,
loading: false,
})
}
handleInputChange = async (event, {name, value}) => {
let inputs = this.state.inputs;
inputs[name] = value;
this.setState({inputs: inputs}, this.checkDirty);
}
handleCheckbox = async (checkbox) => {
let checked = checkbox.current.state.checked;
let name = checkbox.current.props.name;
let inputs = this.state.inputs;
inputs[name] = !checked;
this.setState({inputs: inputs}, this.checkDirty);
}
}
export class Progresses extends React.Component {
constructor(props) {
super(props);
this.state = {
progresses: [],
}
this.socket = null;
}
componentDidMount() {
this.socket = new WebSocket(this.props.streamUrl);
this.socket.onmessage = this.handleMessage;
}
handleMessage = async (e) => {
let data = await JSON.parse(e.data);
if (data.progresses) {
let progresses = [];
for (let i = 0; i < data.progresses.length; i++) {
let progress = data.progresses[i];
// Add a key to each progress.
progress.key = i;
if (progress.percent === 100) {
progress.active = false;
progress.success = true;
} else {
progress.active = true;
progress.success = false;
}
progresses = progresses.concat([progress]);
}
this.setState({progresses: progresses});
}
}
render() {
return <>
{this.state.progresses.map((i) =>
<Progress
progress='ratio'
key={i.key}
active={i.active}
success={i.success}
total={i.total}
value={i.value}
>{i.message || ''}</Progress>
)}
</>
}
}
export function replaceNullValues(obj, newValue) {
newValue = newValue === undefined ? '' : newValue;
let keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
obj[key] = obj[key] === null ? newValue : obj[key];
}
}
export function enumerate(array) {
let newArray = [];
for (let i = 0; i < array.length; i++) {
newArray = newArray.concat([[i, array[i]]]);
}
return newArray;
}
export function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length !== b.length) return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
export function scrollToTop() {
window.scrollTo({
top: 0,
behavior: "auto"
});
}
export function changePageHistory(history, location, activePage, searchStr, searchOrder) {
let search = `?page=${activePage}`;
if (searchStr) {
search = `${search}&q=${searchStr}`;
}
if (searchOrder) {
search = `${search}&o=${searchOrder}`;
}
history.push({
pathname: location.pathname,
search: search,
});
scrollToTop();
}
export function objectToQuery(d) {
// Return an HTTP query string based on the provided dictionary.
// Do not include key/values when the value is null if noNull=true
let arr = Object.keys(d).map((k) => d[k] === null ? '' : `${k}=${d[k]}`);
arr = arr.filter((i) => i !== '')
return arr.join('&');
}

File diff suppressed because it is too large Load diff

96
app/src/components/Nav.js Normal file
View file

@ -0,0 +1,96 @@
import React from "react";
import {NavLink} from "react-router-dom";
import {Dropdown, Menu, Responsive} from "semantic-ui-react";
const responsiveWidth = 500;
const links = [
{
text: 'Videos', links: [
{to: '/videos', text: 'Newest Videos', exact: true},
{to: '/videos/favorites', text: 'Favorites', exact: true},
{to: '/videos/channel', text: 'Channels', exact: true},
{to: '/videos/manage', text: 'Manage', exact: true},
]
},
{text: 'Inventory', to: '/inventory', exact: true},
{text: 'Archive', to: '/archive', exact: true},
{
text: 'Apps', links: [
{to: '/apps/otp', text: 'One Time Pad', exact: true},
]
},
];
const admin = {to: '/admin', text: 'Admin', exact: true};
const rightLinks = [admin,];
const collapsedLinks = links.concat([admin,]);
function DropdownLinks(props) {
return (
<Dropdown item text={props.link.text}>
<Dropdown.Menu>
{props.link.links.map((l) => {
return (
<Link key={l.to} link={l}/>
)
})}
</Dropdown.Menu>
</Dropdown>
)
}
function Link(props) {
let classes = 'item';
if (props.link.header) {
classes = `${classes} header`;
}
if (!props.link.links) {
return (
<NavLink
className={classes}
exact={props.link.exact || false}
to={props.link.to}
>
{props.link.text}
</NavLink>
)
} else {
return (
<DropdownLinks link={props.link}/>
)
}
}
export function NavBar() {
return (
<Menu>
{/*Always show WROLPi home button*/}
<Link link={{to: '/', text: 'WROLPi', exact: true}}/>
{/*Show the links in a menu when on desktop*/}
{links.map((link) => {
return (
<Responsive minWidth={responsiveWidth} as={Link} link={link} key={link.to}/>
)
})}
<Responsive minWidth={responsiveWidth} as={Menu.Menu} position="right">
{rightLinks.map((link) => {
return (<Link link={link} key={link.to}/>)
})}
</Responsive>
{/*Show the menu items in a dropdown when on mobile*/}
<Responsive as={Menu.Menu} maxWidth={responsiveWidth - 1} position='right'>
<Dropdown item icon="bars">
<Dropdown.Menu>
{collapsedLinks.map((link) => {
return (<Link link={link} key={link.to}/>)
})}
</Dropdown.Menu>
</Dropdown>
</Responsive>
</Menu>
)
}

View file

@ -0,0 +1,51 @@
import {Card, Placeholder} from "semantic-ui-react";
import React from "react";
export function VideoPlaceholder() {
return (
<Card.Group doubling stackable>
<Card>
<Placeholder>
<Placeholder.Image rectangular/>
</Placeholder>
<Card.Content>
<Placeholder>
<Placeholder.Line/>
<Placeholder.Line/>
<Placeholder.Line/>
</Placeholder>
</Card.Content>
</Card>
</Card.Group>
)
}
export function ChannelPlaceholder() {
return (
<Placeholder>
<Placeholder.Line length='long'/>
<Placeholder.Line length='short'/>
</Placeholder>
)
}
export function ArchivePlaceholder() {
return (
<Card.Group doubling stackable>
<Card>
<Placeholder>
<Placeholder.Image rectangular/>
</Placeholder>
<Card.Content>
<Placeholder>
<Placeholder.Line/>
<Placeholder.Line/>
</Placeholder>
<Placeholder style={{height: 40, width: 40}}>
<Placeholder.Image rectangular/>
</Placeholder>
</Card.Content>
</Card>
</Card.Group>
)
}

View file

@ -0,0 +1,165 @@
import React, {useState} from 'react';
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {deleteVideo, favoriteVideo} from "../api";
import Button from "semantic-ui-react/dist/commonjs/elements/Button";
import {Link} from "react-router-dom";
import {humanFileSize, uploadDate, VideoCard} from "./Common";
import {Confirm, Container, Segment, Tab} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
const MEDIA_PATH = '/media';
function VideoPage(props) {
let video = props.video;
let channel = video.channel;
let [deleteOpen, setDeleteOpen] = useState(false);
async function handleDeleteVideo(video_id) {
try {
await deleteVideo(video_id)
} catch (e) {
setDeleteOpen(false);
throw e;
}
props.history.goBack();
}
let videoUrl = `${MEDIA_PATH}/${channel.directory}/${encodeURIComponent(video.video_path)}`;
let posterUrl = null;
if (video.poster_path) {
posterUrl = `${MEDIA_PATH}/${channel.directory}/${encodeURIComponent(video.poster_path)}`;
}
let captionsUrl = null;
if (video.caption_path) {
captionsUrl = `${MEDIA_PATH}/${channel.directory}/${encodeURIComponent(video.caption_path)}`;
}
let description = 'No description available.';
let viewCount = null;
if (video.info_json) {
description = video.info_json['description'];
viewCount = video.info_json['view_count'];
}
let [favorite, setFavorite] = React.useState(video.favorite);
let handleFavorite = async (e) => {
e.preventDefault();
let new_favorite = await favoriteVideo(video.id, !!!favorite);
setFavorite(new_favorite);
}
let favorite_button;
if (favorite) {
favorite_button = (
<Button color='green' style={{'margin': '0.5em'}}
onClick={handleFavorite}>
<Icon name='heart'/>
Unfavorite
</Button>
);
} else {
favorite_button = (
<Button basic color='green' style={{'margin': '0.5em'}}
onClick={handleFavorite}>
<Icon name='heart'/>
Favorite
</Button>
);
}
let descriptionPane = {
menuItem: 'Description', render: () => <Tab.Pane>
<pre className="wrap-text">
{description}
</pre>
</Tab.Pane>
};
let statisticsPane = {
menuItem: 'Statistics', render: () => <Tab.Pane>
<h3>Size</h3>
<p>{humanFileSize(video.size)}</p>
<h3>Source ID</h3>
<p>{video.source_id}</p>
<h3>View Count</h3>
<p>{viewCount}</p>
<h3>File Name</h3>
<pre style={{backgroundColor: '#ccc', padding: '0.4em'}}>{video.channel.directory}/{video.video_path}</pre>
</Tab.Pane>
}
let tabPanes = [descriptionPane, statisticsPane];
return (
<Container textAlign='left' style={{marginTop: '2em'}}>
<Button
style={{marginTop: '1em', marginBottom: '1em'}}
onClick={() => props.history.goBack()}
>
<Icon name='left arrow'/>
Back
</Button>
<Segment>
<video controls
autoPlay={props.autoplay !== undefined ? props.autoplay : true}
poster={posterUrl}
id="player"
playsInline={true}
style={{maxWidth: '100%'}}
>
<source src={videoUrl} type="video/mp4"/>
<track kind="captions" label="English captions" src={captionsUrl} srcLang="en" default/>
</video>
<h2>{video.title}</h2>
{video.upload_date && <h3>{uploadDate(video.upload_date)}</h3>}
<h3>
<Link to={`/videos/channel/${channel.link}/video`}>
{channel.name}
</Link>
</h3>
<p>
{favorite_button}
<a href={videoUrl}>
<Button style={{margin: '0.5em'}}>
<Icon name='download'/>
Download
</Button>
</a>
<Button
color='red'
onClick={() => setDeleteOpen(true)}
style={{margin: '0.5em'}}
>Delete</Button>
<Confirm
open={deleteOpen}
content='Are you sure you want to delete this video? All files related to this video will be deleted. It will not be downloaded again!'
confirmButton='Delete'
onCancel={() => setDeleteOpen(false)}
onConfirm={() => handleDeleteVideo(video.id)}
/>
</p>
</Segment>
<Tab panes={tabPanes}/>
<Grid columns={2} stackable>
<Grid.Row>
<Grid.Column textAlign='left'>
{props.prev && <><h3>Older</h3><VideoCard video={props.prev}/></>}
</Grid.Column>
<Grid.Column textAlign='left'>
{props.next && <><h3>Newer</h3><VideoCard video={props.next}/></>}
</Grid.Column>
</Grid.Row>
</Grid>
</Container>
)
}
export default VideoPage;

View file

@ -0,0 +1,547 @@
import React from 'react';
import {Link, Route} from "react-router-dom";
import Paginator, {
changePageHistory,
DEFAULT_LIMIT,
defaultSearchOrder,
defaultVideoOrder,
humanFileSize,
Progresses,
scrollToTop,
searchOrders,
secondsToString,
uploadDate,
VideoCards,
videoOrders
} from "./Common"
import VideoPage from "./VideoPlayer";
import {download, downloadHistory, getChannel, getStatistics, getVideo, refresh, searchVideos} from "../api";
import {Button, Dropdown, Form, Grid, Header, Icon, Input, Loader, Segment, Statistic, Tab} from "semantic-ui-react";
import * as QueryString from 'query-string';
import Container from "semantic-ui-react/dist/commonjs/elements/Container";
import {Channels, EditChannel, NewChannel} from "./Channels";
import {VideoPlaceholder} from "./Placeholder";
class ManageVideos extends React.Component {
constructor(props) {
super(props);
this.state = {
streamUrl: null,
downloadHistory: null,
mostRecentDownload: '',
}
}
async componentDidMount() {
await this.downloadHistory();
}
download = async (e) => {
e.preventDefault();
let response = await download();
if (response.stream_url) {
this.setState({streamUrl: response.stream_url});
}
}
refresh = async (e) => {
e.preventDefault();
let response = await refresh();
if (response.stream_url) {
this.setState({streamUrl: response.stream_url});
}
}
async downloadHistory() {
let response = await downloadHistory();
if (response && response.history.length > 0) {
let history = response.history;
let mostRecentDownload = uploadDate(history[0]['info_date']);
this.setState({downloadHistory: history, mostRecentDownload: mostRecentDownload});
}
}
render() {
return (
<Container>
<Header as="h1">Manage Videos</Header>
<p>
<Button primary
onClick={this.download}
>
Download Videos
</Button>
<label>Download any missing videos</label>
<br/>
Most recent download: {this.state.mostRecentDownload}
</p>
<p>
<Button secondary
onClick={this.refresh}
>
Refresh Video Files
</Button>
<label>Search for any videos in the media directory</label>
</p>
{this.state.streamUrl && <Progresses streamUrl={this.state.streamUrl}/>}
</Container>
)
}
}
export class VideoWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
video: null,
prev: null,
next: null,
channel: null,
}
}
async componentDidMount() {
await this.fetchVideo();
}
async fetchVideo() {
// Get and display the Video specified in the Router match
let [video, prev, next] = await getVideo(this.props.match.params.video_id);
let channel = await getChannel(this.props.match.params.channel_link);
this.setState({video, prev, next, channel}, scrollToTop);
}
async componentDidUpdate(prevProps, prevState) {
if (prevProps.match.params.video_id !== this.props.match.params.video_id) {
// Clear the current video so that it will change, even if the video is playing.
this.setState({video: null, prev: null, next: null, channel: null});
await this.fetchVideo();
}
}
render() {
if (this.state.video && this.state.channel) {
return <VideoPage {...this.state} history={this.props.history} autoplay={true}/>
} else {
return <VideoPlaceholder/>
}
}
}
class VideosPreview extends React.Component {
constructor(props) {
super(props);
this.state = {
videos: null,
};
}
async componentDidMount() {
await this.fetchVideos();
}
render() {
let header = <h2>{this.title}</h2>;
let body = <VideoPlaceholder/>
if (this.state.videos && this.state.videos.length === 0) {
body = <p>No videos available.</p>
} else if (this.state.videos && this.state.videos.length > 0) {
body = <VideoCards videos={this.state.videos}/>
}
return <>
{header}
{body}
</>
}
}
export class FavoriteVideosPreview extends VideosPreview {
constructor(props) {
super(props);
this.title = 'Favorite Videos'
}
async fetchVideos() {
let [videos] = await searchVideos(
0, 3, null, null, true, '-favorite');
this.setState({videos});
}
}
export class ViewedVideosPreview extends VideosPreview {
constructor(props) {
super(props);
this.title = 'Recently Viewed Videos'
}
async fetchVideos() {
let [videos] = await searchVideos(
0, 3, null, null, null, '-viewed');
this.setState({videos});
}
}
class Videos extends React.Component {
constructor(props) {
super(props);
const query = QueryString.parse(this.props.location.search);
let activePage = query.page ? parseInt(query.page) : 1; // First page is 1 by default, of course.
let searchStr = query.q || '';
let searchOrder = query.o || defaultVideoOrder;
this.state = {
channel: null,
videos: null,
queryStr: searchStr,
searchStr: '',
limit: DEFAULT_LIMIT,
activePage: activePage,
totalPages: null,
prev: null,
next: null,
videoOrders: searchStr === '' ? videoOrders : searchOrders,
searchOrder: searchOrder,
title: '',
};
}
async componentDidMount() {
if (this.props.match.params.channel_link) {
await this.fetchChannel();
} else {
await this.fetchVideos();
}
this.setTitle();
}
async componentDidUpdate(prevProps, prevState, snapshot) {
let params = this.props.match.params;
let channelChanged = params.channel_link !== prevProps.match.params.channel_link;
let pageChanged = (
prevState.activePage !== this.state.activePage ||
prevState.searchOrder !== this.state.searchOrder ||
prevState.queryStr !== this.state.queryStr
);
if (channelChanged) {
await this.fetchChannel();
} else if (pageChanged) {
this.applyStateToHistory();
await this.fetchVideos();
}
}
setTitle() {
let title = '';
if (this.props.filter === 'favorites') {
title = 'Favorite Videos';
} else if (this.state.channel) {
title = this.state.channel.name;
} else {
// Find the matching title from the search orders.
for (let i = 0; i < this.state.videoOrders.length; i++) {
let item = this.state.videoOrders[i];
if (item.value === this.state.searchOrder) {
title = item.title;
}
}
}
this.setState({title: title});
}
async fetchChannel() {
// Get and display the channel specified in the Router match
let channel_link = this.props.match.params.channel_link;
let channel = null;
if (channel_link) {
channel = await getChannel(channel_link);
}
this.setState({
channel,
title: channel ? channel.title : '',
offset: 0,
total: null,
videos: null,
video: null,
},
this.fetchVideos);
}
async fetchVideos() {
let offset = this.state.limit * this.state.activePage - this.state.limit;
let channel_link = this.state.channel ? this.state.channel.link : null;
let favorites = this.props.filter !== undefined ? this.props.filter === 'favorites' : null;
let [videos, total] = await searchVideos(
offset, this.state.limit, channel_link, this.state.queryStr, favorites, this.state.searchOrder);
let totalPages = Math.round(total / this.state.limit) || 1;
this.setState({videos, totalPages});
}
changePage = async (activePage) => {
this.setState({activePage});
}
clearSearch = async () => {
this.setState({searchStr: '', queryStr: '', searchOrder: defaultVideoOrder, activePage: 1});
}
applyStateToHistory = () => {
let {history, location} = this.props;
let {activePage, queryStr, searchOrder} = this.state;
changePageHistory(history, location, activePage, queryStr, searchOrder);
}
handleSearch = async (e) => {
e && e.preventDefault();
this.setState({activePage: 1, searchOrder: defaultSearchOrder, queryStr: this.state.searchStr},
this.applyStateToHistory);
}
handleInputChange = (event, {name, value}) => {
this.setState({[name]: value});
}
changeSearchOrder = (event, {value}) => {
this.setState({searchOrder: value, activePage: 1}, this.applyStateToHistory);
}
render() {
let {
activePage,
channel,
queryStr,
searchOrder,
searchStr,
title,
totalPages,
videoOrders,
videos,
} = this.state;
let body = <VideoPlaceholder/>;
if (videos && videos.length === 0) {
// API didn't send back any videos, tell the user what to do.
if (this.props.filter === 'favorites') {
body = <p>You haven't tagged any videos as favorite.</p>;
} else {
// default empty body.
body = <p>No videos retrieved. Have you downloaded videos yet?</p>;
}
} else if (videos) {
body = <VideoCards videos={videos}/>;
}
let pagination = null;
if (totalPages) {
pagination = (
<div style={{marginTop: '3em', textAlign: 'center'}}>
<Paginator
activePage={activePage}
changePage={this.changePage}
totalPages={totalPages}
/>
</div>
);
}
let clearSearchButton = (
<Button icon labelPosition='right' onClick={this.clearSearch}>
Search: {queryStr}
<Icon name='close'/>
</Button>
);
return (
<Container textAlign='center'>
<Grid columns={3} stackable>
<Grid.Column textAlign='left'>
<h1>
{title}
{
channel &&
<>
&nbsp;
&nbsp;
<Link to={`/videos/channel/${channel.link}/edit`}>
<Icon name="edit"/>
</Link>
</>
}
</h1>
{queryStr && clearSearchButton}
</Grid.Column>
<Grid.Column textAlign='right'>
<Form onSubmit={this.handleSearch}>
<Input
fluid
icon='search'
placeholder='Search...'
name="searchStr"
value={searchStr}
onChange={this.handleInputChange}/>
</Form>
</Grid.Column>
<Grid.Column>
<Dropdown
size='large'
placeholder='Sort by...'
selection
fluid
name='searchOrder'
onChange={this.changeSearchOrder}
value={searchOrder}
options={videoOrders}
disabled={searchOrder === defaultSearchOrder}
/>
</Grid.Column>
</Grid>
<Container textAlign='center'>
{body}
</Container>
{pagination}
</Container>
)
}
}
class ManageTabs extends React.Component {
render() {
const panes = [
{menuItem: 'Manage', render: () => <Tab.Pane><ManageVideos/></Tab.Pane>},
{menuItem: 'Statistics', render: () => <Tab.Pane><Statistics/></Tab.Pane>},
]
return (
<Container>
<Tab panes={panes}/>
</Container>
)
}
}
export class VideosRoute extends React.Component {
render() {
return (
<>
<Container fluid={true} style={{margin: '2em', padding: '0.5em'}}>
<Route path='/videos' exact
component={(i) =>
<Videos
match={i.match}
history={i.history}
location={i.location}
/>}
/>
<Route path='/videos/favorites' exact
component={(i) =>
<Videos
match={i.match}
history={i.history}
location={i.location}
filter='favorites'
/>
}/>
<Route path='/videos/channel' exact component={Channels}/>
<Route path='/videos/manage' exact component={ManageTabs}/>
<Route path='/videos/channel/new' exact component={NewChannel}/>
<Route path='/videos/channel/:channel_link/edit' exact
component={(i) =>
<EditChannel
match={i.match}
history={i.history}
/>
}
/>
<Route path='/videos/channel/:channel_link/video' exact component={Videos}/>
<Route path='/videos/statistics' exact component={Statistics}/>
</Container>
</>
)
}
}
class Statistics extends React.Component {
constructor(props) {
super(props);
this.state = {
videos: null,
historical: null,
channels: null,
};
this.videoNames = [
{key: 'videos', label: 'Downloaded Videos'},
{key: 'favorites', label: 'Favorite Videos'},
{key: 'sum_size', label: 'Total Size'},
{key: 'max_size', label: 'Largest Video'},
{key: 'week', label: 'Downloads Past Week'},
{key: 'month', label: 'Downloads Past Month'},
{key: 'year', label: 'Downloads Past Year'},
{key: 'sum_duration', label: 'Total Duration'},
];
this.historicalNames = [
{key: 'average_count', label: 'Average Monthly Downloads'},
{key: 'average_size', label: 'Average Monthly Usage'},
];
this.channelNames = [
{key: 'channels', label: 'Channels'},
];
}
async componentDidMount() {
await this.fetchStatistics();
}
async fetchStatistics() {
let stats = await getStatistics();
stats.videos.sum_duration = secondsToString(stats.videos.sum_duration);
stats.videos.sum_size = humanFileSize(stats.videos.sum_size, true);
stats.videos.max_size = humanFileSize(stats.videos.max_size, true);
stats.historical.average_size = humanFileSize(stats.historical.average_size, true);
this.setState({...stats});
}
buildSegment(title, names, stats) {
return <Segment secondary>
<Header textAlign='center' as='h1'>{title}</Header>
<Statistic.Group>
{names.map(
({key, label}) =>
<Statistic key={key} style={{margin: '2em'}}>
<Statistic.Value>{stats[key]}</Statistic.Value>
<Statistic.Label>{label}</Statistic.Label>
</Statistic>
)}
</Statistic.Group>
</Segment>
}
render() {
if (this.state.videos) {
return (
<>
{this.buildSegment('Videos', this.videoNames, this.state.videos)}
{this.buildSegment('Historical Video', this.historicalNames, this.state.historical)}
{this.buildSegment('Channels', this.channelNames, this.state.channels)}
</>
)
} else {
return <Loader active inline='centered'/>
}
}
}