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
use super::ADBCommand;
use crate::ADBResult;
use std::process::Command;

#[derive(Default)]
pub struct ADBManager {
    connected: bool,
    path: String,
}

impl ADBManager {
    pub fn new() -> ADBManager {
        ADBManager {
            connected: false,
            path: "".to_string(),
        }
    }

    pub fn connect(&mut self, ip: &str, port: &str) -> Result<(), String> {
        let mut command = Command::new("cmd");
        command
            .arg("/c")
            .arg(format!("adb connect {}:{}", ip, port));
        match command.output() {
            Ok(s) => {
                if s.status.success() && !String::from_utf8(s.stdout).unwrap().contains("failed") {
                    self.connected = true;
                    return Ok(());
                }
                Err(s.status.to_string())
            }
            Err(e) => Err(e.to_string()),
        }
    }

    pub fn cwd(&mut self, path: &str) {
        if !path.ends_with('/') {
            self.path = path.to_owned() + "/";
        } else {
            self.path = path.to_owned();
        }
    }

    pub fn shell(&self, cmd: &mut impl ADBCommand) -> Result<ADBResult, String> {
        cmd.path(self.path.clone());
        let mut command = cmd.build()?;
        match command.output() {
            Ok(ok) => {
                if ok.status.success() {
                    Ok(ADBResult {
                        data: String::from_utf8(ok.stdout).unwrap(),
                    })
                } else {
                    Err(ok.status.to_string() + &String::from_utf8(ok.stderr).unwrap())
                }
            }
            Err(e) => Err(e.to_string()),
        }
    }

    pub fn disconnect(&mut self) {
        let mut command = Command::new("cmd");
        command.arg("/c").arg("adb disconnect").output().ok();
        self.connected = false;
    }
}

impl Drop for ADBManager {
    fn drop(&mut self) {
        if self.connected {
            self.disconnect();
        }
    }
}