1use std::path::PathBuf;
2use super::{Config, Error, error::EditConfig, clap_params::*};
3
4pub struct App {
6 text: String,
7 config: Config,
8}
9
10
11impl App {
12
13 pub fn new() -> Self {
15 App {
16 text: String::new(),
17 config: Config::new("", "")
18 }
19 }
20
21
22 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 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 pub async fn take_params(mut self) -> Result<Self, Error> {
49 let matches = get_matches();
50 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 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 if let Some(o) = matches.value_of("text") {
80 self.text = o.to_string();
81 }
82 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 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