/
mod.rs
1246 lines (1044 loc) · 44.1 KB
/
mod.rs
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::{sync::{
Mutex,
Arc
}, time::{SystemTime, UNIX_EPOCH}};
use eframe::egui::epaint::ahash::{HashMap, HashMapExt};
use crate::Config;
use super::{
AppConfig,
Bucket,
Ticket,
Filter,
State,
Tag,
AdapterError,
AdapterErrorType,
TicketAdapter,
BucketPanelLocation,
BucketPanelLocationType
};
pub type SyncedTicketAdapter = Box<dyn TicketAdapter + Sync + Send>;
pub type AdapterConstructor = fn(Arc<Mutex<AppConfig>>, &Config, Arc<Mutex<bool>>) -> Result<SyncedTicketAdapter, AdapterError>;
pub type AdapterConfig = fn() -> Config;
pub struct FilterExpression {
adapter: String,
expression: String
}
pub struct AdapterType {
pub name: String,
pub fancy_name: String,
new_fn: AdapterConstructor,
config_fn: AdapterConfig
}
impl AdapterType {
pub fn new<T: TicketAdapter>() -> Self {
AdapterType{
name: T::get_type_name(),
fancy_name: T::get_fancy_type_name(),
new_fn: T::from_config,
config_fn: T::create_config
}
}
pub fn from_config(&self, app_config: Arc<Mutex<AppConfig>>, config: &Config, done_loading: Arc<Mutex<bool>>) -> Result<SyncedTicketAdapter, AdapterError> {
(self.new_fn)(app_config, config, done_loading)
}
pub fn config(&self) -> Config {
(self.config_fn)()
}
}
pub struct TicketProvider {
type_registry: HashMap<String, AdapterType>,
config: Arc<Mutex<AppConfig>>,
adapters: Arc<Mutex<Vec<Arc<SyncedTicketAdapter>>>>
}
impl TicketProvider {
/**
Setup the Ticket Provider. It is supposed to be a single Provider
that manages all available Adapters, but i tried to avoid making
a global instance just for less problems.
*/
pub fn new(config: Arc<Mutex<AppConfig>>, types_list: Vec<AdapterType>, finished: Arc<Mutex<bool>>) -> TicketProvider {
let adapters: Vec<Arc<Box<dyn TicketAdapter + Sync + Send>>> = vec![];
let mut type_registry: HashMap<String, AdapterType> = HashMap::new();
for type_entry in types_list {
type_registry.insert(type_entry.name.clone(), type_entry);
}
let ticket_provider = TicketProvider {
type_registry,
config,
adapters: Arc::new(Mutex::new(adapters)),
};
ticket_provider.adapters_from_app_config(finished);
ticket_provider
}
pub fn has_adapters(&self) -> bool {
match self.adapters.lock() {
Ok(lock) => !lock.is_empty(),
Err(_) => false,
}
}
/**
Creates a minimal Configuration, from which custom Adapter Implementation can derive
from. This Data is needed at a minimum, to make the whole Adapter Detection System work.
*/
pub fn get_default_config<T: TicketAdapter>() -> Config {
let mut random_identifier = T::get_type_name() + "_";
random_identifier += SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis()
.to_string()
.as_str();
Config::default()
.with("type", T::get_type_name(), "readonly_string")
.with("name", random_identifier, "string")
.with("display", T::get_fancy_type_name(), "string")
}
/**
Creates a Config of a supplied Type, if the type is in the registry of this Ticket Provider
*/
pub fn get_type_config(&self, type_name: &String) -> Option<Config> {
self.type_registry.get(type_name).map(|found_type| found_type.config())
}
/**
Lists all available Adapter Types, that have been registered with this Ticket Provider
*/
pub fn list_available_adapter_types(&self) -> Vec<&AdapterType> {
let mut types_vec = Vec::default();
for type_val in self.type_registry.values() {
types_vec.push(type_val);
}
types_vec
}
/**
Drops an adapter from the enabled Adapters List within this Ticket Adapter
Returns true, if successfully removed an adapter. If drop_from_config is true,
the function will also remove any left over configuration from the adapter,
when removing the adapter itself was successfull.
*/
pub fn drop_adapter(&self, adapter_name: String, drop_from_config: bool) -> bool {
match self.adapters.lock() {
Ok(mut lock) => {
let mut found_index: Option<usize> = None;
for adapter in lock.iter().enumerate() {
if adapter.1.get_name() == adapter_name {
found_index = Some(adapter.0);
break;
}
}
if let Some(index) = found_index {
lock.remove(index);
if drop_from_config {
match self.config.lock() {
Ok(mut lock) => {
let corrected_name = "adapters:".to_string() + adapter_name.as_str();
lock.drop_sub_config(corrected_name.as_str());
if let Some(mut adapters_vec) = lock.get_or_default("adapters", "", "").get::<Vec<String>>() {
let mut found_index: Option<usize> = None;
for adapter_entry in adapters_vec.iter().enumerate() {
if adapter_name == *adapter_entry.1 {
found_index = Some(adapter_entry.0);
}
}
if let Some(found_index) = found_index {
adapters_vec.remove(found_index);
lock.put("adapters", adapters_vec, "");
};
}
},
Err(err) => {
println!("Unable to lock App Config due to {err}");
},
}
}
true
} else {
false
}
},
Err(err) => {
println!("Unable to lock Adapters List due to {err}");
false
},
}
}
/**
Tries to create an Adapter from Config and adds it to the adapters list
within this Ticket Provider. If something fials creating the Adapter,
it will create an AdapterError.
If it was successfull and write_to_app_config is true, then it will write
the supplied config into the app config
*/
pub fn adapter_from_config(&self, config: &Config, write_to_app_config: bool, finished: Arc<Mutex<bool>>) -> Result<(), AdapterError> {
let type_name = match config.get("type") {
Some(option) => match option.get::<String>() {
Some(type_name) => type_name,
None => {
println!("Given Adapter Config has no valid type!");
return Err(AdapterError::new(AdapterErrorType::Instantiation));
},
},
None => {
println!("Given Adapter Config has no valid type!");
return Err(AdapterError::new(AdapterErrorType::Instantiation));
},
};
let constructor = match self.type_registry.get(&type_name) {
Some(found_type) => {
found_type.new_fn
},
None => {
println!("Adapter type \"{type_name}\" does not exist!");
return Err(AdapterError::new(AdapterErrorType::Instantiation));
},
};
match constructor(self.config.clone(), config, finished) {
Ok(adapter) => {
let mut adapters = match self.adapters.lock() {
Ok(lock) => lock,
Err(err) => {
println!("Unable to lock Adapters List due to {err}");
return Err(AdapterError::new(AdapterErrorType::Access));
},
};
let adapter_name = adapter.get_name();
adapters.push(Arc::new(adapter));
if write_to_app_config {
match self.config.lock() {
Ok(mut config_lock) => {
config_lock.put_sub_config(config, ["adapters", adapter_name.as_str()].join(":").as_str());
let mut old_adapters_list = config_lock.get_or_default("adapters", "", "").raw().clone();
if old_adapters_list.is_empty() {
old_adapters_list += adapter_name.as_str();
} else {
old_adapters_list += "|||";
old_adapters_list += adapter_name.as_str();
}
config_lock.put("adapters", old_adapters_list, "");
},
Err(err) => {
println!("Unable to lock Config due to {err}");
return Err(AdapterError::new(AdapterErrorType::Access));
},
}
}
Ok(())
},
Err(err) => {
println!("Found Adapter type \"{type_name}\", but there was a problem instantiating it. Maybe a broken Config?");
Err(err)
},
}
}
/**
Clears the currently installed Adapters and reloads them from the
config, that has been supplied on instantiation of the Ticket provider.
*/
pub fn adapters_from_app_config(&self, finished: Arc<Mutex<bool>>) {
match self.adapters.lock() {
Ok(mut lock) => lock.clear(),
Err(err) => {
println!("Unable to lock Adapters List due to {err}");
return;
},
};
let mut config = match self.config.lock() {
Ok(lock) => lock,
Err(err) => {
println!("Unable to lock Config due to {err}");
return;
},
};
let adapters_vec: Vec<String> = match config.get_or_default("adapters", Vec::<String>::default(), "").get() {
Some(adapters_vec) => adapters_vec,
None => {
println!("No Adapters Vector in Config found, or invalid format.");
return;
},
};
for adapter_name in adapters_vec {
if adapter_name.is_empty() {
println!("Adapter name is empty, ignoring.");
continue;
}
let adapter_config = config.get_sub_config(["adapters", adapter_name.as_str()].join(":").as_str());
match self.adapter_from_config(&adapter_config, false, finished.clone()) {
Ok(_) => (),
Err(err) => println!("Failed creating {adapter_name}. Reason: {err}"),
};
};
}
/**
Adds an Adapter for providing tickets and other things to the ticket management tool.
Be aware that this will consume the Adapter
*/
pub fn add_adapter(&mut self, adapter: Arc<Box<dyn TicketAdapter + Sync + Send>>) {
match self.adapters.lock() {
Ok(mut lock) => {
lock.push(adapter);
},
Err(err) => println!("Wasn't able to add the \"{}\" adapter to the System due to {}", adapter.get_name(), err)
}
}
/**
Returns a list of fancy names from all added adapters as a vector
*/
pub fn list_fancy_adapter_names(&self) -> Vec<String> {
match self.adapters.lock() {
Ok(lock) => {
let mut found_names: Vec<String> = vec![];
for adapter in lock.iter() {
found_names.push(adapter.get_fancy_name())
}
found_names
},
Err(_) => {
println!("Can't lock adapters for listing adapter Names.");
vec![]
}
}
}
/**
* Returns a list of the internal names of the available adapters as a vector
*/
pub fn list_adapter_names(&self) -> Vec<String> {
match self.adapters.lock() {
Ok(lock) => {
let mut found_names: Vec<String> = vec![];
for adapter in lock.iter() {
found_names.push(adapter.get_name())
}
found_names
},
Err(_) => {
println!("Can't lock adapters for listing adapter Names.");
vec![]
}
}
}
/**
* Returns the list of name pairs of the available adapters as a vector.
* The pairs consist of the internal name, followed by the fancy name
*/
pub fn list_adapter_name_pairs(&self) -> Vec<(String, String)> {
match self.adapters.lock() {
Ok(lock) => {
let mut found_names: Vec<(String, String)> = vec![];
for adapter in lock.iter() {
found_names.push((adapter.get_name(), adapter.get_fancy_name()))
}
found_names
},
Err(_) => {
println!("Can't lock adapters for listing adapter Names.");
vec![]
}
}
}
/**
* Returns a list of references to Adapters as a vector
*/
pub fn list_adapter_refs(&self) -> Vec<Arc<Box<dyn TicketAdapter + Sync + Send>>> {
let mut ref_list: Vec<Arc<Box<dyn TicketAdapter + Sync + Send>>> = vec![];
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
ref_list.push(adapter.clone());
}
},
Err(err) => println!("Wasn't able to lock adapters list, due to {err}"),
};
ref_list
}
/**
Returns a Vector of all Buckets from all Adapters. Doesn't fail.
*/
pub fn bucket_list_all(&self) -> Vec<Bucket> {
let mut buckets: Vec<Bucket> = vec![];
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
buckets.append(&mut adapter.bucket_list_all());
}
},
Err(err) => println!("Wasn't able to list buckets from adapters due to {}", err)
};
buckets
}
/**
Writes a bucket to it's corresponding adapter, if not readonly
Throws an error, if the write failed. Other reasons depend on
the used adapters
*/
pub fn bucket_write(&self, bucket: &mut Bucket) -> Result<(), AdapterError> {
let bucket_adapter = bucket.identifier.adapter.clone();
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
if adapter.get_name() == bucket_adapter {
return adapter.bucket_write(bucket);
}
}
},
Err(_) => return Err(AdapterError::new(AdapterErrorType::BucketWrite))
}
Ok(())
}
/**
Check if, the bucket can be inserted as new and is guaranteed
to keep integrity with it's attributes
*/
pub fn bucket_validate(&self, bucket: &Bucket) -> Result<(), AdapterError> {
let mut validation_errors: Vec<(String, String)> = Vec::default();
if bucket.name.is_empty() {
validation_errors.push(("name".to_string(), "The name of the Bucket is not supposed to be empty!".to_string()));
};
match self.adapters.lock() {
Ok(lock) => {
let mut adapter_matched = false;
for adapter in lock.iter() {
if adapter.get_name() == bucket.identifier.adapter {
adapter_matched = true;
let buckets = adapter.bucket_list_all();
let mut bucket_matched = false;
for found_bucket in buckets {
if found_bucket.name == bucket.name {
bucket_matched = true;
break;
}
}
if bucket_matched {
validation_errors.push(("name".to_string(), format!("The Bucket with name {} does already exist in this adapter.", bucket.name)));
}
break;
}
};
if !adapter_matched {
let adapter = &bucket.identifier.adapter;
validation_errors.push(("adapter".to_string(), format!("The Adapter \"{adapter}\" does not match any of the available adapters.")));
}
},
Err(_) => return Err(AdapterError::new(AdapterErrorType::Access))
};
if validation_errors.is_empty() {
Ok(())
} else {
Err(AdapterError::new(AdapterErrorType::Validate(validation_errors, "Bucket".to_string())))
}
}
/**
Checks, if the ticket can be inserted as new and is guaranteed
to keep integrity with it's attributes
*/
pub fn ticket_validate(&self, ticket: &Ticket) -> Result<(), AdapterError> {
let mut validation_errors: Vec<(String, String)> = Vec::default();
if ticket.title.is_empty() {
validation_errors.push(("title".to_string(), "The title of the Ticket is not supposed to be empty!".to_string()));
};
match self.adapters.lock() {
Ok(lock) => {
let mut adapter_matched = false;
for adapter in lock.iter() {
if adapter.get_name() == ticket.adapter {
adapter_matched = true;
let buckets = adapter.bucket_list_all();
let mut bucket_matched = false;
for bucket in buckets {
if bucket.identifier.id == ticket.bucket_id {
bucket_matched = true;
break;
}
}
if !bucket_matched {
let bucket = ticket.bucket_id;
validation_errors.push(("bucket".to_string(), format!("The Bucket with id {bucket} does not exist in this adapter.")));
}
let states = adapter.state_list_all();
let mut state_matched = false;
for state in states {
if state.identifier.name == ticket.state_name {
state_matched = true;
break;
}
}
if !state_matched {
let state = &ticket.state_name;
validation_errors.push(("state".to_string(), format!("The State \"{state}\" does not exist in this adapter.")));
}
break;
}
};
if !adapter_matched {
let adapter = &ticket.adapter;
validation_errors.push(("adapter".to_string(), format!("The Adapter \"{adapter}\" does not match any of the available adapters.")));
}
},
Err(_) => return Err(AdapterError::new(AdapterErrorType::Access))
};
if validation_errors.is_empty() {
Ok(())
} else {
Err(AdapterError::new(AdapterErrorType::Validate(validation_errors, "Ticket".to_string())))
}
}
/**
Check if the State can be inserted as new and keeps integrity with it's attributes
*/
pub fn state_validate(&self, state: &State) -> Result<(), AdapterError> {
let mut validation_errors: Vec<(String, String)> = Vec::default();
if state.identifier.name.is_empty() {
validation_errors.push(("name".to_string(), "The Name of the State is not supposed to be empty!".to_string()));
};
if state.description.len() > 1000 {
validation_errors.push(("description".to_string(), "The arbitrary Limit of the State's Description of 1k chars is reached. Make sure the description is as short and concise as possible.".to_string()));
};
match self.adapters.lock() {
Ok(lock) => {
let mut adapter_matched = false;
for adapter in lock.iter() {
if adapter.get_name() == state.identifier.adapter {
adapter_matched = true;
};
};
if !adapter_matched {
let adapter = &state.identifier.adapter;
validation_errors.push(("adapter".to_string(), format!("The Adapter \"{adapter}\" does not match any of the available adapters.")));
}
},
Err(_) => return Err(AdapterError::new(AdapterErrorType::Access))
};
if validation_errors.is_empty() {
Ok(())
} else {
Err(AdapterError::new(AdapterErrorType::Validate(validation_errors, "State".to_string())))
}
}
/**
Checks, if the Tag can be inserted as new and is guaranteed to keep
integrity with it's attributes
*/
pub fn tag_validate(&self, tag: &Tag) -> Result<(), AdapterError> {
let mut validation_errors: Vec<(String, String)> = Vec::default();
if tag.name.is_empty() {
validation_errors.push(("name".to_string(), "The Name of the Tag is not supposed to be empty!".to_string()));
};
if tag.color.to_ascii_lowercase() == tag.color_text.to_ascii_lowercase() {
validation_errors.push(("color".to_string(), "The colors of the font and the background are the same!".to_string()));
}
match self.adapters.lock() {
Ok(lock) => {
let mut adapter_matched = false;
for adapter in lock.iter() {
if adapter.get_name() == tag.adapter {
adapter_matched = true;
};
};
if !adapter_matched {
let adapter = &tag.adapter;
validation_errors.push(("adapter".to_string(), format!("The Adapter \"{adapter}\" does not match any of the available adapters.")));
}
},
Err(_) => return Err(AdapterError::new(AdapterErrorType::Access))
};
if validation_errors.is_empty() {
Ok(())
} else {
Err(AdapterError::new(AdapterErrorType::Validate(validation_errors, "Tag".to_string())))
}
}
/**
Lists all Tickets from all Adapters. Returns a vector of all
found Tickets. Doesn't fail.
*/
pub fn ticket_list_all(&self) -> Vec<Ticket> {
let mut tickets: Vec<Ticket> = vec![];
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
tickets.append(&mut adapter.ticket_list_all());
}
},
Err(err) => println!("Wasn't able to list states from adapters due to {}", err)
};
tickets
}
/**
Lists a singular Ticket. Not recommended to be used in Loops, it exists to get
the most up to date version of a ticket, to make changes on.
*/
pub fn ticket_list_unique(&self, id: i64, adapter_name: &String) -> Option<Ticket> {
let mut ticket: Option<Ticket> = None;
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
if adapter.get_name().eq(adapter_name) {
ticket = adapter.ticket_list_unique(id);
}
}
},
Err(err) => println!("Wasn't able to list tickets from adapters due to {}", err)
};
ticket
}
/**
Lists a singular Bucket. Not recommended to be used in Loops, it exists to get
the most up to date version of a bucket, to make changes on.
*/
pub fn bucket_list_unique(&self, id: u64, adapter_name: &String) -> Option<Bucket> {
let mut bucket: Option<Bucket> = None;
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
if adapter.get_name().eq(adapter_name) {
bucket = adapter.bucket_list_unique(id);
}
}
},
Err(err) => println!("Wasn't able to list buckets from adapters due to {}", err)
};
bucket
}
/**
Lists all Tickets from one adapter
*/
pub fn tickets_list_adapter(&self, adapter_name: &String) -> Vec<Ticket> {
let mut tickets: Vec<Ticket> = vec![];
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
if adapter.get_name().eq(adapter_name) {
tickets.append(&mut adapter.ticket_list_all());
}
}
},
Err(err) => println!("Wasn't able to list states from adapters due to {}", err)
};
tickets
}
pub fn split_filter_expression(&self, filter_expression: String) -> Result<Vec<FilterExpression>, AdapterError> {
let mut expression = filter_expression.as_str().trim();
// Vector of Tuples with Adapter Name + Expression
let mut found_expressions: Vec<FilterExpression> = vec![];
while expression.contains("[[") {
// Split off the beginning
let cleaned_expression_beginning = expression.split_at(2).1;
// Split off the end and write advanced String to iterated expression
let expression_result = match cleaned_expression_beginning.find("]]") {
Some(found_pos) => {
let (cleaned_expression, rest_of_string) = cleaned_expression_beginning.split_at(found_pos);
let leftover_expression = rest_of_string.split_at(2).1;
expression = leftover_expression.trim();
Ok(cleaned_expression)
},
None => Err(AdapterError{ error_type: AdapterErrorType::Expression("Expression doesn't end with ]]".to_string()) })
};
// If successfully found content between brackets, isolate parameters,
// Otherwise return with error
if let Ok(cleaned_expression) = expression_result {
let filter_expression = match cleaned_expression.find(':') {
Some(found_pos) => {
let (adapter_name, adapter_op) = cleaned_expression.split_at(found_pos);
Ok(FilterExpression{
adapter: String::from(adapter_name.trim()),
expression: String::from(adapter_op.split_at(1).1.trim()) //remove the :
})
},
None => Err(AdapterError{ error_type: AdapterErrorType::Expression("Expression doesn't follow adapter:expression between the square brackets".to_string()) })
};
if let Ok(isolated_expr) = filter_expression {
found_expressions.push(isolated_expr);
} else {
println!("Expression adapter and operation is not split off with : !");
return Err(filter_expression.err().unwrap());
}
} else {
println!("Expression needs to end with ]] !");
return Err(expression_result.err().unwrap());
}
};
// If the found expressions list is empty, error out, because there was
// either nothing or a wrongly formatted expression in the filter string
if found_expressions.is_empty() {
println!("Expression needs start with [[ ! Is the expression empty?");
return Err(AdapterError{ error_type: AdapterErrorType::Expression("Expression needs start with [[ ! Is the expression empty?".to_string()) });
}
Ok(found_expressions)
}
/**
Lists all Tickets, that satisfy expressions specific to the adapters
a valid filter can have the form ```[[adapter: expression]]```.
You can even chain mutliple filter after eachother to collect the
results from multiple adapters such as ```[[ad1: expr1]][[ad2: expr2]]...```
the adapter in this case is the name of the adapter (not the fancy name)
and the expression is specific to the adapter, so you have to look
it up on the adapters documentation.
*/
pub fn ticket_list(&self, filter: &Filter) -> Result<Vec<Ticket>, AdapterError> {
let found_expressions = match self.split_filter_expression(filter.operation.clone()) {
Ok(expressions) => expressions,
Err(err) => return Err(err),
};
let mut tickets: Vec<Ticket> = vec![];
// Find adapters with corresponding name and execute operation on them.
// then collect their results into final list
let local_adapters = self.adapters.clone();
if let Ok(lock) = local_adapters.lock() {
for found_expression in found_expressions {
let expression_adapter = found_expression.adapter.clone();
let found_adapter = lock.iter().by_ref().into_iter().find(move |adapter| adapter.get_name() == expression_adapter);
if let Some(adapter) = found_adapter {
if let Err(error) = match adapter.ticket_list(&found_expression.expression) {
Ok(mut new_tickets) => {
tickets.append(&mut new_tickets);
Ok(())
},
Err(err) => Err(err),
} {
println!("Adapter \"{}\" failed to evaluate expression!", found_expression.adapter);
return Err(error);
}
} else {
println!("Adapter \"{}\" has not been found in Adapterlist!", found_expression.adapter);
return Err(AdapterError{ error_type: AdapterErrorType::Expression(format!("Adapter \"{}\" has not been found in Adapterlist!", found_expression.adapter)) });
}
}
} else {
println!("Wasn't able to Lock Adapterlist");
return Err(AdapterError{ error_type: AdapterErrorType::TicketWrite });
}
// If everything went fine, return the final ticket List
Ok(tickets)
}
/**
Write a given Ticket to it's corresponding Adapter. Throws an
Error, if the write failed. Other reasons depend on used adapters.
*/
pub fn ticket_write(&self, ticket: &Ticket) -> Result<(), AdapterError> {
let ticket_adapter = ticket.adapter.clone();
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
if adapter.get_name() == ticket_adapter {
return adapter.ticket_write(ticket);
}
}
},
Err(_) => return Err(AdapterError::new(AdapterErrorType::TicketWrite))
}
Ok(())
}
/**
Tries to delete a given Ticket from it's corresponding Adapter. Throws
an error, if the delete fails for whatever reason.
*/
pub fn ticket_drop(&self, ticket: &Ticket) -> Result<(), AdapterError> {
let ticket_adapter = ticket.adapter.clone();
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
if adapter.get_name() == ticket_adapter {
return adapter.ticket_drop(ticket);
}
}
},
Err(_) => return Err(AdapterError::new(AdapterErrorType::TicketDelete))
}
Ok(())
}
/**
Lists all states from all Adapters. Returns a vector of all
found states. Doesn't fail.
*/
pub fn state_list_all(&self) -> Vec<State> {
let mut states: Vec<State> = vec![];
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
states.append(&mut adapter.state_list_all());
}
},
Err(err) => println!("Wasn't able to list states from adapters due to {}", err)
};
states
}
/**
Write a state to it's corresponding Adapter. If the write goes wrong,
an Error gets thrown. Other reasons of an error can be found at the
corresponding adapter documentation
*/
pub fn state_write(&self, state: &State) -> Result<(), AdapterError> {
let state_adapter = state.identifier.adapter.clone();
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
if adapter.get_name() == state_adapter {
return adapter.state_write(state);
}
}
},
Err(_) => return Err(AdapterError::new(AdapterErrorType::StateWrite))
}
Ok(())
}
/**
Lists all available tags from all Adapters. Can't fail, gives an empty
vector instead.
*/
pub fn tag_list_all(&self) -> Vec<Tag> {
let mut tags: Vec<Tag> = vec![];
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
tags.append(&mut adapter.tag_list_all());
}
},
Err(err) => println!("Wasn't able to list tags from adapters due to {}", err)
};
tags
}
/**
Writes a given Tag to it's corresponding Adapter. If the write fails,
it throws an Error. Other reasons might be available on the Adapters
documentation
*/
pub fn tag_write(&self, tag: &Tag) -> Result<(), AdapterError> {
let tag_adapter = tag.adapter.clone();
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
if adapter.get_name() == tag_adapter {
return adapter.tag_write(tag);
}
}
},
Err(_) => return Err(AdapterError::new(AdapterErrorType::TagWrite))
}
Ok(())
}
/**
Tries to delete a given Tag from it's corresponding Adapter. Throws
an error, if the delete fails for whatever reason.
*/
pub fn tag_drop(&self, tag: &Tag) -> Result<(), AdapterError> {
let tag_adapter = tag.adapter.clone();
match self.adapters.lock() {
Ok(lock) => {
for adapter in lock.iter() {
if adapter.get_name() == tag_adapter {
return adapter.tag_drop(tag);
}
}
},
Err(_) => return Err(AdapterError::new(AdapterErrorType::TagDelete))
}
Ok(())
}
/**
Tries to delete a given Bucket from it's corresponding Adapter. Throws
an error, if the delete fails for whatever reason.
*/
pub fn bucket_drop(&self, bucket: &Bucket) -> Result<(), AdapterError> {
let bucket_adapter = bucket.identifier.adapter.clone();