summaryrefslogtreecommitdiffhomepage
path: root/mullvad-cli/src/cmds/account.rs
blob: af3af0debd14ed6062f168a7ea8cef39e357b08c (plain)
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
use crate::{new_rpc_client, Command, Error, Result};
use clap::value_t_or_exit;
use itertools::Itertools;
use mullvad_management_interface::{types::Timestamp, Code};
use mullvad_types::account::AccountToken;
use std::io::{self, Write};

pub struct Account;

#[mullvad_management_interface::async_trait]
impl Command for Account {
    fn name(&self) -> &'static str {
        "account"
    }

    fn clap_subcommand(&self) -> clap::App<'static, 'static> {
        clap::SubCommand::with_name(self.name())
            .about("Control and display information about your Mullvad account")
            .setting(clap::AppSettings::SubcommandRequiredElseHelp)
            .subcommand(
                clap::SubCommand::with_name("set")
                    .about("Change account")
                    .arg(
                        clap::Arg::with_name("token")
                            .help("The Mullvad account token to configure the client with")
                            .required(false),
                    ),
            )
            .subcommand(
                clap::SubCommand::with_name("get")
                    .about("Display information about the currently configured account"),
            )
            .subcommand(
                clap::SubCommand::with_name("unset")
                    .about("Removes the account number from the settings"),
            )
            .subcommand(
                clap::SubCommand::with_name("create")
                    .about("Creates a new account and sets it as the active one"),
            )
            .subcommand(
                clap::SubCommand::with_name("redeem")
                    .about("Redeems a voucher")
                    .arg(
                        clap::Arg::with_name("voucher")
                            .help("The Mullvad voucher code to be submitted")
                            .required(true),
                    ),
            )
    }

    async fn run(&self, matches: &clap::ArgMatches<'_>) -> Result<()> {
        if let Some(set_matches) = matches.subcommand_matches("set") {
            let mut token = match set_matches.value_of("token") {
                Some(token) => token.to_string(),
                None => {
                    let mut token = String::new();
                    io::stdout()
                        .write_all(b"Enter account token: ")
                        .expect("Failed to write to STDOUT");
                    let _ = io::stdout().flush();
                    io::stdin()
                        .read_line(&mut token)
                        .expect("Failed to read from STDIN");
                    token
                }
            };
            token = token.split_whitespace().join("").to_string();
            self.set(Some(token)).await
        } else if let Some(_matches) = matches.subcommand_matches("get") {
            self.get().await
        } else if let Some(_matches) = matches.subcommand_matches("unset") {
            self.set(None).await
        } else if let Some(_matches) = matches.subcommand_matches("create") {
            self.create().await
        } else if let Some(matches) = matches.subcommand_matches("redeem") {
            let voucher = value_t_or_exit!(matches.value_of("voucher"), String);
            self.redeem_voucher(voucher).await
        } else {
            unreachable!("No account command given");
        }
    }
}

impl Account {
    async fn set(&self, token: Option<AccountToken>) -> Result<()> {
        let mut rpc = new_rpc_client().await?;
        rpc.set_account(token.clone().unwrap_or_default()).await?;
        if let Some(token) = token {
            println!("Mullvad account \"{}\" set", token);
        } else {
            println!("Mullvad account removed");
        }
        Ok(())
    }

    async fn get(&self) -> Result<()> {
        let mut rpc = new_rpc_client().await?;
        let settings = rpc.get_settings(()).await?.into_inner();
        if settings.account_token != "" {
            println!("Mullvad account: {}", settings.account_token);
            let expiry = rpc
                .get_account_data(settings.account_token)
                .await
                .map_err(|error| Error::RpcFailedExt("Failed to fetch account data", error))?
                .into_inner();
            println!(
                "Expires at     : {}",
                Self::format_expiry(&expiry.expiry.unwrap())
            );
        } else {
            println!("No account configured");
        }
        Ok(())
    }

    async fn create(&self) -> Result<()> {
        let mut rpc = new_rpc_client().await?;
        rpc.create_new_account(()).await?;
        println!("New account created!");
        self.get().await
    }

    async fn redeem_voucher(&self, mut voucher: String) -> Result<()> {
        let mut rpc = new_rpc_client().await?;
        voucher.retain(|c| c.is_alphanumeric());

        match rpc.submit_voucher(voucher).await {
            Ok(submission) => {
                let submission = submission.into_inner();
                println!(
                    "Added {} to the account",
                    Self::format_duration(submission.seconds_added)
                );
                println!(
                    "New expiry date: {}",
                    Self::format_expiry(&submission.new_expiry.unwrap())
                );
                Ok(())
            }
            Err(err) => {
                match err.code() {
                    Code::NotFound | Code::ResourceExhausted => {
                        eprintln!("Failed to submit voucher: {}", err.message());
                    }
                    _ => return Err(Error::RpcFailed(err)),
                }
                std::process::exit(1);
            }
        }
    }

    fn format_duration(seconds: u64) -> String {
        let dur = chrono::Duration::seconds(seconds as i64);
        if dur.num_days() > 0 {
            format!("{} days", dur.num_days())
        } else if dur.num_hours() > 0 {
            format!("{} hours", dur.num_hours())
        } else if dur.num_minutes() > 0 {
            format!("{} minutes", dur.num_minutes())
        } else {
            format!("{} seconds", dur.num_seconds())
        }
    }

    fn format_expiry(expiry: &Timestamp) -> String {
        let ndt = chrono::NaiveDateTime::from_timestamp(expiry.seconds, expiry.nanos as u32);
        let utc = chrono::DateTime::<chrono::Utc>::from_utc(ndt, chrono::Utc);
        utc.with_timezone(&chrono::Local).to_string()
    }
}