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
mod client;
mod content;
mod database;
mod error;
mod input;
mod meta;
mod navigation;
mod request;
mod widget;
use client::Client;
use content::Content;
use error::Error;
use input::Input;
use meta::{Meta, Status};
use navigation::Navigation;
use request::Request;
use widget::Widget;
use crate::app::browser::{
window::{tab::item::Action as TabAction, Action as WindowAction},
Action as BrowserAction,
};
use crate::Profile;
use gtk::{
gdk::Texture,
gdk_pixbuf::Pixbuf,
gio::SocketClientEvent,
glib::{
gformat, GString, Priority, Regex, RegexCompileFlags, RegexMatchFlags, Uri, UriFlags,
UriHideFlags,
},
prelude::{EditableExt, FileExt, SocketClientExt, WidgetExt},
};
use sqlite::Transaction;
use std::{rc::Rc, time::Duration};
pub struct Page {
id: Rc<GString>,
profile: Rc<Profile>,
// Actions
browser_action: Rc<BrowserAction>,
tab_action: Rc<TabAction>,
// Components
pub client: Rc<Client>,
pub content: Rc<Content>,
pub input: Rc<Input>,
pub meta: Rc<Meta>,
pub navigation: Rc<Navigation>,
pub widget: Rc<Widget>,
}
impl Page {
// Constructors
pub fn new(
id: Rc<GString>,
profile: Rc<Profile>,
action: (Rc<BrowserAction>, Rc<WindowAction>, Rc<TabAction>),
) -> Self {
// Init components
let content = Rc::new(Content::new((action.1.clone(), action.2.clone())));
let navigation = Rc::new(Navigation::new(
profile.clone(),
(action.0.clone(), action.1.clone(), action.2.clone()),
));
let input = Rc::new(Input::new());
let widget = Rc::new(Widget::new(
&id,
&navigation.widget.gobject,
&content.gobject,
&input.widget.clamp,
));
let meta = Rc::new(Meta::new(Status::New, gformat!("New page")));
// Done
Self {
id,
profile,
// Actions
browser_action: action.0,
tab_action: action.2,
// Components
client: Rc::new(Client::new()),
content,
navigation,
input,
meta,
widget,
}
}
// Actions
/// Toggle bookmark for current `profile` by navigation request value
/// * return `true` on bookmark created, `false` on deleted
pub fn bookmark(&self) -> Result<bool, Error> {
let result = match self
.profile
.bookmark
.toggle(self.navigation.request.widget.entry.text().as_str())
{
Ok(result) => Ok(result),
Err(_) => Err(Error::Bookmark), // @TODO
};
self.update();
result
}
/// Navigate home URL (parsed from current navigation entry)
/// * this method create new history record in memory as defined in `action_page_open` action
pub fn home(&self) {
if let Some(url) = self.navigation.home.url() {
// Update with history record
self.tab_action.load.activate(Some(&url), true);
}
}
/// Navigate back in history
/// * this method does not create new history record in memory
pub fn history_back(&self) {
if let Some(request) = self.navigation.history.back(true) {
// Update navigation entry
self.navigation.request.widget.entry.set_text(&request);
// Load page (without history record)
self.load(false);
}
}
/// Navigate forward in history
/// * this method does not create new history record in memory
pub fn history_forward(&self) {
if let Some(request) = self.navigation.history.forward(true) {
// Update navigation entry
self.navigation.request.widget.entry.set_text(&request);
// Load page (without history record)
self.load(false);
}
}
/// Main loader for different protocols, that routed by scheme
/// * every protocol has it own (children) method implementation
pub fn load(&self, is_history: bool) {
/// Global limit to prevent infinitive redirects (ALL protocols)
/// * every protocol implementation has own value checker, according to specification
const DEFAULT_MAX_REDIRECT_COUNT: usize = 10;
// Move focus out from navigation entry
self.navigation.reload.widget.gobject.grab_focus();
// Reset widgets
self.input.unset();
// Create shared variant value
let id = self.id.clone();
// Prevent infinitive redirection
if self.meta.redirects() > DEFAULT_MAX_REDIRECT_COUNT {
todo!()
}
// Try redirect request
let request = if let Some(redirect) = self.meta.redirect() {
if redirect.is_foreground {
self.navigation
.request
.widget
.entry
.set_text(&redirect.request);
}
// Return value from redirection holder
Request::from(&redirect.request, redirect.referrer.as_ref())
} else {
// Reset redirect counter as request value taken from user input
self.meta.redirect.borrow_mut().clear();
// Return value from navigation entry
Request::from(&self.navigation.request.widget.entry.text(), None)
};
// Update
self.meta.set_status(Status::Reload).set_title("Loading..");
self.browser_action.update.activate(Some(&id));
// Route by request
match request {
Request::Default(ref uri) | Request::Download(ref uri) | Request::Source(ref uri) => {
// Route by scheme
match uri.scheme().as_str() {
"file" => todo!(),
"gemini" => {
let (uri, is_download, is_source) = match request {
Request::Default(uri) => (uri, false, false),
Request::Download(uri) => (uri, true, false),
Request::Source(uri) => (uri, false, true),
_ => panic!(),
};
self.load_gemini(uri, is_download, is_source, is_history)
}
scheme => {
// Define common data
let status = Status::Failure;
let title = "Oops";
// Add history record
if is_history {
snap_history(self.navigation.clone());
}
// Update widget
self.content
.to_status_failure()
.set_title(title)
.set_description(Some(&format!("Scheme `{scheme}` not supported")));
// Update meta
self.meta.set_status(status).set_title(title);
// Update window
self.browser_action.update.activate(Some(&id));
}
}
}
Request::Search(ref query) => {
// Try interpret URI manually
if Regex::match_simple(
r"^[^\/\s]+\.[\w]{2,}",
query,
RegexCompileFlags::DEFAULT,
RegexMatchFlags::DEFAULT,
) {
// Seems request contain some host, try append default scheme
// * make sure new request conversable to valid URI
match Uri::parse(&format!("gemini://{query}"), UriFlags::NONE) {
Ok(uri) => {
// Update navigation entry
self.navigation
.request
.widget
.entry
.set_text(&uri.to_string());
// Load page (without history record)
self.load(false);
}
Err(_) => {
// @TODO any action here?
}
}
} else {
// Plain text given, make search request to default provider
self.navigation.request.widget.entry.set_text(&format!(
"gemini://tlgs.one/search?{}",
Uri::escape_string(query, None, false)
));
// Load page (without history record)
self.load(false);
}
}
};
}
pub fn update(&self) {
// Update components
self.navigation.update(self.progress_fraction());
// @TODO self.content.update();
}
pub fn clean(
&self,
transaction: &Transaction,
app_browser_window_tab_item_id: &i64,
) -> Result<(), String> {
match database::select(transaction, app_browser_window_tab_item_id) {
Ok(records) => {
for record in records {
match database::delete(transaction, &record.id) {
Ok(_) => {
// Delegate clean action to the item childs
self.meta.clean(transaction, &record.id)?;
self.navigation.clean(transaction, &record.id)?;
}
Err(e) => return Err(e.to_string()),
}
}
}
Err(e) => return Err(e.to_string()),
}
Ok(())
}
pub fn restore(
&self,
transaction: &Transaction,
app_browser_window_tab_item_id: &i64,
) -> Result<(), String> {
// Update status
self.meta.set_status(Status::SessionRestore);
// Begin page restore
match database::select(transaction, app_browser_window_tab_item_id) {
Ok(records) => {
for record in records {
// Delegate restore action to the item childs
self.meta.restore(transaction, &record.id)?;
self.navigation.restore(transaction, &record.id)?;
// Make initial page history snap using `navigation` values restored
// * just to have back/forward navigation ability
snap_history(self.navigation.clone());
}
}
Err(e) => return Err(e.to_string()),
}
// Update status
self.meta.set_status(Status::SessionRestored);
Ok(())
}
pub fn save(
&self,
transaction: &Transaction,
app_browser_window_tab_item_id: &i64,
) -> Result<(), String> {
match database::insert(transaction, app_browser_window_tab_item_id) {
Ok(_) => {
let id = database::last_insert_id(transaction);
// Delegate save action to childs
self.meta.save(transaction, &id)?;
self.navigation.save(transaction, &id)?;
}
Err(e) => return Err(e.to_string()),
}
Ok(())
}
// Getters
pub fn progress_fraction(&self) -> Option<f64> {
// Interpret status to progress fraction
match *self.meta.status.borrow() {
Status::Reload | Status::SessionRestore => Some(0.0),
Status::Resolving => Some(0.1),
Status::Resolved => Some(0.2),
Status::Connecting => Some(0.3),
Status::Connected => Some(0.4),
Status::ProxyNegotiating => Some(0.5),
Status::ProxyNegotiated => Some(0.6),
Status::TlsHandshaking => Some(0.7),
Status::TlsHandshaked => Some(0.8),
Status::Complete => Some(0.9),
Status::Failure | Status::Redirect | Status::Success | Status::Input => Some(1.0),
Status::New | Status::SessionRestored => None,
}
}
pub fn is_loading(&self) -> bool {
match self.progress_fraction() {
Some(progress_fraction) => progress_fraction < 1.0,
None => false,
}
}
// Private helpers
// @TODO move outside
fn load_gemini(&self, uri: Uri, is_download: bool, is_source: bool, is_history: bool) {
// Init shared clones
let cancellable = self.client.cancellable();
let update = self.browser_action.update.clone();
let tab_action = self.tab_action.clone();
let navigation = self.navigation.clone();
let content = self.content.clone();
let id = self.id.clone();
let input = self.input.clone();
let meta = self.meta.clone();
// Listen for connection status updates
self.client.gemini.socket.connect_event({
let id = id.clone();
let meta = meta.clone();
let update = update.clone();
move |_, event, _, _| {
meta.set_status(match event {
SocketClientEvent::Resolving => Status::Resolving,
SocketClientEvent::Resolved => Status::Resolved,
SocketClientEvent::Connecting => Status::Connecting,
SocketClientEvent::Connected => Status::Connected,
SocketClientEvent::ProxyNegotiating => Status::ProxyNegotiating,
SocketClientEvent::ProxyNegotiated => Status::ProxyNegotiated,
// TlsHandshaking have effect only for guest connections!
SocketClientEvent::TlsHandshaking => Status::TlsHandshaking,
SocketClientEvent::TlsHandshaked => Status::TlsHandshaked,
SocketClientEvent::Complete => Status::Complete,
_ => todo!(), // notice on API change
});
update.activate(Some(&id));
}
});
// Begin new socket request
self.client.gemini.request_async(
uri.clone(),
Priority::DEFAULT,
cancellable.clone(),
// Search for user certificate match request
match self.profile.identity.gemini.match_scope(&uri.to_string()) {
Some(identity) => match identity.to_tls_certificate() {
Ok(certificate) => Some(certificate),
Err(reason) => todo!("{reason}"),
},
None => None,
},
move |result| match result {
Ok(response) => {
// Route by status
match response.meta.status {
// https://geminiprotocol.net/docs/protocol-specification.gmi#input-expected
gemini::client::connection::response::meta::Status::Input |
gemini::client::connection::response::meta::Status::SensitiveInput => {
// Format response
let status = Status::Input;
let title = match response.meta.data {
Some(data) => data.value,
None => gformat!("Input expected"),
};
// Toggle input form variant
match response.meta.status {
gemini::client::connection::response::meta::Status::SensitiveInput =>
input.set_new_sensitive(
tab_action.clone(),
uri.clone(),
Some(&title),
Some(1024),
),
_ =>
input.set_new_response(
tab_action.clone(),
uri.clone(),
Some(&title),
Some(1024),
),
}
// Update meta
meta.set_status(status)
.set_title(&title);
// Update page
update.activate(Some(&id));
},
// https://geminiprotocol.net/docs/protocol-specification.gmi#status-20
gemini::client::connection::response::meta::Status::Success => {
if is_history {
snap_history(navigation.clone());
}
if is_download {
// Update meta
meta.set_status(Status::Success).set_title("Download");
// Update window
update.activate(Some(&id));
// Init download widget
content.to_status_download(
&uri_to_title(&uri), // grab default filename
&cancellable,
{
let cancellable = cancellable.clone();
move |file, action| {
match file.replace(
None,
false,
gtk::gio::FileCreateFlags::NONE,
Some(&cancellable)
) {
Ok(file_output_stream) => {
gemini::gio::file_output_stream::move_all_from_stream_async(
response.connection.stream(),
file_output_stream,
cancellable.clone(),
Priority::DEFAULT,
(
0x100000, // 1M bytes per chunk
None, // unlimited
0 // initial totals
),
(
// on chunk
{
let action = action.clone();
move |_, total| action.update.activate(
&format!(
"Received {}...",
format_bytes(total)
)
)
},
// on complete
{
let action = action.clone();
move |result| match result {
Ok((_, total)) => action.complete.activate(
&format!("Saved to {} ({total} bytes total)", file.parse_name())
),
Err(e) => action.cancel.activate(&e.to_string())
}
}
)
);
},
Err(e) => action.cancel.activate(&e.to_string())
}
}
}
);
} else { // browse
match response.meta.mime {
Some(gemini::client::connection::response::meta::Mime::TextGemini) => {
// Read entire input stream to buffer
gemini::client::connection::response::data::Text::from_stream_async(
response.connection.stream(),
Priority::DEFAULT,
cancellable.clone(),
{
let content = content.clone();
let id = id.clone();
let meta = meta.clone();
let update = update.clone();
let uri = uri.clone();
move |result|{
match result {
Ok(buffer) => {
// Set children component,
// extract title from meta parsed
let title = if is_source {
content.to_text_source(
&buffer.data
);
uri_to_title(&uri)
} else {
match content.to_text_gemini(
&uri,
&buffer.data
).meta.title {
Some(meta_title) => meta_title,
None => uri_to_title(&uri)
}
};
// Update page meta
meta.set_status(Status::Success)
.set_title(&title);
// Update window components
update.activate(Some(&id));
}
Err(reason) => {
// Define common data
let status = Status::Failure;
let title = "Oops";
let description = reason.to_string();
// Update widget
content
.to_status_failure()
.set_title(title)
.set_description(Some(&description));
// Update meta
meta.set_status(status)
.set_title(title);
// Update window
update.activate(Some(&id));
},
}
}
}
);
},
Some(
gemini::client::connection::response::meta::Mime::ImagePng |
gemini::client::connection::response::meta::Mime::ImageGif |
gemini::client::connection::response::meta::Mime::ImageJpeg |
gemini::client::connection::response::meta::Mime::ImageWebp
) => {
// Final image size unknown, show loading widget
let status = content.to_status_loading(
Some(Duration::from_secs(1)) // show if download time > 1 second
);
// Asynchronously move `InputStream` data from `SocketConnection` into the local `MemoryInputStream`
// this action allows to count the bytes for loading widget and validate max size for incoming data
gemini::gio::memory_input_stream::from_stream_async(
response.connection.stream(),
cancellable.clone(),
Priority::DEFAULT,
0x400, // 1024 bytes per chunk, optional step for images download tracking
0xA00000, // 10M bytes max to prevent memory overflow if server play with promises
move |_, total| {
// Update loading progress
status.set_description(
Some(&gformat!("Download: {total} bytes"))
);
},
{
let cancellable = cancellable.clone();
let content = content.clone();
let id = id.clone();
let meta = meta.clone();
let update = update.clone();
let uri = uri.clone();
move |result| match result {
Ok((memory_input_stream, _)) => {
Pixbuf::from_stream_async(
&memory_input_stream,
Some(&cancellable),
move |result| {
// Process buffer data
match result {
Ok(buffer) => {
// Update page meta
meta.set_status(Status::Success)
.set_title(uri_to_title(&uri).as_str());
// Update page content
content.to_image(&Texture::for_pixbuf(&buffer));
// Update window components
update.activate(Some(&id));
}
Err(reason) => {
// Define common data
let status = Status::Failure;
let title = "Oops";
// Update widget
content
.to_status_failure()
.set_title(title)
.set_description(Some(reason.message()));
// Update meta
meta.set_status(status)
.set_title(title);
}
}
}
);
},
Err(reason) => {
// Define common data
let status = Status::Failure;
let title = "Oops";
let description = reason.to_string();
// Update widget
content
.to_status_failure()
.set_title(title)
.set_description(Some(&description));
// Update meta
meta.set_status(status)
.set_title(title);
}
}
}
);
},
_ => {
// Define common data
let status = Status::Failure;
let title = "Oops";
let description = gformat!("Content type not supported");
// Update widget
content
.to_status_failure()
.set_title(title)
.set_description(Some(&description));
// Update meta
meta.set_status(status)
.set_title(title);
// Update window
update.activate(Some(&id));
},
}
}
},
// https://geminiprotocol.net/docs/protocol-specification.gmi#status-30-temporary-redirection
gemini::client::connection::response::meta::Status::Redirect |
// https://geminiprotocol.net/docs/protocol-specification.gmi#status-31-permanent-redirection
gemini::client::connection::response::meta::Status::PermanentRedirect => {
// Extract redirection URL from response data
match response.meta.data {
Some(unresolved_url) => {
// New URL from server MAY to be relative (according to the protocol specification),
// resolve to absolute URI gobject using current request as the base for parser:
// https://docs.gtk.org/glib/type_func.Uri.resolve_relative.html
match Uri::resolve_relative(
Some(&uri.to_string()),
unresolved_url.value.as_str(),
UriFlags::NONE,
) {
Ok(resolved_url) => {
// Build valid URI from resolved URL string
// this conversion wanted to simply exclude `query` and `fragment` later (as restricted by protocol specification)
match Uri::parse(resolved_url.as_str(), UriFlags::NONE) {
Ok(resolved_uri) => {
// Client MUST prevent external redirects (by protocol specification)
if is_external_uri(&resolved_uri, &uri) {
// Update meta
meta.set_status(Status::Failure)
.set_title("Oops");
// Show placeholder with manual confirmation to continue @TODO status page?
content.to_text_gemini(
&uri,
&gformat!(
"# Redirect issue\n\nExternal redirects not allowed by protocol\n\nContinue:\n\n=> {}",
resolved_uri.to_string()
)
);
// Client MUST limit the number of redirects they follow to 5 (by protocol specification)
} else if meta.redirects() > 5 {
// Update meta
meta.set_status(Status::Failure)
.set_title("Oops");
// Show placeholder with manual confirmation to continue @TODO status page?
content.to_text_gemini(
&uri,
&gformat!(
"# Redirect issue\n\nLimit the number of redirects reached\n\nContinue:\n\n=> {}",
resolved_uri.to_string()
)
);
// Redirection value looks valid, create new redirect (stored in meta `Redirect` holder)
// then call page reload action to apply it by the parental controller
} else {
meta.add_redirect(
// skip query and fragment by protocol requirements
// @TODO review fragment specification
resolved_uri.to_string_partial(
UriHideFlags::FRAGMENT | UriHideFlags::QUERY
),
// referrer
Some(navigation.request.widget.entry.text()),
// set follow policy based on status code
matches!(response.meta.status, gemini::client::connection::response::meta::Status::PermanentRedirect),
)
.set_status(Status::Redirect) // @TODO is this status really wanted?
.set_title("Redirect");
// Reload page to apply redirection (without history record request)
tab_action.load.activate(None, false);
}
},
Err(reason) => {
let status = Status::Failure;
let title = "Oops";
meta.set_status(status)
.set_title(title);
content
.to_status_failure()
.set_title(title)
.set_description(Some(reason.message()));
}
}
}
Err(reason) => {
let status = Status::Failure;
let title = "Oops";
meta.set_status(status)
.set_title(title);
content
.to_status_failure()
.set_title(title)
.set_description(Some(reason.message()));
},
}
},
None => {
let status = Status::Failure;
let title = "Oops";
meta.set_status(status)
.set_title(title);
content
.to_status_failure()
.set_title(title)
.set_description(Some("Redirection target not defined"));
},
}
update.activate(Some(&id));
},
// https://geminiprotocol.net/docs/protocol-specification.gmi#status-60
gemini::client::connection::response::meta::Status::CertificateRequest |
// https://geminiprotocol.net/docs/protocol-specification.gmi#status-61-certificate-not-authorized
gemini::client::connection::response::meta::Status::CertificateUnauthorized |
// https://geminiprotocol.net/docs/protocol-specification.gmi#status-62-certificate-not-valid
gemini::client::connection::response::meta::Status::CertificateInvalid => {
// Define common data
let status = Status::Success;
let title = "Identity";
// Add history record
if is_history {
snap_history(navigation.clone());
}
// Update widget
content
.to_status_identity()
.set_title(title)
.set_description(Some(&match response.meta.data {
Some(data) => data.value,
None => match response.meta.status {
gemini::client::connection::response::meta::Status::CertificateUnauthorized => gformat!("Certificate not authorized"),
gemini::client::connection::response::meta::Status::CertificateInvalid => gformat!("Certificate not valid"),
_ => gformat!("Client certificate required")
},
}));
// Update meta
meta.set_status(status)
.set_title(title);
// Update window
update.activate(Some(&id));
}
_ => {
// Define common data
let status = Status::Failure;
let title = "Oops";
// Add history record
if is_history {
snap_history(navigation.clone());
}
// Update widget
content
.to_status_failure()
.set_title(title)
.set_description(Some(&match response.meta.data {
Some(data) => data.value,
None => gformat!("Status code not supported"),
}));
// Update meta
meta.set_status(status)
.set_title(title);
// Update window
update.activate(Some(&id));
}
}
},
Err(reason) => {
// Define common data
let status = Status::Failure;
let title = "Oops";
let description = reason.to_string();
// Add history record
if is_history {
snap_history(navigation.clone());
}
// Update widget
content
.to_status_failure()
.set_title(title)
.set_description(Some(&description));
// Update meta
meta.set_status(status)
.set_title(title);
// Update window
update.activate(Some(&id));
}
}
);
}
}
// Tools
pub fn migrate(tx: &Transaction) -> Result<(), String> {
// Migrate self components
if let Err(e) = database::init(tx) {
return Err(e.to_string());
}
// Delegate migration to childs
meta::migrate(tx)?;
navigation::migrate(tx)?;
// Success
Ok(())
}
/// Helper function, extract readable title from [Uri](https://docs.gtk.org/glib/struct.Uri.html)
///
/// Useful as common placeholder when page title could not be detected
///
/// * this feature may be improved and moved outside @TODO
fn uri_to_title(uri: &Uri) -> String {
let title = uri.path().split('/').last().unwrap_or_default().to_string();
if title.is_empty() {
match uri.host() {
Some(host) => host.to_string(),
None => "Untitled".to_string(),
}
} else {
title
}
}
/// Compare `subject` with `base`
///
/// Return `false` on scheme, port or host mismatch
fn is_external_uri(subject: &Uri, base: &Uri) -> bool {
if subject.scheme() != base.scheme() {
return true;
}
if subject.port() != base.port() {
return true;
}
subject.host() != base.host()
}
/// Make new history record for given `navigation` object
/// * applies on shared conditions match only
fn snap_history(navigation: Rc<Navigation>) {
let request = navigation.request.widget.entry.text();
// Apply additional filters
if match navigation.history.current() {
Some(current) => current != request,
None => true,
} {
// Add new record match conditions
navigation.history.add(request, true)
}
}
/// Format bytes to KB/MB/GB presentation
fn format_bytes(value: usize) -> String {
if value < 1024 {
format!("{} bytes", value)
} else if value < 1024 * 1024 {
format!("{:.2} KB", value as f64 / 1024.0)
} else if value < 1024 * 1024 * 1024 {
format!("{:.2} MB", value as f64 / (1024.0 * 1024.0))
} else {
format!("{:.2} GB", value as f64 / (1024.0 * 1024.0 * 1024.0))
}
}