mod files;
pub use files::FALLBACK_PUSH_MODE;
use crate::channel::Connection;
use crate::error::{Error, Result};
use crate::services::content::{self, Row};
use crate::services::{RebootTarget, ShellOutput, props, shell};
use bytes::Bytes;
use std::collections::BTreeMap;
use tokio::sync::OnceCell;
const PNG_MAGIC: [u8; 8] = [0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1A, b'\n'];
#[derive(Debug)]
pub struct Device<C> {
conn: C,
features: OnceCell<Vec<String>>,
}
impl<C: Connection> Device<C> {
pub fn new(conn: C) -> Self {
Self {
conn,
features: OnceCell::new(),
}
}
pub fn connection(&self) -> &C {
&self.conn
}
pub fn into_connection(self) -> C {
self.conn
}
pub async fn features(&self) -> Result<&[String]> {
self.features
.get_or_try_init(|| self.conn.features())
.await
.map(Vec::as_slice)
}
pub async fn has_feature(&self, feature: &str) -> Result<bool> {
Ok(self.features().await?.iter().any(|f| f == feature))
}
pub async fn shell(&self, command: &str) -> Result<ShellOutput> {
shell::shell(&self.conn, self.features().await?, command).await
}
pub async fn shell_with_stdin(&self, command: &str, stdin: &[u8]) -> Result<ShellOutput> {
if !self.has_feature(shell::SHELL_V2_FEATURE).await? {
return Err(Error::Unsupported(
"device lacks shell_v2; stdin needs it".into(),
));
}
shell::shell_v2(&self.conn, command, stdin).await
}
pub async fn shell_v1(&self, command: &str) -> Result<Bytes> {
shell::shell_v1(&self.conn, command).await
}
pub async fn exec(&self, command: &str) -> Result<Bytes> {
shell::exec(&self.conn, command).await
}
async fn shell_checked(&self, command: &str) -> Result<ShellOutput> {
let out = self.shell(command).await?;
if out.success() {
Ok(out)
} else {
Err(Error::RemoteFailure(format!(
"{command:?} exited {}: {}",
out.exit_code.unwrap_or(0),
out.stderr_text().trim()
)))
}
}
pub async fn getprop(&self, name: &str) -> Result<String> {
props::validate_name(name)?;
let out = self.shell_checked(&format!("getprop {name}")).await?;
Ok(out.stdout_text().trim_end_matches(['\r', '\n']).to_owned())
}
pub async fn getprops(&self) -> Result<BTreeMap<String, String>> {
let out = self.shell_checked("getprop").await?;
Ok(props::parse_all(&out.stdout_text()))
}
pub async fn screencap(&self) -> Result<Vec<u8>> {
let png = self.exec("screencap -p").await?;
if png.len() < PNG_MAGIC.len() || png[..PNG_MAGIC.len()] != PNG_MAGIC {
return Err(Error::parse(format!(
"screencap did not return a PNG ({} bytes: {:?})",
png.len(),
String::from_utf8_lossy(&png[..png.len().min(64)])
)));
}
Ok(png.to_vec())
}
pub async fn content_query(&self, uri: &str, projection: &[&str]) -> Result<Vec<Row>> {
self.content_query_with(uri, projection, &[]).await
}
pub async fn content_query_with(
&self,
uri: &str,
projection: &[&str],
extra: &[&str],
) -> Result<Vec<Row>> {
if projection.is_empty() {
return Err(Error::InvalidArgument(
"projection must name at least one column".into(),
));
}
let out = self
.shell_checked(&content::command(uri, projection, extra))
.await?;
let rows = content::parse_rows(&out.stdout_text(), projection)?;
let check = self
.shell_checked(&content::command(uri, &["_id"], extra))
.await?;
let expected = content::count_rows(&check.stdout_text());
if expected != rows.len() {
return Err(Error::parse(format!(
"parsed {} rows but the _id-only query reports {expected}",
rows.len()
)));
}
Ok(rows)
}
pub async fn reboot(&self, target: RebootTarget) -> Result<()> {
crate::services::reboot(&self.conn, target).await
}
}