import React, {useEffect, useRef, useState} from 'react'; import {Link, Outlet, useParams} from "react-router"; import {useHotkeys} from "react-hotkeys-hook"; import { APIButton, CardLink, CardPoster, Duration, encodeMediaPath, ErrorMessage, FileIcon, findPosterPath, humanFileSize, humanNumber, HelpHeader, InfoHeader, isoDatetimeToAgoPopup, PageContainer, PreviewLink, scrollToTop, secondsToFullDuration, TabLinks, textEllipsis, useTitle, CookiesUnlockModal } from "./Common" import VideoPage from "./VideoPlayer"; import { ActionInput, Button, Card, Header, Icon, Loading, Modal, NumberInput, Panel, Placeholder, Statistic, StatisticGroup, Table, Textarea, TextInput, Tooltip, } from "./ui"; import {useChannel, useSearchOrder, useSearchVideos, useVideo, useVideoStatistics} from "../hooks/customHooks"; import {DeepSearchHint, FileRowTagIcon, FilesView, SearchControlBar} from "./Files"; import {BulkTagModal} from "./BulkTagModal"; import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal"; import { deleteFileGroups, deleteCookies, fetchSuggestedUserAgent, fetchVideoDownloaderConfig, getCookiesStatus, lockCookies, postVideoFileFormat, previewBatchReorganization, updateVideoDownloaderConfig, uploadCookies, } from "../api"; import {QueryContext} from "../contexts/contexts"; import _ from "lodash"; import {defaultFileOrder, defaultSearchOrder} from "./Vars"; import {InputForm, ToggleForm, useForm} from "../hooks/useForm"; import {VideoFormatSelectorForm, VideoResolutionSelectorForm} from "./Download"; import {BatchReorganizeModal} from "./collections/BatchReorganizeModal"; export function VideoWrapper() { const {fileGroupId} = useParams(); const {videoFile, prevFile, nextFile, fetchVideo} = useVideo(fileGroupId); // Scroll to the top when fileGroupId changes. useEffect(scrollToTop, [fileGroupId]); return } export function VideosPage() { const {channelId} = useParams(); const {searchParams} = React.useContext(QueryContext); const [selectedVideos, setSelectedVideos] = useState([]); const [bulkTagOpen, setBulkTagOpen] = useState(false); const [taggedFileGroups, setTaggedFileGroups] = useState(null); const searchInputRef = React.useRef(); useHotkeys('f', (e) => { e.preventDefault(); if (searchInputRef.current) { searchInputRef.current.focus(); } }, {enableOnFormTags: false}); let searchOrder = defaultFileOrder; if (searchParams.get('order')) { // Use whatever order the user specified. searchOrder = searchParams.get('order'); } else if (searchParams.get('q')) { // User used a search_str searchOrder = defaultSearchOrder; } const {searchStr, setSearchStr, videos, activePage, setPage, totalPages, fetchVideos, loading} = useSearchVideos(null, channelId, searchOrder); const {channel} = useChannel(channelId); let title = 'Videos'; if (channel && channel.name) { title = `${channel.name} Videos`; } useTitle(title); let videoOrders = [ {value: 'published_datetime', text: 'Published Date', short: 'P.Date'}, {value: 'length', text: 'Length'}, {value: 'size', text: 'Size'}, {value: 'size_to_duration', text: 'Size to Duration', short: 'S/Duration'}, {value: 'view_count', text: 'Views'}, {value: 'viewed', text: 'Recently Viewed', short: 'R.Viewed'}, {value: 'download_datetime', text: 'Download Date', short: 'D.Date'}, ] if (searchStr) { videoOrders = [{value: 'rank', text: 'Search'}, ...videoOrders]; } let header; if (channel && channel.name) { const editLink = `/videos/channel/${channelId}/edit`; header = <>
{channel.name}
; } else if (channelId) { header =
; } const onSelect = (path, checked) => { const newSelectedVideos = checked && path ? [...selectedVideos, path] : selectedVideos.filter(i => i !== path); console.debug(`Selected Videos: ${newSelectedVideos}`); setSelectedVideos(newSelectedVideos); } const onDelete = async (force = false) => { const fileGroupIds = videos.filter(i => selectedVideos.indexOf(i['primary_path']) >= 0).map(i => i['id']); const result = await deleteFileGroups(fileGroupIds, force); if (result && result.tagged) { setTaggedFileGroups(result.file_groups); return; } await fetchVideos(); setSelectedVideos([]); } const invertSelection = async () => { const newSelectedVideos = videos.map(video => video['key']).filter(i => selectedVideos.indexOf(i) < 0); setSelectedVideos(newSelectedVideos); } const clearSelection = async (e) => { if (e) e.preventDefault(); setSelectedVideos([]); } const onBulkTagComplete = async () => { await fetchVideos(); setSelectedVideos([]); } const selectElm =
onDelete(false)} >Delete setBulkTagOpen(false)} paths={selectedVideos} onComplete={onBulkTagComplete} />
; const {body, paginator, viewButton} = FilesView( { files: videos, activePage: activePage, totalPages: totalPages, selectElem: selectElm, selectedKeys: selectedVideos, onSelect: onSelect, setPage: setPage, headlines: !!searchStr, loading: loading, }, ); return <> {header} {body} {paginator} setTaggedFileGroups(null)} onConfirm={async () => { setTaggedFileGroups(null); await onDelete(true); }} /> } function VideoFileNameForm({form}) { const [message, setMessage] = React.useState(null); const debouncedOnChange = React.useCallback( _.debounce(async (value) => { const response = await postVideoFileFormat(value); const {error, preview} = await response.json(); if (error) { setMessage({content: error, header: 'Invalid File Name', negative: true}); } else { setMessage({content: preview, header: 'File Name Preview', positive: true}); } }, 300), [] ); // Cleanup debounce on unmount React.useEffect(() => { return () => debouncedOnChange.cancel(); }, [debouncedOnChange]); const onChange = debouncedOnChange; const label =

Common yt-dlp variables:

  • %(title)s - Video title
  • %(uploader)s - Channel/uploader name
  • %(upload_date)s - Upload date (YYYYMMDD)
  • %(upload_year)s - Upload year (YYYY)
  • %(upload_month)s - Upload month (01-12)
  • %(id)s - Video ID
  • %(channel)s - Channel name
  • %(duration)s - Duration in seconds
  • %(playlist_index)s - Playlist index
  • %(ext)s - File extension (required, must be at end)

See yt-dlp docs for all variables. Subdirectories supported.

} />; return } const settingsGridStyle = { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '1em', marginBottom: '1em', }; export function VideosSettingsPage() { useTitle('Videos Settings'); const [batchModalOpen, setBatchModalOpen] = useState(false); const [channelsNeedingReorg, setChannelsNeedingReorg] = useState(0); const [fetchingReorgCount, setFetchingReorgCount] = useState(true); // Check how many channels need reorganization on mount useEffect(() => { setFetchingReorgCount(true); previewBatchReorganization('channel') .then(data => { setChannelsNeedingReorg(data.total_collections || 0); }) .catch(() => { setChannelsNeedingReorg(0); }) .finally(() => { setFetchingReorgCount(false); }); }, []); const emptyFormData = { video_resolutions: ['1080p', '720p', '480p', 'maximum'], yt_dlp_options: { continue_dl: true, file_name_format: '%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s', merge_output_format: 'mp4', nooverwrites: true, writeautomaticsub: true, writeinfojson: true, writesubtitles: true, writethumbnail: true, }, yt_dlp_extra_args: '', download_missing_video_comments: false, user_agent: '', sleep_requests: 0.75, }; const configSubmitter = async () => { return await updateVideoDownloaderConfig(configForm.formData); }; const configForm = useForm({ fetcher: fetchVideoDownloaderConfig, submitter: configSubmitter, emptyFormData, }); const [suggestedUserAgent, setSuggestedUserAgent] = useState(''); React.useEffect(() => { const fetchSuggested = async () => { const ua = await fetchSuggestedUserAgent(); setSuggestedUserAgent(ua); }; fetchSuggested(); }, []); const downloadMissingVideoCommentsLabel = ; return <>
Video Downloader Config
e.preventDefault()}>
configForm.setValue('sleep_requests', parseFloat(value) || 0)} placeholder='0.75' rightSection={sec} rightSectionWidth={36} />
configForm.setValue('user_agent', e.currentTarget.value)} placeholder='Leave empty to use yt-dlp default' action={} />
Save
File Organization

{fetchingReorgCount ? 'Checking for channels that need reorganization...' : <> {channelsNeedingReorg} channel{channelsNeedingReorg !== 1 ? 's' : ''} {channelsNeedingReorg > 0 ? ' have files that do not match the current file name format.' : '. All channels are organized correctly.'} }

setBatchModalOpen(false)} kind='channel' onComplete={() => { setBatchModalOpen(false); setChannelsNeedingReorg(0); }} /> } function CookiesSettingsSection() { const [status, setStatus] = useState({cookies_exist: false, cookies_unlocked: false}); const [loading, setLoading] = useState(true); const [uploadModalOpen, setUploadModalOpen] = useState(false); const [unlockModalOpen, setUnlockModalOpen] = useState(false); const [cookiesContent, setCookiesContent] = useState(''); const [password, setPassword] = useState(''); const [submitting, setSubmitting] = useState(false); const cookiesContentRef = useRef(null); useEffect(() => { if (uploadModalOpen) { const timer = setTimeout(() => { if (cookiesContentRef.current) { cookiesContentRef.current.focus(); } }, 100); return () => clearTimeout(timer); } }, [uploadModalOpen]); const fetchStatus = async () => { setLoading(true); const result = await getCookiesStatus(); if (result) { setStatus(result); } setLoading(false); }; useEffect(() => { fetchStatus(); }, []); const handleUpload = async () => { if (password.length < 8) { return; } setSubmitting(true); const result = await uploadCookies(cookiesContent, password); setSubmitting(false); if (result.success) { setUploadModalOpen(false); setCookiesContent(''); setPassword(''); fetchStatus(); } }; const handleLock = async () => { setSubmitting(true); await lockCookies(); setSubmitting(false); fetchStatus(); }; const handleDelete = async () => { setSubmitting(true); await deleteCookies(); setSubmitting(false); fetchStatus(); }; // Status is encoded by color like any other status label; no filled "success/warning" // words map directly to a token, so the wrapper picks the token color explicitly. const getStatusLabel = () => { if (loading) return Loading...; if (!status.cookies_exist) return No cookies stored; if (status.cookies_unlocked) return Unlocked; return Locked; }; return

Use this feature at your own risk! You may be suspended or blocked if abused!

Status: {getStatusLabel()}
{!status.cookies_exist && ( )} {status.cookies_exist && !status.cookies_unlocked && ( )} {status.cookies_exist && status.cookies_unlocked && ( )} {status.cookies_exist && ( <> Delete )}
{/* Upload Modal */} setUploadModalOpen(false)} size='small' > Upload Cookies
e.preventDefault()}>