codic/codic/
app.rs

1use std::path::PathBuf;
2use super::{Config, Error, error::EditConfig, clap_params::*};
3
4/// codicアプリケーション本体
5pub struct App {
6    text: String,
7    config: Config,
8}
9
10
11impl App {
12
13    /// 空のAppを生成
14    pub fn new() -> Self {
15        App {
16            text: String::new(),
17            config: Config::new("", "")
18        }
19    }
20
21
22    /// 引数の文字列からApp生成
23    pub fn from_input(text: &str, token: &str, casing: &str) -> Self {
24        App {
25            text: text.to_string(),
26            config: Config::new(token, casing)
27        }
28    }
29
30
31    /// コンフィグファイルからApp生成
32    /// textは空
33    pub fn from_config_file(path: &PathBuf) -> Result<Self, Error> {
34        let config = Config::from_file(path)?;
35        Ok(App {
36            text: String::new(),
37            config
38        })
39    }
40
41
42    pub fn text_mut(&mut self) -> &mut String {
43        &mut self.text
44    }
45
46
47    /// clap machesを解析し、必要に応じてtext、token、casingを変更する
48    pub async fn take_params(mut self) -> Result<Self, Error> {
49        let matches = get_matches();
50        // subcommand 
51        if let Some(sub) = matches.subcommand_matches("config") {
52            if sub.is_present("make") {
53                return Err(Error::ChosenEditConfig{command: EditConfig::Make});
54            } else if sub.is_present("remove") {
55                return Err(Error::ChosenEditConfig{command: EditConfig::Remove});
56            } else if sub.is_present("show") {
57                return Err(Error::ChosenEditConfig{command: EditConfig::Show});
58            } else if let Some(edit) = sub.subcommand_matches("edit") {
59                let mut token: Option<String> = None;
60                let mut casing: Option<String> = None;
61                if let Some(o) = edit.value_of("config token") {
62                    token = Some(o.to_string());
63                }
64                if edit.is_present("config casing") {
65                    //casing = Some("upper underscore".to_string());
66                    for (i, c) in CONFIG_CASINGS.iter().enumerate() {
67                        if edit.is_present(c) {
68                            casing = Some(CASINGS[i].to_string());
69                        }
70                    }
71                }
72                if token.is_some() || casing.is_some() {
73                    return Err(Error::ChosenEditConfig{command: EditConfig::Edit(token, casing)});
74                }
75            }
76            return Err(Error::ChosenEditConfig{command: EditConfig::None});
77        }
78        // main
79        if let Some(o) = matches.value_of("text") {
80            self.text = o.to_string();
81        }
82        // casing
83        for c in &CASINGS {
84            if matches.is_present(c) {
85                *self.config.casing_mut() = c.to_string();
86            }
87        }
88        Ok(self)
89    }
90
91
92    /// アプリケーションを実行する
93    /// # return
94    /// Ok(String): 翻訳された文字列
95    /// Err(codic::Error): サブコマンド選択、または実行時エラーの情報
96    pub async fn run(&self) -> Result<String, Error> {
97        let url = format!("https://api.codic.jp/v1/engine/translate.json?text={}&casing={}",
98                            self.text, self.config.casing());
99        let header = format!("Bearer {}", self.config.token());
100        let json: serde_json::Value = reqwest::Client::new()
101            .get(&url)
102            .header(reqwest::header::AUTHORIZATION, &header)
103            .send().await?
104            .json().await?;
105        if let Some(errors) = json.get("errors") {
106            return Err(Error::CodicError(
107                errors[0]["message"].to_string()
108                .trim_matches('\"').to_string()
109            ));
110        } else if let Some(_) = json[0].get("successful") {
111            return Ok(
112                json[0]["translated_text"].to_string()
113                .trim_matches('\"').to_string()
114            );
115        }
116        Err(Error::CodicError("その他のエラー".to_string()))
117    }
118
119
120}
121