import React, {useState} from "react"; import {useHotkeys} from "react-hotkeys-hook"; import { APIButton, BackButton, CardLink, DirectoryLink, encodeMediaPath, ErrorMessage, ExternalCardLink, FileIcon, findPosterPath, humanFileSize, humanNumber, InfoHeader, isoDatetimeToAgoPopup, PageContainer, PreviewPath, resolveDataPath, SearchInput, TabLinks, textEllipsis, mimetypeColor, useTitle, } from "./Common"; import { deleteDomain, deleteFileGroups, fetchArchiveBrowsers, fetchArchiveDownloaderConfig, generateArchiveScreenshot, getCollectionTagInfo, postArchiveFileFormat, postDownload, previewBatchReorganization, refreshDomain, tagDomain, tagFileGroup, untagFileGroup, updateArchiveDownloaderConfig, } from "../api"; import {useForm} from "../hooks/useForm"; import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal"; import {CollectionTagModal} from "./collections/CollectionTagModal"; import {CollectionReorganizeModal} from "./collections/CollectionReorganizeModal"; import {BatchReorganizeModal} from "./collections/BatchReorganizeModal"; import {useReorganizationStatus} from "../contexts/FileWorkerStatusContext"; import {Link, Route, Routes, useLocation, useNavigate, useParams} from "react-router"; import { useArchive, useArchiveStatistics, useDockerized, useDomain, useDomains, useOneQuery, useSearchArchives, useSearchDomain, useSearchOrder } from "../hooks/customHooks"; import {DeepSearchHint, FileCards, FileRowTagIcon, FilesView, SearchControlBar} from "./Files"; import _ from "lodash"; import { ActionInput, Button, Card, Header, Icon, IconButton, Loader, Loading, Message, Panel, Placeholder, Select, Statistic, StatisticGroup, Table, Tabs, Textarea, TextInput, Tooltip, toast, } from "./ui"; import {BulkTagModal} from "./BulkTagModal"; import {TagsSelector} from "../Tags"; import {AddToPlaylistButton} from "./AddToPlaylist"; import {API_ARCHIVE_UPLOAD_URI, Downloaders} from "./Vars"; import {CollectionTable} from "./collections/CollectionTable"; import {CollectionEditForm} from "./collections/CollectionEditForm"; import {RecurringDownloadsTable} from "./admin/Downloads"; import {DestinationForm} from "./Download"; function ArchivePage() { const navigate = useNavigate(); const {fileGroupId} = useParams(); const {archiveFile, history, fetchArchive} = useArchive(fileGroupId); const [taggedFileGroups, setTaggedFileGroups] = useState(null); let title = archiveFile ? archiveFile.title ? archiveFile.title : archiveFile.name : null; useTitle(title); if (archiveFile === null) { return Loading archive...; } if (archiveFile === undefined) { return <>
Unknown archive
This archive does not exist
} const {data, size, directory} = archiveFile; // Resolve data paths (filename-only) to full relative paths using directory const singlefilePath = resolveDataPath(data.singlefile_path, directory); const readabilityPath = resolveDataPath(data.readability_path, directory); const screenshotPath = resolveDataPath(data.screenshot_path, directory); const singlefileUrl = singlefilePath ? `/media/${encodeMediaPath(singlefilePath)}` : null; const readabilityUrl = readabilityPath ? `/media/${encodeMediaPath(readabilityPath)}` : null; const screenshotUrl = screenshotPath ? `/media/${encodeMediaPath(screenshotPath)}` : null; const singlefileButton = ; const readButton = const screenshot = screenshotUrl ? Archive screenshot : null; const localDeleteArchive = async (force = false) => { const result = await deleteFileGroups([archiveFile.id], force); if (result && result.tagged) { setTaggedFileGroups(result.file_groups); return; } 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(archiveFile.id); if (success) { // Refresh the archive data after a short delay to show the new screenshot setTimeout(() => fetchArchive(), 2000); } } const updateButton = Update ; const deleteButton = localDeleteArchive(false)} obeyWROLMode={true} > 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 = `/archives?domain=${domain}`; domainHeader =
{domain}
; } const localAddTag = async (name) => { await tagFileGroup(archiveFile, name); await fetchArchive(); } const localRemoveTag = async (name) => { await untagFileGroup(archiveFile, name); await fetchArchive(); } const downloadDatetimeString = archiveFile.download_datetime ? isoDatetimeToAgoPopup(archiveFile.download_datetime, true) : 'unknown'; const publishedDatetimeString = archiveFile.published_datetime ? isoDatetimeToAgoPopup(archiveFile.published_datetime, true) : 'unknown'; const modifiedDatetimeString = archiveFile.published_modified_datetime ? isoDatetimeToAgoPopup(archiveFile.published_modified_datetime, true) : 'unknown'; // Helper to find file size from the files array by resolved path const findFileSize = (resolvedPath) => { if (!resolvedPath || !archiveFile.files) return null; const file = archiveFile.files.find(i => String(i.path) === String(resolvedPath)); return file && file.size ? ({humanFileSize(file.size)}) : null; }; // Helper to resolve and preview a data path const localPreviewPath = (dataPath, mimetype) => { const resolvedPath = resolveDataPath(dataPath, directory); if (resolvedPath) { return <>{resolvedPath}{findFileSize(resolvedPath)} } else { return 'Unknown' } } const tableStyle = {width: '100%', borderCollapse: 'separate', borderSpacing: '0 0.7em'}; const labelStyle = {whiteSpace: 'nowrap', paddingRight: '1.5em', verticalAlign: 'top'}; return <>
{screenshot}
{textEllipsis(archiveFile.title || data.url)}
Author: {archiveFile.author ? archiveFile.author : 'unknown'}
Published: {publishedDatetimeString}
Downloaded: {downloadDatetimeString}
{singlefileButton} {readButton} {updateButton} {deleteButton} {generateScreenshotButton}
About Files
Domain
{domainHeader}
Size
{humanFileSize(size)}
URL

{archiveFile.url ? {archiveFile.url} : 'N/A'}

Modified Date

{modifiedDatetimeString}

Singlefile File {localPreviewPath(data.singlefile_path, 'text/html')}
Readability File {localPreviewPath(data.readability_path, 'text/html')}
Readability Text File {localPreviewPath(data.readability_txt_path, 'text/plain')}
Readability JSON File {localPreviewPath(data.readability_json_path, 'application/json')}
Screenshot File {screenshotPath ? <>{screenshotPath}{findFileSize(screenshotPath)} : 'Unknown'}
Directory
{historyList} setTaggedFileGroups(null)} onConfirm={async () => { setTaggedFileGroups(null); await localDeleteArchive(true); }} /> } export function ArchiveCard({file}) { const {sort} = useSearchOrder(); const sortField = sort ? sort.replace(/^-/, '') : null; const {data, directory} = file; // Resolve data paths (filename-only) to full relative paths using directory const screenshotPath = resolveDataPath(data.screenshot_path, directory); const singlefilePath = resolveDataPath(data.singlefile_path, directory); const imageSrc = screenshotPath ? `/media/${encodeMediaPath(screenshotPath)}` : null; const singlefileUrl = singlefilePath ? `/media/${encodeMediaPath(singlefilePath)}` : null; // Marks a tagged file, pinned to the poster's corner (same convention as CardPoster). const cardTagIcon =
; const imageLabel = !_.isEmpty(file.tags) ? cardTagIcon : null; let media; if (imageSrc) { media =
{imageLabel}
; } else { media =
{imageLabel}
; } const domain = data ? data.domain : null; const domainUrl = `/archives?domain=${domain}`; const title = file.title || data.url; const titleElm = {title} ; const dt = file.published_datetime || file.published_modified_datetime || file.modified; const meta = <> {domain &&
{domain}
}
{sortField === 'published_modified_datetime' ? isoDatetimeToAgoPopup(file.published_modified_datetime, false) : sortField === 'download_datetime' ? isoDatetimeToAgoPopup(file.download_datetime, false) : sortField === 'size' ? humanFileSize(file.size) : sortField === 'viewed' ? isoDatetimeToAgoPopup(file.viewed, false) : isoDatetimeToAgoPopup(dt, false) }
; const actions =
; return } // 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: '/archives/domains', edit: '/archives/domain/:id/edit', search: '/archives', searchParam: 'domain' }; function DomainStatistics({statistics}) { if (!statistics) { return <> } return
Statistics
} export function DomainsPage() { useTitle('Archive Domains'); const [domains] = useDomains(); const [searchStr, setSearchStr] = useOneQuery('domain'); const searchInputRef = React.useRef(); useHotkeys('f', (e) => { e.preventDefault(); if (searchInputRef.current) { searchInputRef.current.focus(); } }, {enableOnFormTags: false}); // Header section matching ChannelsPage pattern. No `marginBottom`: this is a top-level block // of the page, and the page's stack spaces it -- its own margin was added to that gap. const header =
setSearchStr('')} onChange={setSearchStr} onSubmit={null} inputRef={searchInputRef} />
{/* No "New Domain" button - domains are auto-created */}
; // Empty state if (domains && domains.length === 0) { return <> {header} ; } // Error state if (domains === undefined) { return <> {header} Could not fetch Domains ; } return <> {header} ; } 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); // Modal state for reorganization const [reorganizeModalOpen, setReorganizeModalOpen] = 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) { if (form.error) { return <>

{form.error}

; } return Loading domain...; } // Handler for domain deletion const handleDelete = async () => { try { let response = await deleteDomain(parseInt(domainId)); if (response.status === 204) { navigate('/archives/domains'); } } catch (e) { console.error('Failed to delete domain', e); } }; const deleteButton = Delete; const refreshButton = domain?.directory ? ( Refresh ) : null; const tagButton = ; const reorganizeButton = ( setReorganizeModalOpen(true)} obeyWROLMode={true} >Reorganize Files ); const actionButtons = <> {deleteButton} {refreshButton} {tagButton} {reorganizeButton} ; const [descriptionProps] = form.getCustomProps({name: 'description', path: 'description'}); return <>
{domain?.needs_reorganization && (

The file name format has changed. Click "Reorganize Files" to move existing files to match the new format.

)} {/* * CollectionEditForm still wraps its children in a `ui stackable grid` div (Semantic's * grid CSS, not a component) because it is shared with unmigrated callers (Channels.js, * Playlists.js). Plain "row"/"column" divs are that CSS's own class names, not a * semantic-ui-react import. */}