import React, {useState} from "react";
import {
AccordionContent,
AccordionTitle,
Grid,
Input,
Responsive,
StatisticLabel,
StatisticValue,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableRow,
} from "semantic-ui-react";
import {createChannel, deleteChannel, downloadChannel, refreshChannel, updateChannel, validateRegex} from "../api";
import {
BackButton,
DirectoryInput,
frequencyOptions,
humanFileSize,
isEmpty,
isoDatetimeToString,
RequiredAsterisk,
secondsToFrequency,
Toggle,
useTitle,
WROLModeMessage
} from "./Common";
import {Link, useNavigate, useParams} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import Confirm from "semantic-ui-react/dist/commonjs/addons/Confirm";
import {ChannelPlaceholder} from "./Placeholder";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {useChannel, useChannels} from "../hooks/customHooks";
import {toast} from "react-semantic-toasts";
import _ from "lodash";
import {
Accordion,
Button,
Form,
FormField,
FormGroup,
FormInput,
Header,
Loader,
Segment,
Statistic,
Table
} from "./Theme";
import Dropdown from "semantic-ui-react/dist/commonjs/modules/Dropdown";
function ChannelStatistics({statistics}) {
if (!statistics) {
return <>>
}
return (
{statistics.video_count}
Videos
{humanFileSize(statistics.size, true)}
Total Size
{humanFileSize(statistics.largest_video, true)}
Largest Video
)
}
function ChannelPage({create, header}) {
const [loading, setLoading] = useState(false);
const [disabled, setDisabled] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const [validRegex, setValidRegex] = useState(true);
const [activeIndex, setActiveIndex] = useState(-1);
const [errors, setErrors] = useState({});
const [error, setError] = useState(false);
const [success, setSuccess] = useState(false);
const [messageHeader, setMessageHeader] = useState();
const [messageContent, setMessageContent] = useState();
const navigate = useNavigate();
const {channelId} = useParams();
const {channel, changeValue, fetchChannel} = useChannel(channelId);
let title;
if (channel && channel.name) {
title = channel.name;
}
useTitle(title);
if (!channel) {
return ;
}
const checkRegex = async (e, {value}) => {
changeValue('match_regex', value);
const valid = await validateRegex(value);
setValidRegex(valid);
}
const handleCheckbox = (e, {name, checked}) => {
if (e) {
e.preventDefault();
}
changeValue(name, checked);
}
const handleInputChange = (e, {name, value}) => {
if (e) {
e.preventDefault();
}
changeValue(name, value);
}
const setErrorMessage = (header, message) => {
setError(true);
setSuccess(false);
setMessageHeader(header);
setMessageContent(message);
}
const setSuccessMessage = (header, message) => {
setError(false);
setSuccess(true);
setMessageHeader(header);
setMessageContent(message);
}
const handleSubmit = async (e) => {
e.preventDefault();
const body = {
name: channel.name,
directory: channel.directory,
mkdir: channel.mkdir,
url: channel.url,
download_frequency: channel.download_frequency,
match_regex: channel.match_regex,
};
setDisabled(true);
setLoading(true);
let response = null;
try {
if (create !== undefined) {
response = await createChannel(body);
} else {
response = await updateChannel(channelId, body);
}
} catch (e) {
console.error(e);
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not save channel',
time: 5000,
});
return;
} finally {
setDisabled(false);
setLoading(false);
}
if (response && response.status >= 200 && response.status < 300) {
let location = response.headers.get('Location');
let channelResponse = await fetch(location);
let data = await channelResponse.json();
let channel = data['channel'];
if (response.status === 201) {
setSuccessMessage(
'Channel created',
Your channel was created. View it here
);
} else {
await fetchChannel();
setSuccessMessage('Channel updated', 'Your channel was updated');
}
} else if (response) {
// Some error occurred.
let error = await response.json();
let cause = error.cause;
if (error.code === 3 || (cause && cause.code === 3)) {
setErrorMessage(
'Invalid directory',
'This directory does not exist.',
'directory',
);
} else if (cause && cause.code === 7) {
setErrorMessage(
'Invalid directory',
'This directory is already used by another channel',
'directory',
);
} else if (cause && cause.code === 5) {
setErrorMessage(
'Invalid name',
'This channel name is already taken',
'name',
);
} else {
setErrorMessage('Invalid channel', 'Unable to save channel. See logs.');
}
} else {
console.error('Did not get a response for channel!');
}
}
const handleAdvancedClick = (e, {index}) => {
setActiveIndex(activeIndex === index ? -1 : index);
}
const handleDownloadChannel = async (e) => {
e.preventDefault();
return await downloadChannel(channelId);
}
const handleRefreshChannel = async (e) => {
e.preventDefault();
return await refreshChannel(channelId);
}
const handleDeleteConfirm = async () => {
setDeleteOpen(false);
let response = await deleteChannel(channelId);
if (response.status === 204) {
navigate('/videos/channel');
} else {
setSuccessMessage('Failed to delete', 'Failed to delete this channel, check logs.');
}
}
const handleDeleteButton = (e) => {
e.preventDefault();
setDeleteOpen(true);
}
return <>
{!create &&
}
{channel.statistics && }
>
}
export function EditChannel(props) {
return ;
}
export function NewChannel(props) {
useTitle('New Channel');
return
}
function ChannelRow({channel}) {
const navigate = useNavigate();
const editTo = `/videos/channel/${channel.id}/edit`;
const videosTo = `/videos/channel/${channel.id}/video`;
return
{channel.name}
{channel.video_count}
{channel.url && channel.info_date ? isoDatetimeToString(channel.info_date) : null}
{channel.url && channel.download_frequency ? secondsToFrequency(channel.download_frequency) : null}
;
}
function MobileChannelRow({channel}) {
const editTo = `/videos/channel/${channel.id}/edit`;
const videosTo = `/videos/channel/${channel.id}/video`;
return
{channel.name}
Videos: {channel.video_count}
Edit
;
}
export function Channels() {
useTitle('Channels');
const {channels} = useChannels();
const [searchStr, setSearchStr] = useState('');
const handleInputChange = (e, {value}) => {
e.preventDefault();
setSearchStr(value);
}
let header =
;
let tableHeader =
Name
Videos
Last Update
Frequency
Manage
;
if (channels === null) {
// Placeholders while fetching
return <>
{header}
>
} else if (isEmpty(channels)) {
return <>
{header}
No channels exist yet!
Create one.
>
}
let filteredChannels = channels;
if (searchStr) {
const re = new RegExp(_.escapeRegExp(searchStr), 'i');
filteredChannels = channels.filter(i => re.test(i['name']));
}
return <>
{header}
{tableHeader}
{filteredChannels.map(channel => )}
{filteredChannels.map(channel => )}
>
}