use super::schema::SCRIPT_LIMIT;
use super::tabs::{execution, Node, OpenTab};
use super::text::{self, READ_LIMIT};
use rho_browser::cdp::dom::SetFileInputFiles;
use rho_browser::cdp::runtime::{
CallArgument, CallFunctionOn, Evaluate, Evaluated, ReleaseObject, RemoteObject,
};
use rho_sdk::tool::ToolError;
use serde::Deserialize;
use serde_json::Value;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Uploads(Vec<PathBuf>);
pub(super) fn uploads(dir: &Path, paths: &[PathBuf]) -> Result<Uploads, String> {
if paths.is_empty() {
return Err("paths must name at least one file".to_owned());
}
let root = dir.canonicalize().map_err(|error| {
format!(
"the upload directory {} (browser.upload_dir) is unusable: {error}",
dir.display()
)
})?;
let files = paths
.iter()
.map(|path| {
let file = root
.join(path)
.canonicalize()
.map_err(|error| format!("could not upload {}: {error}", path.display()))?;
if !file.starts_with(&root) {
return Err(format!(
"could not upload {}: only files in the upload directory {} can be uploaded",
path.display(),
root.display()
));
}
if !file.is_file() {
return Err(format!("could not upload {}: not a file", path.display()));
}
Ok(file)
})
.collect::<Result<_, _>>()?;
Ok(Uploads(files))
}
const FILE_INPUT: &str = r##"function () {
const file = this.localName === "input" && this.type === "file";
return { file, multiple: file && this.multiple };
}"##;
#[derive(Deserialize)]
struct FileInput {
file: bool,
multiple: bool,
}
pub(super) async fn upload(
open: &mut OpenTab,
node: &Node<'_>,
files: &Uploads,
) -> Result<String, ToolError> {
let element = node.name;
let input: FileInput = serde_json::from_value(open.call_on(node, FILE_INPUT, vec![]).await?)
.map_err(|error| execution(format!("the browser answered oddly: {error}")))?;
if !input.file {
return Err(execution(format!(
"{element} is not a file input (<input type=\"file\">), so it takes no files."
)));
}
let Uploads(files) = files;
if files.len() > 1 && !input.multiple {
return Err(execution(format!(
"{element} takes one file, not {}.",
files.len()
)));
}
let set = SetFileInputFiles {
files: files
.iter()
.map(|file| file.display().to_string())
.collect(),
backend_node_id: node.id,
};
open.on_node(&set).await?.ok_or_else(|| node.stale())?;
let names: Vec<String> = files
.iter()
.map(|file| {
file.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned()
})
.collect();
Ok(format!(
"Set the files of {element} to {}.",
names.join(", ")
))
}
pub(super) async fn run_script(open: &mut OpenTab, script: &str) -> Result<String, ToolError> {
let evaluate = Evaluate {
expression: script.to_owned(),
context_id: None,
return_by_value: false,
await_promise: true,
timeout: Some(SCRIPT_LIMIT.as_millis() as u64),
};
let evaluated = open.call(&evaluate).await.map_err(|error| {
execution(format!(
"{} A script, or a promise it returns, has {} s.",
error.message(),
SCRIPT_LIMIT.as_secs()
))
})?;
let text = match script_value(&evaluated) {
Ok(Shown::Text(text)) => text,
Ok(Shown::Object(object)) => object_text(open, &object).await,
Err(thrown) => {
release_thrown(open, evaluated).await;
return Err(execution(format!("The script threw: {thrown}")));
}
};
let url = open.url().await;
let narrower = "Return less, such as one property or a slice.";
Ok(text::framed(&url, &text::fit(text, READ_LIMIT, narrower)))
}
#[derive(Debug, PartialEq)]
enum Shown {
Text(String),
Object(RemoteObject),
}
fn script_value(evaluated: &Evaluated) -> Result<Shown, String> {
if let Some(details) = &evaluated.exception_details {
return Err(details
.exception
.as_ref()
.and_then(|thrown| thrown.description.clone().or_else(|| primitive(thrown)))
.unwrap_or_else(|| details.text.clone()));
}
let result = &evaluated.result;
Ok(match primitive(result) {
Some(text) => Shown::Text(text),
None if result.object_id.is_some() => Shown::Object(result.clone()),
None => Shown::Text(result.description.clone().unwrap_or_default()),
})
}
fn primitive(value: &RemoteObject) -> Option<String> {
match (value.kind.as_str(), &value.value) {
("undefined", _) => Some("undefined".to_owned()),
("object", None) if value.object_id.is_none() => Some("null".to_owned()),
("string", Some(Value::String(text))) => Some(text.clone()),
(_, Some(value)) if !value.is_object() && !value.is_array() => Some(value.to_string()),
_ => value.unserializable_value.clone(),
}
}
const OBJECT_TEXT: &str = r##"function () {
if (typeof this === "function" || this instanceof Node || this instanceof Window) return null;
try {
const json = JSON.stringify(this);
return json === undefined ? null : json;
} catch (error) {
return null;
}
}"##;
async fn object_text(open: &OpenTab, object: &RemoteObject) -> String {
let Some(object_id) = object.object_id.clone() else {
return object.description.clone().unwrap_or_default();
};
let json = open
.call(&CallFunctionOn {
function_declaration: OBJECT_TEXT.to_owned(),
object_id: object_id.clone(),
arguments: Vec::<CallArgument>::new(),
return_by_value: true,
await_promise: false,
})
.await
.ok()
.and_then(|called| called.result.value)
.and_then(|value| value.as_str().map(str::to_owned));
let _ = open.call(&ReleaseObject { object_id }).await;
json.or_else(|| object.description.clone())
.unwrap_or_else(|| "null".to_owned())
}
async fn release_thrown(open: &OpenTab, evaluated: Evaluated) {
let thrown = evaluated
.exception_details
.and_then(|details| details.exception);
let mut handles: Vec<_> = [
evaluated.result.object_id,
thrown.and_then(|thrown| thrown.object_id),
]
.into_iter()
.flatten()
.collect();
handles.dedup();
for object_id in handles {
let _ = open.call(&ReleaseObject { object_id }).await;
}
}
#[cfg(test)]
#[path = "opt_in_tests.rs"]
mod tests;