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
pub mod error;
pub mod output;
mod tests;
use chrono::{prelude::*, Duration};
use error::Error;

use std::process::Stdio;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;

pub type Result<T> = std::result::Result<T, Error>;

//OpCLI have expiration_time field what is the token's expiration time.
//Intent to implement some method to auto renew the token. //TODO
#[derive(Clone)]
pub struct OpCLI {
    expiration_time: DateTime<Utc>,
    session: String,
}

impl OpCLI {
    pub async fn new_with_pass(username: &str, password: &str) -> Result<Self> {
        let mut child = Command::new("op")
            .arg("signin")
            .arg(username)
            .arg("--raw")
            .stdin(Stdio::piped())
            .stderr(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()?;
        let stdin = child.stdin.as_mut().unwrap();
        stdin.write_all(password.as_bytes()).await?;
        let output = child.wait_with_output().await?;
        handle_op_signin_error(String::from_utf8_lossy(&output.stderr).to_string()).await?;
        let expiration_time = Utc::now() + Duration::minutes(29);
        Ok(Self {
            expiration_time,
            session: String::from_utf8_lossy(&output.stdout).to_string(),
        })
    }

    pub fn get(&self) -> GetCmd {
        GetCmd {
            cmd: "get".to_string(),
            session: self.session.to_string(),
        }
    }

    pub fn create(&self) -> CreateCmd {
        CreateCmd {
            cmd: "create".to_string(),
            session: self.session.to_string(),
        }
    }

    pub fn list(&self) -> ListCmd {
        ListCmd {
            cmd: "list".to_string(),
            session: self.session.to_string(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct GetCmd {
    cmd: String,
    session: String,
}

impl sealed::FirstCmd for GetCmd {
    #[doc(hidden)]
    fn cmd(&self) -> &str {
        &self.cmd
    }
    #[doc(hidden)]
    fn session(&self) -> &str {
        &self.session
    }
}

//this macro repeat codes above. to create a first cmd then
//implement FirstCmd trait for it.
macro_rules! its_first_cmd {
    ($first_cmd:ident) => {
        #[derive(Debug, Clone)]
        pub struct $first_cmd {
            cmd: String,
            session: String,
        }

        impl sealed::FirstCmd for $first_cmd {
            #[doc(hidden)]
            fn cmd(&self) -> &str {
                &self.cmd
            }
            #[doc(hidden)]
            fn session(&self) -> &str {
                &self.session
            }
        }
    };
}

its_first_cmd!(CreateCmd);
its_first_cmd!(ListCmd);

//Maybe I can generic on some of second cmd's method, they seems like do same thing.
//TODO
impl GetCmd {
    pub fn account(&self) -> AccountCmd {
        let flags: Vec<String> = Vec::new();
        AccountCmd {
            first: self.clone(),
            cmd: "account".to_string(),
            flags,
        }
    }

    ///this method return items' fields of website,username,password
    pub fn item_lite(&self, item_name: &str) -> ItemLiteCmd {
        let flags: Vec<String> = vec![
            item_name.to_string(),
            "--fields".to_string(),
            "website,username,password".to_string(),
        ];
        ItemLiteCmd {
            first: self.clone(),
            cmd: "item".to_string(),
            flags,
        }
    }

    pub fn item(&self, item_name: &str) -> GetItemCmd {
        let flags: Vec<String> = vec![item_name.to_string()];
        GetItemCmd {
            first: self.clone(),
            cmd: "item".to_string(),
            flags,
        }
    }

    pub fn document(&self, document_name: &str) -> GetDocumentCmd {
        let flags: Vec<String> = vec![document_name.to_string()];
        GetDocumentCmd {
            first: self.clone(),
            cmd: "document".to_string(),
            flags,
        }
    }

    pub fn totp(&self, item_name: &str) -> GetTotpCmd {
        let flags: Vec<String> = vec![item_name.to_string()];

        GetTotpCmd {
            first: self.clone(),
            cmd: "totp".to_string(),
            flags,
        }
    }
}
impl CreateCmd {
    pub fn document(&self, path: &str) -> CreateDocumentCmd {
        let flags: Vec<String> = vec![path.to_string()];
        CreateDocumentCmd {
            first: self.clone(),
            cmd: "document".to_string(),
            flags,
        }
    }
}

impl ListCmd {
    pub fn documents(&self) -> ListDocumentsCmd {
        let flags: Vec<String> = Vec::new();
        ListDocumentsCmd {
            first: self.clone(),
            cmd: "documents".to_string(),
            flags,
        }
    }

    pub fn items(&self) -> ListItemsCmd {
        let flags: Vec<String> = Vec::new();
        ListItemsCmd {
            first: self.clone(),
            cmd: "items".to_string(),
            flags,
        }
    }
}

use crate::sealed::{FirstCmd, SecondCmd};

#[async_trait::async_trait]
pub trait SecondCmdExt: SecondCmd {
    fn add_flag(&mut self, flags: &[&str]) -> &Self {
        for flag in flags {
            if !self.flags().contains(&flag.to_string()) {
                self.flags().push(flag.to_string())
            }
        }
        self
    }

    async fn run(&self) -> Result<Self::Output> {
        let mut args: Vec<String> = vec![
            self.first().cmd().to_string(),
            self.cmd().to_string(),
            "--session".to_string(),
            self.first().session().trim().to_string(),
        ];
        if !self.flags().is_empty() {
            self.flags()
                .into_iter()
                .for_each(|flag| args.push(flag.to_string()))
        }
        let out_str: &str = &exec_command(args).await?;
        Ok(serde_json::from_str(out_str)?)
    }
}

impl<T: SecondCmd> SecondCmdExt for T {}

#[derive(Debug)]
pub struct AccountCmd {
    first: GetCmd,
    cmd: String,
    flags: Vec<String>,
}

#[async_trait::async_trait]
impl SecondCmd for AccountCmd {
    type Output = output::Account;
    type First = GetCmd;

    #[doc(hidden)]
    fn first(&self) -> &GetCmd {
        &self.first
    }

    #[doc(hidden)]
    fn cmd(&self) -> &str {
        &self.cmd
    }

    #[doc(hidden)]
    fn flags(&self) -> Vec<String> {
        self.flags.clone()
    }
}

//This macro repeat above codes. To create a new second cmd struct
//and implement SecondCmd trait for it.
macro_rules! its_second_cmd {
    ($first_cmd:ident,$second_cmd:ident,$output:ident) => {
        #[derive(Debug)]
        pub struct $second_cmd {
            first: $first_cmd,
            cmd: String,
            flags: Vec<String>,
        }

        #[async_trait::async_trait]
        impl SecondCmd for $second_cmd {
            type Output = output::$output;
            type First = $first_cmd;
            #[doc(hidden)]
            fn first(&self) -> &$first_cmd {
                &self.first
            }
            #[doc(hidden)]
            fn cmd(&self) -> &str {
                &self.cmd
            }
            #[doc(hidden)]
            fn flags(&self) -> Vec<String> {
                self.flags.clone()
            }
        }
    };
}

its_second_cmd!(GetCmd, ItemLiteCmd, ItemLite);
its_second_cmd!(GetCmd, GetDocumentCmd, Value);
its_second_cmd!(GetCmd, GetTotpCmd, Value);
its_second_cmd!(GetCmd, GetItemCmd, GetItem);
its_second_cmd!(CreateCmd, CreateDocumentCmd, CreateDocument);
its_second_cmd!(ListCmd, ListDocumentsCmd, ListDocuments);
its_second_cmd!(ListCmd, ListItemsCmd, ListItems);

#[inline]
async fn exec_command(args: Vec<String>) -> Result<String> {
    let child = Command::new("op")
        .args(args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let output = child.wait_with_output().await?;
    handle_op_exec_error(String::from_utf8_lossy(&output.stderr).to_string()).await?;
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

#[inline]
async fn handle_op_signin_error(std_err: String) -> std::result::Result<(), Error> {
    if std_err.contains("401") {
        return Err(Error::OPSignInError("wrong password".to_string()));
    }
    Ok(())
}

#[inline]
async fn handle_op_exec_error(std_err: String) -> std::result::Result<(), Error> {
    if std_err.contains("doesn't seem to be an item") {
        return Err(Error::ItemQueryError("Item not founded".to_string()));
    } else if std_err.trim().contains("Invalid session token") {
        return Err(Error::ItemQueryError("In valid session token".to_string()));
    } else if std_err.trim().contains("More than one item matches") {
        return Err(Error::ItemQueryError(
            "More than one item matches".to_string(),
        ));
    }
    Ok(())
}

//why I need this: because SecondCmdExt need explicit scope in.
//So use this to impl a casting method for the struct who
//implemented SecondCmdExt. now used do not need `use crate::SecondCmdExt`
macro_rules! impl_casting_method {
    ($($ObjName:ident),* $(,)?) => {
        $(
            impl $ObjName {

                pub async fn run(&self) -> Result<<Self as SecondCmd>::Output> {
                    <Self as SecondCmdExt>::run(self).await
                }

                pub fn add_flag(&mut self, flags: &[&str]) -> &Self {
                    <Self as SecondCmdExt>::add_flag(self, flags)
                }
            }
        )*
    };
}

impl_casting_method!(
    ItemLiteCmd,
    GetDocumentCmd,
    GetTotpCmd,
    GetItemCmd,
    CreateDocumentCmd,
    ListDocumentsCmd,
    ListItemsCmd,
    AccountCmd
);

mod sealed {
    use serde::de::DeserializeOwned;

    pub trait FirstCmd {
        #[doc(hidden)]
        fn cmd(&self) -> &str;
        #[doc(hidden)]
        fn session(&self) -> &str;
    }

    #[async_trait::async_trait]
    pub trait SecondCmd {
        type Output: DeserializeOwned;
        type First: FirstCmd + Clone;

        #[doc(hidden)]
        fn first(&self) -> &Self::First;
        #[doc(hidden)]
        fn cmd(&self) -> &str;
        #[doc(hidden)]
        fn flags(&self) -> Vec<String>;
    }
}