'use client'; import { useCallback, useRef, useState } from 'react'; import { toast } from 'sonner'; import type { BunnyDownloadPreference, Comment, DownloadTarget, Version, VideoData, } from '@/components/video-page/types'; import { resolvePublicBunnyCdnHostname } from '@/lib/bunny-cdn'; import { resolvePublicDirectDownloadAllowedHosts } from '@/lib/runtime-public-config'; import { downloadNamedFile, downloadProgressLabel, downloadProgressPercent, extensionFromUrl, navigateDownload, } from '@/lib/client/download-file'; import { createDownloadProgressToast, type DownloadProgressToastHandle, } from '@/components/download-progress-toast'; function sanitizeDownloadFileName(value: string): string { return value .replace(/[<>:"/\\|?*\u0000-\u001F]/g, '-') .replace(/\s+/g, ' ') .trim(); } function getAllowedHosts() { const bunnyCdnHostname = resolvePublicBunnyCdnHostname(); return [ ...(bunnyCdnHostname ? [bunnyCdnHostname.trim().toLowerCase()] : []), ...resolvePublicDirectDownloadAllowedHosts(), ].filter(Boolean); } function getSafeDirectDownloadUrl(rawUrl: string): string | null { try { const parsed = new URL(rawUrl); if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { return null; } const allowedHosts = getAllowedHosts(); if (allowedHosts.length === 0) { return null; } const normalizedHost = parsed.hostname.toLowerCase(); if (!allowedHosts.includes(normalizedHost)) { return null; } return parsed.toString(); } catch { return null; } } interface UseDownloadActionsParams { activeVersion: (Version & { comments: Comment[] }) | undefined; video: VideoData | null; } export function useDownloadActions({ activeVersion, video }: UseDownloadActionsParams) { const [activeDownloadTarget, setActiveDownloadTarget] = useState(null); const isDownloadingVideo = activeDownloadTarget !== null; // The guard reads a ref, not the state. Two calls originating in the same render both // saw the old state value and both proceeded, so a fast double-click downloaded the // file twice. const isDownloadingRef = useRef(false); const startDownload = useCallback( async (preference: BunnyDownloadPreference = 'compressed') => { if (!activeVersion || !video || isDownloadingRef.current) return; if (!video.canDownload) { toast.error('Download is disabled for this shared link'); return; } if ( activeVersion.providerId !== 'bunny' && activeVersion.providerId !== 'direct' && activeVersion.providerId !== 'r2' ) { toast.error('This video source does not support direct download'); return; } const target: DownloadTarget = activeVersion.providerId === 'bunny' ? preference : 'direct'; isDownloadingRef.current = true; setActiveDownloadTarget(target); let progressToast: DownloadProgressToastHandle | null = null; try { let downloadUrl: string | null = null; if (activeVersion.providerId === 'bunny') { const prepareRes = await fetch( `/api/versions/${activeVersion.id}/download?source=${preference}&prepare=1`, { cache: 'no-store', } ); if (!prepareRes.ok) { const prepareBody = await prepareRes.json().catch(() => null); const fallbackError = preference === 'original' ? 'Original file is not available for this video' : 'Compressed file is not available for this video'; const errorMessage = typeof prepareBody?.error === 'string' ? prepareBody.error : fallbackError; throw new Error(errorMessage); } downloadUrl = `/api/versions/${activeVersion.id}/download?source=${preference}`; } else if (activeVersion.providerId === 'r2') { if (!activeVersion.originalUrl.startsWith('/api/upload/video/')) { throw new Error('Direct download URL is not allowed'); } downloadUrl = activeVersion.originalUrl; } else { downloadUrl = getSafeDirectDownloadUrl(activeVersion.originalUrl); if (!downloadUrl) { throw new Error('Direct download URL is not allowed'); } } if (!downloadUrl) { throw new Error('Missing download URL'); } // File name: "