-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcli.rs
More file actions
1270 lines (1166 loc) · 45.7 KB
/
cli.rs
File metadata and controls
1270 lines (1166 loc) · 45.7 KB
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::io::{Read, Write};
use std::path::PathBuf;
use std::{env, fs, io};
use clap::{Parser, Subcommand};
use http_auth_basic::Credentials;
use log::{error, info};
use reqwest::StatusCode;
use rpassword::read_password;
use thiserror::Error;
use crate::authentication::{verify_and_store_token, Authentication, AuthenticationError, Config};
use crate::commands;
use crate::commands::edge_app::instance_manifest::InstanceManifest;
use crate::commands::edge_app::manifest::EdgeAppManifest;
use crate::commands::edge_app::server::MOCK_DATA_FILENAME;
use crate::commands::edge_app::utils::{
transform_edge_app_path_to_manifest, transform_instance_path_to_instance_manifest,
validate_manifests_dependacies,
};
use crate::commands::playlist::PlaylistCommand;
use crate::commands::{CommandError, Formatter, OutputType, PlaylistFile};
const DEFAULT_ASSET_DURATION: u32 = 15;
/// Returns a user-friendly error message for authentication errors.
fn get_authentication_error_message(e: &AuthenticationError) -> String {
match e {
AuthenticationError::Io(io_err) if io_err.kind() == std::io::ErrorKind::NotFound => {
"Not logged in. Please run `screenly login` first to authenticate.".to_string()
}
_ => {
format!("Authentication error: {e}. Please run `screenly login` to authenticate.")
}
}
}
/// Creates an Authentication instance or exits with a user-friendly error message.
fn get_authentication() -> Authentication {
match Authentication::new() {
Ok(auth) => auth,
Err(e) => {
error!("{}", get_authentication_error_message(&e));
std::process::exit(1);
}
}
}
#[derive(Error, Debug)]
enum ParseError {
#[error("missing \"=\" symbol")]
MissingSymbol(),
}
fn parse_key_val(s: &str) -> Result<(String, String), ParseError> {
let pos = s.find('=').ok_or(ParseError::MissingSymbol())?;
Ok((s[..pos].to_string(), s[pos + 1..].to_string()))
}
#[derive(Parser)]
#[command(
version,
about,
long_about = "Command line interface is intended for quick interaction with Screenly through terminal. Moreover, this CLI is built such that it can be used for automating tasks."
)]
#[command(propagate_version = true)]
pub struct Cli {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
#[command(subcommand)]
pub(crate) command: Commands,
}
#[derive(Subcommand)]
pub enum Commands {
/// Logins with the token and stores it for further use if it's valid. You can set API_TOKEN environment variable to override used API token.
Login {},
/// Logouts and removes stored token.
Logout {},
/// Screen related commands.
#[command(subcommand)]
Screen(ScreenCommands),
/// Asset related commands.
#[command(subcommand)]
Asset(AssetCommands),
/// Playlist related commands.
#[command(subcommand)]
Playlist(PlaylistCommands),
/// Edge App related commands.
#[command(subcommand)]
EdgeApp(EdgeAppCommands),
/// For generating `docs/CommandLineHelp.md`.
#[clap(hide = true)]
PrintHelpMarkdown {},
}
#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ScreenCommands {
/// Lists your screens.
List {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
},
/// Gets a single screen by id.
Get {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
/// UUID of the screen.
uuid: String,
},
/// Adds a new screen.
Add {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
/// Pin code created with registrations endpoint.
pin: String,
/// Optional name of the new screen.
name: Option<String>,
},
/// Deletes a screen. This cannot be undone.
Delete {
/// UUID of the screen to be deleted.
uuid: String,
},
}
#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum PlaylistCommands {
///Creates a new playlist.
Create {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
/// Title of the new playlist.
title: String,
/// Predicate for the new playlist. If not specified it will be set to "TRUE".
predicate: Option<String>,
},
/// Lists your playlists.
List {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
},
/// Gets a single playlist by id.
Get {
/// UUID of the playlist.
uuid: String,
},
/// Deletes a playlist. This cannot be undone.
Delete {
/// UUID of the playlist to be deleted.
uuid: String,
},
/// Adds an asset to the end of the playlist.
Append {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
/// UUID of the playlist.
uuid: String,
/// UUID of the asset.
asset_uuid: String,
/// Duration of the playlist item in seconds. If not specified it will be set to 15 seconds.
duration: Option<u32>,
},
/// Adds an asset to the beginning of the playlist.
Prepend {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
/// UUID of the playlist.
uuid: String,
/// UUID of the asset.
asset_uuid: String,
/// Duration of the playlist item in seconds. If not specified it will be set to 15 seconds.
duration: Option<u32>,
},
/// Patches a given playlist.
Update {},
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Headers {
// this struct is only needed because I was getting panic from clap when trying to directly use Vec<(String, String)> and parse it.
// it really did not want to deal with vector when argaction was not set to Append.
headers: Vec<(String, String)>,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Secrets {
secrets: Vec<(String, String)>,
}
pub trait KeyValuePairs {
fn new(pairs: Vec<(String, String)>) -> Self;
}
impl KeyValuePairs for Headers {
fn new(pairs: Vec<(String, String)>) -> Self {
Headers { headers: pairs }
}
}
impl KeyValuePairs for Secrets {
fn new(pairs: Vec<(String, String)>) -> Self {
Secrets { secrets: pairs }
}
}
fn parse_key_values<T: KeyValuePairs>(s: &str) -> Result<T, ParseError> {
if s.is_empty() {
return Ok(T::new(Vec::new()));
}
let mut pairs = Vec::new();
let elements = s.split(',');
for element in elements {
pairs.push(parse_key_val(element)?);
}
Ok(T::new(pairs))
}
#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum AssetCommands {
/// Lists your assets.
List {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
},
/// Gets a single asset by id.
Get {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
/// UUID of the asset.
uuid: String,
},
/// Adds a new asset.
Add {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
/// Path to local file or URL for remote file.
path: String,
/// Asset title.
title: String,
},
/// Deletes an asset. This cannot be undone.
Delete {
/// UUID of the asset to be deleted.
uuid: String,
},
/// Injects JavaScript code inside of the web asset. It will be executed once the asset loads during playback.
InjectJs {
/// UUID of the web asset to inject with JavaScript.
uuid: String,
/// Path to local file or URL for remote file.
path: String,
},
/// Sets HTTP headers for web asset.
SetHeaders {
/// UUID of the web asset to set http headers.
uuid: String,
/// HTTP headers in the following form `header1=value1[,header2=value2[,...]]`. This command
/// replaces all headers of the asset with the given headers (when an empty string is given, e.g. --set-headers "",
/// all existing headers are removed, if any)
#[arg(value_parser = parse_key_values::<Headers>)]
headers: Headers,
},
/// Updates HTTP headers for web asset.
UpdateHeaders {
/// UUID of the web asset to set http headers.
uuid: String,
/// HTTP headers in the following form `header1=value1[,header2=value2[,...]]`. This command updates only the given headers (adding them if new), leaving any other headers unchanged.
#[arg(value_parser=parse_key_values::<Headers>)]
headers: Headers,
},
/// Shortcut for setting up basic authentication headers.
BasicAuth {
/// UUID of the web asset to set up basic authentication for.
uuid: String,
/// Basic authentication credentials in "user=password" form.
#[arg(value_parser = parse_key_val)]
credentials: (String, String),
},
/// Shortcut for setting up bearer authentication headers.
BearerAuth {
/// UUID of the web asset to set up basic authentication for.
uuid: String,
/// Bearer token.
token: String,
},
}
#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum EdgeAppCommands {
/// Creates Edge App in the store.
Create {
/// Edge App name
#[arg(short, long)]
name: String,
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
/// Use an existing Edge App directory with the manifest and index.html.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
in_place: Option<bool>,
},
/// Lists your Edge Apps.
List {
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
},
/// Renames Edge App
Rename {
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
/// Edge App name
#[arg(short, long)]
name: String,
},
/// Runs Edge App emulator.
Run {
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
/// Secrets to be passed to the Edge App in the form KEY=VALUE. Can be specified multiple times.
#[arg(short, long, value_parser = parse_key_values::<Secrets>)]
secrets: Option<Secrets>,
/// Generates mock data to be used with Edge App run
#[arg(short, long, action = clap::ArgAction::SetTrue)]
generate_mock_data: Option<bool>,
},
/// Settings commands.
#[command(subcommand)]
Setting(EdgeAppSettingsCommands),
/// Instance commands.
#[command(subcommand)]
Instance(EdgeAppInstanceCommands),
/// Deploys assets and settings of the Edge App and release it.
Deploy {
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
#[arg(short, long)]
delete_missing_settings: Option<bool>,
},
/// Deletes an Edge App. This cannot be undone.
Delete {
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
},
/// Validates Edge App manifest file
Validate {
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
},
}
#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum EdgeAppSettingsCommands {
/// Lists Edge App settings.
List {
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
},
/// Sets Edge App setting.
Set {
/// Key value pair of the setting to be set in the form of `key=value`.
#[arg(value_parser = parse_key_val)]
setting_pair: (String, String),
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
},
}
#[derive(Subcommand, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum EdgeAppInstanceCommands {
/// Lists Edge App instances.
List {
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
/// Enables JSON output.
#[arg(short, long, action = clap::ArgAction::SetTrue)]
json: Option<bool>,
},
/// Creates Edge App instance.
Create {
/// Name of the Edge App instance.
#[arg(short, long)]
name: Option<String>,
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
},
/// Deletes Edge App instance.
Delete {
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
},
/// Update Edge App instance based on changes in the instance.yml.
Update {
/// Path to the directory with the manifest. If not specified CLI will use the current working directory.
#[arg(short, long)]
path: Option<String>,
},
}
pub fn handle_command_execution_result<T: Formatter>(
result: anyhow::Result<T, CommandError>,
json: &Option<bool>,
) {
match result {
Ok(screen) => {
let output_type = if json.unwrap_or(false) {
OutputType::Json
} else {
OutputType::HumanReadable
};
println!("{}", screen.format(output_type));
}
Err(e) => {
match e {
CommandError::Authentication(_) => {
error!(
"Authentication error occurred. Please use login command to authenticate."
)
}
_ => {
error!("Error occurred: {e:?}");
}
}
std::process::exit(1);
}
}
}
pub fn get_screen_name(
id: &str,
screen_command: &commands::screen::ScreenCommand,
) -> Result<String, CommandError> {
let target_screen = screen_command.get(id)?;
if let Some(screens) = target_screen.value.as_array() {
if screens.is_empty() {
error!("Screen could not be found.");
return Err(CommandError::MissingField);
}
return if let Some(name) = screens[0]["name"].as_str() {
Ok(name.to_string())
} else {
Err(CommandError::MissingField)
};
}
Err(CommandError::MissingField)
}
pub fn get_asset_title(
id: &str,
asset_command: &commands::asset::AssetCommand,
) -> Result<String, CommandError> {
let target_asset = asset_command.get(id)?;
if let Some(assets) = target_asset.value.as_array() {
if assets.is_empty() {
error!("Asset could not be found.");
return Err(CommandError::MissingField);
}
return if let Some(name) = assets[0]["title"].as_str() {
Ok(name.to_string())
} else {
Err(CommandError::MissingField)
};
}
Err(CommandError::MissingField)
}
pub fn handle_cli(cli: &Cli) {
match &cli.command {
Commands::Login {} => {
print!("Enter your API Token: ");
std::io::stdout().flush().unwrap();
let token = read_password().unwrap();
match verify_and_store_token(&token, &Config::default().url) {
Ok(()) => {
info!("Login credentials have been saved.");
std::process::exit(0);
}
Err(e) => match e {
AuthenticationError::WrongCredentials => {
error!("Token verification failed.");
std::process::exit(1);
}
_ => {
error!("Error occurred: {e:?}");
std::process::exit(1);
}
},
}
}
Commands::Screen(command) => handle_cli_screen_command(command),
Commands::Asset(command) => handle_cli_asset_command(command),
Commands::EdgeApp(command) => handle_cli_edge_app_command(command),
Commands::Playlist(command) => handle_cli_playlist_command(command),
Commands::Logout {} => {
Authentication::remove_token().expect("Failed to remove token.");
info!("Logout successful.");
std::process::exit(0);
}
Commands::PrintHelpMarkdown {} => {
clap_markdown::print_help_markdown::<Cli>();
}
}
}
fn get_user_input() -> String {
let stdin = io::stdin();
let mut user_input = String::new();
match stdin.read_line(&mut user_input) {
Ok(_) => {}
Err(e) => {
error!("Error occurred: {e}");
std::process::exit(1);
}
}
user_input.trim().to_string()
}
pub fn handle_cli_screen_command(command: &ScreenCommands) {
let authentication = get_authentication();
let screen_command = commands::screen::ScreenCommand::new(authentication);
match command {
ScreenCommands::List { json } => {
handle_command_execution_result(screen_command.list(), json);
}
ScreenCommands::Get { uuid, json } => {
handle_command_execution_result(screen_command.get(uuid), json);
}
ScreenCommands::Add { pin, name, json } => {
handle_command_execution_result(screen_command.add(pin, name.clone()), json);
}
ScreenCommands::Delete { uuid } => {
match get_screen_name(uuid, &screen_command) {
Ok(name) => {
info!("You are about to delete the screen named \"{name}\". This operation cannot be reversed.");
info!("Enter the screen name to confirm the screen deletion: ");
if name != get_user_input() {
error!("The name you entered is incorrect. Aborting.");
std::process::exit(1);
}
}
Err(e) => {
error!("Error occurred: {e}");
std::process::exit(1);
}
}
match screen_command.delete(uuid) {
Ok(()) => {
info!("Screen deleted successfully.");
std::process::exit(0);
}
Err(e) => {
error!("Error occurred: {e:?}");
std::process::exit(1);
}
}
}
}
}
pub fn handle_cli_playlist_command(command: &PlaylistCommands) {
let playlist_command = PlaylistCommand::new(get_authentication());
match command {
PlaylistCommands::Create {
json,
title,
predicate,
} => {
handle_command_execution_result(
playlist_command.create(title, &predicate.clone().unwrap_or("TRUE".to_owned())),
json,
);
}
PlaylistCommands::List { json } => {
handle_command_execution_result(playlist_command.list(), json);
}
PlaylistCommands::Get { uuid } => {
let playlist_file = playlist_command.get_playlist_file(uuid);
match playlist_file {
Ok(playlist) => {
let pretty_playlist_file = serde_json::to_string_pretty(&playlist).unwrap();
println!("{pretty_playlist_file}");
}
Err(e) => {
eprintln!("Error occurred when getting playlist: {e:?}")
}
}
}
PlaylistCommands::Delete { uuid } => match playlist_command.delete(uuid) {
Ok(()) => {
println!("Playlist deleted successfully.");
}
Err(e) => {
eprintln!("Error occurred when deleting playlist: {e:?}")
}
},
PlaylistCommands::Append {
json,
uuid,
asset_uuid,
duration,
} => {
handle_command_execution_result(
playlist_command.append_asset(
uuid,
asset_uuid,
(*duration).unwrap_or(DEFAULT_ASSET_DURATION),
),
json,
);
}
PlaylistCommands::Prepend {
json,
uuid,
asset_uuid,
duration,
} => {
handle_command_execution_result(
playlist_command.prepend_asset(
uuid,
asset_uuid,
(*duration).unwrap_or(DEFAULT_ASSET_DURATION),
),
json,
);
}
PlaylistCommands::Update {} => {
let mut input = String::new();
io::stdin()
.read_to_string(&mut input)
.expect("Unable to read stdin.");
let playlist: PlaylistFile =
serde_json::from_str(&input).expect("Unable to parse playlist file.");
match playlist_command.update(&playlist) {
Ok(_) => {
println!("Playlist updated successfully.");
}
Err(e) => {
eprintln!("Error occurred when updating playlist: {e:?}")
}
}
}
}
}
pub fn handle_cli_asset_command(command: &AssetCommands) {
let authentication = get_authentication();
let asset_command = commands::asset::AssetCommand::new(authentication);
match command {
AssetCommands::List { json } => {
handle_command_execution_result(asset_command.list(), json);
}
AssetCommands::Get { uuid, json } => {
handle_command_execution_result(asset_command.get(uuid), json);
}
AssetCommands::Add { path, title, json } => {
handle_command_execution_result(asset_command.add(path, title), json);
}
AssetCommands::Delete { uuid } => {
match get_asset_title(uuid, &asset_command) {
Ok(title) => {
info!("You are about to delete the asset named \"{title}\". This operation cannot be reversed.");
info!("Enter the asset title to confirm the asset deletion: ");
io::stdout().flush().unwrap();
let stdin = io::stdin();
let mut user_input = String::new();
match stdin.read_line(&mut user_input) {
Ok(_) => {}
Err(e) => {
error!("Error occurred: {e}");
std::process::exit(1);
}
}
if title != user_input.trim() {
error!("The title you entered is incorrect. Aborting.");
std::process::exit(1);
}
}
Err(e) => {
error!("Error occurred: {e}");
std::process::exit(1);
}
}
match asset_command.delete(uuid) {
Ok(()) => {
info!("Asset deleted successfully.");
std::process::exit(0);
}
Err(e) => {
error!("Error occurred: {e:?}");
std::process::exit(1);
}
}
}
AssetCommands::InjectJs { uuid, path } => {
let js_code = if path.starts_with("http://") || path.starts_with("https://") {
match reqwest::blocking::get(path) {
Ok(response) => match response.status() {
StatusCode::OK => response.text().unwrap_or_default(),
status => {
error!("Failed to retrieve JS injection code. Wrong response status: {status}");
std::process::exit(1);
}
},
Err(e) => {
error!("Failed to retrieve JS injection code. Error: {e}");
std::process::exit(1);
}
}
} else {
match fs::read_to_string(path) {
Ok(text) => text,
Err(e) => {
error!("Failed to read file with JS injection code. Error: {e}");
std::process::exit(1);
}
}
};
match asset_command.inject_js(uuid, &js_code) {
Ok(()) => {
info!("Asset updated successfully.");
}
Err(e) => {
error!("Error occurred: {e:?}");
std::process::exit(1);
}
}
}
AssetCommands::SetHeaders { uuid, headers } => {
match asset_command.set_web_asset_headers(uuid, headers.headers.clone()) {
Ok(()) => {
info!("Asset updated successfully.");
}
Err(e) => {
error!("Error occurred: {e:?}");
std::process::exit(1);
}
}
}
AssetCommands::BasicAuth { uuid, credentials } => {
let basic_auth = Credentials::new(&credentials.0, &credentials.1);
match asset_command.update_web_asset_headers(
uuid,
vec![("Authorization".to_owned(), basic_auth.as_http_header())],
) {
Ok(()) => {
info!("Asset updated successfully.");
}
Err(e) => {
error!("Error occurred: {e:?}");
std::process::exit(1);
}
}
}
AssetCommands::UpdateHeaders { uuid, headers } => {
match asset_command.update_web_asset_headers(uuid, headers.headers.clone()) {
Ok(()) => {
info!("Asset updated successfully.");
}
Err(e) => {
error!("Error occurred: {e:?}");
std::process::exit(1);
}
}
}
AssetCommands::BearerAuth { uuid, token } => {
match asset_command.update_web_asset_headers(
uuid,
vec![("Authorization".to_owned(), format!("Bearer {token}"))],
) {
Ok(()) => {
info!("Asset updated successfully.");
}
Err(e) => {
error!("Error occurred: {e:?}");
std::process::exit(1);
}
}
}
}
}
pub fn handle_cli_edge_app_command(command: &EdgeAppCommands) {
let authentication = get_authentication();
let edge_app_command = commands::edge_app::EdgeAppCommand::new(authentication);
match command {
EdgeAppCommands::Create {
name,
path,
in_place,
} => {
let create_func = if in_place.unwrap_or(false) {
commands::edge_app::EdgeAppCommand::create_in_place
} else {
commands::edge_app::EdgeAppCommand::create
};
let manifest_path = match transform_edge_app_path_to_manifest(path) {
Ok(path) => path,
Err(e) => {
eprintln!("Failed to create edge app: {e}.");
std::process::exit(1);
}
};
match create_func(&edge_app_command, name, manifest_path.as_path()) {
Ok(()) => {
println!("Edge app successfully created.");
}
Err(e) => {
eprintln!("Failed to publish edge app manifest: {e}.");
std::process::exit(1);
}
}
}
EdgeAppCommands::List { json } => {
handle_command_execution_result(edge_app_command.list(), json);
}
EdgeAppCommands::Deploy {
path,
delete_missing_settings,
} => match edge_app_command.deploy(path.clone(), *delete_missing_settings) {
Ok(revision) => {
println!("Edge app successfully deployed. Revision: {revision}.");
}
Err(e) => {
eprintln!("Failed to upload edge app: {e}.");
std::process::exit(1);
}
},
EdgeAppCommands::Setting(command) => match command {
EdgeAppSettingsCommands::List { path, json } => {
handle_command_execution_result(edge_app_command.list_settings(path.clone()), json);
}
EdgeAppSettingsCommands::Set { setting_pair, path } => {
match edge_app_command.set_setting(path.clone(), &setting_pair.0, &setting_pair.1) {
Ok(()) => {
println!("Edge app setting successfully set.");
}
Err(e) => {
eprintln!("Failed to set edge app setting: {e}");
std::process::exit(1);
}
}
}
},
EdgeAppCommands::Delete { path } => {
let actual_app_id = match edge_app_command.get_app_id(path.clone()) {
Ok(id) => id,
Err(e) => {
error!("Error calling delete Edge App: {e}");
std::process::exit(1);
}
};
match edge_app_command.get_app_name(&actual_app_id) {
Ok(name) => {
info!("You are about to delete the Edge App named \"{name}\". This operation cannot be reversed.");
info!("Enter the Edge App name to confirm the app deletion: ");
if name != get_user_input() {
error!("The name you entered is incorrect. Aborting.");
std::process::exit(1);
}
}
Err(e) => {
error!("Error occurred: {e}");
std::process::exit(1);
}
}
match edge_app_command.delete_app(&actual_app_id) {
Ok(()) => {
println!("Edge App Deletion in Progress.\nRequest to delete the Edge App has been received and is now being processed. The deletion is marked for asynchronous handling, so it won't happen instantly.");
let manifest_path = match transform_edge_app_path_to_manifest(path) {
Ok(path) => path,
Err(e) => {
eprintln!("Failed to delete edge app: {e}.");
std::process::exit(1);
}
};
// If the user didn't specify an app id, we need to clear it from the manifest
match edge_app_command.clear_app_id(manifest_path.as_path()) {
Ok(()) => {
println!("App id cleared from manifest.");
}
Err(e) => {
error!("Error occurred while clearing manifest: {e}");
std::process::exit(1);
}
}
std::process::exit(0);
}
Err(e) => {
error!("Error occurred: {e:?}");
std::process::exit(1);
}
}
}
EdgeAppCommands::Rename { path, name } => {
let actual_app_id = match edge_app_command.get_app_id(path.clone()) {
Ok(id) => id,
Err(e) => {
error!("Error calling delete Edge App: {e}");
std::process::exit(1);
}
};
match edge_app_command.update_name(&actual_app_id, name) {
Ok(()) => {
println!("Edge app successfully updated.");
}
Err(e) => {
eprintln!("Failed to update edge app: {e}.");
std::process::exit(1);
}
}
}
EdgeAppCommands::Run {
path,
secrets,
generate_mock_data,
} => {
let secrets = if let Some(secret_pairs) = secrets {
secret_pairs.secrets.clone()
} else {
Vec::new()
};
if generate_mock_data.unwrap_or(false) {
let manifest_path = match transform_edge_app_path_to_manifest(path) {
Ok(path) => path,
Err(e) => {
eprintln!("Failed to generate mock data: {e}.");
std::process::exit(1);
}
};
match edge_app_command.generate_mock_data(&manifest_path) {