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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#![allow(missing_docs)]
use crate::offtime::{Off, OffDays};
use crate::utils::parse_from_hmstr;
use ::structopt::clap::AppSettings;
use anyhow::{bail, Context, Result};
use chrono::Local;
use directories_next::ProjectDirs;
use figment::{
providers::{Format, Serialized, Toml},
Figment,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use structopt;
use structopt::clap::arg_enum;
use tracing::{debug, info, warn};
arg_enum! {
#[derive(Serialize, Deserialize,Debug)]
pub enum SecretType {
Token,
Password,
}
}
#[derive(Debug, PartialEq)]
pub struct WifiStatusConfig {
pub wifi_string: String,
pub emoji: String,
pub text: String,
}
impl std::str::FromStr for WifiStatusConfig {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let splitted: Vec<&str> = s.split("::").collect();
if splitted.len() != 3 {
bail!(
"Expect status argument to contain two and only two :: separator (in '{}')",
&s
);
}
Ok(WifiStatusConfig {
wifi_string: splitted[0].to_owned(),
emoji: splitted[1].to_owned(),
text: splitted[2].to_owned(),
})
}
}
#[derive(structopt::StructOpt, Debug, Clone)]
pub struct QuietVerbose {
#[structopt(
name = "quietverbose",
long = "verbose",
short = "v",
parse(from_occurrences),
conflicts_with = "quietquiet",
global = true
)]
verbosity_level: u8,
#[structopt(
name = "quietquiet",
long = "quiet",
short = "q",
parse(from_occurrences),
conflicts_with = "quietverbose",
global = true
)]
quiet_level: u8,
}
impl Default for QuietVerbose {
fn default() -> Self {
QuietVerbose {
verbosity_level: 1,
quiet_level: 0,
}
}
}
impl Serialize for QuietVerbose {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.get_level_filter())
}
}
fn de_from_str<'de, D>(deserializer: D) -> Result<QuietVerbose, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.to_ascii_lowercase().as_ref() {
"off" => Ok(QuietVerbose {
verbosity_level: 0,
quiet_level: 2,
}),
"error" => Ok(QuietVerbose {
verbosity_level: 0,
quiet_level: 1,
}),
"warn" => Ok(QuietVerbose {
verbosity_level: 0,
quiet_level: 0,
}),
"info" => Ok(QuietVerbose {
verbosity_level: 1,
quiet_level: 0,
}),
"debug" => Ok(QuietVerbose {
verbosity_level: 2,
quiet_level: 0,
}),
_ => Ok(QuietVerbose {
verbosity_level: 3,
quiet_level: 0,
}),
}
}
impl QuietVerbose {
pub fn get_level_filter(&self) -> &str {
let quiet: i8 = if self.quiet_level > 1 {
2
} else {
self.quiet_level as i8
};
let verbose: i8 = if self.verbosity_level > 2 {
3
} else {
self.verbosity_level as i8
};
match verbose - quiet {
-2 => "Off",
-1 => "Error",
0 => "Warn",
1 => "Info",
2 => "Debug",
_ => "Trace",
}
}
}
#[derive(structopt::StructOpt, Serialize, Deserialize, Debug)]
#[structopt(global_settings(&[AppSettings::ColoredHelp, AppSettings::ColorAuto]))]
pub struct Args {
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(short, long, env, name = "itf_name")]
pub interface_name: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
#[structopt(short, long, name = "wifi_substr::emoji::text")]
pub status: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(short = "u", long, env, name = "url")]
pub mm_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(long, env, name = "username")]
pub mm_user: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(short = "t", long, env, possible_values = &SecretType::variants(), case_insensitive = true)]
pub secret_type: Option<SecretType>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(long, env, name = "token service name")]
pub keyring_service: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(long, env, hide_env_values = true, name = "token")]
pub mm_secret: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(long, env, name = "command")]
pub mm_secret_cmd: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(long, env, parse(from_os_str), name = "cache dir")]
pub state_dir: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(short, long, env, name = "begin hh:mm")]
pub begin: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(short, long, env, name = "end hh:mm")]
pub end: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(long, env, name = "expiry hh:mm")]
pub expires_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[structopt(long, env)]
pub delay: Option<u32>,
#[allow(missing_docs)]
#[structopt(flatten)]
#[serde(deserialize_with = "de_from_str")]
pub verbose: QuietVerbose,
#[structopt(skip)]
pub offdays: OffDays,
}
impl Default for Args {
fn default() -> Args {
let res = Args {
#[cfg(target_os = "linux")]
interface_name: Some("wlan0".into()),
#[cfg(target_os = "windows")]
interface_name: Some("Wireless Network Connection".into()),
#[cfg(target_os = "macos")]
interface_name: Some("en0".into()),
status: ["home::house::working at home".to_string()].to_vec(),
delay: Some(60),
state_dir: Some(
ProjectDirs::from("net", "ams", "automattermostatus")
.expect("Unable to find a project dir")
.cache_dir()
.to_owned(),
),
mm_user: None,
keyring_service: None,
mm_secret: None,
mm_secret_cmd: None,
secret_type: Some(SecretType::Password),
mm_url: Some("https://mattermost.example.com".into()),
verbose: QuietVerbose {
verbosity_level: 1,
quiet_level: 0,
},
expires_at: Some("19:30".to_string()),
begin: Some("8:00".to_string()),
end: Some("19:30".to_string()),
offdays: OffDays::default(),
};
res
}
}
impl Off for Args {
fn is_off_time(&self) -> bool {
self.offdays.is_off_time()
|| if let Some(begin) = parse_from_hmstr(&self.begin) {
Local::now() < begin
} else {
false
}
|| if let Some(end) = parse_from_hmstr(&self.end) {
Local::now() > end
} else {
false
}
}
}
impl Args {
pub fn update_secret_with_keyring(mut self) -> Result<Self> {
if let Some(user) = &self.mm_user {
if let Some(service) = &self.keyring_service {
let keyring = keyring::Keyring::new(service, user);
let secret = keyring.get_password().with_context(|| {
format!("Querying OS keyring (user: {}, service: {})", user, service)
})?;
self.mm_secret = Some(secret);
} else {
warn!("User is defined for keyring lookup but service is not");
info!("Skipping keyring lookup");
}
}
Ok(self)
}
pub fn update_secret_with_command(mut self) -> Result<Args> {
if let Some(command) = &self.mm_secret_cmd {
let params =
shell_words::split(command).context("Splitting mm_token_cmd into shell words")?;
debug!("Running command {}", command);
let output = Command::new(¶ms[0])
.args(¶ms[1..])
.output()
.context(format!("Error when running {}", &command))?;
let secret = String::from_utf8_lossy(&output.stdout);
if secret.len() == 0 {
bail!("command '{}' returns nothing", &command);
}
self.mm_secret = Some(secret.to_string());
}
Ok(self)
}
pub fn merge_config_and_params(&self) -> Result<Args> {
let default_args = Args::default();
debug!("default Args : {:#?}", default_args);
let conf_dir = ProjectDirs::from("net", "ams", "automattermostatus")
.expect("Unable to find a project dir")
.config_dir()
.to_owned();
fs::create_dir_all(&conf_dir)
.with_context(|| format!("Creating conf dir {:?}", &conf_dir))?;
let conf_file = conf_dir.join("automattermostatus.toml");
if !conf_file.exists() {
info!("Write {:?} default config file", &conf_file);
fs::write(&conf_file, toml::to_string(&Args::default())?)
.unwrap_or_else(|_| panic!("Unable to write default config file {:?}", conf_file));
}
let config_args: Args = Figment::from(Toml::file(&conf_file)).extract()?;
debug!("config Args : {:#?}", config_args);
debug!("parameter Args : {:#?}", self);
let res = Figment::from(Serialized::defaults(Args::default()))
.merge(Toml::file(&conf_file))
.merge(Serialized::defaults(self))
.extract()
.context("Merging configuration file and parameters")?;
debug!("Merged config and parameters : {:#?}", res);
Ok(res)
}
}