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 } from 'lucide-react'; import KeyInput from './components/KeyInput'; import MediaInput from './components/MediaInput'; import ResultCard from './components/ResultCard'; import ProcessingAnimation from './components/ProcessingAnimation'; 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) => ( ))}
)}
); }; // 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 ''; }); const [uploadUserId, setUploadUserId] = useState(() => localStorage.getItem('uploadUserId') || ''); const [userProfiles, setUserProfiles] = useState([]); // List of {username, connected: []} 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 // 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); }; 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 (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'); setLogs(prev => [...prev, "Error: " + data.error]); 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) => { 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); }; // --- UI Components --- const Sidebar = () => (
Logo
OpenShorts

Open Source

Free & Community Driven

); return (
{/* Background Gradients */}
{/* Top Header */}
{status !== 'idle' && ( )}
{userProfiles.length > 0 && ( )} {!apiKey && ( API Key Missing )}
{/* 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.

)} {/* 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 )}
)}
); } export default App;