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
//! Android-specific features
use std::collections::HashMap;
use async_trait::async_trait;
use fantoccini::elements::Element;
use fantoccini::error::CmdError;
use http::Method;
use serde_derive::Serialize;
use serde_repr::Serialize_repr;
use serde_json::{json, Value};
use crate::{AndroidClient, AppiumClientTrait};
use crate::commands::AppiumCommand;

pub struct AndroidActivity {
    pub app_package: String,
    pub app_activity: String,
    pub app_wait_package: String,
    pub app_wait_activity: String,
    pub intent_action: String,
    pub intent_category: String,
    pub intent_flags: String,
    pub optional_intent_arguments: String,
    pub stop_app: bool,
}

/// Start or check Android actitivies
#[async_trait]
pub trait StartsActivity: AppiumClientTrait {
    async fn start_activity(&self, activity: AndroidActivity) -> Result<(), CmdError> {
        self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/device/start_activity".to_string(),
            Some(json!({
                "appPackage": activity.app_package,
                "appWaitPackage": activity.app_wait_package,
                "appWaitActivity": activity.app_wait_activity,
                "dontStopAppOnReset": !activity.stop_app,
                "intentAction": activity.intent_action,
                "intentCategory": activity.intent_category,
                "intentFlags": activity.intent_flags,
                "optionalIntentArguments": activity.optional_intent_arguments
            }))
        )).await?;

        Ok(())
    }

    async fn current_activity(&self) -> Result<String, CmdError> {
        let value = self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/device/current_activity".to_string(),
            None
        )).await?;

        Ok(serde_json::from_value(value)?)
    }

    async fn current_package(&self) -> Result<String, CmdError> {
        let value = self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/device/current_package".to_string(),
            None
        )).await?;

        Ok(serde_json::from_value(value)?)
    }
}

#[async_trait]
impl StartsActivity for AndroidClient {}

/// Android device details
#[async_trait]
pub trait HasAndroidDeviceDetails :AppiumClientTrait {
    async fn display_density(&self) -> Result<u64, CmdError> {
        let value = self.issue_cmd(AppiumCommand::Custom(
            Method::GET,
            "appium/device/display_density".to_string(),
            None
        )).await?;

        Ok(serde_json::from_value(value)?)
    }

    async fn system_bars(&self) -> Result<HashMap<String, HashMap<String, Value>>, CmdError> {
        let value = self.issue_cmd(AppiumCommand::Custom(
            Method::GET,
            "appium/device/system_bars".to_string(),
            None
        )).await?;

        Ok(serde_json::from_value(value)?)
    }
}

#[async_trait]
impl HasAndroidDeviceDetails for AndroidClient {}

/// Device traits that Appium is able to read
#[async_trait]
pub trait HasSupportedPerformanceDataType : AppiumClientTrait {
    async fn supported_performance_data_type(&self) -> Result<Vec<String>, CmdError> {
        let value = self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/performanceData/types".to_string(),
            None
        )).await?;

        Ok(serde_json::from_value(value)?)
    }

    async fn performance_data(&self, package: &str, data_type: &str, read_timeout: u32) -> Result<Vec<Vec<Value>>, CmdError> {
        let value = self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/performanceData/types".to_string(),
            Some(json!({
                "packageName": package,
                "dataType": data_type,
                "dataReadTimeout": read_timeout
            }))
        )).await?;

        Ok(serde_json::from_value(value)?)
    }
}

#[async_trait]
impl HasSupportedPerformanceDataType for AndroidClient {}

#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GsmCallAction {
    Call,
    Accept,
    Cancel,
    Hold,
}

#[derive(Debug, Serialize_repr, Eq, PartialEq)]
#[repr(u8)]
pub enum GsmSignalStrength {
    NoneOrUnknown = 0,
    Poor = 1,
    Moderate = 2,
    Good = 3,
    Great = 4,
}

#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GsmVoiceState {
    ON,
    OFF,
    Denied,
    Searching,
    Roaming,
    Home,
    Unregistered,
}

#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum NetworkSpeed {
    GSM,
    SCSD,
    GPRS,
    EDGE,
    UMTS,
    HSDPA,
    LTE,
    EVDO,
    FULL,
}

/// Special Android emulator commands like "send SMS"
#[async_trait]
pub trait SupportsSpecialEmulatorCommands : AppiumClientTrait {

    async fn send_sms(&self, phone_number: &str, message: &str) -> Result<(), CmdError> {
        self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/device/send_sms".to_string(),
            Some(json!({
                "phoneNumber": phone_number,
                "message": message
            }))
        )).await?;

        Ok(())
    }

    async fn make_gsm_call(&self, phone_number: &str, action: GsmCallAction) -> Result<(), CmdError> {
        self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/device/gsm_call".to_string(),
            Some(json!({
                "phoneNumber": phone_number,
                "action": action
            }))
        )).await?;

        Ok(())
    }

    async fn set_signal_strength(&self, strength: GsmSignalStrength) -> Result<(), CmdError> {
        self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/device/gsm_signal".to_string(),
            Some(json!({
                "signalStrengh": strength,
                "signalStrength": strength
            }))
        )).await?;

        Ok(())
    }

    async fn set_gsm_voice_state(&self, state: GsmVoiceState) -> Result<(), CmdError> {
        self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/device/gsm_voice".to_string(),
            Some(json!({
                "state": state
            }))
        )).await?;

        Ok(())
    }

    async fn set_network_speed(&self, speed: NetworkSpeed) -> Result<(), CmdError> {
        self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/device/network_speed".to_string(),
            Some(json!({
                "netspeed": speed
            }))
        )).await?;

        Ok(())
    }

    async fn set_power_capacity(&self, percent: u8) -> Result<(), CmdError> {
        if percent > 100 {
            return Err(CmdError::InvalidArgument(
                "percent".to_string(),
                format!("{percent} should be between 0 and 100.")
            ))
        }

        self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/device/power_capacity".to_string(),
            Some(json!({
                "percent": percent
            }))
        )).await?;

        Ok(())
    }

    async fn set_power_ac(&self, power: bool) -> Result<(), CmdError> {
        let state = if power {
            "on"
        } else {
            "off"
        };

        self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "appium/device/power_ac".to_string(),
            Some(json!({
                "state": state
            }))
        )).await?;

        Ok(())
    }
}

#[async_trait]
impl SupportsSpecialEmulatorCommands for AndroidClient {}

/// Chrome DevTools protocol commands (Chrome and webview)
#[async_trait]
pub trait ExecutesCDP : AppiumClientTrait {
    async fn execute_cdp_command(&self, command: &str, params: Option<HashMap<String, Value>>) -> Result<HashMap<String, Value>, CmdError> {
        let value = self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            "goog/cdp/execute".to_string(),
            Some(json!({
                "cmd": command,
                "params": params
            }))
        )).await?;

        Ok(serde_json::from_value(value)?)
    }
}

#[async_trait]
impl ExecutesCDP for AndroidClient {}

/// Replacing element value (instead of retyping into field)
#[async_trait]
pub trait CanReplaceValue: AppiumClientTrait {
    async fn replace_value(&self, element: &Element, value: &str) -> Result<(), CmdError> {
        let id = element.element_id().to_string();
        self.issue_cmd(AppiumCommand::Custom(
            Method::POST,
            format!("appium/element/{}/replace_value", id),
            Some(json!({
                "id": id,
                "value": value
            }))
        )).await?;

        Ok(())
    }
}

#[async_trait]
impl CanReplaceValue for AndroidClient {}