Skip to main content

appium_client/commands/
recording.rs

1//! Screen recording
2use std::collections::HashMap;
3use std::time::Duration;
4use async_trait::async_trait;
5use fantoccini::error::CmdError;
6use http::Method;
7use serde_derive::Serialize;
8use serde_json::{Error, json, Value};
9use crate::{AndroidClient, AppiumClientTrait, IOSClient};
10use crate::commands::AppiumCommand;
11
12#[derive(Clone, Debug)]
13pub struct ScreenRecordingUploadOptions {
14    /// Path to the remote location, where the resulting video should be uploaded.
15    pub remote_path: Option<String>,
16    /// Credentials for remote ftp/http authentication (if needed).
17    pub credentials: Option<ScreenRecordingCredentials>,
18    /// Method name for http(s) upload. PUT is used by default. This option only has an effect if remotePath is provided.
19    pub method: Option<Method>,
20    /// Form field name containing the binary payload in multipart/form-data requests.
21    pub file_field_name: Option<String>,
22    /// Additional headers in multipart/form-data requests.
23    pub headers: Option<HashMap<String, String>>,
24    /// Additional form fields in multipart/form-data requests.
25    pub form_fields: Option<HashMap<String, Value>>,
26}
27
28#[derive(Clone, Debug)]
29pub struct ScreenRecordingCredentials {
30    pub user: String,
31    pub pass: String,
32}
33
34impl ScreenRecordingUploadOptions {
35    pub fn empty() -> ScreenRecordingUploadOptions {
36        Self {
37            remote_path: None,
38            credentials: None,
39            method: None,
40            file_field_name: None,
41            headers: None,
42            form_fields: None,
43        }
44    }
45
46    pub fn to_map(self) -> Result<HashMap<String, Value>, Error> {
47        let mut result = HashMap::new();
48        if let Some(remote_path) = self.remote_path {
49            result.insert("remotePath".to_string(), Value::String(remote_path));
50        }
51        if let Some(credentials) = self.credentials {
52            result.insert("user".to_string(), Value::String(credentials.user));
53            result.insert("pass".to_string(), Value::String(credentials.pass));
54        }
55        if let Some(method) = self.method {
56            result.insert("method".to_string(), Value::String(method.to_string()));
57        }
58        if let Some(file_field_name) = self.file_field_name {
59            result.insert("fileFieldName".to_string(), Value::String(file_field_name));
60        }
61        if let Some(form_fields) = self.form_fields {
62            result.insert("formFields".to_string(), serde_json::to_value(form_fields)?);
63        }
64        if let Some(headers) = self.headers {
65            result.insert("headers".to_string(), serde_json::to_value(headers)?);
66        }
67        Ok(result)
68    }
69}
70
71/// Record screen
72#[async_trait]
73pub trait CanRecordScreen: AppiumClientTrait {
74    async fn start_recording_screen(&self) -> Result<String, CmdError> {
75        self.start_recording_with_options(None, None, HashMap::new()).await
76    }
77
78    async fn start_recording_with_options(&self, force_restart: Option<bool>, time_limit: Option<Duration>, mut options: HashMap<String, Value>) -> Result<String, CmdError> {
79        if let Some(force_restart) = force_restart {
80            options.insert("forceRestart".to_string(), Value::Bool(force_restart));
81        }
82        if let Some(time_limit) = time_limit {
83            options.insert("timeLimit".to_string(), Value::Number(time_limit.as_secs().into()));
84        }
85
86        let value = self.issue_cmd(AppiumCommand::Custom(
87            Method::POST,
88            "appium/start_recording_screen".to_string(),
89            Some(json!({
90                "options": options
91            })),
92        )).await?;
93
94        Ok(serde_json::from_value(value)?)
95    }
96
97    async fn stop_recording_screen(&self) -> Result<String, CmdError> {
98        self.stop_recording_with_options(HashMap::new()).await
99    }
100
101    async fn stop_recording_with_options(&self, options: HashMap<String, Value>) -> Result<String, CmdError> {
102        let value = self.issue_cmd(AppiumCommand::Custom(
103            Method::POST,
104            "appium/stop_recording_screen".to_string(),
105            Some(json!({
106                "options": options
107            })),
108        )).await?;
109
110        Ok(serde_json::from_value(value)?)
111    }
112}
113
114#[async_trait]
115impl CanRecordScreen for AndroidClient {}
116
117#[async_trait]
118impl CanRecordScreen for IOSClient {}
119
120/// Record screen with Android-specific encoding options
121#[async_trait]
122pub trait AndroidCanRecordScreen: CanRecordScreen {
123    /// Starts screen recording (Android).
124    ///
125    /// **bit_rate** - The video bit rate for the video, in megabits per second.
126    /// The default value is 4000000 (4 Mb/s) for Android API level below 27 and 20000000 (20 Mb/s) for API level 27 and above.
127    ///
128    /// **vide_size** - The video size of the generated media file. The format is WIDTHxHEIGHT.
129    /// The default value is the device's native display resolution (if supported), 1280x720 if not.
130    ///
131    /// **bug_report** - Makes the recorder to display an additional information on the video overlay,
132    /// such as a timestamp, that is helpful in videos captured to illustrate bugs.
133    /// This option is only supported since API level 27 (Android P).
134    async fn start_recording(&self,
135                             bit_rate: Option<u32>,
136                             video_size: Option<String>,
137                             bug_report: Option<bool>,
138                             force_restart: Option<bool>,
139                             time_limit: Option<Duration>,
140                             options: ScreenRecordingUploadOptions
141    ) -> Result<String, CmdError> {
142        let mut options = options.to_map()?;
143        if let Some(bit_rate) = bit_rate {
144            options.insert("bitRate".to_string(), Value::Number(bit_rate.into()));
145        }
146        if let Some(video_size) = video_size {
147            options.insert("videoSize".to_string(), Value::String(video_size));
148        }
149        if let Some(bug_report) = bug_report {
150            options.insert("bugReport".to_string(), Value::Bool(bug_report));
151        }
152        self.start_recording_with_options(force_restart, time_limit, options).await
153    }
154
155    async fn stop_recording(&self, options: ScreenRecordingUploadOptions) -> Result<String, CmdError> {
156        self.stop_recording_with_options(options.to_map()?).await
157    }
158}
159
160#[async_trait]
161impl AndroidCanRecordScreen for AndroidClient {}
162
163#[derive(Serialize, Copy, Clone, Debug, Eq, PartialEq)]
164#[serde(rename_all = "lowercase")]
165pub enum IOSVideoQuality {
166    Low,
167    Medium,
168    High,
169    Photo,
170}
171
172/// Record screen with iOS-specific encoding options
173#[async_trait]
174pub trait IOSCanRecordScreen : CanRecordScreen {
175    /// Starts screen recording (Android).
176    ///
177    /// **video_codec** - ffmpeg video codec type used for encoding of the recorded screen capture (see `ffmpeg -codecs`).
178    ///
179    /// **video_quality** - Quality of video encoding. Only works for real devices.
180    ///
181    /// **fps** - The Frames Per Second rate of the recorded video (1..60). Defaults to 10.
182    ///
183    /// **video_scale** - ffmpeg video scaling, none by default (<https://trac.ffmpeg.org/wiki/Scaling>).
184    ///
185    /// **video_filters** - ffmpeg video filters (eg. `transpose=1`, <https://ffmpeg.org/ffmpeg-filters.html>).
186    async fn start_recording(&self,
187                             video_codec: Option<String>,
188                             video_quality: Option<IOSVideoQuality>,
189                             fps: Option<u8>,
190                             video_scale: Option<String>,
191                             video_filters: Option<String>,
192                             force_restart: Option<bool>,
193                             time_limit: Option<Duration>,
194                             options: ScreenRecordingUploadOptions
195    ) -> Result<String, CmdError> {
196        let mut options = options.to_map()?;
197        if let Some(video_codec) = video_codec {
198            options.insert("videoType".to_string(), Value::String(video_codec));
199        }
200        if let Some(video_quality) = video_quality {
201            options.insert("videoQuality".to_string(), serde_json::to_value(video_quality)?);
202        }
203        if let Some(fps) = fps {
204            if !(1..=60).contains(&fps) {
205                return Err(CmdError::InvalidArgument(
206                    "fps".to_string(),
207                    format!("{fps} should be between 1 and 60.")
208                ))
209            }
210            options.insert("videoFps".to_string(), Value::Number(fps.into()));
211        }
212        if let Some(video_scale) = video_scale {
213            options.insert("videoScale".to_string(), Value::String(video_scale));
214        }
215        if let Some(video_filters) = video_filters {
216            options.insert("videoFilters".to_string(), Value::String(video_filters));
217        }
218        self.start_recording_with_options(force_restart, time_limit, options).await
219    }
220
221    async fn stop_recording(&self, options: ScreenRecordingUploadOptions) -> Result<String, CmdError> {
222        self.stop_recording_with_options(options.to_map()?).await
223    }
224}
225
226#[async_trait]
227impl IOSCanRecordScreen for IOSClient {}