-
-
Notifications
You must be signed in to change notification settings - Fork 529
/
Copy pathcommands.rs
326 lines (278 loc) · 8.72 KB
/
commands.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/user/adb.1.md
use crate::parse::{self, Device, ForwardedPorts};
use alvr_filesystem as afs;
use anyhow::{anyhow, Context, Result};
use std::{
collections::HashSet,
io::{Cursor, Read},
process::Command,
time::Duration,
};
use zip::ZipArchive;
#[cfg(windows)]
use std::os::windows::process::CommandExt;
// https://developer.android.com/tools/releases/platform-tools#revisions
// NOTE: At the time of writing this comment, the revisions section above
// shows the latest version as 35.0.2, but the latest that can be downloaded
// by specifying a version is 35.0.0
const PLATFORM_TOOLS_VERSION: &str = "-latest"; // E.g. "_r35.0.0"
#[cfg(target_os = "linux")]
const PLATFORM_TOOLS_OS: &str = "linux";
#[cfg(target_os = "macos")]
const PLATFORM_TOOLS_OS: &str = "darwin";
#[cfg(windows)]
const PLATFORM_TOOLS_OS: &str = "windows";
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
fn get_command(adb_path: &str, args: &[&str]) -> Command {
let mut command = Command::new(adb_path);
command.args(args);
#[cfg(windows)]
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
command
}
pub fn download(url: &str, progress_callback: impl Fn(usize, Option<usize>)) -> Result<Vec<u8>> {
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(REQUEST_TIMEOUT))
.build()
.into();
let response = agent.get(url).call()?;
let maybe_expected_size = response
.headers()
.get("Content-Length")
.and_then(|v| v.to_str().ok()?.parse::<usize>().ok());
let mut result = maybe_expected_size
.map(Vec::with_capacity)
.unwrap_or_default();
let mut reader = response.into_body().into_reader();
let mut buffer = [0; 65535];
loop {
let read_count: usize = reader.read(&mut buffer)?;
if read_count == 0 {
break;
}
result.extend_from_slice(&buffer[..read_count]);
let current_size = result.len();
(progress_callback)(current_size, maybe_expected_size);
}
Ok(result)
}
///////////
// Activity
pub fn get_process_id(
adb_path: &str,
device_serial: &str,
process_name: &str,
) -> Result<Option<usize>> {
let output = get_command(
adb_path,
&["-s", device_serial, "shell", "pidof", process_name],
)
.output()
.context(format!("Failed to get ID of process {process_name}"))?;
let text = String::from_utf8_lossy(&output.stdout).trim().to_owned();
if text.is_empty() {
return Ok(None);
}
let process_id = text
.parse::<usize>()
.context("Failed to parse process ID")?;
Ok(Some(process_id))
}
pub fn is_activity_resumed(
adb_path: &str,
device_serial: &str,
activity_name: &str,
) -> Result<bool> {
let output = get_command(
adb_path,
&[
"-s",
device_serial,
"shell",
"dumpsys",
"activity",
activity_name,
],
)
.output()
.context(format!("Failed to get state of activity {activity_name}"))?;
let text = String::from_utf8_lossy(&output.stdout);
if let Some(line) = text
.lines()
.map(|l| l.trim())
.find(|l| l.contains("mResumed"))
{
let (entry, _) = line
.split_once(' ')
.ok_or(anyhow!("Failed to split resumed state line"))?;
let (_, value) = entry
.split_once('=')
.ok_or(anyhow!("Failed to split resumed state entry"))?;
match value {
"true" => Ok(true),
"false" => Ok(false),
_ => Err(anyhow!("Failed to parse resumed state value"))?,
}
} else {
Err(anyhow!("Failed to find resumed state line"))
}
}
///////////////////
// ADB Installation
pub fn require_adb(
layout: &afs::Layout,
progress_callback: impl Fn(usize, Option<usize>),
) -> Result<String> {
match get_adb_path(layout) {
Some(path) => Ok(path),
None => {
install_adb(layout, progress_callback).context("Failed to install ADB")?;
let path = get_adb_path(layout).context("Failed to get ADB path after installation")?;
Ok(path)
}
}
}
fn install_adb(
layout: &afs::Layout,
progress_callback: impl Fn(usize, Option<usize>),
) -> Result<()> {
let mut reader = Cursor::new(download_adb(progress_callback)?);
ZipArchive::new(&mut reader)?.extract(layout.executables_dir.clone())?;
Ok(())
}
fn download_adb(progress_callback: impl Fn(usize, Option<usize>)) -> Result<Vec<u8>> {
let url = get_platform_tools_url();
download(&url, progress_callback).context(format!("Failed to download ADB from {url}"))
}
fn get_platform_tools_url() -> String {
format!("https://dl.google.com/android/repository/platform-tools{PLATFORM_TOOLS_VERSION}-{PLATFORM_TOOLS_OS}.zip")
}
///////////////
// Applications
pub fn start_application(adb_path: &str, device_serial: &str, application_id: &str) -> Result<()> {
get_command(
adb_path,
&[
"-s",
device_serial,
"shell",
"monkey",
"-p",
application_id,
"1",
],
)
.output()
.context(format!("Failed to start {application_id}"))?;
Ok(())
}
//////////
// Devices
pub fn list_devices(adb_path: &str) -> Result<Vec<Device>> {
let output = get_command(adb_path, &["devices", "-l"])
.output()
.context("Failed to list ADB devices")?;
let text = String::from_utf8_lossy(&output.stdout);
let devices = text
.lines()
.skip(1)
.filter_map(parse::parse_device)
.collect();
Ok(devices)
}
///////////
// Packages
pub fn install_package(adb_path: &str, device_serial: &str, apk_path: &str) -> Result<()> {
get_command(adb_path, &["-s", device_serial, "install", "-r", apk_path])
.output()
.context(format!("Failed to install {apk_path}"))?;
Ok(())
}
pub fn is_package_installed(
adb_path: &str,
device_serial: &str,
application_id: &str,
) -> Result<bool> {
let found = list_installed_packages(adb_path, device_serial)
.context(format!(
"Failed to check if package {application_id} is installed"
))?
.contains(application_id);
Ok(found)
}
pub fn uninstall_package(adb_path: &str, device_serial: &str, application_id: &str) -> Result<()> {
get_command(
adb_path,
&["-s", device_serial, "uninstall", application_id],
)
.output()
.context(format!("Failed to uninstall {application_id}"))?;
Ok(())
}
pub fn list_installed_packages(adb_path: &str, device_serial: &str) -> Result<HashSet<String>> {
let output = get_command(
adb_path,
&["-s", device_serial, "shell", "pm", "list", "package"],
)
.output()
.context("Failed to list installed packages")?;
let text = String::from_utf8_lossy(&output.stdout);
let packages = text.lines().map(|l| l.replace("package:", "")).collect();
Ok(packages)
}
////////
// Paths
/// Returns the path of a local (i.e. installed by ALVR) or OS version of `adb` if found, `None` otherwise.
pub fn get_adb_path(layout: &afs::Layout) -> Option<String> {
let exe_name = afs::exec_fname("adb").to_owned();
let adb_path = get_command(&exe_name, &[])
.output()
.is_ok()
.then_some(exe_name);
adb_path.or_else(|| {
let path = layout.local_adb_exe();
path.try_exists()
.unwrap_or(false)
.then(|| path.to_string_lossy().to_string())
})
}
//////////////////
// Port forwarding
pub fn list_forwarded_ports(adb_path: &str, device_serial: &str) -> Result<Vec<ForwardedPorts>> {
let output = get_command(adb_path, &["-s", device_serial, "forward", "--list"])
.output()
.context(format!(
"Failed to list forwarded ports of device {device_serial:?}"
))?;
let text = String::from_utf8_lossy(&output.stdout);
let forwarded_ports = text
.lines()
.filter_map(parse::parse_forwarded_ports)
.collect();
Ok(forwarded_ports)
}
pub fn forward_port(adb_path: &str, device_serial: &str, port: u16) -> Result<()> {
get_command(
adb_path,
&[
"-s",
device_serial,
"forward",
&format!("tcp:{}", port),
&format!("tcp:{}", port),
],
)
.output()
.context(format!(
"Failed to forward port {port:?} of device {device_serial:?}"
))?;
Ok(())
}
/////////
// Server
pub fn kill_server(adb_path: &str) -> Result<()> {
get_command(adb_path, &["kill-server"])
.output()
.context("Failed to kill ADB server")?;
Ok(())
}