darkwing/server/dtos/request/
start_dto.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Data transfer objects for browser profile startup functionality.
//!
//! This module contains the structures and implementations needed to handle
//! browser profile startup requests and responses, including configuration
//! for operating systems, logging, paths, and various browser settings.

use either::Either;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use validator::Validate;

use crate::database::browser_profile::{
  BrowserProfilePreliminary, Homepage, MainWebsite, Platform, ProxyType,
};

use super::super::{bookmark_dto::BookmarkFullData, proxy_dto::ProxyFullData};

/// Represents supported operating systems for the browser profile.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum Os {
  /// macOS operating system
  #[serde(rename = "darwin")]
  MacOS,
  /// Windows operating system
  #[serde(rename = "win32")]
  Windows,
  /// Linux operating system
  #[serde(rename = "linux")]
  Linux,
}

impl From<Platform> for Os {
  fn from(platform: Platform) -> Self {
    match platform {
      Platform::Macos => Os::MacOS,
      Platform::Windows => Os::Windows,
      Platform::Linux => Os::Linux,
    }
  }
}

/// Information about the connection settings for a browser profile.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ConnectionInfo {
  /// Country code for geolocation
  pub country: String,
  /// Region or state name
  pub region: String,
  /// City name
  pub city: String,
  /// IP address
  pub ip: String,
  /// Timezone identifier
  pub timezone: String,
  /// Postal/ZIP code
  pub zip: String,
  /// Geographic coordinates [latitude, longitude]. Length must be 2
  pub geo: Vec<f64>,
  /// Optional override URL for proxy configuration
  pub override_proxy_url: Option<String>,
}

impl ConnectionInfo {
  /// Creates a mock connection info instance for testing purposes.
  pub fn get_mock() -> Self {
    Self {
      geo: vec![40.7128, -74.0060],
      country: "US".to_string(),
      region: "CA".to_string(),
      city: "San Francisco".to_string(),
      ip: "127.0.0.1".to_string(),
      timezone: "PST".to_string(),
      zip: "94105".to_string(),
      override_proxy_url: None,
    }
  }
}

/// Available logging levels for the browser profile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoggingLevel {
  /// Critical errors that cause immediate termination
  Fatal,
  /// Error conditions
  Error,
  /// Warning messages, something that may be a problem but not an error
  Warning,
  /// Informational messages
  Info,
  /// Debugging information
  Debug,
  /// Detailed tracing information
  Trace,
  /// Most verbose tracing information
  Trace2,
}

impl Serialize for LoggingLevel {
  fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
    match self {
      LoggingLevel::Fatal => serializer.serialize_str("FATAL"),
      LoggingLevel::Error => serializer.serialize_str("ERROR"),
      LoggingLevel::Warning => serializer.serialize_str("WARNING"),
      LoggingLevel::Info => serializer.serialize_str("INFO"),
      LoggingLevel::Debug => serializer.serialize_str("DEBUG"),
      LoggingLevel::Trace => serializer.serialize_str("TRACE"),
      LoggingLevel::Trace2 => serializer.serialize_str("TRACE2"),
    }
  }
}

impl<'de> Deserialize<'de> for LoggingLevel {
  fn deserialize<D: Deserializer<'de>>(
    deserializer: D,
  ) -> Result<Self, D::Error> {
    use serde::de::Error;

    let s = String::deserialize(deserializer)?.to_uppercase();
    match s.as_str() {
      "FATAL" => Ok(LoggingLevel::Fatal),
      "ERROR" => Ok(LoggingLevel::Error),
      "WARNING" => Ok(LoggingLevel::Warning),
      "INFO" => Ok(LoggingLevel::Info),
      "DEBUG" => Ok(LoggingLevel::Debug),
      "TRACE" => Ok(LoggingLevel::Trace),
      "TRACE2" => Ok(LoggingLevel::Trace2),
      _ => Err(D::Error::custom(format!("Invalid logging level: {}", s))),
    }
  }
}

/// Paths configuration for the browser profile.
#[derive(Debug, Serialize, Deserialize, Validate, Clone)]
pub struct UserPaths {
  /// AppData directory. C:\Users\<username>\AppData\Roaming\dolphin_anty on
  /// Windows, ~/.config/dolphin_anty on Linux, ~/Library/Application
  /// Support/dolphin_anty on macOS
  pub app_data_dir: String,
  /// Browser profile data directory. In this folder Chrome stores all its
  /// files. This is the root directory for one profile for Chrome.
  ///
  /// C:\Users\<username>\AppData\Roaming\dolphin_anty\browser_profiles\
  /// <browser_profile_id>\data_dir on Windows,
  /// ~/.config/dolphin_anty/browser_profiles/<browser_profile_id>/data_dir on
  /// Linux, ~/Library/Application
  /// Support/dolphin_anty/browser_profiles/<browser_profile_id>/data_dir on
  /// macOS
  pub user_data_dir: String,
  /// Directory for Chromium components. We do not want to store it in
  /// `user_data_dir` because the folder size will be too big, so there is a
  /// directory-per-user instead of directory-per-browser-profiles.
  pub user_chromium_components_dir: String,
}

impl UserPaths {
  /// Creates a mock paths configuration for testing purposes.
  pub fn get_mock() -> Self {
    Self {
      app_data_dir: "/Users/user/Library/Application Support/dolphin_anty"
        .to_string(),
      user_data_dir:
        "/Users/user/Library/Application Support/dolphin_anty/123456/data_dir"
          .to_string(),
      user_chromium_components_dir:
        "/Users/user/Library/Application Support/dolphin_anty/chromium_components".to_string(),
    }
  }
}

/// Version information for various components.
#[derive(Debug, Serialize, Deserialize, Validate, Clone)]
pub struct Versions {
  /// Browser version number. I.e. 356.
  pub browser: u16,
  /// Local API version string. I.e. "2022.1.1".
  pub local_api: String,
  /// Electron version string. I.e. "2024.351.1".
  pub electron: String,
  /// Anty extension version. I.e. 5.
  pub anty_extension: u16,
  /// Dolphin extension version. I.e. 7.
  pub dolphin_extension: u16,
}

impl Versions {
  /// Creates a mock versions configuration for testing purposes.
  pub fn get_mock() -> Self {
    Self {
      browser: 256,
      local_api: "2022.1.1".to_string(),
      electron: "2024.351.1".to_string(),
      anty_extension: 5,
      dolphin_extension: 7,
    }
  }
}

/// Request structure for starting a browser profile.
#[derive(Debug, Serialize, Deserialize, Validate, Clone)]
pub struct StartRequest {
  /// Unique identifier of the browser profile to start
  pub browser_profile_id: usize,
  /// Platform that user is running our software on
  pub os: Os,
  /// Version information for various components
  pub versions: Versions,
  /// Whether to enable automation mode
  pub automation: bool,
  /// Whether to run browser in headless mode (no GUI)
  pub headless: bool,
  /// Whether to disable images loading
  pub imageless: bool,
  /// Whether to use action synchronization between browser profiles
  pub use_action_synchronizator: bool,
  /// Name of the session to synchronize with.
  /// Required if `use_action_synchronizator` is true.
  pub action_synchronizator_session_name: Option<String>,
  /// Whether this profile owns the synchronization session (so the profile is
  /// master).
  pub action_synchronizator_is_owned: Option<bool>,
  /// Whether to enable custom mode for scenario execution
  pub scenum_custom_mode: bool,
  /// For scenario constructor.
  /// Implies that user _may_ use mock profile (or may not, so be cautious).
  pub for_scenario: bool,
  /// Whether to use a mock profile instead of a real one
  pub use_mock_profile: bool,
  /// Width of the user's screen in pixels
  pub user_screen_width: u16,
  /// Height of the user's screen in pixels
  pub user_screen_height: u16,
  /// Connection and geolocation information
  pub connection_info: ConnectionInfo,
  /// Optional token for Dolphin integration
  pub dolphin_integration_token: Option<String>,
  /// Base URL for remote API calls
  pub remote_api_base_url: String,
  /// File system paths configuration
  pub paths: UserPaths,
  /// Logging verbosity level
  pub logging_level: LoggingLevel,
  /// Port number for browser download operations
  pub browser_down_port: u16,
  /// Hash of the present datadir.
  /// If provided, we may send the diff url alongside the whole datadir url.
  pub present_datadir_hash: Option<String>,
}

impl StartRequest {
  /// Creates a mock start request for testing purposes.
  pub fn get_mock() -> Self {
    Self {
      browser_profile_id: 0,
      os: Os::Linux,
      versions: Versions::get_mock(),
      automation: false,
      headless: false,
      imageless: false,
      use_action_synchronizator: false,
      action_synchronizator_session_name: None,
      action_synchronizator_is_owned: None,
      scenum_custom_mode: false,
      for_scenario: false,
      use_mock_profile: false,
      user_screen_width: 0,
      user_screen_height: 0,
      connection_info: ConnectionInfo::get_mock(),
      dolphin_integration_token: None,
      remote_api_base_url: "https://api.example.com".to_string(),
      paths: UserPaths::get_mock(),
      logging_level: LoggingLevel::Info,
      browser_down_port: 255,
      present_datadir_hash: None,
    }
  }
}

/// Response structure for browser profile start requests.
#[derive(Debug, Serialize)]
pub struct StartResponse {
  /// Hash of the datadir contents
  pub hash: Option<String>,
  /// URL to download the complete datadir
  pub datadir_url: String,
  /// URL to download a patch for the datadir, if applicable
  pub patch_url: Option<String>,
  /// Browser configuration as JSON string
  pub config: String,
  /// Command to launch the browser, either as a single string or array of
  /// arguments.
  ///
  /// Array of arguments is used for Windows, where Node.js requires it to be
  /// as array of strings, and String is used for Linux and macOS
  pub command: Either<String, Vec<String>>,
}

/// Response structure for datadir operations.
#[derive(Debug, Serialize)]
pub struct DatadirResponse {
  /// Hash of the datadir zip archive
  pub hash: Option<String>,
  /// URL to download the datadir
  pub url: String,
}

/// Browser bookmark information, which will be used by anty-local-api to
/// set bookmark presets.
#[derive(Debug, Serialize)]
pub struct Bookmark {
  /// URL of the bookmark
  pub url: String,
  /// Display name of the bookmark
  pub name: String,
}

impl From<BookmarkFullData> for Bookmark {
  fn from(bookmark: BookmarkFullData) -> Self {
    Self {
      url: bookmark.url,
      name: bookmark.name,
    }
  }
}

/// Types of browser extensions that can be installed.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum ExtensionType {
  /// Extension from Chrome Web Store
  ChromeWebStore,
  /// Extension from local file
  File,
}

impl From<String> for ExtensionType {
  fn from(s: String) -> Self {
    match s.as_str() {
      "chromeWebStore" => ExtensionType::ChromeWebStore,
      "file" => ExtensionType::File,
      _ => panic!("Invalid extension type: {}", s),
    }
  }
}

/// Browser extension information.
#[derive(Debug, Serialize)]
pub struct Extension {
  /// Optional display name of the extension
  pub name: Option<String>,
  /// Unique identifier of the extension
  pub extension_id: String,
  /// URL to download or access the extension
  pub url: String,
  /// Type of the extension (Chrome Web Store or local file)
  #[serde(rename = "type")]
  pub r#type: ExtensionType,
  /// Optional hash of the extension contents
  pub hash: Option<String>,
}

impl From<crate::database::browser_profile::Extension> for Extension {
  fn from(extension: crate::database::browser_profile::Extension) -> Self {
    Self {
      extension_id: extension.extension_id,
      url: extension.url,
      r#type: extension.r#type.into(),
      hash: extension.hash,
      name: extension.name,
    }
  }
}

/// Preliminary response with browser profile configuration.
#[derive(Debug, Serialize)]
pub struct PreliminaryResponse {
  /// Proxy configuration if any
  pub proxy: Option<ProxyData>,
  /// Name of the browser profile
  pub name: String,
  /// List of homepage URLs
  pub homepages: Vec<String>,
  /// Main website configuration
  pub main_website: MainWebsite,
  /// List of bookmarks
  pub bookmarks: Vec<Bookmark>,
  /// Optional login username
  pub login: Option<String>,
  /// Optional login password
  pub password: Option<String>,
  /// Creation timestamp
  pub created_at: String,
  /// List of installed extensions
  pub extensions: Vec<Extension>,
}

/// Collection of preliminary data needed to configure a browser profile.
pub struct PreliminaryData {
  /// Basic browser profile information
  pub browser_profile: BrowserProfilePreliminary,
  /// Optional proxy configuration
  pub proxy: Option<ProxyFullData>,
  /// List of configured homepages
  pub homepages: Vec<Homepage>,
  /// List of bookmarks
  pub bookmarks: Vec<BookmarkFullData>,
  /// List of extensions
  pub extensions: Vec<Extension>,
}

impl From<PreliminaryData> for PreliminaryResponse {
  fn from(data: PreliminaryData) -> Self {
    Self {
      proxy: data.proxy.map(ProxyData::from),
      name: data.browser_profile.name,
      homepages: data.homepages.iter().map(|h| h.url.clone()).collect(),
      main_website: data.browser_profile.main_website.into(),
      bookmarks: data.bookmarks.iter().map(|b| b.clone().into()).collect(),
      login: data.browser_profile.login,
      password: data.browser_profile.password,
      created_at: data.browser_profile.created_at.to_string(),
      extensions: data.extensions,
    }
  }
}

impl PreliminaryData {
  /// Creates mock preliminary data for testing purposes.
  pub fn get_mock() -> Self {
    Self {
      proxy: None,
      homepages: vec![],
      bookmarks: vec![],
      extensions: vec![],
      browser_profile: BrowserProfilePreliminary::get_mock(),
    }
  }
}

/// Proxy configuration information.
#[derive(Debug, Serialize)]
pub struct ProxyData {
  /// Unique identifier of the proxy configuration
  pub id: u64,
  /// Type of proxy (SOCKS5, HTTP, etc.)
  pub r#type: ProxyType,
  /// Proxy server hostname
  pub host: String,
  /// Proxy server port
  pub port: String,
  /// Optional proxy authentication username
  pub login: Option<String>,
  /// Optional proxy authentication password
  pub password: Option<String>,
  /// Optional URL to trigger IP rotation
  pub change_ip_url: Option<String>,
}

impl From<ProxyFullData> for ProxyData {
  fn from(proxy: ProxyFullData) -> Self {
    Self {
      id: proxy.id,
      r#type: proxy.proxy_type,
      host: proxy.host,
      port: proxy.port,
      login: proxy.login,
      password: proxy.password,
      change_ip_url: proxy.change_ip_url,
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_os_serialization() {
    let os = Os::MacOS;
    let serialized =
      serde_json::to_string(&os).expect("Failed to serialize OS");
    assert_eq!(serialized, "\"darwin\"");

    let os = Os::Windows;
    let serialized =
      serde_json::to_string(&os).expect("Failed to serialize OS");
    assert_eq!(serialized, "\"win32\"");

    let os = Os::Linux;
    let serialized =
      serde_json::to_string(&os).expect("Failed to serialize OS");
    assert_eq!(serialized, "\"linux\"");
  }

  #[test]
  fn test_os_deserialization() {
    let os: Os =
      serde_json::from_str("\"darwin\"").expect("Failed to deserialize OS");
    assert_eq!(os, Os::MacOS);

    let os: Os =
      serde_json::from_str("\"win32\"").expect("Failed to deserialize OS");
    assert_eq!(os, Os::Windows);

    let os: Os =
      serde_json::from_str("\"linux\"").expect("Failed to deserialize OS");
    assert_eq!(os, Os::Linux);
  }

  #[test]
  fn test_logging_level_serialization() {
    let level = LoggingLevel::Info;
    let serialized =
      serde_json::to_string(&level).expect("Failed to serialize logging level");
    assert_eq!(serialized, "\"INFO\"");

    let level = LoggingLevel::Error;
    let serialized =
      serde_json::to_string(&level).expect("Failed to serialize logging level");
    assert_eq!(serialized, "\"ERROR\"");
  }

  #[test]
  fn test_logging_level_deserialization() {
    let level: LoggingLevel = serde_json::from_str("\"INFO\"")
      .expect("Failed to deserialize logging level");
    assert_eq!(level, LoggingLevel::Info);

    let level: LoggingLevel = serde_json::from_str("\"info\"")
      .expect("Failed to deserialize logging level");
    assert_eq!(level, LoggingLevel::Info);

    let result = serde_json::from_str::<LoggingLevel>("\"INVALID\"");
    assert!(result.is_err());
  }

  #[test]
  fn test_start_request_validation() {
    let mut request = StartRequest::get_mock();
    request.browser_profile_id = 1;
    assert!(request.validate().is_ok());

    let mut invalid_request = StartRequest::get_mock();
    invalid_request.browser_profile_id = 0;
    assert!(invalid_request.validate().is_err());
  }

  #[test]
  fn test_connection_info_serialization() {
    let connection_info = ConnectionInfo::get_mock();

    let serialized = serde_json::to_string(&connection_info)
      .expect("Failed to serialize connection info");
    let deserialized: ConnectionInfo = serde_json::from_str(&serialized)
      .expect("Failed to deserialize connection info");

    assert_eq!(deserialized.country, connection_info.country);
    assert_eq!(deserialized.ip, connection_info.ip);
    assert_eq!(deserialized.geo, connection_info.geo);
  }

  #[test]
  fn test_extension_type_serialization() {
    let extension_type = ExtensionType::ChromeWebStore;
    let serialized = serde_json::to_string(&extension_type)
      .expect("Failed to serialize extension type");
    assert_eq!(serialized, "\"chromeWebStore\"");
  }
}