-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchicha-isotope-map.go
More file actions
8566 lines (7832 loc) · 267 KB
/
Copy pathchicha-isotope-map.go
File metadata and controls
8566 lines (7832 loc) · 267 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
//new: stream markers by track
package main
import (
// http://localhost:8765/debug/pprof/profile?seconds=30
// go tool pprof -http=:8080 Downloads/profile
//_ "net/http/pprof"
"archive/tar"
"archive/zip"
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/tls"
"database/sql"
"embed"
"encoding/csv"
"encoding/json"
"encoding/xml"
"errors"
"flag"
"fmt"
"golang.org/x/crypto/acme/autocert"
"html"
"html/template"
"image/color"
"io"
"io/fs"
"io/ioutil"
"log"
"math"
"math/rand"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"syscall"
"time"
"chicha-isotope-map/pkg/analytics"
"chicha-isotope-map/pkg/api"
"chicha-isotope-map/pkg/atomfastimport"
"chicha-isotope-map/pkg/cimimport"
"chicha-isotope-map/pkg/database"
"chicha-isotope-map/pkg/database/drivers"
"chicha-isotope-map/pkg/desktop"
"chicha-isotope-map/pkg/jsonarchive"
"chicha-isotope-map/pkg/logger"
"chicha-isotope-map/pkg/qrlogoext"
safecastrealtime "chicha-isotope-map/pkg/safecast-realtime"
"chicha-isotope-map/pkg/safecastimport"
"chicha-isotope-map/pkg/setupwizard"
"chicha-isotope-map/pkg/spectrum"
)
// content bundles the UI and the license texts so single-file binaries still
// expose the legal notice when served offline. Embedding keeps deployment
// simple and mirrors the "A little copying is better than a little dependency"
// proverb by avoiding extra runtime file IO.
//
//go:embed public_html/* LICENSE LICENSE.CC0
var content embed.FS
var doseData database.Data
var domain = flag.String("domain", "", "Serve HTTPS on 80/443 via Let's Encrypt when a domain is provided.")
var dbType = flag.String("db-type", "sqlite", "Database driver: chai, sqlite, duckdb, pgx (PostgreSQL), or clickhouse")
var dbPath = flag.String("db-path", "", "Filesystem path for chai/sqlite/duckdb databases; defaults to the working directory.")
var dbConn = flag.String("db-conn", "", "Connection URI for network databases.\n PostgreSQL: postgres://user:pass@host:5432/<database>?sslmode=verify-full\n ClickHouse: clickhouse://user:pass@host:9000/<database>?secure=true")
var port = flag.Int("port", 8765, "Port for running the HTTP server when not using -domain.")
var version = flag.Bool("version", false, "Show the application version")
var defaultLat = flag.Float64("default-lat", 44.08832, "Default map latitude")
var defaultLon = flag.Float64("default-lon", 42.97577, "Default map longitude")
var defaultZoom = flag.Int("default-zoom", 11, "Default map zoom")
// mapboxToken lets operators wire in Mapbox tiles without hardcoding secrets into HTML.
var mapboxToken = flag.String("mapbox-token", "", "Mapbox access token used for the optional Mapbox Satellite base layer")
var defaultLayer = flag.String("default-layer", "OpenStreetMap", `Default base layer: "OpenStreetMap", "Google Satellite", or "Mapbox Satellite"`)
var autoLocateDefault = flag.Bool("auto-locate-default", true, "Auto-center initial map view using browser or GeoIP fallbacks when no URL bounds are provided.")
var safecastRealtimeEnabled = flag.Bool("safecast-realtime", false, "Enable polling and display of Safecast realtime devices")
// Keep the default UI toggle explicit so operators can expose realtime data without auto-enabling it.
var safecastRealtimeDefault = flag.Bool("safecast-realtime-default", false, "Show Safecast realtime markers by default when realtime polling is enabled")
var importSourcesFlag = flag.String("import", "", "Enable importers: safecast, atomfast, safecast,atomfast, or all")
var jsonArchivePathFlag = flag.String("json-archive-path", "", "Filesystem destination for the generated JSON archive tgz bundle")
var jsonArchiveFrequencyFlag = flag.String("json-archive-frequency", "weekly", "How often to rebuild the JSON archive: daily, weekly, monthly, or yearly")
var importTGZURLFlag = flag.String("import-tgz-url", "", "Download and import a remote .tgz of exported JSON files, log progress, and exit once finished. Example: https://pelora.org/api/json/weekly.tgz")
var importTGZFileFlag = flag.String("import-tgz-file", "", "Import a local .tgz of exported JSON files, log progress, and exit once finished.")
var supportEmail = flag.String("support-email", "", "Contact e-mail shown in the legal notice for feedback")
var logoPath = flag.String("logo-path", "", "Filesystem path to a custom logo image that replaces the default branding.")
var logoLink = flag.String("logo-link", "", "Destination URL for the logo link; defaults to the Chicha Isotope Map GitHub repository.")
var desktopMode = flag.Bool("desktop", desktop.DefaultEnabled(), "Run as desktop app with an embedded webview window (build with -tags desktop).")
// setupWizardEnabled is registered only on Linux so other platforms avoid unusable
// flags. We keep the pointer nullable to preserve zero-value semantics without extra
// globals, following the "Make the zero value useful" proverb.
var setupWizardEnabled = registerSetupFlag()
const chichaGitHubURL = "https://github.com/matveynator/chicha-isotope-map"
// logoAsset stores an in-memory custom logo so we can serve it without
// filesystem reads on every request.
type logoAsset struct {
Data []byte
ContentType string
ModTime time.Time
}
// logoConfig captures the resolved UI branding choices to keep handlers lean.
type logoConfig struct {
ImageURL string
LinkURL string
ShowGithubLinkTooltip bool
}
var (
activeLogoConfig logoConfig
customLogoAsset *logoAsset
analyticsService *analytics.Service
)
// usageSection groups CLI flags so operators can scan help output quickly. This keeps
// the help text approachable without duplicating flag registration everywhere.
type usageSection struct {
Key string
Flags []string
}
const (
cliSectionGeneral = "general"
cliSectionDatabase = "database"
cliSectionAppearance = "appearance"
cliSectionPlugins = "plugins"
cliSectionImport = "import"
cliSectionExport = "export"
)
var cliUsageSections = []usageSection{
{Key: cliSectionGeneral, Flags: []string{"version", "domain", "port", "desktop", "setup"}},
{Key: cliSectionDatabase, Flags: []string{"db-type", "db-path", "db-conn"}},
{Key: cliSectionAppearance, Flags: []string{"default-lat", "default-lon", "default-zoom", "default-layer", "auto-locate-default", "support-email", "logo-path", "logo-link"}},
{Key: cliSectionPlugins, Flags: []string{"safecast-realtime", "safecast-realtime-default"}},
{Key: cliSectionImport, Flags: []string{"import", "import-tgz-url", "import-tgz-file"}},
{Key: cliSectionExport, Flags: []string{"json-archive-path", "json-archive-frequency"}},
}
// cliUsageSectionTranslations keeps the help headings localized so operators see familiar
// labels in -h output. We keep the map in code to avoid pulling UI translation files into
// the CLI path, keeping startup lightweight and predictable.
var cliUsageSectionTranslations = map[string]map[string]string{
"ar": {
cliSectionGeneral: "الإعدادات العامة للتطبيق",
cliSectionDatabase: "قاعدة البيانات",
cliSectionAppearance: "المظهر والتوطين",
cliSectionPlugins: "الإضافات (الزمن الحقيقي وغيرها)",
cliSectionImport: "استيراد البيانات",
cliSectionExport: "تصدير البيانات",
},
"cs": {
cliSectionGeneral: "Obecná nastavení aplikace",
cliSectionDatabase: "Databáze",
cliSectionAppearance: "Vzhled a lokalizace",
cliSectionPlugins: "Doplňkové pluginy (reálný čas apod.)",
cliSectionImport: "Import dat",
cliSectionExport: "Export dat",
},
"da": {
cliSectionGeneral: "Generelle programindstillinger",
cliSectionDatabase: "Database",
cliSectionAppearance: "Udseende og lokalisering",
cliSectionPlugins: "Ekstra plugins (realtid m.m.)",
cliSectionImport: "Dataimport",
cliSectionExport: "Dataeksport",
},
"de": {
cliSectionGeneral: "Allgemeine Anwendungseinstellungen",
cliSectionDatabase: "Datenbank",
cliSectionAppearance: "Design und Lokalisierung",
cliSectionPlugins: "Zusatz-Plugins (Realtime usw.)",
cliSectionImport: "Datenimport",
cliSectionExport: "Datenexport",
},
"el": {
cliSectionGeneral: "Γενικές ρυθμίσεις εφαρμογής",
cliSectionDatabase: "Βάση δεδομένων",
cliSectionAppearance: "Εμφάνιση και τοπικοποίηση",
cliSectionPlugins: "Πρόσθετα πρόσθετα (πραγματικού χρόνου κ.λπ.)",
cliSectionImport: "Εισαγωγή δεδομένων",
cliSectionExport: "Εξαγωγή δεδομένων",
},
"en": {
cliSectionGeneral: "General application settings",
cliSectionDatabase: "Database",
cliSectionAppearance: "Appearance & localization",
cliSectionPlugins: "Add-on plugins (realtime, etc.)",
cliSectionImport: "Data import",
cliSectionExport: "Data export",
},
"es": {
cliSectionGeneral: "Configuración general de la aplicación",
cliSectionDatabase: "Base de datos",
cliSectionAppearance: "Apariencia y localización",
cliSectionPlugins: "Plugins adicionales (tiempo real, etc.)",
cliSectionImport: "Importación de datos",
cliSectionExport: "Exportación de datos",
},
"fa": {
cliSectionGeneral: "تنظیمات عمومی برنامه",
cliSectionDatabase: "پایگاه داده",
cliSectionAppearance: "ظاهر و بومیسازی",
cliSectionPlugins: "افزونههای اضافی (بلادرنگ و غیره)",
cliSectionImport: "واردات داده",
cliSectionExport: "صادرات داده",
},
"fi": {
cliSectionGeneral: "Yleiset sovellusasetukset",
cliSectionDatabase: "Tietokanta",
cliSectionAppearance: "Ulkoasu ja lokalisointi",
cliSectionPlugins: "Lisäliitännäiset (reaaliaikaiset jne.)",
cliSectionImport: "Tietojen tuonti",
cliSectionExport: "Tietojen vienti",
},
"fr": {
cliSectionGeneral: "Paramètres généraux de l'application",
cliSectionDatabase: "Base de données",
cliSectionAppearance: "Apparence et localisation",
cliSectionPlugins: "Plugins supplémentaires (temps réel, etc.)",
cliSectionImport: "Importation des données",
cliSectionExport: "Exportation des données",
},
"he": {
cliSectionGeneral: "הגדרות כלליות של היישום",
cliSectionDatabase: "מסד נתונים",
cliSectionAppearance: "מראה ולוקליזציה",
cliSectionPlugins: "תוספים נוספים (זמן אמת וכו׳)",
cliSectionImport: "ייבוא נתונים",
cliSectionExport: "ייצוא נתונים",
},
"hi": {
cliSectionGeneral: "एप्लिकेशन की सामान्य सेटिंग्स",
cliSectionDatabase: "डेटाबेस",
cliSectionAppearance: "रूप-रंग और स्थानीयकरण",
cliSectionPlugins: "अतिरिक्त प्लगइन्स (रीयल-टाइम आदि)",
cliSectionImport: "डेटा आयात",
cliSectionExport: "डेटा निर्यात",
},
"hu": {
cliSectionGeneral: "Alkalmazás általános beállításai",
cliSectionDatabase: "Adatbázis",
cliSectionAppearance: "Megjelenés és lokalizáció",
cliSectionPlugins: "Kiegészítő bővítmények (valós idejű stb.)",
cliSectionImport: "Adatimport",
cliSectionExport: "Adatexport",
},
"id": {
cliSectionGeneral: "Pengaturan umum aplikasi",
cliSectionDatabase: "Basis data",
cliSectionAppearance: "Tampilan dan lokalisasi",
cliSectionPlugins: "Plugin tambahan (waktu nyata, dll.)",
cliSectionImport: "Impor data",
cliSectionExport: "Ekspor data",
},
"it": {
cliSectionGeneral: "Impostazioni generali dell'applicazione",
cliSectionDatabase: "Database",
cliSectionAppearance: "Aspetto e localizzazione",
cliSectionPlugins: "Plugin aggiuntivi (tempo reale, ecc.)",
cliSectionImport: "Importazione dati",
cliSectionExport: "Esportazione dati",
},
"ja": {
cliSectionGeneral: "アプリの一般設定",
cliSectionDatabase: "データベース",
cliSectionAppearance: "外観と言語設定",
cliSectionPlugins: "追加プラグイン(リアルタイムなど)",
cliSectionImport: "データのインポート",
cliSectionExport: "データのエクスポート",
},
"ko": {
cliSectionGeneral: "애플리케이션 일반 설정",
cliSectionDatabase: "데이터베이스",
cliSectionAppearance: "모양 및 현지화",
cliSectionPlugins: "추가 플러그인(실시간 등)",
cliSectionImport: "데이터 가져오기",
cliSectionExport: "데이터 내보내기",
},
"ms": {
cliSectionGeneral: "Tetapan umum aplikasi",
cliSectionDatabase: "Pangkalan data",
cliSectionAppearance: "Penampilan dan penyetempatan",
cliSectionPlugins: "Pemalam tambahan (masa nyata, dll.)",
cliSectionImport: "Import data",
cliSectionExport: "Eksport data",
},
"nl": {
cliSectionGeneral: "Algemene toepassingsinstellingen",
cliSectionDatabase: "Database",
cliSectionAppearance: "Uiterlijk en lokalisatie",
cliSectionPlugins: "Extra plugins (realtime e.d.)",
cliSectionImport: "Gegevensimport",
cliSectionExport: "Gegevensexport",
},
"no": {
cliSectionGeneral: "Generelle programinnstillinger",
cliSectionDatabase: "Database",
cliSectionAppearance: "Utseende og lokalisering",
cliSectionPlugins: "Tilleggs-plugins (sanntid m.m.)",
cliSectionImport: "Dataimport",
cliSectionExport: "Dataeksport",
},
"pl": {
cliSectionGeneral: "Ogólne ustawienia aplikacji",
cliSectionDatabase: "Baza danych",
cliSectionAppearance: "Wygląd i lokalizacja",
cliSectionPlugins: "Dodatkowe wtyczki (czas rzeczywisty itp.)",
cliSectionImport: "Import danych",
cliSectionExport: "Eksport danych",
},
"pt": {
cliSectionGeneral: "Configurações gerais do aplicativo",
cliSectionDatabase: "Banco de dados",
cliSectionAppearance: "Aparência e localização",
cliSectionPlugins: "Plugins adicionais (tempo real etc.)",
cliSectionImport: "Importação de dados",
cliSectionExport: "Exportação de dados",
},
"ru": {
cliSectionGeneral: "Общие настройки приложения",
cliSectionDatabase: "База данных",
cliSectionAppearance: "Оформление и локализация",
cliSectionPlugins: "Дополнительные плагины (реaltime и т.п.)",
cliSectionImport: "Импорт данных",
cliSectionExport: "Экспорт данных",
},
"sv": {
cliSectionGeneral: "Allmänna programinställningar",
cliSectionDatabase: "Databas",
cliSectionAppearance: "Utseende och lokalisering",
cliSectionPlugins: "Extra plugins (realtid m.m.)",
cliSectionImport: "Dataimport",
cliSectionExport: "Dataexport",
},
"th": {
cliSectionGeneral: "การตั้งค่าทั่วไปของแอป",
cliSectionDatabase: "ฐานข้อมูล",
cliSectionAppearance: "รูปลักษณ์และการแปลภาษา",
cliSectionPlugins: "ปลั๊กอินเพิ่มเติม (แบบเรียลไทม์ ฯลฯ)",
cliSectionImport: "นำเข้าข้อมูล",
cliSectionExport: "ส่งออกข้อมูล",
},
"tr": {
cliSectionGeneral: "Uygulama genel ayarları",
cliSectionDatabase: "Veritabanı",
cliSectionAppearance: "Görünüm ve yerelleştirme",
cliSectionPlugins: "Ek eklentiler (gerçek zamanlı vb.)",
cliSectionImport: "Veri içe aktarma",
cliSectionExport: "Veri dışa aktarma",
},
"uk": {
cliSectionGeneral: "Загальні налаштування застосунку",
cliSectionDatabase: "База даних",
cliSectionAppearance: "Оформлення та локалізація",
cliSectionPlugins: "Додаткові плагіни (реального часу тощо)",
cliSectionImport: "Імпорт даних",
cliSectionExport: "Експорт даних",
},
"vi": {
cliSectionGeneral: "Cài đặt chung của ứng dụng",
cliSectionDatabase: "Cơ sở dữ liệu",
cliSectionAppearance: "Giao diện và bản địa hóa",
cliSectionPlugins: "Plugin bổ sung (thời gian thực, v.v.)",
cliSectionImport: "Nhập dữ liệu",
cliSectionExport: "Xuất dữ liệu",
},
"zh": {
cliSectionGeneral: "应用常规设置",
cliSectionDatabase: "数据库",
cliSectionAppearance: "外观与本地化",
cliSectionPlugins: "附加插件(实时等)",
cliSectionImport: "数据导入",
cliSectionExport: "数据导出",
},
}
// resolveCLILanguage inspects locale environment variables so CLI help follows the
// operator's preferred language without extra flags.
func resolveCLILanguage() string {
for _, key := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {
raw := strings.TrimSpace(os.Getenv(key))
if raw == "" {
continue
}
raw = strings.Split(raw, ".")[0]
raw = strings.ReplaceAll(raw, "-", "_")
parts := strings.Split(raw, "_")
if len(parts) == 0 {
continue
}
lang := strings.ToLower(parts[0])
if _, ok := cliUsageSectionTranslations[lang]; ok {
return lang
}
}
return "en"
}
// cliUsageSectionTitle returns a localized title for the given section key. We
// keep the fallback simple so help never fails due to missing translations.
func cliUsageSectionTitle(sectionKey string) string {
lang := resolveCLILanguage()
if translations, ok := cliUsageSectionTranslations[lang]; ok {
if title, ok := translations[sectionKey]; ok {
return title
}
}
return cliUsageSectionTranslations["en"][sectionKey]
}
// importSelection captures which background importers should run based on the
// CLI flag so startup wiring stays explicit and testable.
type importSelection struct {
AtomFast bool
Safecast bool
}
// parseImportSelection normalizes the comma-separated import flag into a simple
// boolean map so callers can branch without repeating string parsing logic.
func parseImportSelection(raw string) importSelection {
selection := importSelection{}
clean := strings.ToLower(strings.TrimSpace(raw))
if clean == "" {
return selection
}
if clean == "all" {
selection.AtomFast = true
selection.Safecast = true
return selection
}
for _, part := range strings.Split(clean, ",") {
item := strings.TrimSpace(part)
switch item {
case "atomfast":
selection.AtomFast = true
case "safecast":
selection.Safecast = true
}
}
return selection
}
// registerSetupFlag avoids showing the setup wizard flag on non-Linux systems so help
// output stays truthful. Returning a pointer lets callers check for nil instead of
// juggling booleans across platforms.
func registerSetupFlag() *bool {
if runtime.GOOS != "linux" {
return nil
}
return flag.Bool("setup", false, "Launch an interactive, coloured setup wizard to install the binary as a systemd service (Linux only)")
}
// cliColorTheme centralises ANSI escape sequences so we can keep colourful help output
// consistent while still falling back to plain text when stdout is redirected. By
// wrapping colour codes in a struct we avoid scattering control characters throughout
// the printing logic and make future tweaks easier to follow.
type cliColorTheme struct {
Enabled bool
Section string
Flag string
Usage string
Default string
Reset string
}
// resolveCLIColorTheme inspects the provided writer to decide whether colourful output is
// appropriate. We only enable ANSI sequences when stdout points to a terminal and the
// operator has not explicitly disabled colour via NO_COLOR, aligning with the "don't
// fight the tool" proverb by respecting common shell conventions.
func resolveCLIColorTheme(out io.Writer) cliColorTheme {
theme := cliColorTheme{}
file, ok := out.(*os.File)
if !ok {
return theme
}
if os.Getenv("NO_COLOR") != "" {
return theme
}
info, err := file.Stat()
if err != nil {
return theme
}
if (info.Mode() & os.ModeCharDevice) == 0 {
return theme
}
theme.Enabled = true
// We switch to a punchier palette that keeps contrast on both dark and light
// backgrounds without feeling gaudy. Section headings lean on a deep ocean blue,
// flags use a vibrant amber, usage strings stay in neutral charcoal, and defaults
// adopt a rich forest green. The tones remain saturated enough to pop on light
// themes while still carrying enough depth for dark terminals.
theme.Section = "\033[38;5;25m"
theme.Flag = "\033[38;5;208m"
theme.Usage = "\033[38;5;240m"
theme.Default = "\033[38;5;34m"
theme.Reset = "\033[0m"
return theme
}
// configureCLIUsage replaces the default flag help with a grouped layout. We do this in init()
// so operators immediately see logically clustered options when running -h, without juggling
// extra wiring at call sites.
func configureCLIUsage() {
flag.CommandLine.SetOutput(os.Stdout)
flag.Usage = func() {
out := flag.CommandLine.Output()
theme := resolveCLIColorTheme(out)
fmt.Fprintf(out, "Usage: %s [flags]\n\n", os.Args[0])
if theme.Enabled {
fmt.Fprintf(out, "%sFlags:%s\n", theme.Section, theme.Reset)
} else {
fmt.Fprintln(out, "Flags:")
}
printed := map[string]bool{}
for _, section := range cliUsageSections {
sectionTitle := cliUsageSectionTitle(section.Key)
var sectionFlags []*flag.Flag
for _, name := range section.Flags {
if f := flag.Lookup(name); f != nil {
sectionFlags = append(sectionFlags, f)
printed[f.Name] = true
}
}
if len(sectionFlags) == 0 {
continue
}
if theme.Enabled {
fmt.Fprintf(out, "%s%s:%s\n", theme.Section, sectionTitle, theme.Reset)
} else {
fmt.Fprintf(out, "%s:\n", sectionTitle)
}
for _, f := range sectionFlags {
writeFlagUsage(out, f, theme)
}
fmt.Fprintln(out)
}
var leftovers []string
flag.VisitAll(func(f *flag.Flag) {
if !printed[f.Name] {
leftovers = append(leftovers, f.Name)
}
})
if len(leftovers) > 0 {
sort.Strings(leftovers)
if theme.Enabled {
fmt.Fprintf(out, "%sAdditional flags:%s\n", theme.Section, theme.Reset)
} else {
fmt.Fprintln(out, "Additional flags:")
}
for _, name := range leftovers {
if f := flag.Lookup(name); f != nil {
writeFlagUsage(out, f, theme)
}
}
}
printCLILicenseNote(out, theme)
}
}
// writeFlagUsage mirrors flag.PrintDefaults but adds indentation and multiline support so the
// help output stays legible even when descriptions contain examples.
func writeFlagUsage(out io.Writer, f *flag.Flag, theme cliColorTheme) {
if f == nil {
return
}
name, usage := flag.UnquoteUsage(f)
if theme.Enabled {
fmt.Fprintf(out, " %s-%s%s", theme.Flag, f.Name, theme.Reset)
} else {
fmt.Fprintf(out, " -%s", f.Name)
}
if name != "" {
fmt.Fprintf(out, " %s", name)
}
fmt.Fprintln(out)
if usage != "" {
for _, part := range strings.Split(usage, "\n") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
if theme.Enabled {
fmt.Fprintf(out, " %s%s%s\n", theme.Usage, part, theme.Reset)
} else {
fmt.Fprintf(out, " %s\n", part)
}
}
}
if def := strings.TrimSpace(f.DefValue); def != "" {
if theme.Enabled {
fmt.Fprintf(out, " %sDefault:%s %s%s%s\n", theme.Flag, theme.Reset, theme.Default, def, theme.Reset)
} else {
fmt.Fprintf(out, " Default: %s\n", def)
}
}
}
// printCLILicenseNote mirrors the in-app license block so terminal operators see the
// same promise: code under MIT, research data under CC0, and an open invitation to
// collaborate. Keeping the wording here ensures the CLI reflects the project ethos
// without forcing admins to open the UI.
func printCLILicenseNote(out io.Writer, theme cliColorTheme) {
if out == nil {
return
}
fmt.Fprintln(out)
if theme.Enabled {
fmt.Fprintf(out, "%sLicense & community:%s\n", theme.Section, theme.Reset)
} else {
fmt.Fprintln(out, "License & community:")
}
lines := []string{
"Code: MIT License.",
"Research datasets: CC0 1.0 Universal (Public Domain).",
"Thank you for using this program and sharing your tracks. This work is fragile — care for it, and it will grow.",
"Support the sources, share honest knowledge, and run your own nodes so the maps stay free and safe.",
}
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
if theme.Enabled {
fmt.Fprintf(out, " %s%s%s\n", theme.Usage, line, theme.Reset)
} else {
fmt.Fprintf(out, " %s\n", line)
}
}
}
var CompileVersion = "dev"
var (
apiDocsArchiveEnabled bool
apiDocsArchiveRoute string
apiDocsArchiveFrequency string
)
var db *database.Database
var runtimeDBDriverName string
var desktopAdminImportSlot = make(chan struct{}, 1)
var importStatusUpdateCh = make(chan importStatusEvent, 128)
var importStatusReadCh = make(chan chan string)
type importStatusEvent struct {
Source string
Text string
}
type desktopAdminSettings struct {
DBPath string `json:"dbPath"`
MapboxToken string `json:"mapboxToken"`
MapboxEnabled bool `json:"mapboxEnabled"`
EnableHistoricalImport bool `json:"enableHistoricalImport"`
EnableSafecastImport bool `json:"enableSafecastImport"`
EnableAtomFastImport bool `json:"enableAtomFastImport"`
EnableRealtimeUpdates bool `json:"enableRealtimeUpdates"`
}
const desktopHistoricalImportURL = "https://pelora.org/api/json/weekly.tgz"
func init() {
// We trigger driver registration here so "go run chicha-isotope-map.go" keeps
// working even when auxiliary files are skipped; relying on init avoids extra
// coordination primitives and mirrors Go's preference for simplicity.
drivers.Ready()
// CLI usage grouping is also configured once during init so every entry point
// inherits the readable help layout without repeating boilerplate.
configureCLIUsage()
// Desktop admin imports run one archive job at a time so operators do not
// accidentally launch overlapping 300 GB syncs from repeated clicks.
desktopAdminImportSlot <- struct{}{}
startImportStatusTracker()
}
// startImportStatusTracker keeps a compact import summary in a single goroutine
// so readers and writers communicate only through channels.
func startImportStatusTracker() {
go func() {
statusBySource := map[string]string{
"TGZ": "idle",
"Safecast": "idle",
"AtomFast": "idle",
}
for {
select {
case event := <-importStatusUpdateCh:
source := strings.TrimSpace(event.Source)
text := strings.TrimSpace(event.Text)
if source == "" || text == "" {
continue
}
statusBySource[source] = text
case replyCh := <-importStatusReadCh:
replyCh <- fmt.Sprintf("TGZ: %s · Safecast: %s · AtomFast: %s", statusBySource["TGZ"], statusBySource["Safecast"], statusBySource["AtomFast"])
}
}
}()
}
func setImportStatus(source, text string) {
event := importStatusEvent{Source: source, Text: text}
select {
case importStatusUpdateCh <- event:
default:
}
}
func readImportStatusLine() string {
replyCh := make(chan string, 1)
select {
case importStatusReadCh <- replyCh:
case <-time.After(100 * time.Millisecond):
return "TGZ: unknown · Safecast: unknown · AtomFast: unknown"
}
select {
case summary := <-replyCh:
return summary
case <-time.After(100 * time.Millisecond):
return "TGZ: unknown · Safecast: unknown · AtomFast: unknown"
}
}
// =====================
// WEB — API docs page
// =====================
func apiDocsHandler(w http.ResponseWriter, r *http.Request) {
// Serve a static, embedded HTML with API usage instructions.
// Keep it simple and cacheable by default; clients can refresh as needed.
b, err := content.ReadFile("public_html/api-usage.html")
if err != nil {
http.NotFound(w, r)
return
}
scheme := "http"
if proto := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); proto != "" {
scheme = strings.ToLower(proto)
} else if r.TLS != nil {
scheme = "https"
}
host := strings.TrimSpace(r.Host)
if host == "" {
if strings.TrimSpace(*domain) != "" {
host = strings.TrimSpace(*domain)
} else {
host = fmt.Sprintf("localhost:%d", *port)
}
}
baseURL := fmt.Sprintf("%s://%s", scheme, host)
apiRoot := strings.TrimRight(baseURL, "/") + "/api"
page := string(b)
page = strings.ReplaceAll(page, "__BASE_URL__", baseURL)
page = strings.ReplaceAll(page, "__API_ROOT__", apiRoot)
page = strings.ReplaceAll(page, "__DISPLAY_HOST__", host)
page = strings.ReplaceAll(page, "__ARCHIVE_ENABLED__", strconv.FormatBool(apiDocsArchiveEnabled))
route := strings.TrimSpace(apiDocsArchiveRoute)
if route == "" {
route = "/api/json/weekly.tgz"
}
page = strings.ReplaceAll(page, "__ARCHIVE_ROUTE__", route)
freq := strings.TrimSpace(apiDocsArchiveFrequency)
if freq == "" {
freq = "weekly"
}
page = strings.ReplaceAll(page, "__ARCHIVE_FREQUENCY__", freq)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write([]byte(page))
}
// resolveArchivePath decides where the JSON archive tgz should live.
// We prefer explicit destinations from flags, otherwise fall back to the user's
// home directory so long-running services do not clutter the repository tree.
// We log resolution failures so operators notice and can correct their setup.
// The defaultFile argument feeds through the configured cadence and domain so
// implicit directories still produce predictable filenames.
func resolveArchivePath(flagValue, defaultFile string, logf func(string, ...any)) string {
cleaned := strings.TrimSpace(flagValue)
fallback := strings.TrimSpace(defaultFile)
if fallback == "" {
fallback = "weekly-json.tgz"
}
if cleaned != "" {
abs, err := filepath.Abs(cleaned)
if err != nil {
if logf != nil {
logf("json archive path resolution fallback for %q: %v", cleaned, err)
}
return filepath.Clean(cleaned)
}
return abs
}
home, err := os.UserHomeDir()
if err == nil && strings.TrimSpace(home) != "" {
return filepath.Join(home, fallback)
}
// Falling back to the working directory keeps the archive predictable even
// in minimal environments where HOME is undefined, trading cleverness for
// clarity per the Go proverbs.
wd, wdErr := os.Getwd()
if wdErr == nil && strings.TrimSpace(wd) != "" {
return filepath.Join(wd, fallback)
}
// As a last resort return a relative filename so the generator can still run.
return fallback
}
// applyDBConnection parses a DSN passed via -db-conn and copies relevant fields into the
// database configuration. We normalise defaults for host, port, and SSL/TLS so operators can
// supply concise URLs while the rest of the application continues using structured settings.
func applyDBConnection(driverName, conn string, cfg *database.Config) error {
if cfg == nil {
return fmt.Errorf("db config is nil")
}
cleaned := strings.TrimSpace(conn)
if cleaned == "" {
return nil
}
parsed, err := url.Parse(cleaned)
if err != nil {
return fmt.Errorf("%s connection string: %w", driverName, err)
}
driver := strings.ToLower(strings.TrimSpace(driverName))
switch driver {
case "pgx":
if parsed.Scheme == "" {
parsed.Scheme = "postgres"
}
case "clickhouse":
if parsed.Scheme == "" {
parsed.Scheme = "clickhouse"
}
default:
return fmt.Errorf("db-conn is only supported for pgx or clickhouse (got %q)", driverName)
}
host := parsed.Hostname()
if host == "" {
host = "127.0.0.1"
}
cfg.DBHost = host
portValue := parsed.Port()
var port int
if portValue != "" {
port, err = strconv.Atoi(portValue)
if err != nil {
return fmt.Errorf("%s connection string: invalid port %q", driverName, portValue)
}
} else {
if driver == "pgx" {
port = 5432
} else {
port = 9000
}
}
cfg.DBPort = port
if parsed.User != nil {
if user := strings.TrimSpace(parsed.User.Username()); user != "" {
cfg.DBUser = user
}
if pass, ok := parsed.User.Password(); ok {
cfg.DBPass = pass
}
}
name := strings.Trim(strings.TrimPrefix(parsed.Path, "/"), " ")
if driver == "pgx" && name == "" {
return fmt.Errorf("%s connection string must include a database name", driverName)
}
if name != "" || driver == "pgx" {
cfg.DBName = name
}
query := parsed.Query()
switch driver {
case "pgx":
sslMode := strings.TrimSpace(query.Get("sslmode"))
if sslMode == "" {
sslMode = "prefer"
query.Set("sslmode", sslMode)
}
cfg.PGSSLMode = sslMode
case "clickhouse":
secureValue := strings.TrimSpace(query.Get("secure"))
secure := false
if secureValue != "" {
secure = secureValue == "1" || strings.EqualFold(secureValue, "true") || strings.EqualFold(secureValue, "yes") || strings.EqualFold(secureValue, "on")
} else if strings.EqualFold(parsed.Scheme, "https") {
secure = true
query.Set("secure", "true")
}
cfg.ClickSecure = secure
}
parsed.RawQuery = query.Encode()
cfg.DBConn = parsed.String()
return nil
}
// handleServerError logs startup failures while allowing normal shutdowns to
// remain quiet. This keeps error handling centralized without the self-upgrade
// rollback behavior.
func handleServerError(err error, logf func(string, ...any)) {
if err == nil || errors.Is(err, http.ErrServerClosed) {
return
}
if logf != nil {
logf("HTTP server error: %v", err)
}
}
// ==========
// Константы для слияния маркеров
// ==========
const (
markerRadiusPx = 10.0 // радиус кружка в пикселях
minValidTS = 1262304000 // 2010-01-01 00:00:00 UTC
)
// microRoentgenPerMicroSievert keeps conversion logic explicit so both the API
// exporter and the JSON importer agree on the units we advertise publicly.
const microRoentgenPerMicroSievert = 100.0
type SpeedRange struct{ Min, Max float64 }
var errNotChichaTrackJSON = errors.New("not chicha track json payload")
// processBGeigieZenFile parses bGeigie Zen/Nano $BNRDD logs.
// Supports ISO8601 timestamps at field[2] and DMM coordinates with N/S/E/W.
func processBGeigieZenFile(
file multipart.File,
trackID string,
db *database.Database,
dbType string,
) (database.Bounds, string, error) {
logT(trackID, "BGEIGIE", "▶ start (stream)")
sc := bufio.NewScanner(file)
sc.Buffer(make([]byte, 0, 64*1024), 2*1024*1024)
const cpmPerMicroSv = 334.0
markers := make([]database.Marker, 0, 4096)
parsed := 0
skipped := 0
for sc.Scan() {
line := strings.TrimSpace(strings.TrimRight(sc.Text(), "\r"))
if line == "" || strings.HasPrefix(line, "#") {
skipped++
continue
}
if !looksLikeBGeigieLine(line) {
skipped++
continue
}
if i := strings.IndexByte(line, '*'); i != -1 {
line = line[:i]
}