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
use crate::{ADBCommand, ADBPathCommand, ADBResult};
use std::process::Command;

#[derive(Default)]
pub struct ADBManager {
    connected: Vec<(String, u32)>,
    path: String,
}

impl ADBManager {
    pub fn new() -> ADBManager {
        ADBManager {
            connected: vec![],
            path: "".to_string(),
        }
    }

    pub fn connect(&mut self, ip: &str, port: u32) -> 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.push((ip.to_owned(), port));
                    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 execute(&self, cmd: &mut impl ADBCommand) -> Result<ADBResult, String> {
        let command = cmd.build()?;
        let result = self.execute_impl(command)?;
        Ok(cmd.process_output(result))
    }

    pub fn execute_path_based(&self, cmd: &mut impl ADBPathCommand) -> Result<ADBResult, String> {
        cmd.path(self.path.clone());
        let command = cmd.build()?;
        let result = self.execute_impl(command)?;
        Ok(cmd.process_output(result))
    }

    fn execute_impl(&self, mut command: Command) -> Result<ADBResult, String> {
        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.stdout).unwrap()
                        + &String::from_utf8(ok.stderr).unwrap())
                }
            }
            Err(e) => Err(e.to_string()),
        }
    }

    pub fn disconnect(&mut self, ip: &str, port: u32) {
        Self::disconnect_one(ip, port);
        if let Some(index) = self
            .connected
            .iter()
            .position(|x| *x == (ip.to_owned(), port))
        {
            self.connected.remove(index);
        }
    }

    fn disconnect_one(ip: &str, port: u32) {
        let mut command = Command::new("adb");
        command
            .arg("disconnect")
            .arg(format!("{ip}:{port}"))
            .output()
            .ok();
    }

    pub fn disconnect_all(&mut self) {
        self.connected
            .iter()
            .for_each(|(ip, port)| Self::disconnect_one(ip, *port));
    }
}

impl Drop for ADBManager {
    fn drop(&mut self) {
        self.disconnect_all();
    }
}