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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
use std::{fs::create_dir_all, path::PathBuf};

use miette::{IntoDiagnostic, Result};
use tokio::fs::read_to_string;

use crate::Browser;

/// just impl `browser` method
pub trait TempPath {
    fn browser(&self) -> Browser;

    /// for gen temp path
    fn temp_path_prefix(&self) -> PathBuf {
        let mut temp_path = dirs::cache_dir().expect("get cache_dir failed");
        temp_path.push(format!("tidy_browser/{}", self.browser(),));
        create_dir_all(&temp_path).expect("create temp path failed");

        temp_path
    }
}

/// just impl the `base` method
pub trait ChromiumInfo: TempPath {
    const BOOKMARKS: &'static str = "Bookmarks"; // json
    const COOKIES: &'static str = "Cookies"; // sqlite3

    // const PROFILE_PICTURE: &'static str = "Edge Profile Picture.png";
    const EXTENSION_COOKIES: &'static str = "Extension Cookies";
    // const FAVICONS: &'static str = "Favicons"; // sqlite3
    const HISTORY: &'static str = "History"; // sqlite3
    const LOAD_STATISTICS: &'static str = "load_statistics.db"; // sqlite3
    const LOGIN_DATA: &'static str = "Login Data"; // sqlite3
    const MEDIA_DEVICE_SALTS: &'static str = "MediaDeviceSalts"; // sqlite3, https://source.chromium.org/chromium/chromium/src/+/main:components/media_device_salt/README.md
    const NETWORK_ACTION_PREDICTOR: &'static str = "Network Action Predictor"; // sqlite3
    const LOCAL_STORAGE: &'static str = "Local Storage/leveldb";
    const EXTENSIONS: &'static str = "Extensions"; // a directory
    const SESSION_STORAGE: &'static str = "Session Storage"; // leveldb
    /// The webdata component manages the "web database", a `SQLite` database stored in the user's profile
    /// containing various webpage-related metadata such as autofill and web search engine data.
    const WEB_DATA: &'static str = "Web Data"; // sqlite3, https://source.chromium.org/chromium/chromium/src/+/main:components/webdata/README.md
    /// This directory contains shared files for the implementation of the <chrome://local-state> `WebUI` page.
    const LOCAL_STATE: &'static str = "Local State"; // key, json, https://source.chromium.org/chromium/chromium/src/+/main:components/local_state/README.md

    fn base(&self) -> &PathBuf;

    /// json, for windows fetch passwd
    fn local_state(&self) -> PathBuf {
        let mut path = self.base().clone();
        path.pop();
        path.push(Self::LOCAL_STATE);
        path
    }
    fn local_state_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::LOCAL_STATE)
    }

    /// sqlite3
    fn credit(&self) -> PathBuf {
        self.base().join(Self::WEB_DATA)
    }
    fn credit_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::WEB_DATA)
    }

    /// leveldb
    fn session(&self) -> PathBuf {
        self.base()
            .join(Self::SESSION_STORAGE)
    }
    fn session_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::SESSION_STORAGE)
    }

    /// a directory
    fn extensions(&self) -> PathBuf {
        self.base().join(Self::EXTENSIONS)
    }
    fn extensions_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::EXTENSIONS)
    }

    /// sqlite3
    fn logindata(&self) -> PathBuf {
        match self.browser() {
            Browser::Yandex => self.base().join("Ya Passman Data"),
            _ => self.base().join(Self::LOGIN_DATA),
        }
    }
    fn logindata_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::LOGIN_DATA)
    }

    /// leveldb
    fn storage(&self) -> PathBuf {
        self.base()
            .join(Self::LOCAL_STORAGE)
    }
    fn storage_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::LOCAL_STORAGE)
    }

    /// json
    fn bookmarks(&self) -> PathBuf {
        self.base().join(Self::BOOKMARKS)
    }
    fn bookmarks_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::BOOKMARKS)
    }

    /// sqlite3
    fn history(&self) -> PathBuf {
        self.base().join(Self::HISTORY)
    }
    fn history_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::HISTORY)
    }

    /// sqlite3
    fn cookies(&self) -> PathBuf {
        self.base().join(Self::COOKIES)
    }
    fn cookies_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::COOKIES)
    }

    /// for fetch password
    #[cfg(target_os = "macos")]
    fn safe_name(&self) -> &str {
        match self.browser() {
            Browser::Chromium => "Chromium",
            Browser::Chrome => "Chrome",
            Browser::Edge => "Microsoft Edge",
            Browser::Brave => "Brave",
            Browser::Yandex => "Yandex",
            Browser::Vivaldi => "Vivaldi",
            Browser::Opera => "Opera",
            #[cfg(not(target_os = "linux"))]
            Browser::OperaGX => "Opera",
            #[cfg(not(target_os = "linux"))]
            Browser::CocCoc => "CocCoc",
            #[cfg(not(target_os = "linux"))]
            Browser::Arc => "Arc",
            _ => panic!("safe storage not support: {}", self.browser()),
        }
    }

    /// for fetch password
    #[cfg(not(target_os = "windows"))]
    fn safe_storage(&self) -> &str {
        match self.browser() {
            Browser::Chromium => "Chromium Safe Storage",
            Browser::Chrome => "Chrome Safe Storage",
            Browser::Edge => "Microsoft Edge Safe Storage",
            Browser::Brave => "Brave Safe Storage",
            Browser::Yandex => "Yandex Safe Storage",
            Browser::Vivaldi => "Vivaldi Safe Storage",
            Browser::Opera => "Opera Safe Storage",
            #[cfg(not(target_os = "linux"))]
            Browser::OperaGX => "Opera Safe Storage",
            #[cfg(not(target_os = "linux"))]
            Browser::CocCoc => "CocCoc Safe Storage",
            #[cfg(not(target_os = "linux"))]
            Browser::Arc => "Arc Safe Storage",
            _ => panic!("safe storage not support: {}", self.browser()),
        }
    }
}

pub trait FfInfo: TempPath {
    const COOKIES: &'static str = "cookies.sqlite";
    const DATAS: &'static str = "places.sqlite"; // Bookmarks, Downloads and Browsing History:
    const BOOKMARKBACKUPS: &'static str = "bookmarkbackups/bookmarks-date.jsonlz4";
    const FAVICONS: &'static str = "favicons.sqlite"; // sqlite3, This file contains all of the favicons for your Firefox bookmarks.
    const KEY: &'static str = "key4.db"; // key sqlite3
    const PASSWD: &'static str = "logins.json"; // passwd
    const SEARCH: &'static str = "search.json.mozlz4"; // This file stores user-installed search engines.
    const STORAGE: &'static str = "webappsstore.sqlite"; // web storage data
    const EXTENSIONS: &'static str = "extensions.json";
    const CERT9: &'static str = "cert9.db"; // This file stores all your security certificate settings and any SSL certificates you have imported into Firefox.

    fn base(&self) -> &PathBuf;

    /// json
    fn extensions(&self) -> PathBuf {
        self.base().join(Self::EXTENSIONS)
    }
    fn extensions_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::EXTENSIONS)
    }

    /// json
    fn passwd(&self) -> PathBuf {
        self.base().join(Self::PASSWD)
    }
    fn passwd_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::PASSWD)
    }

    /// sqlite3
    fn storage(&self) -> PathBuf {
        self.base().join(Self::STORAGE)
    }
    fn storage_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::STORAGE)
    }

    /// sqlite3
    fn key(&self) -> PathBuf {
        self.base().join(Self::KEY)
    }
    fn key_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::KEY)
    }

    /// sqlite3
    fn datas(&self) -> PathBuf {
        self.base().join(Self::DATAS)
    }
    fn datas_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::DATAS)
    }

    /// sqlite3
    fn cookies(&self) -> PathBuf {
        self.base().join(Self::COOKIES)
    }
    fn cookies_temp(&self) -> PathBuf {
        self.temp_path_prefix()
            .join(Self::COOKIES)
    }

    fn helper(
        init_path: PathBuf,
        base: &str,
    ) -> impl std::future::Future<Output = Result<PathBuf>> + Send {
        let mut ini_path = init_path.clone();
        ini_path.push(format!("{}/profiles.ini", base));
        async move {
            if !ini_path.exists() {
                miette::bail!(
                    "{} not exists",
                    ini_path
                        .to_str()
                        .unwrap_or_default()
                );
            }
            let str = read_to_string(ini_path)
                .await
                .into_diagnostic()?;
            let ini_file = ini::Ini::load_from_str(&str).into_diagnostic()?;
            let mut section = String::new();
            for (sec, prop) in ini_file {
                let Some(sec) = sec
                else {
                    continue;
                };
                if sec.starts_with("Install") {
                    prop.get("Default")
                        .unwrap_or_default()
                        .clone_into(&mut section);
                    break;
                }
            }

            tracing::debug!("section: {}", section);

            let mut res = init_path;
            res.push(format!("{}/{}", base, section));
            tracing::debug!("path: {:?}", res);

            Ok(res)
        }
    }
}

#[cfg(target_os = "linux")]
pub mod linux {
    use std::path::PathBuf;

    use miette::Result;

    use super::{ChromiumInfo, FfInfo, TempPath};
    use crate::Browser;

    #[derive(Clone)]
    #[derive(Debug)]
    #[derive(Default)]
    #[derive(PartialEq, Eq)]
    pub struct LinuxChromiumBase {
        pub base:    PathBuf,
        pub browser: Browser,
    }

    impl TempPath for LinuxChromiumBase {
        fn browser(&self) -> Browser {
            self.browser
        }
    }

    impl ChromiumInfo for LinuxChromiumBase {
        fn base(&self) -> &PathBuf {
            &self.base
        }
    }

    // TODO: add dev,nightly .etc channel
    impl LinuxChromiumBase {
        pub const EDGE_LINUX: &'static str = "microsoft-edge/Default";
        pub const CHROME_LINUX: &'static str = "google-chrome/Default";
        pub const OPERA_LINUX: &'static str = "opera/Default";
        pub const BRAVE_LINUX: &'static str = "BraveSoftware/Brave-Browser/Default";
        pub const CHROMIUM_LINUX: &'static str = "chromium/Default";
        pub const YANDEX_LINUX: &'static str = "yandex-browser/Default";
        pub const VIVALDI_LINUX: &'static str = "vivaldi/Default";

        pub fn new(browser: Browser) -> Self {
            let base = match browser {
                Browser::Edge => Self::EDGE_LINUX,
                Browser::Chromium => Self::CHROMIUM_LINUX,
                Browser::Chrome => Self::CHROME_LINUX,
                Browser::Brave => Self::BRAVE_LINUX,
                Browser::Yandex => Self::YANDEX_LINUX,
                Browser::Vivaldi => Self::VIVALDI_LINUX,
                Browser::Opera => Self::OPERA_LINUX,
                _ => panic!("Linux Chromium base not support: {browser}"),
            };
            let mut res = dirs::config_dir().expect("get config dir failed");
            res.push(base);

            Self { base: res, browser }
        }
    }

    #[derive(Clone)]
    #[derive(Debug)]
    #[derive(Default)]
    #[derive(PartialEq, Eq)]
    pub struct LinuxFFBase {
        base:    PathBuf,
        browser: Browser,
    }

    impl TempPath for LinuxFFBase {
        fn browser(&self) -> Browser {
            self.browser
        }
    }

    impl FfInfo for LinuxFFBase {
        fn base(&self) -> &PathBuf {
            &self.base
        }
    }

    impl LinuxFFBase {
        const FF_BASE: &'static str = ".mozilla/firefox";
        const LIBREWOLF_BASE: &'static str = ".librewolf";

        pub async fn new(browser: Browser) -> Result<Self> {
            let init = dirs::home_dir().ok_or_else(|| miette::miette!("get home dir failed"))?;
            let base = match browser {
                Browser::Librewolf => Self::LIBREWOLF_BASE,
                Browser::Firefox => Self::FF_BASE,
                _ => panic!("Linux Firefox base not support: {browser}"),
            };
            let base = Self::helper(init, base).await?;

            Ok(Self { base, browser })
        }
    }
}

#[cfg(target_os = "macos")]
pub mod macos {
    use std::path::PathBuf;

    use miette::Result;

    use super::{ChromiumInfo, FfInfo, TempPath};
    use crate::Browser;

    #[derive(Clone)]
    #[derive(Debug)]
    #[derive(Default)]
    #[derive(PartialEq, Eq)]
    pub struct MacChromiumBase {
        pub base:    PathBuf,
        pub browser: Browser,
    }

    impl TempPath for MacChromiumBase {
        fn browser(&self) -> Browser {
            self.browser
        }
    }

    impl MacChromiumBase {
        pub const EDGE_MAC: &'static str = "Microsoft Edge/Default";
        pub const CHROME_MAC: &'static str = "Google/Chrome/Default";
        pub const CHROMIUM_MAC: &'static str = "Chromium/Default";
        pub const BRAVE_MAC: &'static str = "BraveSoftware/Brave-Browser/Default";
        pub const YANDEX_MAC: &'static str = "Yandex/YandexBrowser/Default";
        pub const VIVALDI_MAC: &'static str = "Vivaldi/Default";
        pub const OPERA_MAC: &'static str = "com.operasoftware.Opera/Default";
        pub const OPERAGX_MAC: &'static str = "com.operasoftware.OperaGX";
        pub const COCCOC_MAC: &'static str = "Coccoc/Default";
        pub const ARC_MAC: &'static str = "Arc/User Data/Default";

        pub fn new(browser: Browser) -> Self {
            let mut cookie_dir = dirs::config_local_dir().expect("get config dir failed");
            let v = match browser {
                Browser::Chrome => Self::CHROME_MAC,
                Browser::Edge => Self::EDGE_MAC,
                Browser::Chromium => Self::CHROMIUM_MAC,
                Browser::Brave => Self::BRAVE_MAC,
                Browser::Yandex => Self::YANDEX_MAC,
                Browser::Vivaldi => Self::VIVALDI_MAC,
                Browser::Opera => Self::OPERA_MAC,
                Browser::OperaGX => Self::OPERAGX_MAC,
                Browser::CocCoc => Self::COCCOC_MAC,
                Browser::Arc => Self::ARC_MAC,
                _ => panic!("MacOs Chromium base not support: {browser}"),
            };
            cookie_dir.push(v);
            Self { base: cookie_dir, browser }
        }
    }

    impl ChromiumInfo for MacChromiumBase {
        fn base(&self) -> &PathBuf {
            &self.base
        }
    }

    #[derive(Clone)]
    #[derive(Debug)]
    #[derive(Default)]
    #[derive(PartialEq, Eq)]
    pub struct MacFFBase {
        pub base: PathBuf,
        browser:  Browser,
    }

    impl TempPath for MacFFBase {
        fn browser(&self) -> Browser {
            self.browser
        }
    }

    impl FfInfo for MacFFBase {
        fn base(&self) -> &PathBuf {
            &self.base
        }
    }

    impl MacFFBase {
        const FIREFOX_BASE: &'static str = "Firefox";
        const LIBREWOLF_BASE: &'static str = "librewolf";

        pub async fn new(browser: Browser) -> Result<Self> {
            let init = dirs::config_local_dir()
                .ok_or_else(|| miette::miette!("get config local dir failed"))?;
            let base = match browser {
                Browser::Librewolf => Self::LIBREWOLF_BASE,
                Browser::Firefox => Self::FIREFOX_BASE,
                _ => panic!("MacOs Firefox base not support: {browser}"),
            };
            let base = Self::helper(init, base).await?;

            Ok(Self { base, browser })
        }
    }
}

#[cfg(target_os = "windows")]
pub mod win {
    use std::path::PathBuf;

    use miette::Result;

    use super::{ChromiumInfo, FfInfo, TempPath};
    use crate::Browser;

    #[derive(Clone)]
    #[derive(Debug)]
    #[derive(Default)]
    #[derive(PartialEq, Eq)]
    pub struct WinChromiumBase {
        base:    PathBuf,
        browser: Browser,
    }

    impl TempPath for WinChromiumBase {
        fn browser(&self) -> Browser {
            self.browser
        }
    }

    impl WinChromiumBase {
        /// consume self
        pub fn into_key(mut self) -> PathBuf {
            self.base.push(Self::LOCAL_STATE);
            self.base
        }
    }

    impl WinChromiumBase {
        const EDGE_WIN: &'static str = "Microsoft/Edge/User Data/Default";
        const CHROME_WIN: &'static str = "Google/Chrome/User Data/Default";
        const CHROMIUM_WIN: &'static str = "Chromium/User Data/Default";
        const BRAVE_WIN: &'static str = "BraveSoftware/Brave-Browser/User Data/Default";
        const VIVALDI_WIN: &'static str = "Vivaldi/User Data/Default";
        const COCCOC_WIN: &'static str = "CocCoc/Browser/User Data/Default";
        const YANDEX_WIN: &'static str = "Yandex/YandexBrowser/User Data/Default";
        const OPERA_WIN: &'static str = "Opera Software/Opera Stable/Default";
        const OPERAGX_WIN: &'static str = "Opera Software/Opera GX Stable";
        // const ARC_WIN: &'static str = r#"Yandex/YandexBrowser/User Data/Default"#;

        pub fn new(browser: Browser) -> Self {
            let mut cookie_dir = if matches!(browser, Browser::Opera | Browser::OperaGX) {
                dirs::data_dir().expect("get config dir failed")
            }
            else {
                dirs::data_local_dir().expect("get config dir failed")
            };

            let path_base = match browser {
                Browser::Edge => Self::EDGE_WIN,
                Browser::Chromium => Self::CHROMIUM_WIN,
                Browser::Chrome => Self::CHROME_WIN,
                Browser::Brave => Self::BRAVE_WIN,
                Browser::Yandex => Self::YANDEX_WIN,
                Browser::Vivaldi => Self::VIVALDI_WIN,
                Browser::Opera => Self::OPERA_WIN,
                Browser::OperaGX => Self::OPERAGX_WIN,
                Browser::CocCoc => Self::COCCOC_WIN,
                // Browser::Arc => Self::ARC_WIN,
                _ => panic!("Windows Chromium base not support: {browser}."),
            };
            cookie_dir.push(path_base);

            Self { base: cookie_dir, browser }
        }
    }

    impl ChromiumInfo for WinChromiumBase {
        const COOKIES: &'static str = "Network/Cookies"; // sqlite3

        fn base(&self) -> &PathBuf {
            &self.base
        }
        fn local_state(&self) -> PathBuf {
            // shit, quirky
            if self.browser == Browser::OperaGX {
                self.base().join(Self::LOCAL_STATE)
            }
            else {
                let mut path = self.base().clone();
                path.pop();
                path.push(Self::LOCAL_STATE);
                path
            }
        }
        fn cookies_temp(&self) -> PathBuf {
            self.temp_path_prefix()
                .join("Cookies")
        }
    }

    #[derive(Clone)]
    #[derive(Debug)]
    #[derive(Default)]
    #[derive(PartialEq, Eq)]
    pub struct WinFFBase {
        base:    PathBuf,
        browser: Browser,
    }

    impl TempPath for WinFFBase {
        fn browser(&self) -> Browser {
            self.browser
        }
    }

    impl WinFFBase {
        const FIREFOX_BASE: &'static str = r"Mozilla\Firefox";
        const LIBREWOLF_BASE: &'static str = "librewolf";

        pub async fn new(browser: Browser) -> Result<Self> {
            let base = match browser {
                Browser::Librewolf => Self::LIBREWOLF_BASE,
                Browser::Firefox => Self::FIREFOX_BASE,
                _ => panic!("Windows Firefox base not support: {browser}"),
            };
            let init =
                dirs::data_dir().ok_or_else(|| miette::miette!("get data local dir failed"))?;
            let base = Self::helper(init, base).await?;

            Ok(Self { base, browser })
        }
    }

    impl FfInfo for WinFFBase {
        fn base(&self) -> &PathBuf {
            &self.base
        }
    }
}