diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml
index 9cc7dd66..041f38cb 100644
--- a/deploy/docker/docker-compose.yml
+++ b/deploy/docker/docker-compose.yml
@@ -14,6 +14,7 @@ services:
environment:
TITANO_ADMIN_USER: admin
TITANO_ADMIN_PASSWORD: ${TITANO_ADMIN_PASSWORD:?set TITANO_ADMIN_PASSWORD in .env}
+ # postgres (with the TITANO_DB_* values below) or a full connection string: Host=…;Database=…;Username=…;Password=…
TITANO_DB: postgres
TITANO_DB_HOST: postgres
TITANO_DB_NAME: titano
diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx
index d63f15e8..0933d7a3 100644
--- a/i18n/en/Admin.resx
+++ b/i18n/en/Admin.resx
@@ -4,17 +4,199 @@
2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ API version
+ DatabaseTLS SHA-256
+ Server nameTitano 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
+ Sequences
+ 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 logArchive
- 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} workersThe 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 panelWrong user name or password.long
+ Only administrators can use this panel.longPassword
+ Your password; it is checked by the server onlySign inSign in to administer this serverUser
+ 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
+ WhoAboutVersion and certificate fingerprintArchive
@@ -29,9 +211,113 @@
Server name, ports, TLS, limits and languageUsersAccounts, 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 passwordAdministratorEditorUploaderViewer
+ 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 outSign 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/en/Server.resx b/i18n/en/Server.resx
index 24a55d5c..512ef763 100644
--- a/i18n/en/Server.resx
+++ b/i18n/en/Server.resx
@@ -14,14 +14,62 @@
ConnectDisconnectNot connected to a server
+ Too many failed sign-ins; the account is locked for a while.longWrong user name or password.long
+ The request is not valid.longThe server certificate changed; confirm it and sign in again.long
+ This upload has no such chunk.long
+ The chunk has the wrong size.long
+ The file could not be stored in the archive; try again.long
+ The security token is missing; reload the page.longThe connection failed; the log has the details.long
+ Your account cannot do this.long
+ The file arrived damaged; upload it again.long
+ Open the admin panel over HTTPS to sign in.long
+ Some chunks are still missing.long
+ The server is out of disk space.long
+ Unexpected server error; try again.longThat is not a valid server address.long
+ Wrong user name or password.long
+ The paging cursor is not valid; start from the first page.long
+ The file name is not valid.long
+ A filter value is not valid.long
+ The SHA-256 must be 64 hexadecimal characters.long
+ This job kind cannot be started here.long
+ The job parameters are not valid.long
+ The priority must be background, normal or user.long
+ The role must be admin, editor, uploader or viewer.long
+ The setting {0} is not valid.long
+ The settings must be valid JSON.long
+ The job cannot do that in its current state.long
+ The naming template is not valid.long
+ Use letters, digits, dot, dash or underscore.long
+ This job is no longer assigned to this node.long
+ This server cannot run that kind of job.long
+ The last administrator cannot be removed or disabled.long
+ This method is not allowed here.long
+ Not found.longThat address is not a Titano Server.long
+ Change your password first.long
+ This upload would exceed your quota.long
+ Too many attempts; wait a minute and try again.long
+ Choose a password different from the current one.long
+ You cannot do this to your own account.longThe session expired; sign in again.long
+ An environment variable sets this; change it there.long
+ The sequence changed on the server; reload it and apply your edit again.long
+ The request is larger than the server accepts.long
+ Too many uploads at once; retry shortly.long
+ Sign in to continue.longThe server does not answer; check the address and the network.long
+ Send the body as JSON.longThe certificate was not trusted, so nothing was sent.long
+ This upload is not accepting that request now.long
+ That user name is taken.long
+ Use at least {0} characters.long
+ Connect with a WebSocket.long
+ The current password is wrong.long
+ This upload belongs to a render job.longServers foundAccountServer
@@ -39,6 +87,7 @@
EditorUploaderViewer
+ Titano time-lapse archive, uploads, jobs and rendering server.longSign outConnectedConnecting…
diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx
index 4e1f7a66..e1bdb0f1 100644
--- a/i18n/it/Admin.it.resx
+++ b/i18n/it/Admin.it.resx
@@ -4,17 +4,199 @@
2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ Versione API
+ DatabaseTLS SHA-256
+ Nome serverTitano 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
+ Sequenze
+ 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 controlloArchivio
- 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} workerIl 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 pannelloNome utente o password errati.
+ Solo gli amministratori possono usare questo pannello.Password
+ La tua password; la verifica solo il serverAccediAccedi per amministrare questo serverUtente
+ 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
+ ChiInformazioniVersione e impronta del certificatoArchivio
@@ -29,9 +211,113 @@
Nome server, porte, TLS, limiti e linguaUtentiAccount, 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 passwordAmministratoreEditorCaricamentoLettore
+ 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
+ EsciEsci 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/i18n/it/Server.it.resx b/i18n/it/Server.it.resx
index 8fdb24f3..fb5bdb68 100644
--- a/i18n/it/Server.it.resx
+++ b/i18n/it/Server.it.resx
@@ -13,14 +13,62 @@
ConnettiDisconnettiNon connesso a un server
+ Troppi accessi falliti; l'account è bloccato per un po'.Nome utente o password errati.
+ La richiesta non è valida.Il certificato del server è cambiato; confermalo e accedi di nuovo.
+ Questo caricamento non ha quel blocco.
+ Il blocco ha la dimensione sbagliata.
+ Il file non è stato salvato nell'archivio; riprova.
+ Manca il token di sicurezza; ricarica la pagina.La connessione non è riuscita; i dettagli sono nel log.
+ Il tuo account non può farlo.
+ Il file è arrivato danneggiato; caricalo di nuovo.
+ Apri il pannello di amministrazione in HTTPS per accedere.
+ Mancano ancora alcuni blocchi.
+ Il server ha esaurito lo spazio su disco.
+ Errore imprevisto del server; riprova.Questo non è un indirizzo di server valido.
+ Nome utente o password errati.
+ Il cursore di paginazione non è valido; ricomincia dalla prima pagina.
+ Il nome del file non è valido.
+ Un valore di filtro non è valido.
+ Lo SHA-256 deve avere 64 caratteri esadecimali.
+ Questo tipo di job non si può avviare qui.
+ I parametri del job non sono validi.
+ La priorità deve essere background, normal o user.
+ Il ruolo deve essere admin, editor, uploader o viewer.
+ L'impostazione {0} non è valida.
+ Le impostazioni devono essere JSON valido.
+ Il job non può farlo nello stato attuale.
+ Il modello dei nomi non è valido.
+ Usa lettere, cifre, punto, trattino o trattino basso.
+ Questo job non è più assegnato a questo nodo.
+ Questo server non può eseguire quel tipo di job.
+ L'ultimo amministratore non può essere rimosso o disattivato.
+ Metodo non consentito qui.
+ Non trovato.Questo indirizzo non è un Titano Server.
+ Cambia prima la password.
+ Questo caricamento supererebbe la tua quota.
+ Troppi tentativi; attendi un minuto e riprova.
+ Scegli una password diversa da quella attuale.
+ Non puoi farlo sul tuo account.La sessione è scaduta; accedi di nuovo.
+ È impostato da una variabile d'ambiente; modificala lì.
+ La sequenza è cambiata sul server; ricaricala e riapplica la modifica.
+ La richiesta supera la dimensione accettata dal server.
+ Troppi caricamenti insieme; riprova tra poco.
+ Accedi per continuare.Il server non risponde; controlla l'indirizzo e la rete.
+ Invia il corpo come JSON.Il certificato non è stato accettato, quindi non è stato inviato nulla.
+ Questo caricamento ora non accetta la richiesta.
+ Questo nome utente è già in uso.
+ Usa almeno {0} caratteri.
+ Connettiti con un WebSocket.
+ La password attuale è errata.
+ Questo caricamento appartiene a un job di rendering.Server trovatiAccountServer
@@ -38,6 +86,7 @@
EditorCaricatoreVisualizzatore
+ Server Titano per archivio time-lapse, caricamenti, job e rendering.EsciConnessoConnessione…
diff --git a/src/Titano.Data/Migrations/postgres/0003_server_uploads.sql b/src/Titano.Data/Migrations/postgres/0003_server_uploads.sql
new file mode 100644
index 00000000..271f679a
--- /dev/null
+++ b/src/Titano.Data/Migrations/postgres/0003_server_uploads.sql
@@ -0,0 +1,9 @@
+-- Titano Server additions (PostgreSQL): automatic grouping key of frame uploads, render-result uploads of
+-- render-node jobs, and the sign-in log lookup. Mirrors sqlite/0005_server_uploads.sql.
+
+ALTER TABLE uploads ADD COLUMN session_key text;
+ALTER TABLE uploads ADD COLUMN job_id uuid;
+ALTER TABLE uploads ADD COLUMN render_json jsonb;
+CREATE INDEX ix_uploads_job ON uploads (job_id);
+
+CREATE INDEX ix_audit_log_action ON audit_log (action, at);
diff --git a/src/Titano.Data/Migrations/sqlite/0003_server_uploads.sql b/src/Titano.Data/Migrations/sqlite/0003_server_uploads.sql
new file mode 100644
index 00000000..ce6e5d64
--- /dev/null
+++ b/src/Titano.Data/Migrations/sqlite/0003_server_uploads.sql
@@ -0,0 +1,9 @@
+-- Titano Server additions (SQLite): automatic grouping key of frame uploads, render-result uploads of render-node
+-- jobs, and the sign-in log lookup. Mirrors postgres/0005_server_uploads.sql.
+
+ALTER TABLE uploads ADD COLUMN session_key TEXT;
+ALTER TABLE uploads ADD COLUMN job_id TEXT;
+ALTER TABLE uploads ADD COLUMN render_json TEXT;
+CREATE INDEX ix_uploads_job ON uploads (job_id);
+
+CREATE INDEX ix_audit_log_action ON audit_log (action, at);
diff --git a/src/Titano.Data/Repositories/AuditRepository.cs b/src/Titano.Data/Repositories/AuditRepository.cs
index 46e13c31..d2199979 100644
--- a/src/Titano.Data/Repositories/AuditRepository.cs
+++ b/src/Titano.Data/Repositories/AuditRepository.cs
@@ -17,11 +17,16 @@ public sealed class AuditRepository
cancellationToken).ConfigureAwait(false);
/// Entries newest first, optionally of one user.
- public Task> ListAsync(Guid? userId = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default)
+ public Task> ListAsync(Guid? userId = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) =>
+ ListAsync(userId, action: null, limit, cursor, cancellationToken);
+
+ /// Entries newest first, optionally of one user and one action (e.g. the sign-in log).
+ public Task> ListAsync(Guid? userId, string? action, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default)
{
var p = new SqlParameters();
var where = new List();
if (userId is { } user) where.Add($"user_id = {p.Add(user)}");
+ if (action is not null) where.Add($"action = {p.Add(action)}");
if (cursor is not null)
{
var (value, id) = Cursor.Decode("audit", cursor);
diff --git a/src/Titano.Data/Repositories/FrameRepository.cs b/src/Titano.Data/Repositories/FrameRepository.cs
index ae064902..cb10e5e7 100644
--- a/src/Titano.Data/Repositories/FrameRepository.cs
+++ b/src/Titano.Data/Repositories/FrameRepository.cs
@@ -16,6 +16,9 @@ public sealed record DuplicateFrame(string Sha256, Guid FrameId, Guid SequenceId
/// Light statistics of one frame, written by the analysis job.
public readonly record struct FrameLightStats(Guid FrameId, double? MeanLogLuminance, double? ClipLow, double? ClipHigh);
+/// Per-format totals and flagged-frame counts of one sequence.
+public sealed record SequenceFrameStats(IReadOnlyList ByFormat, long Missing, long Corrupt, long Duplicate, long Excluded);
+
/// Frames of sequences: bulk import, paged listing, duplicate lookup and bulk updates.
public sealed class FrameRepository
{
@@ -210,6 +213,23 @@ public sealed class FrameRepository
return updated;
}, cancellationToken);
+ /// Formats and flagged-frame counters of one sequence.
+ public Task GetSequenceStatsAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
+ _db.RunAsync(async session =>
+ {
+ var byFormat = await session.QueryListAsync(
+ "SELECT format, count(*), COALESCE(SUM(size), 0) FROM frames WHERE sequence_id = $1 GROUP BY format ORDER BY 2 DESC, 1",
+ [sequenceId], r => new FormatBucket((ImageFileFormat)r.GetInt32(0), r.GetInt64(1), r.GetInt64(2)), cancellationToken).ConfigureAwait(false);
+ var flags = await session.QuerySingleAsync(
+ "SELECT " +
+ $"COALESCE(SUM(CASE WHEN (flags & {(int)FrameFlags.Missing}) <> 0 THEN 1 ELSE 0 END), 0), " +
+ $"COALESCE(SUM(CASE WHEN (flags & {(int)FrameFlags.Corrupt}) <> 0 THEN 1 ELSE 0 END), 0), " +
+ $"COALESCE(SUM(CASE WHEN (flags & {(int)FrameFlags.Duplicate}) <> 0 THEN 1 ELSE 0 END), 0), " +
+ $"COALESCE(SUM(CASE WHEN (flags & {(int)FrameFlags.Excluded}) <> 0 THEN 1 ELSE 0 END), 0) " +
+ "FROM frames WHERE sequence_id = $1", [sequenceId], cancellationToken).ConfigureAwait(false);
+ return new SequenceFrameStats(byFormat, flags.GetInt64(0), flags.GetInt64(1), flags.GetInt64(2), flags.GetInt64(3));
+ }, cancellationToken);
+
/// Removes every frame of a sequence; returns how many.
public Task DeleteBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
_db.ExecuteAsync("DELETE FROM frames WHERE sequence_id = $1", [sequenceId], cancellationToken);
diff --git a/src/Titano.Data/Repositories/JobRepository.cs b/src/Titano.Data/Repositories/JobRepository.cs
index 6736de5c..0a663325 100644
--- a/src/Titano.Data/Repositories/JobRepository.cs
+++ b/src/Titano.Data/Repositories/JobRepository.cs
@@ -3,6 +3,9 @@ using Titano.Core.Model;
namespace Titano.Data.Repositories;
+/// Jobs per state; and count those finished since a given time.
+public sealed record JobCounts(int Queued, int Running, int Paused, int DoneSince, int FailedSince);
+
///
/// The persistent job queue (BRIEF §14.6): workers claim the oldest job of the highest priority atomically,
/// write checkpoints while running, and on startup requeue what a crash left running.
@@ -74,11 +77,16 @@ public sealed class JobRepository
}
/// Jobs, newest first, optionally of one state.
- public Task> ListAsync(JobState? state = null, int limit = 50, string? cursor = null, CancellationToken cancellationToken = default)
+ public Task> ListAsync(JobState? state = null, int limit = 50, string? cursor = null, CancellationToken cancellationToken = default) =>
+ ListAsync(state, kind: null, limit, cursor, cancellationToken);
+
+ /// Jobs, newest first, optionally of one state and one kind.
+ public Task> ListAsync(JobState? state, JobKind? kind, int limit = 50, string? cursor = null, CancellationToken cancellationToken = default)
{
var p = new SqlParameters();
var where = new List();
if (state is { } s) where.Add($"state = {p.Add((int)s)}");
+ if (kind is { } k) where.Add($"kind = {p.Add((int)k)}");
if (cursor is not null)
{
var (value, id) = Cursor.Decode("jobs", cursor);
@@ -117,6 +125,74 @@ public sealed class JobRepository
(nodeId is null ? string.Empty : " AND (node_id = $1 OR substr(node_id, 1, length($2)) = $2)"),
nodeId is null ? [] : [nodeId, nodeId + "#"], cancellationToken);
+ public async Task SetPriorityAsync(Guid id, JobPriority priority, CancellationToken cancellationToken = default) =>
+ await _db.ExecuteAsync("UPDATE jobs SET priority = $2 WHERE id = $1", [id, (int)priority], cancellationToken).ConfigureAwait(false) > 0;
+
+ /// Queued jobs of one kind in claim order (highest priority, then oldest).
+ public Task> ListQueuedAsync(JobKind kind, int limit = 50, CancellationToken cancellationToken = default) =>
+ _db.ListAsync(
+ $"SELECT {Columns} FROM jobs WHERE state = {(int)JobState.Queued} AND kind = $1 ORDER BY priority DESC, created, id LIMIT $2",
+ [(int)kind, Cursor.ClampLimit(limit)], Map, cancellationToken);
+
+ /// Running jobs claimed by .
+ public Task> ListRunningByNodeAsync(string nodeId, CancellationToken cancellationToken = default) =>
+ _db.ListAsync($"SELECT {Columns} FROM jobs WHERE state = {(int)JobState.Running} AND node_id = $1 ORDER BY started, id",
+ [nodeId], Map, cancellationToken);
+
+ /// True when a job of for exactly is waiting in the queue.
+ public async Task IsQueuedAsync(JobKind kind, Guid targetId, CancellationToken cancellationToken = default) =>
+ await _db.ScalarAsync(
+ $"SELECT count(*) FROM jobs WHERE state = {(int)JobState.Queued} AND kind = $1 AND target_ids = $2",
+ [(int)kind, targetId.ToString()], cancellationToken).ConfigureAwait(false) > 0;
+
+ ///
+ /// Claims one specific queued job for (render nodes pick by capability); null when another
+ /// claimer was faster or the job is no longer queued.
+ ///
+ public Task TryClaimAsync(Guid id, string nodeId, CancellationToken cancellationToken = default) =>
+ _db.InTransactionAsync(async session =>
+ {
+ var claimed = await session.ExecuteAsync(
+ $"UPDATE jobs SET state = {(int)JobState.Running}, node_id = $2, started = $3, finished = NULL, error = NULL, attempts = attempts + 1 " +
+ $"WHERE id = $1 AND state = {(int)JobState.Queued}",
+ [id, nodeId, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false);
+ if (claimed == 0) return null;
+ return await session.QuerySingleOrDefaultAsync($"SELECT {Columns} FROM jobs WHERE id = $1", [id], Map, cancellationToken).ConfigureAwait(false);
+ }, cancellationToken);
+
+ /// Progress of a job a render node runs; false when the job is no longer running on that node.
+ public async Task UpdateNodeProgressAsync(Guid id, string nodeId, long done, long total, double? itemsPerSecond, TimeSpan? eta,
+ string? logTail, CancellationToken cancellationToken = default) =>
+ await _db.ExecuteAsync(
+ "UPDATE jobs SET progress_done = $3, progress_total = $4, items_per_second = $5, eta_seconds = $6, log_tail = $7 " +
+ $"WHERE id = $1 AND node_id = $2 AND state = {(int)JobState.Running}",
+ [id, nodeId, done, total, itemsPerSecond, eta?.TotalSeconds, logTail], cancellationToken).ConfigureAwait(false) > 0;
+
+ /// Ends a job a render node runs (done or failed); false when it is no longer running on that node.
+ public async Task FinishNodeJobAsync(Guid id, string nodeId, JobState state, string? error, string? logTail, CancellationToken cancellationToken = default)
+ {
+ if (state is not (JobState.Done or JobState.Failed)) throw new ArgumentOutOfRangeException(nameof(state), state, "Only done or failed end a node job.");
+ return await _db.ExecuteAsync(
+ "UPDATE jobs SET state = $3, error = $4, finished = $5, log_tail = COALESCE($6, log_tail) " +
+ $"WHERE id = $1 AND node_id = $2 AND state = {(int)JobState.Running}",
+ [id, nodeId, (int)state, error, DateTimeOffset.UtcNow, logTail], cancellationToken).ConfigureAwait(false) > 0;
+ }
+
+ /// Queue and history counters for dashboards; finished counts are those since .
+ public Task CountAsync(DateTimeOffset finishedSince, CancellationToken cancellationToken = default) =>
+ _db.RunAsync(async session =>
+ {
+ var row = await session.QuerySingleAsync(
+ "SELECT " +
+ $"COALESCE(SUM(CASE WHEN state = {(int)JobState.Queued} THEN 1 ELSE 0 END), 0), " +
+ $"COALESCE(SUM(CASE WHEN state = {(int)JobState.Running} THEN 1 ELSE 0 END), 0), " +
+ $"COALESCE(SUM(CASE WHEN state = {(int)JobState.Paused} THEN 1 ELSE 0 END), 0), " +
+ $"COALESCE(SUM(CASE WHEN state = {(int)JobState.Done} AND finished >= $1 THEN 1 ELSE 0 END), 0), " +
+ $"COALESCE(SUM(CASE WHEN state = {(int)JobState.Failed} AND finished >= $1 THEN 1 ELSE 0 END), 0) " +
+ "FROM jobs", [finishedSince], cancellationToken).ConfigureAwait(false);
+ return new JobCounts(row.GetInt32(0), row.GetInt32(1), row.GetInt32(2), row.GetInt32(3), row.GetInt32(4));
+ }, cancellationToken);
+
private static Job Map(DbRow r) => new()
{
Id = r.GetGuid(0),
diff --git a/src/Titano.Data/Repositories/RenderNodeRepository.cs b/src/Titano.Data/Repositories/RenderNodeRepository.cs
index 898f1500..85099532 100644
--- a/src/Titano.Data/Repositories/RenderNodeRepository.cs
+++ b/src/Titano.Data/Repositories/RenderNodeRepository.cs
@@ -37,6 +37,15 @@ public sealed class RenderNodeRepository
public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) =>
await _db.ExecuteAsync("DELETE FROM render_nodes WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0;
+ /// Changes the state only (a node that stopped heart-beating keeps its last heartbeat time).
+ public async Task SetStateAsync(Guid id, string state, CancellationToken cancellationToken = default) =>
+ await _db.ExecuteAsync("UPDATE render_nodes SET state = $2 WHERE id = $1", [id, state], cancellationToken).ConfigureAwait(false) > 0;
+
+ /// Nodes not in whose last heartbeat is older than .
+ public Task> ListSilentAsync(DateTimeOffset before, string exceptState, CancellationToken cancellationToken = default) =>
+ _db.ListAsync($"SELECT {Columns} FROM render_nodes WHERE last_heartbeat < $1 AND state <> $2 ORDER BY last_heartbeat, id",
+ [before, exceptState], Map, cancellationToken);
+
private static RenderNode Map(DbRow r) => new()
{
Id = r.GetGuid(0),
diff --git a/src/Titano.Data/Repositories/SequenceRepository.cs b/src/Titano.Data/Repositories/SequenceRepository.cs
index eb566ded..31619615 100644
--- a/src/Titano.Data/Repositories/SequenceRepository.cs
+++ b/src/Titano.Data/Repositories/SequenceRepository.cs
@@ -60,6 +60,28 @@ public sealed record ArchiveStats(
IReadOnlyList ByFormat,
ArchiveHealth Health);
+/// Fields a client may change on a sequence; null leaves a field unchanged, an empty title or notes clears it.
+public sealed record SequenceEdit
+{
+ public string? Title { get; init; }
+ public IReadOnlyList? Tags { get; init; }
+ public int? Rating { get; init; }
+ public string? Notes { get; init; }
+ public string? SettingsJson { get; init; }
+}
+
+public enum SequenceEditOutcome
+{
+ Updated,
+ NotFound,
+
+ /// The settings version moved since the client read it.
+ Conflict,
+}
+
+/// Result of : the updated sequence, or the stored one on conflict.
+public sealed record SequenceEditResult(SequenceEditOutcome Outcome, Sequence? Sequence);
+
public sealed record YearBucket(int Year, int Sequences, long Photos, long Bytes);
/// One heatmap cell: sequences and photos whose first capture falls in the month.
@@ -175,6 +197,38 @@ public sealed class SequenceRepository
return updated;
}, cancellationToken);
+ ///
+ /// Applies a client edit atomically and bumps settings_version. With
+ /// the edit is refused (, carrying the stored sequence) when someone else
+ /// changed the sequence first (BRIEF §14.5).
+ ///
+ public Task EditAsync(Guid id, SequenceEdit edit, int? expectedSettingsVersion, CancellationToken cancellationToken = default) =>
+ _db.InTransactionAsync(async session =>
+ {
+ var current = await session.QuerySingleOrDefaultAsync($"{_select} WHERE s.id = $1{_db.Sql.ForUpdate}", [id], Map, cancellationToken)
+ .ConfigureAwait(false);
+ if (current is null) return new SequenceEditResult(SequenceEditOutcome.NotFound, null);
+ if (expectedSettingsVersion is { } expected && expected != current.SettingsVersion)
+ return new SequenceEditResult(SequenceEditOutcome.Conflict, current);
+ var updated = current with
+ {
+ Title = edit.Title is null ? current.Title : NullIfEmpty(edit.Title),
+ Notes = edit.Notes is null ? current.Notes : NullIfEmpty(edit.Notes),
+ Rating = edit.Rating ?? current.Rating,
+ SettingsJson = edit.SettingsJson ?? current.SettingsJson,
+ SettingsVersion = current.SettingsVersion + 1,
+ UpdatedAt = DateTimeOffset.UtcNow,
+ };
+ await UpsertRowAsync(session, updated, cancellationToken).ConfigureAwait(false);
+ if (edit.Tags is not null) await ReplaceTagsAsync(session, id, edit.Tags, cancellationToken).ConfigureAwait(false);
+ var stored = await session.QuerySingleAsync($"{_select} WHERE s.id = $1", [id], cancellationToken).ConfigureAwait(false);
+ return new SequenceEditResult(SequenceEditOutcome.Updated, Map(stored));
+ }, cancellationToken);
+
+ /// Gives every sequence owned by to ; returns how many.
+ public Task ReassignOwnerAsync(Guid fromUserId, Guid toUserId, CancellationToken cancellationToken = default) =>
+ _db.ExecuteAsync("UPDATE sequences SET owner_user_id = $2 WHERE owner_user_id = $1", [fromUserId, toUserId], cancellationToken);
+
/// One page of sequences matching .
public Task> ListAsync(SequenceQuery query, CancellationToken cancellationToken = default)
{
@@ -393,6 +447,8 @@ public sealed class SequenceRepository
}
}
+ private static string? NullIfEmpty(string value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
+
/// Camera wall-clock times are stored without zone, whatever kind the caller's value has.
internal static DateTime? Wall(DateTime? value) =>
value is { } v ? DateTime.SpecifyKind(v, DateTimeKind.Unspecified) : null;
diff --git a/src/Titano.Data/Repositories/TokenRepository.cs b/src/Titano.Data/Repositories/TokenRepository.cs
index 8b88c0fc..1fed9606 100644
--- a/src/Titano.Data/Repositories/TokenRepository.cs
+++ b/src/Titano.Data/Repositories/TokenRepository.cs
@@ -37,6 +37,22 @@ public sealed class TokenRepository
public Task RevokeAllAsync(Guid userId, CancellationToken cancellationToken = default) =>
_db.ExecuteAsync("UPDATE tokens SET revoked = TRUE WHERE user_id = $1 AND revoked = FALSE", [userId], cancellationToken);
+ /// Revokes every live token of a user except (password changed in that session).
+ public Task RevokeAllExceptAsync(Guid userId, string keepTokenHash, CancellationToken cancellationToken = default) =>
+ _db.ExecuteAsync("UPDATE tokens SET revoked = TRUE WHERE user_id = $1 AND token_hash <> $2 AND revoked = FALSE",
+ [userId, keepTokenHash], cancellationToken);
+
+ /// The most recently used token of every user (last seen time and client), keyed by user id.
+ public async Task> LatestByUserAsync(CancellationToken cancellationToken = default)
+ {
+ var tokens = await _db.ListAsync(
+ $"SELECT {Columns} FROM tokens t WHERE last_used = (SELECT MAX(last_used) FROM tokens l WHERE l.user_id = t.user_id)",
+ [], Map, cancellationToken).ConfigureAwait(false);
+ var latest = new Dictionary();
+ foreach (var token in tokens) latest[token.UserId] = token;
+ return latest;
+ }
+
public Task> ListByUserAsync(Guid userId, CancellationToken cancellationToken = default) =>
_db.ListAsync($"SELECT {Columns} FROM tokens WHERE user_id = $1 ORDER BY last_used DESC", [userId], Map, cancellationToken);
diff --git a/src/Titano.Data/Repositories/UploadRepository.cs b/src/Titano.Data/Repositories/UploadRepository.cs
index 355511ec..35c0a500 100644
--- a/src/Titano.Data/Repositories/UploadRepository.cs
+++ b/src/Titano.Data/Repositories/UploadRepository.cs
@@ -36,6 +36,15 @@ public sealed record Upload
public DateTimeOffset Created { get; init; }
public DateTimeOffset UpdatedAt { get; init; }
+ /// Automatic grouping key of a frame upload without a target sequence (BRIEF §14.4).
+ public string? SessionKey { get; init; }
+
+ /// The render job whose output this upload carries; null for frame uploads.
+ public Guid? JobId { get; init; }
+
+ /// Metadata of the render a render-result upload becomes (JSON).
+ public string? RenderJson { get; init; }
+
public int ChunkCount => (int)((Size + ChunkSize - 1) / ChunkSize);
public bool IsComplete => ReceivedCount >= ChunkCount;
@@ -44,11 +53,15 @@ public sealed record Upload
index >= 0 && index / 8 < Received.Length && (Received[index / 8] & (1 << (index % 8))) != 0;
}
+/// Committed uploads of one UTC day.
+public sealed record UploadDay(DateOnly Day, long Count, long Bytes);
+
/// Resumable uploads: creation, per-chunk bookkeeping, state changes and cleanup.
public sealed class UploadRepository
{
private const string Columns =
- "id, user_id, sequence_id, file_name, size, sha256, captured_at, chunk_size, received, received_count, state, frame_id, created, updated_at";
+ "id, user_id, sequence_id, file_name, size, sha256, captured_at, chunk_size, received, received_count, state, frame_id, created, updated_at, " +
+ "session_key, job_id, render_json";
private readonly DbAccess _db;
@@ -61,10 +74,11 @@ public sealed class UploadRepository
ArgumentOutOfRangeException.ThrowIfNegative(upload.Size);
var stored = upload with { Received = new byte[(upload.ChunkCount + 7) / 8], ReceivedCount = 0, Sha256 = upload.Sha256.ToLowerInvariant() };
await _db.ExecuteAsync(
- $"INSERT INTO uploads ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",
+ $"INSERT INTO uploads ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)",
[
stored.Id, stored.UserId, stored.SequenceId, stored.FileName, stored.Size, stored.Sha256, SequenceRepository.Wall(stored.CapturedAt),
stored.ChunkSize, stored.Received, 0, (int)stored.State, stored.FrameId, stored.Created, stored.UpdatedAt,
+ stored.SessionKey, stored.JobId, DbParam.Json(stored.RenderJson),
], cancellationToken).ConfigureAwait(false);
return stored;
}
@@ -72,10 +86,11 @@ public sealed class UploadRepository
public Task GetAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.SingleAsync($"SELECT {Columns} FROM uploads WHERE id = $1", [id], Map, cancellationToken);
- /// An upload of the same content by the same user that is still receiving, so a client can resume it.
+ /// A frame upload of the same content by the same user that is still receiving, so a client can resume it.
public Task FindReceivingAsync(Guid userId, string sha256, CancellationToken cancellationToken = default) =>
_db.SingleAsync(
- $"SELECT {Columns} FROM uploads WHERE user_id = $1 AND sha256 = $2 AND state = {(int)UploadState.Receiving} ORDER BY created DESC LIMIT 1",
+ $"SELECT {Columns} FROM uploads WHERE user_id = $1 AND sha256 = $2 AND state = {(int)UploadState.Receiving} AND job_id IS NULL " +
+ "ORDER BY created DESC LIMIT 1",
[userId, sha256.ToLowerInvariant()], Map, cancellationToken);
///
@@ -115,6 +130,54 @@ public sealed class UploadRepository
public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) =>
await _db.ExecuteAsync("DELETE FROM uploads WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0;
+ ///
+ /// Moves an upload from to only if it is still in ,
+ /// so two concurrent completions cannot both commit it. Returns false when the state had changed.
+ ///
+ public async Task TryTransitionAsync(Guid id, UploadState from, UploadState to, Guid? frameId = null, CancellationToken cancellationToken = default) =>
+ await _db.ExecuteAsync("UPDATE uploads SET state = $3, frame_id = COALESCE($4, frame_id), updated_at = $5 WHERE id = $1 AND state = $2",
+ [id, (int)from, (int)to, frameId, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false) > 0;
+
+ /// The newest upload carrying the output of render job .
+ public Task FindByJobAsync(Guid jobId, CancellationToken cancellationToken = default) =>
+ _db.SingleAsync($"SELECT {Columns} FROM uploads WHERE job_id = $1 ORDER BY created DESC, id DESC LIMIT 1", [jobId], Map, cancellationToken);
+
+ /// Every upload in , oldest change first.
+ public Task> ListByStateAsync(UploadState state, CancellationToken cancellationToken = default) =>
+ _db.ListAsync($"SELECT {Columns} FROM uploads WHERE state = $1 ORDER BY updated_at, id", [(int)state], Map, cancellationToken);
+
+ /// Bytes a user has announced in frame uploads that are not committed yet (reserved against the quota).
+ public async Task PendingBytesAsync(Guid userId, CancellationToken cancellationToken = default) =>
+ await _db.ScalarAsync(
+ $"SELECT COALESCE(SUM(size), 0) FROM uploads WHERE user_id = $1 AND job_id IS NULL AND state IN ({(int)UploadState.Receiving}, {(int)UploadState.Committing})",
+ [userId], cancellationToken).ConfigureAwait(false);
+
+ /// Committed frame uploads per UTC day since , oldest day first.
+ public Task> CommittedPerDayAsync(DateTimeOffset since, CancellationToken cancellationToken = default)
+ {
+ var day = _db.Sql.IsPostgres ? "to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD')" : "substr(updated_at, 1, 10)";
+ return _db.ListAsync(
+ $"SELECT {day}, count(*), COALESCE(SUM(size), 0) FROM uploads WHERE state = {(int)UploadState.Committed} AND job_id IS NULL AND updated_at >= $1 " +
+ "GROUP BY 1 ORDER BY 1",
+ [since], r => new UploadDay(DateOnly.ParseExact(r.GetString(0), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture), r.GetInt64(1), r.GetInt64(2)),
+ cancellationToken);
+ }
+
+ /// Committed frame uploads per user since .
+ public async Task> CommittedCountByUserAsync(DateTimeOffset since, CancellationToken cancellationToken = default)
+ {
+ var rows = await _db.ListAsync(
+ $"SELECT user_id, count(*) FROM uploads WHERE state = {(int)UploadState.Committed} AND job_id IS NULL AND updated_at >= $1 GROUP BY user_id",
+ [since], r => KeyValuePair.Create(r.GetGuid(0), r.GetInt64(1)), cancellationToken).ConfigureAwait(false);
+ return new Dictionary(rows);
+ }
+
+ /// Deletes committed, failed and cancelled uploads last changed before ; returns how many.
+ public Task PurgeFinishedAsync(DateTimeOffset updatedBefore, CancellationToken cancellationToken = default) =>
+ _db.ExecuteAsync(
+ $"DELETE FROM uploads WHERE state IN ({(int)UploadState.Committed}, {(int)UploadState.Failed}, {(int)UploadState.Cancelled}) AND updated_at < $1",
+ [updatedBefore], cancellationToken);
+
private static Upload Map(DbRow r) => new()
{
Id = r.GetGuid(0),
@@ -131,5 +194,8 @@ public sealed class UploadRepository
FrameId = r.GetGuidOrNull(11),
Created = r.GetDateTimeOffset(12),
UpdatedAt = r.GetDateTimeOffset(13),
+ SessionKey = r.GetStringOrNull(14),
+ JobId = r.GetGuidOrNull(15),
+ RenderJson = r.GetStringOrNull(16),
};
}
diff --git a/src/Titano.Protocol/Admin.cs b/src/Titano.Protocol/Admin.cs
new file mode 100644
index 00000000..17abbd28
--- /dev/null
+++ b/src/Titano.Protocol/Admin.cs
@@ -0,0 +1,53 @@
+namespace Titano.Protocol;
+
+///
+/// GET/PUT /api/v1/server/settings (admin): the editable part of the server configuration. Settings named in
+/// come from environment variables and cannot be changed here; says
+/// that saved values (ports, TLS, workers, chunk size) wait for a restart.
+///
+public sealed record ServerSettingsDto(
+ string ServerName,
+ int HttpPort,
+ int HttpsPort,
+ string TlsMode,
+ string? TlsCert,
+ string? TlsKey,
+ string Language,
+ int Workers,
+ bool Discovery,
+ long MaxUploadBytes,
+ int ChunkSizeBytes,
+ int JobHistoryDays,
+ int TokenLifetimeDays,
+ int UploadRetentionHours,
+ IReadOnlyList Locked,
+ bool RestartRequired);
+
+/// A server log file (GET /api/v1/logs/files).
+public sealed record LogFileDto(string Name, long Size, DateTimeOffset Modified);
+
+/// The last lines of the current server log (GET /api/v1/logs).
+public sealed record LogTailDto(string File, IReadOnlyList Lines);
+
+/// Jobs per state; done and failed count today's (UTC) jobs.
+public sealed record JobCountsDto(int Queued, int Running, int Paused, int DoneToday, int FailedToday);
+
+/// Frames committed by uploads on one UTC day.
+public sealed record UploadDayDto(DateOnly Day, long Frames, long Bytes);
+
+/// GET /api/v1/server/dashboard (admin): everything the dashboard page shows in one call (BRIEF §14.8).
+public sealed record DashboardDto(
+ string ServerName,
+ string Version,
+ long UptimeSeconds,
+ string Database,
+ string TlsMode,
+ bool Discovery,
+ int Users,
+ ArchiveStatsDto Archive,
+ JobCountsDto Jobs,
+ int Workers,
+ IReadOnlyList Nodes,
+ IReadOnlyList Uploads,
+ IReadOnlyList Activity,
+ IReadOnlyList ActiveJobs);
diff --git a/src/Titano.Protocol/Auth.cs b/src/Titano.Protocol/Auth.cs
index 077009c1..fdf07086 100644
--- a/src/Titano.Protocol/Auth.cs
+++ b/src/Titano.Protocol/Auth.cs
@@ -29,3 +29,21 @@ public sealed record UpdateUserRequest(string? DisplayName, string? Role, long?
/// Response of POST /api/v1/users and /users/{id}/reset-password: a temporary password shown once.
public sealed record TemporaryPasswordResponse(UserDto User, string TemporaryPassword);
+
+/// POST /api/v1/users/{id}/reset-password (admin); without a password the server generates one.
+public sealed record ResetPasswordRequest(string? Password);
+
+/// One row of the admin user list: the account plus when and from which client it was last used.
+public sealed record UserSummaryDto(UserDto User, DateTimeOffset? LastSeen, string? LastClient, long UploadsLast30Days);
+
+/// One audit log entry (who did what to which user, sequence or setting).
+public sealed record AuditEntryDto(
+ Guid Id,
+ DateTimeOffset At,
+ Guid? UserId,
+ string? Username,
+ string Action,
+ string? TargetKind,
+ string? TargetId,
+ string? Details,
+ string? RemoteAddress);
diff --git a/src/Titano.Protocol/Client/TitanoClient.cs b/src/Titano.Protocol/Client/TitanoClient.cs
index d8f57f51..d843ca82 100644
--- a/src/Titano.Protocol/Client/TitanoClient.cs
+++ b/src/Titano.Protocol/Client/TitanoClient.cs
@@ -154,37 +154,59 @@ public sealed class TitanoClient : IDisposable
}
var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id.");
- var chunkSize = start.ChunkSize;
- var received = new HashSet(start.Received);
- var chunks = (int)((info.Length + chunkSize - 1) / chunkSize);
- var buffer = new byte[chunkSize];
- await using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan))
- {
- long sent = received.Count == 0 ? 0 : received.Sum(i => (long)Math.Min(chunkSize, info.Length - (long)i * chunkSize));
- progress?.Report(new UploadProgress(sent, info.Length));
- for (var n = 0; n < chunks; n++)
- {
- if (received.Contains(n)) continue;
- var offset = (long)n * chunkSize;
- var length = (int)Math.Min(chunkSize, info.Length - offset);
- file.Position = offset;
- await file.ReadExactlyAsync(buffer.AsMemory(0, length), ct).ConfigureAwait(false);
- await Bandwidth.AcquireAsync(length, ct).ConfigureAwait(false);
- await RetryAsync(async () =>
- {
- using var content = new ByteArrayContent(buffer, 0, length);
- content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
- using var response = await _http.PutAsync($"api/v1/uploads/{uploadId}/chunks/{n}", content, ct).ConfigureAwait(false);
- await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
- return true;
- }, ct).ConfigureAwait(false);
- sent += length;
- progress?.Report(new UploadProgress(sent, info.Length));
- }
- }
+ await SendChunksAsync(path, info.Length, uploadId, start.ChunkSize, start.Received, progress, ct).ConfigureAwait(false);
return await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/uploads/{uploadId}/complete", ProtocolJson.Default.CompleteUploadResponse, ct), ct).ConfigureAwait(false);
}
+ ///
+ /// Render node: uploads the output of a claimed job in resumable chunks, then completes the job; the server verifies
+ /// the SHA-256 in and files the render under the sequence's exports (BRIEF §14.7).
+ ///
+ public async Task UploadRenderResultAsync(Guid nodeId, Guid jobId, string path, RenderResultRequest result,
+ IProgress? progress = null, CancellationToken ct = default)
+ {
+ var length = new FileInfo(path).Length;
+ if (length != result.Size) throw new ArgumentException("The result size does not match the file.", nameof(result));
+ var start = await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/result", result,
+ ProtocolJson.Default.RenderResultRequest, ProtocolJson.Default.StartUploadResponse, ct), ct).ConfigureAwait(false);
+ var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id.");
+ await SendChunksAsync(path, length, uploadId, start.ChunkSize, start.Received, progress, ct).ConfigureAwait(false);
+ return await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/result/complete", ProtocolJson.Default.RenderDto, ct), ct)
+ .ConfigureAwait(false);
+ }
+
+ /// Sends every chunk the server does not have yet; each PUT is idempotent and retried on transient errors.
+ private async Task SendChunksAsync(string path, long length, Guid uploadId, int chunkSize, IReadOnlyList alreadyReceived,
+ IProgress? progress, CancellationToken ct)
+ {
+ var received = new HashSet(alreadyReceived);
+ var chunks = (int)((length + chunkSize - 1) / chunkSize);
+ var buffer = new byte[chunkSize];
+ await using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan);
+ long sent = received.Sum(i => Math.Min(chunkSize, length - (long)i * chunkSize));
+ progress?.Report(new UploadProgress(sent, length));
+ for (var n = 0; n < chunks; n++)
+ {
+ if (received.Contains(n)) continue;
+ var offset = (long)n * chunkSize;
+ var size = (int)Math.Min(chunkSize, length - offset);
+ file.Position = offset;
+ await file.ReadExactlyAsync(buffer.AsMemory(0, size), ct).ConfigureAwait(false);
+ await Bandwidth.AcquireAsync(size, ct).ConfigureAwait(false);
+ var index = n;
+ await RetryAsync(async () =>
+ {
+ using var content = new ByteArrayContent(buffer, 0, size);
+ content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
+ using var response = await _http.PutAsync($"api/v1/uploads/{uploadId}/chunks/{index}", content, ct).ConfigureAwait(false);
+ await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
+ return true;
+ }, ct).ConfigureAwait(false);
+ sent += size;
+ progress?.Report(new UploadProgress(sent, length));
+ }
+ }
+
/// Lower-case hex SHA-256 of a file, streamed.
public static async Task HashFileAsync(string path, CancellationToken ct = default)
{
@@ -201,10 +223,22 @@ public sealed class TitanoClient : IDisposable
public Task CreateJobAsync(CreateJobRequest request, CancellationToken ct = default) =>
SendAsync(HttpMethod.Post, "api/v1/jobs", request, ProtocolJson.Default.CreateJobRequest, ProtocolJson.Default.JobDto, ct);
+ public Task GetJobAsync(Guid id, CancellationToken ct = default) => GetAsync($"api/v1/jobs/{id}", ProtocolJson.Default.JobDto, ct);
+
public Task CancelJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/cancel", ProtocolJson.Default.JobDto, ct);
public Task RetryJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/retry", ProtocolJson.Default.JobDto, ct);
+ public Task PauseJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/pause", ProtocolJson.Default.JobDto, ct);
+
+ public Task ResumeJobAsync(Guid id, CancellationToken ct = default) => SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/resume", ProtocolJson.Default.JobDto, ct);
+
+ /// Moves a waiting job up or down the queue: is background, normal or user.
+ public Task SetJobPriorityAsync(Guid id, string priority, CancellationToken ct = default) =>
+ SendAsync(HttpMethod.Post, $"api/v1/jobs/{id}/priority", new JobPriorityRequest(priority), ProtocolJson.Default.JobPriorityRequest, ProtocolJson.Default.JobDto, ct);
+
+ public Task> ListNodesAsync(CancellationToken ct = default) => GetAsync("api/v1/nodes", ProtocolJson.Default.ListRenderNodeDto, ct);
+
public Task RegisterNodeAsync(RegisterNodeRequest request, CancellationToken ct = default) =>
SendAsync(HttpMethod.Post, "api/v1/nodes/register", request, ProtocolJson.Default.RegisterNodeRequest, ProtocolJson.Default.RenderNodeDto, ct);
@@ -222,6 +256,10 @@ public sealed class TitanoClient : IDisposable
public Task ReportNodeProgressAsync(Guid nodeId, Guid jobId, NodeProgress progress, CancellationToken ct = default) =>
SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/progress", progress, ProtocolJson.Default.NodeProgress, ct);
+ /// Gives a claimed job back as failed; a 409 means it was cancelled or reassigned meanwhile.
+ public Task ReportNodeFailureAsync(Guid nodeId, Guid jobId, string error, CancellationToken ct = default) =>
+ SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/failed", new NodeJobFailure(error), ProtocolJson.Default.NodeJobFailure, ct);
+
// ---------------- Events ----------------
/// Server events over WebSocket until cancelled; reconnect is the caller's policy.
diff --git a/src/Titano.Protocol/Dtos.cs b/src/Titano.Protocol/Dtos.cs
index d841902d..52934196 100644
--- a/src/Titano.Protocol/Dtos.cs
+++ b/src/Titano.Protocol/Dtos.cs
@@ -5,8 +5,8 @@ namespace Titano.Protocol;
/// Error body of every failed API call: { code, message, details } (BRIEF §14.3).
public sealed record ApiError(string Code, string Message, string? Details = null);
-/// Upload limits announced by the server.
-public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes);
+/// Upload and account limits announced by the server.
+public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes, int PasswordMinLength = 10);
/// GET /api/v1/server/info.
public sealed record ServerInfo(
diff --git a/src/Titano.Protocol/Jobs.cs b/src/Titano.Protocol/Jobs.cs
index e5655af4..6a6d8e5c 100644
--- a/src/Titano.Protocol/Jobs.cs
+++ b/src/Titano.Protocol/Jobs.cs
@@ -34,3 +34,27 @@ public sealed record ClaimedJob(JobDto Job, Guid SequenceId, string SettingsJson
/// POST /api/v1/nodes/{id}/jobs/{jobId}/progress.
public sealed record NodeProgress(long Done, long Total, double? ItemsPerSecond, string? LogLine);
+
+/// POST /api/v1/jobs/{id}/priority: background, normal or user.
+public sealed record JobPriorityRequest(string Priority);
+
+///
+/// parametersJson of a render job: what to encode. Render nodes claim the job when they have an encoder for
+/// at × (BRIEF §14.7).
+///
+public sealed record RenderJobParameters(string PresetName, string PresetJson, string Codec, int Width, int Height, bool UseProxies, string? SettingsJson);
+
+/// POST /api/v1/nodes/{id}/jobs/{jobId}/result: the finished output a node is about to upload in chunks.
+public sealed record RenderResultRequest(
+ string FileName,
+ long Size,
+ string Sha256,
+ string PresetName,
+ string? Codec,
+ int Width,
+ int Height,
+ double Fps,
+ double DurationSeconds);
+
+/// POST /api/v1/nodes/{id}/jobs/{jobId}/failed: the node could not render the job.
+public sealed record NodeJobFailure(string Error);
diff --git a/src/Titano.Protocol/ProtocolJson.cs b/src/Titano.Protocol/ProtocolJson.cs
index 2f3dad46..2db29cac 100644
--- a/src/Titano.Protocol/ProtocolJson.cs
+++ b/src/Titano.Protocol/ProtocolJson.cs
@@ -45,4 +45,21 @@ namespace Titano.Protocol;
[JsonSerializable(typeof(NodeProgress))]
[JsonSerializable(typeof(ServerEvent))]
[JsonSerializable(typeof(DiscoveryBeacon))]
+[JsonSerializable(typeof(ResetPasswordRequest))]
+[JsonSerializable(typeof(UserSummaryDto))]
+[JsonSerializable(typeof(List))]
+[JsonSerializable(typeof(AuditEntryDto))]
+[JsonSerializable(typeof(Page))]
+[JsonSerializable(typeof(SequenceStatsDto))]
+[JsonSerializable(typeof(SequenceDeletePlan))]
+[JsonSerializable(typeof(ArchiveSettingsDto))]
+[JsonSerializable(typeof(JobPriorityRequest))]
+[JsonSerializable(typeof(RenderJobParameters))]
+[JsonSerializable(typeof(RenderResultRequest))]
+[JsonSerializable(typeof(NodeJobFailure))]
+[JsonSerializable(typeof(ServerSettingsDto))]
+[JsonSerializable(typeof(LogFileDto))]
+[JsonSerializable(typeof(List))]
+[JsonSerializable(typeof(LogTailDto))]
+[JsonSerializable(typeof(DashboardDto))]
public sealed partial class ProtocolJson : JsonSerializerContext;
diff --git a/src/Titano.Protocol/Sequences.cs b/src/Titano.Protocol/Sequences.cs
index ab3bb730..eaebcc0d 100644
--- a/src/Titano.Protocol/Sequences.cs
+++ b/src/Titano.Protocol/Sequences.cs
@@ -102,3 +102,26 @@ public sealed record ArchiveStatsDto(
int UnverifiedSequences);
public sealed record KeyValueCount(string Key, long Count, long Bytes);
+
+/// GET /api/v1/sequences/{id}/stats: frame totals by format and flagged frames.
+public sealed record SequenceStatsDto(
+ Guid SequenceId,
+ int FrameCount,
+ long TotalBytes,
+ DateTime? FirstCapture,
+ DateTime? LastCapture,
+ double? MedianInterval,
+ IReadOnlyList ByFormat,
+ long MissingFrames,
+ long CorruptFrames,
+ long DuplicateFrames,
+ long ExcludedFrames);
+
+///
+/// DELETE /api/v1/sequences/{id}: what the delete does (with ?dryRun=true) or did. The folder is moved
+/// to inside the archive, never erased.
+///
+public sealed record SequenceDeletePlan(Guid SequenceId, string? Folder, string? TrashFolder, int FrameCount, long TotalBytes, int RenderCount, bool DryRun);
+
+/// GET/PUT /api/v1/archive/settings (admin). The root path comes from the server configuration.
+public sealed record ArchiveSettingsDto(Guid Id, string Name, string RootPath, string FolderTemplate, string FileTemplate, int ProxyLongEdge);
diff --git a/src/Titano.Server/Admin/web/admin.css b/src/Titano.Server/Admin/web/admin.css
index ee54015d..feb6c1a8 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,190 @@ 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-x: auto; }
+.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(110px, 1.4fr) 90px minmax(100px, 1.2fr) minmax(80px, 1fr) 70px 70px 230px; }
+.table.jobs .thead, .table.jobs .row { grid-template-columns: 110px minmax(140px, 1.5fr) 100px minmax(110px, 1fr) 100px 80px 280px; }
+.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 100px; }
+.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; }
+.person { 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); }
+.fingerprint { font: 12px var(--mono); color: var(--text); overflow-wrap: anywhere; }
+
+/* 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 `