import React, { useState, useEffect } from 'react'; import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw } from 'lucide-react'; import KeyInput from './components/KeyInput'; import MediaInput from './components/MediaInput'; import ResultCard from './components/ResultCard'; import ProcessingAnimation from './components/ProcessingAnimation'; // import Gallery from './components/Gallery'; import ThumbnailStudio from './components/ThumbnailStudio'; import SaaShortsTab from './components/SaaShortsTab'; import UGCGallery from './components/UGCGallery'; import { getApiUrl } from './config'; // Enhanced "Encryption" using XOR + Base64 with a Salt // This is better than plain Base64 but still client-side. const SECRET_KEY = import.meta.env.VITE_ENCRYPTION_KEY || "OpenShorts-Static-Salt-Change-Me"; const ENCRYPTION_PREFIX = "ENC:"; const encrypt = (text) => { if (!text) return ''; try { const xor = text.split('').map((c, i) => String.fromCharCode(c.charCodeAt(0) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length)) ).join(''); return ENCRYPTION_PREFIX + btoa(xor); } catch (e) { console.error("Encryption failed", e); return text; } }; const decrypt = (text) => { if (!text) return ''; if (text.startsWith(ENCRYPTION_PREFIX)) { try { const raw = text.slice(ENCRYPTION_PREFIX.length); // Check if it's plain base64 or our custom XOR (simple try) const xor = atob(raw); const result = xor.split('').map((c, i) => String.fromCharCode(c.charCodeAt(0) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length)) ).join(''); return result; } catch (e) { // Fallback if decryption fails (might be old plain text) return ''; } } // Backward compatibility: If no prefix, assume old plain text (or return empty if you want to force re-login) // For migration: Return text as is, so it populates the field, and next save will encrypt it. return text; }; // Simple TikTok icon sine Lucide might not have it or it varies const TikTokIcon = ({ size = 16, className = "" }) => ( ); const UserProfileSelector = ({ profiles, selectedUserId, onSelect }) => { const [isOpen, setIsOpen] = useState(false); if (!profiles || profiles.length === 0) return null; const selectedProfile = profiles.find(p => p.username === selectedUserId) || profiles[0]; return (
{isOpen && (
{profiles.map((profile) => ( ))}
)}
); }; const SESSION_KEY = 'openshorts_session'; const SESSION_MAX_AGE = 3600000; // 1 hour (matches server job retention) // Mock polling function const pollJob = async (jobId) => { const res = await fetch(getApiUrl(`/api/status/${jobId}`)); if (!res.ok) throw new Error('Status check failed'); return res.json(); }; function App() { const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || ''); // Social API State - Load encrypted or plain const [uploadPostKey, setUploadPostKey] = useState(() => { const stored = localStorage.getItem('uploadPostKey_v3'); if (stored) return decrypt(stored); return ''; }); // ElevenLabs API State - Load encrypted const [elevenLabsKey, setElevenLabsKey] = useState(() => { const stored = localStorage.getItem('elevenLabsKey_v1'); if (stored) return decrypt(stored); return ''; }); // fal.ai API State - Load encrypted const [falKey, setFalKey] = useState(() => { const stored = localStorage.getItem('falKey_v1'); if (stored) return decrypt(stored); return ''; }); const [uploadUserId, setUploadUserId] = useState(() => localStorage.getItem('uploadUserId') || ''); const [userProfiles, setUserProfiles] = useState([]); // List of {username, connected: []} const [showKeyModal, setShowKeyModal] = useState(false); const [jobId, setJobId] = useState(null); const [status, setStatus] = useState('idle'); // idle, processing, complete, error const [results, setResults] = useState(null); const [logs, setLogs] = useState([]); const [logsVisible, setLogsVisible] = useState(true); const [processingMedia, setProcessingMedia] = useState(null); const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings const [sessionRecovered, setSessionRecovered] = useState(false); // Sync state for original video playback const [syncedTime, setSyncedTime] = useState(0); const [isSyncedPlaying, setIsSyncedPlaying] = useState(false); const [syncTrigger, setSyncTrigger] = useState(0); const handleClipPlay = (startTime) => { setSyncedTime(startTime); setIsSyncedPlaying(true); setSyncTrigger(prev => prev + 1); }; const handleClipPause = () => { setIsSyncedPlaying(false); }; // Session Recovery: Restore on mount useEffect(() => { try { const saved = localStorage.getItem(SESSION_KEY); if (!saved) return; const session = JSON.parse(saved); if (Date.now() - session.timestamp > SESSION_MAX_AGE) { localStorage.removeItem(SESSION_KEY); return; } if (session.jobId && session.status && session.status !== 'idle') { setJobId(session.jobId); setResults(session.results || null); if (session.processingMedia) setProcessingMedia(session.processingMedia); if (session.activeTab) setActiveTab(session.activeTab); // If was processing, resume polling; if complete/error, just show results setStatus(session.status === 'processing' ? 'processing' : session.status); setSessionRecovered(true); setTimeout(() => setSessionRecovered(false), 5000); } } catch (e) { localStorage.removeItem(SESSION_KEY); } }, []); // Session Recovery: Save state changes useEffect(() => { if (status === 'idle') { localStorage.removeItem(SESSION_KEY); return; } try { const sessionData = { jobId, status, results, processingMedia: processingMedia?.type === 'url' ? processingMedia : null, activeTab, timestamp: Date.now() }; localStorage.setItem(SESSION_KEY, JSON.stringify(sessionData)); } catch (e) { // localStorage full or serialization error - ignore } }, [jobId, status, results, activeTab]); useEffect(() => { // Encrypt Gemini Key too for consistency if desired, but user asked specifically about Social integration not saving well. // For now keeping gemini plain for compatibility unless requested. if (apiKey) localStorage.setItem('gemini_key', apiKey); }, [apiKey]); useEffect(() => { if (uploadPostKey) { localStorage.setItem('uploadPostKey_v3', encrypt(uploadPostKey)); } if (uploadUserId) { localStorage.setItem('uploadUserId', uploadUserId); } }, [uploadPostKey, uploadUserId]); useEffect(() => { if (elevenLabsKey) { localStorage.setItem('elevenLabsKey_v1', encrypt(elevenLabsKey)); } }, [elevenLabsKey]); useEffect(() => { if (falKey) { localStorage.setItem('falKey_v1', encrypt(falKey)); } }, [falKey]); useEffect(() => { if (uploadPostKey && userProfiles.length === 0) { fetchUserProfiles(); } }, [uploadPostKey]); useEffect(() => { let interval; if ((status === 'processing' || status === 'completed') && jobId) { interval = setInterval(async () => { try { const data = await pollJob(jobId); console.log("Job status:", data); // Update results if available (real-time) if (data.result) { setResults(data.result); } if (data.status === 'completed') { setStatus('complete'); clearInterval(interval); } else if (data.status === 'failed') { setStatus('error'); const errorMsg = data.error || (data.logs && data.logs.length > 0 ? data.logs[data.logs.length - 1] : "Process failed"); setLogs(prev => [...prev, "Error: " + errorMsg]); clearInterval(interval); } else { // Update logs if available if (data.logs) setLogs(data.logs); } } catch (e) { console.error("Polling error", e); } }, 2000); } return () => clearInterval(interval); }, [status, jobId]); const fetchUserProfiles = async () => { if (!uploadPostKey) return; try { const res = await fetch(getApiUrl('/api/social/user'), { headers: { 'X-Upload-Post-Key': uploadPostKey } }); if (!res.ok) throw new Error("Failed to fetch"); const data = await res.json(); if (data.profiles && data.profiles.length > 0) { setUserProfiles(data.profiles); // Auto select first if none selected if (!uploadUserId) { setUploadUserId(data.profiles[0].username); } } else { alert("No profiles found for this API Key."); } } catch (e) { alert("Error fetching User Profiles. Please check key."); console.error(e); } }; const handleProcess = async (data) => { if (!apiKey) { setShowKeyModal(true); return; } setStatus('processing'); setLogs(["Starting process..."]); setResults(null); setProcessingMedia(data); try { let body; const headers = { 'X-Gemini-Key': apiKey }; if (data.type === 'url') { headers['Content-Type'] = 'application/json'; body = JSON.stringify({ url: data.payload }); } else { const formData = new FormData(); formData.append('file', data.payload); body = formData; } const res = await fetch(getApiUrl('/api/process'), { method: 'POST', headers: data.type === 'url' ? headers : { 'X-Gemini-Key': apiKey }, body }); if (!res.ok) throw new Error(await res.text()); const resData = await res.json(); setJobId(resData.job_id); } catch (e) { setStatus('error'); setLogs(l => [...l, `Error starting job: ${e.message}`]); } }; const handleReset = () => { setStatus('idle'); setJobId(null); setResults(null); setLogs([]); setProcessingMedia(null); localStorage.removeItem(SESSION_KEY); }; // --- UI Components --- const Sidebar = () => (
Logo
OpenShorts
{ e.preventDefault(); localStorage.removeItem('openshorts_skip_landing'); window.location.hash = ''; window.location.reload(); }} className="flex items-center gap-2 p-3 bg-white/5 hover:bg-white/10 rounded-xl transition-colors group" >

Landing Page

View website

Open Source

Free & Community Driven

); return (
{/* Background Gradients */}
{/* Top Header */}
{status !== 'idle' && ( )}
{userProfiles.length > 0 && ( )} {!apiKey && ( API Key Missing )}
{/* Session Recovery Banner */} {sessionRecovered && (
Session recovered Your previous work has been restored.
)} {/* Main Workspace */}
{/* View: Settings */} {activeTab === 'settings' && (

Settings

Privacy: keys only live in your browser (sent to backend just to process)

Social Integration

Optional

Automatically publish your clips to TikTok, Instagram Reels, and YouTube Shorts via Upload-Post. Includes a free tier (no credit card required). If you prefer, you can skip this and manually download/upload your videos.

setUploadPostKey(e.target.value)} className="input-field" placeholder="ey..." />

Connect your Upload-Post account to enable one-click publishing.


Keys are only stored in your browser. They are sent to the backend only to process your request, never stored server-side.

Video Translation

Optional

Translate your clips to different languages using ElevenLabs AI dubbing. Automatically translates speech while preserving the original voice characteristics.

setElevenLabsKey(e.target.value)} className="input-field" placeholder="sk_..." />

Get your API key from ElevenLabs to enable video translation.


Keys are only stored in your browser. They are sent to the backend only to process your request, never stored server-side.

AI Shorts (UGC Videos)

New

Generate UGC-style videos with AI actors for any product or business using fal.ai. Just describe your product or paste a URL. Requires fal.ai + ElevenLabs API keys.

setFalKey(e.target.value)} className="input-field" placeholder="fal_..." />

Get your API key from fal.ai to enable AI actor video generation.


Keys are only stored in your browser. Sent to backend only to process requests.

)} {/* View: SaaS Shorts */} {activeTab === 'saasshorts' && ( )} {/* View: UGC Gallery */} {activeTab === 'ugc-gallery' && ( )} {/* View: Thumbnails */} {activeTab === 'thumbnails' && ( )} {/* View: Gallery */} {/* {activeTab === 'gallery' && ( )} */} {/* View: Dashboard (Idle) */} {activeTab === 'dashboard' && status === 'idle' && (

Create Viral Shorts

Drop your long-form video URL or file below to instantly generate viral clips with AI.

YouTube Instagram TikTok
)} {/* View: Processing / Results (Split View) */} {activeTab === 'dashboard' && (status === 'processing' || status === 'complete' || status === 'error') && (
{/* Left Panel: Preview & Status */}

Live Analysis

{status.toUpperCase()}
{/* Video Preview */} {processingMedia && ( )} {/* Logs Terminal */}
System Logs
{logsVisible && (
{logs.map((log, i) => (
{new Date().toLocaleTimeString()} {log}
))} {status === 'processing' && (
_
)}
)}
{/* Right Panel: Results Grid */}

Generated Shorts {results?.clips?.length > 0 && ( {results.clips.length} Clips )} {results?.cost_analysis && ( ${results.cost_analysis.total_cost.toFixed(5)} )}

{results && results.clips && results.clips.length > 0 ? (
{results.clips.map((clip, i) => ( handleClipPlay(time)} onPause={handleClipPause} /> ))}
) : ( status === 'processing' ? (

Waiting for clips...

) : status === 'error' ? (

Generation failed.

) : null )}
)}
{/* Missing API Key Modal */} {showKeyModal && (
setShowKeyModal(false)}>
e.stopPropagation()}>

Gemini API Key Required

You need a Google Gemini API key to use the Clip Generator. It's free and takes 30 seconds to get.

How to get your free key:

  1. Go to aistudio.google.com/app/apikey
  2. Sign in with your Google account
  3. Click "Create API Key"
  4. Copy the key and paste it below
{ if (e.key === 'Enter' && e.target.value.trim()) { setApiKey(e.target.value.trim()); setShowKeyModal(false); } }} /> {/* Upload-Post info */}

Optional: Auto-publish to social media

With an Upload-Post API key you can publish your clips directly to TikTok, Instagram Reels, and YouTube Shorts — or schedule them for later. Free tier available, no credit card needed.

  1. Register at app.upload-post.com
  2. Connect your TikTok, Instagram, or YouTube accounts
  3. Go to API Keys and generate one
  4. Paste it in Settings — done!
)}
); } export default App;