Load server logs with validated session-bound query options

This commit is contained in:
omar committed 2026-11-27 20:36:39 +03:00
1 parent 8e9f28c856
commit aff60b9ff3
12 files changed
+419 -19

No files matched your search

+2
View File
@@ -2,6 +2,8 @@
## Unreleased ## Unreleased
- Server Log now waits for Load and accepts the requested line count, start position, order and instance flag. A refusal leaves the request editable; switching server tabs invalidates the old request.
- Server Info discards late replies from a closed panel or a previous connection. Empty, ambiguous and mismatched server-property replies no longer open an editor. - Server Info discards late replies from a closed panel or a previous connection. Empty, ambiguous and mismatched server-property replies no longer open an editor.
- The Move to Own Channel form checks the password's 1024-byte UTF-8 limit before submission and preserves leading and trailing spaces. - The Move to Own Channel form checks the password's 1024-byte UTF-8 limit before submission and preserves leading and trailing spaces.
+2
View File
@@ -2,6 +2,8 @@
## Current Windows account-free checkpoint (2026-11-26) ## Current Windows account-free checkpoint (2026-11-26)
**Server Log on Windows:** With two muted beta14 guests the form showed all four query fields. Cancelling or submitting invalid bounds produced no log panel. Load returned PermissionsClientInsufficient for the guest and retained the submitted options. Changing the viewed tab rejected the old form. Literal line order, metadata-only rows, empty results and malformed replies were checked separately with synthetic data. Successful reading of a permitted server log remains unverified.
**Server Info on Windows:** Two muted beta14 guests opened the server tree row's menu in turn. The rendered name and welcome message matched a separate server_info response for each connection, and the edit action retained the viewed tab's session and server UID. Model tests rejected obsolete results after Back, a new connection generation or a different UID. No server settings were changed. **Server Info on Windows:** Two muted beta14 guests opened the server tree row's menu in turn. The rendered name and welcome message matched a separate server_info response for each connection, and the edit action retained the viewed tab's session and server UID. Model tests rejected obsolete results after Back, a new connection generation or a different UID. No server settings were changed.
**Protected move destination:** On private beta14 the move confirmation opened with an empty secret field for a protected destination. An oversized multibyte password and a tab were rejected in the editor. Cancelling left the two guests in their original channels. A command-builder test checked that a 1024-byte password including surrounding spaces was preserved. This does not establish a successful server-authorized participant move. **Protected move destination:** On private beta14 the move confirmation opened with an empty secret field for a protected destination. An oversized multibyte password and a tab were rejected in the editor. Cancelling left the two guests in their original channels. A command-builder test checked that a 1024-byte password including surrounding spaces was preserved. This does not establish a successful server-authorized participant move.
+2
View File
@@ -4,6 +4,8 @@
## Возврат к разработке на ПК, 2026-11-26 ## Возврат к разработке на ПК, 2026-11-26
Windows, база `8e9f28c`: форма журнала принимает число строк, позицию, порядок и флаг экземпляра. На beta14 проверены отмена, ошибки границ, видимый отказ гостю с сохранением полей и отклонение формы прежней вкладки. Прошли пять нативных тестов и тест stdio на границу позиции; содержимое журнала в отчёт не выводилось. Положительный ответ авторизованному пользователю на живом сервере не проверен.
Windows, база `5e73b78`: закрыт `command:server_info`. На двух вкладках beta14 панель показала имя и приветствие из отдельных ответов сервера, а действие редактирования сохранило нужную сессию и UID. Проверены закрытие панели и отбрасывание устаревших результатов в модели; пустой, неоднозначный и чужой ответ не открывает редактор. Прошли четыре нативных теста и тест ядра на аргументы. Серверные настройки не менялись. Windows, база `5e73b78`: закрыт `command:server_info`. На двух вкладках beta14 панель показала имя и приветствие из отдельных ответов сервера, а действие редактирования сохранило нужную сессию и UID. Проверены закрытие панели и отбрасывание устаревших результатов в модели; пустой, неоднозначный и чужой ответ не открывает редактор. Прошли четыре нативных теста и тест ядра на аргументы. Серверные настройки не менялись.
Windows, база `cebac97`: форма переноса в защищённый канал проверяет пароль до отправки. На приватном beta14 поле открылось пустым, неверные значения остались с ошибкой, отмена не переместила участника. Отдельно проверена передача в команду пароля длиной 1024 байта с пробелами по краям. Прошли три нативных проверки и тест stdio. Перенос с разрешением сервера не подтверждён. Windows, база `cebac97`: форма переноса в защищённый канал проверяет пароль до отправки. На приватном beta14 поле открылось пустым, неверные значения остались с ошибкой, отмена не переместила участника. Отдельно проверена передача в команду пароля длиной 1024 байта с пробелами по краям. Прошли три нативных проверки и тест stdio. Перенос с разрешением сервера не подтверждён.
+7 -1
View File
@@ -58,6 +58,8 @@ pub(super) fn require_server_editor_target(ctx: &RuntimeServices, target: &Targe
rows.iter().any(|row| row["id"] == *id && row["uid"].as_str() == Some(uid.as_str()))) => Ok(()), rows.iter().any(|row| row["id"] == *id && row["uid"].as_str() == Some(uid.as_str()))) => Ok(()),
(Operation::ServerEdit, Entity::Server { uid }) if !uid.is_empty() (Operation::ServerEdit, Entity::Server { uid }) if !uid.is_empty()
&& server["server"]["uid"].as_str() == Some(uid.as_str()) => Ok(()), && server["server"]["uid"].as_str() == Some(uid.as_str()) => Ok(()),
(Operation::ServerLog, Entity::Server { uid }) if !uid.is_empty() && snapshots.viewed_id.as_ref()==Some(&key.connection_id)
&& server["server"]["uid"].as_str()==Some(uid.as_str()) => Ok(()),
(Operation::ChannelEdit, Entity::Channel { id }) if *id != 0 (Operation::ChannelEdit, Entity::Channel { id }) if *id != 0
&& server["channels"].as_array().is_some_and(|rows| rows.iter().any(|row| row["id"].as_u64() == Some(*id))) => Ok(()), && server["channels"].as_array().is_some_and(|rows| rows.iter().any(|row| row["id"].as_u64() == Some(*id))) => Ok(()),
(Operation::ClientPoke, Entity::Client { id, uid, .. }) if *id != 0 && !uid.is_empty() (Operation::ClientPoke, Entity::Client { id, uid, .. }) if *id != 0 && !uid.is_empty()
@@ -103,9 +105,13 @@ pub(super) async fn submit_server_editor(ctx: &Arc<RuntimeServices>, target: &Ta
check()?; check()?;
} }
} }
ctx.request(key, command).await?; let response=ctx.request(key, command).await?;
ctx.require_ui_generation(ui_generation)?; ctx.require_ui_generation(ui_generation)?;
require_server_editor_reply_target(ctx,target,operation)?; require_server_editor_reply_target(ctx,target,operation)?;
if operation==Operation::ServerLog {
let detail=server_actions::project(target,operation,&response,&catalog(ctx)?)?;
return Ok(WorkflowResult::effect(UiEffect::Detail{target:target.clone(),detail}));
}
let mut result = WorkflowResult::default(); let mut result = WorkflowResult::default();
if operation == Operation::ServerEdit { if operation == Operation::ServerEdit {
let refreshed = async { let refreshed = async {
+9 -4
View File
@@ -58,6 +58,11 @@ fn snapshot_session_viewed(key: &SessionKey, connections: &ConnectionsSnapshot)
connections.viewed_id.as_deref() == Some(key.connection_id.as_str()) connections.viewed_id.as_deref() == Some(key.connection_id.as_str())
&& connections.get(&key.connection_id).is_some_and(|tab| tab.key == *key && tab.is_connected()) && connections.get(&key.connection_id).is_some_and(|tab| tab.key == *key && tab.is_connected())
} }
fn server_detail_viewed(target:&Target,connections:&ConnectionsSnapshot)->bool {
let (Some(key),Entity::Server{uid})=(&target.session,&target.entity) else{return false};
!uid.is_empty() && connections.viewed_id.as_ref()==Some(&key.connection_id) && connections.get(&key.connection_id)
.is_some_and(|tab|tab.is_connected() && tab.key==*key && tab.server.as_ref().and_then(|s|s["server"]["uid"].as_str())==Some(uid.as_str()))
}
pub struct AppState { pub struct AppState {
pub snapshot:Snapshot,pub selected:Option<Target>,pub folder:Option<String>, pub snapshot:Snapshot,pub selected:Option<Target>,pub folder:Option<String>,
pub detail_target:Option<Target>,pub detail_operation:Option<Operation>,pub query:crate::app::server_actions::QueryOptions, pub detail_target:Option<Target>,pub detail_operation:Option<Operation>,pub query:crate::app::server_actions::QueryOptions,
@@ -259,8 +264,7 @@ impl AppState {
.is_some_and(|rows| rows.iter().any(|row| row["id"].as_u64() == Some(u64::from(*id)) .is_some_and(|rows| rows.iter().any(|row| row["id"].as_u64() == Some(u64::from(*id))
&& row["uid"].as_str() == Some(uid.as_str()))) { return false; } && row["uid"].as_str() == Some(uid.as_str()))) { return false; }
} else if matches!(operation,Operation::ServerClients|Operation::ServerInfo) { } else if matches!(operation,Operation::ServerClients|Operation::ServerInfo) {
let Entity::Server{uid}=&target.entity else{return false}; if !server_detail_viewed(&target,connections){return false;}
if uid.is_empty() || !viewed.is_connected() || viewed.server.as_ref().and_then(|s|s["server"]["uid"].as_str())!=Some(uid.as_str()){return false;}
} else if result.is_ok() { } else if result.is_ok() {
// Preserve Channel Info's existing error handling for the viewed session. // Preserve Channel Info's existing error handling for the viewed session.
let Entity::Channel { id } = target.entity else { return false; }; let Entity::Channel { id } = target.entity else { return false; };
@@ -418,12 +422,13 @@ impl AppState {
let notifications=ctx.notifications.lock().map_err(|_|super::notification_actions::unavailable())?; let notifications=ctx.notifications.lock().map_err(|_|super::notification_actions::unavailable())?;
self.project_recent_server_events(viewed,&notifications,&c,prefs["chatUse24hTime"]!=false,ctx.notification_clock.epoch_ms()); self.project_recent_server_events(viewed,&notifications,&c,prefs["chatUse24hTime"]!=false,ctx.notification_clock.epoch_ms());
} else if self.detail_target.as_ref().is_some_and(|t|{ } else if self.detail_target.as_ref().is_some_and(|t|{
(matches!(self.detail_operation,Some(Operation::ClientInfo|Operation::ClientConnectionInfo)) (matches!(t.entity,Entity::Server{..}) && !server_detail_viewed(t,&connections))
|| (matches!(self.detail_operation,Some(Operation::ClientInfo|Operation::ClientConnectionInfo))
&& viewed.is_none_or(|tab| t.session.as_ref() != Some(&tab.key))) && viewed.is_none_or(|tab| t.session.as_ref() != Some(&tab.key)))
|| ctx.require_target(t).is_err() || ctx.require_target(t).is_err()
}){ }){
if self.snapshot.snapshot_progress.is_some() { self.leave_snapshot(); } if self.snapshot.snapshot_progress.is_some() { self.leave_snapshot(); }
self.detail_target=None;self.snapshot.detail=Detail::default(); self.detail_target=None;self.detail_operation=None;self.snapshot.detail=Detail::default();
} }
self.snapshot.settings=super::settings_actions::project(ctx,&self.snapshot.settings_view)?; self.snapshot.settings=super::settings_actions::project(ctx,&self.snapshot.settings_view)?;
if let Some((uid,level))=viewed.and_then(|tab|tab.identity_challenge()) { if let Some((uid,level))=viewed.and_then(|tab|tab.identity_challenge()) {
+6 -1
View File
@@ -107,7 +107,12 @@ pub fn prepare(t:&Target,op:Operation,v:&Values)->Result<Option<Command>> {
ServerKeys=>{server(t)?;Command::Admin(A::PrivilegeKeyList)}, ServerKeys=>{server(t)?;Command::Admin(A::PrivilegeKeyList)},
ServerPasswords=>{server(t)?;Command::Admin(A::TempPasswordList)}, ServerPasswords=>{server(t)?;Command::Admin(A::TempPasswordList)},
ServerClients=>{server(t)?;extra(X::ClientDatabaseList{start:0,duration:25})}, ServerClients=>{server(t)?;extra(X::ClientDatabaseList{start:0,duration:25})},
ServerLog=>{server(t)?;extra(X::ServerLog{lines:100,reverse:true,instance:false,begin_pos:0})}, ServerLog=>{
server(t)?;
let lines=u16::try_from(number(v,"lines")?).map_err(|_|bad("lines must be 1..1000"))?;
let flag=|k:&str|match v.get(k){Some(FieldValue::Bool(b))=>Ok(*b),_=>Err(bad("Expected a boolean server log option"))};
extra(X::ServerLog{lines,begin_pos:number(v,"begin_pos")?,reverse:flag("reverse")?,instance:flag("instance")?})
},
ServerGroupCreate|ChannelGroupCreate=>{server(t)?;let kind=if op==ServerGroupCreate{GroupKind::Server}else{GroupKind::Channel};let group_type=match text(v,"type")?.as_str(){"template"=>0,"regular"=>1,"query"=>2,_=>return Err(bad("Invalid group type"))};extra(X::GroupAdd{generation,kind,name:text(v,"name")?,group_type})}, ServerGroupCreate|ChannelGroupCreate=>{server(t)?;let kind=if op==ServerGroupCreate{GroupKind::Server}else{GroupKind::Channel};let group_type=match text(v,"type")?.as_str(){"template"=>0,"regular"=>1,"query"=>2,_=>return Err(bad("Invalid group type"))};extra(X::GroupAdd{generation,kind,name:text(v,"name")?,group_type})},
GroupRename=>{let(kind,group_id)=group(t)?;extra(X::GroupRename{generation,kind,group_id,name:text(v,"name")?})}, GroupRename=>{let(kind,group_id)=group(t)?;extra(X::GroupRename{generation,kind,group_id,name:text(v,"name")?})},
GroupDelete=>{let(kind,group_id)=group(t)?;extra(X::GroupDelete{generation,kind,group_id,force:true,confirm:group_id.to_string()})}, GroupDelete=>{let(kind,group_id)=group(t)?;extra(X::GroupDelete{generation,kind,group_id,force:true,confirm:group_id.to_string()})},
+51 -8
View File
@@ -1,5 +1,6 @@
use super::*; use super::*;
use crate::ui::{i18n::Catalog, shell::{Action, Detail, Entry, InfoRow}}; use crate::ui::{i18n::Catalog, shell::{Action, Detail, Entry, InfoRow}};
use std::fmt::Write as _;
mod connection_info; mod connection_info;
@@ -7,18 +8,17 @@ mod connection_info;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Refresh { None, Snapshot { target: Target }, Query { target: Target, command: Command }, FileDirectory { target: Target } } pub enum Refresh { None, Snapshot { target: Target }, Query { target: Target, command: Command }, FileDirectory { target: Target } }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct QueryOptions { pub offset:u32, pub page_size:u16, pub search:String, pub search_uid:bool, pub log_lines:u16, pub log_begin_pos:u64, pub log_reverse:bool, pub log_instance:bool } pub struct QueryOptions { pub offset:u32, pub page_size:u16, pub search:String, pub search_uid:bool }
impl Default for QueryOptions {fn default()->Self {Self{offset:0,page_size:25,search:String::new(),search_uid:false,log_lines:100,log_begin_pos:0,log_reverse:true,log_instance:false}}} impl Default for QueryOptions {fn default()->Self {Self{offset:0,page_size:25,search:String::new(),search_uid:false}}}
pub fn query(t:&Target,op:Operation,options:&QueryOptions)->Result<Command>{ pub fn query(t:&Target,op:Operation,options:&QueryOptions)->Result<Command>{
generation(t)?; generation(t)?;
let command=match op { let command=match op {
Operation::ServerClients=>{server(t)?;if options.search.trim().is_empty(){extra(X::ClientDatabaseList{start:options.offset,duration:options.page_size})}else{if options.offset!=0{return Err(bad("Database search does not accept pagination"))}extra(X::ClientDatabaseFind{pattern:options.search.trim().into(),uid:options.search_uid})}}, Operation::ServerClients=>{server(t)?;if options.search.trim().is_empty(){extra(X::ClientDatabaseList{start:options.offset,duration:options.page_size})}else{if options.offset!=0{return Err(bad("Database search does not accept pagination"))}extra(X::ClientDatabaseFind{pattern:options.search.trim().into(),uid:options.search_uid})}},
Operation::ServerLog=>{server(t)?;extra(X::ServerLog{lines:options.log_lines,reverse:options.log_reverse,instance:options.log_instance,begin_pos:options.log_begin_pos})},
Operation::GroupPermissions if matches!(t.entity,Entity::Channel{..})=>Command::Admin(A::ChannelPermList{channel_id:channel(t)?}), Operation::GroupPermissions if matches!(t.entity,Entity::Channel{..})=>Command::Admin(A::ChannelPermList{channel_id:channel(t)?}),
_=>prepare(t,op,&Values::new())?.ok_or_else(||bad("Operation is not a core query"))? _=>prepare(t,op,&Values::new())?.ok_or_else(||bad("Operation is not a core query"))?
}; };
if !matches!(op,Operation::ServerInfo|Operation::ServerClients|Operation::ServerLog|Operation::ServerBans|Operation::ServerKeys|Operation::ServerPasswords|Operation::ServerPermissions|Operation::TalkQueue|Operation::ChannelInfo|Operation::ClientInfo|Operation::ClientConnectionInfo|Operation::ClientPermissions|Operation::GroupPermissions|Operation::FileBrowse|Operation::FileRefresh|Operation::TransferList){return Err(bad("Operation is not a query"))} if !matches!(op,Operation::ServerInfo|Operation::ServerClients|Operation::ServerBans|Operation::ServerKeys|Operation::ServerPasswords|Operation::ServerPermissions|Operation::TalkQueue|Operation::ChannelInfo|Operation::ClientInfo|Operation::ClientConnectionInfo|Operation::ClientPermissions|Operation::GroupPermissions|Operation::FileBrowse|Operation::FileRefresh|Operation::TransferList){return Err(bad("Operation is not a query"))}
validate_command(command.clone()).map_err(core)?;Ok(command) validate_command(command.clone()).map_err(core)?;Ok(command)
} }
@@ -53,6 +53,17 @@ fn action(t:&Target,op:Operation,c:&Catalog,context:Option<&Value>,permission:&s
} }
fn row_fields(d:&mut Detail,row:&Value,fields:&[(&str,&str)],c:&Catalog){for(key,label)in fields{let value=string(row,key);if !value.is_empty(){d.rows.push(InfoRow{label:c.text(label),value})}}} fn row_fields(d:&mut Detail,row:&Value,fields:&[(&str,&str)],c:&Catalog){for(key,label)in fields{let value=string(row,key);if !value.is_empty(){d.rows.push(InfoRow{label:c.text(label),value})}}}
fn append_log_value(output: &mut String, value: &Value) -> Result<()> {
match value {
Value::String(text) => output.push_str(text),
Value::Number(_) | Value::Bool(_) | Value::Null => {
write!(output, "{value}").expect("writing to a String cannot fail");
}
_ => return Err(ServiceError::new("bad_response", "Server log fields must be scalar")),
}
Ok(())
}
/// Projects a successful reply only. The caller checks the captured SessionKey /// Projects a successful reply only. The caller checks the captured SessionKey
/// first. Permission-sensitive actions require a fresh admin/client context. /// first. Permission-sensitive actions require a fresh admin/client context.
pub fn project(t:&Target,op:Operation,reply:&Value,c:&Catalog)->Result<Detail>{project_with_context(t,op,reply,c,None,&QueryOptions::default())} pub fn project(t:&Target,op:Operation,reply:&Value,c:&Catalog)->Result<Detail>{project_with_context(t,op,reply,c,None,&QueryOptions::default())}
@@ -72,17 +83,49 @@ pub fn project_with_context(t:&Target,op:Operation,reply:&Value,c:&Catalog,conte
return Ok(d) return Ok(d)
} }
if matches!(op,Operation::FileBrowse|Operation::FileRefresh){return files(t,reply,c)} if matches!(op,Operation::FileBrowse|Operation::FileRefresh){return files(t,reply,c)}
let rows=reply.get("rows").and_then(Value::as_array).ok_or_else(||bad("Query reply is missing its rows"))?; let invalid_rows = |message| {
if rows.len()>teamspeach_core::admin::MAX_ROWS{return Err(bad("Query reply exceeds the core row bound"))} ServiceError::new(if op == Operation::ServerLog { "bad_response" } else { "bad_request" }, message)
};
let rows=reply.get("rows").and_then(Value::as_array).ok_or_else(||invalid_rows("Query reply is missing its rows"))?;
if rows.len()>teamspeach_core::admin::MAX_ROWS{return Err(invalid_rows("Query reply exceeds the core row bound"))}
match op { match op {
Operation::ServerBans|Operation::ServerKeys|Operation::ServerPasswords|Operation::ServerClients|Operation::ServerLog=>{ Operation::ServerLog => {
server(t)?;
if rows.is_empty() {
d.description = c.text("admin.noResults");
}
for (index, row) in rows.iter().enumerate() {
let row = row.as_object().filter(|row| !row.is_empty()).ok_or_else(|| {
invalid_rows("Server log rows must be nonempty objects")
})?;
if index != 0 {
d.description.push('\n');
}
if let Some(line) = row.get("l").filter(|line| !line.is_null()) {
if row.values().any(|value| value.is_array() || value.is_object()) {
return Err(invalid_rows("Server log fields must be scalar"));
}
append_log_value(&mut d.description, line)?;
} else {
for (index, (key, value)) in row.iter().enumerate() {
if index != 0 {
d.description.push(' ');
}
d.description.push_str(key);
d.description.push('=');
append_log_value(&mut d.description, value)?;
}
}
}
},
Operation::ServerBans|Operation::ServerKeys|Operation::ServerPasswords|Operation::ServerClients=>{
for (index,row) in rows.iter().enumerate(){ for (index,row) in rows.iter().enumerate(){
let(mut e,remove,right)=match op { let(mut e,remove,right)=match op {
Operation::ServerBans=>{let ban_id=id(row,"banid")?;let title=["name","ip","uid","mytsid"].iter().map(|k|string(row,k)).find(|s|!s.is_empty()).unwrap_or_else(||ban_id.to_string());(entry(t,Entity::Ban{id:ban_id},format!("ban:{ban_id}"),title,string(row,"reason")),Some(Operation::BanDelete),"b_client_ban_delete")}, Operation::ServerBans=>{let ban_id=id(row,"banid")?;let title=["name","ip","uid","mytsid"].iter().map(|k|string(row,k)).find(|s|!s.is_empty()).unwrap_or_else(||ban_id.to_string());(entry(t,Entity::Ban{id:ban_id},format!("ban:{ban_id}"),title,string(row,"reason")),Some(Operation::BanDelete),"b_client_ban_delete")},
Operation::ServerKeys=>{let token=string(row,"token");if token.is_empty(){return Err(bad("Privilege key reply has no token"))}(entry(t,Entity::PrivilegeKey(token.clone()),format!("key:{index}"),token,string(row,"token_description")),Some(Operation::KeyDelete),"b_virtualserver_token_delete")}, Operation::ServerKeys=>{let token=string(row,"token");if token.is_empty(){return Err(bad("Privilege key reply has no token"))}(entry(t,Entity::PrivilegeKey(token.clone()),format!("key:{index}"),token,string(row,"token_description")),Some(Operation::KeyDelete),"b_virtualserver_token_delete")},
Operation::ServerPasswords=>{let password=string(row,"pw");if password.is_empty(){return Err(bad("Temporary password reply has no password"))}(entry(t,Entity::TemporaryPassword(password.clone()),format!("password:{index}"),password,string(row,"desc")),Some(Operation::PasswordDelete),"b_virtualserver_modify_temporary_passwords")}, Operation::ServerPasswords=>{let password=string(row,"pw");if password.is_empty(){return Err(bad("Temporary password reply has no password"))}(entry(t,Entity::TemporaryPassword(password.clone()),format!("password:{index}"),password,string(row,"desc")),Some(Operation::PasswordDelete),"b_virtualserver_modify_temporary_passwords")},
Operation::ServerClients=>{let dbid=id(row,"cldbid")?;(entry(t,Entity::DatabaseClient(dbid),format!("db:{dbid}"),string(row,"client_nickname"),string(row,"client_unique_identifier")),Some(Operation::ClientDatabaseDelete),"b_client_delete_dbproperties")}, Operation::ServerClients=>{let dbid=id(row,"cldbid")?;(entry(t,Entity::DatabaseClient(dbid),format!("db:{dbid}"),string(row,"client_nickname"),string(row,"client_unique_identifier")),Some(Operation::ClientDatabaseDelete),"b_client_delete_dbproperties")},
Operation::ServerLog=>(entry(t,t.entity.clone(),format!("log:{}:{index}",options.offset),string(row,"l"),String::new()),None,""),_=>unreachable!() _=>unreachable!()
}; };
if let Some(remove)=remove{e.actions.push(action(&e.target,remove,c,context,right));}d.entries.push(e); if let Some(remove)=remove{e.actions.push(action(&e.target,remove,c,context,right));}d.entries.push(e);
} }
+63
View File
@@ -80,6 +80,69 @@ fn database_query_enforces_wire_limits_without_truncating_search(){
assert!(query(&t,Operation::ServerClients,&q).is_err()); assert!(query(&t,Operation::ServerClients,&q).is_err());
} }
#[test]
fn server_log_projects_literal_lines_and_fallback_fields_in_response_order() {
let t = target(Entity::Server { uid: "server".into() });
let catalog = crate::ui::i18n::Catalog::default();
let reply = serde_json::json!({"rows": [
{"l": " first | <literal> \\ line ", "file_size": "123"},
{"l": "", "file_size": "ignored"},
{"last_pos": "80", "file_size": "123"},
{"l": null, "file_size": 123},
{"l": "last"}
]});
let detail = project(&t, Operation::ServerLog, &reply, &catalog).unwrap();
assert_eq!(detail.description, " first | <literal> \\ line \n\nlast_pos=80 file_size=123\nl=null file_size=123\nlast");
assert!(detail.entries.is_empty() && detail.rows.is_empty());
let empty = project(&t, Operation::ServerLog, &serde_json::json!({"rows": []}), &catalog).unwrap();
assert_eq!(empty.description, catalog.text("admin.noResults"));
assert!(empty.entries.is_empty() && empty.rows.is_empty());
for malformed in [
serde_json::json!({}),
serde_json::json!({"rows": {}}),
serde_json::json!({"rows": [null]}),
serde_json::json!({"rows": [[]]}),
serde_json::json!({"rows": [{}]}),
serde_json::json!({"rows": [{"l": ["not a line"]}]}),
serde_json::json!({"rows": [{"file_size": {}}]}),
serde_json::json!({"rows": [{"l": "valid line", "file_size": {}}]}),
] {
assert!(matches!(project(&t, Operation::ServerLog, &malformed, &catalog), Err(e) if e.code == "bad_response"));
}
}
#[test]
fn server_log_prepare_requires_submitted_values_and_validates_bounds() {
let t = target(Entity::Server { uid: "server".into() });
let max_position = teamspeach_core::admin::MAX_SAFE_INTEGER as i64;
let mut v = values(&[
("lines", FieldValue::Integer(1000)),
("begin_pos", FieldValue::Integer(max_position)),
("reverse", FieldValue::Bool(false)),
("instance", FieldValue::Bool(true)),
]);
assert!(matches!(prepare(&t, Operation::ServerLog, &v).unwrap(),
Some(Command::Admin(A::Extra(X::ServerLog { lines: 1000, begin_pos, reverse: false, instance: true })))
if begin_pos == max_position as u64));
assert!(query(&t, Operation::ServerLog, &QueryOptions::default()).is_err());
for (key, invalid) in [
("lines", FieldValue::Integer(-1)),
("lines", FieldValue::Integer(0)),
("lines", FieldValue::Integer(1001)),
("lines", FieldValue::Integer(65_537)),
("begin_pos", FieldValue::Integer(-1)),
("begin_pos", FieldValue::Integer(max_position + 1)),
("reverse", FieldValue::Text("false".into())),
("instance", FieldValue::Integer(1)),
] {
let original = v.insert(key.into(), invalid).unwrap();
assert!(matches!(prepare(&t, Operation::ServerLog, &v), Err(e) if e.code == "bad_request"), "{key}");
v.insert(key.into(), original);
}
}
#[test] #[test]
fn move_never_uses_an_editable_destination_or_uncaptured_channel(){ fn move_never_uses_an_editable_destination_or_uncaptured_channel(){
let t=target(Entity::Client{id:4,uid:"uid".into(),channel_id:2}); let t=target(Entity::Client{id:4,uid:"uid".into(),channel_id:2});
+261
View File
@@ -0,0 +1,261 @@
//! Read-only Server Log coverage against the isolated desktop beta14 guest fixture.
use super::{
ParticipantFixture, SmokeResult, await_tree_menu_action, click_tab, headless, pace_beta14,
rendered_detail_text, rendered_form_button, rendered_tree_menu_action,
run_muted_beta14_participant_fixture, view_muted_beta14_tab,
};
use super::super::{focus, key_profiles::until};
use crate::{
AppRuntime, AppWindow, DialogBridge, ShellBridge,
app::{connections::SessionKey, runtime::context::{RuntimeServices, changed}},
ui::shell::{Entity, Operation, Target},
};
use i_slint_core::{
accessibility::AccessibleStringProperty as Property,
item_tree::ItemRc,
items::{AccessibleRole, ComplexText, SimpleText, TextInput},
window::WindowInner,
};
use slint::{ComponentHandle, Model, SharedString, platform::{Key, WindowEvent}};
const FIELDS: [(&str, &str); 4] = [
("lines", "admin.logLines"),
("begin_pos", "admin.logPosition"),
("reverse", "admin.logReverse"),
("instance", "admin.logInstance"),
];
const DEFAULTS: [&str; 4] = ["100", "0", "true", "false"];
const INVALID: [&str; 4] = ["1001", "9007199254740992", "false", "true"];
const VALID: [&str; 4] = ["2", "1", "false", "true"];
#[test]
#[ignore = "requires exclusive use of private beta14 at 127.0.0.1:19987"]
fn server_log_editor_queries_and_rejects_stale_beta14_tab() {
if headless::install_for_test() {
run_muted_beta14_participant_fixture(ParticipantFixture::ServerLog);
}
}
pub(super) async fn exercise(runtime: &AppRuntime, ui: &AppWindow, owner: &RuntimeServices, tabs: &[SessionKey; 2]) -> SmokeResult<()> {
let [first, second] = tabs;
view_muted_beta14_tab(runtime, ui, first, 0).await?;
let shell = ui.global::<ShellBridge>();
let dialog = ui.global::<DialogBridge>();
let catalog = runtime.snapshot().catalog;
let title = catalog.text("admin.log");
let load = catalog.text("admin.load");
let cancel = catalog.text("native.action.cancel");
let labels = FIELDS.map(|(_, label)| catalog.text(label));
let loading = catalog.text("native.status.loading");
let open = async || {
let id = open_form(runtime, ui, first, &title, &loading).await?;
if dialog.get_submit_label() != load || dialog.get_cancel_label() != cancel || dialog.get_destructive() {
return Err("Server Log did not open a read-only Load/Cancel form".into());
}
check_draft(ui, &title, &labels, DEFAULTS, "")?;
Ok::<_, String>(id)
};
let close = async || {
rendered_form_button(ui, &title, &cancel)?;
until("Server Log cancelled without a pending form", || !dialog.get_visible() && runtime.snapshot().dialog.is_none()).await
};
let previous_error = shell.get_error();
let no_result = || shell.get_subtitle() != title && !shell.get_detail_loading() && shell.get_error() == previous_error;
let cancelled = open().await?;
replace_text(ui, &title, &labels[0], DEFAULTS[0], "7")?;
if !no_result() { return Err(format!("unexpected state before Load: log detail={}, loading={}, global error changed={}",
shell.get_subtitle()==title,shell.get_detail_loading(),shell.get_error()!=previous_error)); }
close().await?;
if !no_result() { return Err("cancelling Server Log produced a result".into()); }
let current = open().await?;
if current == cancelled { return Err("reopened Server Log reused the cancelled editor".into()); }
replace_text(ui, &title, &labels[0], DEFAULTS[0], INVALID[0])?;
replace_text(ui, &title, &labels[1], DEFAULTS[1], INVALID[1])?;
for label in &labels[2..] {
focus::activate(focus::visible_selector(ui, label, AccessibleRole::Checkbox)?)?;
}
rendered_form_button(ui, &title, &load)?;
let range_error = catalog.text("native.form.number");
check_draft(ui, &title, &labels, INVALID, &range_error)?;
if dialog.get_busy() || !dialog.get_error().is_empty() || !no_result()
|| form_text_count(ui, &title, &range_error)? != 2 {
return Err("invalid Server Log fields did not retain two visible range errors without loading".into());
}
replace_text(ui, &title, &labels[0], INVALID[0], VALID[0])?;
replace_text(ui, &title, &labels[1], INVALID[1], VALID[1])?;
pace_beta14().await?;
rendered_form_button(ui, &title, &load)?;
until("Server Log result or server rejection", || {
(!dialog.get_visible() && shell.get_subtitle() == title)
|| (dialog.get_visible() && !dialog.get_busy() && !dialog.get_error().is_empty())
}).await?;
if dialog.get_visible() {
let error = dialog.get_error();
if !error.contains("PermissionsClientInsufficient") || form_text_count(ui, &title, error.as_str())? != 1 || !no_result() {
return Err("Server Log did not display the beta14 guest permission refusal in the editor".into());
}
check_draft(ui, &title, &labels, VALID, "")?;
eprintln!("beta14 Server Log: permission refused; submitted options retained");
close().await?;
} else {
let target = server_target(runtime, first)?;
let empty = catalog.text("admin.noResults");
check_result(runtime, ui, &target, &title, &empty)?;
eprintln!("beta14 Server Log: {}", if runtime.snapshot().detail.description == empty { "empty result" } else { "rows received" });
ui.invoke_back_requested();
until("successful Server Log detail closed before stale submission", no_result).await?;
}
let stale = open().await?;
replace_text(ui, &title, &labels[0], DEFAULTS[0], VALID[0])?;
// The modal blocks tab clicks. Change the real manager view, leaving the captured editor intact.
owner.connected.connections.view(second).await.map_err(|e| e.to_string())?;
owner.changed().await.map_err(|e| e.code)?;
let second_viewed = || {
let state = runtime.snapshot();
state.connections.viewed_id.as_deref() == Some(second.connection_id.as_str())
&& state.connections.get(&second.connection_id).is_some_and(|tab| tab.key == *second && tab.is_connected())
};
let old_capture = || runtime.snapshot().dialog.as_ref().is_some_and(|f| f.id == stale && f.target.session.as_ref() == Some(first));
until("second guest viewed with the original Server Log editor still open", || {
second_viewed() && old_capture() && dialog.get_visible() && dialog.get_error().is_empty() && no_result()
}).await?;
rendered_form_button(ui, &title, &load)?;
let stale_error = changed().message;
until("stale Server Log submission rejected in the original editor", || {
dialog.get_visible() && !dialog.get_busy() && dialog.get_error() == stale_error
}).await?;
check_draft(ui, &title, &labels, [VALID[0], DEFAULTS[1], DEFAULTS[2], DEFAULTS[3]], "")?;
if !second_viewed() || !old_capture() || !no_result() || form_text_count(ui, &title, &stale_error)? != 1 {
return Err("stale Server Log submission leaked a result or did not render the target error".into());
}
close().await
}
fn server_target(runtime: &AppRuntime, key: &SessionKey) -> SmokeResult<Target> {
let snapshot = runtime.snapshot();
let server = snapshot.connections.get(&key.connection_id)
.filter(|tab| tab.key == *key && tab.is_connected()).and_then(|tab| tab.server.as_deref())
.ok_or("missing viewed beta14 server")?;
let uid = server["server"]["uid"].as_str().filter(|uid| !uid.is_empty()).ok_or("missing beta14 server UID")?;
snapshot.tree.iter().map(|entry| &entry.row)
.find(|row| row.id == "server" && row.target.session.as_ref() == Some(key)
&& matches!(&row.target.entity, Entity::Server { uid: captured } if captured == uid))
.map(|row| row.target.clone()).ok_or_else(|| "missing scoped server tree row".into())
}
async fn open_form(runtime: &AppRuntime, ui: &AppWindow, key: &SessionKey, title: &str, loading: &str) -> SmokeResult<String> {
let shell = ui.global::<ShellBridge>();
let dialog = ui.global::<DialogBridge>();
until("beta14 server row for the viewed tab", || server_target(runtime, key).is_ok()).await?;
let target = server_target(runtime, key)?;
let row = shell.get_tree().iter().find(|row| row.id == "tree/server" && row.title == target.name)
.ok_or("missing tree/server Slint row")?;
shell.invoke_context(row.id, 20., 20.);
let action = await_tree_menu_action(ui, &target.name, title, loading).await?;
if !action.enabled || !action.id.starts_with("popup/") || !action.id.ends_with("/ServerLog") {
return Err("server tree menu did not offer the exact enabled ServerLog token".into());
}
// The real menu item's accessible action invokes the captured popup token.
focus::activate(rendered_tree_menu_action(ui, &target.name, title).await?)?;
until("idle Server Log form for the exact server and session", || {
!shell.get_menu_visible() && dialog.get_visible() && !dialog.get_busy() && dialog.get_title() == title
&& dialog.get_error().is_empty() && runtime.snapshot().dialog.as_ref().is_some_and(|f| {
f.target == target && f.operation == Operation::ServerLog
})
}).await?;
runtime.snapshot().dialog.as_ref().map(|f| f.id.clone()).ok_or_else(|| "missing Server Log editor capture".into())
}
fn check_draft(ui: &AppWindow, title: &str, labels: &[String; 4], values: [&str; 4], numeric_error: &str) -> SmokeResult<()> {
let form = focus::visible_selector(ui, title, AccessibleRole::Form)?;
let fields = ui.global::<DialogBridge>().get_fields();
if fields.row_count() != FIELDS.len() { return Err("unexpected Server Log field count".into()); }
for (index, ((id, _), expected)) in FIELDS.into_iter().zip(values).enumerate() {
let label = &labels[index];
let field = fields.iter().find(|f| f.id == id).ok_or("missing Server Log field")?;
let error = if index < 2 { numeric_error } else { "" };
if !field.enabled || field.label != *label || field.value != expected || field.error != error {
return Err(format!("Server Log field {id} did not retain its draft or validation state"));
}
let rendered = if index < 2 {
let input = visible_field(ui, &form, label, AccessibleRole::TextInput)?;
input.downcast::<TextInput>().is_some_and(|input| input.as_pin_ref().text() == expected)
} else {
visible_field(ui, &form, label, AccessibleRole::Checkbox)?.accessible_string_property(Property::Checked).as_deref() == Some(expected)
};
if !rendered { return Err(format!("Server Log field {id} did not render its expected value")); }
}
Ok(())
}
fn visible_field(ui: &AppWindow, form: &ItemRc, label: &str, role: AccessibleRole) -> SmokeResult<ItemRc> {
descendants(form).find(|item| {
let matching_kind = if role == AccessibleRole::TextInput { item.downcast::<TextInput>().is_some() } else { item.accessible_role() == role };
matching_kind && item.accessible_string_property(Property::Label).as_deref() == Some(label)
&& headless::visible_bounds(ui.window(), item).is_some()
}).ok_or_else(|| format!("Server Log field {label} was not on screen"))
}
fn descendants(form: &ItemRc) -> impl Iterator<Item = ItemRc> {
let mut pending: Vec<_> = form.first_child().into_iter().collect();
std::iter::from_fn(move || {
let item = pending.pop()?;
pending.extend(item.next_sibling());
pending.extend(item.first_child());
Some(item)
})
}
fn replace_text(ui: &AppWindow, title: &str, label: &str, before: &str, after: &str) -> SmokeResult<()> {
let form = focus::visible_selector(ui, title, AccessibleRole::Form)?;
let item = visible_field(ui, &form, label, AccessibleRole::TextInput)?;
let field = item.downcast::<TextInput>().ok_or("Server Log numeric field is not editable text")?;
if field.as_pin_ref().text() != before { return Err("unexpected Server Log input draft".into()); }
click_tab(ui, headless::visible_bounds(ui.window(), &item).ok_or("Server Log numeric field not visible")?)?;
if !WindowInner::from_pub(ui.window()).text_input_focused() { return Err("Server Log text input did not take focus".into()); }
let key = |text: SharedString| -> SmokeResult<()> {
for event in [WindowEvent::KeyPressed { text: text.clone() }, WindowEvent::KeyReleased { text }] {
ui.window().dispatch_event_with_result(event).map_err(|e| e.to_string())?;
}
Ok(())
};
key(Key::End.into())?;
for _ in before.chars() { key(Key::Backspace.into())?; }
key(after.into())?;
if field.as_pin_ref().text() != after { return Err("Server Log input changed or truncated the typed value".into()); }
Ok(())
}
fn form_text_count(ui: &AppWindow, title: &str, expected: &str) -> SmokeResult<usize> {
let form = focus::visible_selector(ui, title, AccessibleRole::Form)?;
let mut count = 0;
for item in descendants(&form) {
if headless::visible_bounds(ui.window(), &item).is_none() { continue; }
if item.downcast::<SimpleText>().map(|text| text.as_pin_ref().text())
.or_else(|| item.downcast::<ComplexText>().map(|text| text.as_pin_ref().text()))
.is_some_and(|text| text == expected) { count += 1; }
}
Ok(count)
}
fn check_result(runtime: &AppRuntime, ui: &AppWindow, target: &Target, title: &str, empty: &str) -> SmokeResult<()> {
let shell = ui.global::<ShellBridge>();
let snapshot = runtime.snapshot();
let detail = &snapshot.detail;
let rendered = rendered_detail_text(ui)?;
let shows = |value: &str| rendered.iter().any(|text| text == value);
if shell.get_stage() != 0 || shell.get_detail_loading() || detail.title != target.name || detail.subtitle != title
|| !shows(title) || !detail.error.is_empty() || shell.get_entries().row_count() != 0 {
return Err("Server Log did not render the requested detail".into());
}
if detail.description == empty {
if !shows(empty) { return Err("empty Server Log result did not render its empty state".into()); }
} else if detail.description.trim().is_empty() || !shows(&detail.description) {
return Err("Server Log did not render its literal result text".into());
}
Ok(())
}
+6 -1
View File
@@ -891,7 +891,7 @@ fn participant_context_menu_projects_muted_beta14_capabilities() {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
#[derive(Clone, Copy, PartialEq, Eq)] #[derive(Clone, Copy, PartialEq, Eq)]
enum ParticipantFixture { Info, Statistics, Poke, Context, Volume, Commander, Move, ServerInfo } enum ParticipantFixture { Info, Statistics, Poke, Context, Volume, Commander, Move, ServerInfo, ServerLog }
#[cfg(target_os="windows")] #[cfg(target_os="windows")]
#[test] #[test]
@@ -917,6 +917,10 @@ mod participant_gain;
#[path = "participant_commander.rs"] #[path = "participant_commander.rs"]
mod participant_commander; mod participant_commander;
#[cfg(target_os = "windows")]
#[path = "server_log.rs"]
mod server_log;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
fn run_muted_beta14_participant_fixture(scenario: ParticipantFixture) { fn run_muted_beta14_participant_fixture(scenario: ParticipantFixture) {
use super::key_profiles::until; use super::key_profiles::until;
@@ -966,6 +970,7 @@ fn run_muted_beta14_participant_fixture(scenario: ParticipantFixture) {
let uids = await_muted_beta14_roster(runtime, &tabs, clients).await?; let uids = await_muted_beta14_roster(runtime, &tabs, clients).await?;
match scenario { match scenario {
ParticipantFixture::ServerInfo => return exercise_server_info(runtime,ui,&owner,&tabs).await, ParticipantFixture::ServerInfo => return exercise_server_info(runtime,ui,&owner,&tabs).await,
ParticipantFixture::ServerLog => return server_log::exercise(runtime, ui, &owner, &tabs).await,
ParticipantFixture::Move => return exercise_peer_move(runtime,ui,&owner,&tabs,clients,&uids).await, ParticipantFixture::Move => return exercise_peer_move(runtime,ui,&owner,&tabs,clients,&uids).await,
ParticipantFixture::Statistics => return exercise_beta14_connection_info(runtime, ui, &owner, &mut tabs, clients, &uids, &identities[1]).await, ParticipantFixture::Statistics => return exercise_beta14_connection_info(runtime, ui, &owner, &mut tabs, clients, &uids, &identities[1]).await,
ParticipantFixture::Poke => return exercise_beta14_poke(runtime, ui, &owner, &mut tabs, clients, &uids, ParticipantFixture::Poke => return exercise_beta14_poke(runtime, ui, &owner, &mut tabs, clients, &uids,
+2 -2
View File
@@ -47,7 +47,7 @@ pub fn bind(runtime:Arc<AppRuntime>,generation:u64)->Result<UiAttachment,AppErro
let shell=shell::bind(&window,Arc::new(move|action|{ let shell=shell::bind(&window,Arc::new(move|action|{
let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)) else{return}; let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)) else{return};
let result=match action { let result=match action {
shell::ShellAction::Submit{ref editor_id, ref target, operation,..} if shell::forms::tracked_participant(operation)=>{ shell::ShellAction::Submit{ref editor_id, ref target, operation,..} if shell::forms::tracked_participant(operation)||operation==shell::Operation::ServerLog=>{
let (id,target)=(editor_id.clone(),target.clone()); let (id,target)=(editor_id.clone(),target.clone());
let command=crate::app::runtime::RuntimeCommand::AttachmentShell{action,ui_generation:generation}; let command=crate::app::runtime::RuntimeCommand::AttachmentShell{action,ui_generation:generation};
if let Err(error)=runtime.enqueue(command) { if let Err(error)=runtime.enqueue(command) {
@@ -76,7 +76,7 @@ pub fn bind(runtime:Arc<AppRuntime>,generation:u64)->Result<UiAttachment,AppErro
}, },
action if matches!(&action,shell::ShellAction::Invoke{operation,..} action if matches!(&action,shell::ShellAction::Invoke{operation,..}
if crate::app::runtime::scoped_detail_query(*operation)) if crate::app::runtime::scoped_detail_query(*operation))
|| matches!(&action,shell::ShellAction::Invoke{operation,..} if shell::forms::tracked_participant(*operation) || *operation==shell::Operation::ClientVolume) || matches!(&action,shell::ShellAction::Invoke{operation,..} if shell::forms::tracked_participant(*operation) || matches!(operation,shell::Operation::ClientVolume|shell::Operation::ServerLog))
|| matches!(&action,shell::ShellAction::Cancel{..}|shell::ShellAction::Page{..}|shell::ShellAction::Search{..}) || matches!(&action,shell::ShellAction::Cancel{..}|shell::ShellAction::Page{..}|shell::ShellAction::Search{..})
|| matches!(&action,shell::ShellAction::Invoke{operation,..}|shell::ShellAction::Submit{operation,..} || matches!(&action,shell::ShellAction::Invoke{operation,..}|shell::ShellAction::Submit{operation,..}
if matches!(operation,shell::Operation::SnapshotApply|shell::Operation::SnapshotExport|shell::Operation::SnapshotCancel))=>{ if matches!(operation,shell::Operation::SnapshotApply|shell::Operation::SnapshotExport|shell::Operation::SnapshotCancel))=>{
+8 -2
View File
@@ -3,7 +3,7 @@ use super::super::i18n::Catalog;
use teamspeach_core::menu::{MAX_POKE_BYTES, valid_poke_message}; use teamspeach_core::menu::{MAX_POKE_BYTES, valid_poke_message};
pub(crate) fn tracks_server_ack(operation: Operation) -> bool { pub(crate) fn tracks_server_ack(operation: Operation) -> bool {
matches!(operation, Operation::ChannelEdit | Operation::ServerEdit | Operation::SetNickname) || tracked_participant(operation) matches!(operation, Operation::ChannelEdit | Operation::ServerEdit | Operation::SetNickname | Operation::ServerLog) || tracked_participant(operation)
} }
pub(crate) fn tracked_participant(operation: Operation) -> bool { pub(crate) fn tracked_participant(operation: Operation) -> bool {
matches!(operation,Operation::ClientMove|Operation::ClientPoke|Operation::ClientCommander) matches!(operation,Operation::ClientMove|Operation::ClientPoke|Operation::ClientCommander)
@@ -242,6 +242,12 @@ pub fn form(id:&str, operation:Operation, target:Target, c:&Catalog)->Option<For
} }
ChannelMove => fields.extend([target_choice(c,"parent_id","admin.parent"),target_choice(c,"order","admin.insertAfter")]), ChannelMove => fields.extend([target_choice(c,"parent_id","admin.parent"),target_choice(c,"order","admin.insertAfter")]),
ChannelDelete => fields.push(toggle(c,"force","admin.forceDelete",false)), ChannelDelete => fields.push(toggle(c,"force","admin.forceDelete",false)),
ServerLog => fields.extend([
number(c,"lines","admin.logLines",1,1000,100),
number(c,"begin_pos","admin.logPosition",0,teamspeach_core::admin::MAX_SAFE_INTEGER as i64,0),
toggle(c,"reverse","admin.logReverse",true),
toggle(c,"instance","admin.logInstance",false),
]),
ServerEdit => { ServerEdit => {
for (name,max,multiline) in [("name",64,false),("welcomemessage",8192,true),("nickname",1024,false),("name_phonetic",1024,false),("hostmessage",8192,true),("hostbanner_url",1024,false),("hostbanner_gfx_url",1024,false),("hostbutton_tooltip",1024,false),("hostbutton_url",1024,false),("hostbutton_gfx_url",1024,false)] { for (name,max,multiline) in [("name",64,false),("welcomemessage",8192,true),("nickname",1024,false),("name_phonetic",1024,false),("hostmessage",8192,true),("hostbanner_url",1024,false),("hostbanner_gfx_url",1024,false),("hostbutton_tooltip",1024,false),("hostbutton_url",1024,false),("hostbutton_gfx_url",1024,false)] {
let mut f=text(c,&format!("virtualserver_{name}"),&format!("admin.serverField.{name}"),max,name=="name"); if multiline { f.kind=FieldKind::Multiline; } fields.push(f); let mut f=text(c,&format!("virtualserver_{name}"),&format!("admin.serverField.{name}"),max,name=="name"); if multiline { f.kind=FieldKind::Multiline; } fields.push(f);
@@ -305,7 +311,7 @@ pub fn form(id:&str, operation:Operation, target:Target, c:&Catalog)->Option<For
}; };
let actions=auxiliary.iter().enumerate().map(|(index,op)|Action{id:format!("{id}/aux/{index}"),label:c.text(label_key(*op)),target:target.clone(),operation:*op,enabled:true,reason:String::new(),destructive:destructive(*op),form:None}).collect(); let actions=auxiliary.iter().enumerate().map(|(index,op)|Action{id:format!("{id}/aux/{index}"),label:c.text(label_key(*op)),target:target.clone(),operation:*op,enabled:true,reason:String::new(),destructive:destructive(*op),form:None}).collect();
let confirmation=if destructive(operation) || matches!(operation,ServerEdit|SnapshotApply|ExportIdentity|ConfirmIdentityExport|ImportLegacyProfile) { Some(target.name.clone()) } else { None }; let confirmation=if destructive(operation) || matches!(operation,ServerEdit|SnapshotApply|ExportIdentity|ConfirmIdentityExport|ImportLegacyProfile) { Some(target.name.clone()) } else { None };
let submit_key=if operation==StreamEdit { "native.action.save" } else { label_key(operation) }; let submit_key=match operation {StreamEdit=>"native.action.save",ServerLog=>"admin.load",_=>label_key(operation)};
Some(Form{id:id.into(),target,operation,title:c.text(label_key(operation)),description,fields,confirmation,submit_label:c.text(submit_key),destructive:destructive(operation),busy:false,error:String::new(),actions,acknowledged_revision:0}) Some(Form{id:id.into(),target,operation,title:c.text(label_key(operation)),description,fields,confirmation,submit_label:c.text(submit_key),destructive:destructive(operation),busy:false,error:String::new(),actions,acknowledged_revision:0})
} }