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
use super::{Backupable, Restorable};
use crate::{Account, Algorithm, OTPMethod};
use anyhow::Result;
use serde::{Deserialize, Serialize};

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AndOTP {
    pub secret: String,
    pub issuer: Option<String>,
    pub label: String,
    pub digits: u32,
    #[serde(rename = "type")]
    pub method: OTPMethod,
    pub algorithm: Algorithm,
    pub thumbnail: String,
    pub last_used: i64,
    pub used_frequency: i32,
    pub counter: Option<u32>,
    pub tags: Vec<String>,
    pub period: Option<u32>,
}

impl Backupable for AndOTP {
    fn backup(codes: Vec<Account>) -> Result<Vec<u8>> {
        let items: Vec<AndOTP> = codes.iter().map(From::from).collect();

        let content = serde_json::ser::to_string_pretty(&items)?;
        Ok(content.as_bytes().to_vec())
    }
}

impl From<AndOTP> for Account {
    fn from(andotp: AndOTP) -> Self {
        Self {
            method: andotp.method,
            issuer: andotp.issuer,
            label: andotp.label,
            secret: andotp.secret,
            digits: andotp.digits,
            period: andotp.period,
            counter: andotp.counter,
            algorithm: andotp.algorithm,
        }
    }
}

impl From<&Account> for AndOTP {
    fn from(account: &Account) -> Self {
        Self {
            secret: account.secret.clone(),
            issuer: account.issuer.clone(),
            label: account.label.clone(),
            digits: account.digits,
            method: account.method,
            algorithm: account.algorithm,
            thumbnail: "".to_string(),
            last_used: 0,
            used_frequency: 0,
            counter: account.counter,
            tags: vec![],
            period: account.period,
        }
    }
}

impl Restorable for AndOTP {
    fn restore(bytes: &[u8]) -> Result<Vec<Account>> {
        let items: Vec<AndOTP> = serde_json::de::from_slice(&bytes)?;
        Ok(items.into_iter().map(From::from).collect())
    }
}