import React, {useContext, useEffect, useState} from "react"; import { Button as SButton, ButtonGroup, Card, Confirm, Container, IconGroup, Input, Label, Pagination, Search, Transition } from 'semantic-ui-react'; import {Link, NavLink, useNavigate, useSearchParams} from "react-router-dom"; import Message from "semantic-ui-react/dist/commonjs/collections/Message"; import { useDirectories, useHotspot, useSearchDirectories, useSearchOrder, useSettings, useThrottle, useWROLMode } from "../hooks/customHooks"; import {Media, StatusContext, ThemeContext} from "../contexts/contexts"; import { Button, CardIcon, darkTheme, Form, Header, Icon, lightTheme, Menu, Modal, ModalActions, ModalContent, ModalDescription, ModalHeader, Popup, Statistic } from "./Theme"; import {FilePreviewContext} from "./FilePreview"; import _ from "lodash"; import {killDownloads, startDownloads} from "../api"; import Grid from "semantic-ui-react/dist/commonjs/collections/Grid"; export const API_URI = process.env && process.env.REACT_APP_API_URI ? process.env.REACT_APP_API_URI : `${window.location.protocol}//${window.location.host}/api`; export const VIDEOS_API = `${API_URI}/videos`; export const ARCHIVES_API = `${API_URI}/archive`; export const OTP_API = `${API_URI}/otp`; export const ZIM_API = `${API_URI}/zim`; export const DEFAULT_LIMIT = 20; export const NAME = process.env && process.env.REACT_APP_NAME ? process.env.REACT_APP_NAME : null; export function Paginator({activePage, onPageChange, totalPages, showFirstAndLast, size = 'mini'}) { const handlePageChange = (e, {activePage}) => { onPageChange(activePage); } return <> } export function divmod(x, y) { return [Math.floor(x / y), x % y]; } export function secondsElapsed(seconds) { // Convert the provided seconds into a human-readable string of the time elapsed between the provided timestamp // and now. if (!seconds || seconds < 0) { return null; } // Get seconds elapsed between now and `seconds` which is a UTC epoch. const localNow = (new Date()).getTime(); let years; let days; let hours; let minutes; seconds = Math.abs((localNow / 1000) - seconds); [years, seconds] = divmod(seconds, secondsToYears); [days, seconds] = divmod(seconds, secondsToDays); [hours, seconds] = divmod(seconds, secondsToHours); [minutes, seconds] = divmod(seconds, secondsToMinutes); seconds = Math.floor(seconds); if (years > 0 && days > 30) { return `${years}y${days}d`; } else if (years > 0) { return `${years}y`; } else if (days > 0) { return `${days}d`; } else if (hours > 0) { return `${hours}h`; } else if (minutes > 0) { return `${minutes}m`; } return `${seconds}s` } export function secondsToElapsedPopup(seconds) { // Return a Popup which allows the user see a more detailed timestamp when hovering. const elapsed = secondsElapsed(seconds); if (!elapsed) { return <>; } return {elapsed}} /> } export function isoDatetimeToElapsedPopup(dt) { let d = new Date(dt); return secondsToElapsedPopup(d.getTime() / 1000); } export function secondsToDuration(video) { let duration = video.duration; let hours = Math.floor(duration / 3600); duration -= hours * 3600; let minutes = Math.floor(duration / 60); let seconds = duration - (minutes * 60); hours = String('00' + hours).slice(-2); minutes = String('00' + minutes).slice(-2); seconds = String('00' + seconds).slice(-2); return [hours, minutes, seconds]; } export function Duration({video}) { let [hours, minutes, seconds] = secondsToDuration(video); if (hours > 0) { return
{hours}:{minutes}:{seconds}
} else if (video.duration) { return
{minutes}:{seconds}
} else { return <> } } export function isoDatetimeToString(dt) { // Convert a datetime to a human-readable date format. let d = ; if (dt) { d = new Date(dt); d = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`; } return d; } 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 {props.children} } export function ExternalCardLink({to, ...props}) { const {t} = useContext(ThemeContext); return {props.children} } export function PreviewLink({file, children, className, ...props}) { const {t} = useContext(ThemeContext); const {setPreviewFile} = React.useContext(FilePreviewContext); className = className ? `clickable ${className}` : `clickable `; return setPreviewFile(file)} {...props} {...t}> {children} } export function PreviewPath({path, mimetype, ...props}) { return } export function RequiredAsterisk() { return * } export let defaultVideoOrder = '-upload_date'; export let defaultSearchOrder = 'rank'; export const frequencyOptions = [{key: null, text: '', value: null}, { key: 'daily', text: 'Daily', value: 86400 }, {key: 'weekly', text: 'Weekly', value: 604800}, {key: 'biweekly', text: 'Biweekly', value: 1209600}, { key: '30days', text: '30 Days', value: 2592000 }, {key: '90days', text: '90 Days', value: 7776000},]; export const rssFrequencyOptions = [{key: 'once', text: 'Once', value: 0}, { key: 'hourly', text: 'Hourly', value: 3600 }, {key: '3hours', text: '3 hours', value: 10800}, {key: '12hours', text: '12 hours', value: 43200}, { key: 'daily', text: 'Daily', value: 86400 }, {key: 'weekly', text: 'Weekly', value: 604800}, {key: 'biweekly', text: 'Biweekly', value: 1209600}, { key: '30days', text: '30 Days', value: 2592000 }, {key: '90days', text: '90 Days', value: 7776000}, {key: '180days', text: '180 Days', value: 15552000}]; export function secondsToFrequency(seconds) { for (let i = 0; i < Object.keys(rssFrequencyOptions).length; i++) { let d = rssFrequencyOptions[i]; if (d.value === seconds) { return d.text; } } return null; } const secondsToYears = 31536000; const secondsToDays = 86400; const secondsToHours = 3600; const secondsToMinutes = 60; export function secondsToFullDuration(seconds) { let s = ''; let years, days, hours, minutes; [years, seconds] = divmod(seconds, secondsToYears); [days, seconds] = divmod(seconds, secondsToDays); [hours, seconds] = divmod(seconds, secondsToHours); [minutes] = divmod(seconds, secondsToMinutes); if (years > 0) { s = `${years}Y`; } if (days > 0) { s = `${s} ${days}D`; } if (hours > 0 || minutes > 0) { hours = String(hours).padStart(2, '0'); minutes = String(minutes).padStart(2, '0'); s = `${s} ${hours}:${minutes}`; } return s; } export function secondsToTimestamp(seconds) { let d = new Date(seconds * 1000); const month = String(d.getMonth() + 1).padStart(2, '0'); const day = String(d.getDate()).padStart(2, '0'); const hours = String(d.getHours()).padStart(2, '0'); const minutes = String(d.getMinutes()).padStart(2, '0'); const sec = String(d.getSeconds()).padStart(2, '0'); return `${d.getFullYear()}-${month}-${day} ${hours}:${minutes}:${sec}`; } export function humanFileSize(bytes, dp = 1) { const thresh = 1024; if (Math.abs(bytes) < thresh) { return bytes + ' B'; } const units = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; let u = -1; const r = 10 ** dp; do { bytes /= thresh; ++u; } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1); return bytes.toFixed(dp) + ' ' + units[u]; } export function humanBandwidth(bytes) { // Convert bytes to MBps and return a string. const thresh = 1024; if (Math.abs(bytes) < thresh) { return bytes + ' Bps'; } const units = ['KBps', 'MBps', 'GBps', 'TBps', 'PBps', 'EBps', 'ZBps', 'YBps']; let u = -1; const r = 10; do { bytes /= thresh; ++u; } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1); return bytes.toFixed(0) + ' ' + units[u]; } export function humanNumber(num, dp = 1) { // Convert large numbers to a more human-readable format. // >> humanNumber(1000) // 1.0k // >> humanNumber(1500000) // 1.5m const divisor = 1000; if (Math.abs(num) < divisor) { return num; } const units = ['k', 'm', 'b']; let i = -1; const r = 10 ** dp; do { num /= divisor; ++i; } while (Math.round(Math.abs(num) * r) / r >= divisor && i < units.length - 1); return num.toFixed(dp) + units[i]; } export function replaceNullValues(obj, newValue) { newValue = newValue === undefined ? '' : newValue; let keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { let key = keys[i]; obj[key] = obj[key] === null ? newValue : obj[key]; } } export function enumerate(array) { let newArray = []; for (let i = 0; i < array.length; i++) { newArray = newArray.concat([[i, array[i]]]); } return newArray; } export function arraysEqual(a, b) { if (a === b) return true; if (a == null || b == null) return false; if (a.length !== b.length) return false; for (var i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; } export function scrollToTop() { window.scrollTo({ top: 0, behavior: "auto" }); } export function scrollToTopOfElement(element, smooth = true) { element.scroll({ top: 0, behavior: smooth ? 'smooth' : 'auto', }); } export function SearchInput({ searchStr, onSubmit, size = 'small', placeholder, action, actionIcon, clearable, autoFocus = false, onClear = null, ...props }) { let [value, setValue] = useState(searchStr || ''); const handleClearSearch = (e) => { e.preventDefault(); // Clear the input when the "clear" button is clicked, search again. setValue(''); onSubmit(''); if (onClear) { onClear(); } } const localOnSubmit = (e) => { // Send the value up when submitting. e.preventDefault(); onSubmit(value); } if ((action || actionIcon) && searchStr && searchStr === value && clearable) { action = ; } return
setValue(e.target.value)} value={value} size={size} action={action} />
} export function WROLModeMessage({content}) { const wrolModeEnabled = useWROLMode(); if (wrolModeEnabled) { return } return null; } // Thanks https://www.npmjs.com/package/text-ellipsis 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)); case "end": default: return str.slice(0, maxLength - ellipsis.length) + ellipsis; } } return str; } export function TabLinks({links}) { const [searchParams, setSearchParams] = useSearchParams(); const getTo = (to) => { return `${to}?${searchParams.toString()}`; } return {links.map((link) => {link.text} )} } export function PageContainer(props) { return <> {props.children} {props.children} ; } export function CardGroupCentered(props) { return
{props.children} {props.children}
} export function findPosterPath(file) { if (!file) { return; } const {files, poster_path, cover_path, screenshot_path, video} = file; if (poster_path) { return poster_path; } if (cover_path) { return cover_path; } if (screenshot_path) { return screenshot_path; } if (file['data'] && file['data']['cover_path']) { // Ebook. return file['data']['cover_path']; } if (video && video['poster_path']) { // file is a video model. return video['poster_path']; } if (!_.isEmpty(files)) { for (let i = 0; i < files.length; i++) { const file = files[i]; if (file['mimetype'] && file['mimetype'].startsWith('image/')) { // Found an image file, use that as the poster. return file['path']; } } } } export function CardPoster({to, file}) { const {s} = useContext(ThemeContext); // Used to center posters in CardIcon. const style = {display: 'flex', justifyContent: 'center', ...s['style']}; const navigate = useNavigate(); const cardTagIcon =
; let imageLabel = !_.isEmpty(file.tags) ? cardTagIcon : null; let posterPath = findPosterPath(file); if (!posterPath && to && (to.startsWith('/download/') || to.startsWith('/media/'))) { // No poster, link is to download a file directly. return { window.location.href = to; return null }}> {imageLabel} } else if (!posterPath && to) { // No poster, link to the full page. return navigate(to)}> {imageLabel} } else if (!posterPath) { // No poster, no to, use a Preview. return {imageLabel} } posterPath = `/media/${encodeMediaPath(posterPath)}`; const image = <> {/* Replicate but with maxHeight applied to image */} {imageLabel} poster ; if (to) { // Link using React Router. return {image} } else { // Preview the file. return
{image}
} } export function HelpPopup({icon, size, content, position, iconSize = 'small'}) { return } /> } export function HelpHeader({icon, headerSize, iconSize, headerContent, popupContent}) { return
{headerContent}
} export function HotspotToggle() { let {on, setHotspot} = useHotspot(); const disabled = on === null; return
setHotspot(checked)} /> {disabled && }
; } export function ThrottleToggle() { let {on, setThrottle} = useThrottle(); const disabled = on === null; return
setThrottle(checked)} /> {disabled && }
; } export function Toggle({label, checked, disabled, onChange, icon}) { // Custom toggle because Semantic UI does not handle inverted labels correctly. const {t, inverted} = useContext(ThemeContext); 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 = } return <>
{icon} {label} } export function DisableDownloadsToggle() { const [pending, setPending] = React.useState(false); const {status, fetchStatus} = React.useContext(StatusContext); const {downloads} = status ? status : {downloads: null}; const wrolModeEnabled = useWROLMode(); const setDownloads = async (enable) => { setPending(true); if (enable) { await startDownloads(); } else { await killDownloads(); } await fetchStatus(); setPending(false); } const on = downloads && downloads['disabled'] === false && downloads['stopped'] === false; return
; } export function emptyToNull(obj) { const keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { const key = keys[i]; if (obj[key] === '') { obj[key] = null; } } return obj; } export function mimetypeColor(mimetype) { if (!mimetype) { return 'grey'; } try { if (mimetype === 'application/pdf') { return 'red' } else if (mimetype.startsWith('video/')) { return 'blue' } else if (mimetype.startsWith('image/')) { return 'pink' } else if (mimetype.startsWith('text/html')) { return 'green' } else if (mimetype.startsWith('application/zip') || mimetype.startsWith('application/zlib') || mimetype.startsWith('application/x-7z-compressed') || mimetype.startsWith('application/x-bzip2') || mimetype.startsWith('application/x-xz')) { return 'purple' } else if (mimetype.startsWith('application/epub') || mimetype.startsWith('application/x-mobipocket-ebook')) { return 'yellow' } else if (mimetype.startsWith('audio/')) { return 'violet' } } catch (e) { console.error(e); console.error('Unable to choose mimetype color'); } return 'grey' } export function isZipMimetype(mimetype) { return mimetype.startsWith('application/zip') || mimetype.startsWith('application/zlib') || mimetype.startsWith('application/x-7z-compressed') || mimetype.startsWith('application/x-bzip2') || mimetype.startsWith('application/x-xz') || mimetype.startsWith('application/gzip') || mimetype.startsWith('application/x-rar'); } export function mimetypeIconName(mimetype, lowerPath = '') { if (mimetype) { if (mimetype.startsWith('text/html') || mimetype.startsWith('application/json') || mimetype.startsWith('text/yaml') || mimetype.startsWith('text/xml')) { return 'file code'; } else if (mimetype.startsWith('application/pdf')) { return 'file pdf'; } else if (mimetype.startsWith('text/plain')) { return 'file text'; } else if (mimetype.startsWith('image/')) { return 'image'; } else if (mimetype.startsWith('video/')) { return 'film'; } else if (mimetype.startsWith('message/rfc822')) { return 'mail'; } else if (isZipMimetype(mimetype)) { return 'file archive'; } else if (mimetype.startsWith('application/x-iso9660-image') || mimetype.startsWith('application/x-raw-disk-image') || mimetype.startsWith('application/x-cd-image')) { return 'dot circle'; } else if (mimetype.startsWith('application/epub') || mimetype.startsWith('application/x-mobipocket-ebook') || mimetype.startsWith('application/vnd.amazon.mobi8-ebook')) { return 'book'; } else if (mimetype.startsWith('text/vtt') || mimetype.startsWith('text/srt')) { return 'closed captioning'; } else if (mimetype.startsWith('application/x-openscad') || mimetype.startsWith('model/stl')) { return 'cube'; } else if (mimetype.startsWith('application/x-dosexec') || mimetype.startsWith('application/x-msi')) { return 'microsoft'; } else if (mimetype.startsWith('audio/')) { return 'file audio'; } else if (mimetype.startsWith('application/vnd.openxmlformats-officedocument.wordprocessingml.document')) { return 'file word'; } else if (mimetype.startsWith('application/x-x509-ca-cert')) { return 'certificate'; } else if (mimetype.startsWith('application/octet-stream')) { if (lowerPath.endsWith('.mp3')) { return 'file audio'; } else if (lowerPath.endsWith('.stl')) { return 'cube'; } else if (lowerPath.endsWith('.blend')) { return 'cube'; } else if (lowerPath.endsWith('.dmg')) { return 'apple'; } else if (lowerPath.endsWith('.azw3')) { return 'book'; } } else if (mimetype.startsWith('application/vnd.openxmlformats-officedocument.spreadsheetml.') || mimetype.startsWith('application/vnd.ms-excel') || mimetype.startsWith('application/vnd.oasis.opendocument.spreadsheet')) { return 'file excel' } else if (mimetype.startsWith('application/vnd.openxmlformats-officedocument.wordprocessingml.') || mimetype.startsWith('application/msword') || mimetype.startsWith('application/vnd.oasis.opendocument.text')) { return 'file word' } else if (mimetype.startsWith('application/vnd.openxmlformats-officedocument.presentationml.') || mimetype.startsWith('application/vnd.ms-powerpoint') || mimetype.startsWith('application/vnd.oasis.opendocument.presentation')) { return 'file powerpoint' } } if (lowerPath.endsWith('.pem')) { return 'certificate'; } return 'file'; } export function FileIcon({file, disabled = true, size = 'huge', ...props}) { // Default to a grey file icon. const {mimetype, path, primary_path} = file; // `file` may be a file_group or a file. const lowerPath = primary_path ? primary_path.toLocaleString() : path.toLowerCase(); props['name'] = mimetypeIconName(mimetype, lowerPath); props['color'] = mimetypeColor(mimetype); return } export function LoadStatistic({label, value, cores, ...props}) { const quarter = cores / 4; if (cores && value >= (quarter * 3)) { props['color'] = 'red'; } else if (cores && value >= (quarter * 2)) { props['color'] = 'orange'; } return ; } export function DarkModeToggle() { const {savedTheme, cycleSavedTheme} = useContext(ThemeContext); let iconName = 'lightbulb outline'; if (savedTheme === darkTheme) { iconName = 'moon'; } else if (savedTheme === lightTheme) { iconName = 'sun'; } return } export function UnsupportedModal(header, message, icon) { const [open, setOpen] = useState(false); const onOpen = () => setOpen(true); const onClose = () => setOpen(false); const modal =
{header || 'Unsupported'}
{message}
; return {modal, doClose: onClose, doOpen: onOpen}; } export function HotspotStatusIcon() { const {on, setHotspot, dockerized} = useHotspot(); const {modal, doOpen} = UnsupportedModal('Unsupported on Docker', 'You cannot toggle the hotspot on Docker.'); const toggleHotspot = (e) => { e.preventDefault(); if (dockerized) { doOpen(); } if (on != null) { setHotspot(!on); } } return <> {on === false && } {on === null && } {modal} } export function useTitle(title) { const documentDefined = typeof document !== 'undefined'; const originalTitle = React.useRef(documentDefined ? document.title : null); const name = NAME ? `${NAME} WROLPi` : `WROLPi`; useEffect(() => { if (!documentDefined) { return; } const newTitle = `${title} - ${name}` if (title && document.title !== newTitle) { document.title = newTitle; } return () => { document.title = originalTitle.current; } }, [title]); } export function DirectorySearch({onSelect, value, ...props}) { const { directoryName, setDirectoryName, directories, channelDirectories, domainDirectories, loading, } = useSearchDirectories(value); const [results, setResults] = useState(); useEffect(() => { if ( (directories && directories.length >= 0) || (channelDirectories && channelDirectories.length >= 0) || (domainDirectories && domainDirectories.length >= 0)) { setResults({ directories: { name: 'Directories', results: directories.map(i => { return {title: i['path']} }), }, channel_directories: { name: 'Channels', results: channelDirectories.map(i => { return {title: i['path'], description: i['name']}; }), }, domain_directories: { name: 'Domains', results: domainDirectories.map(i => { return {title: i['path'], description: i['domain']}; }), } }); } }, [ JSON.stringify(directories), JSON.stringify(channelDirectories), JSON.stringify(domainDirectories), loading, ]); const handleSearchChange = (e, data) => { if (e) { e.preventDefault(); } if (onSelect) { onSelect(''); } setDirectoryName(data.value); } const handleResultSelect = (e, data) => { if (e) { e.preventDefault(); } // title is the relative path. if (onSelect) { onSelect(data.result.title); } setDirectoryName(data.result.title); } const handleClear = (e) => { if (e) { e.preventDefault(); } onSelect(''); setDirectoryName(''); } return }) } return <> setOpen(false)} > Sort By {sortFields} : {buttonContent}; // Wrap button in to show success or failure animations. button = {button} ; if (confirmContent) { // Wrap button with button = <> {button} setConfirmOpen(false)} onCancel={() => setConfirmOpen(false)} onConfirm={localOnConfirm} /> } button = <> {button} return {button, ref} } export function APIButton({ color, size, floated, onClick, disabled, confirmContent, confirmButton, themed, obeyWROLMode, icon, ...props }) { const {button} = useAPIButton( color, size, floated, onClick, disabled, confirmContent, confirmButton, themed, obeyWROLMode, icon, props ); return button; }