import React, {useEffect, useState} from 'react';
import {useHotkeys} from 'react-hotkeys-hook';
import {deleteFileGroups, downloadVideoMetadata, tagFileGroup, untagFileGroup} from "../api";
import {Link, useNavigate, useParams} from "react-router";
import _ from "lodash";
import {
APIButton,
BackButton,
DirectoryLink,
encodeMediaPath,
ErrorMessage,
humanFileSize,
humanNumber,
isoDatetimeToAgoPopup,
MultilineText,
PageContainer,
PreviewPath,
useMediaSession,
useTitle
} from "./Common";
import {VideoPlaceholder} from "./Placeholder";
import {useChannel, useVideoCaptions, useVideoExtras} from "../hooks/customHooks";
import {Button, Grid, Header, Icon, Label, Loading, Panel, Placeholder, Tabs, TextInput} from "./ui";
import {VideoCard} from "./Videos";
import {TagsSelector} from "../Tags";
import {AddToPlaylistButton} from "./AddToPlaylist";
import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal";
import {VideoEditMenu} from "./VideoEditMenu";
import {IconPlayerPause, IconPlayerPlay} from "@tabler/icons-react";
const MEDIA_PATH = '/media';
// YouTube auto-generated captions (downloaded via yt-dlp) stamp every cue with `align:start position:0%`,
// which pins the text to the bottom-left of the player and makes it hard to read. Detect that signature and
// reset those cues to the browser's centered default. This mutates only the in-memory VTTCue objects the
// browser parsed; the .vtt file on disk is never modified. Cues that were deliberately positioned (anything
// other than the auto-caption signature) are left untouched. YouTube auto-captions never set `line`, so we
// require `line === 'auto'` too; that leaves a deliberately placed cue (e.g. `line:0` for top-edge) alone even
// if it happens to also be `align:start position:0%`.
export function centerAutoCaptions(track) {
if (!track || !track.cues) {
return 0;
}
let changed = 0;
for (const cue of track.cues) {
if (cue.align === 'start' && cue.position === 0 && cue.line === 'auto') {
cue.align = 'center';
cue.position = 'auto';
changed++;
}
}
return changed;
}
function handleCaptionTrackLoad(event) {
const track = event.target.track;
if (!track) {
return;
}
if (track.cues && track.cues.length > 0) {
centerAutoCaptions(track);
} else {
// A non-default track has mode 'disabled' at load time, so its cues are not parsed yet. Normalize
// them once the browser populates the cue list (when the user selects the track and playback advances
// into a cue). Only detach after cues actually exist, in case a cuechange fires before they load.
const onCueChange = () => {
if (track.cues && track.cues.length > 0) {
centerAutoCaptions(track);
track.removeEventListener('cuechange', onCueChange);
}
};
track.addEventListener('cuechange', onCueChange);
}
}
export function CaptionTrack({src, ...props}) {
// Center YouTube auto-generated captions once the browser parses the cues (see centerAutoCaptions).
props = {onLoad: handleCaptionTrackLoad, ...props};
if (src.endsWith('.de.vtt')) {
return
} else if (src.endsWith('.es.vtt')) {
return
} else if (src.endsWith('.fr.vtt')) {
return
} else if (src.endsWith('.id.vtt')) {
return
} else if (src.endsWith('.it.vtt')) {
return
} else if (src.endsWith('.ja.vtt')) {
return
} else if (src.endsWith('.pl.vtt')) {
return
} else if (src.endsWith('.pt.vtt')) {
return
} else if (src.endsWith('.ro.vtt')) {
return
} else if (src.endsWith('.ru.vtt')) {
return
} else if (src.endsWith('.th.vtt')) {
return
}
return
}
const NoComments = ({video}) => {
const videoUrl = video.url;
const handleRefresh = async () => {
await downloadVideoMetadata(videoUrl);
};
if (videoUrl) {
return
No comments have been been downloaded. Refresh the video?
Refresh
} else {
return
No comment have been downloaded. WROLPi does not know the URL of this video, so it cannot download
the comments.
Try finding and downloading the video again.
}
}
// The token library has no comment-thread component -- this is a nested
// comment thread, not a reusable widget, so it is built here from plain elements and tokens.
const VideoComment = ({comment, children}) => {
const {is_favorited, like_count, author, timestamp, text, author_is_uploader} = comment;
// Author comments and favorited comments are important.
let specialIcon = null;
if (author_is_uploader) {
specialIcon = ;
} else if (is_favorited) {
specialIcon = ;
}
return
{specialIcon}{author}
{isoDatetimeToAgoPopup(timestamp * 1000)}
{like_count ?
{humanNumber(comment['like_count'])}
: null}
{children && !_.isEmpty(children) &&
{children.map((i, key) => )}
}
}
// `comments` follows useVideoExtras: null = pending, undefined = fetch failed, [] = none downloaded.
// Only the last of those may offer the Refresh button.
export const Comments = ({comments, video}) => {
if (comments === null) {
return
} else if (comments === undefined) {
return Could not fetch the comments.
} else if (_.isEmpty(comments)) {
return
}
comments.sort((a, b) => {
// Treat undefined like_count as 0
const likeA = a.like_count ?? 0;
const likeB = b.like_count ?? 0;
// For descending order
return likeB - likeA;
});
const rootComments = comments.filter(i => i['parent'] === 'root');
// Comments are in an array, convert it to a dict, grouped by their parent.
const groupedByParent = {};
comments.forEach(obj => {
if (!groupedByParent[obj.parent]) {
groupedByParent[obj.parent] = [];
}
groupedByParent[obj.parent].push(obj);
})
// Sort replies to each parent by the time they were created.
comments.forEach(obj => {
const children = groupedByParent[obj.parent];
groupedByParent[obj.parent] = _.sortBy(children, ['timestamp']);
})
return
}
function formatVideoDescription(description, setVideoTime) {
// Convert timestamps to links which change the video's playback location. Change hashtags to search links.
if (description && description.length > 0) {
try {
const lines = _.split(description, '\n');
let newLines = [];
for (let i = 0; i <= lines.length; i++) {
const line = lines[i];
const match = line ? line.match(chapterRegex) : null;
let link;
if (match) {
// This line in the description starts with a chapter timestamp, parse it and create a link.
try {
const timestamp = match[1];
const title = match[6];
// Assume 0 if no part of timestamp could be found.
const [hour, minute, second] = match.slice(3, 6).map(i => parseInt(i) || 0);
// Convert timestamp to seconds.
const seconds = (((hour * 60) + minute) * 60) + second;
link = <>
setVideoTime(seconds)}>{timestamp}
{title}
>;
} catch (e) {
// Report an error while creating timestamp link.
console.error(e);
}
// Use the link if we could create it, otherwise fallback to the original `line`.
newLines = [...newLines, link || hashtagLinks(line)];
} else if (line !== undefined) {
// Line does not start with a timestamp.
newLines = [...newLines, hashtagLinks(line)];
}
}
// Map all lines and links with a break between.
return <>
{newLines.map((i, idx) =>
{i}
)}
>;
} catch (e) {
// Some error happened while parsing description. Report it but don't fail.
console.error(e);
}
}
// Error occurred, or no description, don't fail.
return description;
}
const hashtagRegex = /(#+[_a-zA-Z0-9]+)/ig;
function hashtagLinks(text) {
// Converts a string into a div which has hashtags converted to search links.
// Example: Some text #hashtag the rest of the text
if (text && text.length > 0) {
const parts = text.split(hashtagRegex);
let newParts = '';
for (let i = 0; i < parts.length; i++) {
let part = parts[i];
part = part.startsWith('#') ?
// Part is a hashtag.
{part}
// Part is not a hashtag.
: {part};
newParts = [...newParts, part];
}
return {newParts};
}
return text;
}