Verify the restored Windows download location with a real transfer
This commit is contained in:
1 parent
6712e6dab6
commit
e7951f1bc6
5 files changed
+468
No files matched your search
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
## Current Windows account-free checkpoint (2026-11-26)
|
## Current Windows account-free checkpoint (2026-11-26)
|
||||||
|
|
||||||
|
**Windows default download folder:** Transfer Settings selected and cancelled through the system folder picker. After restart, a muted beta14 guest downloaded the fixture's 46 known bytes using classic file transfer into the selected folder. Cancelling an overwrite preserved the existing bytes without queuing a transfer. A separate restart test removed the selected folder and observed the restore error without recreating it or staging a download. To reproduce the positive test, provision `/teamspeach-download-smoke.bin` in the disposable server's default channel with `BYTES` from `native/src/smoke/download_folder_fixture.rs`; the guest needs list and read permission only. This covers Windows `preload:filesChooseDefaultDir`, not S3, uploads, or multi-tab limits.
|
||||||
|
|
||||||
**Recording destination on Windows:** Audio Settings opened the Windows folder picker. Selecting a disposable folder updated Settings; Cancel retained it, generic preferences could not replace it, and two fresh runtime launches restored it. Both beta14 recording exports landed in that folder. A separate service test rejected failed persistence and stale chooser results without granting access. This covers Windows `preload:pickRecordingFolder` and `preference:recordingFolder`, not Android or iOS document pickers.
|
**Recording destination on Windows:** Audio Settings opened the Windows folder picker. Selecting a disposable folder updated Settings; Cancel retained it, generic preferences could not replace it, and two fresh runtime launches restored it. Both beta14 recording exports landed in that folder. A separate service test rejected failed persistence and stale chooser results without granting access. This covers Windows `preload:pickRecordingFolder` and `preference:recordingFolder`, not Android or iOS document pickers.
|
||||||
|
|
||||||
**Recording commands on beta14:** The Slint panel started, paused, resumed and stopped a master take in a disposable destination. The track waveform, recorder status and info were checked against the silent PCM export and its timeline. Cancelling or submitting an invalid start left the destination untouched. During a second take, old buttons and a queued Stop could not pause or stop it; the first WAV remained byte-for-byte intact. Reconnection opened an idle recorder. Eleven native checks passed. A separate offline stdio test rejected malformed arguments for all seven recording commands with bad_request and preserved an existing file. No physical audio devices were opened.
|
**Recording commands on beta14:** The Slint panel started, paused, resumed and stopped a master take in a disposable destination. The track waveform, recorder status and info were checked against the silent PCM export and its timeline. Cancelling or submitting an invalid start left the destination untouched. During a second take, old buttons and a queued Stop could not pause or stop it; the first WAV remained byte-for-byte intact. Reconnection opened an idle recorder. Eleven native checks passed. A separate offline stdio test rejected malformed arguments for all seven recording commands with bad_request and preserved an existing file. No physical audio devices were opened.
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
## Возврат к разработке на ПК, 2026-11-26
|
## Возврат к разработке на ПК, 2026-11-26
|
||||||
|
|
||||||
|
Windows, база `6712e6d`: проверен `preload:filesChooseDefaultDir`. Два теста Slint: после перезапуска гостевой клиент beta14 получил 46 ожидаемых байт в выбранную папку; отсутствующая папка вызвала ошибку без подстановки другого пути. Классический стенд получил исходный файл при создании; загрузка гостем на сервер не разрешена, S3 не проверен. Стенд остановлен.
|
||||||
|
|
||||||
Windows, база `9a518bd`: выбор папки записи проверен из настроек звука через системный диалог. Отмена и попытка записи через общие настройки путь не изменили; после двух перезапусков оба WAV экспортированы в выбранную папку. Прошли два теста; стенд beta14 остановлен. Мобильные диалоги не проверялись.
|
Windows, база `9a518bd`: выбор папки записи проверен из настроек звука через системный диалог. Отмена и попытка записи через общие настройки путь не изменили; после двух перезапусков оба WAV экспортированы в выбранную папку. Прошли два теста; стенд beta14 остановлен. Мобильные диалоги не проверялись.
|
||||||
|
|
||||||
Windows, база `5916610`: проверены семь команд `recording_*`. Панель Slint запрашивает статус ядра; старый Stop не останавливает вторую запись. На beta14 сверены форма сигнала, длительность и WAV, сохранность первого файла и чистое состояние после переподключения. Прошли 11 нативных проверок и отдельный тест stdio на неверные аргументы. Физический звук не использовался; стенд остановлен.
|
Windows, база `5916610`: проверены семь команд `recording_*`. Панель Slint запрашивает статус ядра; старый Stop не останавливает вторую запись. На beta14 сверены форма сигнала, длительность и WAV, сохранность первого файла и чистое состояние после переподключения. Прошли 11 нативных проверок и отдельный тест stdio на неверные аргументы. Физический звук не использовался; стенд остановлен.
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ mod focus;
|
|||||||
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod key_profiles;
|
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod key_profiles;
|
||||||
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod recording_waveform;
|
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod recording_waveform;
|
||||||
#[cfg(all(test, windows))] mod owned_folder_dialog;
|
#[cfg(all(test, windows))] mod owned_folder_dialog;
|
||||||
|
#[cfg(all(test, windows))] mod download_folder;
|
||||||
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod theme_selection;
|
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod theme_selection;
|
||||||
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod speaker_gain;
|
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod speaker_gain;
|
||||||
#[cfg(feature="webrtc")] pub mod media;
|
#[cfg(feature="webrtc")] pub mod media;
|
||||||
|
|||||||
@@ -0,0 +1,288 @@
|
|||||||
|
use std::{env, fs, io::{self, Write}, path::Path, process::Command};
|
||||||
|
use slint::ComponentHandle;
|
||||||
|
|
||||||
|
use super::{SmokeResult, identities::{ack, category, row, run_ui, wait}, key_profiles::until, owned_folder_dialog::OwnedFolderDialog};
|
||||||
|
use crate::{AppConfig, AppRuntime, AppWindow, DialogBridge, SettingsBridge, ShellBridge,
|
||||||
|
app::runtime::model::Snapshot, platform::desktop::documents::restore_directory,
|
||||||
|
services::{ServiceError, profile_import::initialize_native_root},
|
||||||
|
ui::{settings::Category, shell::{Entity, Operation, ShellAction, Target}},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[path = "download_folder_fixture.rs"]
|
||||||
|
mod download_folder_fixture;
|
||||||
|
use download_folder_fixture::{BYTES, REMOTE_NAME, existing_file, connect_guest, disconnect_guest, guest_identity};
|
||||||
|
|
||||||
|
const FOLDER: &str = "selected-downloads";
|
||||||
|
const ASK: &str = "files:ask";
|
||||||
|
const CHOOSE: &str = "files-choose";
|
||||||
|
const LOCATION: &str = "files-location";
|
||||||
|
|
||||||
|
/// The exact test runs in its own process to isolate Slint and the Windows profile environment.
|
||||||
|
#[test]
|
||||||
|
#[ignore = "requires private beta14 with the known teamspeach-download-smoke.bin in the default channel"]
|
||||||
|
fn chosen_download_folder_survives_restart_and_receives_the_file() {
|
||||||
|
isolated_scenario(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "requires winit and the private beta14 loopback fixture"]
|
||||||
|
fn missing_download_folder_does_not_fall_back_after_restart() {
|
||||||
|
isolated_scenario(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn isolated_scenario(download_file: bool) {
|
||||||
|
const CHILD: &str = "TEAMSPEACH_DOWNLOAD_FOLDER_TEST_CHILD";
|
||||||
|
let thread = std::thread::current();
|
||||||
|
let name = thread.name().expect("expected a named libtest thread");
|
||||||
|
if env::var(CHILD).as_deref() == Ok(name) {
|
||||||
|
scenario(download_file).unwrap_or_else(|error| panic!("{error}"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let sandbox = tempfile::tempdir().expect("create isolated Windows profile base");
|
||||||
|
let output = Command::new(env::current_exe().expect("locate test binary"))
|
||||||
|
.args(["--exact", name, "--ignored", "--nocapture"])
|
||||||
|
.env(CHILD, name)
|
||||||
|
.env("APPDATA", sandbox.path())
|
||||||
|
.env("LOCALAPPDATA", sandbox.path())
|
||||||
|
.output().expect("start isolated winit test process");
|
||||||
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||||
|
assert!(output.status.success() && stdout.contains("1 passed"), "{name}: {}\n{stdout}\n{}",
|
||||||
|
output.status, String::from_utf8_lossy(&output.stderr));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scenario(download_file: bool) -> SmokeResult<()> {
|
||||||
|
slint::BackendSelector::new().backend_name("winit".into()).renderer_name("software".into()).select().map_err(|e| e.to_string())?;
|
||||||
|
let temp = tempfile::tempdir().map_err(|e| e.to_string())?;
|
||||||
|
let root = temp.path().join("profile");
|
||||||
|
let destination = temp.path().join(FOLDER);
|
||||||
|
let inactive = temp.path().join("unavailable-selected-downloads");
|
||||||
|
fs::create_dir(&destination).map_err(|e| e.to_string())?;
|
||||||
|
let selected = destination.canonicalize().map_err(|e| e.to_string())?;
|
||||||
|
let saved = selected.to_string_lossy().into_owned();
|
||||||
|
initialize_native_root(&root).map_err(|e| e.to_string())?;
|
||||||
|
let identity = guest_identity(&root)?;
|
||||||
|
let config = AppConfig { allow_os_actions: true, ..AppConfig::isolated(root.clone()) };
|
||||||
|
|
||||||
|
let picker_path = destination.clone();
|
||||||
|
let expected = saved.clone();
|
||||||
|
run_ui(&config, async move |runtime, ui| {
|
||||||
|
open_transfers(runtime, ui).await?;
|
||||||
|
set_ask(runtime, ui, true).await?;
|
||||||
|
wait(runtime, "always-ask hides default destination", |_| row(ui, CHOOSE).is_none().then_some(())).await?;
|
||||||
|
set_ask(runtime, ui, false).await?;
|
||||||
|
expect_location(runtime, ui, "", "").await?;
|
||||||
|
choose(runtime, ui, Some(&picker_path), "choose default download directory").await?;
|
||||||
|
expect_location(runtime, ui, &expected, FOLDER).await?;
|
||||||
|
choose(runtime, ui, None, "cancel default download chooser").await?;
|
||||||
|
expect_location(runtime, ui, &expected, FOLDER).await
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let expected = saved.clone();
|
||||||
|
let guest = identity.clone();
|
||||||
|
let folder = destination.clone();
|
||||||
|
let staging = root.join("file-workflows").join("downloads");
|
||||||
|
let transfer_stage = staging.clone();
|
||||||
|
if download_file { return run_ui(&config, async move |runtime, ui| {
|
||||||
|
open_transfers(runtime, ui).await?;
|
||||||
|
expect_location(runtime, ui, &expected, &expected).await?;
|
||||||
|
ui.global::<ShellBridge>().invoke_navigate(0);
|
||||||
|
let target = existing_file(runtime, &guest).await?;
|
||||||
|
let outcome = download(runtime, ui, target.clone(), &folder, &transfer_stage).await;
|
||||||
|
let cleanup = disconnect_guest(runtime, &target).await;
|
||||||
|
combine(outcome, "disconnect read-only guest", disconnected(runtime, cleanup).await)
|
||||||
|
}); }
|
||||||
|
|
||||||
|
// Remove the original name only after the transfer runtime has closed its directory grant.
|
||||||
|
fs::rename(&destination, &inactive).map_err(|e| format!("make selected folder unavailable: {e}"))?;
|
||||||
|
run_ui(&config, async move |runtime, ui| {
|
||||||
|
open_transfers(runtime, ui).await?;
|
||||||
|
expect_location(runtime, ui, &saved, &saved).await?;
|
||||||
|
ui.global::<ShellBridge>().invoke_navigate(0);
|
||||||
|
let guest = connect_guest(runtime, &identity).await?;
|
||||||
|
let outcome = reject_unavailable(runtime, ui, guest.clone(), &selected).await;
|
||||||
|
let cleanup = disconnect_guest(runtime, &guest).await;
|
||||||
|
combine(outcome, "disconnect stale-path probe", disconnected(runtime, cleanup).await)?;
|
||||||
|
if destination.try_exists().map_err(|e| e.to_string())? {
|
||||||
|
return Err("FileDownload recreated the unavailable chosen folder".into());
|
||||||
|
}
|
||||||
|
empty_or_absent(&staging)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn open_transfers(runtime: &AppRuntime, ui: &AppWindow) -> SmokeResult<()> {
|
||||||
|
wait(runtime, "isolated download settings", |s| (s.settings.loaded && s.settings.files.is_some()).then_some(())).await?;
|
||||||
|
ui.global::<ShellBridge>().invoke_navigate(3);
|
||||||
|
category(runtime, ui, Category::FileTransfer).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_ask(runtime: &AppRuntime, ui: &AppWindow, enabled: bool) -> SmokeResult<()> {
|
||||||
|
let toggle = wait(runtime, "always-ask download toggle", |_| row(ui, ASK).filter(|row| row.enabled)).await?;
|
||||||
|
let serial = runtime.snapshot().settings_completed + 1;
|
||||||
|
ui.global::<SettingsBridge>().invoke_toggle_value(toggle.token, enabled);
|
||||||
|
ack(runtime, serial, "save always-ask download setting", None).await?;
|
||||||
|
wait(runtime, "always-ask value in Transfers settings", |s| {
|
||||||
|
(s.settings.files.as_ref().is_some_and(|files| files.always_ask == enabled)
|
||||||
|
&& row(ui, ASK).is_some_and(|control| control.checked == enabled)).then_some(())
|
||||||
|
}).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn choose(runtime: &AppRuntime, ui: &AppWindow, directory: Option<&Path>, label: &str) -> SmokeResult<()> {
|
||||||
|
let button = wait(runtime, "enabled default download chooser", |_| row(ui, CHOOSE).filter(|row| row.enabled)).await?;
|
||||||
|
let serial = runtime.snapshot().settings_completed + 1;
|
||||||
|
let picker = OwnedFolderDialog::start(directory)?;
|
||||||
|
ui.global::<SettingsBridge>().invoke_invoke(button.token);
|
||||||
|
picker.finish().await.map_err(|error| format!("{label}: {error}"))?;
|
||||||
|
ack(runtime, serial, label, None).await.map(|_| ()).map_err(|error| {
|
||||||
|
runtime.snapshot().last_error.as_ref().map_or(error, |e| format!("{label}: {}: {}", e.code, e.message))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn expect_location(runtime: &AppRuntime, ui: &AppWindow, saved: &str, visible: &str) -> SmokeResult<()> {
|
||||||
|
wait(runtime, "saved and visible default download destination", |s| {
|
||||||
|
(s.settings.files.as_ref().is_some_and(|files| {
|
||||||
|
!files.always_ask && files.approved_download_dir.as_deref() == (!saved.is_empty()).then(|| Path::new(saved))
|
||||||
|
}) && row(ui, ASK).is_some_and(|control| !control.checked)
|
||||||
|
&& row(ui, LOCATION).is_some_and(|location| location.subtitle.as_str() == visible)).then_some(())
|
||||||
|
}).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn download(runtime: &AppRuntime, ui: &AppWindow, target: Target, folder: &Path, staging: &Path) -> SmokeResult<()> {
|
||||||
|
let name = REMOTE_NAME;
|
||||||
|
crate::platform::resources::require_component(name).map_err(|e| e.to_string())?;
|
||||||
|
runtime.dispatch_shell(ShellAction::Invoke {
|
||||||
|
target: Target { entity: Entity::Connection, ..target.clone() }, operation: Operation::TransferList,
|
||||||
|
}).map_err(|e| format!("open baseline Transfers: {}: {}", e.code, e.message))?;
|
||||||
|
let baseline = observe(runtime, "baseline transfer history", |s| {
|
||||||
|
transfer_panel(s).then(|| Ok(transfer_ids(s).collect::<Vec<_>>()))
|
||||||
|
}).await?;
|
||||||
|
runtime.dispatch_shell(ShellAction::Back).map_err(|e| format!("dismiss baseline Transfers: {}: {}", e.code, e.message))?;
|
||||||
|
observe(runtime, "dismissed transfer panel", |s| (!transfer_panel(s)).then_some(Ok(()))).await?;
|
||||||
|
|
||||||
|
let file = folder.join(name);
|
||||||
|
const SENTINEL: &[u8] = b"existing fixture file, do not overwrite";
|
||||||
|
fs::File::create_new(&file).and_then(|mut file| file.write_all(SENTINEL)).map_err(|e| format!("create collision sentinel: {e}"))?;
|
||||||
|
|
||||||
|
{
|
||||||
|
// If the workflow unexpectedly asks for a folder, dismiss only its owned native picker.
|
||||||
|
let _unexpected_picker = OwnedFolderDialog::start(None)?;
|
||||||
|
let dialog = ui.global::<DialogBridge>();
|
||||||
|
invoke_download(runtime, target.clone())?;
|
||||||
|
observe(runtime, "overwrite confirmation for the collision sentinel", |s| {
|
||||||
|
s.dialog.as_ref().filter(|form| form.operation == Operation::ConfirmOverwrite && form.target == target
|
||||||
|
&& form.confirmation.as_deref() == Some(name) && dialog.get_visible()).map(|_| Ok(()))
|
||||||
|
}).await?;
|
||||||
|
require_contents(&file, SENTINEL)?;
|
||||||
|
dialog.invoke_cancel();
|
||||||
|
observe(runtime, "cancelled overwrite with no transfer queued", |s| {
|
||||||
|
(s.dialog.is_none() && !dialog.get_visible() && transfer_panel(s)).then(|| {
|
||||||
|
if transfer_ids(s).eq(baseline.iter().copied()) { Ok(()) }
|
||||||
|
else { Err("cancelling overwrite changed transfer history".into()) }
|
||||||
|
})
|
||||||
|
}).await?;
|
||||||
|
require_contents(&file, SENTINEL)?;
|
||||||
|
empty_or_absent(staging)?;
|
||||||
|
}
|
||||||
|
fs::remove_file(&file).map_err(|e| format!("remove collision sentinel: {e}"))?;
|
||||||
|
|
||||||
|
let _unexpected_picker = OwnedFolderDialog::start(None)?;
|
||||||
|
invoke_download(runtime, target.clone())?;
|
||||||
|
observe(runtime, "publication of the downloaded fixture file", |s| {
|
||||||
|
let row = s.detail.entries.iter().filter(|row| row.title == name && row.target.session == target.session)
|
||||||
|
.find(|row| matches!(row.target.entity, Entity::Transfer { id } if !baseline.contains(&id)))?;
|
||||||
|
let action = |op| row.actions.iter().any(|action| action.enabled && action.operation == op);
|
||||||
|
if action(Operation::TransferOpen) && action(Operation::TransferReveal) {
|
||||||
|
Some(Ok(()))
|
||||||
|
} else if action(Operation::TransferClear) {
|
||||||
|
Some(Err(format!("FileDownload transfer: {}", row.subtitle)))
|
||||||
|
} else { None }
|
||||||
|
}).await?;
|
||||||
|
require_contents(&file, BYTES)?;
|
||||||
|
empty_or_absent(staging)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn reject_unavailable(runtime: &AppRuntime, ui: &AppWindow, mut target: Target, unavailable: &Path) -> SmokeResult<()> {
|
||||||
|
let expected = match restore_directory(unavailable) {
|
||||||
|
Err(error) if error.code == "io" => error,
|
||||||
|
Err(error) => return Err(format!("unexpected unavailable directory error: {}: {}", error.code, error.message)),
|
||||||
|
Ok(_) => return Err("restored a grant to the removed directory".into()),
|
||||||
|
};
|
||||||
|
let Entity::Channel { id: channel_id } = target.entity else { return Err("guest is missing its fixture channel".into()); };
|
||||||
|
// If changed code falls back to system Downloads, Windows must reject this leaf before a file can be opened.
|
||||||
|
target.name = "CON".into();
|
||||||
|
target.entity = Entity::File { channel_id, path: "/CON".into(), directory: false };
|
||||||
|
let _unexpected_picker = OwnedFolderDialog::start(None)?;
|
||||||
|
invoke_download(runtime, target)?;
|
||||||
|
let shell = ui.global::<ShellBridge>();
|
||||||
|
let mut actual = None;
|
||||||
|
until("visible FileDownload rejection for an unavailable configured directory", || {
|
||||||
|
let s = runtime.snapshot();
|
||||||
|
actual = s.last_error.clone();
|
||||||
|
!silent(&s) || actual.as_ref().is_some_and(|error| shell.get_error().as_str() == error.message)
|
||||||
|
}).await.map_err(|timeout| actual.as_ref().map_or(timeout, |e| format!("FileDownload: {}: {}", e.code, e.message)))?;
|
||||||
|
if !silent(&runtime.snapshot()) { return Err("download probe started physical audio".into()); }
|
||||||
|
let Some(ServiceError { code, message }) = actual else { return Err("missing FileDownload error".into()); };
|
||||||
|
if (code.as_str(), message.as_str()) != (expected.code.as_str(), expected.message.as_str()) {
|
||||||
|
return Err(format!("FileDownload did not report the saved-directory failure: {code}: {message} (expected {}: {})", expected.code, expected.message));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn disconnected(runtime: &AppRuntime, cleanup: SmokeResult<()>) -> SmokeResult<()> {
|
||||||
|
cleanup?;
|
||||||
|
until("disposable guest disconnected in runtime snapshot", || !runtime.snapshot().connections.any_active()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transfer_panel(s: &Snapshot) -> bool { s.detail.title == s.catalog.text("files.transfers.title") }
|
||||||
|
|
||||||
|
fn transfer_ids(s: &Snapshot) -> impl Iterator<Item = u32> + '_ {
|
||||||
|
s.detail.entries.iter().filter_map(|row| match row.target.entity { Entity::Transfer { id } => Some(id), _ => None })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invoke_download(runtime: &AppRuntime, target: Target) -> SmokeResult<()> {
|
||||||
|
runtime.dispatch_shell(ShellAction::Invoke { target, operation: Operation::FileDownload })
|
||||||
|
.map_err(|error| format!("FileDownload dispatch: {}: {}", error.code, error.message))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn observe<T>(runtime: &AppRuntime, label: &str, mut ready: impl FnMut(&Snapshot) -> Option<SmokeResult<T>>) -> SmokeResult<T> {
|
||||||
|
let mut result = None;
|
||||||
|
until(label, || {
|
||||||
|
let s = runtime.snapshot();
|
||||||
|
result = if !silent(&s) { Some(Err("download workflow started physical audio".into())) }
|
||||||
|
else if let Some(error) = &s.last_error { Some(Err(format!("{label}: {}: {}", error.code, error.message))) }
|
||||||
|
else { ready(&s) };
|
||||||
|
result.is_some()
|
||||||
|
}).await.map_err(|error| {
|
||||||
|
let s = runtime.snapshot();
|
||||||
|
if s.error.is_empty() { error } else { format!("{error}: {}", s.error) }
|
||||||
|
})?;
|
||||||
|
result.ok_or("missing download observation")?
|
||||||
|
}
|
||||||
|
|
||||||
|
fn silent(s: &Snapshot) -> bool {
|
||||||
|
!s.audio_input_active && !s.audio_output_active && s.audio_input_starts == 0 && s.audio_output_starts == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_contents(path: &Path, expected: &[u8]) -> SmokeResult<()> {
|
||||||
|
let bytes = fs::read(path).map_err(|e| format!("read {}: {e}", path.display()))?;
|
||||||
|
if bytes != expected { return Err(format!("unexpected contents at {} ({} bytes)", path.display(), bytes.len())); }
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn empty_or_absent(path: &Path) -> SmokeResult<()> {
|
||||||
|
match fs::read_dir(path) {
|
||||||
|
Ok(mut entries) => match entries.next().transpose().map_err(|e| e.to_string())? {
|
||||||
|
None => Ok(()), Some(_) => Err(format!("download left transfer staging at {}", path.display())),
|
||||||
|
},
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||||
|
Err(error) => Err(format!("inspect transfer staging at {}: {error}", path.display())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn combine(primary: SmokeResult<()>, label: &str, secondary: SmokeResult<()>) -> SmokeResult<()> {
|
||||||
|
match (primary, secondary) {
|
||||||
|
(Err(error), Err(other)) => Err(format!("{error}; {label}: {other}")),
|
||||||
|
(Ok(()), Err(other)) => Err(format!("{label}: {other}")),
|
||||||
|
(outcome, Ok(())) => outcome,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
use std::{path::Path, sync::Arc};
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
use teamspeach_core::{
|
||||||
|
file_transfer::Request,
|
||||||
|
protocol::{Command, ConnectArgs},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
AppRuntime,
|
||||||
|
app::connections::{ConnectionManager, CoreStatus, SessionKey},
|
||||||
|
services::{
|
||||||
|
connected::ConnectedServices, identities::IdentityService,
|
||||||
|
},
|
||||||
|
ui::shell::{Entity, Target},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::super::{SmokeResult, identities::wait, key_profiles::until};
|
||||||
|
|
||||||
|
const ENDPOINT: &str = "127.0.0.1:19987";
|
||||||
|
const NICKNAME: &str = "Download folder QA guest";
|
||||||
|
pub(super) const BYTES: &[u8] = b"TeamsPeach Windows download folder fixture\r\n\x00\xff";
|
||||||
|
|
||||||
|
pub(super) fn guest_identity(profile: &Path) -> SmokeResult<String> {
|
||||||
|
IdentityService::open(profile).and_then(|identities| identities.onboard(NICKNAME))
|
||||||
|
.map_err(|error| format!("create disposable download fixture identity: {error}"))?["uid"]
|
||||||
|
.as_str().map(str::to_owned).ok_or_else(|| "download fixture identity has no UID".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Guest {
|
||||||
|
connected: Arc<ConnectedServices>,
|
||||||
|
key: SessionKey,
|
||||||
|
own_client_id: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Guest {
|
||||||
|
async fn connect(runtime: &AppRuntime, identity_id: &str) -> SmokeResult<(Self, Target)> {
|
||||||
|
if runtime.config.network_enabled || runtime.config.profile_dir.is_none() {
|
||||||
|
return Err("download fixture requires an explicit disposable profile and disabled public network services".into());
|
||||||
|
}
|
||||||
|
wait(runtime, "download fixture profile", |state| state.settings.loaded.then_some(())).await?;
|
||||||
|
let owner = runtime.services.lock().map_err(|_| "runtime services unavailable")?
|
||||||
|
.upgrade().ok_or("download fixture runtime closed")?;
|
||||||
|
let identity = owner.profile().and_then(|profile| profile.identities.profile(Some(identity_id)))
|
||||||
|
.map_err(|error| format!("read disposable download fixture identity: {error}"))?;
|
||||||
|
if identity["uid"] != identity_id || identity["nickname"] != NICKNAME || identity["is_default"] != true {
|
||||||
|
return Err("download fixture must connect with its freshly onboarded guest identity".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let connected = owner.connected.clone();
|
||||||
|
let manager = &connected.connections;
|
||||||
|
let key = manager.key("c1").await.map_err(|error| format!("get download fixture tab: {error}"))?;
|
||||||
|
if manager.snapshot().any_active() {
|
||||||
|
return Err("download fixture runtime already has a live connection".into());
|
||||||
|
}
|
||||||
|
let muted = manager.request(&key, Command::SetAudio {
|
||||||
|
input_muted: Some(true), output_muted: Some(true),
|
||||||
|
}).await.map_err(|error| format!("mute download fixture before connecting: {error}"))?;
|
||||||
|
if muted["input_muted"] != true || muted["output_muted"] != true {
|
||||||
|
return Err("download fixture core did not acknowledge both mutes".into());
|
||||||
|
}
|
||||||
|
// Keep AppConfig offline: this explicit manager request is the only login, to the fixed
|
||||||
|
// IPv4 loopback endpoint. Public updates, media requests and discovery stay disabled.
|
||||||
|
let reply = manager.request(&key, Command::Connect(ConnectArgs {
|
||||||
|
address: ENDPOINT.into(), identity_id: Some(identity_id.to_owned()), nickname: None,
|
||||||
|
channel: None, server_password: None, channel_password: None,
|
||||||
|
})).await.map_err(|error| format!("connect disposable guest to beta14 at {ENDPOINT}: {error}"))?;
|
||||||
|
let key = manager.key(&key.connection_id).await.map_err(|error| format!("capture connected fixture tab: {error}"))?;
|
||||||
|
let guest = Self { connected, key, own_client_id: reply["own_client_id"].as_u64().unwrap_or(0) };
|
||||||
|
match guest.lobby().await {
|
||||||
|
Ok(target) => Ok((guest, target)),
|
||||||
|
Err(error) => combine(Err(error), guest.disconnect().await),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn lobby(&self) -> SmokeResult<Target> {
|
||||||
|
if self.own_client_id == 0 {
|
||||||
|
return Err("beta14 connect did not return the fixture client ID".into());
|
||||||
|
}
|
||||||
|
until("beta14 initial channel and guest roster", || self.server().is_some_and(|server| {
|
||||||
|
server["own_channel_id"].as_u64().filter(|&id| id > 0)
|
||||||
|
.is_some_and(|id| channel(&server, id).is_some())
|
||||||
|
&& server["clients"].as_array().is_some_and(|rows| rows.iter().any(|row| row["id"] == self.own_client_id))
|
||||||
|
})).await?;
|
||||||
|
let server = self.server().ok_or("download fixture connection changed")?;
|
||||||
|
let beta14 = server["server"]["version"].as_str().is_some_and(|version| {
|
||||||
|
version.starts_with("6.") && version.split(|c: char| !c.is_ascii_alphanumeric())
|
||||||
|
.any(|part| part.eq_ignore_ascii_case("beta14"))
|
||||||
|
});
|
||||||
|
if !beta14 { return Err(format!("loopback endpoint did not report TS6 beta14: {}", server["server"]["version"])); }
|
||||||
|
let id = server["own_channel_id"].as_u64().ok_or("beta14 did not report the initial channel ID")?;
|
||||||
|
let lobby = channel(&server, id).filter(|row| row["is_default"] == true)
|
||||||
|
.ok_or("download fixture guest did not join the beta14 default channel")?;
|
||||||
|
let name = lobby["name"].as_str().ok_or("beta14 did not report the default channel name")?;
|
||||||
|
let Some([client]) = server["clients"].as_array().map(Vec::as_slice) else {
|
||||||
|
return Err("download fixture requires the exclusive use of the private beta14 server".into());
|
||||||
|
};
|
||||||
|
if client["id"] != self.own_client_id || server["own_client_id"] != self.own_client_id
|
||||||
|
|| client["uid"].as_str().is_none_or(str::is_empty) || client["nickname"] != NICKNAME || client["client_type"] != "normal"
|
||||||
|
|| client["input_muted"] != true || client["output_muted"] != true {
|
||||||
|
return Err("private beta14 roster did not show only the expected muted guest".into());
|
||||||
|
}
|
||||||
|
Ok(Target { session: Some(self.key.clone()), entity: Entity::Channel { id }, name: name.into(), own_channel_id: Some(id) })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn server(&self) -> Option<Arc<Value>> {
|
||||||
|
self.connected.connections.snapshot().get(&self.key.connection_id)
|
||||||
|
.filter(|tab| tab.key == self.key && tab.status == CoreStatus::Ready
|
||||||
|
&& tab.is_connected() && tab.address == ENDPOINT)
|
||||||
|
.and_then(|tab| tab.server.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn request(&self, operation: &str, command: Command) -> SmokeResult<Value> {
|
||||||
|
self.connected.connections.request(&self.key, command).await
|
||||||
|
.map_err(|error| format!("{operation} as disposable beta14 guest: {error}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn disconnect(&self) -> SmokeResult<()> {
|
||||||
|
disconnect(&self.connected.connections, &self.key).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn connect_guest(runtime: &AppRuntime, identity_id: &str) -> SmokeResult<Target> {
|
||||||
|
Guest::connect(runtime, identity_id).await.map(|(_, lobby)| lobby)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn disconnect_guest(runtime: &AppRuntime, target: &Target) -> SmokeResult<()> {
|
||||||
|
let key = target.session.as_ref().ok_or("missing captured download fixture session")?;
|
||||||
|
let owner = runtime.services.lock().map_err(|_| "runtime services unavailable")?
|
||||||
|
.upgrade().ok_or("download fixture runtime closed")?;
|
||||||
|
disconnect(&owner.connected.connections, key).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn disconnect(manager: &ConnectionManager, key: &SessionKey) -> SmokeResult<()> {
|
||||||
|
let inactive = || manager.snapshot().get(&key.connection_id)
|
||||||
|
.is_none_or(|tab| tab.state == crate::app::connections::ConnectionState::Disconnected);
|
||||||
|
if inactive() { return Ok(()); }
|
||||||
|
manager.request(key, Command::Disconnect { message: None }).await
|
||||||
|
.map_err(|error| format!("disconnect captured download fixture guest: {error}"))?;
|
||||||
|
until("download fixture guest disconnected", inactive).await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn channel(server: &Value, id: u64) -> Option<&Value> {
|
||||||
|
server["channels"].as_array()?.iter().find(|row| row["id"] == id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn combine<T>(result: SmokeResult<T>, cleanup: SmokeResult<()>) -> SmokeResult<T> {
|
||||||
|
match (result, cleanup) {
|
||||||
|
(Ok(value), Ok(())) => Ok(value),
|
||||||
|
(Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error),
|
||||||
|
(Err(error), Err(cleanup)) => Err(format!("{error}; cleanup: {cleanup}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) const REMOTE_NAME: &str = "teamspeach-download-smoke.bin";
|
||||||
|
|
||||||
|
/// Read-only fixture: the private server owner places BYTES at /REMOTE_NAME in the default channel.
|
||||||
|
/// The downloader needs list/read permissions only. Never upload or delete remote content here.
|
||||||
|
pub(super) async fn existing_file(runtime: &AppRuntime, identity_id: &str) -> SmokeResult<Target> {
|
||||||
|
let (guest, mut target) = Guest::connect(runtime, identity_id).await?;
|
||||||
|
let result = async {
|
||||||
|
let Entity::Channel { id: channel_id } = target.entity else { return Err("missing default channel".into()); };
|
||||||
|
let reply = guest.request("list default channel files", Command::Files(Request::List {
|
||||||
|
channel_id, path: "/".into(), password: String::new(),
|
||||||
|
})).await?;
|
||||||
|
let entries = reply["entries"].as_array().ok_or("missing default channel file list")?;
|
||||||
|
if !entries.iter().any(|entry| entry["name"] == REMOTE_NAME && entry["type"] == "file" && entry["size"] == BYTES.len() as u64) {
|
||||||
|
return Err(format!("private fixture requires a readable /{REMOTE_NAME} containing the {} known test bytes", BYTES.len()));
|
||||||
|
}
|
||||||
|
target.entity = Entity::File { channel_id, path: format!("/{REMOTE_NAME}"), directory: false };
|
||||||
|
target.name = REMOTE_NAME.into();
|
||||||
|
Ok(target)
|
||||||
|
}.await;
|
||||||
|
match result { Ok(target) => Ok(target), Err(error) => combine(Err(error), guest.disconnect().await) }
|
||||||
|
}
|
||||||
Reference in new issue
Block a user