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
use std::{
    string::ToString,
    time::{SystemTime, UNIX_EPOCH},
};

use anyhow::Result;
use diesel::prelude::*;
use gtk::{
    gdk_pixbuf, gio,
    glib::{self, clone},
    prelude::*,
    subclass::prelude::*,
};
use url::Url;

use crate::{
    models::{database, Account, AccountsModel, Algorithm, Method, FAVICONS_PATH, OTP},
    schema::providers,
};

pub struct ProviderPatch {
    pub name: String,
    pub website: Option<String>,
    pub help_url: Option<String>,
    pub image_uri: Option<String>,
    pub period: i32,
    pub digits: i32,
    pub default_counter: i32,
    pub algorithm: String,
    pub method: String,
    pub is_backup_restore: bool,
}

#[derive(Insertable)]
#[diesel(table_name = providers)]
struct NewProvider {
    pub name: String,
    pub website: Option<String>,
    pub help_url: Option<String>,
    pub image_uri: Option<String>,
    pub period: i32,
    pub digits: i32,
    pub default_counter: i32,
    pub algorithm: String,
    pub method: String,
}

#[derive(Identifiable, Queryable)]
#[diesel(table_name = providers)]
pub struct DieselProvider {
    pub id: i32,
    pub name: String,
    pub website: Option<String>,
    pub help_url: Option<String>,
    pub image_uri: Option<String>,
    pub period: i32,
    pub digits: i32,
    pub default_counter: i32,
    pub algorithm: String,
    pub method: String,
}

mod imp {
    use std::cell::{Cell, RefCell};

    use super::*;

    #[derive(glib::Properties)]
    #[properties(wrapper_type = super::Provider)]
    pub struct Provider {
        #[property(get, set, construct_only)]
        pub id: Cell<u32>,
        #[property(get, set)]
        pub name: RefCell<String>,
        #[property(get, set, maximum = 1000, default = OTP::DEFAULT_PERIOD)]
        pub period: Cell<u32>,
        #[property(get, set, builder(Method::default()))]
        pub method: Cell<Method>,
        #[property(get, set, default = OTP::DEFAULT_COUNTER)]
        pub default_counter: Cell<u32>,
        #[property(get, set, builder(Algorithm::default()))]
        pub algorithm: Cell<Algorithm>,
        #[property(get, set, maximum = 1000, default = OTP::DEFAULT_DIGITS)]
        pub digits: Cell<u32>,
        #[property(get, set)]
        pub website: RefCell<Option<String>>,
        #[property(get, set)]
        pub help_url: RefCell<Option<String>>,
        #[property(get, set = Self::set_image_uri, explicit_notify)]
        pub image_uri: RefCell<Option<String>>,
        #[property(get, set)]
        pub remaining_time: Cell<u64>,
        #[property(get)]
        pub accounts_model: AccountsModel,
        pub filter_model: gtk::FilterListModel,
        pub tick_callback: RefCell<Option<glib::SourceId>>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for Provider {
        const NAME: &'static str = "Provider";
        type Type = super::Provider;

        fn new() -> Self {
            let model = AccountsModel::default();
            Self {
                id: Cell::default(),
                default_counter: Cell::new(OTP::DEFAULT_COUNTER),
                algorithm: Cell::new(Algorithm::default()),
                digits: Cell::new(OTP::DEFAULT_DIGITS),
                name: RefCell::default(),
                website: RefCell::default(),
                help_url: RefCell::default(),
                image_uri: RefCell::default(),
                method: Cell::new(Method::default()),
                period: Cell::new(OTP::DEFAULT_PERIOD),
                filter_model: gtk::FilterListModel::new(Some(model.clone()), None::<gtk::Filter>),
                accounts_model: model,
                tick_callback: RefCell::default(),
                remaining_time: Cell::default(),
            }
        }
    }

    #[glib::derived_properties]
    impl ObjectImpl for Provider {
        fn dispose(&self) {
            // Stop ticking
            if let Some(source_id) = self.tick_callback.borrow_mut().take() {
                source_id.remove();
            }
        }
    }

    impl Provider {
        fn set_image_uri_inner(&self, id: i32, uri: Option<&str>) -> anyhow::Result<()> {
            let db = database::connection();
            let mut conn = db.get()?;

            let target = providers::table.filter(providers::columns::id.eq(id));
            diesel::update(target)
                .set(providers::columns::image_uri.eq(uri))
                .execute(&mut conn)?;

            Ok(())
        }

        fn set_image_uri(&self, uri: Option<&str>) {
            let obj = self.obj();
            if let Err(err) = self.set_image_uri_inner(obj.id() as i32, uri) {
                tracing::warn!("Failed to update provider image {}", err);
            }
            self.image_uri.replace(uri.map(ToOwned::to_owned));
            obj.notify_image_uri();
        }
    }
}

glib::wrapper! {
    pub struct Provider(ObjectSubclass<imp::Provider>);
}

impl Provider {
    #[allow(clippy::too_many_arguments)]
    pub fn create(
        name: &str,
        period: u32,
        algorithm: Algorithm,
        website: Option<String>,
        method: Method,
        digits: u32,
        default_counter: u32,
        help_url: Option<String>,
        image_uri: Option<String>,
    ) -> Result<Self> {
        let db = database::connection();
        let mut conn = db.get()?;

        diesel::insert_into(providers::table)
            .values(NewProvider {
                name: name.to_string(),
                period: period as i32,
                method: method.to_string(),
                website,
                algorithm: algorithm.to_string(),
                digits: digits as i32,
                default_counter: default_counter as i32,
                help_url,
                image_uri,
            })
            .execute(&mut conn)?;

        providers::table
            .order(providers::columns::id.desc())
            .first::<DieselProvider>(&mut conn)
            .map_err(From::from)
            .map(From::from)
    }

    pub fn load() -> Result<impl Iterator<Item = Self>> {
        use crate::schema::providers::dsl::*;
        let db = database::connection();
        let mut conn = db.get()?;

        let results = providers
            .load::<DieselProvider>(&mut conn)?
            .into_iter()
            .map(From::from)
            .map(|p: Provider| {
                let accounts = Account::load(&p).unwrap().collect::<Vec<_>>();
                p.add_accounts(&accounts);
                p
            });
        Ok(results)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: u32,
        name: &str,
        period: u32,
        method: Method,
        algorithm: Algorithm,
        digits: u32,
        default_counter: u32,
        website: Option<String>,
        help_url: Option<String>,
        image_uri: Option<String>,
    ) -> Provider {
        glib::Object::builder()
            .property("id", id)
            .property("name", name)
            .property("website", website)
            .property("help-url", help_url)
            .property("image-uri", image_uri)
            .property("period", period)
            .property("method", method)
            .property("algorithm", algorithm)
            .property("digits", digits)
            .property("default-counter", default_counter)
            .build()
    }

    pub async fn favicon(
        website: String,
        name: String,
        id: u32,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let website_url = Url::parse(&website)?;
        let favicon = favicon_scrapper::Scrapper::from_url(&website_url).await?;
        tracing::debug!("Found the following icons {:#?} for {}", favicon, name);

        let icon_name = format!("{id}_{}", name.replace(' ', "_"));
        let icon_name = glib::base64_encode(icon_name.as_bytes());
        let small_icon_name = format!("{icon_name}_32x32");
        let large_icon_name = format!("{icon_name}_96x96");
        // TODO: figure out why trying to grab icons at specific size causes stack size
        // errors We need two sizes:
        // - 32x32 for the accounts lists
        // - 96x96 elsewhere
        if let Some(best_favicon) = favicon.find_best().await {
            tracing::debug!("Largest favicon found is {:#?}", best_favicon);
            let cache_path = FAVICONS_PATH.join(&*icon_name);
            best_favicon.save(cache_path.clone()).await?;
            // Don't try to scale down svg variants
            if !best_favicon.metadata().format().is_svg() {
                tracing::debug!("Creating scaled down variants for {:#?}", cache_path);
                {
                    let pixbuf = gdk_pixbuf::Pixbuf::from_file(cache_path.clone())?;
                    tracing::debug!("Creating a 32x32 variant of the favicon");
                    let small_pixbuf = pixbuf
                        .scale_simple(32, 32, gdk_pixbuf::InterpType::Bilinear)
                        .unwrap();

                    let mut small_cache = cache_path.clone();
                    small_cache.set_file_name(small_icon_name);
                    small_pixbuf.savev(small_cache.clone(), "png", &[])?;

                    tracing::debug!("Creating a 96x96 variant of the favicon");
                    let large_pixbuf = pixbuf
                        .scale_simple(96, 96, gdk_pixbuf::InterpType::Bilinear)
                        .unwrap();
                    let mut large_cache = cache_path.clone();
                    large_cache.set_file_name(large_icon_name);
                    large_pixbuf.savev(large_cache.clone(), "png", &[])?;
                };
                tokio::fs::remove_file(cache_path).await?;
            } else {
                let mut small_cache = cache_path.clone();
                small_cache.set_file_name(small_icon_name);
                tokio::fs::symlink(&cache_path, small_cache).await?;

                let mut large_cache = cache_path.clone();
                large_cache.set_file_name(large_icon_name);
                tokio::fs::symlink(&cache_path, large_cache).await?;
            }
            Ok(icon_name.to_string())
        } else {
            Err(Box::new(favicon_scrapper::Error::NoResults))
        }
    }

    pub fn delete(&self) -> Result<()> {
        let db = database::connection();
        let mut conn = db.get()?;
        diesel::delete(providers::table.filter(providers::columns::id.eq(self.id() as i32)))
            .execute(&mut conn)?;
        Ok(())
    }

    pub fn update(&self, patch: &ProviderPatch) -> Result<()> {
        // Can't implement PartialEq because of how GObject works
        if patch.name == self.name()
            && patch.website == self.website()
            && patch.help_url == self.help_url()
            && patch.image_uri == self.image_uri()
            && patch.period == self.period() as i32
            && patch.digits == self.digits() as i32
            && patch.default_counter == self.default_counter() as i32
            && patch.algorithm == self.algorithm().to_string()
            && patch.method == self.method().to_string()
        {
            return Ok(());
        }

        let db = database::connection();
        let mut conn = db.get()?;

        let target = providers::table.filter(providers::columns::id.eq(self.id() as i32));
        diesel::update(target)
            .set((
                providers::columns::algorithm.eq(&patch.algorithm),
                providers::columns::method.eq(&patch.method),
                providers::columns::digits.eq(&patch.digits),
                providers::columns::period.eq(&patch.period),
                providers::columns::default_counter.eq(&patch.default_counter),
                providers::columns::name.eq(&patch.name),
            ))
            .execute(&mut conn)?;
        if !patch.is_backup_restore {
            diesel::update(target)
                .set((
                    providers::columns::image_uri.eq(&patch.image_uri),
                    providers::columns::website.eq(&patch.website),
                    providers::columns::help_url.eq(&patch.help_url),
                ))
                .execute(&mut conn)?;
        };

        self.set_properties(&[
            ("name", &patch.name),
            ("period", &(patch.period as u32)),
            ("method", &patch.method.parse::<Method>()?),
            ("digits", &(patch.digits as u32)),
            ("algorithm", &patch.algorithm.parse::<Algorithm>()?),
            ("default-counter", &(patch.default_counter as u32)),
        ]);

        if !patch.is_backup_restore {
            self.set_properties(&[
                ("image-uri", &patch.image_uri),
                ("website", &patch.website),
                ("help-url", &patch.help_url),
            ]);
        }
        Ok(())
    }

    pub fn open_help(&self) {
        if let Some(ref url) = self.help_url() {
            gio::AppInfo::launch_default_for_uri(url, None::<&gio::AppLaunchContext>).unwrap();
        }
    }

    fn tick(&self) {
        let period = self.period() as u64;
        let remaining_time: u64 = period
            - SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs()
                % period;
        if period == remaining_time {
            self.regenerate_otp();
        }
        self.set_remaining_time(remaining_time);
    }

    fn setup_tick_callback(&self) {
        if self.imp().tick_callback.borrow().is_some() || self.method().is_event_based() {
            return;
        }
        self.set_remaining_time(self.period() as u64);

        match self.method() {
            Method::TOTP | Method::Steam => {
                let source_id = glib::timeout_add_seconds_local(
                    1,
                    clone!(@weak self as provider => @default-return glib::ControlFlow::Break, move || {
                        provider.tick();
                        glib::ControlFlow::Continue
                    }),
                );
                self.imp().tick_callback.replace(Some(source_id));
            }
            _ => (),
        };
    }

    fn regenerate_otp(&self) {
        let accounts = self.accounts();
        for i in 0..accounts.n_items() {
            let item = accounts.item(i).unwrap();
            let account = item.downcast_ref::<Account>().unwrap();
            account.generate_otp();
        }
    }

    pub fn has_accounts(&self) -> bool {
        self.accounts_model().n_items() != 0
    }

    fn add_accounts(&self, accounts: &[Account]) {
        self.accounts_model().splice(accounts);
        self.setup_tick_callback();
    }

    pub fn add_account(&self, account: &Account) {
        self.accounts_model().append(account);
        self.setup_tick_callback();
    }

    fn tokenize_search(account_name: &str, provider_name: &str, term: &str) -> bool {
        let term = term.to_ascii_lowercase();
        let provider_name = provider_name.to_ascii_lowercase();
        let account_name = account_name.to_ascii_lowercase();

        account_name.split_ascii_whitespace().any(|x| x == term)
            || provider_name.split_ascii_whitespace().any(|x| x == term)
            || account_name.contains(term.as_str())
            || provider_name.contains(term.as_str())
    }

    pub fn find_accounts(&self, terms: &[String]) -> Vec<Account> {
        let mut results = vec![];
        let model = self.accounts_model();
        let provider_name = self.name();
        for pos in 0..model.n_items() {
            let account = model.item(pos).and_downcast::<Account>().unwrap();
            let account_name = account.name();

            if terms
                .iter()
                .any(|term| Self::tokenize_search(&account_name, &provider_name, term))
            {
                results.push(account);
            }
        }
        results
    }

    pub fn accounts(&self) -> &gtk::FilterListModel {
        &self.imp().filter_model
    }

    pub fn filter(&self, text: String) {
        let filter = gtk::CustomFilter::new(
            glib::clone!(@weak self as provider => @default-return false, move |obj| {
                let account = obj.downcast_ref::<Account>().unwrap();
                let account_name = account.name();
                let provider_name = provider.name();

                Self::tokenize_search(&account_name, &provider_name, &text)
            }),
        );
        self.imp().filter_model.set_filter(Some(&filter));
    }

    pub fn remove_account(&self, account: &Account) {
        let imp = self.imp();
        let model = self.accounts_model();
        if let Some(pos) = model.find_position_by_id(account.id()) {
            model.remove(pos);
            if !self.has_accounts() && self.method().is_time_based() {
                // Stop ticking
                if let Some(source_id) = imp.tick_callback.borrow_mut().take() {
                    source_id.remove();
                }
            }
        }
    }
}

impl From<DieselProvider> for Provider {
    fn from(p: DieselProvider) -> Self {
        Self::new(
            p.id as u32,
            &p.name,
            p.period as u32,
            p.method.parse::<Method>().unwrap(),
            p.algorithm.parse::<Algorithm>().unwrap(),
            p.digits as u32,
            p.default_counter as u32,
            p.website,
            p.help_url,
            p.image_uri,
        )
    }
}

impl From<&Provider> for DieselProvider {
    fn from(p: &Provider) -> Self {
        Self {
            id: p.id() as i32,
            name: p.name(),
            period: p.period() as i32,
            method: p.method().to_string(),
            algorithm: p.algorithm().to_string(),
            digits: p.digits() as i32,
            default_counter: p.default_counter() as i32,
            website: p.website(),
            help_url: p.help_url(),
            image_uri: p.image_uri(),
        }
    }
}