From 26016f16212f3d794eda78ebb4bb008cf522be95 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 12:41:42 +0000 Subject: [PATCH] feat(server): admin panel pages for dashboard, users, archive, jobs, settings and logs Vanilla ES modules under a strict CSP (bars and charts are SVG, no inline styles), cookie session with CSRF header, first sign-in password change, live updates over the events WebSocket, language menu fed by /api/v1/i18n. Every label and tooltip is an Admin.* resource (en, it). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Admin.resx | 289 +++++++++++++++++- i18n/it/Admin.it.resx | 289 +++++++++++++++++- src/Titano.Server/Admin/web/admin.css | 184 +++++++++-- src/Titano.Server/Admin/web/api.js | 95 +++++- src/Titano.Server/Admin/web/app.js | 153 ++++++++-- src/Titano.Server/Admin/web/i18n.js | 53 +++- src/Titano.Server/Admin/web/icons.js | 1 + src/Titano.Server/Admin/web/jobs.js | 41 +++ src/Titano.Server/Admin/web/pages/about.js | 21 +- src/Titano.Server/Admin/web/pages/archive.js | 109 +++++++ .../Admin/web/pages/dashboard.js | 145 ++++++++- src/Titano.Server/Admin/web/pages/jobs.js | 163 ++++++++++ src/Titano.Server/Admin/web/pages/logs.js | 104 +++++++ src/Titano.Server/Admin/web/pages/settings.js | 108 +++++++ src/Titano.Server/Admin/web/pages/users.js | 234 ++++++++++++++ src/Titano.Server/Admin/web/ui.js | 146 +++++++++ 16 files changed, 2029 insertions(+), 106 deletions(-) create mode 100644 src/Titano.Server/Admin/web/jobs.js create mode 100644 src/Titano.Server/Admin/web/pages/archive.js create mode 100644 src/Titano.Server/Admin/web/pages/jobs.js create mode 100644 src/Titano.Server/Admin/web/pages/logs.js create mode 100644 src/Titano.Server/Admin/web/pages/settings.js create mode 100644 src/Titano.Server/Admin/web/pages/users.js create mode 100644 src/Titano.Server/Admin/web/ui.js diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index d63f15e8..052d546b 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -4,17 +4,198 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + API version + Database TLS SHA-256 + Server name Titano Server - API version + Running for + Version + {0} changed the archive layoutlong + {0} started {1}long + {0} signed in · {1}long + failed sign-in as {0}long + {0} changed their passwordlong + {0} reset the password of {1}long + {0} created {1}long + {0} deleted {1}long + {0} edited a sequence · {1}long + {0} changed the server settingslong + {0} created user {1}long + {0} deleted user {1}long + {0} changed a user · {1}long + Cameras + Formats + File template + Name of new originals, e.g. {date}_{time}_{n:0000} + Folder template + Folder of new sequences, e.g. {year}/{date} {camera}; existing folders are never renamed + free + Health + Layout + Maintenance + Clean up stale caches and database entries + Name + Name of the archive shown to clients + Originals + Proxies + Long edge of the JPEG proxies built for editing and viewing + {0} px + Full size + Off + Job queued. + Rebuild + Rebuild the index from the sidecars on disk; files are not touched + Scan + Look for new and changed sequences on disk + unverified + Verify + Read every original again and compare its SHA-256 + Cancel + Discard the changes + Close + Close this panel + Keep + Leave everything as it is + Load more + Show the next page + Refresh + Save + Save the changes on the server + Saved. + Recent activity + All logs + Open the audit log Archive - Server + Storage by year + discovery off + discovery on + {0} free + {0} queued · {1} done today · {2} failedlong + Jobs + up {0} · {1} · TLS {2} · {3}long + No activity yet + Nothing here yet + {0} sequences without proxieslong + Render nodes + of {0} + online + originals {0} + {0} photos · {1} cameras + Queue and history + Open the Jobs page + running + sequences + Storage + frames per day · {0} total · peak {1}long + Uploads · last 30 days + {0} workers The server did not answer; try again.long + Adopt + Deep analysis + Duplicates + Import + Light analysis + Maintenance + Move + Orphans + Proxies + Rebuild + Render + Scan + Thumbnails + Upload + Verify + busy + cancelled + done + failed + idle + offline + paused + queued + running + Cancel + Cancel this job + Created + No jobs + Encoders + All + Cancelled + Done + Failed + Paused + Queued + Running + Show only jobs in this state + Forget + Remove this node; its running jobs go back to the queue + Forget {0}? + Last heartbeat + Kind + Show or hide the job log + {0} running · {1} nodes onlinelong + No render nodes + Node + Node + Render nodes + Owner + Pause + Stop at the next checkpoint and keep the progress + Background + Normal + Order in the queue: user jobs run before normal and background ones + User + Progress + Remove + Remove from the queue + Resume + Put the job back in the queue from its checkpoint + Retry + Queue the job again from its last checkpoint + server + State + Target + Language of this panel Wrong user name or password.long + Only administrators can use this panel.long Password + Your password; it is checked by the server only Sign in Sign in to administer this server User + Your user name on this server + Archive layout + Job started + Sign-in + Failed sign-in + Password changed + Password reset + Sequence created + Sequence deleted + Sequence edited + Server settings + User created + User deleted + User changed + Details + Download + Save this log file + Nothing recorded yet + Log files + From + {0} lines + How many of the latest lines to show + Read the log again + Audit + Changes to users, sequences, the archive and settings + Server log + The latest lines of the server log, and the log files + Sign-ins + Who signed in, from where and when + What + When + Who About Version and certificate fingerprint Archive @@ -29,9 +210,113 @@ Server name, ports, TLS, limits and language Users Accounts, roles and quotas + Current password + The password you signed in with + The two passwords differ.long + New password + At least 10 characters; other sessions of this account end + Repeat + Type the new password again + Change password + Replace the password and continue to the panel + Choose a new password Administrator Editor Uploader Viewer + Chunk size (MiB) + Size of each upload chunk; smaller chunks resume faster on poor links + LAN discovery + Announce this server on the local network so clients find it + Fingerprint + SHA-256 of the certificate; clients ask the user to compare it once + HTTP port + Port of the admin panel and API over HTTP + HTTPS port + Port of the API over TLS for Titano clients + Job history (days) + Days finished jobs are kept + Language + Language of server messages when a client asks for none + Limits and retention + Set by the environment variable {0} + Max file (MB) + Largest single upload accepted + Network and TLS + Restart required + Saved ports, TLS, workers, chunk size or job history apply after a restart + Server + Server name + Name shown to clients and on the LAN + Self-signed + Own certificate + Reverse proxy + Certificate + PEM certificate file used in Own certificate mode + Private key + PEM private key file used in Own certificate mode + TLS mode + How HTTPS is provided + Session days + Days a client stays signed in without being used + Abandoned after (h) + Hours after which unfinished uploads are discarded + Workers + Jobs this server runs at the same time + Sign out Sign out of the admin panel + Active + Password copied. + Copy the password + Create + Create the account + Delete… + Delete the account; its sequences are reassigned to you + The account and its sessions are removed; its sequences become yours.long + Delete + Delete {0}? + Disable + Disable: sessions end, files stay + Disabled + Display name + Shown in the client and in activity + Edit + Change name, role, quota or render-node right + Edit user + No users match + Enable + Re-enable the account + {0} free on the server + Last seen + {0} accounts · {1} active + must change password + Must change password + Always required for accounts created here + New user + Create an account; the user must change the password at first sign-in + Passwords: PBKDF2-SHA512, {0} characters minimum · tokens expire after {1} days idlelong + Quota + Originals uploaded by this user count against the quota; 0 = unlimited + {0} of {1} + Generate another + May act as render node + Lets this user's PC take render jobs from the server + Reset password + Set a temporary password; the user must replace it and their sessions end + Role + Everything, including users and settings + Import, edit, render, upload and download + Upload only; cannot edit sequences + Browse and download renders only + Search + Filter by user or display name + Sign-in log + Who signed in from where, and when + Status + Temporary password + Give this to the user; they must replace it at first sign-in + Uploads 30 d + User + Username + Letters, digits, dot and dash; cannot be changed later diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index 4e1f7a66..626d14c6 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -4,17 +4,198 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Versione API + Database TLS SHA-256 + Nome server Titano Server - Versione API + In esecuzione da + Versione + {0} ha modificato l'organizzazione dell'archivio + {0} ha avviato {1} + {0} ha effettuato l'accesso · {1} + accesso fallito come {0} + {0} ha cambiato la propria password + {0} ha reimpostato la password di {1} + {0} ha creato {1} + {0} ha eliminato {1} + {0} ha modificato una sequenza · {1} + {0} ha modificato le impostazioni del server + {0} ha creato l'utente {1} + {0} ha eliminato l'utente {1} + {0} ha modificato un utente · {1} + Fotocamere + Formati + Modello file + Nome dei nuovi originali, es. {date}_{time}_{n:0000} + Modello cartelle + Cartella delle nuove sequenze, es. {year}/{date} {camera}; le cartelle esistenti non vengono mai rinominate + liberi + Stato + Organizzazione + Manutenzione + Pulisci cache obsolete e voci del database + Nome + Nome dell'archivio mostrato ai client + Originali + Proxy + Lato lungo dei proxy JPEG creati per modifica e visione + {0} px + Dimensione piena + Disattivati + Job in coda. + Ricostruisci + Ricostruisci l'indice dai file sidecar su disco; i file non vengono toccati + Scansiona + Cerca sequenze nuove e modificate sul disco + non verificate + Verifica + Rileggi ogni originale e confronta il suo SHA-256 + Annulla + Scarta le modifiche + Chiudi + Chiudi questo pannello + Mantieni + Lascia tutto com'è + Carica altri + Mostra la pagina successiva + Aggiorna + Salva + Salva le modifiche sul server + Salvato. + Attività recenti + Tutti i log + Apri il registro di controllo Archivio - Server + Spazio per anno + rilevamento spento + rilevamento attivo + {0} liberi + {0} in coda · {1} completati oggi · {2} falliti + Job + attivo da {0} · {1} · TLS {2} · {3} + Nessuna attività + Ancora niente qui + {0} sequenze senza proxy + Nodi di rendering + di {0} + online + originali {0} + {0} foto · {1} fotocamere + Coda e cronologia + Apri la pagina Job + in corso + sequenze + Spazio + foto al giorno · {0} totali · picco {1} + Caricamenti · ultimi 30 giorni + {0} worker Il server non ha risposto; riprova. + Adozione + Analisi completa + Duplicati + Importazione + Analisi rapida + Manutenzione + Spostamento + Orfani + Proxy + Ricostruzione + Rendering + Scansione + Miniature + Caricamento + Verifica + occupato + annullato + completato + fallito + inattivo + offline + in pausa + in coda + in corso + Annulla + Annulla questo job + Creato + Nessun job + Encoder + Tutti + Annullati + Completati + Falliti + In pausa + In coda + In corso + Mostra solo i job in questo stato + Dimentica + Rimuovi questo nodo; i suoi job in corso tornano in coda + Dimenticare {0}? + Ultimo segnale + Tipo + Mostra o nascondi il log del job + {0} in corso · {1} nodi online + Nessun nodo di rendering + Nodo + Nodo + Nodi di rendering + Proprietario + Pausa + Fermati al prossimo punto di controllo e mantieni l'avanzamento + Background + Normale + Ordine in coda: i job utente partono prima di quelli normali e in background + Utente + Avanzamento + Rimuovi + Rimuovi dalla coda + Riprendi + Rimetti il job in coda dal suo punto di controllo + Riprova + Rimetti in coda il job dall'ultimo punto di controllo + server + Stato + Oggetto + Lingua di questo pannello Nome utente o password errati. + Solo gli amministratori possono usare questo pannello. Password + La tua password; la verifica solo il server Accedi Accedi per amministrare questo server Utente + Il tuo nome utente su questo server + Organizzazione archivio + Job avviato + Accesso + Accesso fallito + Password cambiata + Password reimpostata + Sequenza creata + Sequenza eliminata + Sequenza modificata + Impostazioni server + Utente creato + Utente eliminato + Utente modificato + Dettagli + Scarica + Salva questo file di log + Ancora nessuna registrazione + File di log + Da + {0} righe + Quante delle ultime righe mostrare + Rileggi il log + Controllo + Modifiche a utenti, sequenze, archivio e impostazioni + Log del server + Le ultime righe del log del server e i file di log + Accessi + Chi ha effettuato l'accesso, da dove e quando + Cosa + Quando + Chi Informazioni Versione e impronta del certificato Archivio @@ -29,9 +210,113 @@ Nome server, porte, TLS, limiti e lingua Utenti Account, ruoli e quote + Password attuale + La password con cui hai effettuato l'accesso + Le due password non coincidono. + Nuova password + Almeno 10 caratteri; le altre sessioni di questo account terminano + Ripeti + Digita di nuovo la nuova password + Cambia password + Sostituisci la password e continua nel pannello + Scegli una nuova password Amministratore Editor Caricamento Lettore + Dimensione blocco (MiB) + Dimensione di ogni blocco di caricamento; blocchi piccoli riprendono prima su linee lente + Rilevamento LAN + Annuncia questo server nella rete locale così che i client lo trovino + Impronta + SHA-256 del certificato; i client chiedono all'utente di confrontarlo una volta + Porta HTTP + Porta del pannello e delle API in HTTP + Porta HTTPS + Porta delle API in TLS per i client Titano + Cronologia job (giorni) + Giorni di conservazione dei job conclusi + Lingua + Lingua dei messaggi del server se il client non ne chiede una + Limiti e conservazione + Impostato dalla variabile d'ambiente {0} + File massimo (MB) + Caricamento singolo più grande accettato + Rete e TLS + Riavvio richiesto + Porte, TLS, worker, dimensione blocchi o cronologia job salvati valgono dopo un riavvio + Server + Nome server + Nome mostrato ai client e nella rete locale + Autofirmato + Certificato proprio + Reverse proxy + Certificato + File del certificato PEM usato in modalità Certificato proprio + Chiave privata + File della chiave privata PEM usato in modalità Certificato proprio + Modalità TLS + Come viene fornito HTTPS + Giorni di sessione + Giorni in cui un client resta connesso senza essere usato + Abbandono dopo (h) + Ore dopo le quali i caricamenti incompleti vengono scartati + Worker + Job che questo server esegue contemporaneamente + Esci Esci dal pannello di amministrazione + Attivo + Password copiata. + Copia la password + Crea + Crea l'account + Elimina… + Elimina l'account; le sue sequenze vengono assegnate a te + L'account e le sue sessioni vengono rimossi; le sue sequenze diventano tue. + Elimina + Eliminare {0}? + Disattiva + Disattiva: le sessioni terminano, i file restano + Disattivato + Nome visualizzato + Mostrato nel client e nelle attività + Modifica + Cambia nome, ruolo, quota o diritto di nodo di rendering + Modifica utente + Nessun utente corrisponde + Attiva + Riattiva l'account + {0} liberi sul server + Ultimo accesso + {0} account · {1} attivi + deve cambiare password + Cambio password obbligatorio + Sempre richiesto per gli account creati qui + Nuovo utente + Crea un account; l'utente deve cambiare la password al primo accesso + Password: PBKDF2-SHA512, almeno {0} caratteri · i token scadono dopo {1} giorni di inattività + Quota + Gli originali caricati da questo utente contano nella quota; 0 = illimitata + {0} di {1} + Generane un'altra + Può fare da nodo di rendering + Permette al PC di questo utente di prendere job di rendering dal server + Reimposta password + Imposta una password temporanea; l'utente deve sostituirla e le sue sessioni terminano + Ruolo + Tutto, compresi utenti e impostazioni + Importa, modifica, esegue rendering, carica e scarica + Solo caricamento; non può modificare le sequenze + Solo consultazione e download dei rendering + Cerca + Filtra per nome utente o nome visualizzato + Registro accessi + Chi ha effettuato l'accesso, da dove e quando + Stato + Password temporanea + Comunicala all'utente; dovrà sostituirla al primo accesso + Caricamenti 30 g + Utente + Nome utente + Lettere, cifre, punto e trattino; non si può cambiare in seguito diff --git a/src/Titano.Server/Admin/web/admin.css b/src/Titano.Server/Admin/web/admin.css index ee54015d..bf20d10c 100644 --- a/src/Titano.Server/Admin/web/admin.css +++ b/src/Titano.Server/Admin/web/admin.css @@ -1,4 +1,4 @@ -/* Titano Server admin — DESIGN.md light tokens (the web admin is light-only). */ +/* Titano Server admin — DESIGN.md light tokens (the web admin is light-only), mockups Admin.html and AdminUsers.html. */ :root { --bg: #f3f3f3; --chrome: #ffffff; @@ -15,12 +15,14 @@ --on-accent: #ffffff; --accent-selected: #e8f1fa; --sun: #e08a1e; + --sun-soft: #fff4e5; --success: #0f7b4f; --warning: #9a6700; --error: #c42b1c; --radius: 6px; --radius-card: 8px; --font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Noto Sans", sans-serif; + --mono: Consolas, "Cascadia Mono", ui-monospace, monospace; } * { box-sizing: border-box; } @@ -28,73 +30,189 @@ html, body { height: 100%; } body { margin: 0; font: 13px/1.45 var(--font); color: var(--text); background: var(--bg); } button, input, select { font: inherit; color: inherit; } a { color: var(--accent); } +a:hover { color: #004c8c; } +h1, h2 { margin: 0; } +h2 { font-size: 14px; font-weight: 600; } .num { font-variant-numeric: tabular-nums; } +.mono { font-family: var(--mono); } +.muted { color: var(--text-muted); } +.right { text-align: right; justify-self: end; } +.nowrap { white-space: nowrap; } +.ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.spacer { flex: 1; } +[hidden] { display: none !important; } /* Shell */ .shell { display: grid; grid-template-columns: 220px 1fr; min-height: 100vh; } -.sidebar { background: var(--chrome); border-right: 1px solid var(--stroke); display: flex; flex-direction: column; padding: 16px 12px; } -.brand { display: flex; align-items: center; gap: 10px; padding: 4px 8px 20px; } -.brand img { width: 28px; height: 28px; } +.sidebar { background: var(--chrome); border-right: 1px solid var(--stroke); display: flex; flex-direction: column; padding: 16px 12px; position: sticky; top: 0; height: 100vh; } +.brand { display: flex; align-items: center; gap: 10px; padding: 4px 8px 18px; } +.brand img { width: 22px; height: 22px; } .brand strong { display: block; font-size: 14px; } .brand span { display: block; font-size: 11px; color: var(--text-muted); } -.nav a { display: flex; align-items: center; gap: 12px; height: 36px; padding: 0 12px; border-radius: var(--radius); color: var(--text); text-decoration: none; margin-bottom: 2px; } +.brand.large img { width: 40px; height: 40px; } +.brand.large strong { font-size: 18px; } +.nav { display: grid; gap: 2px; } +.nav a { display: flex; align-items: center; gap: 10px; height: 36px; padding: 0 10px; border-radius: var(--radius); color: var(--text); text-decoration: none; } .nav a:hover { background: var(--card-hover); } .nav a[aria-current="page"] { background: var(--accent-selected); color: var(--accent); font-weight: 600; } -.nav svg { width: 16px; height: 16px; flex: none; } -.nav .badge { margin-left: auto; min-width: 18px; height: 16px; padding: 0 5px; border-radius: 8px; background: var(--accent); color: var(--on-accent); font-size: 10px; font-weight: 600; display: inline-flex; align-items: center; justify-content: center; } -.sidebar .user { margin-top: auto; border-top: 1px solid var(--stroke); padding: 12px 8px 0; display: flex; align-items: center; gap: 10px; } -.avatar { width: 28px; height: 28px; border-radius: 50%; background: var(--accent-selected); color: var(--accent); display: grid; place-items: center; font-weight: 600; } +.nav svg { flex: none; } +.badge { margin-left: auto; min-width: 18px; padding: 0 6px; border-radius: 8px; background: var(--accent); color: var(--on-accent); font-size: 11px; font-weight: 600; text-align: center; } +.badge.quiet { background: none; color: var(--text-muted); font-weight: 400; } +.sidebar .user { margin-top: auto; border-top: 1px solid var(--stroke); padding: 8px 10px 0; display: flex; align-items: center; gap: 10px; } .user .who { flex: 1; min-width: 0; } .user .who strong { display: block; } .user .who span { color: var(--text-muted); font-size: 11px; } .main { display: flex; flex-direction: column; min-width: 0; } -.header { height: 60px; display: flex; align-items: center; gap: 12px; padding: 0 24px; border-bottom: 1px solid var(--stroke); background: var(--chrome); } -.header h1 { font-size: 18px; font-weight: 600; margin: 0; } +.header { min-height: 60px; display: flex; align-items: center; gap: 14px; padding: 0 24px; border-bottom: 1px solid var(--stroke); background: var(--chrome); flex-wrap: wrap; } +.header h1 { font-size: 18px; font-weight: 600; } .header .meta { color: var(--text-muted); } -.header .spacer { flex: 1; } -.content { padding: 24px; display: grid; gap: 20px; } +.header .actions { display: flex; align-items: center; gap: 8px; } +.header .language { width: auto; } +.content { padding: 24px; display: grid; gap: 20px; align-content: start; } /* Controls */ -.btn { height: 32px; min-width: 44px; padding: 0 12px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 8px; } +.btn { height: 32px; min-width: 44px; padding: 0 12px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 8px; text-decoration: none; color: var(--text); white-space: nowrap; } .btn:hover { background: var(--card-hover); border-color: var(--stroke-strong); } -.btn:focus-visible, .input:focus-visible, select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.btn:focus-visible, .input:focus-visible, .chip:focus-visible, .link:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } .btn.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); font-weight: 600; } .btn.primary:hover { background: var(--accent-hover); } +.btn.destructive { border-color: var(--error); color: var(--error); background: transparent; } .btn.subtle { border-color: transparent; background: transparent; } -.btn.icon { width: 32px; padding: 0; } +.btn.icon { width: 32px; min-width: 32px; padding: 0; } +.btn.small { height: 28px; padding: 0 10px; font-size: 12px; } .btn:disabled { opacity: .4; cursor: default; } +.btn[aria-pressed="true"] { color: var(--accent); border-color: var(--accent); } +.link { border: 0; background: none; padding: 0; color: var(--text); cursor: pointer; text-align: left; } +.link:hover { color: var(--accent); } .input { height: 32px; width: 100%; padding: 0 10px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); } .input:hover { border-color: var(--stroke-strong); } .input:focus { border-color: var(--accent); outline: none; } .input[aria-invalid="true"] { border-color: var(--error); } -select.input { padding-right: 24px; } +.input:disabled, .input[readonly] { background: var(--bg); color: var(--text-muted); } +.input.small { height: 28px; width: auto; font-size: 12px; } +.input.narrow { width: 120px; } +.input.search { width: 220px; } +input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); margin: 0; } +.chips, .button-row { display: flex; gap: 8px; flex-wrap: wrap; } +.chip { height: 24px; padding: 0 10px; border: 1px solid var(--stroke); border-radius: 12px; background: var(--card); font-size: 11px; cursor: pointer; } +.chip[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); } +.chip.warn { border-color: var(--warning); color: var(--warning); cursor: default; display: inline-flex; align-items: center; } +.segmented { display: inline-flex; } +.segmented .btn { border-radius: 0; margin-left: -1px; } +.segmented .btn:first-child { border-radius: var(--radius) 0 0 var(--radius); } +.segmented .btn:last-child { border-radius: 0 var(--radius) var(--radius) 0; } -.panel { background: var(--surface); border: 1px solid var(--stroke); border-radius: var(--radius-card); padding: 18px 20px; } -.panel h2 { font-size: 14px; font-weight: 600; margin: 0 0 12px; } -.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; } -.tile .label { color: var(--text-muted); } -.tile .value { font-size: 28px; font-weight: 600; margin-top: 4px; } -.tile .value small { font-size: 13px; font-weight: 400; color: var(--text-muted); margin-left: 6px; } -.tile .sub { color: var(--text-muted); margin-top: 6px; } -.progress { height: 6px; border-radius: 3px; background: var(--stroke); overflow: hidden; margin-top: 10px; } -.progress > div { height: 6px; background: var(--accent); } +/* Panels and tiles */ +.panel { background: var(--surface); border: 1px solid var(--stroke); border-radius: var(--radius-card); padding: 16px 18px; display: grid; gap: 10px; align-content: start; min-width: 0; } +.panel.flush { padding: 0; gap: 0; overflow: hidden; } +.panel-head { display: flex; align-items: center; gap: 12px; } +.panel-head h2 { flex: 1; } +.panel-head.padded { padding: 12px 18px; border-bottom: 1px solid var(--stroke); } +.empty { padding: 24px 18px; color: var(--text-muted); } +.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 20px; } +.tile { gap: 8px; } +.tile .label, .tile .sub { font-size: 12px; color: var(--text-muted); } +.tile .value { font-size: 26px; font-weight: 600; display: flex; align-items: baseline; gap: 6px; } +.tile .value small { font-size: 13px; font-weight: 400; color: var(--text-muted); } +.grid { display: grid; gap: 20px; } +.grid.two { grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); } +.grid.wide-right { grid-template-columns: minmax(300px, 1fr) minmax(400px, 1.4fr); } -.status-ok { color: var(--success); } -.status-warn { color: var(--warning); } -.status-err { color: var(--error); } +/* Bars and charts (SVG attributes only: the panel runs under a strict CSP) */ +svg.bar { width: 100%; height: 6px; display: block; } +svg.bar .track { fill: var(--stroke); } +svg.bar .fill { fill: var(--accent); } +svg.bar.muted .fill { fill: var(--text-faint); } +svg.chart { width: 100%; height: auto; max-height: 220px; } +svg.chart .axis { stroke: var(--stroke); } +svg.chart .column { fill: var(--accent); } +svg.chart.sun .column { fill: var(--sun); } +svg.chart text { font: 10px var(--font); text-anchor: middle; } +svg.chart .value { fill: var(--text); } +svg.chart .label { fill: var(--text-muted); } +.progress-cell { display: flex; align-items: center; gap: 8px; min-width: 0; } +.progress-cell svg.bar { flex: 1; min-width: 40px; } + +/* Tables (grid rows, 52 px in the admin) */ +.table { display: grid; min-width: 0; } +.table .thead, .table .row { display: grid; gap: 12px; align-items: center; padding: 0 18px; } +.table .thead { font-size: 11px; color: var(--text-muted); padding-top: 10px; padding-bottom: 10px; border-bottom: 1px solid var(--stroke); } +.table .row { min-height: 52px; border-bottom: 1px solid var(--stroke); } +.table .row:hover { background: var(--card-hover); } +.table .row.dim { color: var(--text-muted); } +.table.compact .row { min-height: 32px; padding: 0; grid-template-columns: 1fr auto auto auto; border-bottom: 0; } +.table.compact .row:hover { background: none; } +.table.users .thead, .table.users .row { grid-template-columns: minmax(180px, 1.4fr) 100px minmax(160px, 1.3fr) 130px 100px 100px minmax(200px, auto); } +.table.jobs .thead, .table.jobs .row { grid-template-columns: 110px minmax(160px, 1.5fr) 100px minmax(120px, 1fr) 110px 90px minmax(220px, auto); } +.table.jobs-mini .thead, .table.jobs-mini .row { grid-template-columns: 96px minmax(120px, 1.5fr) 92px minmax(100px, 1fr) 90px 80px; padding: 0; min-height: 40px; } +.table.jobs-mini .row { border-bottom: 0; } +.table.nodes .thead, .table.nodes .row { grid-template-columns: minmax(140px, 1fr) 120px minmax(140px, 1fr) 170px 100px auto; } +.table.audit .thead, .table.audit .row { grid-template-columns: 170px 120px 170px minmax(160px, 1fr) 130px; min-height: 40px; } +.table-foot { display: flex; align-items: center; gap: 16px; padding: 10px 18px; font-size: 12px; } +.row-actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; } +.who { display: flex; align-items: center; gap: 10px; min-width: 0; } +.stack { display: flex; flex-direction: column; min-width: 0; } +.stack small { font-size: 11px; color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.avatar { width: 30px; height: 30px; flex: none; border-radius: 50%; background: var(--accent-selected); color: var(--accent); display: grid; place-items: center; font-weight: 600; } +.avatar.uploader { background: var(--sun-soft); color: var(--warning); } +.row.dim .avatar { background: #eeeeee; color: var(--text-muted); } +.state { white-space: nowrap; } +.state.running { color: var(--accent); } +.state.done { color: var(--success); } +.state.failed { color: var(--error); } +.state.paused { color: var(--warning); } +.state.queued, .state.cancelled { color: var(--text-muted); } +.activity { display: grid; grid-template-columns: 64px 1fr; column-gap: 12px; row-gap: 9px; font-size: 12px; } +pre.log { margin: 0; padding: 12px 18px; background: var(--bg); border-top: 1px solid var(--stroke); font: 12px/1.5 var(--mono); white-space: pre-wrap; overflow: auto; max-height: 260px; } +pre.log.tall { max-height: 60vh; border-top: 0; } + +/* Forms */ +.split { display: grid; grid-template-columns: 1fr auto; gap: 20px; align-items: start; } +.side { width: 340px; } +.form { display: grid; gap: 12px; } +.form label { display: grid; gap: 6px; color: var(--text-muted); } +.form label.check, label.check { display: flex; align-items: center; gap: 8px; color: var(--text); } +.form fieldset { border: 0; margin: 0; padding: 0; display: grid; gap: 8px; } +.form legend { color: var(--text-muted); margin-bottom: 8px; } +.form h2 { font-size: 16px; } +.inline { display: flex; align-items: center; gap: 8px; } +.buttons { display: flex; gap: 8px; justify-content: flex-end; } +.error { color: var(--error); min-height: 18px; } +.settings { display: grid; gap: 20px; } +.field { display: grid; grid-template-columns: 180px minmax(0, 420px); align-items: center; gap: 12px; color: var(--text-muted); } +.settings-form .field { grid-template-columns: 140px minmax(0, 1fr); } + +/* Dialogs and toasts */ +dialog.dialog { border: 1px solid var(--stroke); border-radius: 12px; padding: 20px 22px; width: 420px; max-width: calc(100vw - 32px); box-shadow: 0 8px 24px rgba(0, 0, 0, .18); } +dialog.dialog::backdrop { background: rgba(0, 0, 0, .25); } +dialog.dialog form { display: grid; gap: 14px; } +dialog.dialog h2 { font-size: 16px; } +dialog.dialog p { margin: 0; color: var(--text-muted); } +#toasts { position: fixed; right: 24px; bottom: 24px; display: grid; gap: 8px; z-index: 10; } +.toast { width: 420px; max-width: calc(100vw - 48px); padding: 12px 14px; background: var(--card); border: 1px solid var(--stroke); border-left: 3px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px rgba(0, 0, 0, .12); } +.toast.error { border-left-color: var(--error); } + +/* About */ +.about dl { display: grid; grid-template-columns: 180px 1fr; gap: 8px 16px; margin: 0; } +.about dt { color: var(--text-muted); } +.about dd { margin: 0; overflow-wrap: anywhere; } /* Login */ .login { min-height: 100vh; display: grid; place-items: center; padding: 16px; } .login form { width: 360px; max-width: 100%; display: grid; gap: 14px; } .login .brand { padding: 0 0 8px; } +.login h1 { font-size: 16px; font-weight: 600; } .login label { display: grid; gap: 6px; color: var(--text-muted); } -.login .error { color: var(--error); min-height: 18px; } +.login .row { display: flex; gap: 8px; } -@media (max-width: 800px) { +@media (max-width: 900px) { .shell { grid-template-columns: 1fr; } - .sidebar { flex-direction: row; overflow-x: auto; padding: 8px; } + .sidebar { flex-direction: row; overflow-x: auto; padding: 8px; position: static; height: auto; } .sidebar .brand, .sidebar .user { display: none; } .nav { display: flex; gap: 4px; } - .nav a span { display: none; } + .nav a span:not(.badge) { display: none; } + .split, .grid.wide-right { grid-template-columns: 1fr; } + .side { width: auto; } + .field { grid-template-columns: 1fr; } } diff --git a/src/Titano.Server/Admin/web/api.js b/src/Titano.Server/Admin/web/api.js index 55d66e9d..b64edf04 100644 --- a/src/Titano.Server/Admin/web/api.js +++ b/src/Titano.Server/Admin/web/api.js @@ -1,13 +1,16 @@ -// Same API as the desktop clients: cookie session + double-submit CSRF token for the web admin (BRIEF §14.2). +// Same API as the desktop clients: cookie session + CSRF header for the web admin (BRIEF §14.2). +import { culture } from "./i18n.js"; + export class ApiFailure extends Error { - constructor(status, code, message) { + constructor(status, code, message, details) { super(message); this.status = status; this.code = code; + this.details = details; } } -const SESSION_KEY = "titano.admin.user"; +let currentUser = null; function csrfToken() { const m = document.cookie.match(/(?:^|; )titano_csrf=([^;]+)/); @@ -15,15 +18,27 @@ function csrfToken() { } async function request(method, url, body) { - const headers = { Accept: "application/json" }; + const headers = { Accept: "application/json", "Accept-Language": culture() }; if (body !== undefined) headers["Content-Type"] = "application/json"; if (method !== "GET") headers["X-CSRF-Token"] = csrfToken(); - const res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) }); - if (res.status === 401 && url !== "/api/v1/auth/login") sessionStorage.removeItem(SESSION_KEY); + let res; + try { + res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) }); + } catch { + throw new ApiFailure(0, "unreachable", ""); + } + if (res.status === 401 && url !== "/api/v1/auth/login") { + currentUser = null; + window.dispatchEvent(new Event("titano:signed-out")); + } if (!res.ok) { let err = { code: "http_" + res.status, message: res.statusText }; - try { err = await res.json(); } catch { /* non-JSON error */ } - throw new ApiFailure(res.status, err.code, err.message); + try { + err = await res.json(); + } catch { + // Not a JSON error body. + } + throw new ApiFailure(res.status, err.code, err.message, err.details); } return res.status === 204 ? null : res.json(); } @@ -31,17 +46,71 @@ async function request(method, url, body) { export const api = { get: (url) => request("GET", url), post: (url, body) => request("POST", url, body ?? {}), + put: (url, body) => request("PUT", url, body), patch: (url, body) => request("PATCH", url, body), del: (url) => request("DELETE", url), - isSignedIn: () => sessionStorage.getItem(SESSION_KEY) !== null, - user: () => JSON.parse(sessionStorage.getItem(SESSION_KEY) ?? "null"), + user: () => currentUser, + + /** Restores the session from the cookie; null when signed out. */ + async resume() { + try { + currentUser = await request("GET", "/api/v1/auth/me"); + } catch { + currentUser = null; + } + return currentUser; + }, + async signIn(username, password) { const r = await request("POST", "/api/v1/auth/login", { username, password, clientName: "admin-web", cookie: true }); - sessionStorage.setItem(SESSION_KEY, JSON.stringify(r.user)); + currentUser = r.user; return r; }, + + async changePassword(currentPassword, newPassword) { + await request("POST", "/api/v1/auth/password", { currentPassword, newPassword }); + currentUser = await request("GET", "/api/v1/auth/me"); + }, + async signOut() { - try { await request("POST", "/api/v1/auth/logout", {}); } catch { /* already gone */ } - sessionStorage.removeItem(SESSION_KEY); + try { + await request("POST", "/api/v1/auth/logout", {}); + } catch { + // Already signed out. + } + currentUser = null; + }, + + /** Server events over WebSocket (cookie session), reconnecting with back-off until stop() is called. */ + events(onEvent) { + let socket = null; + let stopped = false; + let delay = 1000; + const connect = () => { + if (stopped) return; + socket = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/v1/events`); + socket.onopen = () => { + delay = 1000; + }; + socket.onmessage = (m) => { + try { + onEvent(JSON.parse(m.data)); + } catch { + // Ignore malformed or unknown events. + } + }; + socket.onclose = () => { + if (stopped) return; + setTimeout(connect, delay); + delay = Math.min(delay * 2, 30000); + }; + }; + connect(); + return { + stop() { + stopped = true; + socket?.close(); + }, + }; }, }; diff --git a/src/Titano.Server/Admin/web/app.js b/src/Titano.Server/Admin/web/app.js index c6295f82..29d8834a 100644 --- a/src/Titano.Server/Admin/web/app.js +++ b/src/Titano.Server/Admin/web/app.js @@ -1,42 +1,53 @@ // Titano Server admin panel — vanilla ES modules, no build step (BRIEF §14.8). import { api, ApiFailure } from "./api.js"; -import { t, loadStrings, applyStrings } from "./i18n.js"; +import { t, loadStrings, applyStrings, setLanguage, languages, culture } from "./i18n.js"; import { icons } from "./icons.js"; +import { escapeHtml, attr, errorText, nativeName } from "./ui.js"; const app = document.getElementById("app"); const pages = ["dashboard", "users", "archive", "jobs", "settings", "logs", "about"]; -const pageIcon = { dashboard: "dashboard", users: "users", archive: "archive", jobs: "jobs", settings: "settings", logs: "logs", about: "about" }; let info = null; +let events = null; +const listeners = new Set(); async function start() { - await loadStrings(navigator.language); + await loadStrings(); info = await api.get("/api/v1/server/info").catch(() => null); + await api.resume(); window.addEventListener("hashchange", render); + window.addEventListener("titano:signed-out", () => { + events?.stop(); + events = null; + render(); + }); render(); } function currentPage() { - const p = location.hash.replace(/^#\/?/, ""); + const p = location.hash.replace(/^#\/?/, "").split("?")[0]; return pages.includes(p) ? p : "dashboard"; } function render() { - if (!api.isSignedIn()) { - renderLogin(); - return; - } + const user = api.user(); + if (!user) return renderLogin(); + if (user.mustChangePassword) return renderPasswordChange(); renderShell(currentPage()); } -function renderLogin() { +function brand() { + return `
Titano Server${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}
`; +} + +function renderLogin(message = "") { app.innerHTML = `
-
Titano Server${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}
- - - + ${brand()} + + +
`; @@ -48,10 +59,56 @@ function renderLogin() { error.textContent = ""; const data = new FormData(form); try { - await api.signIn(String(data.get("username")), String(data.get("password"))); + const r = await api.signIn(String(data.get("username")), String(data.get("password"))); + if (r.user.role !== "admin") { + await api.signOut(); + error.textContent = t("Admin.Login.NotAdmin"); + return; + } render(); } catch (err) { - error.textContent = err instanceof ApiFailure && err.status === 401 ? t("Admin.Login.Failed") : t("Admin.Error.Unreachable"); + error.textContent = err instanceof ApiFailure && err.status === 401 ? t("Admin.Login.Failed") : errorText(err); + } + }); + form.querySelector("input").focus(); +} + +function renderPasswordChange() { + app.innerHTML = ` +
+
+ ${brand()} +

+ + + + +
+ + + +
+
+
`; + applyStrings(app); + const form = app.querySelector("form"); + const error = form.querySelector(".error"); + app.querySelector("#cancel").addEventListener("click", async () => { + await api.signOut(); + render(); + }); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + const data = new FormData(form); + if (data.get("next") !== data.get("repeat")) { + error.textContent = t("Admin.Password.Mismatch"); + return; + } + try { + await api.changePassword(String(data.get("current")), String(data.get("next"))); + render(); + } catch (err) { + error.textContent = errorText(err); } }); form.querySelector("input").focus(); @@ -59,40 +116,82 @@ function renderLogin() { function renderShell(page) { const nav = pages.map((p) => ` - ${icons[pageIcon[p]]}`).join(""); + ${icons[p]}`).join(""); const user = api.user(); + const options = languages().map((code) => ``).join(""); app.innerHTML = `
-

+
+

+ + + + +
`; applyStrings(app); app.querySelector("#signout").addEventListener("click", async () => { + events?.stop(); + events = null; await api.signOut(); render(); }); + app.querySelector("#language").addEventListener("change", async (e) => { + await setLanguage(e.target.value); + render(); + }); + events ??= api.events((e) => listeners.forEach((fn) => fn(e))); + listeners.clear(); + updateBadges(); + listeners.add((e) => { + if (e.type === "jobState") updateBadges(); + }); + const content = app.querySelector("#content"); + const context = { + api, + info, + meta: app.querySelector("#meta"), + actions: app.querySelector("#actions"), + onEvent: (fn) => listeners.add(fn), + }; import(`./pages/${page}.js`) - .then((m) => m.render(content, { api, t, info, meta: app.querySelector("#meta") })) - .catch(() => { - content.innerHTML = `
`; - applyStrings(content); + .then((m) => m.render(content, context)) + .catch((err) => { + content.innerHTML = `
${escapeHtml(errorText(err))}
`; }); } -export function escapeHtml(s) { - return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +let badgeTimer = null; + +/** Running jobs and accounts, as nav badges (refreshed at most every two seconds). */ +function updateBadges() { + if (badgeTimer) return; + badgeTimer = setTimeout(() => { + badgeTimer = null; + }, 2000); + api.get("/api/v1/jobs?state=running&limit=100").then((page) => setBadge("jobs", page.items.length, true)).catch(() => {}); + api.get("/api/v1/users").then((users) => setBadge("users", users.length, false)).catch(() => {}); +} + +function setBadge(page, count, accent) { + const badge = document.getElementById(`badge-${page}`); + if (!badge) return; + badge.hidden = count === 0; + badge.textContent = String(count); + badge.classList.toggle("quiet", !accent); } function cap(s) { diff --git a/src/Titano.Server/Admin/web/i18n.js b/src/Titano.Server/Admin/web/i18n.js index 3b50350c..5014e5ef 100644 --- a/src/Titano.Server/Admin/web/i18n.js +++ b/src/Titano.Server/Admin/web/i18n.js @@ -1,9 +1,17 @@ // Strings come from /api/v1/i18n/{culture}, generated from the same .resx catalog as the desktop apps. +const LANGUAGE_KEY = "titano.admin.language"; let strings = {}; -export async function loadStrings(culture) { +/** Loads the strings of the chosen language (remembered per browser), else of the browser's language. */ +export async function loadStrings(requested) { + let preferred = requested; try { - const res = await fetch(`/api/v1/i18n/${encodeURIComponent(culture || "en")}`); + preferred ??= localStorage.getItem(LANGUAGE_KEY); + } catch { + // Storage may be blocked; the browser language is used. + } + try { + const res = await fetch(`/api/v1/i18n/${encodeURIComponent(preferred || navigator.language || "en")}`); strings = await res.json(); } catch { strings = {}; @@ -12,16 +20,47 @@ export async function loadStrings(culture) { document.documentElement.dir = strings.$rtl === "true" ? "rtl" : "ltr"; } +export async function setLanguage(code) { + try { + localStorage.setItem(LANGUAGE_KEY, code); + } catch { + // Only this session uses the language then. + } + await loadStrings(code); +} + +/** The current culture (e.g. "it"), used for numbers, dates and the Accept-Language of API calls. */ +export function culture() { + return strings.$culture || "en"; +} + +/** Languages with translated strings, as codes. */ +export function languages() { + return (strings.$languages || "en").split(","); +} + /** Localized string for key with {0}, {1}… placeholders filled from args. */ export function t(key, ...args) { const s = strings[key]; if (s === undefined) return `⟦${key}⟧`; - return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => (args[Number(i)] ?? "")); + return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => String(args[Number(i)] ?? "")); } -/** Fills data-i18n (text), data-i18n-title (tooltip) and data-i18n-placeholder attributes. */ +/** True when the catalog has the key (for keys built from data, e.g. audit actions). */ +export function has(key) { + return strings[key] !== undefined; +} + +/** Fills data-i18n (text), data-i18n-title (tooltip, also the accessible name of icon buttons) and data-i18n-placeholder. */ export function applyStrings(root) { - root.querySelectorAll("[data-i18n]").forEach((el) => { el.textContent = t(el.dataset.i18n); }); - root.querySelectorAll("[data-i18n-title]").forEach((el) => { el.title = t(el.dataset.i18nTitle); }); - root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => { el.placeholder = t(el.dataset.i18nPlaceholder); }); + root.querySelectorAll("[data-i18n]").forEach((el) => { + el.textContent = t(el.dataset.i18n); + }); + root.querySelectorAll("[data-i18n-title]").forEach((el) => { + el.title = t(el.dataset.i18nTitle); + if (el.classList.contains("icon")) el.setAttribute("aria-label", el.title); + }); + root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => { + el.placeholder = t(el.dataset.i18nPlaceholder); + }); } diff --git a/src/Titano.Server/Admin/web/icons.js b/src/Titano.Server/Admin/web/icons.js index 1ea443a0..73e78d2d 100644 --- a/src/Titano.Server/Admin/web/icons.js +++ b/src/Titano.Server/Admin/web/icons.js @@ -12,5 +12,6 @@ export const icons = { refresh: ``, close: ``, plus: ``, + copy: ``, search: ``, }; diff --git a/src/Titano.Server/Admin/web/jobs.js b/src/Titano.Server/Admin/web/jobs.js new file mode 100644 index 00000000..bd0d6b41 --- /dev/null +++ b/src/Titano.Server/Admin/web/jobs.js @@ -0,0 +1,41 @@ +// Job and node labels shared by the dashboard and the Jobs page. +import { t, has } from "./i18n.js"; +import { escapeHtml, attr, bar } from "./ui.js"; + +export function pascal(text) { + return String(text).split(/[-_]/).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join(""); +} + +export function kindLabel(kind) { + const key = `Admin.Job.Kind.${pascal(kind)}`; + return has(key) ? t(key) : kind; +} + +export function stateLabel(state) { + const key = `Admin.Job.State.${pascal(state)}`; + return has(key) ? t(key) : state; +} + +/** Where a job runs: this server, a render node by name, or nowhere yet. */ +export function nodeLabel(job, nodes) { + if (!job.nodeId) return "—"; + if (job.nodeId.startsWith("server:")) return t("Admin.Jobs.Server"); + return nodes.find((n) => n.id === job.nodeId)?.clientName ?? "—"; +} + +export function progressCell(job) { + if (job.progressTotal <= 0) return `
${bar(0, true)}—
`; + const fraction = job.progressDone / job.progressTotal; + return `
${bar(fraction)}${Math.floor(fraction * 100)} %
`; +} + +export function stateCell(state) { + const glyph = { running: "◐", queued: "○", paused: "❚❚", done: "●", failed: "✕", cancelled: "○" }[state] ?? ""; + return `${glyph} ${escapeHtml(stateLabel(state))}`; +} + +/** Node encoders as "NVENC HEVC/H.264/AV1". */ +export function encoders(node) { + const names = [...new Set(node.encoders.map((e) => e.codec.toUpperCase()))]; + return names.join("/"); +} diff --git a/src/Titano.Server/Admin/web/pages/about.js b/src/Titano.Server/Admin/web/pages/about.js index 1228e1fe..f287dd9c 100644 --- a/src/Titano.Server/Admin/web/pages/about.js +++ b/src/Titano.Server/Admin/web/pages/about.js @@ -1,12 +1,21 @@ +// About: version, API, database, uptime and the certificate fingerprint clients are asked to trust. import { applyStrings } from "../i18n.js"; -import { escapeHtml } from "../app.js"; +import { escapeHtml, formatDuration } from "../ui.js"; -export async function render(root, { info }) { +export async function render(root, { api, info }) { + const dashboard = await api.get("/api/v1/server/dashboard").catch(() => null); + const rows = [ + ["Admin.About.Name", info?.name], + ["Admin.About.Version", info?.version], + ["Admin.About.Api", info?.apiVersion], + ["Admin.About.Database", dashboard?.database], + ["Admin.About.Uptime", dashboard ? formatDuration(dashboard.uptimeSeconds) : null], + ["Admin.About.Fingerprint", info?.tlsFingerprint], + ]; root.innerHTML = ` -
-

-

Titano Server ${escapeHtml(info?.version ?? "")} · API ${escapeHtml(String(info?.apiVersion ?? ""))}

-

${escapeHtml(info?.tlsFingerprint ?? "–")}

+
+
+
${rows.map(([key, value]) => `
${escapeHtml(value ?? "—")}
`).join("")}
`; applyStrings(root); } diff --git a/src/Titano.Server/Admin/web/pages/archive.js b/src/Titano.Server/Admin/web/pages/archive.js new file mode 100644 index 00000000..6190bcd0 --- /dev/null +++ b/src/Titano.Server/Admin/web/pages/archive.js @@ -0,0 +1,109 @@ +// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics. +import { t, applyStrings } from "../i18n.js"; +import { escapeHtml, attr, formatBytes, formatNumber, bar, columns, toast, errorText } from "../ui.js"; + +const PROXY_SIZES = [-1, 1280, 1920, 2560, 3840, 0]; +const ACTIONS = ["scan", "rebuild", "verify", "maintenance"]; + +export async function render(root, { api, meta }) { + let settings; + let stats; + try { + [settings, stats] = await Promise.all([api.get("/api/v1/archive/settings"), api.get("/api/v1/archive/stats")]); + } catch (err) { + root.innerHTML = `
${escapeHtml(errorText(err))}
`; + return; + } + meta.textContent = settings.rootPath; + const used = stats.capacityBytes > 0 ? (stats.capacityBytes - stats.freeBytes) / stats.capacityBytes : 0; + const sizes = PROXY_SIZES.includes(settings.proxyLongEdge) ? PROXY_SIZES : [settings.proxyLongEdge, ...PROXY_SIZES]; + const proxyOptions = sizes.map((size) => ``).join(""); + + root.innerHTML = ` +
+
${formatNumber(stats.sequences)} + ${escapeHtml(t("Admin.Dashboard.PhotosCameras", formatNumber(stats.photos), formatNumber(stats.cameras)))}
+
${escapeHtml(formatBytes(stats.bytes))} + ${escapeHtml(stats.firstYear ? `${stats.firstYear}–${stats.lastYear}` : "—")}
+
${escapeHtml(formatBytes(stats.freeBytes))} + ${bar(used)}${escapeHtml(t("Admin.Dashboard.Of", formatBytes(stats.capacityBytes)))}
+
${formatNumber(stats.unverifiedSequences)} + ${escapeHtml(t("Admin.Dashboard.NoProxies", formatNumber(stats.sequencesWithoutProxies)))}
+
+
+
+

+ + + + +
+
+
+

+
${ACTIONS.map((a) => ``).join("")}
+

+
+ ${stats.byCamera.slice(0, 8).map((c) => `
${escapeHtml(c.key || "—")}${formatNumber(c.count)}${escapeHtml(formatBytes(c.bytes))}
`).join("") + || `

`} +
+
+
+
+

+ ${stats.byYear.length === 0 ? `

` + : columns(stats.byYear.map((y) => ({ label: y.key, value: y.bytes, title: `${y.key} · ${formatBytes(y.bytes)}` })), { valueLabel: (i) => formatBytes(i.value) })}
+

+
+ ${stats.byFormat.map((f) => `
${escapeHtml(f.key.toUpperCase())}${formatNumber(f.count)}${escapeHtml(formatBytes(f.bytes))}
`).join("") + || `

`} +
+
`; + applyStrings(root); + + const form = root.querySelector("form"); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + form.querySelectorAll("[aria-invalid]").forEach((el) => el.removeAttribute("aria-invalid")); + const data = new FormData(form); + try { + settings = await api.put("/api/v1/archive/settings", { + ...settings, + name: String(data.get("name")).trim(), + folderTemplate: String(data.get("folderTemplate")), + fileTemplate: String(data.get("fileTemplate")), + proxyLongEdge: Number(data.get("proxyLongEdge")), + }); + toast(t("Admin.Common.Saved")); + } catch (err) { + // Errors name the field in details; the field gets the error border and the message as its tooltip. + const field = err.details && form.elements[err.details]; + if (field) { + field.setAttribute("aria-invalid", "true"); + field.title = errorText(err); + } + toast(errorText(err), true); + } + }); + root.querySelectorAll("[data-action]").forEach((button) => button.addEventListener("click", async () => { + button.disabled = true; + try { + await api.post(`/api/v1/archive/${button.dataset.action}`); + toast(t("Admin.Archive.Queued")); + } catch (err) { + toast(errorText(err), true); + } finally { + button.disabled = false; + } + })); +} + +function proxyLabel(size) { + if (size === -1) return t("Admin.Archive.ProxiesOff"); + if (size === 0) return t("Admin.Archive.ProxiesFull"); + return t("Admin.Archive.ProxiesEdge", size); +} + +function cap(s) { + return s.charAt(0).toUpperCase() + s.slice(1); +} diff --git a/src/Titano.Server/Admin/web/pages/dashboard.js b/src/Titano.Server/Admin/web/pages/dashboard.js index 4a4ab432..697d83b4 100644 --- a/src/Titano.Server/Admin/web/pages/dashboard.js +++ b/src/Titano.Server/Admin/web/pages/dashboard.js @@ -1,18 +1,131 @@ -// Dashboard: storage, archive, jobs, render nodes (BRIEF §14.8). Data from the public API only. -import { applyStrings } from "../i18n.js"; +// Dashboard (mockup Admin.html, BRIEF §14.8): storage, archive, jobs, render nodes, charts, activity, active jobs. +import { t, has, applyStrings } from "../i18n.js"; +import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText } from "../ui.js"; +import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders, pascal } from "../jobs.js"; -export async function render(root, { api, t, info, meta }) { - const health = await api.get("/health").catch(() => null); - meta.textContent = info ? `v${info.version} · TLS ${info.tlsFingerprint ? "auto" : "proxy"}` : ""; - root.innerHTML = ` -
-
-
${health?.status === "ok" ? `●` : `✕`}${health?.status ?? ""}
-
${info?.name ?? ""}
-
-
${health?.checks?.archive === "ok" ? `●` : `▲`}${health?.checks?.archive ?? ""}
-
-
${info?.apiVersion ?? "–"}
${(info?.capabilities ?? []).join(" · ")}
-
`; - applyStrings(root); +export async function render(root, { api, meta, onEvent }) { + let timer = null; + const refresh = () => { + clearTimeout(timer); + timer = setTimeout(load, 1500); + }; + + async function load() { + let d; + try { + d = await api.get("/api/v1/server/dashboard"); + } catch (err) { + root.innerHTML = `
${escapeHtml(errorText(err))}
`; + return; + } + meta.textContent = t("Admin.Dashboard.Meta", formatDuration(d.uptimeSeconds), d.database, d.tlsMode, + t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff")); + const a = d.archive; + const used = a.capacityBytes > 0 ? (a.capacityBytes - a.freeBytes) / a.capacityBytes : 0; + const online = d.nodes.filter((n) => n.state !== "offline"); + const uploads = lastThirtyDays(d.uploads); + const totalUploads = uploads.reduce((s, u) => s + u.value, 0); + const peak = Math.max(0, ...uploads.map((u) => u.value)); + + root.innerHTML = ` +
+
+ + ${escapeHtml(formatBytes(a.capacityBytes - a.freeBytes))}${escapeHtml(t("Admin.Dashboard.Of", formatBytes(a.capacityBytes)))} + ${bar(used)} + ${escapeHtml(t("Admin.Dashboard.Free", formatBytes(a.freeBytes)))} · ${escapeHtml(t("Admin.Dashboard.Originals", formatBytes(a.bytes)))} +
+
+ + ${formatNumber(a.sequences)} + ${escapeHtml(t("Admin.Dashboard.PhotosCameras", formatNumber(a.photos), formatNumber(a.cameras)))} + ${escapeHtml(t("Admin.Dashboard.NoProxies", formatNumber(a.sequencesWithoutProxies)))} +
+
+ + ${formatNumber(d.jobs.running)} + ${escapeHtml(t("Admin.Dashboard.JobCounts", formatNumber(d.jobs.queued), formatNumber(d.jobs.doneToday), formatNumber(d.jobs.failedToday)))} + ${escapeHtml(t("Admin.Dashboard.Workers", formatNumber(d.workers)))} +
+
+ + ${formatNumber(online.length)} + ${online.slice(0, 2).map((n) => `${escapeHtml(n.clientName)} · ${escapeHtml(encoders(n))} · ${escapeHtml(stateLabel(n.state))}`).join("")} +
+
+
+
+

+ ${a.byYear.length === 0 ? `

` + : columns(a.byYear.map((y) => ({ label: y.key, value: y.bytes, title: `${y.key} · ${formatBytes(y.bytes)} · ${formatNumber(y.count)}` })), { valueLabel: (i) => formatBytes(i.value) })} +
+
+

+ ${escapeHtml(t("Admin.Dashboard.UploadTotals", formatNumber(totalUploads), formatNumber(peak)))}
+ ${columns(uploads, { sun: true })} +
+
+
+
+

+
${d.activity.map((e) => `${escapeHtml(formatTime(e.at))}${escapeHtml(activityText(e))}`).join("")}
+ ${d.activity.length === 0 ? `

` : ""} +
+
+

+ ${d.activeJobs.length === 0 ? `

` : ` +
+
+ ${d.activeJobs.map((j) => ` +
+ ${escapeHtml(kindLabel(j.kind))}${escapeHtml(j.targetLabel ?? "")}${escapeHtml(nodeLabel(j, d.nodes))} + ${progressCell(j)}${stateCell(j.state)} + +
`).join("")} +
`} +
+
`; + applyStrings(root); + root.querySelectorAll("[data-cancel]").forEach((button) => button.addEventListener("click", async () => { + button.disabled = true; + try { + await api.post(`/api/v1/jobs/${button.dataset.cancel}/cancel`); + refresh(); + } catch (err) { + toast(errorText(err), true); + button.disabled = false; + } + })); + } + + onEvent((e) => { + if (e.type === "jobProgress") { + const cell = root.querySelector(`[data-job="${CSS.escape(e.jobId)}"] .progress`); + if (cell) cell.innerHTML = progressCell({ progressDone: e.done, progressTotal: e.total }); + } else { + refresh(); + } + }); + await load(); +} + +/** One sentence per audit entry, e.g. "alberto signed in" (unknown actions show their code). */ +function activityText(entry) { + const key = `Admin.Activity.${pascal(entry.action)}`; + return has(key) ? t(key, entry.username ?? "—", entry.details ?? "") : `${entry.username ?? ""} ${entry.action}`; +} + +/** Frames per UTC day for the last 30 days, zero-filled. */ +function lastThirtyDays(days) { + const byDay = new Map(days.map((d) => [d.day, d.frames])); + const items = []; + const today = new Date(); + for (let i = 29; i >= 0; i--) { + const day = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate() - i)); + const key = day.toISOString().slice(0, 10); + const value = byDay.get(key) ?? 0; + const label = i === 29 || i === 0 ? new Intl.DateTimeFormat(document.documentElement.lang, { day: "numeric", month: "short" }).format(day) : ""; + items.push({ value, label, title: `${key} · ${formatNumber(value)}` }); + } + return items; } diff --git a/src/Titano.Server/Admin/web/pages/jobs.js b/src/Titano.Server/Admin/web/pages/jobs.js new file mode 100644 index 00000000..56f6e792 --- /dev/null +++ b/src/Titano.Server/Admin/web/pages/jobs.js @@ -0,0 +1,163 @@ +// Jobs (BRIEF §14.8): queue and history with cancel/pause/resume/retry/priority, log tails, render nodes. +import { t, applyStrings } from "../i18n.js"; +import { escapeHtml, attr, formatTime, formatDateTime, toast, errorText, confirmDialog } from "../ui.js"; +import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js"; + +const FILTERS = ["all", "running", "queued", "paused", "failed", "done", "cancelled"]; +const PRIORITIES = ["background", "normal", "user"]; + +export async function render(root, { api, meta, onEvent }) { + let filter = "all"; + let jobs = []; + let nodes = []; + let cursor = null; + const expanded = new Set(); + let timer = null; + + root.innerHTML = ` +
${FILTERS.map((f) => ``).join("")}
+
+
+
+
+
+
+
+
+
+

+
+
+
+
+
+
`; + applyStrings(root); + root.querySelectorAll("[data-filter]").forEach((chip) => chip.addEventListener("click", () => { + filter = chip.dataset.filter; + root.querySelectorAll("[data-filter]").forEach((c) => c.setAttribute("aria-pressed", String(c === chip))); + load(); + })); + root.querySelector("#more").addEventListener("click", () => load(true)); + + async function load(more = false) { + try { + const state = filter === "all" ? "" : `&state=${filter}`; + const page = await api.get(`/api/v1/jobs?limit=50${state}${more && cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`); + jobs = more ? jobs.concat(page.items) : page.items; + cursor = page.nextCursor; + nodes = await api.get("/api/v1/nodes"); + } catch (err) { + toast(errorText(err), true); + return; + } + const running = jobs.filter((j) => j.state === "running").length; + meta.textContent = t("Admin.Jobs.Meta", running, nodes.filter((n) => n.state !== "offline").length); + draw(); + } + + function draw() { + const host = root.querySelector("#rows"); + host.innerHTML = jobs.map((j) => ` +
+ + ${escapeHtml(j.targetLabel ?? "")} + ${escapeHtml(nodeLabel(j, nodes))} + ${progressCell(j)} + ${stateCell(j.state)} + ${escapeHtml(formatTime(j.created))} + ${buttons(j)} +
+ ${expanded.has(j.id) ? `
${escapeHtml(j.error ? `${j.logTail ?? ""}\n${j.error}`.trim() : j.logTail ?? "")}
` : ""}`).join("") + || `
`; + applyStrings(host); + host.querySelectorAll("[data-toggle]").forEach((b) => b.addEventListener("click", () => { + const id = b.dataset.toggle; + if (!expanded.delete(id)) expanded.add(id); + draw(); + })); + host.querySelectorAll("[data-act]").forEach((b) => b.addEventListener("click", () => act(b.closest(".row").dataset.job, b.dataset.act))); + host.querySelectorAll("select[data-priority]").forEach((s) => s.addEventListener("change", () => setPriority(s.dataset.priority, s.value))); + root.querySelector("#more").hidden = !cursor; + + const nodeHost = root.querySelector("#nodes"); + nodeHost.innerHTML = nodes.map((n) => ` +
+ ${escapeHtml(n.clientName)}${escapeHtml(n.username)} + ${escapeHtml(encoders(n))} + ${escapeHtml(formatDateTime(n.lastHeartbeat))} + ${n.state === "offline" ? "○" : "●"} ${escapeHtml(stateLabel(n.state))} + +
`).join("") || `
`; + applyStrings(nodeHost); + nodeHost.querySelectorAll("[data-forget]").forEach((b) => b.addEventListener("click", () => forget(nodes.find((n) => n.id === b.dataset.forget)))); + } + + function buttons(job) { + const button = (act, key) => ``; + const priority = ``; + switch (job.state) { + case "running": return button("pause", "Pause") + button("cancel", "Cancel"); + case "queued": return priority + button("pause", "Pause") + button("cancel", "Remove"); + case "paused": return priority + button("resume", "Resume") + button("cancel", "Cancel"); + case "failed": + case "cancelled": return button("retry", "Retry"); + default: return ""; + } + } + + async function act(id, action) { + try { + await api.post(`/api/v1/jobs/${id}/${action}`); + await load(); + } catch (err) { + toast(errorText(err), true); + } + } + + async function setPriority(id, priority) { + try { + await api.post(`/api/v1/jobs/${id}/priority`, { priority }); + } catch (err) { + toast(errorText(err), true); + } + } + + async function forget(node) { + const confirmed = await confirmDialog({ + title: t("Admin.Jobs.ForgetTitle", node.clientName), + confirm: t("Admin.Jobs.Forget"), + confirmTip: t("Admin.Jobs.Forget.Tip"), + cancel: t("Admin.Common.Keep"), + cancelTip: t("Admin.Common.Keep.Tip"), + }); + if (!confirmed) return; + try { + await api.del(`/api/v1/nodes/${node.id}`); + await load(); + } catch (err) { + toast(errorText(err), true); + } + } + + onEvent((e) => { + if (e.type === "jobProgress") { + const job = jobs.find((j) => j.id === e.jobId); + if (job) { + job.progressDone = e.done; + job.progressTotal = e.total; + const cell = root.querySelector(`[data-job="${CSS.escape(e.jobId)}"] .progress`); + if (cell) cell.innerHTML = progressCell(job); + } + } else if (e.type === "jobState" || e.type === "nodeState") { + clearTimeout(timer); + timer = setTimeout(load, 800); + } + }); + await load(); +} + +function cap(s) { + return s.charAt(0).toUpperCase() + s.slice(1); +} diff --git a/src/Titano.Server/Admin/web/pages/logs.js b/src/Titano.Server/Admin/web/pages/logs.js new file mode 100644 index 00000000..25375c88 --- /dev/null +++ b/src/Titano.Server/Admin/web/pages/logs.js @@ -0,0 +1,104 @@ +// Logs (BRIEF §14.8): server log tail and downloads, sign-in log, audit log. +import { t, has, applyStrings } from "../i18n.js"; +import { escapeHtml, attr, formatBytes, formatDateTime, toast, errorText, routeParams } from "../ui.js"; +import { pascal } from "../jobs.js"; + +const VIEWS = ["server", "signins", "audit"]; +const LINES = [100, 300, 1000]; + +export async function render(root, { api, meta, actions }) { + let view = VIEWS.includes(routeParams().get("view")) ? routeParams().get("view") : "server"; + let lines = 300; + let audit = []; + let cursor = null; + + actions.innerHTML = `
${VIEWS.map((v) => + ``).join("")}
`; + applyStrings(actions); + actions.querySelectorAll("[data-view]").forEach((b) => b.addEventListener("click", () => { + view = b.dataset.view; + actions.querySelectorAll("[data-view]").forEach((x) => x.setAttribute("aria-pressed", String(x === b))); + history.replaceState(null, "", `#/logs?view=${view}`); + show(); + })); + + async function show() { + meta.textContent = ""; + if (view === "server") await showServerLog(); + else await showAudit(false); + } + + async function showServerLog() { + let tail; + let files; + try { + [tail, files] = await Promise.all([api.get(`/api/v1/logs?lines=${lines}`), api.get("/api/v1/logs/files")]); + } catch (err) { + toast(errorText(err), true); + return; + } + meta.textContent = tail.file; + root.innerHTML = ` +
+
+ + + +
+
${escapeHtml(tail.lines.join("\n"))}
+
+
+

+
${files.map((f) => ` +
${escapeHtml(f.name)}${escapeHtml(formatBytes(f.size))} + ${escapeHtml(formatDateTime(f.modified))} +
`).join("")} +
+
`; + applyStrings(root); + const pre = root.querySelector("pre"); + pre.scrollTop = pre.scrollHeight; + root.querySelector("#lines").addEventListener("change", (e) => { + lines = Number(e.target.value); + showServerLog(); + }); + root.querySelector("#refresh").addEventListener("click", showServerLog); + } + + async function showAudit(more) { + const action = view === "signins" ? "&action=login" : ""; + try { + const page = await api.get(`/api/v1/audit?limit=100${action}${more && cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`); + audit = more ? audit.concat(page.items) : page.items; + cursor = page.nextCursor; + } catch (err) { + toast(errorText(err), true); + return; + } + root.innerHTML = ` +
+
+
+
+ ${audit.map((e) => ` +
${escapeHtml(formatDateTime(e.at))}${escapeHtml(e.username ?? "—")} + ${escapeHtml(actionLabel(e.action))}${escapeHtml(e.details ?? "")} + ${escapeHtml(e.remoteAddress ?? "")}
`).join("") || `
`} +
+
+
`; + applyStrings(root); + root.querySelector("#more").addEventListener("click", () => showAudit(true)); + } + + await show(); +} + +function actionLabel(action) { + const key = `Admin.Logs.Action.${pascal(action)}`; + return has(key) ? t(key) : action; +} + +function cap(s) { + return s.charAt(0).toUpperCase() + s.slice(1); +} diff --git a/src/Titano.Server/Admin/web/pages/settings.js b/src/Titano.Server/Admin/web/pages/settings.js new file mode 100644 index 00000000..24cd050b --- /dev/null +++ b/src/Titano.Server/Admin/web/pages/settings.js @@ -0,0 +1,108 @@ +// Settings (BRIEF §14.8): server name, ports, TLS, discovery, limits, language, retention. Values fixed by environment +// variables are read-only here; ports, TLS, workers, chunk size and job history apply at the next restart. +import { t, applyStrings, languages } from "../i18n.js"; +import { escapeHtml, attr, toast, errorText, nativeName } from "../ui.js"; + +/** Setting → environment variable that can fix it (BRIEF §14.9). */ +const VARIABLES = { + serverName: "TITANO_SERVER_NAME", httpPort: "TITANO_HTTP_PORT", httpsPort: "TITANO_HTTPS_PORT", tlsMode: "TITANO_TLS_MODE", + tlsCert: "TITANO_TLS_CERT", tlsKey: "TITANO_TLS_KEY", language: "TITANO_LANG", workers: "TITANO_WORKERS", discovery: "TITANO_DISCOVERY", +}; +const MB = 1e6; +const MIB = 1024 * 1024; + +export async function render(root, { api, info, meta }) { + let settings; + try { + settings = await api.get("/api/v1/server/settings"); + } catch (err) { + root.innerHTML = `
${escapeHtml(errorText(err))}
`; + return; + } + + const locked = (name) => settings.locked.some((l) => l.toLowerCase() === name.toLowerCase()); + const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", VARIABLES[name] ?? name))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`; + const field = (name, input) => ``; + const number = (name, value, attrs = "") => field(name, ``); + const text = (name, value) => field(name, ``); + + function draw() { + meta.textContent = ""; + root.innerHTML = ` +
+
+

+ ${settings.restartRequired ? `` : ""}
+ ${text("serverName", settings.serverName)} + ${field("language", ``)} + ${number("workers", settings.workers, 'min="1" max="64"')} + ${field("discovery", ``)} +
+
+

+ ${number("httpPort", settings.httpPort, 'min="1" max="65535"')} + ${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')} + ${field("tlsMode", ``)} + ${text("tlsCert", settings.tlsCert)} + ${text("tlsKey", settings.tlsKey)} + ${field("fingerprint", ``)} +
+
+

+ ${number("maxUploadMb", Math.round(settings.maxUploadBytes / MB), 'min="1"')} + ${number("chunkSizeMib", settings.chunkSizeBytes / MIB, 'min="0.0625" max="64" step="0.0625"')} + ${number("tokenLifetimeDays", settings.tokenLifetimeDays, 'min="1" max="365"')} + ${number("uploadRetentionHours", settings.uploadRetentionHours, 'min="1" max="8760"')} + ${number("jobHistoryDays", settings.jobHistoryDays, 'min="1" max="3650"')} +
+
+
`; + applyStrings(root); + root.querySelector("form").addEventListener("submit", save); + } + + async function save(e) { + e.preventDefault(); + const form = e.target; + const data = new FormData(form); + const value = (name, fallback) => (form.elements[name]?.disabled ? fallback : data.get(name)); + const request = { + ...settings, + serverName: String(value("serverName", settings.serverName)).trim(), + language: String(value("language", settings.language)), + workers: Number(value("workers", settings.workers)), + discovery: form.elements.discovery.disabled ? settings.discovery : form.elements.discovery.checked, + httpPort: Number(value("httpPort", settings.httpPort)), + httpsPort: Number(value("httpsPort", settings.httpsPort)), + tlsMode: String(value("tlsMode", settings.tlsMode)), + tlsCert: String(value("tlsCert", settings.tlsCert ?? "")).trim() || null, + tlsKey: String(value("tlsKey", settings.tlsKey ?? "")).trim() || null, + maxUploadBytes: Math.round(Number(data.get("maxUploadMb")) * MB), + chunkSizeBytes: Math.round(Number(data.get("chunkSizeMib")) * MIB), + tokenLifetimeDays: Number(data.get("tokenLifetimeDays")), + uploadRetentionHours: Number(data.get("uploadRetentionHours")), + jobHistoryDays: Number(data.get("jobHistoryDays")), + }; + try { + settings = await api.put("/api/v1/server/settings", request); + draw(); + toast(t("Admin.Common.Saved")); + } catch (err) { + toast(errorText(err), true); + const name = err.details && Object.keys(form.elements).find((k) => k.toLowerCase() === String(err.details).toLowerCase()); + const input = name ? form.elements[name] : null; + if (input) { + input.setAttribute("aria-invalid", "true"); + input.title = errorText(err); + } + } + } + + draw(); +} + +function cap(s) { + return s.charAt(0).toUpperCase() + s.slice(1); +} diff --git a/src/Titano.Server/Admin/web/pages/users.js b/src/Titano.Server/Admin/web/pages/users.js new file mode 100644 index 00000000..1b11f918 --- /dev/null +++ b/src/Titano.Server/Admin/web/pages/users.js @@ -0,0 +1,234 @@ +// Users (mockup AdminUsers.html, BRIEF §14.8): accounts table and a side panel to create, edit and reset. +import { t, applyStrings } from "../i18n.js"; +import { escapeHtml, attr, formatBytes, formatNumber, formatTime, bar, toast, confirmDialog, errorText } from "../ui.js"; +import { icons } from "../icons.js"; + +const ROLES = ["viewer", "uploader", "editor", "admin"]; +const TB = 1e12; +const RENDER_NODE = 32; + +export async function render(root, { api, info, meta, actions }) { + let users = []; + let filter = ""; + let freeBytes = 0; + let tokenDays = 30; + + actions.innerHTML = ` + + `; + applyStrings(actions); + actions.querySelector("#search").addEventListener("input", (e) => { + filter = e.target.value.trim().toLowerCase(); + drawTable(); + }); + actions.querySelector("#new").addEventListener("click", () => openForm(null)); + + root.innerHTML = ` +
+
+
+
+
+
+
+
+
+
+ +
`; + applyStrings(root); + + async function load() { + try { + const [list, stats, settings] = await Promise.all([ + api.get("/api/v1/users"), + api.get("/api/v1/archive/stats").catch(() => null), + api.get("/api/v1/server/settings").catch(() => null), + ]); + users = list; + freeBytes = stats?.freeBytes ?? 0; + tokenDays = settings?.tokenLifetimeDays ?? tokenDays; + } catch (err) { + toast(errorText(err), true); + return; + } + const active = users.filter((u) => !u.user.disabled).length; + meta.textContent = t("Admin.Users.Meta", formatNumber(users.length), formatNumber(active)); + root.querySelector("#policy").textContent = t("Admin.Users.Policy", info?.limits?.passwordMinLength ?? 10, tokenDays); + drawTable(); + } + + function drawTable() { + const rows = users.filter((u) => !filter || u.user.username.toLowerCase().includes(filter) || (u.user.displayName ?? "").toLowerCase().includes(filter)); + const host = root.querySelector("#rows"); + host.innerHTML = rows.map((row) => { + const u = row.user; + const subtitle = [u.displayName, u.mustChangePassword ? t("Admin.Users.MustChange") : null, u.disabled ? t("Admin.Users.Disabled") : null] + .filter(Boolean).join(" · "); + const quota = u.quotaBytes > 0 + ? `
${bar(u.usedBytes / u.quotaBytes, u.disabled)}${escapeHtml(t("Admin.Users.QuotaOf", formatBytes(u.usedBytes), formatBytes(u.quotaBytes)))}
` + : `${escapeHtml(u.usedBytes > 0 ? formatBytes(u.usedBytes) : "—")}`; + const seen = row.lastSeen ? `${formatTime(row.lastSeen)}${row.lastClient ? " · " + row.lastClient : ""}` : "—"; + const buttons = u.disabled + ? ` + ` + : ` + + ${u.id === api.user().id ? "" : ``}`; + return ` +
+ ${escapeHtml(u.username.slice(0, 1).toUpperCase())} + ${escapeHtml(u.username)}${escapeHtml(subtitle)} + + ${quota} + ${escapeHtml(seen)} + ${formatNumber(row.uploadsLast30Days)} + ${u.disabled ? "○" : "●"} + ${buttons} +
`; + }).join("") || `
`; + applyStrings(host); + host.querySelectorAll("[data-act]").forEach((button) => button.addEventListener("click", () => { + const row = users.find((u) => u.user.id === button.closest(".row").dataset.id); + act(button.dataset.act, row.user); + })); + } + + async function act(action, user) { + try { + if (action === "edit") return openForm(user); + if (action === "reset") { + const r = await api.post(`/api/v1/users/${user.id}/reset-password`, {}); + showPassword(r); + } else if (action === "disable" || action === "enable") { + await api.patch(`/api/v1/users/${user.id}`, { disabled: action === "disable" }); + } else if (action === "delete") { + const confirmed = await confirmDialog({ + title: t("Admin.Users.DeleteTitle", user.username), + body: t("Admin.Users.DeleteBody"), + confirm: t("Admin.Users.DeleteConfirm"), + confirmTip: t("Admin.Users.Delete.Tip"), + cancel: t("Admin.Common.Keep"), + cancelTip: t("Admin.Common.Keep.Tip"), + typed: user.username, + }); + if (!confirmed) return; + await api.del(`/api/v1/users/${user.id}`); + } + await load(); + } catch (err) { + toast(errorText(err), true); + } + } + + function openForm(user) { + const side = root.querySelector("#side"); + const editing = user !== null; + const quotaTb = editing && user.quotaBytes > 0 ? +(user.quotaBytes / TB).toFixed(3) : 0; + const renderNode = editing ? (user.permissions & RENDER_NODE) !== 0 : false; + side.hidden = false; + side.innerHTML = ` +
+

+ + +
+ ${ROLES.map((r) => ``).join("")} +
+ + ${editing ? "" : ` + + `} + + +
+ + +
+
`; + applyStrings(side); + const form = side.querySelector("form"); + side.querySelector("#close").addEventListener("click", () => { + side.hidden = true; + }); + side.querySelector("#regenerate")?.addEventListener("click", () => { + form.elements.password.value = generatePassword(); + }); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + const error = form.querySelector(".error"); + error.textContent = ""; + const data = new FormData(form); + const quotaBytes = Math.round(Number(data.get("quota") || 0) * TB); + try { + if (editing) { + await api.patch(`/api/v1/users/${user.id}`, { + displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes, allowRenderNode: data.get("renderNode") === "on", + }); + side.hidden = true; + } else { + const r = await api.post("/api/v1/users", { + username: String(data.get("username")).trim(), displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes, + password: String(data.get("password")), allowRenderNode: data.get("renderNode") === "on", + }); + showPassword(r); + } + await load(); + } catch (err) { + error.textContent = errorText(err); + } + }); + form.querySelector("input:not([disabled])").focus(); + } + + /** The one-time password of a new or reset account, shown once in the side panel. */ + function showPassword(result) { + const side = root.querySelector("#side"); + side.hidden = false; + side.innerHTML = ` +
+

${escapeHtml(result.user.username)}

+ +
+
`; + applyStrings(side); + side.querySelector("#copy").addEventListener("click", async () => { + try { + await navigator.clipboard.writeText(result.temporaryPassword); + toast(t("Admin.Users.Copied")); + } catch { + side.querySelector("input").select(); + } + }); + side.querySelector("#close").addEventListener("click", () => { + side.hidden = true; + }); + } + + await load(); +} + +/** Three groups of four unambiguous characters, like the server's own temporary passwords. */ +function generatePassword() { + const alphabet = "abcdefghjkmnpqrstuvwxyz23456789"; + const chars = []; + while (chars.length < 12) { + // Bytes at or above 248 (8 × 31) are skipped so every character is equally likely. + for (const b of crypto.getRandomValues(new Uint8Array(16))) { + if (b < 248 && chars.length < 12) chars.push(alphabet[b % alphabet.length]); + } + } + return `${chars.slice(0, 4).join("")}-${chars.slice(4, 8).join("")}-${chars.slice(8).join("")}`; +} + +function cap(s) { + return s.charAt(0).toUpperCase() + s.slice(1); +} diff --git a/src/Titano.Server/Admin/web/ui.js b/src/Titano.Server/Admin/web/ui.js new file mode 100644 index 00000000..a9f25e67 --- /dev/null +++ b/src/Titano.Server/Admin/web/ui.js @@ -0,0 +1,146 @@ +// Small DOM and formatting helpers shared by the admin pages. No inline styles: the panel runs under a strict CSP. +import { t, culture } from "./i18n.js"; + +export function escapeHtml(s) { + return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +} + +/** Escaped attribute value for title="…" tooltips. */ +export const attr = escapeHtml; + +export function formatNumber(n) { + return new Intl.NumberFormat(culture()).format(n ?? 0); +} + +/** 9.4 TB, 610 GB … (decimal units, like disk vendors and the desktop client). */ +export function formatBytes(bytes) { + const units = ["B", "KB", "MB", "GB", "TB", "PB"]; + let value = Number(bytes ?? 0); + let unit = 0; + while (value >= 1000 && unit < units.length - 1) { + value /= 1000; + unit++; + } + const digits = value >= 100 || unit === 0 ? 0 : 1; + return `${new Intl.NumberFormat(culture(), { maximumFractionDigits: digits }).format(value)} ${units[unit]}`; +} + +export function formatTime(iso) { + if (!iso) return "—"; + const date = new Date(iso); + const sameDay = new Date().toDateString() === date.toDateString(); + return new Intl.DateTimeFormat(culture(), sameDay ? { timeStyle: "short" } : { dateStyle: "medium" }).format(date); +} + +export function formatDateTime(iso) { + return iso ? new Intl.DateTimeFormat(culture(), { dateStyle: "short", timeStyle: "medium" }).format(new Date(iso)) : "—"; +} + +export function formatDuration(seconds) { + const s = Math.max(0, Math.round(seconds ?? 0)); + if (s >= 86400) return t("Common.Duration.Days", Math.floor(s / 86400), Math.floor((s % 86400) / 3600)); + if (s >= 3600) return t("Common.Duration.Hours", Math.floor(s / 3600), Math.floor((s % 3600) / 60)); + if (s >= 60) return t("Common.Duration.Minutes", Math.floor(s / 60)); + return t("Common.Duration.Seconds", s); +} + +/** 6 px progress bar drawn as SVG (attributes, not inline styles). */ +export function bar(fraction, muted = false) { + const width = Math.max(0, Math.min(100, Math.round((fraction ?? 0) * 100))); + return ``; +} + +/** + * Column chart: values with labels under each bar and, when given, the value above it. + * Bars use the accent colour, or the sun colour for upload activity. + */ +export function columns(items, { sun = false, valueLabel = null, height = 190 } = {}) { + const width = 400; + const base = height - 30; + const max = Math.max(1, ...items.map((i) => i.value)); + const step = width / Math.max(1, items.length); + const barWidth = Math.max(2, Math.min(32, step * 0.65)); + let svg = ``; + svg += ``; + items.forEach((item, i) => { + const h = item.value > 0 ? Math.max(2, (item.value / max) * (base - 18)) : 0; + const x = i * step + (step - barWidth) / 2; + svg += `${escapeHtml(item.title ?? "")}`; + if (valueLabel) svg += `${escapeHtml(valueLabel(item))}`; + if (item.label) svg += `${escapeHtml(item.label)}`; + }); + return svg + ""; +} + +/** Shows a toast at the bottom right for 8 s (hover pauses). */ +export function toast(message, isError = false) { + const host = document.getElementById("toasts") ?? document.body.appendChild(Object.assign(document.createElement("div"), { id: "toasts" })); + const item = document.createElement("div"); + item.className = `toast${isError ? " error" : ""}`; + item.setAttribute("role", isError ? "alert" : "status"); + item.textContent = message; + host.appendChild(item); + let remaining = 8000; + let started = Date.now(); + let timer = setTimeout(() => item.remove(), remaining); + item.addEventListener("mouseenter", () => { + clearTimeout(timer); + remaining -= Date.now() - started; + }); + item.addEventListener("mouseleave", () => { + started = Date.now(); + timer = setTimeout(() => item.remove(), remaining); + }); +} + +/** + * Two-button confirmation dialog (safe action left and default). Resolves true when the destructive action is chosen; + * with `typed`, that button stays disabled until the text is typed. + */ +export function confirmDialog({ title, body, confirm, confirmTip, cancel, cancelTip, typed }) { + return new Promise((resolve) => { + const dialog = document.createElement("dialog"); + dialog.className = "dialog"; + dialog.innerHTML = ` +
+

${escapeHtml(title)}

+ ${body ? `

${escapeHtml(body)}

` : ""} + ${typed ? `` : ""} +
+ + +
+
`; + document.body.appendChild(dialog); + const ok = dialog.querySelector('button[value="ok"]'); + dialog.querySelector('input[name="typed"]')?.addEventListener("input", (e) => { + ok.disabled = e.target.value !== typed; + }); + dialog.addEventListener("close", () => { + resolve(dialog.returnValue === "ok"); + dialog.remove(); + }); + dialog.showModal(); + }); +} + +/** The localised message of an API failure, or the generic one when the server was not reached. */ +export function errorText(err) { + return err?.message && err.status ? err.message : t("Admin.Error.Unreachable"); +} + +/** Query parameters of the hash route (#/logs?view=signins). */ +export function routeParams() { + return new URLSearchParams(location.hash.split("?")[1] ?? ""); +} + +/** A language's own name ("Italiano"), for language menus. */ +export function nativeName(code) { + try { + const name = new Intl.DisplayNames([code], { type: "language" }).of(code) ?? code; + return name.charAt(0).toLocaleUpperCase(code) + name.slice(1); + } catch { + return code; + } +}