e_imzo/lib.rs
1#![allow(clippy::never_loop)]
2#![allow(clippy::result_large_err)]
3
4pub mod client;
5pub mod error;
6pub mod prelude;
7
8// Public re-exports
9pub use error::{EIMZOError as Error, Result};
10
11use chrono::{Local, NaiveDateTime};
12use client::{Client, Connected, Disconnected};
13use locale_rs::Locale;
14use prelude::*;
15use serde_json::json;
16use std::str::FromStr;
17use tungstenite::Message;
18
19pub struct EIMZO<State> {
20 client: Client<State>,
21}
22
23impl EIMZO<Disconnected> {
24 pub fn new() -> Result<EIMZO<Connected>> {
25 Ok(EIMZO {
26 client: Client::connect::<String>(None)?,
27 })
28 }
29}
30
31impl EIMZO<Connected> {
32 /// Информацио о версии JVM
33 /// doc: https://127.0.0.1:64443/apidoc.html#app.show_menu
34 ///
35 ///```
36 /// let mut eimzo = EIMZO::new().unwrap();
37 /// match eimzo.show_menu() {
38 /// Ok(res) => println!("show_menu: {res:#?}"),
39 /// Err(e) => println!("{e}"),
40 ///}
41 ///```
42 pub fn show_menu(&mut self) -> Result<(), error::EIMZOError> {
43 let cmd: serde_json::Value = json!({
44 "plugin" :"app",
45 "name" :"show_menu",
46 });
47
48 self.client
49 .send_and_wait(Message::Text(cmd.to_string().into()))?;
50
51 Ok(())
52 }
53 /// Информацио о версии JVM
54 /// doc: https://127.0.0.1:64443/apidoc.html#app.get_jvm_version
55 ///
56 ///```
57 /// let mut eimzo = EIMZO::new().unwrap();
58 /// match eimzo.get_jvm_version() {
59 /// Ok(res) => println!("get_jvm_version: {res:#?}"),
60 /// Err(e) => println!("{e}"),
61 ///}
62 ///```
63 pub fn get_jvm_version(&mut self) -> Result<String, error::EIMZOError> {
64 let cmd: serde_json::Value = json!({
65 "plugin" :"app",
66 "name" :"get_jvm_version",
67 });
68
69 let response = self
70 .client
71 .send_and_wait(Message::Text(cmd.to_string().into()))?;
72
73 let msg = match response {
74 Message::Text(msg) => msg,
75 _ => todo!(), // pattern matching handled on send_and_wait so do something with this
76 };
77
78 let version = serde_json::from_str::<GenericTextMessage>(&msg)?;
79 Ok(version.message)
80 }
81
82 /// Изменить язык интерфейса (не сохраняя в настройках)
83 /// doc: https://127.0.0.1:64443/apidoc.html#app.change_ui_lang
84 ///
85 ///```
86 /// let mut eimzo = EIMZO::new().unwrap();
87 /// eimzo.change_ui_lang("uz")
88 ///```
89 pub fn change_ui_lang<T>(&mut self, lang: T) -> Result<(), error::EIMZOError>
90 where
91 T: AsRef<str> + serde::Serialize,
92 {
93 let locale = Locale::from_str(lang.as_ref())?;
94
95 let cmd: serde_json::Value = json!({
96 "plugin" :"app",
97 "name" :"change_ui_lang",
98 "arguments": [
99 locale.as_str()
100 ],
101 });
102
103 self.client
104 .send_and_wait(Message::Text(cmd.to_string().into()))?;
105
106 Ok(())
107 }
108
109 /// Получить список всех сертификатов пользователя
110 /// doc: https://127.0.0.1:64443/apidoc.html#pfx.list_all_certificates
111 ///
112 /// ```
113 /// let mut eimzo = EIMZO::new()?;
114 /// match eimzo.list_all_certificates() {
115 /// Ok(pfx) => {
116 /// let a: Vec<_> = pfx.iter().map(|c| (c, c.get_alias())).collect();
117 /// println!("this is resut list_all_certificates; {a:?}");
118 /// pfx.iter().map(|c| (c, c.get_alias())).for_each(|(c, a)| {
119 /// let validfrom: Vec<_> = a.get("validfrom").unwrap().split(" ").collect();
120 /// let mut year_month_day: Vec<_> = validfrom[0].split(".").collect();
121 /// year_month_day.reverse();
122 ///
123 /// println!("CERT: {c:#?}");
124 /// println!("ALIAS: {a:#?}");
125 /// println!("-----");
126 /// println!("DATE: {:#?}", year_month_day.join("."));
127 /// });
128 /// }
129 /// Err(e) => println!("{e}"),
130 /// }
131 ///```
132 pub fn list_all_certificates(&mut self) -> Result<Vec<Certificate>, error::EIMZOError> {
133 let cmd: serde_json::Value = json!({
134 "plugin": "pfx",
135 "name": "list_all_certificates",
136 });
137
138 let response = self
139 .client
140 .send_and_wait(Message::Text(cmd.to_string().into()))?;
141
142 let msg = match response {
143 Message::Text(msg) => msg,
144 _ => todo!(), // pattern matching handled on send_and_wait so do something with this
145 };
146
147 let certs = serde_json::from_str::<ListAllCertificatesResponse>(&msg)
148 .unwrap_or_default()
149 .certificates
150 .into_iter()
151 .map(|mut x| {
152 let _a = x.get_alias();
153
154 x.valid_from = Some(
155 NaiveDateTime::parse_from_str(
156 _a.get("validfrom").unwrap(),
157 "%Y.%m.%d %H:%M:%S",
158 )
159 .unwrap_or_default(),
160 );
161
162 x.valid_to = Some(
163 NaiveDateTime::parse_from_str(_a.get("validto").unwrap(), "%Y.%m.%d %H:%M:%S")
164 .unwrap_or_default(),
165 );
166
167 let now = Local::now().naive_local();
168 x.is_expired =
169 Some(now.signed_duration_since(x.valid_to.unwrap()).num_seconds() > 0);
170
171 x
172 })
173 .collect();
174
175 Ok(certs)
176 }
177}