import React, {useContext, useState} from "react";
import {
CardContent,
CardDescription,
CardHeader,
CardMeta,
Container,
GridColumn,
GridRow,
Image,
Input,
TableCell,
} from "semantic-ui-react";
import {
APIButton,
BackButton,
CardLink,
encodeMediaPath,
ErrorMessage,
ExternalCardLink,
FileIcon,
findPosterPath,
humanFileSize,
InfoHeader,
isoDatetimeToAgoPopup,
mimetypeColor,
PageContainer,
PreviewPath,
SearchInput,
SortButton,
TabLinks,
textEllipsis,
useTitle
} from "./Common";
import {deleteArchives, deleteDomain, generateArchiveScreenshot, getCollectionTagInfo, postDownload, refreshDomain, tagDomain, tagFileGroup, untagFileGroup} from "../api";
import {CollectionTagModal} from "./collections/CollectionTagModal";
import {Link, Route, Routes, useLocation, useNavigate, useParams} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {
useArchive,
useDomain,
useDomains,
useOneQuery,
useSearchArchives,
useSearchOrder
} from "../hooks/customHooks";
import {FileCards, FileRowTagIcon, FilesView} from "./Files";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import _ from "lodash";
import {Media, ThemeContext} from "../contexts/contexts";
import {Button, Card, CardIcon, darkTheme, Header, Loader, Placeholder, Popup, Segment, Tab, TabPane} from "./Theme";
import {SortableTable} from "./SortableTable";
import {taggedImageLabel, TagsSelector, TagsContext} from "../Tags";
import {toast} from "react-semantic-toasts-2";
import {API_ARCHIVE_UPLOAD_URI, Downloaders} from "./Vars";
import {CollectionTable} from "./collections/CollectionTable";
import {CollectionEditForm} from "./collections/CollectionEditForm";
import {RecurringDownloadsTable} from "./admin/Downloads";
function archiveFileLink(path, directory = false) {
if (path) {
const href = directory ?
`/media/${encodeMediaPath(path)}/`
: `/media/${encodeMediaPath(path)}`;
return
{path}
} else {
return
Unknown
}
}
function ArchivePage() {
const navigate = useNavigate();
const {archiveId} = useParams();
const {archiveFile, history, fetchArchive} = useArchive(archiveId);
const {theme} = useContext(ThemeContext);
let title = archiveFile ? archiveFile.title ? archiveFile.title : archiveFile.name : null;
useTitle(title);
if (archiveFile === null) {
return ;
}
if (archiveFile === undefined) {
return <>
This archive does not exist
>
}
const {data, size} = archiveFile;
const singlefileUrl = data.singlefile_path ? `/media/${encodeMediaPath(data.singlefile_path)}` : null;
const readabilityUrl = data.readability_path ? `/media/${encodeMediaPath(data.readability_path)}` : null;
const screenshotUrl = data.screenshot_path ? `/media/${encodeMediaPath(data.screenshot_path)}` : null;
const singlefileButton =
;
const readButton =
const screenshot = screenshotUrl ?
:
null;
const localDeleteArchive = async () => {
await deleteArchives([data.id]);
toast({
type: 'success',
title: 'Archive Deleted',
description: 'Archive was successfully deleted.',
time: 2000,
})
navigate(-1);
}
const localUpdateArchive = async () => {
const downloadData = {urls: [archiveFile.url], downloader: Downloaders.Archive};
const response = await postDownload(downloadData);
if (response.ok) {
toast({
type: 'success',
title: 'Archive Downloading',
description: 'Archive update has been scheduled.',
time: 2000,
});
}
}
const localGenerateScreenshot = async () => {
const success = await generateArchiveScreenshot(data.id);
if (success) {
// Refresh the archive data after a short delay to show the new screenshot
setTimeout(() => fetchArchive(), 2000);
}
}
const updateButton =
Update
;
const deleteButton =
Delete
;
const generateScreenshotButton = !screenshotUrl ?
Generate Screenshot
: null;
let historyList = ;
if (history && history.length === 0) {
historyList = No history available
;
} else if (history) {
historyList = ;
}
const domain = data.domain ? data.domain : null;
let domainHeader = Unknown
;
if (domain) {
const domainUrl = `/archive?domain=${domain}`;
domainHeader = ;
}
const localAddTag = async (name) => {
await tagFileGroup(archiveFile, name);
await fetchArchive();
}
const localRemoveTag = async (name) => {
await untagFileGroup(archiveFile, name);
await fetchArchive();
}
const archivedDatetimeString = isoDatetimeToAgoPopup(archiveFile.download_datetime, true);
const publishedDatetimeString = archiveFile.published_datetime ? isoDatetimeToAgoPopup(archiveFile.published_datetime, true)
: 'unknown';
const modifiedDatetimeString = archiveFile.published_modified_datetime
? isoDatetimeToAgoPopup(archiveFile.published_modified_datetime, true)
: 'unknown';
const aboutPane = {
menuItem: 'About', render: () =>
{domainHeader}
{humanFileSize(size)}
{archiveFile.url ? {archiveFile.url} : 'N/A'}
{modifiedDatetimeString}
};
const localPreviewPath = (path, mimetype) => {
if (path) {
return {path}
} else {
return 'Unknown'
}
}
const filesPane = {
menuItem: 'Files', render: () =>
{localPreviewPath(data.singlefile_path, 'text/html')}
{localPreviewPath(data.readability_path, 'text/html')}
{localPreviewPath(data.readability_txt_path, 'text/plain')}
{localPreviewPath(data.readability_json_path, 'application/json')}
{data.screenshot_path ?
archiveFileLink(data.screenshot_path)
: 'Unknown'}
{archiveFileLink(archiveFile.directory, true)}
};
const tabPanes = [aboutPane, filesPane];
const tabMenu = theme === darkTheme ? {inverted: true, attached: true} : {attached: true};
return <>
{screenshot}
{textEllipsis(archiveFile.title || data.url)}
Author: {archiveFile.author ? archiveFile.author : 'unknown'}
Published: {publishedDatetimeString}
Archived: {archivedDatetimeString}
{singlefileButton}
{readButton}
{updateButton}
{deleteButton}
{generateScreenshotButton}
{historyList}
>
}
export function ArchiveCard({file}) {
const {s} = useContext(ThemeContext);
const {data} = file;
const imageSrc = data.screenshot_path ? `/media/${encodeMediaPath(data.screenshot_path)}` : null;
const singlefileUrl = data.singlefile_path ? `/media/${encodeMediaPath(data.singlefile_path)}` : null;
let screenshot = ;
const imageLabel = file.tags && file.tags.length ? taggedImageLabel : null;
if (imageSrc) {
screenshot = ;
}
const domain = data ? data.domain : null;
const domainUrl = `/archive?domain=${domain}`;
const title = file.title || data.url;
const header = {title};
const dt = file.published_datetime || file.published_modified_datetime || file.modified;
return
{screenshot}
{domain &&
{domain}
}
{isoDatetimeToAgoPopup(dt, false)}
}
// Domain table column configuration
const DOMAIN_COLUMNS = [
{key: 'domain', label: 'Domain', sortable: true, width: 7},
{key: 'tag_name', label: 'Tag', sortable: true, width: 2},
{key: 'archive_count', label: 'Archives', sortable: true, align: 'right', width: 2},
{key: 'min_download_frequency', label: 'Download Frequency', sortable: true, format: 'frequency', width: 2, hideOnMobile: true},
{key: 'size', label: 'Size', sortable: true, align: 'right', format: 'bytes', width: 2, hideOnMobile: true},
{key: 'actions', label: 'Manage', sortable: false, type: 'actions', width: 1}
];
const DOMAIN_ROUTES = {
list: '/archive/domains',
edit: '/archive/domain/:id/edit',
search: '/archive',
searchParam: 'domain'
};
export function DomainsPage() {
useTitle('Archive Domains');
const [domains] = useDomains();
const [searchStr, setSearchStr] = useOneQuery('domain');
// Header section matching ChannelsPage pattern
const header =
setSearchStr('')}
onChange={setSearchStr}
onSubmit={null}
/>
{/* No "New Domain" button - domains are auto-created */}
;
// Empty state
if (domains && domains.length === 0) {
return <>
{header}
No domains yet. Archive some webpages!
>;
}
// Error state
if (domains === undefined) {
return <>
{header}
Could not fetch Domains
>;
}
return <>
{header}
>;
}
// Domain form field configuration
const DOMAIN_FIELDS = [
{key: 'directory', label: 'Directory', type: 'directory', placeholder: 'Optional directory path'},
// tag_name field is handled via modal button, not inline in form
{key: 'description', label: 'Description', type: 'textarea', placeholder: 'Optional description'}
];
const DOMAIN_MESSAGES = {
no_directory: 'Set a directory to enable tagging',
tag_will_move: 'Tagging will move files to a new directory'
};
export function DomainEditPage() {
const {domainId} = useParams();
const navigate = useNavigate();
const {domain, form, fetchDomain} = useDomain(parseInt(domainId));
// Modal state for tagging
const [tagEditModalOpen, setTagEditModalOpen] = useState(false);
useTitle(`Edit Domain: ${domain?.domain || '...'}`);
// Wrap form.onSubmit to add toast and refresh domain data
React.useEffect(() => {
if (form && form.onSubmit) {
const originalOnSubmit = form.onSubmit;
form.onSubmit = async () => {
try {
await originalOnSubmit();
toast({
type: 'success',
title: 'Domain Updated',
description: 'Domain was successfully updated',
time: 3000,
});
// Refresh domain data to show updated values
await fetchDomain();
} catch (e) {
console.error('Failed to update domain:', e);
throw e;
}
};
}
}, [form, fetchDomain]);
// Handler for tag modal save
const handleTagSave = async (tagName, directory) => {
try {
await tagDomain(parseInt(domainId), tagName, directory);
toast({
type: 'success',
title: 'Domain Tagged',
description: `Domain "${domain?.domain}" has been tagged with "${tagName}"`,
time: 3000,
});
} catch (e) {
console.error('Failed to tag domain', e);
} finally {
setTimeout(async () => {
await fetchDomain();
}, 500);
}
};
// Handler for fetching tag info
const handleGetTagInfo = async (tagName) => {
if (domain?.id) {
return await getCollectionTagInfo(domain.id, tagName);
}
return null;
};
const handleRefreshDomain = async (e) => {
if (e) {
e.preventDefault();
}
await refreshDomain(parseInt(domainId));
// Refresh domain data after completion
await fetchDomain();
};
if (!form.ready) {
return Loading domain...;
}
// Handler for domain deletion
const handleDelete = async () => {
try {
let response = await deleteDomain(parseInt(domainId));
if (response.status === 204) {
navigate('/archive/domains');
}
} catch (e) {
console.error('Failed to delete domain', e);
}
};
const deleteButton = Delete;
const refreshButton = domain?.directory ? (
Refresh
) : null;
const tagButton = ;
const actionButtons = <>
{deleteButton}
{refreshButton}
{tagButton}
>;
return <>
{/* Tag Modal */}
setTagEditModalOpen(false)}
currentTagName={domain?.tag_name}
originalDirectory={domain?.directory}
getTagInfo={handleGetTagInfo}
onSave={handleTagSave}
collectionName="Domain"
/>
{/* Downloads Segment */}
>;
}
function ArchiveSettingsPage() {
const {t} = React.useContext(ThemeContext);
const urlClipboardButton = navigator.clipboard.writeText(API_ARCHIVE_UPLOAD_URI)}
/>;
const dataFieldNameClipboardButton = navigator.clipboard.writeText('singlefile_contents')}
/>;
const urlFieldNameClipboardButton = navigator.clipboard.writeText('url')}
/>;
return
SingleFile Browser Extension
These are the settings necessary to configure the SingleFile Browser
Extension to automatically upload to your WROLPi.
}
function ArchivesPage() {
const [selectedArchives, setSelectedArchives] = useState([]);
useTitle('Archives');
const {
archives,
totalPages,
activePage,
setPage,
searchStr,
setSearchStr,
fetchArchives,
} = useSearchArchives();
let archiveOrders = [
{value: 'published_datetime', text: 'Published Date', short: 'P.Date'},
{value: 'published_modified_datetime', text: 'Modified Date', short: 'M.Date'},
{value: 'download_datetime', text: 'Download Date', short: 'D.Date'},
{value: 'size', text: 'Size'},
{value: 'viewed', text: 'Recently Viewed', short: 'R.Viewed'},
];
if (searchStr) {
archiveOrders = [{value: 'rank', text: 'Rank'}, ...archiveOrders];
}
const onSelect = (path, checked) => {
if (checked && path) {
setSelectedArchives([...selectedArchives, path]);
} else if (path) {
setSelectedArchives(selectedArchives.filter(i => i !== path));
}
}
const onDelete = async () => {
const archiveIds = archives.filter(i => selectedArchives.indexOf(i['primary_path']) >= 0)
.map(i => i['data']['id']);
await deleteArchives(archiveIds);
await fetchArchives();
setSelectedArchives([]);
}
const invertSelection = async () => {
const newSelectedArchives = archives.map(archive => archive['key']).filter(i => selectedArchives.indexOf(i) < 0);
setSelectedArchives(newSelectedArchives);
}
const clearSelection = async (e) => {
if (e) e.preventDefault();
setSelectedArchives([]);
}
const selectElm = ;
const {body, paginator, selectButton, viewButton, limitDropdown, tagQuerySelector} = FilesView(
{
files: archives,
activePage: activePage,
totalPages: totalPages,
selectElem: selectElm,
selectedKeys: selectedArchives,
onSelect: onSelect,
setPage: setPage,
headlines: !!searchStr
},
);
const [localSearchStr, setLocalSearchStr] = React.useState(searchStr || '');
const searchInput = setLocalSearchStr(null)}
searchStr={localSearchStr}
onSubmit={setSearchStr}
placeholder='Search Archives...'
/>;
return <>
{selectButton}
{viewButton}
{limitDropdown}
{tagQuerySelector}
{searchInput}
{selectButton}
{viewButton}
{limitDropdown}
{tagQuerySelector}
{searchInput}
{body}
{paginator}
>
}
export function ArchiveRowCells({file}) {
const {data} = file;
let {sort} = useSearchOrder();
sort = sort ? sort.replace(/^-+/, '') : null;
const archiveUrl = `/archive/${data.id}`;
const posterPath = findPosterPath(file);
const posterUrl = posterPath ? `/media/${encodeMediaPath(posterPath)}` : null;
let poster;
if (posterUrl) {
poster =
;
} else {
poster = ;
}
let dataCell = file.published_datetime ? isoDatetimeToAgoPopup(file.published_datetime) : '';
if (sort === 'published_modified_datetime') {
dataCell = file.published_modified_datetime ? isoDatetimeToAgoPopup(file.published_modified_datetime) : '';
} else if (sort === 'download_datetime') {
dataCell = file.download_datetime ? isoDatetimeToAgoPopup(file.download_datetime) : '';
} else if (sort === 'size') {
dataCell = humanFileSize(file.size);
} else if (sort === 'viewed') {
dataCell = isoDatetimeToAgoPopup(file.viewed);
}
// Fragment for SelectableRow
return
{poster}
{textEllipsis(file.title || file.stem)}
{dataCell}
}
export function ArchiveRoute() {
const location = useLocation();
const path = location.pathname;
const links = [
{
text: 'Archives',
to: '/archive',
end: true,
isActive: () => path === '/archive' || /^\/archive\/\d+$/.test(path)
},
{
text: 'Domains',
to: '/archive/domains',
isActive: () => path.startsWith('/archive/domain')
},
{text: 'Settings', to: '/archive/settings'},
];
return
}/>
}/>
}/>
}/>
}/>
}