Fixing JS warnings.

Handling all combinations of toggle in light and dark.

Changing CPUUsageProgress colors to be more readable in dark mode.

Moving theme handling into Theme.js.  Importing element wrappers from Theme.js to handle element theming.

Changing video menu to dark mode.

Creating ThemeContext to share Dark Mode setting.

Removing duplicate code for search functions.

Displaying X when downloads are disabled.

Using react context to share settings across components.

Refusing to start workers when WROL Mode is enabled.

Changing warning to debug.

Queuing recurring downloads first.

Adding Video.url index.

Adding special handling for youtube shorts to videos.

Reworking Downloads to have one worker per process.

Testing creating downloads and getting downloaders.

Testing video validation and poster generation.  Testing video statistics.

Increasing inventory test coverage.

Adding pytest.ini to automatically detect async test.

Adding more archive test coverage.

Testing Archive CRUD.

Catching and logging when encountering error during indexing.

Using FileIcon when Archive has no screenshot.

A Video will be assigned to a Channel by its info json first, then to its directory.

Including suffix in File json.

Adding index for File.suffix.

Gathering suffix during indexing.

Passing entire file down to FileIcon.

Moving logging up.

Returning File.associated in file json.

Associated files are last in file search.

Removing duplicate refreshing code by creating new _refresh_directory function.

Changing File.idempotency to a datetime to avoid having to clear idempotency.

Truncating indexes to avoid error with large files.

Don't overwrite video data when info json is empty.

Using already_downloaded for channel videos.

Awaiting refresh in Channel.refresh.

Testing that videos already downloaded aren't downloaded again.

Adding indexes for video/archive referenced paths.

Changing grid width for mobile or computer.

Adding button to refresh specific directories.

Restoring Channel edit link.

Fixing caption path in video_modeler.

Adding ZIP files to mimetype colors.

Using model instead of first file's model.

Fetching File models in batches to avoid issuing a SELECT for every File with a model.

Flushing generated poster file.

Getting Channel in VideoPage, relying on Video.channl_id, falling back to URL's channel_id.

Attaching Video to it's Channel during download.

Using ExternalCardLink for ArchivePage singlefile link.

Validating and indexing videos after download.

Handling glob when file name contains matching characters.

Reworking and testing split_path_stem_and_suffix and glob_shared_stem.

Adding associated video files to DB during upsert.

Adding pending downloads to dashboard.

Hiding status when download is open.

Handling when load is empty.

Adding load statistics to Dashboard.

Limiting concurrent after_refresh functions.

Handling when no onSelect is declared.

Adding ImageRow for FileTable.

Moving image date into Card.Meta.

Using ExternalLink for FileCard.

Using ExternalLink for ImageCard.

Handling when error occurs during refresh of a directory.  Committing during refresh to avoid losing all files if an error occurs.

Removing api health check to avoid spamming logs.

Creating ImageCard to display image posters when they aren't too large.

Removing archive.domain_id not null.

Reworking file refresh to process all files in a single directory.

Bumping version for major file rework.

No longer checking for video corruption.

Adding duration by default to speed up tests.

Using register_indexer for all indexers.

Adding CPU usage progress bar in Welcome.

Modifying TextIndexer to ignore large text files.

Counting all files during refresh.

Adding refresh_logger to clarify logging.  Checking for wrol_mode before refresh functions.

Removing unused idempotency from video/channel tables.

Using magic module to speed up mimetype identification.

All tests pass.

Archive tests pass.

Changing video get endpoint to return 'file' to avoid ambiguity.

Video tests pass.

Simplifying regex filtering.

Using regex to ignore case when filtering.

Converting all channel classes to functions.

Restoring channel refresh and download buttons.

Matching format of Archive and Video pages.

Adding sorting to Archives search.

Reworking video orders for file search.  Using SearchInput for videos search.

Archives can be searched on the Archives page.  Domains can be filtered.

Reworking Archive search to use Files.  Videos, Archives and Global search use the FilesView.

Videos are claimed by their Channel based on the Channel's directory.  Prev and Next video cards are displayed on the VideoPage.

Creating useVideo for reworked VideoWrapper and VideoPage.

Adding Paginator to FilesView.

Moving file refresh button out of manage tab.  Removing Files page tabs.  Limiting refresh to one at a time.

Adding class for card icon to match poster height.

Video and Archives always re-claim their files on refresh.

Archive files are indexed and claimed.

FileView table is compact and striped.

Videos page uses FileView.

Updated navlinks to router v6.

Removing ! character from file names.

Disabling select button when cards are visible.

Adding show/hide button for FileTable selection.

The Archive Page is displayed.

Adding mimetype dropdown.

Upgrading to React Router v6 for useSearchParams.

Validating video during modeling.  Removing screenshot during corruption check because it was very slow.  Updating app to use video files as search results.

Updating video search to return Files.

Video and WROLPi tests pass.

Creating function to refresh files within a channel's directory.

Removing troubleshooting print.  Updating result order in test.

Reworking video_factory to handle a specific video file location.

Returning video model on file search.

Getting session using video_file.

Screenshotting when checking for video corruption.

Reducing ffmpeg calls by gathering duration during poster generation.

Moving video file matching into model.

VideoIndexer is moved into video module.  Video files are validated.

Moving files module into wrolpi in preparation to use it in modules.

Title and contents are indexed for text file.

Files are indexed on refresh by using their indexer.

Zip files are indexed using their contents.

Testing multiple zip files.

Adding unique to file.path.  Checking that the correct indexer is used.

Adding index to file.modification_datetime and file.size.

Handling file info gathering in File.do_index.  Only reading contents of file if file.indexed is False.

Video model is found during file refresh.  A Video record is created that has the associated files.

Videos without associated files are found.

Videos are found using registered video_modeler() rather than in refresh code.

Removing old video columns.

Handling video info json files.

Trying to import each module individually.  Will continue to import modules even if one fails.

Reworking refresh so it performs less DB calls.

Converting file.path to primary key.

file.path is always a pathlib.Path.

Updating video_factory to use new file system, testing it.

Bump sanic from 21.9.1 to 21.12.2 in /docker/archive

Bumps [sanic](https://github.com/sanic-org/sanic) from 21.9.1 to 21.12.2.
- [Release notes](https://github.com/sanic-org/sanic/releases)
- [Changelog](https://github.com/sanic-org/sanic/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/sanic-org/sanic/compare/v21.9.1...v21.12.2)

---
updated-dependencies:
- dependency-name: sanic
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
dependabot[bot] 2022-08-06 05:22:07 +00:00 • committed by lrnselfreliance
parent 1ede5f3f55
commit d4ed5fa5ce
98 changed files with 7441 additions and 5257 deletions

View file

@ -1,24 +1,23 @@
import React from 'react';
import React, {useContext} from 'react';
import {
Button,
Checkbox,
Confirm,
Container,
Dimmer,
Divider,
Form,
Header,
Icon,
Loader,
Modal,
Placeholder, Progress, Statistic,
Table
PlaceholderLine,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableRow
} from "semantic-ui-react";
import {
clearCompletedDownloads,
clearFailedDownloads,
getDownloads,
getSettings, getStatus,
getSettings,
getStatus,
killDownload,
postDownload,
saveSettings
@ -26,18 +25,38 @@ import {
import TimezoneSelect from 'react-timezone-select';
import {
DisableDownloadsToggle,
ExternalCardLink,
HelpPopup,
HotspotToggle, humanFileSize,
HotspotToggle,
humanFileSize,
LoadStatistic,
PageContainer,
secondsToDate,
secondsToFrequency,
TabLinks,
textEllipsis,
ThrottleToggle,
Toggle,
WROLModeMessage
} from "./Common";
import {Route} from "react-router-dom";
import {Route, Routes} from "react-router-dom";
import QRCode from "react-qr-code";
import {ThemeContext} from "../contexts/contexts";
import {useDownloads} from "../hooks/customHooks";
import {
Button,
Form,
FormField,
FormGroup,
FormInput,
Header,
Loader,
Placeholder,
Progress,
Statistic,
StatisticGroup,
Table
} from "./Theme";
class Settings extends React.Component {
@ -150,54 +169,53 @@ class Settings extends React.Component {
const qrButton = <Button icon style={{marginBottom: '1em'}}><Icon name='qrcode' size='big'/></Button>;
return (
<Container fluid>
return <ThemeContext.Consumer>
{({i, t}) => <Container fluid>
<WROLModeMessage content='Settings are disabled because WROL Mode is enabled.'/>
<HotspotToggle/>
<br/>
<ThrottleToggle style={{marginTop: '0.5em'}}/>
<ThrottleToggle/>
<Divider/>
<Header as='h3'>
The settings for your WROLPi.
</Header>
<p className="text-muted">
<p {...t}>
Any changes will be written to <i>config/wrolpi.yaml</i>.
</p>
<Form id="settings" onSubmit={this.handleSubmit}>
<Checkbox toggle
style={{marginTop: '0.5em', marginBottom: '0.5em'}}
label='Download on Startup'
disabled={disabled || download_on_startup === null}
checked={download_on_startup === true}
onChange={(e, d) => this.handleInputChange(e, 'download_on_startup', d.checked)}
/>
<div style={{margin: '0.5em'}}>
<Toggle
label='Download on Startup'
disabled={disabled || download_on_startup === null}
checked={download_on_startup === true}
onChange={(checked) => this.handleInputChange(null, 'download_on_startup', checked)}
/>
</div>
<br/>
<Checkbox toggle
style={{marginTop: '0.5em', marginBottom: '0.5em'}}
label='WiFi Hotspot on Startup'
disabled={disabled || hotspot_on_startup === null}
checked={hotspot_on_startup === true}
onChange={(e, d) => this.handleInputChange(e, 'hotspot_on_startup', d.checked)}
/>
<div style={{margin: '0.5em'}}>
<Toggle
label='WiFi Hotspot on Startup'
disabled={disabled || hotspot_on_startup === null}
checked={hotspot_on_startup === true}
onChange={(checked) => this.handleInputChange(null, 'hotspot_on_startup', checked)}
/>
</div>
<br/>
<div style={{margin: '0.5em'}}>
<Toggle
label='CPU Power-save on Startup'
disabled={disabled || throttle_on_startup === null}
checked={throttle_on_startup === true}
onChange={(checked) => this.handleInputChange(null, 'throttle_on_startup', checked)}
/>
</div>
<Checkbox toggle
style={{marginTop: '0.5em', marginBottom: '0.5em'}}
label='CPU Power-save on Startup'
disabled={disabled || throttle_on_startup === null}
checked={throttle_on_startup === true}
onChange={(e, d) => this.handleInputChange(e, 'throttle_on_startup', d.checked)}
/>
<Form.Group inline>
<Form.Input
<FormGroup inline>
<FormInput
label={<>
<b>Download Timeout</b>
<b {...t}>Download Timeout</b>
<HelpPopup content='Downloads will be stopped after this many seconds have elapsed.
Downloads will never timeout if this is empty.'/>
</>}
@ -205,30 +223,30 @@ class Settings extends React.Component {
disabled={disabled || download_timeout === null}
onChange={(e, d) => this.handleTimeoutChange(e, 'download_timeout', d.value)}
/>
</Form.Group>
</FormGroup>
<Form.Group inline>
<Form.Input
<FormGroup inline>
<FormInput
label='Hotspot SSID'
value={hotspot_ssid}
disabled={disabled || hotspot_ssid === null}
onChange={(e, d) =>
this.setState({hotspot_ssid: d.value}, this.handleHotspotChange)}
/>
<Form.Input
<FormInput
label='Hotspot Password'
disabled={disabled || hotspot_password === null}
value={hotspot_password}
onChange={(e, d) =>
this.setState({hotspot_password: d.value}, this.handleHotspotChange)}
/>
<Form.Input
<FormInput
label='Hotspot Device'
disabled={disabled || hotspot_password === null}
value={hotspot_device}
onChange={(e, d) => this.handleInputChange(e, 'hotspot_device', d.value)}
/>
</Form.Group>
</FormGroup>
<Modal closeIcon
onClose={() => this.setState({qrOpen: false})}
@ -244,25 +262,26 @@ class Settings extends React.Component {
</Modal.Content>
</Modal>
<Form.Field>
<FormField>
<label>Timezone</label>
<TimezoneSelect
value={timezone}
onChange={(v) => this.handleInputChange(null, 'timezone', v)}
onChange={i => this.handleInputChange(null, 'timezone', i)}
/>
</Form.Field>
</FormField>
<Button color="blue" type="submit" disabled={disabled}>
Save
</Button>
<Dimmer active={pending} inverted>
<Dimmer active={pending}>
<Loader active={pending} size='large'/>
</Dimmer>
</Form>
</Container>
)
}
</ThemeContext.Consumer>
}
}
@ -284,13 +303,13 @@ class WROLMode extends React.Component {
}
}
toggleWROLMode = async () => {
toggleWROLMode = async (checked) => {
// Handle WROL Mode toggling by itself so that other settings are not modified.
let config = {
wrol_mode: !this.state.WROLMode,
wrol_mode: checked,
}
await saveSettings(config);
this.setState({disabled: !this.state.WROLMode, WROLMode: !this.state.WROLMode});
this.setState({disabled: !this.state.WROLMode, WROLMode: checked});
}
render() {
@ -298,39 +317,28 @@ class WROLMode extends React.Component {
return <Loader active inline='centered'/>
}
return (
<Container fluid>
return <ThemeContext.Consumer>
{({i, t}) => <Container fluid>
<Header as="h1">WROL Mode</Header>
<h4>
<Header as='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>
</Header>
<p {...t}>
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'}
<Toggle
checked={this.state.WROLMode}
onChange={this.toggleWROLMode}
label={this.state.WROLMode ? 'WROL Mode Enabled' : 'WROL Mode Disabled'}
/>
</Container>
)
</Container>}
</ThemeContext.Consumer>
}
}
function LoadStatistic({label, value, cores}) {
let color;
const quarter = cores / 4;
if (cores && value >= (quarter * 3)) {
color = 'red';
} else if (cores && value >= (quarter * 2)) {
color = 'yellow';
}
return <Statistic label={label} value={parseFloat(value).toFixed(1)} color={color}/>;
}
function DriveInfo({used, size, percent, mount}) {
let color;
if (percent >= 90) {
@ -359,20 +367,20 @@ function CPUTemperatureStatistic({value}) {
return <Statistic label='Temp C°' value={value} color={color}/>
}
function CPUUsageProgress({value, label}) {
export function CPUUsageProgress({value, label}) {
if (value === null) {
return <Progress progress={0} color='grey' label='Average CPU Usage ERROR' disabled/>
}
let color = 'grey';
let color = 'black';
if (value >= 90) {
color = 'red';
} else if (value >= 70) {
color = 'orange';
color = 'brown';
} else if (value >= 50) {
color = 'yellow';
color = 'orange';
} else if (value >= 30) {
color = 'olive';
color = 'green';
}
return <Progress percent={value} progress color={color} label={label}/>
}
@ -407,34 +415,35 @@ class Status extends React.Component {
}
render() {
let body = <Loader active inline='centered'>Loading system status</Loader>;
if (this.state.status) {
const {cpu_info, load, drives} = this.state.status;
const {minute_1, minute_5, minute_15} = load;
const {percent, cores, temperature} = cpu_info;
body = (<>
<CPUUsageProgress value={percent} label='CPU Usage'/>
return <ThemeContext.Consumer>
{({i}) => <>
<CPUUsageProgress value={percent} label='CPU Usage'/>
<CPUTemperatureStatistic value={temperature}/>
<Statistic label='Cores' value={cores || '?'}/>
<Statistic.Group>
<LoadStatistic label='1 Minute Load' value={minute_1} cores={cores}/>
<LoadStatistic label='5 Minute Load' value={minute_5} cores={cores}/>
<LoadStatistic label='15 Minute Load' value={minute_15} cores={cores}/>
</Statistic.Group>
<CPUTemperatureStatistic value={temperature}/>
<Statistic label='Cores' value={cores || '?'}/>
<StatisticGroup>
<LoadStatistic label='1 Minute Load' value={minute_1} cores={cores}/>
<LoadStatistic label='5 Minute Load' value={minute_5} cores={cores}/>
<LoadStatistic label='15 Minute Load' value={minute_15} cores={cores}/>
</StatisticGroup>
<Header as='h2'>Drive Usage</Header>
{drives.map(DriveInfo)}
</>);
<Header as='h2'>Drive Usage</Header>
{drives.map((drive) => <DriveInfo key={drive['mount']} {...drive}/>)}
</>}
</ThemeContext.Consumer>
}
return (
<Container fluid style={{marginBottom: '5em'}}>
{body}
return <ThemeContext.Consumer>
{({i}) => <Container fluid style={{marginBottom: '5em'}}>
<Loader active inline='centered'>Loading system status</Loader>;
</Container>
)
}
</ThemeContext.Consumer>
}
}
@ -529,15 +538,15 @@ class DownloadRow extends React.Component {
</Modal.Actions>
</Modal>;
return (
<Table.Row positive={positive}>
<Table.Cell><a href={url} target='_blank'>{textEllipsis(url, 50)}</a></Table.Cell>
<Table.Cell>{secondsToFrequency(frequency)}</Table.Cell>
<Table.Cell>{last_successful_download ? secondsToDate(last_successful_download) : null}</Table.Cell>
<Table.Cell>{secondsToDate(next_download)}</Table.Cell>
<Table.Cell>{error && errorModal}{location && <a href={location}>View</a>}</Table.Cell>
</Table.Row>
);
return <TableRow positive={positive}>
<TableCell>
<ExternalCardLink to={url}>{textEllipsis(url, 50)}</ExternalCardLink>
</TableCell>
<TableCell>{secondsToFrequency(frequency)}</TableCell>
<TableCell>{last_successful_download ? secondsToDate(last_successful_download) : null}</TableCell>
<TableCell>{secondsToDate(next_download)}</TableCell>
<TableCell>{error && errorModal}{location && <a href={location}>View</a>}</TableCell>
</TableRow>
}
}
@ -587,14 +596,14 @@ class StoppableRow extends React.Component {
let {stopOpen, startOpen, errorModalOpen} = this.state;
let completedAtCell = last_successful_download ? secondsToDate(last_successful_download) : null;
let buttonCell = <Table.Cell/>;
let buttonCell = <TableCell/>;
let positive = false;
let negative = false;
let warning = false;
if (status === 'pending' || status === 'new') {
positive = status === 'pending';
buttonCell = (
<Table.Cell>
<TableCell>
<Button
onClick={this.openStop}
color='red'
@ -606,13 +615,13 @@ class StoppableRow extends React.Component {
onCancel={this.closeStop}
onConfirm={this.handleStop}
/>
</Table.Cell>
</TableCell>
);
} else if (status === 'failed' || status === 'deferred') {
negative = status === 'failed';
warning = status === 'deferred';
buttonCell = (
<Table.Cell>
<TableCell>
<Button
onClick={this.openStop}
color='red'
@ -635,13 +644,13 @@ class StoppableRow extends React.Component {
onCancel={this.closeStart}
onConfirm={this.handleStart}
/>
</Table.Cell>
</TableCell>
);
} else if (status === 'complete' && location) {
buttonCell = (
<Table.Cell>
<TableCell>
<a href={location}>View</a>
</Table.Cell>
</TableCell>
);
}
if (error) {
@ -665,138 +674,97 @@ class StoppableRow extends React.Component {
}
return (
<Table.Row positive={positive} negative={negative} warning={warning}>
<Table.Cell><a href={url} target='_blank'>{textEllipsis(url, 50)}</a></Table.Cell>
<Table.Cell>{status}</Table.Cell>
<Table.Cell>{completedAtCell}</Table.Cell>
<TableRow positive={positive} negative={negative} warning={warning}>
<TableCell>
<ExternalCardLink to={url}>{textEllipsis(url, 50)}</ExternalCardLink>
</TableCell>
<TableCell>{status}</TableCell>
<TableCell>{completedAtCell}</TableCell>
{buttonCell}
</Table.Row>
</TableRow>
);
}
}
class Downloads extends React.Component {
constructor(props) {
super(props);
this.state = {
once_downloads: null,
recurring_downloads: null,
pending_downloads: null,
stopOpen: false,
disabled: false,
};
function Downloads() {
const {t} = useContext(ThemeContext);
const {onceDownloads, recurringDownloads, fetchDownloads} = useDownloads();
const tablePlaceholder = <Placeholder>
<PlaceholderLine/>
<PlaceholderLine/>
</Placeholder>;
const stoppableHeader = (
<TableHeader>
<TableRow>
<TableHeaderCell>URL</TableHeaderCell>
<TableHeaderCell>Status</TableHeaderCell>
<TableHeaderCell>Completed At</TableHeaderCell>
<TableHeaderCell>Control</TableHeaderCell>
</TableRow>
</TableHeader>
);
const nonStoppableHeader = (
<TableHeader>
<TableRow>
<TableHeaderCell>URL</TableHeaderCell>
<TableHeaderCell>Download Frequency</TableHeaderCell>
<TableHeaderCell>Last Successful Download</TableHeaderCell>
<TableHeaderCell>Next Download</TableHeaderCell>
<TableHeaderCell>View</TableHeaderCell>
</TableRow>
</TableHeader>
);
let onceTable = tablePlaceholder;
if (onceDownloads && onceDownloads.length === 0) {
onceTable = <p {...t}>No downloads are scheduled.</p>
} else if (onceDownloads) {
onceTable = (
<>
<ClearCompleteDownloads callback={fetchDownloads}/>
<ClearFailedDownloads callback={fetchDownloads}/>
<Table>
{stoppableHeader}
<TableBody>
{onceDownloads.map((i) =>
<StoppableRow fetchDownloads={fetchDownloads} key={i.id} {...i}/>
)}
</TableBody>
</Table>
</>);
}
async componentDidMount() {
await this.fetchDownloads();
this.intervalId = setInterval(this.fetchDownloads, 1000 * 10);
let recurringTable = tablePlaceholder;
if (recurringDownloads && recurringDownloads.length === 0) {
recurringTable = <p {...t}>No recurring downloads are scheduled.</p>
} else if (recurringDownloads) {
recurringTable = <Table>
{nonStoppableHeader}
<TableBody>
{recurringDownloads.map((i) => <DownloadRow key={i.id} {...i}/>)}
</TableBody>
</Table>;
}
componentWillUnmount() {
clearInterval(this.intervalId);
}
return <>
<WROLModeMessage content='Downloads are disabled because WROL Mode is enabled.'/>
<DisableDownloadsToggle/>
<Header as='h1'>Downloads</Header>
{onceTable}
closeStop = () => {
this.setState({stopOpen: false});
}
openStop = () => {
this.setState({stopOpen: true});
}
fetchDownloads = async () => {
try {
let data = await getDownloads();
this.setState({
once_downloads: data.once_downloads,
recurring_downloads: data.recurring_downloads,
pending_downloads: data.pending_downloads,
});
} catch (e) {
console.error(e);
}
}
render() {
let tablePlaceholder = (
<Placeholder>
<Placeholder.Line/>
<Placeholder.Line/>
</Placeholder>
);
let stoppableHeader = (
<Table.Header>
<Table.Row>
<Table.HeaderCell>URL</Table.HeaderCell>
<Table.HeaderCell>Status</Table.HeaderCell>
<Table.HeaderCell>Completed At</Table.HeaderCell>
<Table.HeaderCell>Control</Table.HeaderCell>
</Table.Row>
</Table.Header>
);
let nonStoppableHeader = (
<Table.Header>
<Table.Row>
<Table.HeaderCell>URL</Table.HeaderCell>
<Table.HeaderCell>Download Frequency</Table.HeaderCell>
<Table.HeaderCell>Last Successful Download</Table.HeaderCell>
<Table.HeaderCell>Next Download</Table.HeaderCell>
<Table.HeaderCell>View</Table.HeaderCell>
</Table.Row>
</Table.Header>
);
let onceTable = tablePlaceholder;
if (this.state.once_downloads !== null && this.state.once_downloads.length === 0) {
onceTable = <p>No downloads are scheduled.</p>
} else if (this.state.once_downloads !== null) {
onceTable = (
<>
<ClearCompleteDownloads callback={() => this.fetchDownloads()}/>
<ClearFailedDownloads callback={() => this.fetchDownloads()}/>
<Table>
{stoppableHeader}
<Table.Body>
{this.state.once_downloads.map((i) =>
<StoppableRow {...i} fetchDownloads={this.fetchDownloads} key={i.id}/>
)}
</Table.Body>
</Table>
</>);
}
let recurringTable = tablePlaceholder;
if (this.state.recurring_downloads !== null && this.state.recurring_downloads.length === 0) {
recurringTable = <p>No recurring downloads are scheduled.</p>
} else if (this.state.recurring_downloads !== null) {
recurringTable = (<Table>
{nonStoppableHeader}
<Table.Body>
{this.state.recurring_downloads.map((i) => <DownloadRow {...i} key={i.id}/>)}
</Table.Body>
</Table>);
}
return (
<div>
<WROLModeMessage content='Downloads are disabled because WROL Mode is enabled.'/>
<DisableDownloadsToggle/>
<Header as='h1'>Downloads</Header>
{onceTable}
<Header as='h1'>Recurring Downloads</Header>
{recurringTable}
</div>
);
}
<Header as='h1'>Recurring Downloads</Header>
{recurringTable}
</>
}
export default function Admin(props) {
const links = [
{text: 'Downloads', to: '/admin', exact: true, key: 'admin'},
{text: 'Downloads', to: '/admin', key: 'admin', end: true},
{text: 'Settings', to: '/admin/settings', key: 'settings'},
{text: 'Status', to: '/admin/status', key: 'status'},
{text: 'WROL Mode', to: '/admin/wrol', key: 'wrol'},
@ -805,10 +773,12 @@ export default function Admin(props) {
return (
<PageContainer>
<TabLinks links={links}/>
<Route path='/admin' exact component={Downloads}/>
<Route path='/admin/settings' exact component={Settings}/>
<Route path='/admin/status' exact component={Status}/>
<Route path='/admin/wrol' exact component={WROLMode}/>
<Routes>
<Route path='/' exact element={<Downloads/>}/>
<Route path='settings' exact element={<Settings/>}/>
<Route path='status' exact element={<Status/>}/>
<Route path='wrol' exact element={<WROLMode/>}/>
</Routes>
</PageContainer>
)

View file

@ -1,17 +1,17 @@
import React from 'react';
import {Button, Divider, Segment, TextArea} from "semantic-ui-react";
import {Route} from "react-router-dom";
import React, {useContext} from 'react';
import {Divider, SegmentGroup} from "semantic-ui-react";
import {Route, Routes} from "react-router-dom";
import "../static/wrolpi.css";
import {decryptOTP, encryptOTP} from "../api";
import {PageContainer} from "./Common";
import {ThemeContext} from "../contexts/contexts";
import {Button, Header, Segment, TextArea} from "./Theme";
class Encrypt extends React.Component {
constructor(props) {
super(props);
this.state = {
otp: '',
plaintext: '',
ciphertext: '',
otp: '', plaintext: '', ciphertext: '',
}
}
@ -30,39 +30,37 @@ class Encrypt extends React.Component {
}
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>
</>
)
return <>
<Header as='h2'>Encrypt</Header>
<SegmentGroup>
<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>
</SegmentGroup>
<br/>
<Button onClick={this.handleSubmit}>Encrypt</Button>
</>
}
}
@ -70,9 +68,7 @@ class Decrypt extends React.Component {
constructor(props) {
super(props);
this.state = {
otp: '',
plaintext: '',
ciphertext: '',
otp: '', plaintext: '', ciphertext: '',
}
}
@ -91,70 +87,66 @@ class Decrypt extends React.Component {
}
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>
</>
)
return <>
<Header as='h2'>Decrypt</Header>
<SegmentGroup>
<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>
</SegmentGroup>
<br/>
<Button onClick={this.handleSubmit}>Decrypt</Button>
</>
}
}
class OTP extends React.Component {
render() {
let newPadURL = `http://${window.location.host}/api/otp/html`;
let cheatSheetURL = `${process.env.PUBLIC_URL}/one-time-pad-cheat-sheet.pdf`;
function OTP() {
const {t} = useContext(ThemeContext);
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>
let newPadURL = `http://${window.location.host}/api/otp/html`;
let cheatSheetURL = `${process.env.PUBLIC_URL}/one-time-pad-cheat-sheet.pdf`;
<Divider/>
<Encrypt/>
return <>
<Header as='h1'>One-Time Pad</Header>
<Header as='h4'>One-Time Pads can be used to encrypt your communications. This can be done by hand
(yes, really) or in this app.</Header>
<p {...t}>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/>
<Decrypt/>
</div>
)
}
<Divider/>
<Encrypt/>
<Divider/>
<Decrypt/>
</>
}
export function AppsRoute(props) {
return (
<PageContainer>
<Route path='/apps/otp' exact component={OTP}/>
</PageContainer>
)
return (<PageContainer>
<Routes>
<Route path='otp' exact element={<OTP/>}/>
</Routes>
</PageContainer>)
}

View file

@ -1,52 +1,71 @@
import React, {useState} from "react";
import {Card, Confirm, Container, Header, Image, Loader, Placeholder, Segment} from "semantic-ui-react";
import React, {useContext, useState} from "react";
import {
CardGroupCentered,
ClearButton,
Card,
Confirm,
Container,
Image,
Input,
PlaceholderHeader,
PlaceholderLine,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableRow
} from "semantic-ui-react";
import {
CardLink,
defaultSearchOrder,
ExternalCardLink,
FileIcon,
HelpHeader,
mimetypeColor,
PageContainer,
Paginator,
SearchInput,
TabLinks,
textEllipsis,
uploadDate,
WROLModeMessage
uploadDate
} from "./Common";
import {deleteArchive, postDownload, refreshArchives} from "../api";
import Button from "semantic-ui-react/dist/commonjs/elements/Button";
import {Link, Route, Switch, useHistory} from "react-router-dom";
import {ArchivePlaceholder} from "./Placeholder";
import Table from "semantic-ui-react/dist/commonjs/collections/Table";
import {deleteArchive, postDownload} from "../api";
import {Link, Route, Routes, useNavigate, useParams} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {useArchive, useArchives, useDomains} from "../hooks/customHooks";
import {useArchive, useDomains, useQuery, useSearchArchives} from "../hooks/customHooks";
import {FileCards, FilesView} from "./Files";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import Dropdown from "semantic-ui-react/dist/commonjs/modules/Dropdown";
import _ from "lodash";
import {ThemeContext} from "../contexts/contexts";
import {Button, Header, Loader, Placeholder, Segment, Table} from "./Theme";
function ArchivePage(props) {
function ArchivePage() {
const [deleteOpen, setDeleteOpen] = useState(false);
const [syncOpen, setSyncOpen] = useState(false);
const history = useHistory();
const archiveId = props.match.params.archive_id;
const [archive, alternatives] = useArchive(archiveId);
const navigate = useNavigate();
const {archiveId} = useParams();
const {archiveFile, alternatives} = useArchive(archiveId);
if (archive === null) {
if (archiveFile === null) {
return <Segment><Loader active/></Segment>;
}
if (archive === undefined) {
if (archiveFile === undefined) {
return <>
<Header as='h2'>Unknown archive</Header>
This archive does not exist
</>
}
const {archive} = archiveFile;
const singlefileUrl = archive.singlefile_path ? `/media/${encodeURIComponent(archive.singlefile_path)}` : null;
const screenshotUrl = archive.screenshot_path ? `/media/${encodeURIComponent(archive.screenshot_path)}` : null;
const readabilityUrl = archive.readability_path ? `/media/${encodeURIComponent(archive.readability_path)}` : null;
const singlefileButton = <a href={singlefileUrl} target='_blank'>
const singlefileButton = <ExternalCardLink to={singlefileUrl}>
<Button content='View' color='blue'/>
</a>;
</ExternalCardLink>;
const readabilityLink = readabilityUrl ?
<a href={readabilityUrl} target='_blank'><Button content='Article'/></a> :
<ExternalCardLink to={readabilityUrl}><Button content='Article'/></ExternalCardLink> :
<Button disabled content='Article'/>;
const screenshot = screenshotUrl ?
@ -85,22 +104,26 @@ function ArchivePage(props) {
let alternativesList = <Loader active/>;
if (alternatives && alternatives.length > 0) {
alternativesList = <ArchivesList archives={alternatives}/>;
alternativesList = <FileCards files={alternatives}/>;
} else if (alternatives && alternatives.length === 0) {
alternativesList = <p>No alternatives available</p>;
}
return (
<>
<Button icon='arrow left' content='Back' onClick={() => history.goBack()}/>
<Button icon='arrow left' content='Back' onClick={() => navigate(-1)}/>
<Segment>
{screenshot}
<a href={singlefileUrl} target='_blank' className='no-link-underscore card-link'>
<ExternalCardLink to={singlefileUrl}>
<Header as='h2'>{textEllipsis(archive.title || archive.url, 100)}</Header>
</a>
</ExternalCardLink>
<Header as='h3'>{uploadDate(archive.archive_datetime)}</Header>
<p><a href={archive.url} target='_blank'>{textEllipsis(archive.url, 100)}</a></p>
<p>
<ExternalCardLink to={archive.url}>
{textEllipsis(archive.url, 100)}
</ExternalCardLink>
</p>
{singlefileButton}
{readabilityLink}
@ -119,32 +142,41 @@ function ArchivePage(props) {
)
}
function ArchiveCard({archive, setDomain}) {
export function ArchiveCard({file}) {
const {s} = useContext(ThemeContext);
const {archive} = file;
const imageSrc = archive.screenshot_path ? `/media/${encodeURIComponent(archive.screenshot_path)}` : null;
const singlefileUrl = archive.singlefile_path ? `/media/${encodeURIComponent(archive.singlefile_path)}` : null;
const domain = archive.domain.domain;
let screenshot = <center className='card-icon'><FileIcon file={file}/></center>;
if (imageSrc) {
screenshot = <Image src={imageSrc} wrapped style={{position: 'relative', width: '100%'}}/>;
}
const domain = archive.domain ? archive.domain.domain : null;
const domainUrl = `/archive?domain=${domain}`;
return (
<Card>
<a href={singlefileUrl} target='_blank' className='no-link-underscore card-link'>
<Image src={imageSrc} wrapped style={{position: 'relative', width: '100%'}}/>
</a>
<Card color={mimetypeColor(file.mimetype)} {...s}>
<div>
<ExternalCardLink to={singlefileUrl}>
{screenshot}
</ExternalCardLink>
</div>
<Card.Content>
<Card.Header>
<Container textAlign='left'>
<a href={singlefileUrl} target='_blank' className='no-link-underscore card-link'>
<p>{textEllipsis(archive.title || archive.url, 100)}</p>
</a>
<ExternalCardLink to={singlefileUrl}>
{textEllipsis(archive.title || archive.url, 100)}
</ExternalCardLink>
</Container>
</Card.Header>
{setDomain &&
<a onClick={() => setDomain(domain)} className="no-link-underscore card-link">
{textEllipsis(domain, 40)}
</a>
}
<Card.Meta>
{domain &&
<CardLink to={domainUrl}>
<p {...s}>{domain}</p>
</CardLink>}
<Card.Meta {...s}>
<p>
{uploadDate(archive.archive_datetime)}
</p>
@ -161,158 +193,145 @@ function ArchiveCard({archive, setDomain}) {
)
}
function ArchiveCards({archives, setDomain}) {
return (
<CardGroupCentered>
{archives.map((i) => {
return <ArchiveCard
key={i['id']}
archive={i}
setDomain={setDomain}
/>
})}
</CardGroupCentered>
)
}
export function ArchivesList({archives, searchStr, setDomain}) {
if (archives === null || archives === undefined) {
// Fetching archives.
return <ArchivePlaceholder/>;
} else if (archives.length === 0 && searchStr) {
// Search with no results.
return <p>No archives found! Is your search too restrictive?</p>;
} else if (archives.length === 0) {
// No archives fetched.
return <Message>
<Message.Header>No archives</Message.Header>
<Message.Content>Have you archived any webpages?</Message.Content>
</Message>;
} else {
// Archives fetched successfully!
return <ArchiveCards
archives={archives}
setDomain={setDomain}
/>;
}
}
export function Archives() {
const {archives, setPage, totalPages, searchStr, activePage, setSearchStr, domain, setDomain, search} =
useArchives(20);
let domainClearButton = null;
if (domain) {
domainClearButton = <ClearButton
onClick={() => setDomain(null)}
style={{marginBottom: '1em'}}
label={`Domain: ${domain}`}
/>;
}
return (
<>
<SearchInput initValue={searchStr} onSubmit={setSearchStr}/>
{domainClearButton}
<ArchivesList
archives={archives}
searchStr={searchStr}
setDomain={setDomain}
/>
<div style={{marginTop: '3em', textAlign: 'center'}}>
<Paginator activePage={activePage} totalPages={totalPages} onPageChange={setPage}/>
</div>
</>
)
}
class ManageArchives extends React.Component {
async refresh() {
await refreshArchives();
}
render() {
return (<>
<WROLModeMessage content='Cannot modify Archives'/>
<Button secondary
id='refresh_archives'
onClick={this.refresh}>
Refresh Archive Files
</Button>
<label htmlFor='refresh_archives'>
Find any new archive files. Remove Archives which no longer have files.
</label>
</>)
}
}
function Domains() {
export function Domains() {
const [domains] = useDomains();
const 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>
}
if (domains && domains.length > 0) {
return (
<>
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Domain</Table.HeaderCell>
<Table.HeaderCell>Archives</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{domains.map(row)}
</Table.Body>
</Table>
</>
)
}
const [searchStr, setSearchStr] = useState('');
if (domains === null) {
return (<>
<Placeholder>
<Placeholder.Header>
<Placeholder.Line/>
<Placeholder.Line/>
</Placeholder.Header>
<PlaceholderHeader>
<PlaceholderLine/>
<PlaceholderLine/>
</PlaceholderHeader>
</Placeholder>
</>)
}
return (<>
<Message>
} else if (!domains || domains.length === 0) {
return <Message>
<Message.Header>No domains yet.</Message.Header>
<Message.Content>Archive some webpages!</Message.Content>
</Message>
</>)
</Message>;
}
let filteredDomains = domains;
if (searchStr) {
const re = new RegExp(_.escapeRegExp(searchStr), 'i');
filteredDomains = domains.filter(i => re.test(i['domain']));
}
const row = ({domain, url_count}) => {
return <TableRow key={domain}>
<TableCell>
<Link to={`/archive?domain=${domain}`}>
{domain}
</Link>
</TableCell>
<TableCell>{url_count}</TableCell>
</TableRow>
}
return <>
<Input
icon='search'
value={searchStr}
placeholder='Search...'
onChange={(e, {value}) => setSearchStr(value)}
/>
<Table celled>
<TableHeader>
<TableRow>
<TableHeaderCell>Domain</TableHeaderCell>
<TableHeaderCell>Archives</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{filteredDomains.map(row)}
</TableBody>
</Table>
</>;
}
function Archives() {
const [domains] = useDomains();
let filterOptions = [];
if (domains && domains.length > 0) {
domains.forEach(i => {
filterOptions = [...filterOptions, {text: i['domain'], key: i['domain'], value: i['domain']}]
});
}
const {searchParams, updateQuery} = useQuery();
export function ArchiveRoute(props) {
let searchOrder = '-date';
if (searchParams.get('order')) {
// Use whatever order the user specified.
searchOrder = searchParams.get('order');
} else if (searchParams.get('q')) {
// User used a search_str
searchOrder = defaultSearchOrder;
}
const domain = searchParams.get('domain');
const {archives, limit, setLimit, totalPages, activePage, setPage, searchStr, setSearchStr, setOrderBy} =
useSearchArchives(24, domain, searchOrder);
const setView = (value) => updateQuery({view: value});
const view = searchParams.get('view');
const setDomain = (value) => updateQuery({'domain': value});
const archiveOrders = [
{key: '-date', value: '-date', text: 'Newest'},
{key: 'date', value: 'date', text: 'Oldest'},
];
const menuColumns = (<>
<Grid.Column width={5}>
<SearchInput clearable
actionIcon='search'
searchStr={searchStr}
onSubmit={setSearchStr}
/>
</Grid.Column>
<Grid.Column width={5}>
<Dropdown selection fluid
placeholder='Sort by...'
value={searchOrder}
options={archiveOrders}
onChange={(e, {value}) => setOrderBy(value)}
/>
</Grid.Column>
</>);
return <FilesView
files={archives}
limit={limit}
setLimit={setLimit}
activePage={activePage}
totalPages={totalPages}
showLimit={true}
showSelect={true}
view={view}
setView={setView}
setPage={setPage}
filterOptions={filterOptions}
activeFilters={domain}
setFilters={setDomain}
filterPlaceholder='Domain'
menuColumns={menuColumns}
menuColumnsCount={2}
/>
}
export function ArchiveRoute() {
const links = [
{text: 'Archives', to: '/archive', exact: true, key: 'archive'},
{text: 'Domains', to: '/archive/domains', key: 'domains'},
{text: 'Manage', to: '/archive/manage', key: 'manage'},
{text: 'Archives', to: '/archive', end: true},
{text: 'Domains', to: '/archive/domains'},
];
return <PageContainer>
<TabLinks links={links}/>
<Switch>
<Route path='/archive/domains' exact component={Domains}/>
<Route path='/archive/manage' exact component={ManageArchives}/>
<Route path='/archive/:archive_id' exact component={ArchivePage}/>
<Route path='/archive' exact component={Archives}/>
</Switch>
<Routes>
<Route path='/' element={<Archives/>}/>
<Route path='domains' element={<Domains/>}/>
<Route path=':archiveId' element={<ArchivePage/>}/>
</Routes>
</PageContainer>
}

File diff suppressed because it is too large Load diff

View file

@ -1,24 +1,11 @@
import React, {useEffect, useState} from "react";
import {
Card,
Checkbox,
Container,
Form,
Header,
Icon,
Image,
Input,
Menu,
Pagination,
Popup,
Responsive
} from 'semantic-ui-react';
import React, {useContext, useEffect, useState} from "react";
import {Card, Container, Image, Input, Pagination, Popup, Responsive, TableCell, TableRow} from 'semantic-ui-react';
import {Link, NavLink} from "react-router-dom";
import Button from "semantic-ui-react/dist/commonjs/elements/Button";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {getSettings} from "../api";
import {useDownloaders, useHotspot, useThrottle} from "../hooks/customHooks";
import {getSettings} from "../api";
import {darkTheme, SettingsContext, ThemeContext} from "../contexts/contexts";
import {Button, Form, Header, Icon, Menu, Statistic} from "./Theme";
export const API_URI = `http://${window.location.host}/api`;
export const VIDEOS_API = `${API_URI}/videos`;
@ -26,65 +13,21 @@ export const ARCHIVES_API = `${API_URI}/archive`;
export const OTP_API = `${API_URI}/otp`;
export const DEFAULT_LIMIT = 20;
export default class OldPaginator 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 Paginator({activePage, onPageChange, totalPages, showFirstAndLast}) {
export function Paginator({activePage, onPageChange, totalPages, showFirstAndLast, size = 'mini'}) {
const handlePageChange = (e, {activePage}) => {
onPageChange(activePage);
}
return (
<Pagination
activePage={activePage}
boundaryRange={1}
onPageChange={handlePageChange}
size='mini'
siblingRange={2}
totalPages={totalPages}
firstItem={showFirstAndLast ? undefined : null}
lastItem={showFirstAndLast ? undefined : null}
/>
)
return (<Pagination
activePage={activePage}
boundaryRange={1}
onPageChange={handlePageChange}
size={size}
siblingRange={2}
totalPages={totalPages}
firstItem={showFirstAndLast ? undefined : null}
lastItem={showFirstAndLast ? undefined : null}
/>)
}
export function secondsToDuration(video) {
@ -114,7 +57,7 @@ export function Duration({video}) {
}
export function uploadDate(d) {
// Convert a date integer to a human readable date format.
// Convert a date integer to a human-readable date format.
let upload_date = <></>;
if (d) {
upload_date = new Date(d * 1000);
@ -123,69 +66,137 @@ export function uploadDate(d) {
return upload_date;
}
export function secondsToDateTime(seconds) {
var t = new Date(1970, 0, 1); // Epoch
t.setSeconds(seconds);
return t;
export function CardLink({to, newTab = false, ...props}) {
const {t} = useContext(ThemeContext);
props = {...props, ...t};
props = newTab === true ? {...props, target: '_blank', rel: 'noopener noreferrer'} : props;
return <Link to={to} className="no-link-underscore card-link" {...props}>
{props.children}
</Link>
}
export function VideoCard({video}) {
export function ExternalCardLink({to, ...props}) {
const {t} = useContext(ThemeContext);
return <a href={to} target='_blank' rel='noopener noreferrer' className='no-link-underscore card-link' {...t}>
{props.children}
</a>
}
export function VideoCard({file}) {
const {video} = file;
const {s} = useContext(ThemeContext);
let video_url = `/videos/video/${video.id}`;
let upload_date = uploadDate(video.upload_date);
const upload_date = uploadDate(video.upload_date);
// A video may not have a channel.
let channel = video.channel ? video.channel : null;
const channel = video.channel ? video.channel : null;
let channel_url = null;
if (channel) {
channel_url = `/videos/channel/${channel.id}/video`;
video_url = `/videos/channel/${channel.id}/video/${video.id}`;
}
let poster_url = video.poster_path ? `/media/${encodeURIComponent(video.poster_path)}` : null;
const poster_url = video.poster_path ? `/media/${encodeURIComponent(video.poster_path)}` : null;
let imageLabel = null;
if (video.favorite) {
imageLabel = {corner: 'left', icon: 'heart', color: 'green'};
}
let poster = <center className='card-icon'><FileIcon file={file}/></center>;
if (poster_url) {
poster = <Image wrapped
src={poster_url}
label={imageLabel}
style={{position: 'relative', width: '100%'}}
/>;
}
return (
<Card>
<Link to={video_url}>
<Image wrapped
src={poster_url}
label={imageLabel}
style={{position: 'relative', width: '100%'}}
/>
</Link>
<Duration video={video}/>
<Card.Content>
<Card.Header>
<Container textAlign='left'>
<Link to={video_url} className="no-link-underscore card-link">
<p>{textEllipsis(video.title || video.stem || video.video_path, 100)}</p>
</Link>
</Container>
</Card.Header>
<Card.Description>
<Container textAlign='left'>
{channel &&
<Link to={channel_url} className="no-link-underscore card-link">
<b>{channel.name}</b>
</Link>}
<p>{upload_date}</p>
</Container>
</Card.Description>
</Card.Content>
</Card>
)
return (<Card color={mimetypeColor(file.mimetype)}>
<Link to={video_url}>
{poster}
</Link>
<Duration video={video}/>
<Card.Content {...s}>
<Card.Header>
<Container textAlign='left'>
<Link to={video_url} className="no-link-underscore card-link">
<p {...s}>{textEllipsis(video.title || video.stem || video.video_path, 100)}</p>
</Link>
</Container>
</Card.Header>
<Card.Description>
<Container textAlign='left'>
{channel && <Link to={channel_url} className="no-link-underscore card-link">
<b {...s}>{channel.name}</b>
</Link>}
<p {...s}>{upload_date}</p>
</Container>
</Card.Description>
</Card.Content>
</Card>)
}
export function VideoCards({videos}) {
return (
<CardGroupCentered>
{videos.map((v) => {
return <VideoCard key={v['id']} video={v}/>
})}
</CardGroupCentered>
)
export function VideoRow({file, checkbox}) {
const {video} = file;
let video_url = `/videos/video/${video.id}`;
const poster_url = video.poster_path ? `/media/${encodeURIComponent(video.poster_path)}` : null;
let poster;
let imageLabel = video.favorite ? {corner: 'left', icon: 'heart', color: 'green'} : null;
if (poster_url) {
poster = <CardLink to={video_url}>
<Image wrapped
src={poster_url}
label={imageLabel}
width='50px'
/>
</CardLink>
} else {
poster = <FileIcon file={file} size='large'/>;
}
return (<TableRow>
{checkbox}
<TableCell>
<center>
{poster}
</center>
</TableCell>
<TableCell>
<CardLink to={video_url}>
{textEllipsis(video.title || video.stem || video.video_path, 100)}
</CardLink>
</TableCell>
</TableRow>)
}
export function ArchiveRow({file, checkbox}) {
const {archive} = file;
const archiveUrl = `/archive/${archive.id}`;
const posterUrl = archive.screenshot_path ? `/media/${encodeURIComponent(archive.screenshot_path)}` : null;
let poster;
if (posterUrl) {
poster = <CardLink to={archiveUrl}>
<Image wrapped src={posterUrl} width='50px'/>
</CardLink>;
} else {
poster = <FileIcon file={file} size='large'/>;
}
return (<TableRow>
{checkbox}
<TableCell>
<center>{poster}</center>
</TableCell>
<TableCell>
<CardLink to={archiveUrl}>
{textEllipsis(archive.title || archive.stem, 100)}
</CardLink>
</TableCell>
</TableRow>)
}
export function RequiredAsterisk() {
@ -195,43 +206,33 @@ export function RequiredAsterisk() {
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'},
{key: '-modification_datetime', value: '-modification_datetime', text: 'Newest File', title: 'Newest File'},
{key: 'modification_datetime', value: 'modification_datetime', text: 'Oldest File', title: 'Oldest File'},
]
export let videoOrders = [{key: '-upload_date', value: '-upload_date', text: 'Newest'}, {
key: 'upload_date', value: 'upload_date', text: 'Oldest'
}, {key: '-duration', value: '-duration', text: 'Longest'}, {
key: 'duration', value: 'duration', text: 'Shortest'
}, {key: '-viewed', value: '-viewed', text: 'Recently viewed'}, {
key: '-size', value: '-size', text: 'Largest'
}, {key: 'size', value: 'size', text: 'Smallest'}, {
key: '-view_count', value: '-view_count', text: 'Most Views'
}, {key: 'view_count', value: 'view_count', text: 'Least Views'}, {
key: '-modification_datetime', value: '-modification_datetime', text: 'Newest File'
}, {key: 'modification_datetime', value: 'modification_datetime', text: 'Oldest File'},]
export let searchOrders = [
{key: 'rank', value: 'rank', text: 'Search Rank', title: 'Search Results'},
];
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 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 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},
];
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},];
export function secondsToFrequency(seconds) {
for (let i = 0; i < Object.keys(rssFrequencyOptions).length; i++) {
@ -343,20 +344,13 @@ export class APIForm extends React.Component {
errors[errorName] = true;
}
this.setState({
error: true,
errors: errors,
message_content: content,
message_header: header,
success: false,
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,
error: false, message_content: content, message_header: header, success: true,
});
}
@ -407,18 +401,13 @@ export class APIForm extends React.Component {
setLoading = () => {
this.setState({
disabled: true,
error: false,
errors: this.getEmptyErrors(),
loading: true,
success: false,
disabled: true, error: false, errors: this.getEmptyErrors(), loading: true, success: false,
})
}
clearLoading = () => {
this.setState({
disabled: false,
loading: false,
disabled: false, loading: false,
})
}
@ -470,8 +459,7 @@ export function arraysEqual(a, b) {
export function scrollToTop() {
window.scrollTo({
top: 0,
behavior: "auto"
top: 0, behavior: "auto"
});
}
@ -488,95 +476,54 @@ export function changePageHistory(history, location, activePage, searchStr, sear
search = `${search}&f=${filters}`;
}
history.push({
pathname: location.pathname,
search: search,
pathname: location.pathname, search: search,
});
scrollToTop();
}
export function ClearButton({onClick, style, label, icon = 'close'}) {
return <Button icon
labelPosition='right'
onClick={onClick}
style={style}
>
{label}
<Icon name={icon}/>
</Button>
}
export function SearchInput({
searchStr,
onSubmit,
size = 'small',
placeholder,
action,
actionIcon,
clearable,
...props
}) {
let [value, setValue] = useState(searchStr || '');
export function SearchInput({initValue, onSubmit, size, placeholder = 'Search...'}) {
let [value, setValue] = useState(initValue || '');
size = size || 'small';
const buttonClick = () => {
const handleClearSearch = (e) => {
e.preventDefault();
// Clear the input when the "clear" button is clicked, search again.
setValue('');
onSubmit('');
}
// Button is "search" when input is dirty, otherwise it is "clear".
let button = (
<Button icon onClick={buttonClick} style={{marginLeft: '0.5em'}} type='reset' size={size}>
<Icon name='close'/>
</Button>
);
if (!initValue || initValue !== value) {
button = (
<Button icon style={{marginLeft: '0.5em'}} type='submit' disabled={value === ''} size={size}>
<Icon name='search'/>
</Button>
);
}
const localOnSubmit = (e) => {
// Send the value up when submitting.
e.preventDefault();
onSubmit(value);
}
return (
<Form onSubmit={localOnSubmit}>
<Form.Group inline style={{marginBottom: '1em'}}>
<Input
type='text'
placeholder={placeholder}
onChange={(e) => setValue(e.target.value)}
value={value}
size={size}
/>
{button}
</Form.Group>
</Form>
)
}
if ((action || actionIcon) && searchStr && searchStr === value && clearable) {
action = <Button icon='close' size={size} onClick={handleClearSearch}/>;
} else if (actionIcon) {
action = <Button icon={actionIcon} size={size}/>;
} else if (action) {
action = <Button size={size}>{action}</Button>;
}
export function ExternalLink(props) {
return (
<Link to={props.to} target='_blank' className={props.className} rel='noopener noreferrer'>
{props.children}
</Link>
)
}
export function MoreButton(props) {
return (
<Grid columns={1} textAlign='center'>
<Grid.Row>
<Grid.Column>
<Button
onClick={props.onClick}
size='big'
style={{marginTop: '1em'}}
disabled={props.disabled}
>
{props.children}
More
</Button>
</Grid.Column>
</Grid.Row>
</Grid>
)
return <Form onSubmit={localOnSubmit} {...props}>
<Input
placeholder={placeholder}
type='text'
onChange={(e) => setValue(e.target.value)}
value={value}
size={size}
action={action}
/>
</Form>
}
export const useWROLMode = () => {
@ -601,16 +548,18 @@ export const useWROLMode = () => {
}
export function WROLModeMessage({content}) {
let enabled = useWROLMode();
if (enabled) {
const settings = useContext(SettingsContext);
const wrol_mode = settings ? settings.wrol_mode : null;
if (wrol_mode) {
return <Message icon='lock' header='WROL Mode Enabled' content={content}/>
}
return null;
}
// Thanks https://www.npmjs.com/package/text-ellipsis
export function textEllipsis(str, maxLength, {side = "end", ellipsis = "..."} = {}) {
if (str.length > maxLength) {
export function textEllipsis(str, maxLength = 100, {side = "end", ellipsis = "..."} = {}) {
if (str && str.length > maxLength) {
switch (side) {
case "start":
return ellipsis + str.slice(-(maxLength - ellipsis.length));
@ -623,55 +572,47 @@ export function textEllipsis(str, maxLength, {side = "end", ellipsis = "..."} =
}
export function TabLinks({links}) {
return (
<Menu tabular>
{links.map((link) =>
<NavLink
to={link.to}
className={'item'}
exact={link.exact || false}
style={{padding: '1em'}}
key={link.key}
>
{link.text}
</NavLink>
)}
</Menu>
)
return (<Menu tabular>
{links.map((link) => <NavLink
to={link.to}
className='item'
style={{padding: '1em'}}
key={link.to}
end={link.end === true ? true : null}
>
{link.text}
</NavLink>)}
</Menu>)
}
export function PageContainer(props) {
return (
<>
<Responsive minWidth={770}>
<Container fluid style={{marginTop: '1em', padding: '1em'}}>
{props.children}
</Container>
</Responsive>
<Responsive maxWidth={769}>
<Container style={{marginTop: '1em', padding: 0}}>
{props.children}
</Container>
</Responsive>
</>
)
return (<>
<Responsive minWidth={770}>
<Container fluid style={{marginTop: '1em', padding: '1em'}}>
{props.children}
</Container>
</Responsive>
<Responsive maxWidth={769}>
<Container style={{marginTop: '1em', padding: 0}}>
{props.children}
</Container>
</Responsive>
</>)
}
export function CardGroupCentered(props) {
return (
<>
<Responsive minWidth={770}>
<Card.Group>
{props.children}
</Card.Group>
</Responsive>
<Responsive maxWidth={769}>
<Card.Group centered>
{props.children}
</Card.Group>
</Responsive>
</>
)
return (<div style={{marginTop: '1em'}}>
<Responsive minWidth={770}>
<Card.Group>
{props.children}
</Card.Group>
</Responsive>
<Responsive maxWidth={769}>
<Card.Group centered>
{props.children}
</Card.Group>
</Responsive>
</div>)
}
export function HelpPopup({icon, size, content, position}) {
@ -679,64 +620,109 @@ export function HelpPopup({icon, size, content, position}) {
content={content}
size={size || null}
position={position || 'left center'}
trigger={
<Icon circular link name={icon || 'question'} size='small'
style={{marginLeft: '0.25em', marginRight: '0.25em'}}
/>}
trigger={<Icon circular link name={icon || 'question'} size='small'
style={{marginLeft: '0.25em', marginRight: '0.25em'}}
/>}
/>
}
export function HelpHeader({icon, headerSize, iconSize, headerContent, popupContent}) {
return (
<div className='inline-header'>
<Header as={headerSize || 'h2'}>{headerContent}</Header>
<span>
return (<div className='inline-header'>
<Header as={headerSize || 'h2'}>{headerContent}</Header>
<span>
<HelpPopup content={popupContent} size={iconSize} icon={icon}/>
</span>
</div>
)
</div>)
}
export function HotspotToggle(props) {
export function HotspotToggle() {
let {on, setHotspot} = useHotspot();
const disabled = on === null;
return (
<>
<Checkbox toggle {...props}
label='WiFi Hotspot'
disabled={disabled}
checked={on === true}
onChange={(e, data) => setHotspot(data.checked)}
/>
{disabled && <HelpPopup content='Hotspot is not supported on this server'/>}
</>
);
return (<div style={{margin: '0.5em'}}>
<Toggle
label='WiFi Hotspot'
disabled={disabled}
checked={on === true}
onChange={(e, data) => setHotspot(data.checked)}
/>
{disabled && <HelpPopup content='Hotspot is not supported on this server'/>}
</div>);
}
export function ThrottleToggle(props) {
export function ThrottleToggle() {
let {on, setThrottle} = useThrottle();
const disabled = on === null;
return (
<>
<Checkbox toggle {...props}
label='CPU Power-save'
disabled={disabled}
checked={on === true}
onChange={(e, data) => setThrottle(data.checked)}
/>
{disabled && <HelpPopup content='CPU Power-save is not supported on this server'/>}
</>
);
return (<div style={{margin: '0.5em'}}>
<Toggle
label='CPU Power-save'
disabled={disabled}
checked={on === true}
onChange={(e, data) => setThrottle(data.checked)}
/>
{disabled && <HelpPopup content='CPU Power-save is not supported on this server'/>}
</div>);
}
export function Toggle({label, checked, disabled, onChange, icon}) {
// Custom toggle because Semantic UI does not handle inverted labels correctly.
const {i, t} = useContext(ThemeContext);
const inverted = i && i['inverted'] === true ? 'inverted' : '';
let style = {marginLeft: '1em'};
if (t && t.style) {
style = {...t.style, ...style};
}
disabled = disabled === true ? 'disabled' : '';
let inputClassName = `${disabled} ${inverted}`;
let sliderClassName = `${disabled} ${inverted} slider`;
if (inverted) {
style['color'] = '#dddddd';
}
if (disabled && inverted) {
style['color'] = '#888888';
}
let onMouseUp;
if (onChange) {
onMouseUp = (e) => {
if (disabled) {
return;
}
e.preventDefault();
if (onChange) {
onChange(!checked);
}
}
}
if (icon) {
icon = <Icon name={icon}/>
}
return <>
<div className='toggle' onMouseUp={onMouseUp}>
<input type="checkbox" className={inputClassName} checked={checked} onChange={onMouseUp}/>
<span className={sliderClassName}></span>
</div>
<span style={style}>
{icon}
{label}
</span>
</>
}
export function DisableDownloadsToggle() {
let {on, setDownloads} = useDownloaders();
return <Checkbox toggle
label={on ? 'Downloading Enabled' : 'Downloading Disabled'}
disabled={on === null}
checked={on === true}
onChange={(e, data) => setDownloads(data.checked)}
/>;
return <Form>
<Toggle toggle
label={on ? 'Downloading Enabled' : 'Downloading Disabled'}
disabled={on === null}
checked={on === true}
onChange={setDownloads}
/>
</Form>;
}
export function emptyToNull(obj) {
@ -750,10 +736,95 @@ export function emptyToNull(obj) {
return obj;
}
export function minutesToTimestamp(minutes) {
minutes = Math.round(minutes);
const hours = String(Math.floor(minutes / 60)).padStart(1, '0');
minutes = minutes - (hours * 60);
minutes = String(minutes).padStart(2, '0');
return `${hours}:${minutes}`
export function mimetypeColor(mimetype) {
try {
if (mimetype === 'application/pdf') {
return 'red'
} else if (mimetype && mimetype.startsWith('video/')) {
return 'blue'
} else if (mimetype && mimetype.startsWith('image/')) {
return 'pink'
} else if (mimetype && mimetype.startsWith('text/html')) {
return 'green'
} else if (mimetype && mimetype.startsWith('application/zip')) {
return 'purple'
}
} catch (e) {
console.error(e);
console.error('Unable to choose mimetype color');
}
return 'grey'
}
export function FileIcon({file, disabled = true, size = 'huge', ...props}) {
// Default to a grey file icon.
const {mimetype} = file;
props['name'] = 'file';
props['color'] = mimetypeColor(mimetype);
if (mimetype) {
if (mimetype.startsWith('text/html') || mimetype.startsWith('application/json')) {
props['name'] = 'file code';
} else if (mimetype.startsWith('application/pdf')) {
props['name'] = 'file pdf';
} else if (mimetype.startsWith('text/plain')) {
props['name'] = 'file text';
} else if (mimetype.startsWith('image/')) {
props['name'] = 'image';
} else if (mimetype.startsWith('video/')) {
props['name'] = 'film';
} else if (mimetype.startsWith('application/zip')) {
props['name'] = 'file archive';
} else if (mimetype.startsWith('application/x-iso9660-image')) {
props['name'] = 'dot circle';
}
}
return <Icon disabled={disabled} size={size} {...props}/>
}
export function LoadStatistic({label, value, cores, ...props}) {
let color;
const quarter = cores / 4;
if (cores && value >= (quarter * 3)) {
color = 'red';
} else if (cores && value >= (quarter * 2)) {
color = 'orange';
}
return <Statistic label={label} value={value ? parseFloat(value).toFixed(1) : '?'} color={color}
{...props}/>;
}
export function DarkModeToggle() {
const {theme, setDarkTheme, setLightTheme} = useContext(ThemeContext);
const darkMode = theme === darkTheme;
const toggleDarkMode = () => {
if (darkMode) {
setLightTheme();
} else {
setDarkTheme();
}
}
return <>
<Toggle checked={darkMode} onChange={toggleDarkMode} icon={darkMode ? 'moon' : 'sun'}/>
</>
}
export function useTitle(title) {
const documentDefined = typeof document !== 'undefined';
const originalTitle = React.useRef(documentDefined ? document.title : null);
useEffect(() => {
if (!documentDefined) {
return;
}
const newTitle = `${title} - WROLPi`
if (title && document.title !== newTitle) {
document.title = newTitle;
}
return () => {
document.title = originalTitle.current;
}
}, []);
}

View file

@ -1,11 +1,41 @@
import React from "react";
import React, {useContext} from "react";
import FileBrowser from 'react-keyed-file-browser';
import {Button, Confirm, Header, Icon, Modal} from "semantic-ui-react";
import {
Card,
Checkbox,
Confirm,
Divider,
Dropdown,
Image, PlaceholderLine,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableRow,
} from "semantic-ui-react";
import 'react-keyed-file-browser/dist/react-keyed-file-browser.css';
import {deleteFile, refreshFiles} from "../api";
import {Paginator, humanFileSize, PageContainer, SearchInput, TabLinks} from "./Common";
import {useBrowseFiles, useSearchFiles} from "../hooks/customHooks";
import {Route} from "react-router-dom";
import {deleteFile, refreshDirectoryFiles, refreshFiles} from "../api";
import {
ArchiveRow,
CardGroupCentered,
ExternalCardLink,
FileIcon,
humanFileSize,
mimetypeColor,
PageContainer,
Paginator,
textEllipsis,
uploadDate,
VideoCard,
VideoRow
} from "./Common";
import {useBrowseFiles, useQuery, useSearchFiles} from "../hooks/customHooks";
import {Route, Routes} from "react-router-dom";
import {CardPlacholder} from "./Placeholder";
import {ArchiveCard} from "./Archive";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {ThemeContext} from "../contexts/contexts";
import {Button, Icon, Placeholder, Segment, Table} from "./Theme";
const icons = {
File: <Icon name='file'/>,
@ -16,42 +46,33 @@ const icons = {
};
export function Files() {
const {searchFiles, setPage, totalPages, activePage, searchStr, setSearchStr} = useSearchFiles(50);
const {t} = useContext(ThemeContext);
const {browseFiles, setOpenFolders, fetchFiles} = useBrowseFiles();
const [deleteOpen, setDeleteOpen] = React.useState(false);
const [previewOpen, setPreviewOpen] = React.useState(false);
const [selectedFile, setSelectedFile] = React.useState(null);
const [selectedDirectory, setSelectedDirectory] = React.useState(null);
const handleFolderChange = async (file, browserProps) => {
let openFolders = Object.keys(browserProps.openFolders);
setOpenFolders(openFolders);
}
const onDownloadFile = async () => {
// Open file in new tab/window.
window.open(`/media/${selectedFile.key}`);
}
const onSelectFile = async (file) => {
setSelectedFile(file);
openPreview();
const onSelect = async (file) => {
// A user can only select one file or one directory.
if (file.key.endsWith('/')) {
setSelectedFile(null);
setSelectedDirectory(file);
} else {
setSelectedDirectory(null);
setSelectedFile(file);
}
}
const onDeleteFile = async () => {
await deleteFile(selectedFile.key);
await fetchFiles();
closePreview();
}
const openPreview = () => {
setPreviewOpen(true);
}
const closePreview = () => {
setPreviewOpen(false);
setSelectedFile(null);
setDeleteOpen(false);
}
const openDelete = () => {
@ -62,95 +83,427 @@ export function Files() {
setDeleteOpen(false);
}
let selectedModal = <></>;
if (selectedFile) {
selectedModal = (
<Modal closeIcon
open={previewOpen}
onClose={closePreview}
>
<Modal.Header><Icon name='file'/>File Preview</Modal.Header>
<Modal.Content>
<Header>{selectedFile.name}</Header>
<p>{humanFileSize(selectedFile.size)}</p>
</Modal.Content>
<Modal.Actions>
<Button color='red' onClick={openDelete} floated='left'>Delete</Button>
<Confirm
open={deleteOpen}
content={`Are you sure you want to delete ${selectedFile.key}`}
onCancel={closeDelete}
onConfirm={onDeleteFile}
/>
<Button color='green' onClick={onDownloadFile}>Download</Button>
</Modal.Actions>
</Modal>);
const clearSelection = async (e) => {
e.preventDefault();
setOpenFolders(null);
setSelectedDirectory(null);
setSelectedFile(null);
await fetchFiles();
}
let browser;
let pagination = null;
if (searchStr) {
browser = (<FileBrowser
showActionBar={false}
canFilter={false}
files={searchFiles}
icons={icons}
onSelectFile={onSelectFile}
detailRenderer={() => <></>} // Hide the preview that the 3rd party provided.
/>);
pagination = (
<div style={{marginTop: '3em', textAlign: 'center'}}>
<Paginator
activePage={activePage}
changePage={setPage}
totalPages={totalPages}
/>
</div>);
let clearButton = <Button
onClick={clearSelection}
disabled={!!!selectedFile && !!!selectedDirectory}>
Clear
</Button>;
let buttons;
if (selectedFile) {
buttons = <>
<ExternalCardLink to={`/media/${selectedFile.key}`}>
<Button primary>Open</Button>
</ExternalCardLink>
<Confirm
open={deleteOpen}
onCancel={closeDelete}
onConfirm={onDeleteFile}
content={`Are you sure you want to delete: ${selectedFile.key}`}
confirmButton='Delete'
/>
<Button floated='right' color='red' onClick={openDelete}>Delete</Button>
</>;
} else if (selectedDirectory) {
buttons = <>
<DirectoryFilesRefreshButton directory={selectedDirectory.key}/>
</>;
} else {
browser = (<FileBrowser
showActionBar={false}
canFilter={false}
files={browseFiles}
icons={icons}
onFolderOpen={handleFolderChange}
onFolderClose={handleFolderChange}
onSelectFile={onSelectFile}
detailRenderer={() => <></>} // Hide the preview that the 3rd party provided.
/>);
buttons = <FilesRefreshButton/>;
}
return <>
<SearchInput initValue={searchStr} onSubmit={setSearchStr}/>
{selectedModal}
{browser}
{pagination}
{clearButton}
{buttons}
<Divider/>
<div {...t}>
<FileBrowser
showActionBar={false}
canFilter={false}
files={browseFiles}
icons={icons}
onFolderOpen={handleFolderChange}
onFolderClose={handleFolderChange}
onSelect={onSelect}
detailRenderer={() => <></>} // Hide the preview that the 3rd party provided.
/>
</div>
</>
}
function ManageFiles() {
return (<>
<Button secondary
id='refresh_files'
onClick={refreshFiles}>
Refresh Files
</Button>
<label htmlFor='refresh_files'>
Find and index any new files.
</label>
</>)
function ImageCard({file}) {
const {s} = useContext(ThemeContext);
const url = `/media/${encodeURIComponent(file.path)}`;
let poster = <center className='card-icon'><FileIcon file={file}/></center>;
if (file.size && file.size < 50000000) {
// Image is less than 5mb, use it.
poster = <Image wrapped
src={url}
style={{position: 'relative', width: '100%'}}
/>;
}
return <Card color={mimetypeColor(file.mimetype)}>
<ExternalCardLink to={url}>
{poster}
</ExternalCardLink>
<Card.Content {...s}>
<Card.Header>
<ExternalCardLink to={url} className='no-link-underscore card-link'>
<p>{textEllipsis(file.title || file.stem || file.path, 100)}</p>
</ExternalCardLink>
</Card.Header>
<Card.Meta {...s}>
<p>{uploadDate(file.modified / 1000)}</p>
</Card.Meta>
<Card.Description {...s}>
<p>{humanFileSize(file.size)}</p>
</Card.Description>
</Card.Content>
</Card>
}
export function FilesRoute(props) {
const links = [
{text: 'Files', to: '/files', exact: true, key: 'files'},
{text: 'Manage', to: '/files/manage', exact: true, key: 'manage'},
];
function FileCard({file}) {
const {s} = useContext(ThemeContext);
if (file.model === 'video' && file['video']) {
return <VideoCard key={file['path']} file={file}/>;
} else if (file.model === 'archive' && file['archive']) {
return <ArchiveCard key={file['path']} file={file}/>;
} else if (file.mimetype && file.mimetype.startsWith('image/')) {
return <ImageCard key={file['path']} file={file}/>;
}
const url = `/media/${encodeURIComponent(file.path)}`;
const color = mimetypeColor(file.mimetype);
return <Card color={color}>
<ExternalCardLink to={url}>
<center className='card-icon'>
<FileIcon file={file}/>
</center>
</ExternalCardLink>
<Card.Content {...s}>
<Card.Header>
<ExternalCardLink to={url}>
{textEllipsis(file.title || file.stem || file.path)}
</ExternalCardLink>
</Card.Header>
</Card.Content>
</Card>
}
export function FileCards({files}) {
if (files && files.length > 0) {
return <CardGroupCentered>
{files.map((i) => <FileCard key={i['path']} file={i}/>)}
</CardGroupCentered>
} else if (files && files.length === 0) {
return <p>No files found.</p>
} else {
return <CardGroupCentered><CardPlacholder/></CardGroupCentered>
}
}
function ImageRow({file, checkbox}) {
const url = `/media/${encodeURIComponent(file.path)}`;
let poster = <FileIcon file={file} size='large'/>;
if (file.size && file.size < 50000000) {
// Image is less than 5mb, use it.
poster = <Image wrapped src={url} width='50px'/>;
}
return (
<PageContainer>
<TabLinks links={links}/>
<Route path='/files' exact component={Files}/>
<Route path='/files/manage' exact component={ManageFiles}/>
</PageContainer>
);
<Table.Row>
{checkbox}
<Table.Cell>
<center>
{poster}
</center>
</Table.Cell>
<Table.Cell>
<ExternalCardLink to={url}>
<p>{textEllipsis(file.title || file.stem || file.path, 100)}</p>
</ExternalCardLink>
</Table.Cell>
</Table.Row>
)
}
function FileRow({file, selectOn, onSelect}) {
let checkbox;
if (selectOn) {
const localOnSelect = (e, {checked}) => {
try {
onSelect(file.key, checked);
} catch (e) {
console.error('No onSelect declared');
}
};
checkbox = <Table.Cell>
<Checkbox onChange={localOnSelect}/>
</Table.Cell>
}
if (file.model === 'video' && 'video' in file) {
return <VideoRow key={file['path']} file={file} checkbox={checkbox}/>;
} else if (file.model === 'archive' && 'archive' in file) {
return <ArchiveRow key={file['path']} file={file} checkbox={checkbox}/>;
} else if (file.mimetype && file.mimetype.startsWith('image/')) {
return <ImageRow key={file['path']} file={file} checkbox={checkbox}/>;
}
const onDownloadFile = async () => window.open(`/media/${file.key}`);
return <TableRow>
{checkbox}
<TableCell>
<center><FileIcon file={file} size='large'/></center>
</TableCell>
<TableCell onClick={() => onDownloadFile()}>
{textEllipsis(file.title)}
</TableCell>
</TableRow>
}
export function FileTable({files, selectOn, onSelect}) {
if (files && files.length > 0) {
return (
<Table unstackable striped compact='very'>
<TableHeader>
<TableRow>
{selectOn && <TableHeaderCell/>}
<TableHeaderCell>Poster</TableHeaderCell>
<TableHeaderCell>Title</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{files.map(i => <FileRow key={i['path']} file={i} selectOn={selectOn} onSelect={onSelect}/>)}
</TableBody>
</Table>
)
} else if (files && files.length === 0) {
return <Segment><p>No results!</p></Segment>
} else {
return <Placeholder>
<PlaceholderLine/>
<PlaceholderLine/>
<PlaceholderLine/>
</Placeholder>
}
}
export function FilesView({
files,
limit,
setLimit,
showLimit = false,
activePage,
totalPages,
view,
setView,
showView = true,
showSelect = false,
onSelect,
setPage,
menuColumnsCount,
menuColumns,
filterOptions,
activeFilters,
setFilters,
multipleFilters,
filterPlaceholder,
}) {
let selectButton;
const [selectOn, setSelectOn] = React.useState(false);
const toggleSelectOn = () => setSelectOn(!selectOn);
const selectButtonDisabled = view !== 'list';
if (showSelect && selectOn) {
selectButton = <Button active disabled={selectButtonDisabled} icon='checkmark box'
onClick={toggleSelectOn}/>;
} else if (showSelect) {
selectButton = <Button icon='checkmark box' disabled={selectButtonDisabled}
onClick={toggleSelectOn}/>;
}
let viewButton;
if (showView) {
if (view === 'list') {
viewButton = <Button icon='th' onClick={() => setView('cards')}/>;
} else {
viewButton = <Button icon='browser' onClick={() => setView('list')}/>;
}
}
let limitDropdown;
const limitOptions = [
{key: 12, value: 12, text: '12'},
{key: 24, value: 24, text: '24'},
{key: 48, value: 48, text: '48'},
{key: 96, value: 96, text: '96'},
];
if (showLimit) {
limitDropdown = <Dropdown
compact
selection
placeholder='Limit'
options={limitOptions}
value={parseInt(limit || limitOptions[0]['value'])}
onChange={(e, {value}) => setLimit(value)}
/>
}
const paginator = <center style={{marginTop: '2em'}}>
<Paginator activePage={activePage} totalPages={totalPages} onPageChange={setPage}/>
</center>;
let body;
if (view === 'list') {
body = <FileTable files={files} selectOn={selectOn} onSelect={onSelect}/>;
} else {
body = <FileCards files={files}/>;
}
const filtersDropdown = <Dropdown selection clearable search
multiple={multipleFilters || undefined}
options={filterOptions}
placeholder={filterPlaceholder || 'Filters'}
onChange={(e, {value}) => setFilters(value)}
style={{marginLeft: '0.3em'}}
value={activeFilters}
/>;
return <>
<Grid columns={menuColumnsCount || 1} stackable>
<Grid.Column mobile={8} computer={6}>
{selectButton}
{viewButton}
{limitDropdown}
{filterOptions && filtersDropdown}
</Grid.Column>
{menuColumns}
</Grid>
{body}
{paginator}
</>
}
export function FilesSearchView({
showView = true,
showLimit = false,
showSelect = false,
emptySearch = false,
filterOptions,
mimetype,
model,
onSelect,
setFilters,
}) {
const {searchFiles, limit, setLimit, totalPages, activePage, setPage} =
useSearchFiles(24, emptySearch, mimetype, model);
const {searchParams, updateQuery} = useQuery();
const setView = (value) => updateQuery({view: value});
const view = searchParams.get('view');
const setMimetype = (value) => updateQuery({'mimetype': value});
filterOptions = filterOptions || [
{key: 'video', text: 'Video', value: 'video'},
{key: 'archive', text: 'Archive', value: 'text/html'},
{key: 'pdf', text: 'PDF', value: 'application/pdf'},
{key: 'zip', text: 'ZIP', value: 'application/zip'},
{key: 'image', text: 'Image', value: 'image'},
];
return <FilesView
files={searchFiles}
limit={limit}
setLimit={setLimit}
showLimit={showLimit}
activePage={activePage}
totalPages={totalPages}
view={view}
setView={setView}
showView={showView}
showSelect={showSelect}
onSelect={onSelect}
setPage={setPage}
filterOptions={filterOptions}
setFilters={setFilters || setMimetype}
/>
}
function FilesRefreshButton() {
const {t} = useContext(ThemeContext);
const [loading, setLoading] = React.useState(false);
const [name, setName] = React.useState('refresh');
const handleClick = async () => {
setLoading(true);
await refreshFiles();
setLoading(false);
setName('check');
}
return <>
<Button icon
labelPosition='left'
loading={loading}
id='refresh_files'
onClick={handleClick}>
<Icon name={name}/>
Refresh Files
</Button>
<label htmlFor='refresh_files' {...t}>
Find and index all files in the media directory.
</label>
</>;
}
function DirectoryFilesRefreshButton({directory}) {
const {t} = useContext(ThemeContext);
const [loading, setLoading] = React.useState(false);
const [name, setName] = React.useState('refresh');
const handleClick = async () => {
setLoading(true);
await refreshDirectoryFiles(directory);
setLoading(false);
setName('check');
}
return <>
<Button icon primary
labelPosition='left'
loading={loading}
id='refresh_files'
onClick={handleClick}>
<Icon name={name}/>
Refresh Directory
</Button>
<label htmlFor='refresh_files' {...t}>
Find and index all files in the directory.
</label>
</>;
}
export function FilesRoute() {
return (<PageContainer>
<Routes>
<Route path='/' exact element={<Files/>}/>
</Routes>
</PageContainer>);
}

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,19 @@
import React from "react";
import {HelpPopup, humanFileSize, PageContainer, TabLinks, WROLModeMessage} from "./Common";
import {Route} from "react-router-dom";
import {Route, Routes} from "react-router-dom";
import {getMapImportStatus, importMapFiles} from "../api";
import Table from "semantic-ui-react/dist/commonjs/collections/Table";
import {Button, Checkbox, Icon, Loader, Placeholder} from "semantic-ui-react";
import {
Checkbox,
PlaceholderLine,
TableBody,
TableCell,
TableFooter,
TableHeader,
TableHeaderCell,
TableRow
} from "semantic-ui-react";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {Button, Icon, Loader, Placeholder, Table} from "./Theme";
class ManageMap extends React.Component {
constructor(props) {
@ -76,28 +85,28 @@ class ManageMap extends React.Component {
let ref = React.createRef();
const {size, path, imported, time_to_import} = pbf;
let sizeCells = (<>
<Table.Cell>{humanFileSize(size)}</Table.Cell>
<Table.Cell>{humanFileSize(size * 25)}</Table.Cell>
<Table.Cell>{time_to_import}</Table.Cell>
<TableCell>{humanFileSize(size)}</TableCell>
<TableCell>{humanFileSize(size * 25)}</TableCell>
<TableCell>{time_to_import}</TableCell>
</>);
return <Table.Row key={path}>
<Table.Cell collapsing>
return <TableRow key={path}>
<TableCell collapsing>
<Checkbox
disabled={disabled}
ref={ref}
onChange={(e, data) => this.handleCheckbox(data.checked, pbf)}
/>
</Table.Cell>
<Table.Cell>
</TableCell>
<TableCell>
<a href={`/media/${path}`}>{path}</a>
</Table.Cell>
<Table.Cell>
</TableCell>
<TableCell>
{path === this.state.importing ?
<Loader active inline size='mini'/> :
imported ? 'yes' : 'no'}
</Table.Cell>
{size !== null ? sizeCells : <Table.Cell colSpan={3}/>}
</Table.Row>
</TableCell>
{size !== null ? sizeCells : <TableCell colSpan={3}/>}
</TableRow>
}
render() {
@ -170,19 +179,19 @@ class ManageMap extends React.Component {
let rows;
if (!files) {
// Fetch request is not complete.
rows = <Table.Row>
<Table.Cell/>
<Table.Cell colSpan={6}>
rows = <TableRow>
<TableCell/>
<TableCell colSpan={6}>
<Placeholder>
<Placeholder.Line/>
<Placeholder.Line/>
<PlaceholderLine/>
<PlaceholderLine/>
</Placeholder>
</Table.Cell>
</Table.Row>;
</TableCell>
</TableRow>;
} else if (files.length === 0) {
rows = <Table.Row>
<Table.Cell/><Table.Cell colSpan={5}>No PBF map files were found in <b>map/pbf</b></Table.Cell>
</Table.Row>;
rows = <TableRow>
<TableCell/><TableCell colSpan={5}>No PBF map files were found in <b>map/pbf</b></TableCell>
</TableRow>;
} else {
rows = files.map(i => this.tableRow(i, disabled));
}
@ -191,37 +200,35 @@ class ManageMap extends React.Component {
content='Upon importing, a PBF file will consume more disk space than the original file.'/>;
let timeHelpPopup = <HelpPopup content='Estimated for a Raspberry Pi 4'/>;
return (
<PageContainer>
<WROLModeMessage content='Cannot modify Map'/>
{dockerWarning}
{downloadMessage}
{importingLoader}
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell/>
<Table.HeaderCell>PBF File</Table.HeaderCell>
<Table.HeaderCell>Imported</Table.HeaderCell>
<Table.HeaderCell>Size</Table.HeaderCell>
<Table.HeaderCell>Space Required {spaceHelpPopup}</Table.HeaderCell>
<Table.HeaderCell>Time to Import {timeHelpPopup}</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{rows}
</Table.Body>
<Table.Footer>
<Table.Row>
<Table.HeaderCell/>
<Table.HeaderCell colSpan={5}>
{importButton}
</Table.HeaderCell>
</Table.Row>
</Table.Footer>
</Table>
</PageContainer>
);
return <PageContainer>
<WROLModeMessage content='Cannot modify Map'/>
{dockerWarning}
{downloadMessage}
{importingLoader}
<Table>
<TableHeader>
<TableRow>
<TableHeaderCell/>
<TableHeaderCell>PBF File</TableHeaderCell>
<TableHeaderCell>Imported</TableHeaderCell>
<TableHeaderCell>Size</TableHeaderCell>
<TableHeaderCell>Space Required {spaceHelpPopup}</TableHeaderCell>
<TableHeaderCell>Time to Import {timeHelpPopup}</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{rows}
</TableBody>
<TableFooter>
<TableRow>
<TableHeaderCell/>
<TableHeaderCell colSpan={5}>
{importButton}
</TableHeaderCell>
</TableRow>
</TableFooter>
</Table>
</PageContainer>
}
}
@ -241,13 +248,15 @@ function MapApp() {
export function MapRoute() {
const links = [
{text: 'Map', to: '/map', exact: true, key: 'map'},
{text: 'Manage', to: '/map/manage', exact: true, key: 'manage'},
{text: 'Map', to: '/map', key: 'map', end: true},
{text: 'Manage', to: '/map/manage', key: 'manage'},
];
return <div style={{marginTop: '2em'}}>
<TabLinks links={links}/>
<Route path='/map' exact component={MapApp}/>
<Route path='/map/manage' exact component={ManageMap}/>
<Routes>
<Route path='/' exact element={<MapApp/>}/>
<Route path='manage' exact element={<ManageMap/>}/>
</Routes>
</div>
}

View file

@ -1,6 +1,9 @@
import React from "react";
import React, {useContext} from "react";
import {NavLink} from "react-router-dom";
import {Dropdown, Menu, Responsive} from "semantic-ui-react";
import {SettingsContext, ThemeContext} from "../contexts/contexts";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {DarkModeToggle} from "./Common";
const responsiveWidth = 500;
@ -43,11 +46,12 @@ function MenuLink(props) {
}
if (!props.link.links) {
const exact = props.link.exact ? {exact: null} : {};
return (
<NavLink
className={classes}
exact={props.link.exact || false}
to={props.link.to}
{...exact}
>
{props.link.text}
</NavLink>
@ -60,10 +64,15 @@ function MenuLink(props) {
}
export function NavBar() {
const settings = useContext(SettingsContext);
const wrol_mode = settings ? settings.wrol_mode : null;
const topNavText = wrol_mode ? <>WROLPi&nbsp; <Icon name='lock'/></> : 'WROLPi';
const {i} = useContext(ThemeContext);
return (
<Menu>
<Menu {...i}>
{/*Always show WROLPi home button*/}
<MenuLink link={{to: '/', text: 'WROLPi', exact: true}}/>
<MenuLink link={{to: '/', text: topNavText, exact: true}}/>
{/*Show the links in a menu when on desktop*/}
{links.map((link) => {
@ -72,11 +81,17 @@ export function NavBar() {
)
})}
<Responsive minWidth={responsiveWidth} as={Menu.Menu} position="right">
<div style={{margin: '0.8em'}}>
<DarkModeToggle/>
</div>
{rightLinks.map((link) => <MenuLink link={link} key={link.key}/>)}
</Responsive>
{/*Show the menu items in a dropdown when on mobile*/}
<Responsive as={Menu.Menu} maxWidth={responsiveWidth - 1} position='right'>
<div style={{margin: '0.8em'}}>
<DarkModeToggle/>
</div>
<Dropdown item icon="bars">
<Dropdown.Menu>
{collapsedLinks.map((link) =>

View file

@ -1,21 +1,29 @@
import {Card, Placeholder} from "semantic-ui-react";
import React from "react";
import {Card, PlaceholderImage, PlaceholderLine} from "semantic-ui-react";
import React, {useContext} from "react";
import {ThemeContext} from "../contexts/contexts";
import {Placeholder} from "./Theme";
export function CardPlacholder() {
const {s} = useContext(ThemeContext);
return <Card>
<Placeholder>
<PlaceholderImage rectangular/>
</Placeholder>
<Card.Content {...s}>
<Placeholder>
<PlaceholderLine/>
<PlaceholderLine/>
<PlaceholderLine/>
</Placeholder>
</Card.Content>
</Card>
}
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>
<CardPlacholder/>
</Card.Group>
)
}
@ -23,29 +31,8 @@ export function VideoPlaceholder() {
export function ChannelPlaceholder() {
return (
<Placeholder>
<Placeholder.Line length='long'/>
<Placeholder.Line length='short'/>
<PlaceholderLine length='long'/>
<PlaceholderLine 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>
)
}

154
app/src/components/Theme.js Normal file
View file

@ -0,0 +1,154 @@
import React, {useContext} from 'react';
import {ThemeContext} from "../contexts/contexts";
import {
Accordion as ACCORDION,
Button as BUTTON,
Form as FORM,
FormField as FORM_FIELD,
FormGroup as FORM_GROUP,
FormInput as FORM_INPUT,
Header as HEADER,
Icon as ICON,
Loader as LOADER,
Menu as MENU,
Placeholder as PLACEHOLDER,
Popup as POPUP,
Progress as PROGRESS,
Segment as SEGMENT,
Statistic as STATISTIC,
StatisticGroup as STATISTIC_GROUP,
Tab as TAB,
Table as TABLE,
TabPane as TAB_PANE,
TextArea as TEXTAREA
} from "semantic-ui-react";
// Simple wrappers for Semantic UI elements to use the current theme.
const invertedNull = (props) => {
if (props['inverted'] === true) {
props['inverted'] = null;
}
return props;
}
export function Button(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <BUTTON {...props}/>
}
export function Accordion(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <ACCORDION {...props}/>
}
export function Header(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <HEADER {...props}/>
}
export function Form(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <FORM {...props}/>
}
export function FormField(props) {
const {i} = useContext(ThemeContext);
props = invertedNull({...i, ...props});
return <FORM_FIELD {...props}/>
}
export function FormGroup(props) {
const {i} = useContext(ThemeContext);
props = invertedNull({...i, ...props});
return <FORM_GROUP {...props}/>
}
export function FormInput(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <FORM_INPUT {...props}/>
}
export function Icon(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <ICON {...props}/>
}
export function Loader(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <LOADER {...props}/>
}
export function Menu(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <MENU {...props}/>
}
export function Placeholder(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <PLACEHOLDER {...props}/>
}
export function Popup(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <POPUP {...props}/>
}
export function Progress(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <PROGRESS {...props}/>
}
export function Segment(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <SEGMENT {...props}/>
}
export function Statistic(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <STATISTIC {...props}/>
}
export function StatisticGroup(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <STATISTIC_GROUP {...props}/>
}
export function Tab(props) {
const {i} = useContext(ThemeContext);
props = invertedNull({...i, ...props});
return <TAB {...props}/>
}
export function TabPane(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <TAB_PANE {...props}/>
}
export function Table(props) {
const {i} = useContext(ThemeContext);
props = {...i, ...props};
return <TABLE {...props}/>
}
export function TextArea(props) {
const {i} = useContext(ThemeContext);
props = invertedNull({...i, ...props});
return <TEXTAREA {...props}/>
}

View file

@ -1,9 +1,11 @@
import React, {useState} from "react";
import {Button, Form, Header, Loader, TextArea} from "semantic-ui-react";
import {getDownloaders, postDownload} from "../api";
import {frequencyOptions, rssFrequencyOptions, WROLModeMessage} from "./Common";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {ThemeContext} from "../contexts/contexts";
import {Button, Form, FormInput, Header, Loader, TextArea} from "./Theme";
import {FormDropdown} from "semantic-ui-react";
const validUrl = /^(http|https):\/\/[^ "]+$/;
@ -55,22 +57,22 @@ class Downloader extends React.Component {
let disabled = !this.state.urls || !this.state.valid || this.state.pending || !this.state.downloader;
const {header} = this.props;
return (
<Form onSubmit={this.submitDownload}>
<WROLModeMessage content='Downloading is disabled while WROL Mode is enabled'/>
<Header as='h3'>{header}</Header>
<Form.Field>
return <ThemeContext.Consumer>
{({i}) => (
<Form onSubmit={this.submitDownload}>
<WROLModeMessage content='Downloading is disabled while WROL Mode is enabled'/>
<Header as='h3'>{header}</Header>
<TextArea required
placeholder={'Enter one URL per line'}
name='urls'
onChange={this.handleInputChange}
value={this.state.urls}
/>
</Form.Field>
<Button content='Cancel' onClick={this.props.clearSelected}/>
<Button primary style={{marginTop: '1em'}} disabled={disabled}>Download</Button>
</Form>
)
<Button content='Cancel' onClick={this.props.clearSelected}/>
<Button primary style={{marginTop: '1em'}} disabled={disabled}>Download</Button>
</Form>
)}
</ThemeContext.Consumer>
}
}
@ -134,42 +136,41 @@ class ChannelDownload extends React.Component {
in the future.</Message.Content>
</Message>);
return (
<Form>
<Header as='h4'><Icon name='video'/> Channel / Playlist</Header>
<Form.Input
required
label='URL'
placeholder='https://example.com/channel/videos'
value={url}
error={error}
onChange={this.handleUrlChange}
/>
<Form.Dropdown
required
selection
label='Download Frequency'
name='download_frequency'
placeholder='Frequency'
options={this.freqOptions}
value={frequency}
selected={frequency}
onChange={this.handleFrequencyChange}
/>
return <Form>
<WROLModeMessage content='Downloading is disabled while WROL Mode is enabled'/>
<Header as='h4'><Icon name='video'/> Channel / Playlist</Header>
<FormInput
required
label='URL'
placeholder='https://example.com/channel/videos'
value={url}
error={error}
onChange={this.handleUrlChange}
/>
<FormDropdown
required
selection
label='Download Frequency'
name='download_frequency'
placeholder='Frequency'
options={this.freqOptions}
value={frequency}
selected={frequency}
onChange={this.handleFrequencyChange}
/>
{frequency === 0 && onceMessage}
{frequency === 0 && onceMessage}
<Button content='Cancel' onClick={this.props.clearSelected}/>
<Button
color='blue'
content='Download'
onClick={this.handleSubmit}
disabled={buttonDisabled}
/>
<Loader active={pending}/>
{success && <Icon name='check'/>}
</Form>
)
<Button content='Cancel' onClick={this.props.clearSelected}/>
<Button
color='blue'
content='Download'
onClick={this.handleSubmit}
disabled={buttonDisabled}
/>
<Loader active={pending}/>
{success && <Icon name='check'/>}
</Form>
}
}
@ -236,63 +237,68 @@ class RSSDownload extends ChannelDownload {
in the future.</Message.Content>
</Message>);
return (
<Form>
<Header as='h4'><Icon name='rss'/> RSS Feed</Header>
<Form.Input
required
label='URL'
placeholder='https://example.com/feed'
value={url}
error={error}
onChange={this.handleUrlChange}
/>
<Form.Dropdown
required
selection
label='Download Frequency'
name='download_frequency'
placeholder='Frequency'
options={this.freqOptions}
value={frequency}
selected={frequency}
onChange={this.handleFrequencyChange}
/>
{frequency === 0 && onceMessage}
<Form.Dropdown selection required
name='sub_downloader'
label='Downloader'
options={this.state.downloaders}
placeholder='Select a downloader'
onChange={this.handleInputChange}
/>
return <Form>
<WROLModeMessage content='Downloading is disabled while WROL Mode is enabled'/>
<Header as='h4'><Icon name='rss'/> RSS Feed</Header>
<FormInput
required
label='URL'
placeholder='https://example.com/feed'
value={url}
error={error}
onChange={this.handleUrlChange}
/>
<FormDropdown
required
selection
label='Download Frequency'
name='download_frequency'
placeholder='Frequency'
options={this.freqOptions}
value={frequency}
selected={frequency}
onChange={this.handleFrequencyChange}
/>
{frequency === 0 && onceMessage}
<FormDropdown selection required
name='sub_downloader'
label='Downloader'
options={this.state.downloaders}
placeholder='Select a downloader'
onChange={this.handleInputChange}
/>
<Button content='Cancel' onClick={this.props.clearSelected}/>
<Button
color='blue'
content='Download'
onClick={this.handleSubmit}
disabled={buttonDisabled}
/>
<Loader active={pending}/>
{success && <Icon name='check'/>}
</Form>
)
<Button content='Cancel' onClick={this.props.clearSelected}/>
<Button
color='blue'
content='Download'
onClick={this.handleSubmit}
disabled={buttonDisabled}
/>
<Loader active={pending}/>
{success && <Icon name='check'/>}
</Form>
}
}
export function Downloads() {
export function DownloadMenu({onOpen}) {
const [downloader, setDownloader] = useState();
const localOnOpen = (name) => {
setDownloader(name);
onOpen(name)
}
let body = (<>
<Button content='Videos' onClick={() => setDownloader('video')}/>
<Button content='Archive' onClick={() => setDownloader('archive')}/>
<Button content='Channel/Playlist' onClick={() => setDownloader('video_channel')}/>
<Button content='RSS Feed' onClick={() => setDownloader('rss')}/>
<Button content='Videos' onClick={() => localOnOpen('video')} style={{marginBottom: '1em'}}/>
<Button content='Archive' onClick={() => localOnOpen('archive')} style={{marginBottom: '1em'}}/>
<Button content='Channel/Playlist' onClick={() => localOnOpen('video_channel')}
style={{marginBottom: '1em'}}/>
<Button content='RSS Feed' onClick={() => localOnOpen('rss')} style={{marginBottom: '1em'}}/>
</>);
function clearSelected() {
setDownloader(null);
localOnOpen(null);
body = null;
}
@ -307,10 +313,8 @@ export function Downloads() {
body = downloader in downloaders ? downloaders[downloader] : body;
return (
<>
<Header as='h2'>Download</Header>
{body}
</>
)
return <>
<Header as='h2'>Download</Header>
{body}
</>
}

View file

@ -1,40 +1,57 @@
import React, {useState} from 'react';
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import React, {useContext, useState} from 'react';
import {deleteVideo, favoriteVideo} from "../api";
import Button from "semantic-ui-react/dist/commonjs/elements/Button";
import {Link} from "react-router-dom";
import {humanFileSize, humanNumber, secondsToTimestamp, uploadDate, VideoCard} from "./Common";
import {Confirm, Segment, Tab} from "semantic-ui-react";
import {Link, useNavigate, useParams} from "react-router-dom";
import {humanFileSize, humanNumber, PageContainer, secondsToTimestamp, uploadDate, useTitle, VideoCard} from "./Common";
import {Confirm} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import Container from "semantic-ui-react/dist/commonjs/elements/Container";
import {VideoPlaceholder} from "./Placeholder";
import {useChannel} from "../hooks/customHooks";
import {darkTheme, ThemeContext} from "../contexts/contexts";
import {Button, Header, Icon, Segment, Tab, TabPane} from "./Theme";
const MEDIA_PATH = '/media';
function VideoPage(props) {
let {video, channel} = props;
function VideoPage({videoFile, prevFile, nextFile, ...props}) {
const {theme} = useContext(ThemeContext);
const navigate = useNavigate();
let [deleteOpen, setDeleteOpen] = useState(false);
async function handleDeleteVideo(video_id) {
useTitle(videoFile === null || videoFile === undefined ? null : videoFile.video.title);
let video;
if (videoFile) {
video = videoFile.video;
}
// Get the Video's channel, fallback to the URL's channel id.
const {channelId} = useParams();
const {channel} = useChannel(video && video.channel_id ? video.channel_id : channelId);
if (videoFile === null) {
return <VideoPlaceholder/>;
}
if (videoFile === undefined) {
return <PageContainer><p>Could not find video</p></PageContainer>;
}
let favorite = video.favorite;
const handleDeleteVideo = async (video_id) => {
try {
await deleteVideo(video_id)
} catch (e) {
setDeleteOpen(false);
throw e;
}
props.history.goBack();
navigate(-1);
}
let videoUrl = `${MEDIA_PATH}/${encodeURIComponent(video.video_path)}`;
let posterUrl = null;
if (video.poster_path) {
posterUrl = `${MEDIA_PATH}/${encodeURIComponent(video.poster_path)}`;
}
let captionsUrl = null;
if (video.caption_path) {
captionsUrl = `${MEDIA_PATH}/${encodeURIComponent(video.caption_path)}`;
}
let posterUrl = video.poster_path ? `${MEDIA_PATH}/${encodeURIComponent(video.poster_path)}` : null;
let captionsUrl = video.caption_path ? `${MEDIA_PATH}/${encodeURIComponent(video.caption_path)}` : null;
let description = 'No description available.';
let viewCount = video.view_count;
@ -43,41 +60,33 @@ function VideoPage(props) {
viewCount = 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);
favorite = await favoriteVideo(video.id, !!!favorite);
}
let favorite_button;
if (favorite) {
favorite_button = (
<Button color='green' style={{'margin': '0.5em'}}
onClick={handleFavorite}>
<Icon name='heart'/>
Unfavorite
</Button>
);
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>
);
favorite_button = (<Button basic color='green' style={{'margin': '0.5em'}} onClick={handleFavorite}>
<Icon name='heart'/>
Favorite
</Button>);
}
let descriptionPane = {
menuItem: 'Description', render: () => <Tab.Pane>
menuItem: 'Description', render: () => <TabPane>
<pre className="wrap-text">
{description || 'No description'}
</pre>
</Tab.Pane>
</TabPane>
};
let aboutPane = {
menuItem: 'About', render: () => <Tab.Pane>
menuItem: 'About', render: () => <TabPane>
<h3>Size</h3>
<p>{video.size ? humanFileSize(video.size) : '???'}</p>
@ -95,89 +104,88 @@ function VideoPage(props) {
<h3>File Modification Time</h3>
<p>{video.modification_datetime ? secondsToTimestamp(video.modification_datetime) : null}</p>
</Tab.Pane>
</TabPane>
}
let captionsPane = {
menuItem: 'Captions', render: () => <Tab.Pane>
menuItem: 'Captions', render: () => <TabPane>
<pre>{video.caption}</pre>
</Tab.Pane>
</TabPane>
};
let tabPanes = [descriptionPane, aboutPane, captionsPane];
const tabMenu = theme === darkTheme ? {inverted: true, attached: true} : {attached: true};
return (
<>
<Container>
<Button
style={{marginTop: '1em', marginBottom: '1em'}}
onClick={() => props.history.goBack()}
>
<Icon name='left arrow'/>
Back
</Button>
</Container>
<video controls
autoPlay={props.autoplay !== undefined ? props.autoplay : true}
poster={posterUrl}
id="player"
playsInline={true}
style={{maxWidth: '100%'}}
return (<>
<Container>
<Button
style={{marginTop: '1em', marginBottom: '1em'}}
onClick={() => navigate(-1)}
>
<source src={videoUrl} type="video/mp4"/>
<track kind="captions" label="English captions" src={captionsUrl} srcLang="en" default/>
</video>
<Icon name='left arrow'/>
Back
</Button>
</Container>
<Container style={{marginTop: '1em'}}>
<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 || video.video_path}</h2>
{video.upload_date && <h3>{uploadDate(video.upload_date)}</h3>}
<h3>
{channel && <Link to={`/videos/channel/${channel.id}/video`}>
{channel.name}
</Link>}
</h3>
<Container style={{marginTop: '1em'}}>
<Segment>
<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>
<Header as='h2'>{video.title || video.video_path}</Header>
{video.upload_date && <h3>{uploadDate(video.upload_date)}</h3>}
<h3>
{channel && <Link to={`/videos/channel/${channel.id}/video`}>
{channel.name}
</Link>}
</h3>
<Tab panes={tabPanes}/>
<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>
<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>
</>
)
<Tab menu={tabMenu} panes={tabPanes}/>
<Grid columns={2} stackable>
<Grid.Row>
<Grid.Column textAlign='left'>
{prevFile && <><Header as='h3'>Older</Header><VideoCard file={prevFile}/></>}
</Grid.Column>
<Grid.Column textAlign='left'>
{nextFile && <><Header as='h3'>Newer</Header><VideoCard file={nextFile}/></>}
</Grid.Column>
</Grid.Row>
</Grid>
</Container>
</>)
}
export default VideoPage;

View file

@ -1,619 +1,193 @@
import React from 'react';
import {Link, Route} from "react-router-dom";
import OldPaginator, {
changePageHistory,
DEFAULT_LIMIT,
import {Link, Route, Routes, useParams} from "react-router-dom";
import {
defaultSearchOrder,
defaultVideoOrder,
humanFileSize,
PageContainer,
scrollToTop,
searchOrders,
secondsToString,
SearchInput,
TabLinks,
VideoCards,
videoOrders,
WROLModeMessage
useTitle,
videoOrders
} from "./Common"
import VideoPage from "./VideoPlayer";
import {download, getChannel, getStatistics, getVideo, refresh, searchVideos} from "../api";
import {
Button,
Dropdown,
Form,
Grid,
Header,
Icon,
Input,
Loader,
Modal,
Radio,
Segment,
Statistic
} from "semantic-ui-react";
import * as QueryString from 'query-string';
import Container from "semantic-ui-react/dist/commonjs/elements/Container";
import {Dropdown, PlaceholderHeader, PlaceholderLine, StatisticLabel, StatisticValue} from "semantic-ui-react";
import {Channels, EditChannel, NewChannel} from "./Channels";
import {VideoPlaceholder} from "./Placeholder";
import {useChannel, useQuery, useSearchVideos, useVideo, useVideoStatistics} from "../hooks/customHooks";
import {FilesView} from "./Files";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {Header, Loader, Placeholder, Segment, Statistic, StatisticGroup} from "./Theme";
class ManageVideos extends React.Component {
export function VideoWrapper() {
const {videoId} = useParams();
const {videoFile, prevFile, nextFile} = useVideo(videoId);
scrollToTop();
constructor(props) {
super(props);
this.state = {
streamUrl: null,
mostRecentDownload: '',
}
}
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});
}
}
render() {
return (
<Container fluid>
<WROLModeMessage content='Cannot modify Videos'/>
<p>
<Button secondary
id='refresh_videos'
onClick={this.refresh}
>
Refresh Video Files
</Button>
<label htmlFor='refresh_videos'>
Find any new video files. Remove any Videos which no longer have files.
</label>
</p>
</Container>
)
}
return <VideoPage videoFile={videoFile} prevFile={prevFile} nextFile={nextFile} autoplay={true}/>
}
export class VideoWrapper extends React.Component {
function Videos({filter}) {
const {channelId} = useParams();
const {searchParams, updateQuery} = useQuery();
constructor(props) {
super(props);
this.state = {
video: null,
prev: null,
next: null,
channel: null,
no_channel: null,
}
let searchOrder = defaultVideoOrder;
if (searchParams.get('order')) {
// Use whatever order the user specified.
searchOrder = searchParams.get('order');
} else if (searchParams.get('q')) {
// User used a search_str
searchOrder = defaultSearchOrder;
}
async componentDidMount() {
await this.fetchVideo();
let filtersEnabled = searchParams.getAll('filter');
filtersEnabled = filter ? [...filtersEnabled, filter] : filtersEnabled;
const {searchStr, setSearchStr, videos, activePage, setPage, limit, setLimit, totalPages, setOrderBy} =
useSearchVideos(null, channelId, searchOrder, filtersEnabled);
const setView = (value) => updateQuery({view: value});
const view = searchParams.get('view');
const {channel} = useChannel(channelId);
const filterOptions = [
{text: 'Favorites', key: 'favorite', value: 'favorite'},
{text: 'Censored', key: 'censored', value: 'censored'},
];
const setFilters = (value) => updateQuery({filter: value});
const menuColumns = <>
<Grid.Column mobile={8} computer={5}>
<SearchInput clearable searchStr={searchStr} onSubmit={setSearchStr} actionIcon='search'/>
</Grid.Column>
<Grid.Column mobile={6} computer={5}>
<Dropdown selection fluid
size='large'
placeholder='Sort by...'
value={searchOrder}
options={videoOrders}
onChange={(e, {value}) => setOrderBy(value)}
/>
</Grid.Column>
</>;
let header;
if (channel && channel.name) {
const editLink = `/videos/channel/${channelId}/edit`;
header = <>
<Header as='h1'>
{channel.name}
<Link to={editLink}>
<Icon name='edit' style={{marginLeft: '0.5em'}}/>
</Link>
</Header>
</>;
} else if (channelId) {
header = <Placeholder style={{marginBottom: '1em'}}>
<PlaceholderHeader>
<PlaceholderLine/>
</PlaceholderHeader>
</Placeholder>;
}
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_id = this.props.match.params.channel_id;
let channel = channel_id ? await getChannel(channel_id) : null;
let no_channel = false;
if (!channel) {
no_channel = true;
}
this.setState({video, prev, next, channel, no_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.no_channel || this.state.channel)) {
return <VideoPage {...this.state} history={this.props.history} autoplay={true}/>
} else {
return <VideoPlaceholder/>
}
}
}
export function VideosPreview({videos}) {
let body = <VideoPlaceholder/>
if (videos && videos.length === 0) {
body = <p>No videos available.</p>
} else if (videos && videos.length > 0) {
body = <VideoCards videos={videos}/>
}
return <>
{body}
{header}
<FilesView
files={videos}
view={view}
limit={limit}
activePage={activePage}
totalPages={totalPages}
showView={true}
showLimit={true}
showSelect={true}
setView={setView}
setLimit={setLimit}
setPage={setPage}
filterOptions={filterOptions}
activeFilters={filtersEnabled}
setFilters={setFilters}
multipleFilters={true}
menuColumnsCount={3}
menuColumns={menuColumns}
>
</FilesView>
</>
}
function FilterModal(props) {
/*
Expecting props.filters = [
{label: 'Favorites', name: 'favorite', value: false},
{label: 'Censored', name: 'censored', value: false},
function Statistics() {
const {statistics} = useVideoStatistics();
const {videos, historical, channels} = statistics;
if (!videos) {
return <Loader active inline='centered'/>
}
const 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'},
];
*/
let inputs = props.filters.map((i) =>
<Form.Input>
<Radio toggle
checked={i.value}
label={i.label}
onClick={!i.disabled ? () => props.toggleFilter(i.name) : null}
disabled={i.disabled}
/>
</Form.Input>
)
const historicalNames = [
{key: 'average_count', label: 'Average Monthly Downloads'},
{key: 'average_size', label: 'Average Monthly Usage'},
];
const channelNames = [
{key: 'channels', label: 'Channels'},
];
const buildSegment = (title, names, stats) => {
return <Segment>
<Header textAlign='center' as='h1'>{title}</Header>
<StatisticGroup>
{names.map(
({key, label}) =>
<Statistic key={key} style={{margin: '2em'}}>
<StatisticValue>{stats[key]}</StatisticValue>
<StatisticLabel>{label}</StatisticLabel>
</Statistic>
)}
</StatisticGroup>
</Segment>
}
return (
<Modal closeIcon open={props.open} onClose={props.onClose} onOpen={props.onOpen} size='mini'>
<Modal.Header>{props.header}</Modal.Header>
<Modal.Content>
<Modal.Description>
<Form>
{inputs}
</Form>
</Modal.Description>
</Modal.Content>
<Modal.Actions>
{props.applyButton && <Button color='blue'>Apply</Button>}
<Button color='black' onClick={props.onClose}>Close</Button>
</Modal.Actions>
</Modal>
)
}
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;
let filtersEnabled = query.f && query.f.length > 0 ? query.f.split(',') : [];
let filters = [
{
label: 'Favorites',
name: 'favorite',
value: filtersEnabled.indexOf('favorite') >= 0 || props.filter === 'favorite',
disabled: props.filter === 'favorite',
},
{
label: 'Censored',
name: 'censored',
value: filtersEnabled.indexOf('censored') >= 0
},
];
this.state = {
activePage,
channel: null,
filters,
filtersEnabled,
filtersOpen: false,
header: '',
limit: DEFAULT_LIMIT,
next: null,
prev: null,
queryStr: searchStr,
searchOrder,
searchStr: '',
totalPages: null,
videoOrders: searchStr === '' ? videoOrders : searchOrders,
videos: null,
};
}
async componentDidMount() {
if (this.props.match.params.channel_id) {
await this.fetchChannel();
} else {
await this.fetchVideos();
}
this.setHeader();
}
async componentDidUpdate(prevProps, prevState, snapshot) {
let params = this.props.match.params;
let channelChanged = params.channel_id !== prevProps.match.params.channel_id;
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();
// TODO this causes a double search request. This will be fixed with a custom hook.
await this.fetchVideos();
}
}
setHeader() {
let header = '';
if (this.props.header) {
header = this.props.header;
} else if (this.state.channel) {
header = this.state.channel.name;
} else {
// Find the matching header 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) {
header = item.title;
}
}
}
this.setState({header: header});
}
async fetchChannel() {
// Get and display the channel specified in the Router match
let channel_id = this.props.match.params.channel_id;
let channel = null;
if (channel_id) {
channel = await getChannel(channel_id);
}
this.setState({
channel,
title: channel ? channel.title : '',
offset: 0,
total: null,
videos: null,
video: null,
},
this.fetchVideos);
}
enabledFilters = () => {
let filters = this.state.filters;
let filtersArr = [];
for (let i = 0; i < filters.length; i++) {
let filter = filters[i];
if (filter['value'] === true) {
filtersArr = filtersArr.concat([filter['name']]);
}
}
return filtersArr;
}
async fetchVideos() {
this.setState({videos: null});
let offset = this.state.limit * this.state.activePage - this.state.limit;
let channel_id = this.state.channel ? this.state.channel.id : null;
let {queryStr, searchOrder, limit} = this.state;
// Pass any enabled filters to the search.
let filtersArr = this.enabledFilters();
try {
let [videos, total] = await searchVideos(offset, limit, channel_id, queryStr, searchOrder, filtersArr);
let totalPages = Math.round(total / this.state.limit) || 1;
this.setState({videos, totalPages});
} catch (e) {
console.error(e);
}
}
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;
let filters = this.enabledFilters();
changePageHistory(history, location, activePage, queryStr, searchOrder, filters);
}
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);
}
toggleFilter = (name) => {
let filters = this.state.filters;
let filtersEnabled = [];
for (let i = 0; i < filters.length; i++) {
let filter = filters[i];
if (filter.name === name) {
filter.value = !filter.value;
}
if (filter.value) {
filtersEnabled = filtersEnabled.concat([filter.name]);
}
}
this.setState({filters, filtersEnabled});
}
applyFilters = async () => {
this.applyStateToHistory();
await this.fetchVideos();
}
closeFilters = () => {
this.setState({filtersOpen: false}, this.applyFilters);
}
openFilters = () => {
this.setState({filtersOpen: true});
}
render() {
let {
activePage,
channel,
queryStr,
searchOrder,
searchStr,
header,
totalPages,
videoOrders,
videos,
filtersEnabled,
} = this.state;
let body = <Container fluid style={{marginTop: '1em'}}><VideoPlaceholder/></Container>;
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'}}>
<OldPaginator
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 fluid>
<Grid columns={4} stackable>
<Grid.Column textAlign='left' width={6}>
<h1>
{header}
{
channel &&
<>
&nbsp;
&nbsp;
<Link to={`/videos/channel/${channel.id}/edit`}>
<Icon name="edit"/>
</Link>
</>
}
</h1>
{queryStr && clearSearchButton}
</Grid.Column>
<Grid.Column width={1}>
<Button icon onClick={this.openFilters} color={filtersEnabled.length > 0 ? 'black' : null}>
<Icon name='filter'/>
</Button>
<FilterModal
applyFilters={this.applyFilters}
open={this.state.filtersOpen}
onClose={this.closeFilters}
header='Filter Videos'
filters={this.state.filters}
toggleFilter={this.toggleFilter}
applyButton={null}
/>
</Grid.Column>
<Grid.Column textAlign='right' width={5}>
<Form onSubmit={this.handleSearch}>
<Input
fluid
icon='search'
placeholder='Search...'
name="searchStr"
value={searchStr}
onChange={this.handleInputChange}/>
</Form>
</Grid.Column>
<Grid.Column width={4}>
<Dropdown
size='large'
placeholder='Sort by...'
selection
fluid
name='searchOrder'
onChange={this.changeSearchOrder}
value={searchOrder}
options={videoOrders}
disabled={searchOrder === defaultSearchOrder}
/>
</Grid.Column>
</Grid>
<Container fluid>
{body}
</Container>
{pagination}
</Container>
)
}
}
function ManageTab(props) {
return (
<Container fluid>
<ManageVideos/>
<Statistics/>
</Container>
<>
{buildSegment('Videos', videoNames, videos)}
{buildSegment('Historical Video', historicalNames, historical)}
{buildSegment('Channels', channelNames, channels)}
</>
)
}
export function VideosRoute(props) {
useTitle('Videos');
const links = [
{text: 'Videos', to: '/videos', exact: true, key: 'videos'},
{text: 'Videos', to: '/videos', key: 'videos', end: true},
{text: 'Favorites', to: '/videos/favorites', key: 'favorites'},
{text: 'Channels', to: '/videos/channel', key: 'channel'},
{text: 'Manage', to: '/videos/manage', key: 'manage'},
{text: 'Statistics', to: '/videos/statistics', key: 'statistics'},
];
return (
<PageContainer>
<TabLinks links={links}/>
<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='favorite'
header='Favorite Videos'
/>
}/>
<Route path='/videos/channel' exact component={Channels}/>
<Route path='/videos/manage' exact component={ManageTab}/>
<Route path='/videos/channel/new' exact component={NewChannel}/>
<Route path='/videos/channel/:channel_id/edit' exact
component={(i) =>
<EditChannel
match={i.match}
history={i.history}
/>
}
/>
<Route path='/videos/channel/:channel_id/video' exact component={Videos}/>
<Routes>
<Route path='/' exact element={<Videos/>}/>
<Route path='favorites' exact element={<Videos filter='favorite' header='Favorite Videos'/>}/>
<Route path='channel' exact element={<Channels/>}/>
<Route path='statistics' exact element={<Statistics/>}/>
<Route path='channel/new' exact element={<NewChannel/>}/>
<Route path='channel/:channelId/edit' exact element={<EditChannel/>}/>
<Route path='channel/:channelId/video' exact element={<Videos/>}/>
</Routes>
</PageContainer>
)
}
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() {
try {
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});
} catch (e) {
console.error(e);
}
}
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'/>
}
}
}