boomack-cli 0.2.1

CLI client for Boomack
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use std::path::{Path, PathBuf};
use std::process::exit;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::{sleep, spawn};
use std::time::{Duration, SystemTime};
use clap::{Args, ArgGroup};
use http_types::url::Url;
use http_types::mime::Mime;
use http_types::headers::{HeaderValues, ToHeaderValues};
use serde::Serialize;
use notify::{Watcher, RecommendedWatcher, RecursiveMode, EventKind};
use boomack::client::api::ClientRequest;
use boomack::client::json::*;
use boomack::client::display::{
    DisplayParameters,
    display_text_request,
    display_url_request,
    display_file_request,
    display_stdin_request,
};
use super::structs::*;
use super::{
    CliConfig,
    parse_location,
    file_url, has_local_host,
    source_auto_content_uf,
    run_request,
};

#[derive(Args, Serialize)]
#[clap(group(ArgGroup::new("input").args(&["text-input", "url-input", "file-input"])))]
pub struct DisplaySubCommandArguments {

    #[clap(short = 'l', long = "location",
           help = "Panel and slot: E. g. 'my-panel/slot-a'")]
    pub location: Option<String>,

    #[clap(help = "Auto content: URL, filename, or text")]
    pub auto_content: Option<String>,

    #[clap(id = "text-input", short = 's', long = "string",
           help = "Text content")]
    pub text_input: Option<String>,

    #[clap(id = "url-input", short = 'u', long = "url",
           help = "URL content")]
    pub url_input: Option<String>,

    #[clap(id = "file-input", short = 'f', long = "file", value_name = "PATH",
           help = "File content")]
    pub file_input: Option<String>,

    #[clap(long = "no-file-url",
           help = "Prevents passing a file:// URL in case a file is displayed and the server is localhost",
           takes_value = false)]
    pub no_file_url: bool,

    #[clap(id = "watch", short = 'w', long = "watch",
           help = "Watch the file and display content on change",
           requires = "file-input",
           takes_value = false)]
    pub watch: bool,

    #[clap(short = 't', long = "type", value_name = "MIME_TYPE",
           help = "MIME type of the content")]
    pub content_type: Option<String>,

    #[clap(short = 'x', long = "extend", value_name = "POSITION",
           help = "Position where to add to existing content in the target slot",
           possible_values = ["start", "end"])]
    pub extend: Option<String>,

    #[clap(long = "prepend",
           help = "Same as --extend start",
           takes_value = false)]
    pub prepend: bool,

    #[clap(long = "append",
           help = "Same as --extend end",
           takes_value = false)]
    pub append: bool,

    #[clap(short = 'c', long ="cache", value_name = "MODE",
           help = "Specifies the intended caching on the server",
           possible_values = ["auto", "memory", "file"])]
    pub cache: Option<String>,

    #[clap(short = 'e', long = "embed",
           help = "A switch to state the intention, \
                   that the media content should be embedded \
                   into the HTML and not referenced as a resource",
           takes_value = false)]
    pub embed : bool,

    #[clap(short = 'p', long = "presets", value_name = "PRESET",
           help = "One or more IDs of presets to apply",
           takes_value = true, multiple_values = true, multiple_occurrences = true)]
    pub presets: Vec<String>,

    #[clap(short = 'o', long = "options", value_name="OPTION",
           help = "Options as key=value pair(s) or as a YAML map",
           takes_value = true, multiple_values = true, multiple_occurrences = true)]
    pub options: Vec<String>,

    // #[clap(short = 'r', long = "raw",
    //        help = "Send content directly as JSON request. Ignores all options but --string and --file.",
    //        takes_value = false)]
    // pub raw: bool,

    #[clap(long = "debug",
           help = "Display debug information instead of the actual media item",
           takes_value = false)]
    pub debug: bool,
}

impl DisplaySubCommandArguments {
    pub fn get_display_command(&self) -> DisplayCommand {
        DisplayCommand {
            location: self.location.as_deref(),
            auto_content: self.auto_content.as_deref(),
            text_input: self.text_input.as_deref(),
            url_input: self.url_input.as_deref(),
            file_input: self.file_input.as_deref(),
            no_file_url: self.no_file_url,
            watch: self.watch,
            content_type: self.content_type.as_deref(),
            extend: self.extend.as_deref(),
            prepend: self.prepend,
            append: self.append,
            cache: self.cache.as_deref(),
            embed: self.embed,
            presets: self.presets.iter().map(|x| x.as_ref()).collect(),
            options: self.options.iter().map(|x| x.as_ref()).collect(),
            debug: self.debug,
        }
    }
}

pub struct DisplayCommand<'l> {
    pub location: Option<&'l str>,
    pub auto_content: Option<&'l str>,
    pub text_input: Option<&'l str>,
    pub url_input: Option<&'l str>,
    pub file_input: Option<&'l str>,
    pub no_file_url: bool,
    pub watch: bool,
    pub content_type: Option<&'l str>,
    pub extend: Option<&'l str>,
    pub prepend: bool,
    pub append: bool,
    pub cache: Option<&'l str>,
    pub embed : bool,
    pub presets: Vec<&'l str>,
    pub options: Vec<&'l str>,
    // pub raw: bool,
    pub debug: bool,
}

impl<'l> DisplayCommand<'l> {

    fn parse_options(&self, stdin_consumed: &mut bool) -> JsonMap {
        let option_layers = self.options.clone().into_iter()
            .map(|o| parse_structure(&o, true, stdin_consumed, parse_kvp_lines));
        merge_layers(option_layers)
    }

    fn apply_known_options(&self, options: &mut JsonMap) {
        if let Some(cache) = self.cache {
            set_json_str_value(options, "cache", cache);
        }
        if self.embed {
            set_json_bool_value(options, "embed", true);
        }

        let extend = if let Some(extend) = self.extend {
            Some(extend)
        } else if self.append {
            Some("end")
        } else if self.prepend {
            Some("start")
        } else {
            None
        };
        if let Some(extend) = extend {
            set_json_str_value(options, "extend", extend);
        }

        if self.debug {
            set_json_bool_value(options, "debug", true);
        }
    }

    pub fn build_options(&self, stdin_consumed: &mut bool) -> JsonMap {
        let mut options = self.parse_options(stdin_consumed);
        self.apply_known_options(&mut options);
        options
    }

    pub fn to_parameters(&'l self, options: JsonMap, default_content_type: Option<&'l str>) -> DisplayParameters<'l> {
        let (panel, slot) = parse_location(self.location.as_deref());
        DisplayParameters {
            panel,
            slot,
            content_type: self.content_type.or(default_content_type),
            presets: self.presets.clone(),
            options,
        }
    }
}

fn mime_from_extension(ext: &str) -> Option<Mime> {
    let ext_low = ext.to_lowercase();
    match ext_low.as_ref() {
        // text types
        "txt" => Some(Mime::from("text/plain")),
        "htm" | "html" => Some(Mime::from("text/html")),
        "md" => Some(Mime::from("text/markdown")),

        // data types
        "xml" | "xsd" | "xslt" => Some(Mime::from("text/xml")),
        "json" => Some(Mime::from("application/json")),
        "yaml" | "yml" => Some(Mime::from("application/yaml")),

        // programming languages
        "css" => Some(Mime::from("text/css")),
        "js" | "jsm" => Some(Mime::from("application/javascript")),
        "ts" => Some(Mime::from("application/typescript")),

        // image types
        "png" => Some(Mime::from("image/png")),
        "jpg" | "jpeg" => Some(Mime::from("image/jpeg")),
        "gif" => Some(Mime::from("image/gif")),
        "svg" => Some(Mime::from("image/svg+xml")),
        _ => None
    }
}

fn derive_content_type_from_filename(filename: &str) -> Option<String> {
    Path::new(filename).extension()
        .and_then(|file_ext| mime_from_extension(&file_ext.to_string_lossy()))
        .map(|mime| String::from(HeaderValues::from_iter(mime.to_header_values().unwrap()).as_str()))
}

fn content_type_for_filename(cfg: &CliConfig, cmd: &DisplayCommand, filename: &str) -> Option<String> {
    match cmd.content_type {
        Some(content_type) => Some(content_type.into()),
        None => {
            let content_type = derive_content_type_from_filename(filename);
            if let Some(mime) = &content_type {
                trace!(cfg, "MIME type from file extension: {}", mime);
            }
            content_type
        }
    }
}

fn derive_content_type_from_url(url: &str) -> Option<String> {
    Url::parse(url).ok().and_then(|url| {
        url.path().split('.').last()
            .and_then(|path_ext| mime_from_extension(path_ext))
            .map(|mime| String::from(HeaderValues::from_iter(mime.to_header_values().unwrap()).as_str()))
    })
}

fn content_type_for_url(cfg: &CliConfig, cmd: &DisplayCommand, url: &str) -> Option<String> {
    match cmd.content_type {
        Some(content_type) => Some(content_type.into()),
        None => {
            let content_type = derive_content_type_from_url(url);
            if let Some(mime) = &content_type {
                trace!(cfg, "MIME type from file extension in URL path: {}", mime);
            }
            content_type
        },
    }
}

pub fn dispatch_display_command(cfg: &CliConfig, cmd: &DisplayCommand) -> i32 {
    let mut text_arg: Option<&str> = cmd.text_input.as_deref();
    let mut url_arg: Option<&str> = cmd.url_input.as_deref();
    let mut file_arg: Option<&str> = cmd.file_input.as_deref();

    if text_arg.is_none() && url_arg.is_none() && file_arg.is_none() {
        source_auto_content_uf(cmd.auto_content, &mut text_arg, &mut url_arg, &mut file_arg);
    }

    if let Some(file_input) = file_arg {
        if file_input == "-" {
            file_arg = Option::None;
        }
    }

    let mut stdin_consumed = false;
    let options = cmd.build_options(&mut stdin_consumed);

    if cfg.is_verbose() {
        trace!(cfg, "DISPLAY OPTIONS: {}", pprint_json(&options));
    }

    let mut file_path: String = String::from("");

    let request = if let Some(text_input) = text_arg {
        let params = cmd.to_parameters(options, Some("text/plain"));
        trace!(cfg, "Text request");
        display_text_request(&params, text_input)
    } else if let Some(file_input) = file_arg {
        file_path = file_input.to_string();
        let content_type = content_type_for_filename(cfg, cmd, file_input);
        let params = cmd.to_parameters(options, content_type.as_deref());
        if !cmd.no_file_url && has_local_host(&cfg.api.server.get_api_url()) {
            let file_url = file_url(file_input);
            trace!(cfg, "File request as file URL: {}", file_url);
            display_url_request(&params, &file_url)
        } else {
            trace!(cfg, "File request as stream: {}", file_input);
            display_file_request(&params, file_input)
        }
    } else if let Some(url_input) = url_arg {
        if let Ok(url) = Url::from_str(url_input) {
            if url.scheme() != "http" &&
                    url.scheme() != "http" &&
                    url.scheme() != "file" {
                eprintln!("Invalid protocol in URL. Allowed: http, https, file.");
                exit(1);
            }
        } else {
            eprintln!("Invalid URL: {}", url_input);
            exit(1)
        }
        let content_type = content_type_for_url(cfg, cmd, url_input);
        let params = cmd.to_parameters(options, content_type.as_deref());
        trace!(cfg, "URL request: {}", url_input);
        display_url_request(&params, url_input)
    } else {
        let params = cmd.to_parameters(options, Some("application/octet-stream"));
        trace!(cfg, "Trying to read from STDIN");
        if stdin_consumed {
            eprintln!("Can not read display content from STDIN, because STDIN was already consumed by options!");
            exit(1);
        }
        display_stdin_request(&params)
    };

    fn equal_path(a: &PathBuf, b: &PathBuf) -> bool {
        if let Ok(a) = a.canonicalize() {
            if let Ok(b) = b.canonicalize() {
                return a == b;
            }
        }
        false
    }

    if cmd.watch { if let Some(file_input) = file_arg {

        // post the request at least one time
        let first_result = run_request(cfg, request.clone());
        if first_result != 0 {
            return first_result;
        }

        // prepare local copies for the moving event handling closure
        let local_cfg = cfg.clone();
        let test_path = PathBuf::from_str(&file_path).unwrap();
        let busy = Arc::new(AtomicBool::new(false));
        let skipped = Arc::new(AtomicBool::new(false));
        let t = Arc::new(Mutex::new(SystemTime::now()));

        let mut watcher = Box::new(
            RecommendedWatcher::new(
                // event handling closure
                move |res: Result<notify::Event, notify::Error>| {
                    // check if event is valid
                    if let Ok(event) = res {
                        // check if event describes a create/modify on the target file
                        if (matches!(event.kind, EventKind::Create(_) | EventKind::Modify(_)))
                            && event.paths.iter().any(|p| equal_path(p, &test_path))
                        {
                            // debounce event with 100ms
                            let ct = SystemTime::now();
                            {
                                let mut t = t.lock().unwrap();
                                if ct.duration_since(*t).unwrap() < Duration::from_millis(100) {
                                    return;
                                }
                                *t = ct;
                            }

                            trace!(&local_cfg, "File was {}", match event.kind {
                                EventKind::Create(_) => "created",
                                EventKind::Modify(_) => "modified",
                                _ => "<unexpected event>",
                            });

                            // create a context with copies of the relevant data for a new thread
                            let worker = DisplayWorkerContext::new(
                                local_cfg.clone(), request.clone(),
                                busy.clone(), skipped.clone()
                            );
                            // spawn a new thread to post the display request
                            worker.spawn();
                        }
                    }
                },
                notify::Config::default())
                .unwrap());

        // add the parent directory of the target file to the watcher
        let file_path = Path::new(file_input);
        let dir_path = file_path.parent()
            .expect("Can not watch file without parent directory");
        watcher.watch(dir_path, RecursiveMode::NonRecursive).unwrap();
        println!("Watching...");

        loop { sleep(Duration::from_millis(100)); }
        // return 0;
    } }
    run_request(cfg, request)
}

#[derive(Clone)]
struct DisplayWorkerContext {
    pub cfg: CliConfig,
    pub busy: Arc<AtomicBool>,
    pub skipped: Arc<AtomicBool>,
    pub request: ClientRequest,
}

impl DisplayWorkerContext {
    pub fn new(cfg: CliConfig, request: ClientRequest, busy: Arc<AtomicBool>, skipped: Arc<AtomicBool>) -> DisplayWorkerContext {
        DisplayWorkerContext {
            cfg,
            request,
            busy,
            skipped,
        }
    }

    fn run(&self) {
        // check if another thread is already busy posting the request
        // if not, acquire the busy lock
        if matches!(self.busy.compare_exchange(false, true, Ordering::Acquire, Ordering::Acquire),
                Err(_)) {
            // if yes, set a marker for the skipped change
            self.skipped.store(true, Ordering::Relaxed);
            return;
        }

        // post the request
        trace!(&self.cfg, "Sending request after filesystem event");
        run_request(&self.cfg, self.request.clone());

        // release the busy lock
        self.busy.store(false, Ordering::Release);

        // check if a change was skipped
        // if yes, reset the skipped mark and respawn in a new thread
        if matches!(self.skipped.compare_exchange(true, false, Ordering::Release, Ordering::Relaxed),
                Ok(_)) {
            self.spawn();
        }
    }

    pub fn spawn(&self) {
        // clone the worker context for the new thread
        let local_ctx = self.clone();
        // and move it into the thread closure
        spawn(move || local_ctx.run());
    }
}