Zim/Kiwix (Wikipedia) feature

* A new zim module has been added, this module allows several things to interact with Zim files.
  * Allow searching of Zim files using libzim.
  * Allow downloading of Kiwix projects (wikipedia, wikibooks, etc) on a schedule which replaces the outdated files.
  * Creation of a new zim docker container which allows viewing of the Zim file contents.

* This commit also adds move/rename/mkdir features in the File Browser.
  * File tags are preserved when moving/renaming.
This commit is contained in:
Roland 2023-05-29 18:04:03 -06:00
parent cc5ab4e339
commit 03a2df217d
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
117 changed files with 6393 additions and 1100 deletions

View file

@ -34,7 +34,7 @@ import {
textEllipsis,
useTitle
} from "./Common";
import {addTag, deleteArchives, postDownload, removeTag} from "../api";
import {deleteArchives, postDownload, tagFileGroup, untagFileGroup} from "../api";
import {Link, Route, Routes, useNavigate, useParams} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {useArchive, useDomains, useSearchArchives, useSearchDomain} from "../hooks/customHooks";
@ -146,12 +146,12 @@ function ArchivePage() {
}
const localAddTag = async (name) => {
await addTag(archiveFile, name);
await tagFileGroup(archiveFile, name);
await fetchArchive();
}
const localRemoveTag = async (name) => {
await removeTag(archiveFile, name);
await untagFileGroup(archiveFile, name);
await fetchArchive();
}
@ -359,7 +359,8 @@ function Archives() {
const onDelete = async (e) => {
e.preventDefault();
setDeleteOpen(false);
const archiveIds = archives.filter(i => selectedArchives.indexOf(i['path']) >= 0).map(i => i['archive']['id']);
const archiveIds = archives.filter(i => selectedArchives.indexOf(i['primary_path']) >= 0)
.map(i => i['archive']['id']);
await deleteArchives(archiveIds);
await fetchArchives();
setSelectedArchives([]);

View file

@ -1,6 +1,6 @@
import React, {useContext, useEffect, useState} from "react";
import {Button as SButton, ButtonGroup, Card, Container, IconGroup, Input, Pagination, Search} from 'semantic-ui-react';
import {Link, NavLink, useNavigate} from "react-router-dom";
import {ButtonGroup, Card, Container, IconGroup, Input, Label, Pagination, Search} 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,
@ -23,7 +23,8 @@ import {
Modal,
ModalActions,
ModalContent,
ModalDescription, ModalHeader,
ModalDescription,
ModalHeader,
Popup,
Statistic
} from "./Theme";
@ -36,6 +37,7 @@ export const API_URI = process.env && process.env.REACT_APP_API_URI ? process.en
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;
@ -215,7 +217,7 @@ export const rssFrequencyOptions = [{key: 'once', text: 'Once', value: 0}, {
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: '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++) {
@ -359,7 +361,7 @@ export function scrollToTop() {
});
}
export function scrollToTopOfElement(element, smooth=true) {
export function scrollToTopOfElement(element, smooth = true) {
element.scroll({
top: 0,
behavior: smooth ? 'smooth' : 'auto',
@ -375,6 +377,7 @@ export function SearchInput({
actionIcon,
clearable,
autoFocus = false,
onClear = null,
...props
}) {
let [value, setValue] = useState(searchStr || '');
@ -384,6 +387,9 @@ export function SearchInput({
// Clear the input when the "clear" button is clicked, search again.
setValue('');
onSubmit('');
if (onClear) {
onClear();
}
}
const localOnSubmit = (e) => {
@ -437,9 +443,15 @@ export function textEllipsis(str, maxLength = 100, {side = "end", ellipsis = "..
}
export function TabLinks({links}) {
const [searchParams, setSearchParams] = useSearchParams();
const getTo = (to) => {
return `${to}?${searchParams.toString()}`;
}
return <Menu tabular>
{links.map((link) => <NavLink
to={link.to}
to={getTo(link.to)}
className='item'
style={{padding: '1em'}}
key={link.to}
@ -771,6 +783,12 @@ export function mimetypeIconName(mimetype, lowerPath = '') {
} 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')) {
@ -1162,4 +1180,14 @@ export function SortButton({sorts = []}) {
<Button content={selectedSort['text']} onClick={() => setOpen(true)}/>
</ButtonGroup>
</>
}
export function TagIcon() {
return <Label circular color='green' style={{padding: '0.5em', marginRight: '0.5em'}}>
<Icon name='tag' style={{margin: 0}}/>
</Label>
}
export function normalizeEstimate(estimate) {
return estimate > 999 ? '>999' : estimate;
}

View file

@ -1,11 +1,23 @@
import {Button, Icon, Placeholder} from "./Theme";
import {Checkbox, Confirm, PlaceholderLine, TableCell, TableFooter, TableHeaderCell, TableRow} from "semantic-ui-react";
import {FileIcon, humanFileSize} from "./Common";
import React, {useEffect} from "react";
import {deleteFile} from "../api";
import {Button, Header, Icon, Modal, ModalActions, ModalContent, ModalHeader, Placeholder, Table} from "./Theme";
import {
Checkbox,
Confirm,
IconGroup,
Input,
PlaceholderLine,
TableBody,
TableCell,
TableFooter,
TableHeader,
TableHeaderCell,
TableRow
} from "semantic-ui-react";
import {DirectorySearch, FileIcon, humanFileSize} from "./Common";
import React, {useEffect, useState} from "react";
import {deleteFile, makeDirectory, movePaths, renamePath} from "../api";
import _ from 'lodash';
import {SortableTable} from "./SortableTable";
import {useBrowseFiles} from "../hooks/customHooks";
import {useBrowseFiles, useMediaDirectory} from "../hooks/customHooks";
import {DirectoryRefreshButton, FileRowTagIcon, FilesRefreshButton} from "./Files";
import {FilePreviewContext} from "./FilePreview";
@ -15,14 +27,40 @@ function depthIndentation(path) {
return '\xa0\xa0\xa0\xa0'.repeat(depth);
}
function Folder({folder, onFolderClick, sortData, selectedPath, onFileClick, onSelect}) {
export function pathDirectory(path) {
// Return the full path of the path's directory.
// pathDirectory('/some/directory/file.txt') -> '/some/directory'
return path.substring(0, path.lastIndexOf('/'));
}
export function pathName(path) {
// Return the file's name.
// pathName('/some/directory/file.txt') -> 'file.txt'
// pathName('/some/directory') -> 'directory'
if (path.endsWith('/')) {
// Path is a directory, return its name.
path = path.substring(0, path.length - 1);
}
return path.substring(path.lastIndexOf('/') + 1);
}
export function splitPathParentAndName(path) {
if (path.endsWith('/')) {
// Path is a directory, return its name.
path = path.substring(0, path.length - 1);
}
const slashIndex = path.lastIndexOf('/');
return [path.substring(0, slashIndex), path.substring(slashIndex + 1, path.length)];
}
function Folder({folder, onFolderClick, sortData, selectedPaths, onFileClick, onSelect, disabled}) {
// Creates a single table row for a folder, or a row for itself and indented rows for its children.
let {path, children, is_empty} = folder;
const pathWithNoTrailingSlash = path.substring(0, path.length - 1);
const name = path.substring(pathWithNoTrailingSlash.lastIndexOf('/') + 1);
const f = <TableRow key={path}>
const f = <TableRow key={path} disabled={disabled}>
<TableCell collapsing>
<Checkbox checked={selectedPath === folder['path']} onChange={() => onSelect(folder['path'])}/>
<Checkbox checked={selectedPaths.indexOf(folder['path']) >= 0} onChange={() => onSelect(folder['path'])}/>
</TableCell>
<TableCell onClick={() => onFolderClick(path)} className='file-path' colSpan={2} disabled={is_empty}>
{depthIndentation(pathWithNoTrailingSlash)}
@ -37,7 +75,7 @@ function Folder({folder, onFolderClick, sortData, selectedPath, onFileClick, onS
_.forEach(children, (p, k) => {
childPaths = [...childPaths,
<Path key={k} path={p} onFolderClick={onFolderClick} sortData={sortData} onFileClick={onFileClick}
selectedPath={selectedPath} onSelect={onSelect}/>];
selectedPaths={selectedPaths} onSelect={onSelect} disabled={disabled}/>];
});
return <React.Fragment>
{f}
@ -49,19 +87,18 @@ function Folder({folder, onFolderClick, sortData, selectedPath, onFileClick, onS
}
}
function File({file, onFileClick, selectedPath, onSelect}) {
function File({file, onFileClick, selectedPaths, onSelect, disabled}) {
const {path, size} = file;
const name = path.substring(path.lastIndexOf('/') + 1);
return <TableRow key={path}>
return <TableRow key={path} disabled={disabled}>
<TableCell collapsing>
<Checkbox checked={selectedPath === path} onChange={() => onSelect(path)}/>
<Checkbox checked={selectedPaths.indexOf(path) >= 0} onChange={() => onSelect(path)}/>
</TableCell>
<TableCell onClick={() => onFileClick(file)} className='file-path'>
{depthIndentation(path)}
<FileRowTagIcon file={file}/>
{/*null size to make icon the correct size*/}
<FileIcon file={file} size={null}/>
{name}
{pathName(path)}
</TableCell>
<TableCell collapsing textAlign='right'>
{humanFileSize(size)}
@ -69,31 +106,37 @@ function File({file, onFileClick, selectedPath, onSelect}) {
</TableRow>
}
function Path({path, onFolderClick, onFileClick, sortData, selectedPath, onSelect}) {
function Path({path, onFolderClick, onFileClick, sortData, selectedPaths, onSelect, disabled}) {
if (path['path'].endsWith('/')) {
return <Folder
folder={path}
onFolderClick={onFolderClick}
sortData={sortData}
selectedPath={selectedPath}
selectedPaths={selectedPaths}
onSelect={onSelect}
onFileClick={onFileClick}
disabled={disabled}
/>
} else {
return <File
file={path}
onFileClick={onFileClick}
selectedPath={selectedPath}
selectedPaths={selectedPaths}
onSelect={onSelect}
disabled={disabled}
/>
}
}
export function FileBrowser() {
const [selectedPath, setSelectedPath] = React.useState(null);
const [selectedPaths, setSelectedPaths] = React.useState([]);
const [deleteOpen, setDeleteOpen] = React.useState(false);
const [fileSelected, setFileSelected] = React.useState(false);
const [folderSelected, setFolderSelected] = React.useState(false);
const [renameOpen, setRenameOpen] = React.useState(false);
const [moveOpen, setMoveOpen] = React.useState(false);
const [makeDirectoryOpen, setMakeDirectoryOpen] = React.useState(false);
const [pending, setPending] = React.useState(false);
const selectedPathsCount = selectedPaths ? selectedPaths.length : 0;
const {browseFiles, openFolders, setOpenFolders, fetchFiles} = useBrowseFiles();
@ -113,53 +156,97 @@ export function FileBrowser() {
}, []);
const onSelect = (path) => {
if (path.endsWith('/') && selectedPath === path) {
// Deselect folder.
setFileSelected(false);
setFolderSelected(false);
setSelectedPath(null);
} else if (path.endsWith('/')) {
// Select folder.
setFileSelected(false);
setFolderSelected(true);
setSelectedPath(path);
} else if (selectedPath === path) {
// Deselect file.
setFileSelected(false);
setFolderSelected(false);
setSelectedPath(null);
let newSelectedPaths;
// Select or deselect if the paths was previously selected.
if (selectedPathsCount && selectedPaths.indexOf(path) >= 0) {
newSelectedPaths = selectedPaths.filter(i => i !== path);
} else {
// Select file.
setFileSelected(true);
setFolderSelected(false);
setSelectedPath(path);
newSelectedPaths = [...selectedPaths, path];
}
setSelectedPaths(newSelectedPaths);
console.debug('selectedPaths', newSelectedPaths);
}
const onDelete = async () => {
await deleteFile(selectedPath);
setDeleteOpen(false);
await fetchFiles();
await deleteFile(selectedPaths);
await reset();
};
const handleMakeDirectory = async () => {
setMakeDirectoryOpen(false);
await reset();
}
const reset = async () => {
setDeleteOpen(false);
setSelectedPaths([]);
setPending(true);
try {
await fetchFiles();
} finally {
setPending(false);
}
}
const footer = <TableFooter fullWidth>
<TableRow>
<TableHeaderCell colSpan={3}>
{folderSelected ? <DirectoryRefreshButton directory={selectedPath}/> : <FilesRefreshButton/>}
<Button
color='red'
onClick={() => setDeleteOpen(true)}
disabled={!fileSelected}
>
<Icon name='close'/>
Delete
</Button>
{selectedPathsCount ?
<DirectoryRefreshButton paths={selectedPaths}/>
: <FilesRefreshButton/>
}
<Button icon='trash'
color='red'
onClick={() => setDeleteOpen(true)}
disabled={selectedPathsCount === 0}
/>
<Confirm
open={deleteOpen}
content='Are you sure you want to delete these files?'
onConfirm={onDelete}
onCancel={() => setDeleteOpen(false)}
/>
<Button icon='text cursor'
color='yellow'
onClick={() => setRenameOpen(true)}
disabled={selectedPathsCount !== 1}
/>
{selectedPathsCount === 1 ?
<RenameModal
open={renameOpen}
onClose={() => setRenameOpen(false)}
onPending={setPending}
path={selectedPaths[0]}
onSubmit={reset}
/> : null}
<Button icon='move'
color='violet'
disabled={selectedPathsCount === 0}
onClick={() => setMoveOpen(true)}
/>
{selectedPathsCount > 0 ?
<MoveModal open={moveOpen}
onClose={() => setMoveOpen(false)}
paths={selectedPaths}
onSubmit={reset}
/> : null}
<Button
color='blue'
onClick={() => setMakeDirectoryOpen(true)}
disabled={selectedPaths && selectedPaths.length > 1}
style={{paddingLeft: '1em', paddingRight: '0.8em'}}
>
<IconGroup>
<Icon name='folder'/>
<Icon corner name='add'/>
</IconGroup>
</Button>
<MakeDirectoryModal
open={makeDirectoryOpen}
onClose={() => setMakeDirectoryOpen(false)}
parent={selectedPaths.length ? selectedPaths[0] : null}
onSubmit={handleMakeDirectory}
/>
</TableHeaderCell>
</TableRow>
</TableFooter>;
@ -197,10 +284,187 @@ export function FileBrowser() {
onFolderClick={onFolderClick}
onFileClick={(i) => setPreviewFile(i)}
sortData={sortData}
selectedPath={selectedPath}
selectedPaths={selectedPaths}
onSelect={onSelect}
disabled={pending}
/>}
footer={footer}
/>
</>
}
export function RenameModal({open, onClose, path, onSubmit, onPending}) {
const [parent, name] = splitPathParentAndName(path);
const [value, setValue] = React.useState(name);
const disabled = value === name;
const handleInputChange = (e, props) => {
if (e) {
e.preventDefault();
}
setValue(props.value);
}
const handleSubmit = async (e) => {
if (e) {
e.preventDefault();
}
try {
console.log(`Renaming: ${path} to ${value}`);
onPending(true);
await renamePath(path, value);
} finally {
onClose();
onPending(false);
if (onSubmit) {
await onSubmit();
}
}
}
useEffect(() => {
setValue(pathName(path));
}, [path]);
return <Modal closeIcon
open={open}
onClose={onClose}
>
<ModalHeader>Rename: {name}</ModalHeader>
<ModalContent>
<Header as='h4'>New Name</Header>
<pre>{parent ? parent + '/' : null}{value}</pre>
<Input fluid
label='Name'
value={value}
onChange={handleInputChange}
/>
</ModalContent>
<ModalActions>
<Button
color='violet'
disabled={disabled}
onClick={handleSubmit}
>
Rename
</Button>
<Button
onClick={() => setValue(name)}
floated='left'
>
Reset
</Button>
</ModalActions>
</Modal>
}
export function MoveModal({open, paths, onClose, onSubmit}) {
const [destination, setDestination] = React.useState('');
const [pending, setPending] = React.useState(false);
const handleDirectory = (value) => {
setDestination(value);
}
const handleMove = async () => {
try {
setPending(true);
await movePaths(destination, paths);
onClose();
} catch (e) {
console.error(e);
setPending(false);
}
if (onSubmit) {
await onSubmit();
}
}
const fileCell = i => <TableCell>
<pre style={{marginTop: 0, marginBottom: 0}}>{i}</pre>
</TableCell>;
const destinationRows = paths.map(i => <TableRow key={i}>
{fileCell(i)}
{destination ? fileCell(destination + '/' + pathName(i)) : fileCell(pathName(i))}
</TableRow>);
return <Modal closeIcon
onClose={onClose}
open={open}
>
<ModalHeader>Move Files/Directories</ModalHeader>
<ModalContent>
<p>Search for a directory to move your files into:</p>
<DirectorySearch onSelect={handleDirectory} disabled={pending}/>
<Table>
<TableHeader>
<TableRow>
<TableHeaderCell>Source</TableHeaderCell>
<TableHeaderCell>Destination</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{destinationRows}
</TableBody>
</Table>
</ModalContent>
<ModalActions>
<Button
color='violet'
onClick={handleMove}
disabled={pending}
>Move</Button>
<Button
onClick={() => setDestination(null)}
floated='left'
disabled={pending}
>Reset</Button>
</ModalActions>
</Modal>
}
export function MakeDirectoryModal({open, onClose, parent, onSubmit}) {
const [value, setValue] = useState('');
const mediaDirectory = useMediaDirectory();
const handleInputChange = (e, props) => {
if (e) {
e.preventDefault();
}
setValue(props.value);
}
const handleSubmit = async (e) => {
if (e) {
e.preventDefault();
}
try {
const path = parent ? `${parent}/${value}` : value;
await makeDirectory(path);
setValue('');
if (onSubmit) {
await onSubmit();
}
} catch (e) {
console.error(e);
}
}
return <Modal closeIcon open={open} onClose={onClose}>
<ModalHeader>Make Directory</ModalHeader>
<ModalContent>
<pre>{mediaDirectory}/{parent}{value}</pre>
<Input fluid
label='Name'
value={value}
onChange={handleInputChange}
/>
</ModalContent>
<ModalActions>
<Button color='violet' onClick={handleSubmit}>Create</Button>
</ModalActions>
</Modal>
}

View file

@ -1,12 +1,13 @@
import React from "react";
import _ from "lodash";
import {Grid, Header as SHeader, Image,} from "semantic-ui-react";
import {TagsProvider, TagsSelector} from "../Tags";
import {TagsSelector} from "../Tags";
import {Media} from "../contexts/contexts";
import {encodeMediaPath} from "./Common";
import {addTag, fetchFile, removeTag} from "../api";
import {fetchFile, tagFileGroup, untagFileGroup} from "../api";
import {StlViewer} from "react-stl-viewer";
import {Button, Modal, ModalActions, ModalContent, ModalHeader} from "./Theme";
import {toast} from "react-semantic-toasts-2";
function getMediaPathURL(previewFile) {
if (previewFile['primary_path']) {
@ -26,9 +27,9 @@ function getDownloadPathURL(previewFile) {
function getEpubViewerURL(previewFile) {
if (previewFile['primary_path']) {
return `/epub.html?url=download/${encodeMediaPath(previewFile['primary_path'])}`;
return `/epub/epub.html?url=download/${encodeMediaPath(previewFile['primary_path'])}`;
} else {
return `/epub.html?url=download/${encodeMediaPath(previewFile['path'])}`;
return `/epub/epub.html?url=download/${encodeMediaPath(previewFile['path'])}`;
}
}
@ -65,7 +66,7 @@ function getImageModal(previewFile) {
function getEpubModal(previewFile) {
const downloadURL = getDownloadPathURL(previewFile);
const viewerUrl = `/epub.html?url=${downloadURL}`;
const viewerUrl = `/epub/epub.html?url=${downloadURL}`;
return <ModalContent>
<div className='full-height'>
<iframe title='textModal' src={viewerUrl}
@ -138,6 +139,15 @@ function getSTLModal(previewFile) {
</React.Fragment>
}
function getGenericModal(previewFile) {
const path = previewFile.primary_path ?? previewFile.path;
const name = path.replace(/^.*[\\\/]/, '');
return <React.Fragment>
<ModalHeader>{name}</ModalHeader>
</React.Fragment>
}
export const FilePreviewContext = React.createContext({
previewFile: null,
setPreviewFile: null,
@ -183,29 +193,28 @@ export function FilePreviewProvider({children}) {
}
const localAddTag = async (name) => {
await addTag(previewFile, name);
await tagFileGroup(previewFile, name);
await localFetchFile();
}
const localRemoveTag = async (name) => {
await removeTag(previewFile, name);
await untagFileGroup(previewFile, name);
await localFetchFile();
}
function setModalContent(content, url, downloadURL) {
let openButton;
if (url) {
openButton = <Button color='blue' as='a' href={url}>Open</Button>;
}
function setModalContent(content, url, downloadURL, path) {
const openButton = url ? <Button color='blue' as='a' href={url}>Open</Button> : null;
const closeButton = <Button onClick={handleClose}>Close</Button>;
const tagsDisplay = <TagsSelector selectedTagNames={previewFile['tags']} onAdd={localAddTag}
onRemove={localRemoveTag}/>;
let downloadButton;
if (downloadURL) {
downloadButton = <Button color='yellow' as='a' href={downloadURL} floated='left'>
Download
</Button>;
}
const downloadButton = downloadURL ?
<Button color='yellow' as='a' href={downloadURL} floated='left'>Download</Button>
: null;
const pathContent = path ? <ModalContent>
<pre>{path}</pre>
</ModalContent>
: null;
console.log('path', path);
setPreviewModal(<Modal closeIcon
size='fullscreen'
@ -213,6 +222,7 @@ export function FilePreviewProvider({children}) {
onClose={e => handleClose(e)}
>
{content}
{pathContent}
<ModalActions>
<Media at='mobile'>
<Grid>
@ -244,41 +254,47 @@ export function FilePreviewProvider({children}) {
setPreviewModal(null);
if (previewFile && !_.isObject(previewFile)) {
console.error(`Unknown previewFile type: ${typeof previewFile}`);
toast({
type: 'error',
title: 'Cannot preview file',
description: 'Cannot preview file',
time: 5000,
});
return;
}
if (previewFile && !_.isEmpty(previewFile)) {
const {mimetype, size} = previewFile;
const path = previewFile['primary_path'] || previewFile['path'];
console.debug('Previewing file', previewFile);
const lowerPath = path.toLowerCase();
console.debug(`useFilePreview path=${previewFile['path']} mimetype=${mimetype}`);
const url = getMediaPathURL(previewFile);
const downloadURL = getDownloadPathURL(previewFile);
if (mimetype.startsWith('text/') && size > MAXIMUM_TEXT_SIZE) {
// Large text files should be downloaded.
window.open(downloadURL);
} else if (mimetype.startsWith('text/') || mimetype.startsWith('application/json')) {
setModalContent(getIframeModal(previewFile), url, downloadURL);
setModalContent(getIframeModal(previewFile), url, downloadURL, path);
} else if (mimetype.startsWith('video/')) {
setModalContent(getVideoModal(previewFile), url, downloadURL);
setModalContent(getVideoModal(previewFile), url, downloadURL, path);
} else if (mimetype.startsWith('audio/')) {
setModalContent(getAudioModal(previewFile), url, downloadURL);
setModalContent(getAudioModal(previewFile), url, downloadURL, path);
} else if (mimetype.startsWith('application/epub')) {
const viewerURL = getEpubViewerURL(previewFile);
setModalContent(getEpubModal(previewFile), viewerURL, downloadURL);
setModalContent(getEpubModal(previewFile), viewerURL, downloadURL, path);
} else if (mimetype.startsWith('application/pdf')) {
setModalContent(getIframeModal(previewFile), url, downloadURL);
setModalContent(getIframeModal(previewFile), url, downloadURL, path);
} else if (mimetype.startsWith('image/')) {
setModalContent(getImageModal(previewFile), url);
setModalContent(getImageModal(previewFile), url, null, path);
} else if (mimetype.startsWith('model/stl')) {
setModalContent(getSTLModal(previewFile), null, downloadURL);
setModalContent(getSTLModal(previewFile), null, downloadURL, path);
} else if (mimetype.startsWith('application/octet-stream') && lowerPath.endsWith('.mp3')) {
setModalContent(getAudioModal(previewFile), url, downloadURL);
setModalContent(getAudioModal(previewFile), url, downloadURL, path);
} else if (mimetype.startsWith('application/octet-stream') && lowerPath.endsWith('.stl')) {
setModalContent(getSTLModal(previewFile), null, downloadURL);
setModalContent(getSTLModal(previewFile), null, downloadURL, path);
} else {
// No special handler for this file type, just open it.
window.open(downloadURL);
setModalContent(getGenericModal(previewFile), url, downloadURL, path);
}
}
}, [previewFile]);

View file

@ -9,7 +9,6 @@ import {
Dropdown,
Form,
Image,
Label,
PlaceholderLine,
TableCell,
TableHeaderCell,
@ -28,6 +27,7 @@ import {
PageContainer,
Paginator,
PreviewLink,
TagIcon,
textEllipsis,
useTitle
} from "./Common";
@ -40,7 +40,7 @@ import {
useSearchView
} from "../hooks/customHooks";
import {Route, Routes} from "react-router-dom";
import {CardPlacholder} from "./Placeholder";
import {CardPlaceholder} from "./Placeholder";
import {ArchiveCard, ArchiveRowCells} from "./Archive";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {Media, StatusContext, ThemeContext} from "../contexts/contexts";
@ -72,7 +72,7 @@ function EbookCard({file}) {
const downloadUrl = `/download/${encodeMediaPath(file.primary_path)}`;
const isEpub = file['mimetype'].startsWith('application/epub');
const viewerUrl = isEpub ? `/epub.html?url=${downloadUrl}` : null;
const viewerUrl = isEpub ? `/epub/epub.html?url=${downloadUrl}` : null;
const color = mimetypeColor(file.mimetype);
return <Card color={color}>
@ -125,7 +125,7 @@ function FileCard({file}) {
file.mimetype.startsWith('application/epub') || file.mimetype.startsWith('application/x-mobipocket-ebook')
);
if (file.model === 'video') {
if (file.model === 'video' && 'video' in file) {
return <VideoCard key={file['primary_path']} file={file}/>;
} else if (file.model === 'archive') {
return <ArchiveCard key={file['primary_path']} file={file}/>;
@ -167,7 +167,7 @@ export function FileCards({files}) {
} else if (files && files.length === 0) {
return <Segment>No results!</Segment>
} else {
return <CardGroupCentered><CardPlacholder/></CardGroupCentered>
return <CardGroupCentered><CardPlaceholder/></CardGroupCentered>
}
}
@ -269,9 +269,7 @@ export function FileTable({files, selectOn, onSelect, footer, selectedKeys}) {
export function FileRowTagIcon({file}) {
if (file.tags && file.tags.length) {
return <Label circular color='green' style={{padding: '0.5em', marginRight: '0.5em'}}>
<Icon name='tag' style={{margin: 0}}/>
</Label>;
return <TagIcon/>;
}
}
@ -431,10 +429,10 @@ export function TagsQuerySelector({onChange}) {
const {searchParams, updateQuery} = useQuery();
const activeTags = searchParams.getAll('tag');
const localOnChange = (name) => {
updateQuery({'tag': name});
const localOnChange = (tagNames) => {
updateQuery({'tag': tagNames});
if (onChange) {
onChange(name);
onChange(tagNames);
}
}
@ -464,16 +462,16 @@ export function FilesSearchView({
{key: 'model', text: '3D Model', value: 'model'},
];
const {searchFiles, totalPages, activePage, setPage} = useSearchFiles(24, emptySearch, model);
const {searchFiles, pages} = useSearchFiles(24, emptySearch, model);
const {body, paginator, selectButton, viewButton, limitDropdown, tagQuerySelector} = FilesView(
searchFiles,
activePage,
totalPages,
pages.activePage,
pages.totalPages,
null,
null,
null,
setPage,
pages.setPage,
true,
);
@ -597,7 +595,7 @@ export function FilesRefreshButton() {
</Button>;
}
export function DirectoryRefreshButton({directory}) {
export function DirectoryRefreshButton({paths}) {
const {status} = useContext(StatusContext);
const refreshing = status && status['flags'] && status['flags'].indexOf('refreshing') >= 0;
const refreshingDirectory = status && status['flags'] && status['flags'].indexOf('refreshing_directory') >= 0;
@ -606,7 +604,7 @@ export function DirectoryRefreshButton({directory}) {
const handleClick = async () => {
setLoading(true);
await refreshDirectoryFiles(directory);
await refreshDirectoryFiles(paths);
}
// Clear loading when global refresh event completes.
@ -620,6 +618,6 @@ export function DirectoryRefreshButton({directory}) {
disabled={loading || refreshing || refreshingDirectory}
>
<Icon name='refresh'/>
Refresh Directory
Refresh
</Button>
}

View file

@ -8,14 +8,14 @@ import _ from "lodash";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {FileRowTagIcon} from "./Files";
const HeadlineParagraph = ({headline}) => {
export const HeadlineText = ({headline, openTag = '<u>', closeTag = '</u>'}) => {
const {s} = React.useContext(ThemeContext);
if (headline) {
headline = headline.replaceAll('<b>', '<b><u>');
headline = headline.replaceAll('</b>', '</b></u>');
headline = headline.replaceAll('<b>', openTag);
headline = headline.replaceAll('</b>', closeTag);
headline = headline.replaceAll('\n', '<br/>');
// Postgres inserts <b>...</b> tags which we will use.
return <p {...s} dangerouslySetInnerHTML={{__html: headline}}></p>
return <span {...s} dangerouslySetInnerHTML={{__html: headline}}></span>
}
}
@ -33,18 +33,18 @@ const FileHeadline = ({file, to}) => {
let header = title || name;
if (title_headline) {
header = <PreviewLink file={file}><HeadlineParagraph headline={title_headline}/></PreviewLink>;
header = <PreviewLink file={file}><HeadlineText headline={title_headline}/></PreviewLink>;
}
if (to) {
header = <Link to={to}><HeadlineParagraph headline={title_headline}/></Link>
header = <Link to={to}><HeadlineText headline={title_headline}/></Link>
}
let body = <p><small>No highlights available.</small></p>;
if (b_headline || c_headline || d_headline) {
body = <>
<HeadlineParagraph headline={b_headline}/>
<HeadlineParagraph headline={c_headline}/>
<HeadlineParagraph headline={d_headline}/>
<HeadlineText headline={b_headline}/>
<HeadlineText headline={c_headline}/>
<HeadlineText headline={d_headline}/>
</>;
}

View file

@ -71,8 +71,8 @@ function DownloadMessage() {
</p>
<p><b>Download only the areas you need</b>. Large regions like all of Asia, or the entire
planet are most likely <b>too large</b> and won't render quickly. I recommend only
importing files less than 1GB on a Raspberry Pi.</p>
planet are most likely <b>too large</b> and won't render quickly. It is recommend to only
import files less than 1GB on a Raspberry Pi.</p>
<p>Only <b>*.osm.pbf</b> files are supported!</p>
@ -235,7 +235,6 @@ class ManageMap extends React.Component {
return <PageContainer>
<WROLModeMessage content='Cannot modify Map'/>
<DockerMapImportWarning/>
<DownloadMessage/>
<SlowImportMessage/>
<Loader size='large' active={import_running} inline='centered'>
{importingMessage}
@ -263,6 +262,7 @@ class ManageMap extends React.Component {
</TableRow>
</TableFooter>
</Table>
<DownloadMessage/>
</PageContainer>
}
}

View file

@ -10,11 +10,12 @@ const links = [
{text: 'Videos', to: '/videos', key: 'videos'},
{text: 'Archive', to: '/archive', key: 'archive'},
{text: 'Map', to: '/map', key: 'map'},
{text: 'Zim', to: '/zim', key: 'zim'},
{text: 'Files', to: '/files', key: 'files'},
{text: 'Inventory', to: '/inventory', key: 'inventory'},
{
text: 'More', key: 'more',
links: [
{text: 'Inventory', to: '/inventory', key: 'inventory'},
{to: '/more/otp', text: 'One Time Pad', end: true},
{to: '/more/statistics', text: 'Statistics', end: true},
{to: '/more/vin', text: 'VIN Decoder', end: true},

View file

@ -3,7 +3,7 @@ import React, {useContext} from "react";
import {ThemeContext} from "../contexts/contexts";
import {Card, Placeholder} from "./Theme";
export function CardPlacholder() {
export function CardPlaceholder() {
const {s} = useContext(ThemeContext);
return <Card>
@ -22,7 +22,7 @@ export function CardPlacholder() {
export function VideoPlaceholder() {
return <CardGroup doubling stackable>
<CardPlacholder/>
<CardPlaceholder/>
</CardGroup>
}
@ -39,3 +39,11 @@ export function ProgressPlaceholder() {
<PlaceholderLine/>
</Placeholder>
}
export function TextPlaceholder() {
return <Placeholder style={{marginBottom: '1em'}}>
<PlaceholderLine/>
<PlaceholderLine/>
<PlaceholderLine/>
</Placeholder>
}

View file

@ -0,0 +1,113 @@
import React, {useEffect, useState} from "react";
import {createSearchParams, Route, Routes, useHref, useNavigate} from "react-router-dom";
import {FilesSearchView} from "./Files";
import {usePages, useQuery} from "../hooks/customHooks";
import {ZimSearchView} from "./Zim";
import {searchEstimate} from "../api";
import {normalizeEstimate, TabLinks} from "./Common";
export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false, model) => {
const navigate = useNavigate();
const href = useHref();
const {searchParams, updateQuery} = useQuery();
const searchStr = searchParams.get('q');
const activeTags = searchParams.getAll('tag');
const pages = usePages(defaultLimit, totalPages);
const filter = searchParams.get('filter');
const model_ = searchParams.get('model') || model;
const setSearchStr = (value) => {
navigate({
pathname: '/search',
// Start new search at offset 0.
search: createSearchParams({q: value, o: 0}).toString(),
});
}
const setTags = (tags) => {
updateQuery({tag: tags});
}
const addTag = (name) => {
const newTags = [...activeTags, name];
setTags(newTags);
}
const removeTag = (name) => {
const newTags = activeTags.filter(i => i !== name);
setTags(newTags);
}
return {
activeTags,
addTag,
filter,
href,
model: model_,
pages,
removeTag,
searchParams,
searchStr,
setSearchStr,
setTags,
}
}
export const useSearchEstimate = (search_str, activeTags) => {
const [fileGroups, setFileGroups] = useState('?');
const [zims, setZims] = useState(null);
const [zimsSum, setZimsSum] = useState('?');
const localFetchSearchEstimate = async () => {
if (!search_str && !activeTags) {
return;
}
try {
const estimates = await searchEstimate(search_str, activeTags);
console.debug('estimates', estimates);
setFileGroups(estimates['file_groups']);
setZimsSum(estimates['zimSum']);
setZims(estimates['zims']);
} catch (e) {
console.error('Failed to fetch estimates');
console.error(e);
setFileGroups(null);
setZimsSum(null);
setZims(null);
}
}
useEffect(() => {
localFetchSearchEstimate();
}, [search_str, JSON.stringify(activeTags)]);
return {fileGroups, zimsSum, zims}
}
export function SearchView() {
const {searchStr, activeTags} = useSearch();
const estimates = useSearchEstimate(searchStr, activeTags);
let filesTabName = 'Files';
let zimsTabName = 'Zims';
if (estimates) {
const {fileGroups, zimsSum} = estimates;
filesTabName = `Files (${normalizeEstimate(fileGroups)})`;
zimsTabName = `Zims (${normalizeEstimate(zimsSum)})`;
}
const links = [
{text: filesTabName, to: '/search', key: 'filesSearch', end: true},
{text: zimsTabName, to: '/search/zim', key: 'zimsSearch'},
]
return <React.Fragment>
<TabLinks links={links}/>
<Routes>
<Route path='/*' element={<FilesSearchView/>}/>
<Route path='/zim' exact element={<ZimSearchView estimates={estimates}/>}/>
</Routes>
</React.Fragment>
}

View file

@ -6,7 +6,10 @@ import {Table} from "./Theme";
export class SortableTable extends React.Component {
constructor(props) {
super(props);
this.state = {sortColumn: null, direction: 'ascending'};
this.state = {
sortColumn: props.defaultSortColumn || null,
direction: props.defaultDirection || 'ascending',
};
}
changeSort = (key) => {

View file

@ -186,8 +186,8 @@ export function Divider({...props}) {
}
export function Header(props) {
const {t, inverted} = useContext(ThemeContext);
props = defaultGrey({...t, ...props}, inverted);
const {t} = useContext(ThemeContext);
props = {...t, ...props};
return <SHeader {...props}/>
}

View file

@ -1,5 +1,5 @@
import React, {useContext, useState} from 'react';
import {addTag, deleteVideos, removeTag} from "../api";
import {tagFileGroup, deleteVideos, untagFileGroup} from "../api";
import {Link, useNavigate, useParams} from "react-router-dom";
import _ from "lodash";
import {
@ -159,12 +159,12 @@ function VideoPage({videoFile, prevFile, nextFile, fetchVideo, ...props}) {
const tabMenu = theme === darkTheme ? {inverted: true, attached: true} : {attached: true};
const localAddTag = async (name) => {
await addTag(videoFile, name);
await tagFileGroup(videoFile, name);
await fetchVideo();
}
const localRemoveTag = async (name) => {
await removeTag(videoFile, name);
await untagFileGroup(videoFile, name);
await fetchVideo();
}

View file

@ -113,17 +113,15 @@ function VideosPage() {
}
const onSelect = (path, checked) => {
if (checked && path) {
setSelectedVideos([...selectedVideos, path]);
} else if (path) {
setSelectedVideos(selectedVideos.filter(i => i !== path));
}
const newSelectedVideos = checked && path ? [...selectedVideos, path] : selectedVideos.filter(i => i !== path);
console.debug(`Selected Videos: ${newSelectedVideos}`);
setSelectedVideos(newSelectedVideos);
}
const onDelete = async (e) => {
e.preventDefault();
setDeleteOpen(false);
const videoIds = videos.filter(i => selectedVideos.indexOf(i['path']) >= 0).map(i => i['video']['id']);
const videoIds = videos.filter(i => selectedVideos.indexOf(i['primary_path']) >= 0).map(i => i['video']['id']);
await deleteVideos(videoIds);
await fetchVideos();
setSelectedVideos([]);

548
app/src/components/Zim.js Normal file
View file

@ -0,0 +1,548 @@
import {useOutdatedZims, useSearchZim} from "../hooks/customHooks";
import {
Accordion,
Button,
Divider,
Header,
Icon,
Modal,
ModalActions,
ModalContent,
ModalHeader,
Placeholder,
Segment
} from "./Theme";
import {HeadlineText} from "./Headline";
import {TextPlaceholder} from "./Placeholder";
import {
AccordionContent,
AccordionTitle,
Button as SButton,
Dropdown,
Icon as SIcon,
Label,
Message,
PlaceholderHeader,
PlaceholderLine,
TableCell,
TableFooter,
TableHeaderCell,
TableRow
} from "semantic-ui-react";
import React, {useContext, useState} from "react";
import {
encodeMediaPath,
humanFileSize,
normalizeEstimate,
PageContainer,
Paginator,
TabLinks,
TagIcon,
useTitle
} from "./Common";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {TagsSelector} from "../Tags";
import {
deleteOutdatedZims,
fetchZims,
fetchZimSubscriptions,
refreshFiles,
saveSettings,
tagZimEntry,
untagZimEntry,
zimSubscribe,
zimUnsubscribe
} from "../api";
import {useSearch} from "./Search";
import {TagsQuerySelector} from "./Files";
import {ThemeContext} from "../contexts/contexts";
import {Link, Route, Routes} from "react-router-dom";
import {SortableTable} from "./SortableTable";
import {toast} from "react-semantic-toasts-2";
const VIEWER_URL = `http://${window.location.hostname}:8085/`;
export const OutdatedZimsMessage = ({onClick}) => {
const [open, setOpen] = React.useState(false);
const {outdated, current} = useOutdatedZims();
const onOpen = () => setOpen(true);
const onClose = () => setOpen(false);
const handleDelete = async (e) => {
if (e) {
e.preventDefault();
}
try {
const success = await deleteOutdatedZims();
if (success) {
toast({
type: 'info',
title: 'Zims deleted',
description: 'Outdated Zims have been deleted.',
time: 5000,
});
} else {
toast({
type: 'error',
title: 'Failed to delete Zims',
description: 'Outdated Zims have NOT been deleted. See server logs.',
time: 5000,
});
}
} finally {
onClose();
}
}
const handleIgnore = async (e) => {
if (e) {
e.preventDefault();
}
const config = {ignore_outdated_zims: true};
await saveSettings(config);
if (onClick) {
await onClick();
}
}
let modalContent = <Placeholder>
<PlaceholderLine/>
</Placeholder>;
if (outdated && outdated.length > 0) {
modalContent = <>
<Header as='h3'>To Delete</Header>
{outdated.map(i => <pre key={i}>{i}</pre>)}
<Header as='h3'>To Keep</Header>
{current.map(i => <pre key={i}>{i}</pre>)}
</>
}
return <Message icon info>
<SIcon name='question'/>
<Message.Content>
<Message.Header>Outdated Zim Files</Message.Header>
New Zim files have been downloaded. Outdated Zim files can be removed.
<p></p>
<SButton primary onClick={() => setOpen(true)}>Delete</SButton>
<Modal closeIcon
open={open}
onClose={onClose}
onOpen={onOpen}
>
<ModalHeader>Delete</ModalHeader>
<ModalContent>
{modalContent}
</ModalContent>
<ModalActions>
<Button color='red' floated='left' onClick={handleDelete}>Delete</Button>
<Button onClick={onClose}>Close</Button>
</ModalActions>
</Modal>
<Link to='/files?folders=zims'><SButton>Delete Manually</SButton></Link>
<SButton secondary onClick={handleIgnore}>Ignore Forever</SButton>
</Message.Content>
</Message>
}
export const KiwixRestartMessage = () => {
return <Message icon warning>
<SIcon name='exclamation'/>
<Message.Content>
<Message.Header>Kiwix must be restarted</Message.Header>
<p>New Zim files have been downloaded; you must restart your containers.</p>
<p>Run the following to restart your containers:</p>
<pre> docker-compose restart</pre>
</Message.Content>
</Message>
}
const ZimSearchEntry = ({zimId, onTag, onUntag, entry}) => {
const {path, title, headline, tag_names} = entry;
const [open, setOpen] = React.useState(false);
const url = `/api/zim/${zimId}/entry/${encodeMediaPath(path)}`;
const handleClick = async (e) => {
if (e) {
e.preventDefault();
}
setOpen(true);
}
const localAddTag = (name) => {
onTag(zimId, path, name);
}
const localUntag = (name) => {
onUntag(zimId, path, name);
}
const tagIcon = tag_names && tag_names.length > 0 ? <TagIcon/> : null;
return <div style={{marginLeft: '0.5em'}}>
<Header
as='h3'
className='clickable'
onClick={handleClick}
>
<u>
<HeadlineText headline={title || path} openTag={'<i>'} closeTag={'</i>'}/>
</u>
{tagIcon}
</Header>
<HeadlineText headline={headline}/>
<Modal closeIcon
open={open}
onClose={() => setOpen(false)}>
<ModalContent>
<div className='full-height'>
<iframe title='textModal' src={url}
style={{
height: '100%', width: '100%', border: 'none', position: 'absolute', top: 0,
// Use white to avoid iframe displaying with dark-theme.
backgroundColor: '#ffffff',
}}/>
</div>
</ModalContent>
<ModalActions>
<Grid>
<Grid.Column mobile={10} tablet={14}>
<TagsSelector selectedTagNames={tag_names} onAdd={localAddTag} onRemove={localUntag}/>
</Grid.Column>
<Grid.Column width={2}>
<Button color='blue' as='a' href={url} target='_blank'>Open</Button>
</Grid.Column>
</Grid>
</ModalActions>
</Modal>
</div>
}
const ZimAccordion = ({data, index, activeIndex, onClick, searchStr, activeTags}) => {
const {id, estimate, metadata} = data;
const {title, date} = metadata;
const {zim, fetchSearch, pages, loading} = useSearchZim(searchStr, id, index === activeIndex, activeTags);
const {t} = useContext(ThemeContext);
const localAddTag = async (zimId, path, name) => {
await tagZimEntry(zimId, path, name);
await fetchSearch();
}
const localUntag = async (zimId, path, name) => {
await untagZimEntry(zimId, path, name);
await fetchSearch();
}
let body = <TextPlaceholder/>;
if (zim && !loading) {
const {search} = zim;
if (search && search.length > 0) {
body = search.map(i => <Segment vertical key={i['path']}>
<ZimSearchEntry zimId={id} onTag={localAddTag} onUntag={localUntag} entry={i}/>
</Segment>);
} else {
body = <p {...t}>No results</p>;
}
}
const paginator = <center style={{marginTop: '2em'}}>
<Paginator activePage={pages.activePage} totalPages={pages.totalPages} onPageChange={pages.setPage}/>
</center>;
return <React.Fragment>
<AccordionTitle
index={index}
active={index === activeIndex}
onClick={() => onClick(index, activeIndex)}
>
<Header as='h3'>
<Icon name='dropdown'/> {title} <Label>{normalizeEstimate(estimate)}</Label>
</Header>
</AccordionTitle>
<AccordionContent active={index === activeIndex}>
<Header as='h4'>{date}</Header>
{body}
{paginator}
</AccordionContent>
</React.Fragment>
}
const ZimsRefreshWarning = () => {
return <Message icon warning onClick={refreshFiles}>
<SIcon name='hand point right'/>
<Message.Content>
<Message.Header>No Zims have been indexed.</Message.Header>
<a href='#'>Click here</a> to refresh all your files.
</Message.Content>
</Message>;
}
export const ZimSearchView = ({estimates}) => {
const [activeIndex, setActiveIndex] = React.useState(null);
const {searchStr, activeTags, setTags} = useSearch();
const {zims} = estimates;
const handleClick = (index, activeIndex_) => {
setActiveIndex(index === activeIndex_ ? -1 : index);
}
let body = <TextPlaceholder/>;
if (zims && zims.length === 0) {
body = <ZimsRefreshWarning/>;
} else if (zims) {
body = zims.map((i, index) => <ZimAccordion
key={i['path']}
index={index}
activeIndex={activeIndex}
data={i}
searchStr={searchStr}
activeTags={activeTags}
onClick={handleClick}
/>);
}
return <>
<TagsQuerySelector onChange={setTags}/>
<Accordion>
{body}
</Accordion>
</>
}
const ViewerMessage = () => {
return <Message warning icon>
<SIcon name='warning'/>
<Message.Content>
<p>You can view your Zim files using the Kiwix app, or at <a href={VIEWER_URL}>{VIEWER_URL}</a></p>
</Message.Content>
</Message>
}
const ZimCatalogItemRow = ({item, subscriptions, iso_639_codes, fetchSubscriptions}) => {
const {name, languages, size} = item;
const subscription = name in subscriptions ? subscriptions[name] : null;
const subscriptionLanguage = subscription ? subscription['language'] : 'en';
const [langauge, setLanguage] = useState(subscriptionLanguage);
const [pending, setPending] = useState(false);
const languageChange = subscription ? langauge !== subscription['language'] : false;
const handleButton = async (e) => {
if (e) {
e.preventDefault();
}
let success = false;
try {
setPending(true);
if (subscription && !languageChange) {
success = await zimUnsubscribe(subscription['id']);
} else {
success = await zimSubscribe(name, langauge);
}
} catch (e) {
console.error(e);
}
setPending(false);
if (!success) {
toast({
type: 'error',
title: 'Error!',
description: subscription ? 'Failed to unsubscribe' : 'Failed to subscribe',
})
}
if (fetchSubscriptions) {
await fetchSubscriptions();
}
}
const handleLanguageChange = (e, {value}) => {
if (e) {
e.preventDefault();
}
setLanguage(value);
}
const languageOptions = languages.map(i => {
return {key: i, value: i, text: iso_639_codes[i]}
});
const languageDropdown = <Dropdown fluid search selection
placeholder='Language'
options={languageOptions}
value={langauge}
onChange={handleLanguageChange}
/>;
const subscribeButton = <Button
disabled={pending}
onClick={handleButton}>
{subscription && !languageChange ? 'Unsubscribe' : 'Subscribe'}
</Button>
return <TableRow key={name}>
<TableCell>{name}</TableCell>
<TableCell>{languageDropdown}</TableCell>
<TableCell>{subscribeButton}</TableCell>
<TableCell>{humanFileSize(size)}</TableCell>
</TableRow>
}
class ManageZim extends React.Component {
constructor(props) {
super(props);
this.state = {
catalog: undefined,
iso_639_codes: undefined,
subscriptions: undefined,
zims: undefined,
}
}
async componentDidMount() {
await this.fetchZims();
await this.fetchSubscriptions();
}
async fetchZims() {
try {
const {zims} = await fetchZims();
this.setState({zims});
} catch (e) {
console.error(e);
}
}
async fetchSubscriptions() {
try {
const {subscriptions, catalog, iso_639_codes} = await fetchZimSubscriptions();
this.setState({subscriptions, catalog, iso_639_codes});
} catch (e) {
console.error(e);
}
}
zimFileTableRow = (zim, sortData) => {
const {path, size} = zim;
return <TableRow key={path}>
<TableCell>{path}</TableCell>
<TableCell>{humanFileSize(size)}</TableCell>
</TableRow>
}
render() {
const {zims, catalog, iso_639_codes, subscriptions} = this.state;
const zimFilesHeaders = [
{key: 'path', text: 'Path', sortBy: 'path', width: 14},
{key: 'size', text: 'Size', sortBy: 'size', width: 2},
];
let zimFilesBody = <Placeholder>
<PlaceholderHeader>
<PlaceholderLine/>
<PlaceholderLine/>
</PlaceholderHeader>
</Placeholder>;
if (zims && zims.length > 0) {
zimFilesBody = <SortableTable
data={zims}
rowFunc={this.zimFileTableRow}
rowKey='path'
tableHeaders={zimFilesHeaders}
/>;
} else if (zims === null || (zims && zims.length === 0)) {
zimFilesBody = <Message icon warning>
<Message.Content>
You have not subscribed to any Kiwix projects, or your files have not been refreshed.
</Message.Content>
</Message>;
}
const kiwixCatalogHeaders = [
{
key: 'name', text: 'Name', 'sortBy': [i => {
return i['name'].toLowerCase()
}], width: 8
},
{key: 'language', text: 'Language', 'sortBy': null, width: 4},
{key: 'subscription', text: 'Subscription', 'sortBy': null, width: 2},
{key: 'size', text: 'Maximum Size', sortBy: 'size', width: 2},
];
let kiwixCatalog = <Placeholder>
<PlaceholderHeader>
<PlaceholderLine/>
<PlaceholderLine/>
</PlaceholderHeader>
</Placeholder>;
if (subscriptions && Object.keys(subscriptions).length > 0) {
kiwixCatalog = <SortableTable
defaultSortColumn='name'
data={catalog}
rowFunc={i => <ZimCatalogItemRow
iso_639_codes={iso_639_codes}
subscriptions={subscriptions}
item={i}
fetchSubscriptions={async () => await this.fetchSubscriptions()}
/>}
rowKey='name'
tableHeaders={kiwixCatalogHeaders}
footer={<TableFooter>
<TableRow>
<TableHeaderCell colSpan={4}>
<p>More Zim files are available from the full Kiwix library&nbsp;
<a href='https://download.kiwix.org/'>https://download.kiwix.org/</a>
</p>
</TableHeaderCell>
</TableRow>
</TableFooter>}
/>
}
return <PageContainer>
<Header as='h2'>Zim Files</Header>
{zimFilesBody}
<Header as='h2'>Kiwix Catalog</Header>
{kiwixCatalog}
<Divider/>
<ViewerMessage/>
</PageContainer>
}
}
function ZimApp() {
return <iframe
title='zim'
src={VIEWER_URL}
style={{
position: 'fixed',
height: '100%',
width: '100%',
border: 'none',
backgroundColor: '#FFFFFF',
}}/>
}
export function ZimRoute() {
useTitle('Zim');
const links = [
{text: 'Viewer', to: '/zim', key: 'zim', end: true},
{text: 'Manage', to: '/zim/manage', key: 'manage'},
]
return <div style={{marginTop: '2em'}}>
<TabLinks links={links}/>
<Routes>
<Route path='/' exact element={<ZimApp/>}/>
<Route path='manage' exact element={<ManageZim/>}/>
</Routes>
</div>
}

View file

@ -25,6 +25,7 @@ export class Settings extends React.Component {
hotspot_password: null,
hotspot_ssid: null,
hotspot_status: null,
ignore_outdated_zims: null,
throttle_on_startup: null,
throttle_status: null,
}
@ -46,6 +47,7 @@ export class Settings extends React.Component {
hotspot_password: settings.hotspot_password,
hotspot_ssid: settings.hotspot_ssid,
hotspot_status: settings.hotspot_status,
ignore_outdated_zims: settings.ignore_outdated_zims,
throttle_on_startup: settings.throttle_on_startup,
throttle_status: settings.throttle_status,
}, this.handleHotspotChange);
@ -64,6 +66,7 @@ export class Settings extends React.Component {
hotspot_on_startup: this.state.hotspot_on_startup,
hotspot_password: this.state.hotspot_password,
hotspot_ssid: this.state.hotspot_ssid,
ignore_outdated_zims: this.state.ignore_outdated_zims,
throttle_on_startup: this.state.throttle_on_startup,
}
await saveSettings(settings);
@ -111,6 +114,7 @@ export class Settings extends React.Component {
hotspot_on_startup,
hotspot_password,
hotspot_ssid,
ignore_outdated_zims,
pending,
qrCodeValue,
throttle_on_startup,
@ -163,6 +167,15 @@ export class Settings extends React.Component {
/>
</div>
<div style={{margin: '0.5em'}}>
<Toggle
label='Ignore outdated Zims'
disabled={disabled || ignore_outdated_zims === null}
checked={ignore_outdated_zims === true}
onChange={checked => this.handleInputChange(null, 'ignore_outdated_zims', checked)}
/>
</div>
<FormGroup inline>
<FormInput
label={<>