-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathwebframe.rs
1394 lines (1302 loc) · 46 KB
/
webframe.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
/*
* Copyright 2021 Miklos Vajna
*
* SPDX-License-Identifier: MIT
*/
#![deny(warnings)]
#![warn(clippy::all)]
#![warn(missing_docs)]
//! The webframe module provides the header, toolbar and footer code.
use crate::areas;
use crate::context;
use crate::cron;
use crate::i18n::translate as tr;
use crate::stats;
use crate::util;
use crate::yattag;
use anyhow::Context;
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::Read;
use std::ops::DerefMut;
use std::rc::Rc;
/// Produces the end of the page.
pub fn get_footer(last_updated: &str) -> yattag::Doc {
let mut items: Vec<yattag::Doc> = Vec::new();
{
let doc = yattag::Doc::new();
doc.text(&tr("Version: "));
doc.append_value(
util::git_link(
git_version::git_version!(args = ["--always", "--long"]),
"https://github.com/vmiklos/osm-gimmisn/commit/",
)
.get_value(),
);
items.push(doc);
items.push(yattag::Doc::from_text(&tr(
"OSM data © OpenStreetMap contributors.",
)));
if !last_updated.is_empty() {
items.push(yattag::Doc::from_text(
&(tr("Last update: ") + last_updated),
));
}
}
let doc = yattag::Doc::new();
doc.stag("hr");
{
let div = doc.tag("div", &[]);
for (index, item) in items.iter().enumerate() {
if index > 0 {
div.text(" ¦ ");
}
div.append_value(item.get_value());
}
}
doc
}
/// Fills items with function-specific links in the header. Returns the extended list.
fn fill_header_function(
ctx: &context::Context,
function: &str,
relation_name: &str,
items: &[yattag::Doc],
) -> anyhow::Result<Vec<yattag::Doc>> {
let mut items: Vec<yattag::Doc> = items.to_vec();
let prefix = ctx.get_ini().get_uri_prefix();
if function == "missing-housenumbers" {
// The OSM data source changes much more frequently than the ref one, so add a dedicated link
// to update OSM house numbers first.
let doc = yattag::Doc::new();
{
let span = doc.tag("span", &[("id", "trigger-street-housenumbers-update")]);
{
// TODO consider using HTTP POST here, see
// https://stackoverflow.com/questions/1367409/how-to-make-button-look-like-a-link
let a = span.tag(
"a",
&[(
"href",
&format!("{prefix}/street-housenumbers/{relation_name}/update-result"),
)],
);
a.text(&tr("Update from OSM"));
}
}
items.push(doc);
} else if function == "missing-streets" || function == "additional-streets" {
// The OSM data source changes much more frequently than the ref one, so add a dedicated link
// to update OSM streets first.
let doc = yattag::Doc::new();
{
let span = doc.tag("span", &[("id", "trigger-streets-update")]);
{
let a = span.tag(
"a",
&[(
"href",
&format!("{prefix}/streets/{relation_name}/update-result"),
)],
);
a.text(&tr("Update from OSM"));
}
}
items.push(doc);
} else if function == "street-housenumbers" {
let doc = yattag::Doc::new();
{
let span = doc.tag("span", &[("id", "trigger-street-housenumbers-update")]);
{
let a = span.tag(
"a",
&[(
"href",
&format!("{prefix}/street-housenumbers/{relation_name}/update-result"),
)],
);
a.text(&tr("Call Overpass to update"));
}
}
items.push(doc);
let doc = yattag::Doc::new();
{
let a = doc.tag(
"a",
&[(
"href",
&format!("{prefix}/street-housenumbers/{relation_name}/view-query"),
)],
);
a.text(&tr("View query"));
}
items.push(doc);
} else if function == "streets" {
let doc = yattag::Doc::new();
{
let span = doc.tag("span", &[("id", "trigger-streets-update")]);
{
let a = span.tag(
"a",
&[(
"href",
&format!("{prefix}/streets/{relation_name}/update-result"),
)],
);
a.text(&tr("Call Overpass to update"));
}
}
items.push(doc);
let doc = yattag::Doc::new();
{
let a = doc.tag(
"a",
&[(
"href",
&format!("{prefix}/streets/{relation_name}/view-query"),
)],
);
a.text(&tr("View query"));
}
items.push(doc);
} else if function == "invalid-addr-cities" {
let doc = yattag::Doc::new();
{
let span = doc.tag("span", &[("id", "trigger-invalid-addr-cities-update")]);
{
let a = span.tag(
"a",
&[(
"href",
&format!("{prefix}/lints/whole-country/invalid-addr-cities/update-result"),
)],
);
a.text(&tr("Update from OSM"));
}
}
items.push(doc);
}
Ok(items)
}
/// Generates the 'missing house numbers/streets' part of the header.
fn fill_missing_header_items(
ctx: &context::Context,
streets: &str,
additional_housenumbers: bool,
relation_name: &str,
items: &[yattag::Doc],
) -> anyhow::Result<Vec<yattag::Doc>> {
let mut items: Vec<yattag::Doc> = items.to_vec();
let prefix = ctx.get_ini().get_uri_prefix();
if streets != "only" {
let doc = yattag::Doc::new();
{
let a = doc.tag(
"a",
&[(
"href",
&format!("{prefix}/missing-housenumbers/{relation_name}/view-result"),
)],
);
a.text(&tr("Missing house numbers"));
}
items.push(doc);
if additional_housenumbers {
let doc = yattag::Doc::new();
{
let a = doc.tag(
"a",
&[(
"href",
&format!("{prefix}/additional-housenumbers/{relation_name}/view-result"),
)],
);
a.text(&tr("Additional house numbers"));
}
items.push(doc);
}
}
if streets != "no" {
let doc = yattag::Doc::new();
{
let a = doc.tag(
"a",
&[(
"href",
&format!("{prefix}/missing-streets/{relation_name}/view-result"),
)],
);
a.text(&tr("Missing streets"));
}
items.push(doc);
let doc = yattag::Doc::new();
{
let a = doc.tag(
"a",
&[(
"href",
&format!("{prefix}/additional-streets/{relation_name}/view-result"),
)],
);
a.text(&tr("Additional streets"));
}
items.push(doc);
}
Ok(items)
}
/// Generates the 'existing house numbers/streets' part of the header.
fn fill_existing_header_items(
ctx: &context::Context,
streets: &str,
relation_name: &str,
items: &[yattag::Doc],
) -> anyhow::Result<Vec<yattag::Doc>> {
let mut items: Vec<yattag::Doc> = items.to_vec();
let prefix = ctx.get_ini().get_uri_prefix();
if streets != "only" {
let doc = yattag::Doc::new();
{
let a = doc.tag(
"a",
&[(
"href",
&format!("{prefix}/street-housenumbers/{relation_name}/view-result"),
)],
);
a.text(&tr("Existing house numbers"));
}
items.push(doc);
}
let doc = yattag::Doc::new();
{
let a = doc.tag(
"a",
&[(
"href",
&format!("{prefix}/streets/{relation_name}/view-result"),
)],
);
a.text(&tr("Existing streets"));
}
items.push(doc);
Ok(items)
}
/// Emit localized strings for JS purposes.
pub fn emit_l10n_strings_for_js(doc: &yattag::Doc, string_pairs: &[(&str, String)]) {
let div = doc.tag("div", &[("style", "display: none;")]);
for (key, value) in string_pairs {
let div = div.tag("div", &[("id", key), ("data-value", value)]);
drop(div);
}
}
/// Produces the start of the page. Note that the content depends on the function and the
/// relation, but not on the action to keep a balance between too generic and too specific
/// content.
pub fn get_toolbar(
ctx: &context::Context,
relations: Option<&mut areas::Relations<'_>>,
function: &str,
relation_name: &str,
relation_osmid: u64,
) -> anyhow::Result<yattag::Doc> {
let mut items: Vec<yattag::Doc> = Vec::new();
let mut streets: String = "".into();
let mut additional_housenumbers = false;
if let Some(relations) = relations {
if !relation_name.is_empty() {
let relation = relations.get_relation(relation_name)?;
streets = relation.get_config().should_check_missing_streets();
additional_housenumbers = relation.get_config().should_check_additional_housenumbers();
}
}
let doc = yattag::Doc::new();
{
let a = doc.tag("a", &[("href", &(ctx.get_ini().get_uri_prefix() + "/"))]);
a.text(&tr("Area list"))
}
items.push(doc);
if !relation_name.is_empty() {
items = fill_missing_header_items(
ctx,
&streets,
additional_housenumbers,
relation_name,
&items,
)?;
}
items = fill_header_function(ctx, function, relation_name, &items)?;
if !relation_name.is_empty() {
items = fill_existing_header_items(ctx, &streets, relation_name, &items)?;
}
let doc = yattag::Doc::new();
let string_pairs = &[
("str-toolbar-overpass-wait", tr("Waiting for Overpass...")),
("str-toolbar-overpass-error", tr("Error from Overpass: ")),
(
"str-toolbar-reference-wait",
tr("Creating from reference..."),
),
("str-toolbar-reference-error", tr("Error from reference: ")),
];
emit_l10n_strings_for_js(&doc, string_pairs);
{
let a = doc.tag("a", &[("href", "https://overpass-turbo.eu/")]);
a.text(&tr("Overpass turbo"));
}
items.push(doc);
let doc = yattag::Doc::new();
if relation_osmid > 0 {
{
let a = doc.tag(
"a",
&[(
"href",
&format!("https://www.openstreetmap.org/relation/{relation_osmid}"),
)],
);
a.text(&tr("Area boundary"))
}
items.push(doc);
} else {
// These are on the main page only.
{
let a = doc.tag(
"a",
&[(
"href",
&(ctx.get_ini().get_uri_prefix() + "/housenumber-stats/whole-country/"),
)],
);
a.text(&tr("Statistics"));
}
items.push(doc);
let doc = yattag::Doc::new();
{
let a = doc.tag(
"a",
&[(
"href",
&(ctx.get_ini().get_uri_prefix() + "/lints/whole-country/"),
)],
);
a.text(&tr("Lints"));
}
items.push(doc);
let doc = yattag::Doc::new();
{
let a = doc.tag("a", &[("href", &tr("https://vmiklos.hu/osm-gimmisn"))]);
a.text(&tr("Documentation"));
}
items.push(doc);
}
let doc = yattag::Doc::new();
{
let div = doc.tag("div", &[("id", "toolbar")]);
for (index, item) in items.iter().enumerate() {
if index > 0 {
div.text(" ¦ ");
}
div.append_value(item.get_value());
}
}
doc.stag("hr");
Ok(doc)
}
pub type Headers = Vec<(Cow<'static, str>, Cow<'static, str>)>;
/// Handles serving static content.
pub fn handle_static(
ctx: &context::Context,
request_uri: &str,
) -> anyhow::Result<(Vec<u8>, String, Headers)> {
let mut tokens = request_uri.split('/');
let path = tokens.next_back().context("next_back() failed")?;
let extra_headers = Vec::new();
if request_uri.ends_with(".js") {
let content_type = "application/x-javascript; charset=utf-8";
let (content, extra_headers) =
get_content_with_meta(ctx, &ctx.get_abspath(&format!("target/browser/{path}")))?;
return Ok((content, content_type.into(), extra_headers));
}
if request_uri.ends_with(".css") {
let content_type = "text/css; charset=utf-8";
let (content, extra_headers) =
get_content_with_meta(ctx, &ctx.get_abspath(&format!("target/browser/{path}")))
.context("get_content_with_meta() failed")?;
return Ok((content, content_type.into(), extra_headers));
}
if request_uri.ends_with(".json") {
let content_type = "application/json; charset=utf-8";
let (content, extra_headers) = get_content_with_meta(
ctx,
&format!("{}/stats/{}", ctx.get_ini().get_workdir(), path),
)?;
return Ok((content, content_type.into(), extra_headers));
}
if request_uri.ends_with(".ico") {
let content_type = "image/x-icon";
let (content, extra_headers) = get_content_with_meta(ctx, &ctx.get_abspath(path))?;
return Ok((content, content_type.into(), extra_headers));
}
if request_uri.ends_with(".svg") {
let content_type = "image/svg+xml; charset=utf-8";
let (content, extra_headers) = get_content_with_meta(ctx, &ctx.get_abspath(path))?;
return Ok((content, content_type.into(), extra_headers));
}
let bytes: Vec<u8> = Vec::new();
Ok((bytes, "".into(), extra_headers))
}
/// Displays an unhandled error on the page.
pub fn handle_error(request: &rouille::Request, error: &str) -> rouille::Response {
if request.url().ends_with(".json") {
let mut ret: HashMap<String, String> = HashMap::new();
ret.insert("error".into(), error.into());
return rouille::Response::json(&ret);
}
let doc = yattag::Doc::new();
util::write_html_header(&doc);
{
let pre = doc.tag("pre", &[]);
let url = request.url();
pre.text(&format!(
"{}\n",
tr("Internal error when serving {0}").replace("{0}", &url)
));
pre.text(error);
}
make_response(
500_u16,
vec![("Content-type".into(), "text/html; charset=utf-8".into())],
doc.get_value().as_bytes().to_vec(),
)
}
/// Displays a not-found page.
pub fn handle_404() -> yattag::Doc {
let doc = yattag::Doc::new();
util::write_html_header(&doc);
{
let html = doc.tag("html", &[]);
{
let body = html.tag("body", &[]);
{
let h1 = body.tag("h1", &[]);
h1.text(&tr("Not Found"));
}
{
let p = doc.tag("p", &[]);
p.text(&tr("The requested URL was not found on this server."));
}
}
}
doc
}
/// Formats timestamp as UI date-time.
pub fn format_timestamp(timestamp: &time::OffsetDateTime) -> anyhow::Result<String> {
let format = time::format_description::parse("[year]-[month]-[day] [hour]:[minute]")?;
Ok(timestamp.format(&format)?)
}
/// Expected request_uri: e.g. /osm/housenumber-stats/whole-country/cityprogress.
fn handle_stats_cityprogress(
ctx: &context::Context,
relations: &mut areas::Relations<'_>,
) -> anyhow::Result<yattag::Doc> {
let doc = yattag::Doc::new();
doc.append_value(
get_toolbar(
ctx,
Some(relations),
/*function=*/ "",
/*relation_name=*/ "",
/*relation_osmid=*/ 0,
)?
.get_value(),
);
let mut ref_citycounts: HashMap<String, u64> = HashMap::new();
let csv_stream: Rc<RefCell<dyn Read>> = ctx
.get_file_system()
.open_read(&ctx.get_ini().get_reference_citycounts_path()?)?;
let mut guard = csv_stream.borrow_mut();
let mut read = guard.deref_mut();
let mut csv_reader = util::make_csv_reader(&mut read);
for result in csv_reader.deserialize() {
let row: util::CityCount = result?;
ref_citycounts.insert(row.city, row.count);
}
let date_time = ctx.get_time().now();
let format = time::format_description::parse("[year]-[month]-[day]")?;
let today = date_time.format(&format)?;
let mut osm_citycounts: HashMap<String, u64> = HashMap::new();
let conn = ctx.get_database_connection()?;
let mut stmt = conn.prepare("select city, count from stats_citycounts where date = ?1")?;
let mut rows = stmt.query([&today])?;
while let Some(row) = rows.next()? {
let city: String = row.get(0).unwrap();
let count: String = row.get(1).unwrap();
osm_citycounts.insert(city, count.parse()?);
}
let ref_cities: Vec<_> = ref_citycounts
.keys()
.map(|k| util::Street::from_string(k))
.collect();
let osm_cities: Vec<_> = osm_citycounts
.keys()
.map(|k| util::Street::from_string(k))
.collect();
let in_both = util::get_in_both(&ref_cities, &osm_cities);
let mut cities: Vec<_> = in_both.iter().map(|i| i.get_osm_name()).collect();
cities.sort_by_key(|i| util::get_sort_key(i));
let mut table: Vec<Vec<yattag::Doc>> = vec![vec![
yattag::Doc::from_text(&tr("City name")),
yattag::Doc::from_text(&tr("House number coverage")),
yattag::Doc::from_text(&tr("OSM count")),
yattag::Doc::from_text(&tr("Reference count")),
]];
for city in cities {
let mut percent = 100_f64;
if ref_citycounts[city] > 0 && osm_citycounts[city] < ref_citycounts[city] {
let osm_count = osm_citycounts[city] as f64;
let ref_count = ref_citycounts[city] as f64;
percent = osm_count / ref_count * 100_f64;
}
let percent = util::format_percent(percent).context("util::format_percent() failed:")?;
table.push(vec![
yattag::Doc::from_text(city),
yattag::Doc::from_text(&percent),
yattag::Doc::from_text(&osm_citycounts[city].to_string()),
yattag::Doc::from_text(&ref_citycounts[city].to_string()),
]);
}
doc.append_value(util::html_table_from_list(&table).get_value());
{
let h2 = doc.tag("h2", &[]);
h2.text(&tr("Note"));
}
{
let div = doc.tag("div", &[]);
div.text(&tr(
r#"These statistics are estimates, not taking house number filters into account.
Only cities with house numbers in OSM are considered."#,
));
}
doc.append_value(get_footer(/*last_updated=*/ "").get_value());
Ok(doc)
}
/// Expected request_uri: e.g. /osm/housenumber-stats/whole-country/housenumberless-settlements.
fn handle_stats_housenumberless(
ctx: &context::Context,
relations: &mut areas::Relations<'_>,
) -> anyhow::Result<yattag::Doc> {
let doc = yattag::Doc::new();
doc.append_value(
get_toolbar(
ctx,
Some(relations),
/*function=*/ "",
/*relation_name=*/ "",
/*relation_osmid=*/ 0,
)?
.get_value(),
);
let query = areas::make_turbo_query_for_housenumberless(ctx)?;
{
let pre = doc.tag("pre", &[]);
pre.text(&query);
}
let format = tr("{0} (osm), {1} (areas)");
let osm = format_timestamp(&stats::get_sql_mtime(ctx, "whole-country/osm-base")?)?;
let areas = format_timestamp(&stats::get_sql_mtime(ctx, "whole-country/areas-base")?)?;
let last_updated = format.replace("{0}", &osm).replace("{1}", &areas);
doc.append_value(get_footer(&last_updated).get_value());
Ok(doc)
}
/// Expected request_uri: e.g. /osm/housenumber-stats/whole-country/zipprogress.
fn handle_stats_zipprogress(
ctx: &context::Context,
relations: &mut areas::Relations<'_>,
) -> anyhow::Result<yattag::Doc> {
let doc = yattag::Doc::new();
doc.append_value(
get_toolbar(
ctx,
Some(relations),
/*function=*/ "",
/*relation_name=*/ "",
/*relation_osmid=*/ 0,
)?
.get_value(),
);
let mut ref_zipcounts: HashMap<String, u64> = HashMap::new();
let csv_stream: Rc<RefCell<dyn Read>> = ctx
.get_file_system()
.open_read(&ctx.get_ini().get_reference_zipcounts_path()?)?;
let mut guard = csv_stream.borrow_mut();
let mut read = guard.deref_mut();
let mut csv_reader = util::make_csv_reader(&mut read);
for result in csv_reader.deserialize() {
let row: util::ZipCount = result?;
ref_zipcounts.insert(row.zip, row.count);
}
let now = ctx.get_time().now();
let format = time::format_description::parse("[year]-[month]-[day]")?;
let today = now.format(&format)?;
let mut osm_zipcounts: HashMap<String, u64> = HashMap::new();
let conn = ctx.get_database_connection()?;
let mut stmt = conn.prepare("select zip, count from stats_zipcounts where date = ?1")?;
let mut rows = stmt.query([&today])?;
while let Some(row) = rows.next()? {
let zip: String = row.get(0).unwrap();
let count: String = row.get(1).unwrap();
osm_zipcounts.insert(zip, count.parse()?);
}
let ref_zips: Vec<_> = ref_zipcounts
.keys()
.map(|k| util::Street::from_string(k))
.collect();
let osm_zips: Vec<_> = osm_zipcounts
.keys()
.map(|k| util::Street::from_string(k))
.collect();
let in_both = util::get_in_both(&ref_zips, &osm_zips);
let mut zips: Vec<_> = in_both.iter().map(|i| i.get_osm_name()).collect();
zips.sort_by_key(|i| util::get_sort_key(i));
let mut table: Vec<Vec<yattag::Doc>> = vec![vec![
yattag::Doc::from_text(&tr("ZIP code")),
yattag::Doc::from_text(&tr("House number coverage")),
yattag::Doc::from_text(&tr("OSM count")),
yattag::Doc::from_text(&tr("Reference count")),
]];
for zip in zips {
let mut percent = 100_f64;
if *ref_zipcounts.get(zip).unwrap() > 0
&& osm_zipcounts.get(zip).unwrap() < ref_zipcounts.get(zip).unwrap()
{
let osm_count = osm_zipcounts[zip] as f64;
let ref_count = ref_zipcounts[zip] as f64;
percent = osm_count / ref_count * 100_f64;
}
let percent = util::format_percent(percent).context("util::format_percent() failed:")?;
table.push(vec![
yattag::Doc::from_text(zip),
yattag::Doc::from_text(&percent),
yattag::Doc::from_text(&osm_zipcounts.get(zip).unwrap().to_string()),
yattag::Doc::from_text(&ref_zipcounts.get(zip).unwrap().to_string()),
]);
}
doc.append_value(util::html_table_from_list(&table).get_value());
{
let h2 = doc.tag("h2", &[]);
h2.text(&tr("Note"));
}
{
let div = doc.tag("div", &[]);
div.text(&tr(
r#"These statistics are estimates, not taking house number filters into account.
Only zip codes with house numbers in OSM are considered."#,
));
}
doc.append_value(get_footer(/*last_updated=*/ "").get_value());
Ok(doc)
}
/// Gets the update date of the whole country.
fn get_whole_county_last_modified(ctx: &context::Context) -> anyhow::Result<String> {
let format = tr("{0} (osm), {1} (areas)");
let osm = format_timestamp(&stats::get_sql_mtime(ctx, "whole-country/osm-base")?)?;
let areas = format_timestamp(&stats::get_sql_mtime(ctx, "whole-country/areas-base")?)?;
Ok(format.replace("{0}", &osm).replace("{1}", &areas))
}
/// Expected request uri: /housenumber-stats/whole-country/invalid-addr-cities.
fn handle_invalid_addr_cities(
ctx: &context::Context,
relations: &mut areas::Relations<'_>,
) -> anyhow::Result<yattag::Doc> {
let doc = yattag::Doc::new();
doc.append_value(
get_toolbar(
ctx,
Some(relations),
/*function=*/ "invalid-addr-cities",
/*relation_name=*/ "",
/*relation_osmid=*/ 0,
)?
.get_value(),
);
let mut table: Vec<Vec<yattag::Doc>> = Vec::new();
let mut count = 0;
{
let conn = ctx.get_database_connection()?;
let mut stmt = conn
.prepare("select osm_id, osm_type, postcode, city, street, housenumber, user, timestamp, fixme from stats_invalid_addr_cities")?;
let mut invalids = stmt.query([])?;
{
let cells: Vec<yattag::Doc> = vec![
yattag::Doc::from_text(&tr("Identifier")),
yattag::Doc::from_text(&tr("Type")),
yattag::Doc::from_text(&tr("Postcode")),
yattag::Doc::from_text(&tr("City")),
yattag::Doc::from_text(&tr("Street")),
yattag::Doc::from_text(&tr("Housenumber")),
yattag::Doc::from_text(&tr("User")),
yattag::Doc::from_text(&tr("Timestamp")),
yattag::Doc::from_text(&tr("Fixme")),
];
table.push(cells);
}
while let Some(invalid) = invalids.next()? {
let mut cells: Vec<yattag::Doc> = Vec::new();
let osm_id: String = invalid.get(0).unwrap();
let osm_type: String = invalid.get(1).unwrap();
{
let cell = yattag::Doc::new();
let href = format!("https://www.openstreetmap.org/{osm_type}/{osm_id}");
{
let a = cell.tag("a", &[("href", href.as_str()), ("target", "_blank")]);
a.text(&osm_id.to_string());
}
cells.push(cell);
}
cells.push(yattag::Doc::from_text(&osm_type));
let postcode: String = invalid.get(2).unwrap();
cells.push(yattag::Doc::from_text(&postcode));
let city: String = invalid.get(3).unwrap();
cells.push(yattag::Doc::from_text(&city));
let street: String = invalid.get(4).unwrap();
cells.push(yattag::Doc::from_text(&street));
let housenumber: String = invalid.get(5).unwrap();
cells.push(yattag::Doc::from_text(&housenumber));
let user: String = invalid.get(6).unwrap();
cells.push(yattag::Doc::from_text(&user));
let timestamp: String = invalid.get(7).unwrap();
cells.push(yattag::Doc::from_text(×tamp));
let fixme: String = invalid.get(8).unwrap();
cells.push(yattag::Doc::from_text(&fixme));
table.push(cells);
count += 1;
}
}
{
let p = doc.tag("p", &[]);
p.text(
&tr("The addr:city key of the below {0} objects probably has an invalid value.")
.replace("{0}", &count.to_string()),
);
}
doc.append_value(util::html_table_from_list(&table).get_value());
doc.append_value(get_footer(&get_whole_county_last_modified(ctx)?).get_value());
Ok(doc)
}
fn handle_invalid_addr_cities_update(ctx: &context::Context) -> anyhow::Result<()> {
cron::update_stats_overpass(ctx).context("update_stats_overpass failed")?;
stats::update_invalid_addr_cities(ctx).context("update_invalid_addr_cities failed")?;
Ok(())
}
/// Expected request uri: /lints/whole-country/invalid-addr-cities/update-result.json.
pub fn handle_invalid_addr_cities_update_json(ctx: &context::Context) -> anyhow::Result<String> {
handle_invalid_addr_cities_update(ctx).context("handle_invalid_addr_cities_update failed")?;
let mut ret: HashMap<String, String> = HashMap::new();
ret.insert("error".into(), "".into());
Ok(serde_json::to_string(&ret)?)
}
/// Expected request uri: /lints/whole-country/invalid-addr-cities/update-result.
fn handle_invalid_addr_cities_update_html(
ctx: &context::Context,
relations: &mut areas::Relations<'_>,
) -> anyhow::Result<yattag::Doc> {
handle_invalid_addr_cities_update(ctx)?;
let doc = yattag::Doc::new();
doc.append_value(
get_toolbar(
ctx,
Some(relations),
/*function=*/ "",
/*relation_name=*/ "",
/*relation_osmid=*/ 0,
)?
.get_value(),
);
doc.text(&tr("Update successful: "));
let prefix = ctx.get_ini().get_uri_prefix();
let link = format!("{prefix}/lints/whole-country/invalid-addr-cities");
doc.append_value(util::gen_link(&link, &tr("View updated result")).get_value());
doc.append_value(get_footer(&get_whole_county_last_modified(ctx)?).get_value());
Ok(doc)
}
/// Expected request_uri: e.g. /osm/lints/whole-country/invalid-relations."""
fn handle_invalid_refstreets(
ctx: &context::Context,
relations: &mut areas::Relations<'_>,
) -> anyhow::Result<yattag::Doc> {
let doc = yattag::Doc::new();
doc.append_value(
get_toolbar(
ctx,
Some(relations),
/*function=*/ "",
/*relation_name=*/ "",
/*relation_osmid=*/ 0,
)?
.get_value(),
);
let prefix = ctx.get_ini().get_uri_prefix();
for relation in relations.get_relations()? {
if !stats::has_sql_mtime(ctx, &format!("streets/{}", relation.get_name())).unwrap() {
continue;
}
let (osm_invalids, ref_invalids) = relation
.get_invalid_refstreets()
.context("get_invalid_refstreets() failed")?;
let key_invalids = relation.get_invalid_filter_keys()?;
if osm_invalids.is_empty() && ref_invalids.is_empty() && key_invalids.is_empty() {
continue;
}
{
let h1 = doc.tag("h1", &[]);
let relation_name = relation.get_name();
{
let a = h1.tag(
"a",
&[(
"href",
&format!("{prefix}/streets/{relation_name}/view-result"),
)],
);
a.text(&relation_name);
}
}
doc.append_value(
util::invalid_refstreets_to_html(&osm_invalids, &ref_invalids).get_value(),
);
doc.append_value(util::invalid_filter_keys_to_html(&key_invalids).get_value());
}
doc.append_value(get_footer(/*last_updated=*/ "").get_value());
Ok(doc)
}
/// Expected request_uri: e.g. /osm/housenumber-stats/whole-country/.
pub fn handle_stats(
ctx: &context::Context,
relations: &mut areas::Relations<'_>,
request_uri: &str,
) -> anyhow::Result<yattag::Doc> {
if request_uri.ends_with("/cityprogress") {
return handle_stats_cityprogress(ctx, relations)
.context("handle_stats_cityprogress() failed");
}
if request_uri.ends_with("/zipprogress") {
return handle_stats_zipprogress(ctx, relations)
.context("handle_stats_zipprogress() failed");
}
if request_uri.ends_with("/housenumberless-settlements") {
return handle_stats_housenumberless(ctx, relations)
.context("handle_stats_housenumberless() failed");
}
let doc = yattag::Doc::new();
doc.append_value(
get_toolbar(
ctx,
Some(relations),
/*function=*/ "",
/*relation_name=*/ "",
/*relation_osmid=*/ 0,
)?
.get_value(),
);
let prefix = ctx.get_ini().get_uri_prefix();
let string_pairs = &[
(
"str-daily-title",
tr("New house numbers, last 2 weeks, as of {}"),
),
("str-daily-x-axis", tr("During this day")),
("str-daily-y-axis", tr("New house numbers")),
(
"str-monthly-title",
tr("New house numbers, last year, as of {}"),
),
("str-monthly-x-axis", tr("During this month")),
("str-monthly-y-axis", tr("New house numbers")),
(
"str-monthlytotal-title",
tr("All house numbers, last year, as of {}"),
),
("str-monthlytotal-x-axis", tr("Latest for this month")),
("str-monthlytotal-y-axis", tr("All house numbers")),
(
"str-dailytotal-title",
tr("All house numbers, last 2 weeks, as of {}"),
),
("str-dailytotal-x-axis", tr("At the start of this day")),
("str-dailytotal-y-axis", tr("All house numbers")),
(
"str-topusers-title",
tr("Top house number editors, as of {}"),
),
("str-topusers-x-axis", tr("User name")),
(
"str-topusers-y-axis",
tr("Number of house numbers last changed by this user"),
),
("str-topcities-title", tr("Top edited cities, as of {}")),
("str-topcities-x-axis", tr("City name")),
(
"str-topcities-y-axis",
tr("Number of house numbers added in the past 30 days"),