Memeriksa sesi aman…

const BASE = window.location.origin; const modelHighlight=document.createElement('div');modelHighlight.className='model-highlight';modelHighlight.setAttribute('aria-label','Model generate gambar terbaru');modelHighlight.append('MODEL GENERATE GAMBAR · ');const modelName=document.createElement('strong');modelName.textContent='FLASH IMAGE TERBARU';modelHighlight.append(modelName);document.querySelector('.landing-actions')?.after(modelHighlight); const DASH_VIEWS = [ ['ringkasan','Ringkasan','card-ringkasan'],['gambar','Gambar','cardImage'],['gptimage','GPT Image','cardGptImage'],['analisis','Analisis','cardVision'],['chat','Chat','cardChat'],['audio','Audio','cardTTS'],['video','Omni Video','cardOmni'],['mcp','MCP','mcp'],['profil','Profil','profileView'],['pengguna','Pengguna','adminMcp'],['dokumentasi','Dokumentasi','docs'] ]; const navIcon = ''; // ─── Fitur yang diizinkan admin (user.features) ───────────────────────────── // Kosong / null = akses penuh. Dipakai untuk menyembunyikan menu & kartu yang // tidak dicentang admin, supaya console tidak menawarkan fitur yang ditolak server. const FITUR_VIEW = { gambar: ['imageGenerate', 'imageEdit'], gptimage: ['gptImage'], analisis: ['vision'], chat: ['chat'], audio: ['audio'], video: ['omniVideo', 'omniIngredients', 'videoWatermark', 'videoEdit'], }; function fiturAkunDiizinkan(fitur) { const f = authSession?.user?.features; if (!Array.isArray(f) || f.length === 0) return true; return f.includes(fitur); } function viewDiizinkan(id) { const butuh = FITUR_VIEW[id]; if (!butuh) return true; return butuh.some(fiturAkunDiizinkan); } function terapkanFiturAkun() { const kartu = { cardImage: ['imageGenerate', 'imageEdit'], cardGptImage: ['gptImage'], cardVision: ['vision'], cardChat: ['chat'], cardTTS: ['audio'], cardOmni: ['omniVideo', 'omniIngredients', 'videoWatermark', 'videoEdit'], }; Object.entries(kartu).forEach(([id, butuh]) => { const el = document.getElementById(id); if (el) el.style.display = butuh.some(fiturAkunDiizinkan) ? '' : 'none'; }); const punyaOmni = fiturAkunDiizinkan('omniVideo'); const punyaIng = fiturAkunDiizinkan('omniIngredients'); const punyaWm = fiturAkunDiizinkan('videoWatermark'); const punyaEdit = fiturAkunDiizinkan('videoEdit'); document.querySelectorAll('[data-omode]').forEach(b => { const m = b.dataset.omode; const ok = m === 'wm' ? punyaWm : m === 'edit' ? punyaEdit : m === 'ing' ? punyaIng : punyaOmni; b.style.display = ok ? '' : 'none'; }); const aktif = document.querySelector('[data-omode].active'); if (aktif && aktif.style.display === 'none') { const alt = [...document.querySelectorAll('[data-omode]')].find(b => b.style.display !== 'none'); if (alt && typeof omniSetMode === 'function') omniSetMode(alt.dataset.omode); } // Daftar tool MCP: tool yang fiturnya tidak dicentang tidak ditampilkan sama sekali. const daftarTool = document.querySelectorAll('.mcp-tools li[data-fitur]'); if (daftarTool.length) { let tampil = 0; daftarTool.forEach(li => { const ok = li.dataset.fitur.split(',').some(fiturAkunDiizinkan); li.style.display = ok ? '' : 'none'; if (ok) tampil++; }); const judul = document.getElementById('mcpToolCount'); if (judul) judul.textContent = `${tampil} Tool Tersedia`; } } function navigateView(id, updateHash = true) { if (!DASH_VIEWS.some(v => v[0] === id)) id = 'ringkasan'; if (!viewDiizinkan(id)) id = 'ringkasan'; if (authSession?.entitlement === 'profile-only' && !['profil','dokumentasi'].includes(id)) id = 'profil'; if (id === 'pengguna' && authSession?.role !== 'admin') id = 'ringkasan'; document.querySelectorAll('.card,.mcp-panel,.code-section').forEach(el => el.classList.remove('view-active')); document.querySelector('.hero').hidden = id !== 'ringkasan'; document.querySelector('.pool-bar').hidden = id !== 'ringkasan' || authSession?.role !== 'admin'; document.querySelector('.creds').hidden = id !== 'ringkasan'; document.querySelector('.simple-key').hidden = id !== 'ringkasan' || authSession?.role !== 'user'; if(id !== 'ringkasan') clearRawKey(); document.getElementById('userOnlineStatus').hidden = id !== 'ringkasan' || authSession?.role === 'admin'; document.getElementById('mcpContent').hidden = id === 'pengguna'; document.getElementById('adminMcp').hidden = id !== 'pengguna' || authSession?.role !== 'admin'; document.getElementById('profileView').hidden = id !== 'profil'; const targets = {gambar:'cardImage',gptimage:'cardGptImage',analisis:'cardVision',chat:'cardChat',audio:'cardTTS',video:'cardOmni',mcp:'mcpTitle',profil:'profileView',pengguna:'adminMcp',dokumentasi:'codeCurl'}; const target = targets[id] && document.getElementById(targets[id]); if (target) (target.closest('.card,.mcp-panel,.code-section') || target).classList.add('view-active'); document.querySelectorAll('[data-view]').forEach(b => { const active=b.dataset.view === id; b.classList.toggle('active', active); if(active) b.setAttribute('aria-current','page'); else b.removeAttribute('aria-current'); }); document.getElementById('currentViewTitle').textContent = DASH_VIEWS.find(v => v[0] === id)[1]; document.getElementById('moreTray').classList.remove('open'); if (id === 'pengguna') { document.getElementById('adminArea').hidden = false; document.getElementById('adminToggle').setAttribute('aria-expanded','true'); } if (id === 'profil') loadProfile(); if (updateHash) history.replaceState(null, '', '#' + id); } function buildNavigation() { document.getElementById('desktopNav').replaceChildren(); document.getElementById('mobileNav').replaceChildren(); document.getElementById('moreTray').replaceChildren(); const make = ([id,label]) => { const b=document.createElement('button'); b.type='button'; b.className='nav-btn'; b.dataset.view=id; b.innerHTML=navIcon+''+label+''; b.onclick=()=>navigateView(id); return b; }; const allowed=DASH_VIEWS.filter(v=>(authSession?.entitlement!=='profile-only'||['profil','dokumentasi'].includes(v[0]))&&(v[0]!=='pengguna'||authSession?.role==='admin')&&viewDiizinkan(v[0])); allowed.forEach(v=>document.getElementById('desktopNav').append(make(v))); allowed.slice(0,4).forEach(v=>document.getElementById('mobileNav').append(make(v))); const more=document.createElement('button'); more.type='button'; more.innerHTML=navIcon+'Lainnya'; more.onclick=()=>document.getElementById('moreTray').classList.toggle('open'); document.getElementById('mobileNav').append(more); allowed.slice(4).forEach(v=>document.getElementById('moreTray').append(make(v))); const hash=location.hash.slice(1); navigateView(hash==='adminMcp'?'pengguna':hash,false); } window.addEventListener('hashchange',()=>navigateView(location.hash.slice(1)==='adminMcp'?'pengguna':location.hash.slice(1),false)); const MCP_ENDPOINT = 'https://scgenconsole.azkazamdigital.com/mcp'; const MCP_CONFIG = JSON.stringify({ mcpServers: { cosmicAI: { url: MCP_ENDPOINT, headers: { Authorization: 'Bearer YOUR_MCP_KEY' } } } }, null, 2); let authSession = null; let rawKeyTimer=null; let trialActiveTimer=null; function clearRawKey(){if(rawKeyTimer)clearTimeout(rawKeyTimer);rawKeyTimer=null;document.getElementById('credKey').textContent='Dikelola aman oleh sesi dashboard';} function revealRawKey(key){clearRawKey();document.getElementById('credKey').textContent=key;rawKeyTimer=setTimeout(clearRawKey,60000)} function setApiKey() { document.getElementById('credKey').textContent = 'Dikelola aman oleh sesi dashboard'; } function showAuthScreen(name) { document.getElementById('authLoading').hidden=name!=='checking'; document.getElementById('loginScreen').hidden=name!=='login'; document.getElementById('trialScreen').hidden=name!=='trial'; document.getElementById('dashboardApp').hidden=name!=='dashboard'; } function clearTrialActiveTimer(){if(trialActiveTimer)clearInterval(trialActiveTimer);trialActiveTimer=null} function startTrialStatus(session){clearTrialActiveTimer();const user=session.user||{},end=user.expiresAt,isPaid=user.accountType==='paid';document.getElementById('trialStatusBox').hidden=!user.trialStartedAt&&!isPaid;document.getElementById('trialOriginalEnd').textContent=user.trialEndsAt?`Akhir trial awal: ${new Date(user.trialEndsAt).toLocaleString('id-ID')}`:'';const tick=()=>{const expired=end&&Date.parse(end)<=Date.now();document.getElementById('trialStatusLabel').textContent=isPaid?(expired?'Masa aktif habis':'Masa aktif aktif'):(expired?'Trial Habis':'Trial Aktif');document.getElementById('trialLiveCountdown').textContent=end?durationId(Date.parse(end)-Date.now()):''};tick();if(end)trialActiveTimer=setInterval(tick,1000)} function showDashboard(session, credential='') { clearTrialState(); document.body.style.overflow=''; authSession=session; setApiKey(); startTrialStatus(session); document.getElementById('accountEmail').textContent=session.user?.email||''; document.getElementById('accountRole').textContent=session.role; document.getElementById('keyNotice').classList.remove('show'); document.querySelector('.simple-key').hidden=session.role==='admin'; document.getElementById('userOnlineStatus').hidden=session.role==='admin'; showAuthScreen('dashboard'); buildNavigation(); terapkanFiturAkun(); if(session.entitlement==='profile-only')navigateView('profil'); init(); if(session.role==='admin'){setAdminState(true); loadUsers().catch(e=>adminMessage(e.message));} } function returnToLogin() { clearRawKey(); authSession=null; history.replaceState(null,'',location.pathname); showAuthScreen('login'); } function durationId(ms) { if (ms == null) return 'Tidak dibatasi'; if (ms <= 0) return 'Masa aktif telah berakhir'; if (ms < 86400000) return `${Math.ceil(ms/3600000)} jam tersisa`; return `${Math.ceil(ms/86400000)} hari tersisa`; } async function loadProfile() { clearRawKey(); try { const r=await fetch(`${BASE}/profile`, { credentials:'include', headers:{Accept:'application/json'} }); if(r.status===401){returnToLogin();return} const data=await r.json().catch(()=>null); if(!r.ok)throw new Error(errorMessage(r.status,data)); const user=data.user||{},isUser=(data.role||authSession?.role)==='user'; if(authSession&&user.features!==undefined)authSession.user={...(authSession.user||{}),...user}; terapkanFiturAkun(); document.getElementById('profileSummary').textContent=`Email: ${user.email||'-'} · Label: ${user.label||'-'} · Role: ${data.role||authSession?.role||'-'} · Status: ${user.active===false?'Nonaktif':'Aktif'}`; const accountLabel=user.accountType==='paid'?'Akun penuh':user.accountType==='trial'?'Trial':'Dikelola admin'; document.getElementById('profileAccountType').textContent=`Jenis akun: ${accountLabel} · Status: ${user.active===false?'Nonaktif':'Aktif'}`; document.getElementById('profileTrialDates').textContent=user.trialStartedAt?`Trial: ${new Date(user.trialStartedAt).toLocaleString('id-ID')} – ${new Date(user.trialEndsAt||user.expiresAt).toLocaleString('id-ID')}`:'Trial: -'; document.getElementById('profileCurrentExpiry').textContent=`Kedaluwarsa saat ini: ${user.expiresAt?new Date(user.expiresAt).toLocaleString('id-ID'):'Tidak dibatasi'}`; document.getElementById('profileOnlyNotice').hidden=(data.entitlement||authSession?.entitlement)!=='profile-only'; document.getElementById('userProfileFields').hidden=!isUser; document.getElementById('passwordForm').hidden=!isUser; document.getElementById('adminProfileNote').hidden=isUser; if(isUser){document.getElementById('profileExpiry').textContent=`Kedaluwarsa: ${user.expiresAt?new Date(user.expiresAt).toLocaleString('id-ID'):'Tidak dibatasi'} · ${durationId(data.remainingMs)}`;document.getElementById('profileKeyStatus').textContent=`API key: ${data.hasApiKey?'Ada':'Belum ada'}${data.keyCreatedAt?' · Dibuat '+new Date(data.keyCreatedAt).toLocaleString('id-ID'):''} · Batas ${data.rpmLimit??user.rpmLimit??60} RPM · Maks. ${data.workerLimit??user.workerLimit??5} request aktif`;renderMyKey(data);} }catch(e){document.getElementById('profileSummary').textContent=e.message} } function renderMyKey(data){const has=Boolean(data.hasApiKey),rpm=data.rpmLimit??data.user?.rpmLimit??60,workers=data.workerLimit??data.user?.workerLimit??5;document.getElementById('myApiKeyMeta').textContent=has?`Key aktif${data.keyId?' · ID '+data.keyId:''}${data.keyCreatedAt?' · Dibuat '+new Date(data.keyCreatedAt).toLocaleString('id-ID'):''} · ${rpm} RPM · ${workers} worker`:`Belum memiliki API key · Batas akun ${rpm} RPM · ${workers} worker`;document.getElementById('generateKeyBtn').querySelector('span').textContent=has?'Ganti API Key':'Generate API Key';document.getElementById('revokeKeyBtn').hidden=!has;} async function refreshPaidSession(){try{const response=await fetch(`${BASE}/auth/session`,{credentials:'include',headers:{Accept:'application/json'}}),data=await response.json();if(response.ok){authSession=data;startTrialStatus(data);buildNavigation();terapkanFiturAkun()}}catch{}} document.getElementById('passwordForm').addEventListener('submit',async event=>{event.preventDefault();const currentPassword=document.getElementById('currentPassword').value,newPassword=document.getElementById('newPassword').value,confirmPassword=document.getElementById('confirmPassword').value,msg=document.getElementById('profileMessage');if(newPassword.length<10){msg.textContent='Password baru minimal 10 karakter.';msg.className='admin-message show error';return}if(newPassword!==confirmPassword){msg.textContent='Konfirmasi password tidak cocok.';msg.className='admin-message show error';return}try{const r=await fetch(`${BASE}/profile/password`,{method:'POST',credentials:'include',headers:{'Content-Type':'application/json','Accept':'application/json'},body:JSON.stringify({ currentPassword, newPassword, confirmPassword })});const d=await r.json().catch(()=>null);if(r.status===401){msg.textContent='Password saat ini salah.';msg.className='admin-message show error';return}if(!r.ok)throw new Error(errorMessage(r.status,d));event.target.reset();msg.textContent='Password berhasil diperbarui. Sesi aman telah diganti.';msg.className='admin-message show info';}catch(e){msg.textContent=e.message;msg.className='admin-message show error'}}); let trialFlow={email:'',password:''},trialResendTimer=null; function clearTrialState(){if(trialResendTimer)clearInterval(trialResendTimer);trialResendTimer=null;trialFlow={email:'',password:''};['trialPassword','trialConfirmPassword','trialOtp'].forEach(id=>document.getElementById(id).value='');document.getElementById('trialSignupForm').hidden=false;document.getElementById('trialOtpForm').hidden=true;document.getElementById('trialError').textContent='';} function maskEmail(email){const [name,domain]=email.split('@');return `${name.slice(0,2)}***@${domain}`} function startResendCountdown(){if(trialResendTimer)clearInterval(trialResendTimer);let left=60;const btn=document.getElementById('trialResend'),out=document.getElementById('trialCountdown');btn.disabled=true;out.textContent=`Kirim ulang dalam ${left} detik`;trialResendTimer=setInterval(()=>{left--;out.textContent=left?`Kirim ulang dalam ${left} detik`:'';if(!left){clearInterval(trialResendTimer);trialResendTimer=null;btn.disabled=false}},1000)} async function requestTrial(){const password=trialFlow.password;const r=await fetch(`${BASE}/auth/trial/request`,{method:'POST',credentials:'include',headers:{'Content-Type':'application/json','Accept':'application/json'},body:JSON.stringify({email:trialFlow.email,password,confirmPassword:password})});if(r.status!==202)throw new Error('Permintaan trial belum dapat diproses.');document.getElementById('trialMaskedEmail').textContent=maskEmail(trialFlow.email);document.getElementById('trialSignupForm').hidden=true;document.getElementById('trialOtpForm').hidden=false;startResendCountdown()} async function checkSession() { try { const r=await fetch(`${BASE}/auth/session`,{credentials:'include',headers:{Accept:'application/json'}}); const d=await r.json().catch(()=>null); if(r.ok&&d?.authenticated) return showDashboard(d); } catch {} showAuthScreen('login'); } function openLogin(){clearTrialState();document.getElementById('loginError').textContent='';showAuthScreen('login');document.getElementById('loginEmail').focus()} function openTrial(){clearTrialState();showAuthScreen('trial');document.getElementById('trialEmail').focus()} [['openLogin',openLogin],['heroLogin',openLogin],['openTrial',openTrial]].forEach(([id,fn])=>{const el=document.getElementById(id); if(el) el.onclick=fn;});document.getElementById('loginTrial').onclick=openTrial;document.getElementById('trialLoginSwitch').onclick=openLogin;document.getElementById('trialClose').onclick=()=>{clearTrialState();showAuthScreen('login')};document.getElementById('loginBack').onclick=()=>{clearTrialState();showAuthScreen('login')}; document.getElementById('trialSignupForm').addEventListener('submit',async e=>{e.preventDefault();const email=document.getElementById('trialEmail').value.trim(),password=document.getElementById('trialPassword').value,confirm=document.getElementById('trialConfirmPassword').value,error=document.getElementById('trialError');error.textContent='';if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)){error.textContent='Email tidak valid.';return}if(password.length<10||password.length>1024){error.textContent='Password harus 10–1024 karakter.';return}if(password!==confirm){error.textContent='Konfirmasi password tidak cocok.';return}trialFlow={email,password};try{await requestTrial()}catch(err){error.textContent=err.message}}); document.getElementById('trialOtpForm').addEventListener('submit',async e=>{e.preventDefault();const otp=document.getElementById('trialOtp').value.trim(),error=document.getElementById('trialError');if(!/^\d{6}$/.test(otp)){error.textContent='OTP harus tepat enam digit.';return}try{const r=await fetch(`${BASE}/auth/trial/verify`,{method:'POST',credentials:'include',headers:{'Content-Type':'application/json','Accept':'application/json'},body:JSON.stringify({email:trialFlow.email,otp})});const d=await r.json().catch(()=>null);if(!r.ok||!d?.authenticated)throw new Error('Kode OTP tidak valid atau kedaluwarsa.');showDashboard(d)}catch(err){document.getElementById('trialOtp').value='';error.textContent=err.message}}); document.getElementById('trialResend').onclick=async()=>{try{await requestTrial()}catch(err){document.getElementById('trialError').textContent=err.message}};window.addEventListener('pagehide',()=>{clearTrialState()}); document.getElementById('dashboardLoginForm').addEventListener('submit',async e=>{e.preventDefault();const btn=document.getElementById('loginSubmit'),credential=document.getElementById('loginCredential').value;setLoading(btn,true);document.getElementById('loginError').textContent='';try{const r=await fetch(`${BASE}/auth/login`,{method:'POST',credentials:'include',headers:{'Content-Type':'application/json','Accept':'application/json'},body:JSON.stringify({email:document.getElementById('loginEmail').value.trim(),credential})});const d=await r.json().catch(()=>null);if(!r.ok||!d?.authenticated)throw new Error('Email atau kredensial tidak valid.');document.getElementById('loginCredential').value='';showDashboard(d,d.role==='user'?credential:'');}catch(err){document.getElementById('loginCredential').value='';document.getElementById('loginError').textContent=err.message;}finally{setLoading(btn,false)}}); document.getElementById('accountLogout').onclick=async()=>{try{await fetch(`${BASE}/auth/logout`,{method:'POST',credentials:'include'})}finally{clearRawKey();authSession=null;setApiKey();history.replaceState(null,'',location.pathname);showAuthScreen('login')}}; async function init() { document.getElementById('credUrl').textContent = BASE; setApiKey(); await checkStatus(); if (authSession?.role === 'admin') await loadPoolInfo(); await checkMcpStatus(); } function requireApiKey() { if (!authSession) { showAuthScreen('login'); return false; } return true; } async function checkMcpStatus() { const dot = document.getElementById('mcpStatusDot'); const text = document.getElementById('mcpStatusText'); dot.className = 'status-dot loading'; text.textContent = 'Memeriksa status…'; try { const response = await fetch(`${BASE}/health/mcp`, { headers: { Accept: 'application/json' } }); if (!response.ok) throw new Error('HTTP ' + response.status); await response.json(); dot.className = 'status-dot'; text.textContent = 'MCP online'; } catch { dot.className = 'status-dot offline'; text.textContent = 'MCP offline / tidak terjangkau'; } } document.getElementById('copyMcpEndpoint').addEventListener('click', () => copyText(MCP_ENDPOINT)); document.getElementById('copyMcpConfig').addEventListener('click', () => copyText(MCP_CONFIG)); // ─── MCP admin ─────────────────────────── let adminBusy = false; const adminArea = document.getElementById('adminArea'); const adminLoginForm = document.getElementById('adminLoginForm'); const adminDashboard = document.getElementById('adminDashboard'); function clearSecret() { document.getElementById('secretKey').textContent = ''; document.getElementById('secretResult').classList.remove('show'); } function adminMessage(text, type = 'error') { const el = document.getElementById('adminMessage'); el.textContent = text || ''; el.className = `admin-message${text ? ` show ${type}` : ''}`; } function setAdminState(loggedIn) { adminLoginForm.hidden = loggedIn; adminDashboard.hidden = !loggedIn; document.getElementById('adminToggle').querySelector('span').textContent = loggedIn ? 'Panel Admin' : 'Login Admin'; if (!loggedIn) { document.getElementById('adminUsers').replaceChildren(); renderUsageStats(); } } function expireAdmin(message = 'Sesi admin berakhir. Silakan login kembali.') { clearSecret(); setAdminState(false); adminMessage(message); } function errorMessage(status, data) { if (status === 400) return 'Data tidak valid. Periksa kembali semua isian.'; if (status === 401) return 'Sesi tidak sah atau telah berakhir.'; if (status === 429) return 'Terlalu banyak permintaan. Tunggu sebentar lalu coba lagi.'; if (status >= 500) return 'Layanan admin sedang bermasalah. Coba lagi nanti.'; return typeof data?.error === 'string' ? data.error : 'Permintaan gagal. Silakan coba lagi.'; } async function adminFetch(path, options = {}) { const headers = { Accept: 'application/json', ...(options.body ? { 'Content-Type': 'application/json' } : {}) }; let response; try { response = await fetch(`${BASE}${path}`, { ...options, credentials: 'include', headers }); } catch { throw new Error('Tidak dapat terhubung ke layanan admin.'); } let data = null; if (response.status !== 204) { try { data = await response.json(); } catch {} } if (!response.ok) { if (response.status === 401) expireAdmin(); throw new Error(errorMessage(response.status, data)); } return data; } function toExpiry(date) { return date ? new Date(`${date}T23:59:59.999`).toISOString() : null; } function dateInput(iso) { return iso ? iso.slice(0, 10) : ''; } function field(label, input) { const wrap = document.createElement('div'); wrap.className = 'field'; const lab = document.createElement('label'); lab.textContent = label; lab.htmlFor = input.id; wrap.append(lab, input); return wrap; } function button(label, kind, action) { const b = document.createElement('button'); b.type = 'button'; b.className = `btn secondary${kind ? ` ${kind}` : ''}`; const s = document.createElement('span'); s.textContent = label; b.append(s); b.addEventListener('click', action); return b; } async function runAdminAction(action) { if (adminBusy) return; adminBusy = true; clearSecret(); adminMessage('Memproses…', 'info'); try { await action(); } catch (e) { adminMessage(e.message); } finally { adminBusy = false; } } function showSecret(key, email='', title='PASSWORD AWAL') { if (!key) return; document.getElementById('secretTitle').textContent = `${title} hanya ditampilkan satu kali`; document.getElementById('secretEmail').textContent = email ? `EMAIL: ${email}` : ''; document.getElementById('secretKey').textContent = key; document.getElementById('secretResult').classList.add('show'); document.getElementById('secretResult').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } function usageNumber(value) { return new Intl.NumberFormat('id-ID').format(Number(value) || 0); } function renderUsageStats(stats = {}) { const totals = stats.totals || {}; const values = { usageOverall: totals.overall, usageImages: totals.images, usageImageGenerate: totals.imageGenerate, usageImageEdit: totals.imageEdit, usageVision: totals.vision, usageChat: totals.chat, usageAudio: totals.audio }; Object.entries(values).forEach(([id, value]) => { document.getElementById(id).textContent = usageNumber(value); }); } function renderUsers(users, usageUsers = []) { const list = document.getElementById('adminUsers'); list.replaceChildren(); if (!users.length) { const p = document.createElement('p'); p.className = 'user-meta'; p.textContent = 'Belum ada pengguna.'; list.append(p); return; } const usageByUser = new Map(usageUsers.map(item => [item.userId, item])); users.forEach(user => { const card = document.createElement('article'); card.className = 'user-card'; const summary = document.createElement('div'); summary.className = 'user-summary'; const identity = document.createElement('div'); const email = document.createElement('div'); email.className = 'user-email'; email.textContent = user.email; const label = document.createElement('div'); label.className = 'user-meta'; label.textContent = user.label || 'Tanpa label'; identity.append(email, label); const usage = usageByUser.get(user.id) || {}; const meta = document.createElement('div'); meta.className = 'user-meta'; meta.textContent = `Kedaluwarsa: ${user.expiresAt ? new Date(user.expiresAt).toLocaleDateString('id-ID') : 'Tidak dibatasi'} · Maks. sesi: ${user.maxSessions} · ${user.rpmLimit || 60} RPM · ${user.workerLimit || 5} worker · Key ID: ${user.keyId || 'Belum ada'}`; const usageMeta = document.createElement('div'); usageMeta.className = 'user-meta'; usageMeta.textContent = `Pemakaian: ${usageNumber(usage.overall)} total · ${usageNumber(usage.images)} request gambar · ${usageNumber(usage.vision)} analisis · ${usageNumber(usage.chat)} chat · ${usageNumber(usage.audio)} audio · ${usageNumber(usage.omniVideo)} video`; // ==== RINGKASAN KUOTA VIDEO OMNI (4 Nov'26) ==== // Batas 0 = tanpa batas. Angka di kiri = jumlah video yang sudah dibuat. const batasTeks = nilai => (Number.isInteger(nilai) && nilai > 0) ? usageNumber(nilai) : '∞'; const videoMeta = document.createElement('div'); videoMeta.className = 'user-meta'; videoMeta.textContent = `Video Omni — hari ini: ${usageNumber(usage.videoToday)} / ${batasTeks(user.videoDailyLimit)} · minggu ini: ${usageNumber(usage.videoWeek)} / ${batasTeks(user.videoWeeklyLimit)}`; const gambarMeta = document.createElement('div'); gambarMeta.className = 'user-meta'; gambarMeta.textContent = `Gambar — hari ini: ${usageNumber(usage.imageToday)} / ${batasTeks(user.imageDailyLimit)} · minggu ini: ${usageNumber(usage.imageWeek)}`; identity.append(usageMeta, videoMeta, gambarMeta); const badge = document.createElement('span'); const isPaid=user.accountType==='paid',isTrial=user.accountType==='trial',accountEnd=isPaid?user.expiresAt:user.trialEndsAt,accountExpired=accountEnd&&Date.parse(accountEnd)<=Date.now();const badgeLabel=isPaid?(accountExpired?'Masa aktif habis':'Aktif'):isTrial?(accountExpired?'Trial Habis':'Trial Aktif'):'Akun Aktif';badge.className=`badge${isPaid&&user.active&&!accountExpired?' paid':''}${user.active?'':' off'}`;badge.textContent=user.active?badgeLabel:'NONAKTIF';summary.append(identity, meta, badge); const edit = document.createElement('div'); edit.className = 'user-edit'; const labelInput = document.createElement('input'); labelInput.className = 'input'; labelInput.id = `label-${user.id}`; labelInput.maxLength = 200; labelInput.value = user.label || ''; const expiryInput = document.createElement('input'); expiryInput.className = 'input'; expiryInput.id = `expiry-${user.id}`; expiryInput.type = 'date'; expiryInput.value = dateInput(user.expiresAt); const sessionsInput = document.createElement('input'); sessionsInput.className = 'input'; sessionsInput.id = `sessions-${user.id}`; sessionsInput.type = 'number'; sessionsInput.min = '1'; sessionsInput.max = '1000'; sessionsInput.value = user.maxSessions; const rpmInput = document.createElement('input'); rpmInput.className = 'input'; rpmInput.id = `rpm-${user.id}`; rpmInput.type = 'number'; rpmInput.min = '1'; rpmInput.max = '600'; rpmInput.value = user.rpmLimit || 20; const workerInput = document.createElement('input'); workerInput.className = 'input'; workerInput.id = `workers-${user.id}`; workerInput.type = 'number'; workerInput.min = '1'; workerInput.max = '20'; workerInput.value = user.workerLimit || 5; // ==== BATAS VIDEO OMNI PER PENGGUNA (4 Nov'26) ==== // 0 = tanpa batas. Harian maksimal 10.000, mingguan maksimal 70.000. const videoDayInput = document.createElement('input'); videoDayInput.className = 'input'; videoDayInput.id = `videoday-${user.id}`; videoDayInput.type = 'number'; videoDayInput.min = '0'; videoDayInput.max = '10000'; videoDayInput.placeholder = '0 = tanpa batas'; videoDayInput.value = Number.isInteger(user.videoDailyLimit) ? user.videoDailyLimit : 10000; const videoWeekInput = document.createElement('input'); videoWeekInput.className = 'input'; videoWeekInput.id = `videoweek-${user.id}`; videoWeekInput.type = 'number'; videoWeekInput.min = '0'; videoWeekInput.max = '70000'; videoWeekInput.placeholder = '0 = tanpa batas'; videoWeekInput.value = Number.isInteger(user.videoWeeklyLimit) ? user.videoWeeklyLimit : 70000; // ==== BATAS GAMBAR PER PENGGUNA (6 Nov'26) ==== 0 = tanpa batas, default 5.000/hari. const imageDayInput = document.createElement('input'); imageDayInput.className = 'input'; imageDayInput.id = `imageday-${user.id}`; imageDayInput.type = 'number'; imageDayInput.min = '0'; imageDayInput.max = '100000'; imageDayInput.placeholder = '0 = tanpa batas'; imageDayInput.value = Number.isInteger(user.imageDailyLimit) ? user.imageDailyLimit : 5000; const featWrap = document.createElement('div'); featWrap.className = 'field'; featWrap.style.gridColumn = '1/-1'; const featTitle = document.createElement('label'); featTitle.textContent = 'Fitur yang diizinkan (kosong = semua)'; const featBox = document.createElement('div'); featBox.style.cssText = 'display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:.15rem 1rem;margin-top:.3rem'; featBox.innerHTML = FITUR_LIST.map(([nilai, teks]) => { const on = !Array.isArray(user.features) || user.features.includes(nilai); return ``; }).join(''); featWrap.append(featTitle, featBox); const featsInput = () => { const dipilih = [...featBox.querySelectorAll('input[type=checkbox]')].filter(c => c.checked).map(c => c.value); return dipilih.length === FITUR_LIST.length ? null : dipilih; // semua = akses penuh }; const save = button('Simpan edit', '', () => runAdminAction(async () => { const maxSessions = Number(sessionsInput.value), rpmLimit = Number(rpmInput.value), workerLimit = Number(workerInput.value), videoDailyLimit = Number(videoDayInput.value), videoWeeklyLimit = Number(videoWeekInput.value); const imageDailyLimit = Number(imageDayInput.value); if (!Number.isInteger(maxSessions) || maxSessions < 1 || maxSessions > 1000) throw new Error('Maksimum sesi harus 1–1000.'); if (!Number.isInteger(rpmLimit) || rpmLimit < 1 || rpmLimit > 600) throw new Error('Batas RPM harus 1–600.'); if (!Number.isInteger(workerLimit) || workerLimit < 1 || workerLimit > 10000) throw new Error('Worker harus 1–10000.'); if (!Number.isInteger(videoDailyLimit) || videoDailyLimit < 0 || videoDailyLimit > 10000) throw new Error('Batas video per hari harus 0–10000 (0 = tanpa batas).'); if (!Number.isInteger(videoWeeklyLimit) || videoWeeklyLimit < 0 || videoWeeklyLimit > 70000) throw new Error('Batas video per minggu harus 0–70000 (0 = tanpa batas).'); if (!Number.isInteger(imageDailyLimit) || imageDailyLimit < 0 || imageDailyLimit > 100000) throw new Error('Batas gambar per hari harus 0–100000 (0 = tanpa batas).'); await adminFetch(`/admin/users/${encodeURIComponent(user.id)}`, { method: 'PATCH', body: JSON.stringify({ label: labelInput.value.trim(), expiresAt: toExpiry(expiryInput.value), maxSessions, rpmLimit, workerLimit, videoDailyLimit, videoWeeklyLimit, imageDailyLimit, features: featsInput() }) }); adminMessage('Perubahan pengguna disimpan.', 'info'); await loadUsers(); })); edit.append(field('Label / nama', labelInput), field('Kedaluwarsa', expiryInput), field('Maks. sesi', sessionsInput), field('Batas RPM', rpmInput), field('Worker', workerInput), field('Batas video / hari', videoDayInput), field('Batas video / minggu', videoWeekInput), field('Batas gambar / hari', imageDayInput), featWrap, save); const actions = document.createElement('div'); actions.className = 'user-actions'; actions.append(button(user.active ? 'Nonaktifkan akses' : 'Aktifkan akses', user.active ? 'danger' : '', () => { if (user.active && !confirm(`Nonaktifkan akses untuk ${user.email}?`)) return; runAdminAction(async () => { await adminFetch(`/admin/users/${encodeURIComponent(user.id)}`, { method: 'PATCH', body: JSON.stringify({ active: !user.active }) }); adminMessage(user.active ? 'Pengguna dinonaktifkan.' : 'Pengguna diaktifkan.', 'info'); await loadUsers(); }); }), button('Reset Password', '', () => { if (!confirm(`Reset password ${user.email}?`)) return; runAdminAction(async () => { const data=await adminFetch(`/admin/users/${encodeURIComponent(user.id)}/reset-password`,{method:'POST'});await loadUsers();showSecret(data.password,user.email,'PASSWORD BARU'); }); }), ...(user.keyId?[button('Cabut API Key','danger',()=>{if(!confirm(`Cabut API key ${user.email}?`))return;runAdminAction(async()=>{await adminFetch(`/admin/users/${encodeURIComponent(user.id)}/api-key`,{method:'DELETE'});adminMessage('API key dicabut.','info');await loadUsers();});})]:[]), button('Hapus Pengguna', 'danger', () => { const typed=prompt(`Ketik email ${user.email} untuk menghapus permanen:`); if(typed!==user.email||!confirm(`Hapus permanen ${user.email}?`))return;runAdminAction(async()=>{await adminFetch(`/admin/users/${encodeURIComponent(user.id)}`,{method:'DELETE'});adminMessage('Pengguna telah dihapus permanen.','info');await loadUsers();}); })); card.append(summary, edit, actions); list.append(card); }); } async function loadUsers() { const [data, stats] = await Promise.all([adminFetch('/admin/users'), adminFetch('/admin/stats')]); renderUsageStats(stats); renderUsers(Array.isArray(data?.users) ? data.users : [], Array.isArray(stats?.users) ? stats.users : []); } document.getElementById('adminToggle').addEventListener('click', () => { const opening = adminArea.hidden; adminArea.hidden = !opening; document.getElementById('adminToggle').setAttribute('aria-expanded', String(opening)); clearSecret(); if (opening && authSession?.role === 'admin') runAdminAction(async () => { setAdminState(true); await loadUsers(); adminMessage('Sesi admin aktif.', 'info'); }); }); adminLoginForm.addEventListener('submit', event => { event.preventDefault(); openLogin(); }); // ==== FITUR PER-USER (20 Okt'26) ==== // Daftar HARUS sama dengan FEATURES di mcp/lib/tools.js & VALID_FEATURES di admin.js. const FITUR_LIST = [ ['chat', 'AI Chat (teks)'], ['vision', 'Analisa Gambar'], ['imageGenerate', 'Generate Gambar'], ['imageEdit', 'Edit Gambar'], ['gptImage', 'Generate Gambar GPT'], ['audio', 'Text to Speech / Audio'], ['omniVideo', 'Video AI (Teks/Gambar → Video)'], ['omniIngredients', 'Video Ingredients (Frame to Video, 1–3 bahan)'], ['videoWatermark', 'Hapus Watermark Video'], ['videoEdit', 'Edit Video AI'], ['info', 'Info sistem (status layanan)'] ]; // Kosong = akses penuh (semua fitur). Bukan kosong = hanya fitur itu. function bacaFitur() { const kotak = document.getElementById('userFeatures'); if (!kotak) return undefined; const dipilih = [...kotak.querySelectorAll('input[type=checkbox]')].filter(c => c.checked).map(c => c.value); return dipilih.length === FITUR_LIST.length ? undefined : dipilih; // semua dicentang = akses penuh } function setFitur(daftar) { const kotak = document.getElementById('userFeatures'); if (!kotak) return; const aktif = Array.isArray(daftar) ? daftar : null; // null = semua kotak.querySelectorAll('input[type=checkbox]').forEach(c => { c.checked = aktif === null || aktif.includes(c.value); }); } (function initFitur() { const kotak = document.getElementById('userFeatures'); if (!kotak) return; kotak.innerHTML = FITUR_LIST.map(([nilai, teks]) => `` ).join(''); kotak.style.cssText = 'display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:.15rem 1rem'; document.getElementById('featAll')?.addEventListener('click', () => setFitur(null)); document.getElementById('featNone')?.addEventListener('click', () => setFitur([])); })(); document.getElementById('userForm').addEventListener('submit', event => { event.preventDefault(); runAdminAction(async () => { const email = document.getElementById('userEmail').value.trim(); const maxSessions = Number(document.getElementById('userMaxSessions').value); const rpmLimit = Number(document.getElementById('userRpmLimit').value); const workerLimit = Number(document.getElementById('userWorkerLimit').value); const videoDailyLimit = Number(document.getElementById('userVideoDaily').value); const videoWeeklyLimit = Number(document.getElementById('userVideoWeekly').value); const imageDailyLimit = Number(document.getElementById('userImageDaily').value); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) throw new Error('Masukkan email pengguna yang valid.'); if (!Number.isInteger(maxSessions) || maxSessions < 1 || maxSessions > 1000) throw new Error('Maksimum sesi harus 1–1000.'); if (!Number.isInteger(rpmLimit) || rpmLimit < 1 || rpmLimit > 600) throw new Error('Batas RPM harus 1–600.'); if (!Number.isInteger(workerLimit) || workerLimit < 1 || workerLimit > 10000) throw new Error('Worker harus 1–10000.'); if (!Number.isInteger(videoDailyLimit) || videoDailyLimit < 0 || videoDailyLimit > 10000) throw new Error('Batas video per hari harus 0–10000 (0 = tanpa batas).'); if (!Number.isInteger(videoWeeklyLimit) || videoWeeklyLimit < 0 || videoWeeklyLimit > 70000) throw new Error('Batas video per minggu harus 0–70000 (0 = tanpa batas).'); if (!Number.isInteger(imageDailyLimit) || imageDailyLimit < 0 || imageDailyLimit > 100000) throw new Error('Batas gambar per hari harus 0–100000 (0 = tanpa batas).'); const payload = { email, label: document.getElementById('userLabel').value.trim(), expiresAt: toExpiry(document.getElementById('userExpiry').value), maxSessions, rpmLimit, workerLimit, videoDailyLimit, videoWeeklyLimit, imageDailyLimit, features: bacaFitur(), active: document.getElementById('userActive').checked }; const data = await adminFetch('/admin/users', { method: 'POST', body: JSON.stringify(payload) }); event.target.reset(); document.getElementById('userMaxSessions').value = '1'; document.getElementById('userRpmLimit').value = '60'; document.getElementById('userWorkerLimit').value = '5'; document.getElementById('userVideoDaily').value = '10000'; document.getElementById('userVideoWeekly').value = '70000'; document.getElementById('userImageDaily').value = '5000'; document.getElementById('userActive').checked = true; adminMessage(data.password ? 'Pengguna dibuat. Simpan password awal sekarang.' : 'Data pengguna diperbarui.', 'info'); await loadUsers(); showSecret(data.password,data.user?.email||email,'PASSWORD AWAL'); }); }); document.getElementById('copySecret').addEventListener('click', () => { const secret = document.getElementById('secretKey').textContent; if (secret) navigator.clipboard.writeText(secret).then(() => showToast('Kredensial disalin')).catch(() => showToast('Gagal menyalin kredensial')); }); document.getElementById('adminLogout').addEventListener('click', () => document.getElementById('accountLogout').click()); window.addEventListener('hashchange', clearSecret); setAdminState(false); async function generateSimpleKey() { const btn = document.getElementById('generateKeyBtn'); if (btn.textContent.includes('Ganti') && !confirm('Mengganti API key akan langsung menonaktifkan key lama. Lanjutkan?')) return; let keyState = null; setLoading(btn, true); try { const r = await fetch(`${BASE}/profile/api-key`, { method: 'POST', credentials: 'include', headers:{Accept:'application/json'} }); const data = await r.json().catch(()=>null); if(r.status===401){returnToLogin();return} if (!r.ok || !data?.key) throw new Error(data?.error || 'Gagal membuat API key'); keyState = {hasApiKey:true,keyId:data.keyId,keyCreatedAt:data.createdAt,rpmLimit:data.rpmLimit,workerLimit:data.workerLimit}; renderMyKey(keyState); revealRawKey(data.key); showToast('API key dibuat. Salin sekarang; key hanya ditampilkan satu kali.'); } catch (e) { showToast(e.message); } finally { setLoading(btn, false); if(keyState) renderMyKey(keyState); } } async function revokeSimpleKey(){if(!confirm('Cabut API key aktif? Key segera tidak berlaku.'))return;try{const r=await fetch(`${BASE}/profile/api-key`, { method:'DELETE', credentials:'include', headers:{Accept:'application/json'} });if(r.status===401){returnToLogin();return}if(!r.ok)throw new Error('Gagal mencabut API key');clearRawKey();document.getElementById('credKey').textContent='Belum dibuat';renderMyKey({hasApiKey:false});showToast('API key berhasil dicabut.');}catch(e){showToast(e.message)}} function copyCurrentKey() { const key=document.getElementById('credKey').textContent.trim();if(!key.startsWith('cosmic-mcp-')){showToast('Secret API key hanya tersedia sesaat setelah generate.');return}navigator.clipboard.writeText(key).then(()=>showToast('API key disalin')).catch(()=>showToast('Gagal menyalin')); } async function checkStatus() { const dot = document.getElementById('statusDot'); const txt = document.getElementById('statusText'); const topDot = document.getElementById('topStatusDot'); const topTxt = document.getElementById('topStatusText'); try { const r = await fetch(`${BASE}/api/health`); if (!r.ok) throw new Error(); const health = await r.json(); if (health.tokensReady) { dot.className = 'status-dot'; txt.textContent = '● Online — Token Valid'; txt.style.color = 'var(--success)'; if(topDot)topDot.className = 'status-dot'; if(topTxt)topTxt.textContent = 'GEN / OPERASIONAL'; } else { dot.className = 'status-dot loading'; txt.textContent = '● Server Online — Token Belum Ada'; txt.style.color = 'var(--warn)'; if(topDot)topDot.className = 'status-dot loading'; if(topTxt)topTxt.textContent = 'TOKEN BELUM SIAP'; } } catch { dot.className = 'status-dot offline'; txt.textContent = '● Server Offline'; txt.style.color = 'var(--error)'; if(topDot)topDot.className = 'status-dot offline'; if(topTxt)topTxt.textContent = 'GEN / OFFLINE'; } } async function loadPoolInfo() { try { const r = await fetch(`${BASE}/api/pool/detail`, { credentials: 'include' }); if (!r.ok) return; const pool = await r.json(); document.getElementById('poolBar').style.display = 'flex'; document.getElementById('poolTotal').textContent = pool.total; document.getElementById('poolActive').textContent = pool.active; document.getElementById('poolMode').textContent = pool.rotationMode; document.getElementById('poolLabel').textContent = pool.currentLabel; document.getElementById('poolCaptured').textContent = pool.capturedAgo; } catch {} } setInterval(() => { checkStatus(); if (authSession?.role === 'admin') loadPoolInfo(); checkMcpStatus(); }, 30000); // ─── Helpers ──────────────────────────── function setLoading(btn, loading) { const span = btn.querySelector('span'); if (loading) { btn.disabled = true; btn._origText = span.innerHTML; span.innerHTML = '
Working…'; } else { btn.disabled = false; if (btn._origText) span.innerHTML = btn._origText; } } function showResult(id) { document.getElementById(id).classList.add('show'); } function showError(id, msg) { document.getElementById(id).classList.add('show'); const body = document.getElementById(id + 'Body'); body.replaceChildren(); const error = document.createElement('div'); error.className = 'result-error'; error.textContent = msg; body.append(error); } function copyText(text) { navigator.clipboard.writeText(text); showToast('Copied: ' + text.substring(0, 30) + '…'); } function showToast(msg) { const t = document.getElementById('toast'); t.textContent = msg; t.classList.add('show'); setTimeout(() => t.classList.remove('show'), 2500); } // ─── Image Generation ─────────────────── let imageMode = 'text'; const MAX_REF_IMAGES_UI = 5; let sourceImages = []; // [{data, name, size, type}] — maksimal 5 let sourceImageData = null; // cermin gambar pertama (kompatibilitas) function setImageMode(mode) { imageMode = mode === 'image' ? 'image' : 'text'; document.getElementById('modeText').classList.toggle('active', imageMode === 'text'); document.getElementById('modeImage').classList.toggle('active', imageMode === 'image'); document.getElementById('imageSourceField').hidden = imageMode !== 'image'; document.getElementById('imageModeSubtitle').textContent = imageMode === 'image' ? 'Image → Image (1–5 referensi)' : 'Text → Image'; document.getElementById('imagePromptLabel').textContent = imageMode === 'image' ? 'Instruksi / prompt gabungan' : 'Prompt'; document.getElementById('imgPrompt').placeholder = imageMode === 'image' ? 'Gabungkan elemen dari semua gambar referensi: ubah jadi ilustrasi 3D sinematik, pertahankan komposisi utama' : 'kucing astronot duduk di tepi kawah bulan, cinematic lighting'; } function renderSourceImages() { const list = document.getElementById('imageRefList'); const count = document.getElementById('imageRefCount'); if (!list) return; list.replaceChildren(); sourceImages.forEach((img, i) => { const wrap = document.createElement('div'); wrap.style.cssText = 'position:relative;width:88px;height:88px;border-radius:8px;overflow:hidden;border:1px solid var(--border)'; const im = document.createElement('img'); im.src = img.data; im.alt = 'Referensi ' + (i + 1); im.style.cssText = 'width:100%;height:100%;object-fit:cover;display:block'; const badge = document.createElement('span'); badge.textContent = String(i + 1); badge.style.cssText = 'position:absolute;top:3px;left:3px;background:#1a73e8;color:#fff;font-size:11px;font-weight:700;width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center'; const del = document.createElement('button'); del.type = 'button'; del.textContent = '×'; del.title = 'Hapus gambar ' + (i + 1); del.style.cssText = 'position:absolute;top:2px;right:2px;width:20px;height:20px;border-radius:50%;border:0;background:rgba(0,0,0,.65);color:#fff;font-size:13px;line-height:1;cursor:pointer'; del.onclick = () => removeRefImage(i); wrap.append(im, badge, del); list.appendChild(wrap); }); if (count) count.textContent = sourceImages.length + ' / ' + MAX_REF_IMAGES_UI + ' gambar referensi'; const up = document.getElementById('imageUpload'); if (up) up.classList.toggle('has-file', sourceImages.length > 0); sourceImageData = sourceImages[0] ? sourceImages[0].data : null; } function handleSourceImage() { const input = document.getElementById('imageFile'); const files = Array.from(input.files || []); input.value = ''; if (!files.length) return; for (const file of files) { if (sourceImages.length >= MAX_REF_IMAGES_UI) { showToast('Maksimal ' + MAX_REF_IMAGES_UI + ' gambar referensi'); break; } if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) { showToast('Gunakan JPEG, PNG, atau WebP'); continue; } if (file.size > 10 * 1024 * 1024) { showToast('Tiap gambar maksimal 10 MB'); continue; } const reader = new FileReader(); reader.onload = () => { sourceImages.push({ data: reader.result, name: file.name, size: file.size, type: file.type }); renderSourceImages(); }; reader.readAsDataURL(file); } } function removeRefImage(index) { sourceImages.splice(index, 1); renderSourceImages(); } function removeSourceImage() { sourceImages = []; sourceImageData = null; const input = document.getElementById('imageFile'); if (input) input.value = ''; renderSourceImages(); } async function generateImage() { if (!requireApiKey()) return; const prompt = document.getElementById('imgPrompt').value.trim(); if (!prompt) return showToast('Prompt wajib diisi'); if (imageMode === 'image' && !sourceImages.length) return showToast('Upload gambar referensi terlebih dahulu'); const ratio = document.getElementById('imgRatio').value; const count = parseInt(document.getElementById('imgCount').value); const btn = document.getElementById('btnImage'); setLoading(btn, true); try { const endpoint = count > 1 ? '/dashboard/v1/images/variations' : '/dashboard/v1/images/generations'; // slim:true → server hanya kirim 1 salinan gambar (bukan 4x). // Tanpa ini 4 gambar parallel ≈ 19 MB → koneksi HP putus ("Failed to fetch"). const body = { prompt, ratio, slim: true }; if (imageMode === 'image') { // 1–5 gambar referensi: gambar pertama jadi acuan utama, sisanya extraImages. body.image = sourceImages[0].data; if (sourceImages.length > 1) body.extraImages = sourceImages.slice(1).map(x => x.data); } if (count > 1) body.count = count; const r = await fetch(`${BASE}${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); const data = await r.json(); if (!r.ok) throw new Error(data.error || 'Request failed'); showResult('resultImage'); const body_el = document.getElementById('resultImageBody'); if (count > 1 && data.results) { const imgs = data.results.filter(x => x.image).map(x => x.image.url || x.image.dataUrl); document.getElementById('resultImageMeta').textContent = `${imgs.length}/${count} images`; const grid = document.createElement('div'); grid.className = 'result-grid'; imgs.forEach(url => { const img = document.createElement('img'); img.src = url; img.alt = 'Hasil gambar'; img.addEventListener('click', () => window.open(url, '_blank', 'noopener')); grid.append(img); }); body_el.replaceChildren(grid); } else if (data.image) { document.getElementById('resultImageMeta').textContent = `seed: ${data.seed}`; const img = document.createElement('img'); img.src = data.image.url || data.image.dataUrl; img.alt = 'Hasil gambar'; img.loading = 'lazy'; body_el.replaceChildren(img); } else { throw new Error('No image in response'); } } catch (e) { showError('resultImage', e.message); } finally { setLoading(btn, false); } } // ─── GPT Image ─────────────────────────── let gptMode = 'text'; let gptSourceImages = []; // [{data}] maksimal 5 function gptSetMode(mode) { gptMode = mode === 'image' ? 'image' : 'text'; document.getElementById('gptModeText').classList.toggle('active', gptMode === 'text'); document.getElementById('gptModeImage').classList.toggle('active', gptMode === 'image'); document.getElementById('gptSourceField').hidden = gptMode !== 'image'; document.getElementById('gptModeSubtitle').textContent = gptMode === 'image' ? 'Image → Image (1–5 referensi)' : 'Text → Image'; document.getElementById('gptPromptLabel').textContent = gptMode === 'image' ? 'Instruksi / prompt' : 'Prompt'; document.getElementById('gptPrompt').placeholder = gptMode === 'image' ? 'Ubah jadi poster kopi dengan tulisan "KOPI KITA", pertahankan produk & komposisi aslinya' : "poster kopi spesialti, tulisan 'KOPI KITA' di atas meja kayu, cahaya pagi, detail tajam"; } function gptRenderRefs() { const list = document.getElementById('gptRefList'); const count = document.getElementById('gptRefCount'); if (!list) return; list.replaceChildren(); gptSourceImages.forEach((img, i) => { const wrap = document.createElement('div'); wrap.style.cssText = 'position:relative;width:88px;height:88px;border-radius:8px;overflow:hidden;border:1px solid var(--border)'; const im = document.createElement('img'); im.src = img.data; im.alt = 'Referensi ' + (i + 1); im.style.cssText = 'width:100%;height:100%;object-fit:cover;display:block'; const badge = document.createElement('span'); badge.textContent = String(i + 1); badge.style.cssText = 'position:absolute;top:3px;left:3px;background:#1a73e8;color:#fff;font-size:11px;font-weight:700;width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center'; const del = document.createElement('button'); del.type = 'button'; del.textContent = '×'; del.title = 'Hapus gambar ' + (i + 1); del.style.cssText = 'position:absolute;top:3px;right:3px;width:20px;height:20px;border-radius:50%;border:0;background:rgba(0,0,0,.65);color:#fff;font-size:13px;line-height:1;cursor:pointer'; del.onclick = () => { gptSourceImages.splice(i, 1); gptRenderRefs(); }; wrap.append(im, badge, del); list.append(wrap); }); if (count) count.textContent = `${gptSourceImages.length} / 5 gambar referensi`; } function gptHandleFiles() { const input = document.getElementById('gptFile'); const files = Array.from(input.files || []); input.value = ''; if (!files.length) return; for (const file of files) { if (gptSourceImages.length >= 5) { showToast('Maksimal 5 gambar referensi'); break; } if (!/^image\/(jpeg|png|webp)$/.test(file.type)) { showToast('Format harus JPEG, PNG, atau WebP'); continue; } if (file.size > 10 * 1024 * 1024) { showToast('Ukuran gambar maksimal 10 MB'); continue; } const reader = new FileReader(); reader.onload = () => { gptSourceImages.push({ data: reader.result }); gptRenderRefs(); }; reader.readAsDataURL(file); } } async function generateGptImage() { if (!requireApiKey()) return; const prompt = document.getElementById('gptPrompt').value.trim(); if (!prompt) return showToast('Prompt wajib diisi'); const rasio = document.getElementById('gptRatio').value; const jumlah = parseInt(document.getElementById('gptCount').value, 10) || 1; if (gptMode === 'image' && !gptSourceImages.length) return showToast('Upload gambar referensi dulu'); const btn = document.getElementById('btnGpt'); setLoading(btn, true); try { const body = { prompt, rasio, jumlah }; if (gptMode === 'image') body.referensi = gptSourceImages.map(x => x.data); const r = await fetch(`${BASE}/dashboard/v1/gpt-image`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.error || 'Gambar belum berhasil dibuat'); const urls = (Array.isArray(data.data) ? data.data : []).map(x => x && x.url).filter(Boolean); if (!urls.length) throw new Error('Gambar belum berhasil dibuat'); showResult('resultGpt'); document.getElementById('resultGptMeta').textContent = `${urls.length}/${jumlah} gambar · ${rasio}`; const grid = document.createElement('div'); grid.className = 'result-grid'; urls.forEach((url, i) => { const a = document.createElement('a'); a.href = url; a.target = '_blank'; a.rel = 'noopener'; const img = document.createElement('img'); img.src = url; img.alt = `Hasil GPT Image ${i + 1}`; a.append(img); grid.append(a); }); document.getElementById('resultGptBody').replaceChildren(grid); } catch (e) { showError('resultGpt', e.message); } finally { setLoading(btn, false); } } // ─── Vision ────────────────────────────── let visionImageData = null; function handleFile(type) { const fileInput = document.getElementById(type + 'File'); const label = document.getElementById(type + 'Upload'); const nameEl = document.getElementById(type + 'FileName'); const file = fileInput.files[0]; if (!file) return; nameEl.textContent = file.name + ' (' + (file.size / 1024).toFixed(0) + ' KB)'; nameEl.style.display = 'block'; label.classList.add('has-file'); const reader = new FileReader(); reader.onload = () => { const match = reader.result.match(/^data:(.+?);base64,(.*)/); if (match) { visionImageData = { mimeType: match[1], base64: match[2] }; } }; reader.readAsDataURL(file); } async function analyzeImage() { if (!requireApiKey()) return; const prompt = document.getElementById('visionPrompt').value.trim() || 'Deskripsikan gambar ini'; if (!visionImageData) return showToast('Upload gambar dulu'); const btn = document.getElementById('btnVision'); setLoading(btn, true); try { const r = await fetch(`${BASE}/dashboard/v1/chat/completions`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt, referenceImage: visionImageData }), }); const data = await r.json(); if (!r.ok) throw new Error(data.error || 'Request failed'); showResult('resultVision'); const text = data.text || data.choices?.[0]?.message?.content || 'No response'; const pre = document.createElement('pre'); pre.textContent = text; document.getElementById('resultVisionBody').replaceChildren(pre); } catch (e) { showError('resultVision', e.message); } finally { setLoading(btn, false); } } // ─── Chat ──────────────────────────────── async function chatText() { if (!requireApiKey()) return; const prompt = document.getElementById('chatPrompt').value.trim(); if (!prompt) return showToast('Message wajib diisi'); const btn = document.getElementById('btnChat'); setLoading(btn, true); try { const r = await fetch(`${BASE}/dashboard/v1/chat/completions`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt }), }); const data = await r.json(); if (!r.ok) throw new Error(data.error || 'Request failed'); showResult('resultChat'); const text = data.text || data.choices?.[0]?.message?.content || 'No response'; const pre = document.createElement('pre'); pre.textContent = text; document.getElementById('resultChatBody').replaceChildren(pre); } catch (e) { showError('resultChat', e.message); } finally { setLoading(btn, false); } } // ─── TTS ───────────────────────────────── async function generateTTS() { if (!requireApiKey()) return; const text = document.getElementById('ttsText').value.trim(); if (!text) return showToast('Text wajib diisi'); const voice = document.getElementById('ttsVoice').value; const btn = document.getElementById('btnTTS'); setLoading(btn, true); try { const r = await fetch(`${BASE}/dashboard/v1/audio/speech`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input: text, voice }), }); const data = await r.json(); if (!r.ok) throw new Error(data.error || 'Request failed'); showResult('resultTTS'); const audio = document.createElement('audio'); audio.controls = true; audio.autoplay = true; audio.src = data.audio.dataUrl; document.getElementById('resultTTSBody').replaceChildren(audio); } catch (e) { showError('resultTTS', e.message); } finally { setLoading(btn, false); } } // ─── Code tabs ─────────────────────────── function showCode(lang, btn) { document.querySelectorAll('.code-tab').forEach(t => t.classList.remove('active')); btn.classList.add('active'); ['curl', 'python', 'js', 'openai'].forEach(l => { document.getElementById('code' + l.charAt(0).toUpperCase() + l.slice(1)).style.display = l === lang ? 'block' : 'none'; }); } // ─── Start ─────────────────────────────── checkSession(); /* ===== Omni Video ===== */ let omniMode='i2v', omniPollTimer=null; // Durasi video sumber utk mode Edit Video AI (batas Omni Video = 10 detik). let omniEditDur=null; function omniSetMode(m){ omniMode=m; document.querySelectorAll('[data-omode]').forEach(b=>b.classList.toggle('active',b.dataset.omode===m)); document.getElementById('omniImageField').style.display = m==='i2v'?'':'none'; const ingF=document.getElementById('omniIngField'); if(ingF)ingF.style.display = m==='ing'?'':'none'; document.getElementById('omniPromptField').style.display = m==='wm'?'none':''; document.getElementById('omniVideoField').style.display = m==='wm'?'':'none'; document.getElementById('omniEditField').style.display = m==='edit'?'':'none'; document.getElementById('omniRatioField').style.display = m==='wm'?'none':''; document.getElementById('omniResField').style.display = m==='wm'?'none':''; document.getElementById('omniDurField').style.display = m==='wm'?'none':''; document.getElementById('omniWmField').style.display = (m==='wm'||m==='edit')?'none':''; // Judul & tombol menyesuaikan mode biar tidak membingungkan. const pt=document.getElementById('omniPrompt'); if(pt)pt.placeholder = m==='edit' ? 'Contoh: hapus semua teks di video, bikin tampilan lebih bersih' : (m==='ing' ? 'Contoh: ketiga bahan tampil bersamaan dalam satu adegan, kamera bergerak halus, sinematik' : 'Contoh: kamera perlahan mendekat, objek bergerak halus, suasana sinematik'); const btn=document.getElementById('btnOmni'); if(btn)btn.querySelector('span').textContent = m==='edit' ? 'Edit video (Video → Video)' : (m==='ing' ? 'Buat video dari bahan' : 'Buat video'); } // Mode Ingredients Frame to video: pratinjau 1–3 gambar bernomor. document.getElementById('omniIngredients')?.addEventListener('change',e=>{ const box=document.getElementById('omniIngPreview'); if(!box)return; box.innerHTML=''; const fs=[...e.target.files].slice(0,3); fs.forEach((f,i)=>{ const w=document.createElement('div'); w.style.cssText='position:relative;width:86px;height:86px;border-radius:8px;overflow:hidden;border:1px solid var(--border)'; const im=document.createElement('img'); im.src=URL.createObjectURL(f); im.style.cssText='width:100%;height:100%;object-fit:cover'; const n=document.createElement('span'); n.textContent=String(i+1); n.style.cssText='position:absolute;top:3px;left:3px;background:#1a73e8;color:#fff;font-size:11px;font-weight:700;width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center'; w.appendChild(im);w.appendChild(n);box.appendChild(w); }); }); document.getElementById('omniImage')?.addEventListener('change',e=>{ const f=e.target.files[0]; if(!f)return; const p=document.getElementById('omniPreview'); p.src=URL.createObjectURL(f); p.style.display='block'; }); // Mode Edit Video AI: baca durasi video sumber di browser (batas 10 detik). document.getElementById('omniEditVideo')?.addEventListener('change',e=>{ const f=e.target.files[0]; const info=document.getElementById('omniEditInfo'); omniEditDur=null; if(!f){ return; } const url=URL.createObjectURL(f); const v=document.createElement('video'); v.preload='metadata'; v.onloadedmetadata=()=>{ omniEditDur=v.duration; const mb=(f.size/1048576).toFixed(1); if(!isFinite(v.duration)||v.duration<=0){ info.innerHTML='⚠️ Durasi tidak terbaca ('+mb+' MB). Coba file MP4 lain ya.'; } else if(v.duration>10.05){ info.innerHTML='✅ Siap diedit: '+v.duration.toFixed(1)+' detik · '+mb+' MB.
✂️ Video akan dipakai 10 detik pertama. Ketik perintahnya di bawah.'; } else { info.innerHTML='✅ Siap diedit: '+v.duration.toFixed(1)+' detik · '+mb+' MB. Ketik perintahnya di bawah.'; } URL.revokeObjectURL(url); }; v.onerror=()=>{ info.innerHTML='⚠️ File tidak bisa dibaca sebagai video ('+(f.size/1048576).toFixed(1)+' MB).'; URL.revokeObjectURL(url); }; v.src=url; }); function omniShow(html){const r=document.getElementById('resultOmni');r.classList.add('show');document.getElementById('resultOmniBody').innerHTML=html;} async function generateOmni(){ const btn=document.getElementById('btnOmni'); btn.disabled=true; document.getElementById('resultOmniMeta').textContent=''; try{ let res; if(omniMode==='wm'){ const vf=document.getElementById('omniVideo').files[0]; if(!vf){omniShow('

Pilih video dulu ya.

');return;} omniShow('

⏳ Mengunggah video ('+Math.round(vf.size/1048576)+' MB)... proses 1-3 menit.

'); const fd=new FormData(); fd.append('video',vf); res=await fetch(BASE+'/omni/api/upload',{method:'POST',body:fd}); } else if(omniMode==='edit'){ // ── Edit Video AI: video (<=10s) + instruksi → video baru ── const vf=document.getElementById('omniEditVideo').files[0]; if(!vf){omniShow('

Pilih video dulu ya.

');return;} if(omniEditDur!=null && omniEditDur>10.05){ // [30 Okt'26] Video panjang TIDAK diblokir lagi: server mengambil 10 // detik pertama otomatis (meniru perilaku pemilih segmen 10 detik). omniShow('

✂️ Video '+omniEditDur.toFixed(1)+' detik — dipakai 10 detik pertama.

'); } const p=document.getElementById('omniPrompt').value.trim(); if(!p){omniShow('

Tulis perintah edit dulu ya (mis. “hapus semua teks”).

');return;} omniShow('

⏳ Mengunggah video ('+Math.round(vf.size/1048576)+' MB)... edit pakai AI butuh 1-4 menit.

'); const fd=new FormData(); fd.append('video',vf); fd.append('prompt',p); fd.append('ratio',document.getElementById('omniRatio').value); fd.append('resolution',document.getElementById('omniRes').value); fd.append('duration',document.getElementById('omniDur').value); fd.append('remove_wm',document.getElementById('omniRemoveWm').checked?'1':'0'); const refEl=document.getElementById('omniEditRef'); const rf=refEl&&refEl.files&&refEl.files[0]; if(rf){ if(rf.size>15*1048576){omniShow('

Gambar referensi maksimal 15 MB.

');return;} fd.append('image',rf); } res=await fetch(BASE+'/omni/api/edit',{method:'POST',body:fd}); } else { const fd = new FormData(); if(omniMode==='i2v'){ const f=document.getElementById('omniImage').files[0]; if(!f){omniShow('

Pilih gambar dulu ya.

');return;} fd.append('image',f); } if(omniMode==='ing'){ // Ingredients Frame to video: 1–3 gambar bahan, satu job. const fs=[...document.getElementById('omniIngredients').files]; if(!fs.length){omniShow('

Pilih 1–3 gambar bahan dulu ya.

');return;} if(fs.length>3){omniShow('

Maksimal 3 gambar bahan.

');return;} for(const f of fs){ if(f.size>8*1048576){omniShow('

Tiap gambar bahan maksimal 8 MB.

');return;} fd.append('images',f); } } const p=document.getElementById('omniPrompt').value.trim(); if(!p){omniShow('

Isi prompt dulu ya.

');return;} fd.append('prompt',p); fd.append('ratio',document.getElementById('omniRatio').value); fd.append('resolution',document.getElementById('omniRes').value); fd.append('duration',document.getElementById('omniDur').value); fd.append('remove_wm',document.getElementById('omniRemoveWm').checked?'1':'0'); omniShow('

⏳ Job dikirim... proses ±1-3 menit (lebih lama bila antre). Halaman ini update otomatis.

'); const _ac=new AbortController(); const _batas=setTimeout(()=>_ac.abort(), omniMode==='edit'?300000:180000); try{ const _path = omniMode==='i2v' ? 'generate' : (omniMode==='ing' ? 'ingredients' : 't2v'); res=await fetch(BASE+'/omni/api/'+_path,{method:'POST',body:fd,signal:_ac.signal}); }catch(err){ omniShow('

❌ '+(err&&err.name==='AbortError'?'Server tidak menjawab (waktu habis). Coba lagi.':'Gagal menghubungi server: '+(err&&err.message||err))+'

'); return; }finally{clearTimeout(_batas);} } if(!res.ok){const e=await res.json().catch(()=>({}));omniShow('

Gagal: '+(e.error||res.status)+'

');return;} const d=await res.json(); const job=d.id; const t0=Date.now(); omniShow( '
'+ '
🎬 Sedang membuat video…
'+ '
'+ '
🕓 Antre di server…
'+ '
Estimasi '+(omniMode==='edit'?'1-4 menit':'±1-3 menit')+' — jangan tutup halaman ini, status update otomatis tiap 10 detik
'+ '
Job: '+job+' · 0:00 berlalu
'+ '
'+ '
'); if(omniPollTimer)clearInterval(omniPollTimer); let omniGagal=0; window.__omniGagal=0; const omniTick=setInterval(()=>{const s=Math.floor((Date.now()-t0)/1000);const el=document.getElementById('omniElapsed');if(el)el.textContent=Math.floor(s/60)+':'+String(s%60).padStart(2,'0');},1000); omniPollTimer=setInterval(async()=>{ try{ const st=await fetch(BASE+'/omni/api/status/'+job); const s=await st.json(); const bar=document.getElementById('omniBar'); const el=document.getElementById('omniStat'); const phaseTxt={queued:'🕓 Antre di server…',engine:'⚙️ Menyiapkan mesin edit…',uploading:'⬆️ Mengunggah video…',generating:'🎞️ Omni Video sedang mengedit…',downloading:'⬇️ Mengunduh hasil…',delogo:'🧹 Menghapus watermark…',cleaning:'🧹 Menghapus watermark…',done:'✅ Selesai!',error:'❌ Gagal'}; const cur=phaseTxt[s.phase]||null; if(el)el.textContent=cur||('Status: '+s.status); const pct={queued:4,engine:8,uploading:12,generating:35,downloading:75,delogo:90,cleaning:90,done:100,error:100}[s.phase]; if(bar&&pct)bar.style.width=Math.min(99,pct+(Math.floor((Date.now()-t0)/30000)%4))+'%'; const lg=document.getElementById('omniLog'); if(lg&&s.log)lg.innerHTML=s.log.slice(-5).map(x=>'> '+x).join('
'); omniGagal=0; window.__omniGagal=0; if(s.status==='done'){ clearInterval(omniPollTimer); clearInterval(omniTick); const src=s.video.startsWith('http')?s.video:BASE+'/omni/video/'+s.video.split('/').pop(); document.getElementById('resultOmniMeta').textContent='Selesai'; omniShow('

⬇ Download MP4

'); } else if(s.status==='error'){ clearInterval(omniPollTimer); clearInterval(omniTick); omniShow('

❌ Gagal: '+(s.error||'unknown')+'

'); } }catch(e){ omniGagal=window.__omniGagal=(window.__omniGagal||0)+1; if(omniGagal>=3){ clearInterval(omniPollTimer); omniShow('

⚠️ Status tidak bisa dihubungi (sesi mungkin berakhir atau jaringan putus).
Muat ulang halaman lalu masuk lagi — job tetap berjalan di server dengan ID '+job+'.

'); } } },10000); } finally { btn.disabled=false; } }