Skip to content

ui.modal_view

ui.modal_view

Modal content rendering for the TapMap UI.

Build Dash components for menu actions, map clicks, and modal screens shown by the application.

ColumnSpec dataclass

Describe one table column.

Source code in ui/tables.py
16
17
18
19
20
21
@dataclass(frozen=True)
class ColumnSpec:
    """Describe one table column."""

    header: str
    width: str | None = None

ModalTextBuilder

Build modal content for menu actions and map clicks.

All methods return Dash components, not raw strings.

Source code in ui/modal_view.py
 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
class ModalTextBuilder:
    """Build modal content for menu actions and map clicks.

    All methods return Dash components, not raw strings.
    """

    def __init__(self, app_name: str, app_version: str, app_author: str) -> None:
        self.app_name = app_name
        self.app_version = app_version
        self.app_author = app_author

        self._label_map: dict[str, str] = {
            "menu_unmapped": "Show unmapped public services",
            "menu_lan_local": "Show established LAN/LOCAL services",
            "menu_open_ports": "Show open ports",
            "menu_cache_terminal": "Show cache in terminal",
            "menu_clear_cache": "Clear cache",
            "menu_help": "Help",
            "menu_about": "About",
        }

    def for_action(
        self,
        action: str,
        *,
        snapshot: Any | None = None,
        show_system: bool = False,
        is_docker: bool,
    ) -> list[Any]:
        """Build modal body content for a menu action.

        Args:
            action: Menu action ID.
            snapshot: Latest model snapshot (dict) or None.
            show_system: Open ports view toggle state.
            is_docker: Whether the application is running in Docker.

        Returns:
            Dash components for the modal body.
        """
        if action == "menu_unmapped":
            return self._render_unmapped(snapshot)

        if action == "menu_lan_local":
            return self._render_lan_local(snapshot)

        if action == "menu_open_ports":
            return self._render_open_ports(snapshot, show_system=show_system)

        if action == "menu_help":
            return render_help()

        if action == "menu_about":
            return render_about(
                app_name=self.app_name,
                app_version=self.app_version,
                app_author=self.app_author,
                snapshot=snapshot,
                is_docker=is_docker,
            )
        label = self._label_map.get(action, action)
        return [self._h1("Details"), html.Pre(f"Menu selected: {label}")]

    def for_click(self, click_data: Any, ui_view: Any) -> html.Pre | None:
        """Build click detail content from Plotly clickData.

        Args:
            click_data: Plotly clickData payload.
            ui_view: Dash store content with the "details" mapping.

        Returns:
            html.Pre for a valid click, otherwise None.
        """
        if not isinstance(click_data, dict):
            return None

        points = click_data.get("points")
        if not isinstance(points, list) or not points:
            return None

        point0 = points[0]
        if not isinstance(point0, dict):
            return None

        idx = self.first_idx(point0.get("customdata"))
        if idx is None:
            return None

        view = ui_view if isinstance(ui_view, dict) else {}
        details = view.get("details")
        details_map = details if isinstance(details, dict) else {}

        detail = details_map.get(str(idx), f"Location {idx}")
        lon = point0.get("lon")
        lat = point0.get("lat")

        body_text = f"lon={lon}  lat={lat}\n\n{detail}"
        return html.Pre(body_text)

    # ---------- Common UI helpers ----------

    @staticmethod
    def _h1(title: str) -> html.H1:
        return html.H1(title)

    @classmethod
    def _open_ports_sort_key(cls, row: dict[str, Any]) -> tuple[int, int, int, str, int]:
        """Return sort key for Open Ports rows."""
        bind_scope = safe_str(row.get("bind_scope")).upper()
        proto = safe_str(row.get("proto")).upper()
        local_address = safe_str(row.get("local_address"))

        port = port_from_local(local_address)
        port = port if port >= 0 else 65536

        process_name = safe_str(row.get("process_label") or row.get("process_name")).lower()
        pid = safe_int(row.get("pid"))

        scope_order = {
            "PUBLIC": 0,
            "LAN": 1,
            "LOCAL": 2,
        }.get(bind_scope, 3)

        proto_order = 0 if proto == "TCP" else 1

        return (scope_order, proto_order, port, process_name, pid)

    @staticmethod
    def _is_system_process(row: dict[str, Any]) -> bool:
        """Return True if the row should be treated as a system process."""
        process_status = safe_str(row.get("process_status"))
        process_name = safe_str(row.get("process_name") or row.get("process_label")).lower()

        hidden = {
            "system",
            "svchost.exe",
            "lsass.exe",
            "wininit.exe",
            "services.exe",
            "spoolsv.exe",
        }

        return process_status != "OK" or process_name in hidden

    @classmethod
    def _render_open_ports(
        cls,
        snapshot: Any | None,
        *,
        show_system: bool,
    ) -> list[Any]:
        """Build modal content for the Open Ports view."""
        snap = snapshot if isinstance(snapshot, dict) else {}
        rows = snap.get("open_ports")
        rows_list = rows if isinstance(rows, list) else []
        cleaned: list[dict[str, Any]] = [r for r in rows_list if isinstance(r, dict)]

        if not show_system:
            filtered: list[dict[str, Any]] = []
            for r in cleaned:
                if cls._is_system_process(r):
                    continue
                filtered.append(r)
            cleaned = filtered

        cleaned.sort(key=cls._open_ports_sort_key)

        toggle = dcc.Checklist(
            id="toggle_open_ports_system",
            options=[{"label": "Show system processes", "value": "on"}],
            value=(["on"] if show_system else []),
            className="mx-title-toggle",
        )

        header = [
            html.H1(
                children=[html.Span("Open ports (TCP LISTEN and UDP bound)"), toggle],
                className="mx-h1-with-toggle",
            )
        ]

        if not cleaned:
            return [*header, html.Pre("(no open ports found)")]

        body_rows: list[Any] = []
        for r in cleaned:
            full_local = safe_str(r.get("local_address"))
            ip_display = pretty_bind_ip(strip_port(full_local))

            service = safe_str(r.get("service"))
            service_hint = safe_str(r.get("service_hint")) or None

            process_label = safe_str(r.get("process_label") or r.get("process_name"))
            process_hint = safe_str(r.get("process_hint")) or None
            process_status = safe_str(r.get("process_status")) or None

            if not process_label:
                process_label = process_status or "Unavailable"
            if process_hint is None:
                process_hint = process_status

            pid_value = r.get("pid")
            pid_text = str(safe_int(pid_value)) if pid_value is not None else ""

            body_rows.append(
                html.Tr(
                    [
                        cell(safe_str(r.get("bind_scope"))),
                        cell(safe_str(r.get("proto"))),
                        cell(str(port_from_local(full_local))),
                        cell(ip_display, title=full_local),
                        cell(service, title=service_hint),
                        cell(pid_text),
                        cell(process_label, title=process_hint),
                    ]
                )
            )

        columns = [
            ColumnSpec("Bind scope", "8.0%"),
            ColumnSpec("Proto", "8.0%"),
            ColumnSpec("Port", "8.0%"),
            ColumnSpec("Local IP", "24.0%"),
            ColumnSpec("Port service", "20.0%"),
            ColumnSpec("PID", "8.0%"),
            ColumnSpec("Process", "24.0%"),
        ]

        table = build_table(
            class_name="mx-table mx-open-ports",
            columns=columns,
            header_cells=[c.header for c in columns],
            body_rows=body_rows,
        )

        return [*header, table]

    # Helpers for unmapped and LAN/LOCAL services views
    @staticmethod
    def _process_text(row: dict[str, Any]) -> tuple[str, str | None]:
        """Return process label and tooltip."""
        label = safe_str(row.get("process_name"))
        if not label:
            label = safe_str(row.get("process_status")) or "Unavailable"

        exe = row.get("exe")
        if isinstance(exe, str) and exe.strip():
            return label, exe.strip()

        status = row.get("process_status")
        if isinstance(status, str) and status.strip():
            return label, status.strip()

        return label, None

    @staticmethod
    def _service_text(row: dict[str, Any]) -> tuple[str, str | None]:
        """Return service label and tooltip."""
        service = safe_str(row.get("service")) or "Unknown"
        hint = safe_str(row.get("service_hint")) or None
        return service, hint

    @classmethod
    def _aggregate_service_rows(cls, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
        """Aggregate service rows by scope, ip, port, pid and process."""
        agg: dict[tuple[str, str, int, int, str], dict[str, Any]] = {}

        for r in rows:
            ip = safe_str(r.get("ip"))
            port = safe_int(r.get("port"), default=-1)
            scope = safe_str(r.get("service_scope")) or "UNKNOWN"

            pid_val = r.get("pid")
            pid = safe_int(pid_val) if pid_val is not None else -1

            proc_label, proc_tip = cls._process_text(r)
            svc_val, svc_tip = cls._service_text(r)

            key = (scope, ip, port, pid, proc_label)
            entry = agg.get(key)

            if entry is None:
                agg[key] = {
                    "scope": scope,
                    "ip": ip,
                    "port": port,
                    "service": svc_val,
                    "service_tip": svc_tip,
                    "pid": pid if pid != -1 else None,
                    "process": proc_label,
                    "process_tip": proc_tip,
                    "count": 1,
                }
            else:
                entry["count"] = int(entry.get("count") or 0) + 1
                if entry.get("process_tip") in {None, ""} and proc_tip:
                    entry["process_tip"] = proc_tip
                if entry.get("service_tip") in {None, ""} and svc_tip:
                    entry["service_tip"] = svc_tip

        return list(agg.values())

    @staticmethod
    def _service_sort_key(row: dict[str, Any]) -> tuple[int, int, int, str, str]:
        """Return sort key for aggregated service rows."""
        interesting_ports = {443, 53, 80, 3478, 22, 3389}

        scope = safe_str(row.get("scope"))
        port = safe_int(row.get("port"), default=-1)
        proc = safe_str(row.get("process"))
        ip = safe_str(row.get("ip"))
        count = safe_int(row.get("count"), default=0)

        port_rank = 0 if port in interesting_ports else 1
        return (scope_rank(scope), port_rank, -count, proc.lower(), ip)

    @classmethod
    def _build_service_body_rows(cls, aggregated: list[dict[str, Any]]) -> list[Any]:
        """Build table rows for aggregated service entries."""
        body_rows: list[Any] = []

        for row in sorted(aggregated, key=cls._service_sort_key):
            scope = safe_str(row.get("scope"))
            ip = safe_str(row.get("ip"))
            port = safe_int(row.get("port"), default=-1)

            service = safe_str(row.get("service")) or "Unknown"
            service_tip = safe_str(row.get("service_tip")) or None

            pid_val = row.get("pid")
            pid_txt = str(safe_int(pid_val)) if pid_val is not None else ""

            proc = safe_str(row.get("process"))
            proc_tip = safe_str(row.get("process_tip")) or None

            count = safe_int(row.get("count"), default=1)

            body_rows.append(
                html.Tr(
                    [
                        cell(scope),
                        cell(ip or "-"),
                        cell(str(port) if port > 0 else "-"),
                        cell(service, title=service_tip),
                        cell(str(count)),
                        cell(pid_txt),
                        cell(proc, title=proc_tip),
                    ]
                )
            )

        return body_rows

    @classmethod
    def _build_service_table(
        cls,
        aggregated: list[dict[str, Any]],
        *,
        class_name: str,
    ) -> html.Table:
        """Build a service table for aggregated rows."""
        columns = [
            ColumnSpec("Scope", "8%"),
            ColumnSpec("Remote IP", "28%"),
            ColumnSpec("Port", "8%"),
            ColumnSpec("Port service", "16%"),
            ColumnSpec("Count", "8%"),
            ColumnSpec("PID", "8%"),
            ColumnSpec("Process", "24%"),
        ]

        return build_table(
            class_name=class_name,
            columns=columns,
            header_cells=[c.header for c in columns],
            body_rows=cls._build_service_body_rows(aggregated),
        )

    @classmethod
    def _render_unmapped(cls, snapshot: Any | None) -> list[Any]:
        """Render unmapped services.

        Render established TCP services with PUBLIC service_scope and missing geolocation.
        """
        snap = snapshot if isinstance(snapshot, dict) else {}
        items = snap.get("cache_items")
        rows = items if isinstance(items, list) else []

        cleaned: list[dict[str, Any]] = [r for r in rows if isinstance(r, dict)]

        def has_geo(r: dict[str, Any]) -> bool:
            lat = r.get("lat")
            lon = r.get("lon")
            return isinstance(lat, (int, float)) and isinstance(lon, (int, float))

        filtered: list[dict[str, Any]] = []
        for r in cleaned:
            scope = safe_str(r.get("service_scope")) or "UNKNOWN"
            geo_ok = has_geo(r)
            if scope == "PUBLIC" and not geo_ok:
                filtered.append(r)

        header = html.H1("Unmapped public services (missing geolocation)", className="mx-h1")

        if not filtered:
            return [header, html.Pre("(no unmapped public services)")]

        aggregated = cls._aggregate_service_rows(filtered)
        table = cls._build_service_table(
            aggregated,
            class_name="mx-table mx-unmapped",
        )

        return [header, table]

    # LAN/LOCAL services view
    @classmethod
    def _render_lan_local(cls, snapshot: Any | None) -> list[Any]:
        """Render LAN and LOCAL established services."""
        snap = snapshot if isinstance(snapshot, dict) else {}
        items = snap.get("cache_items")
        rows = items if isinstance(items, list) else []

        cleaned: list[dict[str, Any]] = [r for r in rows if isinstance(r, dict)]

        def is_established_tcp(row: dict[str, Any]) -> bool:
            state = row.get("state")
            if isinstance(state, str) and state.strip() and state.strip().upper() != "ESTABLISHED":
                return False

            proto = row.get("proto")
            return not (isinstance(proto, str) and proto.strip() and proto.strip().lower() != "tcp")

        filtered: list[dict[str, Any]] = []
        for r in cleaned:
            scope = safe_str(r.get("service_scope")) or "UNKNOWN"
            if scope in {"LAN", "LOCAL"} and is_established_tcp(r):
                filtered.append(r)

        header = html.H1("Established LAN/LOCAL services", className="mx-h1")

        if not filtered:
            return [header, html.Pre("(no LAN/LOCAL services)")]

        aggregated = cls._aggregate_service_rows(filtered)
        table = cls._build_service_table(
            aggregated,
            class_name="mx-table mx-lan-local",
        )

        return [header, table]

    def missing_geo_db(self, geo_data_dir: str, *, is_docker: bool) -> list[Any]:
        """Render the Missing GeoIP databases view."""
        return [
            self._h1("Missing GeoIP databases"),
            html.P(
                [
                    "TapMap can run without geolocation, but GeoIP lookups will be disabled. ",
                    "To enable geolocation, download the GeoLite2 databases and place them in "
                    "this folder:",
                ]
            ),
            html.Div(
                className="mx-path-row",
                children=[
                    html.Pre(geo_data_dir, className="mx-path-box"),
                    *(
                        []
                        if is_docker
                        else [
                            html.Button(
                                "Open data folder",
                                id="btn_open_data",
                                n_clicks=0,
                                className="mx-btn mx-btn--primary mx-btn--nowrap",
                                type="button",
                            )
                        ]
                    ),
                    html.Button(
                        "Recheck databases",
                        id="btn_check_databases",
                        n_clicks=0,
                        className="mx-btn mx-btn--primary mx-btn--nowrap",
                        type="button",
                    ),
                ],
            ),
            *(
                [
                    html.P(
                        "Running in Docker. Place the GeoLite2 .mmdb files in the "
                        "host folder mounted to this path.",
                        className="mx-note",
                    )
                ]
                if is_docker
                else []
            ),
            html.P("Required files:"),
            html.Ul(
                [
                    html.Li("GeoLite2-ASN.mmdb"),
                    html.Li("GeoLite2-City.mmdb"),
                ]
            ),
            html.H2("Steps"),
            html.Ol(
                [
                    *(
                        [html.Li("Open the data folder.")]
                        if not is_docker
                        else [
                            html.Li(
                                "Copy the GeoLite2 .mmdb files into the host "
                                "folder mapped to this path."
                            )
                        ]
                    ),
                    html.Li(
                        "Copy the GeoLite2 .mmdb files into the folder."
                        if not is_docker
                        else "Restart or return to the app after the files are in place."
                    ),
                    html.Li("Click Recheck GeoIP databases in the app."),
                ]
            ),
            html.H2("Download"),
            html.P(
                [
                    "Download is free from MaxMind, but requires an account and "
                    "acceptance of license terms. ",
                    "Create a free account and download the databases here: ",
                    html.A(
                        "MaxMind GeoLite2 download page",
                        href="https://dev.maxmind.com/geoip/geolite2-free-geolocation-data",
                        target="_blank",
                        rel="noopener noreferrer",
                    ),
                    ".",
                ]
            ),
            html.P(
                "Update recommendation: download updated databases regularly (for example monthly)."
            ),
        ]

    # ---------- Click helpers ----------

    @staticmethod
    def first_idx(customdata: Any) -> int | None:
        """Extract a service index from Plotly customdata.

        Supported forms:
            - dict with keys {"kind", "idx"}
            - integer
            - nested list or tuple structures
        """
        if isinstance(customdata, dict):
            if customdata.get("kind") in {"target", "line"}:
                idx = customdata.get("idx")
                return idx if isinstance(idx, int) else None
            return None

        if isinstance(customdata, int):
            return customdata

        if isinstance(customdata, (list, tuple)) and customdata:
            return ModalTextBuilder.first_idx(customdata[0])

        return None

for_action(action, *, snapshot=None, show_system=False, is_docker)

Build modal body content for a menu action.

Parameters:

Name Type Description Default
action str

Menu action ID.

required
snapshot Any | None

Latest model snapshot (dict) or None.

None
show_system bool

Open ports view toggle state.

False
is_docker bool

Whether the application is running in Docker.

required

Returns:

Type Description
list[Any]

Dash components for the modal body.

Source code in ui/modal_view.py
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
def for_action(
    self,
    action: str,
    *,
    snapshot: Any | None = None,
    show_system: bool = False,
    is_docker: bool,
) -> list[Any]:
    """Build modal body content for a menu action.

    Args:
        action: Menu action ID.
        snapshot: Latest model snapshot (dict) or None.
        show_system: Open ports view toggle state.
        is_docker: Whether the application is running in Docker.

    Returns:
        Dash components for the modal body.
    """
    if action == "menu_unmapped":
        return self._render_unmapped(snapshot)

    if action == "menu_lan_local":
        return self._render_lan_local(snapshot)

    if action == "menu_open_ports":
        return self._render_open_ports(snapshot, show_system=show_system)

    if action == "menu_help":
        return render_help()

    if action == "menu_about":
        return render_about(
            app_name=self.app_name,
            app_version=self.app_version,
            app_author=self.app_author,
            snapshot=snapshot,
            is_docker=is_docker,
        )
    label = self._label_map.get(action, action)
    return [self._h1("Details"), html.Pre(f"Menu selected: {label}")]

for_click(click_data, ui_view)

Build click detail content from Plotly clickData.

Parameters:

Name Type Description Default
click_data Any

Plotly clickData payload.

required
ui_view Any

Dash store content with the "details" mapping.

required

Returns:

Type Description
Pre | None

html.Pre for a valid click, otherwise None.

Source code in ui/modal_view.py
 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
def for_click(self, click_data: Any, ui_view: Any) -> html.Pre | None:
    """Build click detail content from Plotly clickData.

    Args:
        click_data: Plotly clickData payload.
        ui_view: Dash store content with the "details" mapping.

    Returns:
        html.Pre for a valid click, otherwise None.
    """
    if not isinstance(click_data, dict):
        return None

    points = click_data.get("points")
    if not isinstance(points, list) or not points:
        return None

    point0 = points[0]
    if not isinstance(point0, dict):
        return None

    idx = self.first_idx(point0.get("customdata"))
    if idx is None:
        return None

    view = ui_view if isinstance(ui_view, dict) else {}
    details = view.get("details")
    details_map = details if isinstance(details, dict) else {}

    detail = details_map.get(str(idx), f"Location {idx}")
    lon = point0.get("lon")
    lat = point0.get("lat")

    body_text = f"lon={lon}  lat={lat}\n\n{detail}"
    return html.Pre(body_text)

missing_geo_db(geo_data_dir, *, is_docker)

Render the Missing GeoIP databases view.

Source code in ui/modal_view.py
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
def missing_geo_db(self, geo_data_dir: str, *, is_docker: bool) -> list[Any]:
    """Render the Missing GeoIP databases view."""
    return [
        self._h1("Missing GeoIP databases"),
        html.P(
            [
                "TapMap can run without geolocation, but GeoIP lookups will be disabled. ",
                "To enable geolocation, download the GeoLite2 databases and place them in "
                "this folder:",
            ]
        ),
        html.Div(
            className="mx-path-row",
            children=[
                html.Pre(geo_data_dir, className="mx-path-box"),
                *(
                    []
                    if is_docker
                    else [
                        html.Button(
                            "Open data folder",
                            id="btn_open_data",
                            n_clicks=0,
                            className="mx-btn mx-btn--primary mx-btn--nowrap",
                            type="button",
                        )
                    ]
                ),
                html.Button(
                    "Recheck databases",
                    id="btn_check_databases",
                    n_clicks=0,
                    className="mx-btn mx-btn--primary mx-btn--nowrap",
                    type="button",
                ),
            ],
        ),
        *(
            [
                html.P(
                    "Running in Docker. Place the GeoLite2 .mmdb files in the "
                    "host folder mounted to this path.",
                    className="mx-note",
                )
            ]
            if is_docker
            else []
        ),
        html.P("Required files:"),
        html.Ul(
            [
                html.Li("GeoLite2-ASN.mmdb"),
                html.Li("GeoLite2-City.mmdb"),
            ]
        ),
        html.H2("Steps"),
        html.Ol(
            [
                *(
                    [html.Li("Open the data folder.")]
                    if not is_docker
                    else [
                        html.Li(
                            "Copy the GeoLite2 .mmdb files into the host "
                            "folder mapped to this path."
                        )
                    ]
                ),
                html.Li(
                    "Copy the GeoLite2 .mmdb files into the folder."
                    if not is_docker
                    else "Restart or return to the app after the files are in place."
                ),
                html.Li("Click Recheck GeoIP databases in the app."),
            ]
        ),
        html.H2("Download"),
        html.P(
            [
                "Download is free from MaxMind, but requires an account and "
                "acceptance of license terms. ",
                "Create a free account and download the databases here: ",
                html.A(
                    "MaxMind GeoLite2 download page",
                    href="https://dev.maxmind.com/geoip/geolite2-free-geolocation-data",
                    target="_blank",
                    rel="noopener noreferrer",
                ),
                ".",
            ]
        ),
        html.P(
            "Update recommendation: download updated databases regularly (for example monthly)."
        ),
    ]

first_idx(customdata) staticmethod

Extract a service index from Plotly customdata.

Supported forms
  • dict with keys {"kind", "idx"}
  • integer
  • nested list or tuple structures
Source code in ui/modal_view.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
@staticmethod
def first_idx(customdata: Any) -> int | None:
    """Extract a service index from Plotly customdata.

    Supported forms:
        - dict with keys {"kind", "idx"}
        - integer
        - nested list or tuple structures
    """
    if isinstance(customdata, dict):
        if customdata.get("kind") in {"target", "line"}:
            idx = customdata.get("idx")
            return idx if isinstance(idx, int) else None
        return None

    if isinstance(customdata, int):
        return customdata

    if isinstance(customdata, (list, tuple)) and customdata:
        return ModalTextBuilder.first_idx(customdata[0])

    return None

render_about(*, app_name, app_version, app_author, snapshot=None, is_docker)

Render About view content.

Read snapshot["app_info"] only and avoid network calls.

Source code in ui/about_view.py
 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
def render_about(
    *,
    app_name: str,
    app_version: str,
    app_author: str,
    snapshot: Any | None = None,
    is_docker: bool,
) -> list[Any]:
    """Render About view content.

    Read snapshot["app_info"] only and avoid network calls.
    """
    app_info: dict[str, Any] = {}
    if isinstance(snapshot, dict):
        info = snapshot.get("app_info")
        if isinstance(info, dict):
            app_info = info

    server_port = app_info.get("server_port")
    poll_ms = app_info.get("poll_interval_ms")
    coord_precision = app_info.get("coord_precision")
    near_km = app_info.get("zoom_near_km")

    geoinfo_enabled = bool(app_info.get("geoinfo_enabled", False))
    geo_data_dir_val = app_info.get("geo_data_dir")
    geo_data_dir = geo_data_dir_val if isinstance(geo_data_dir_val, str) else ""

    myloc_mode_val = app_info.get("myloc_mode")
    myloc_mode = myloc_mode_val if isinstance(myloc_mode_val, str) else "OFF"
    my_location = app_info.get("my_location")

    public_ip_cached = app_info.get("public_ip_cached")
    public_ip_cached = (
        public_ip_cached if isinstance(public_ip_cached, str) and public_ip_cached else None
    )

    auto_geo_cached = app_info.get("auto_geo_cached")
    auto_geo = auto_geo_cached if isinstance(auto_geo_cached, dict) else {}

    os_text = app_info.get("os") if isinstance(app_info.get("os"), str) else "-"
    py_text = app_info.get("python") if isinstance(app_info.get("python"), str) else "-"

    net_backend_val = app_info.get("net_backend")
    net_backend = net_backend_val if isinstance(net_backend_val, str) else "-"
    net_backend_version_val = app_info.get("net_backend_version")
    net_backend_version = (
        net_backend_version_val if isinstance(net_backend_version_val, str) else "-"
    )

    tapmap_rows: list[tuple[str, str]] = [
        ("Name", app_name),
        ("Version", app_version),
        ("Author", app_author),
        ("Server port", str(server_port) if isinstance(server_port, int) else "-"),
        ("Poll interval", f"{poll_ms} ms" if isinstance(poll_ms, int) else "-"),
        ("Coord precision", str(coord_precision) if coord_precision is not None else "-"),
        ("Near distance", f"{near_km} km" if isinstance(near_km, (int, float)) else "-"),
    ]

    geo_rows: list[tuple[str, str]] = [
        ("Geolocation", "Enabled" if geoinfo_enabled else "Disabled"),
        ("GeoIP data folder", geo_data_dir if geo_data_dir else "-"),
    ]

    location_rows = _build_location_rows(
        myloc_mode=myloc_mode,
        my_location=my_location,
        public_ip_cached=public_ip_cached,
        auto_geo=auto_geo,
    )

    runtime_rows: list[tuple[str, str]] = [
        ("OS", os_text),
        ("Python", py_text),
        ("Network backend", net_backend),
        ("Backend version", net_backend_version),
    ]

    return [
        html.H1(f"About {app_name}"),
        html.P(
            "TapMap inspects local socket data, enriches IP addresses "
            "with geolocation, and visualizes their locations on an interactive map."
        ),
        html.P(
            "It reads active socket data using a platform-specific backend, "
            "local MaxMind GeoLite2 databases for geolocation, "
            "and Dash with Plotly for visualization."
        ),
        html.P("All processing is local. TapMap does not inspect traffic contents."),
        kv_table(tapmap_rows),
        html.H2("Geolocation"),
        html.P(
            "Geolocation is based on local MaxMind GeoLite2 .mmdb databases. "
            "The databases are not included."
        ),
        kv_table(geo_rows),
        html.Div(
            className="mx-path-row",
            children=[
                html.Pre(geo_data_dir, className="mx-path-box") if geo_data_dir else None,
                *(
                    []
                    if is_docker
                    else [
                        html.Button(
                            "Open data folder",
                            id="btn_open_data",
                            n_clicks=0,
                            className="mx-btn mx-btn--primary mx-btn--nowrap",
                            type="button",
                        )
                    ]
                ),
                html.Button(
                    "Recheck GeoIP databases",
                    id="btn_check_databases",
                    n_clicks=0,
                    className="mx-btn mx-btn--primary mx-btn--nowrap",
                    type="button",
                ),
            ],
        ),
        *(
            [
                html.P(
                    "Running in Docker. Place the GeoLite2 .mmdb files in the "
                    "host folder mounted to this path.",
                    className="mx-note",
                )
            ]
            if is_docker
            else []
        ),
        html.H2("Location"),
        kv_table(location_rows),
        html.H2("Runtime"),
        kv_table(runtime_rows),
        html.H2("Project"),
        html.P("TapMap is free and open source."),
        html.Ul(
            [
                html.Li(
                    html.A(
                        "Project page on GitHub",
                        href="https://github.com/olalie/tapmap",
                        target="_blank",
                        rel="noopener noreferrer",
                    )
                ),
                html.Li(
                    html.A(
                        "MaxMind GeoLite2 project",
                        href="https://dev.maxmind.com/geoip/geolite2-free-geolocation-data",
                        target="_blank",
                        rel="noopener noreferrer",
                    )
                ),
                html.Li(
                    html.A(
                        "Buy Me a Coffee",
                        href="https://www.buymeacoffee.com/olalie",
                        target="_blank",
                        rel="noopener noreferrer",
                    )
                ),
            ]
        ),
    ]

port_from_local(addr)

Extract port from an 'ip:port' string.

Source code in ui/formatting.py
31
32
33
34
35
36
def port_from_local(addr: str) -> int:
    """Extract port from an 'ip:port' string."""
    try:
        return int(addr.rsplit(":", 1)[-1])
    except (ValueError, TypeError):
        return -1

pretty_bind_ip(ip)

Map wildcard bind addresses to readable labels.

Source code in ui/formatting.py
56
57
58
59
60
61
62
def pretty_bind_ip(ip: str) -> str:
    """Map wildcard bind addresses to readable labels."""
    if ip == "0.0.0.0":
        return "ALL (IPv4)"
    if ip == "::":
        return "ALL (IPv6)"
    return ip

safe_int(value, default=-1)

Convert value to int, or return default on failure.

Source code in ui/formatting.py
17
18
19
20
21
22
def safe_int(value: Any, default: int = -1) -> int:
    """Convert value to int, or return default on failure."""
    try:
        return int(value)
    except (TypeError, ValueError):
        return default

safe_str(value)

Return empty string for None, otherwise str(value).

Source code in ui/formatting.py
12
13
14
def safe_str(value: Any) -> str:
    """Return empty string for None, otherwise str(value)."""
    return "" if value is None else str(value)

scope_rank(scope)

Return sort rank for scope values.

Source code in ui/formatting.py
25
26
27
28
def scope_rank(scope: str) -> int:
    """Return sort rank for scope values."""
    order = {"PUBLIC": 0, "LAN": 1, "LOCAL": 2}
    return order.get(scope.upper(), 9)

strip_port(addr)

Remove trailing ':port' from an address string.

Source code in ui/formatting.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def strip_port(addr: str) -> str:
    """Remove trailing ':port' from an address string."""
    if not addr:
        return ""

    s = addr.strip()

    if s.startswith("["):
        end = s.find("]")
        return s[1:end].strip() if end != -1 else s

    if s.count(":") == 1:
        return s.rsplit(":", 1)[0].strip()

    return s

render_help()

Build Help modal content.

Returns a list of Dash components representing the Help window. No side effects. Pure view construction.

Source code in ui/help_view.py
 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
def render_help() -> list[Any]:
    """Build Help modal content.

    Returns a list of Dash components representing the Help window.
    No side effects. Pure view construction.
    """
    return [
        html.H1("Help"),
        html.P(
            [
                "TapMap shows the locations of the systems your computer connects to on a "
                "world map.",
                html.Br(),
                "Explore each location for summaries and details about the systems and the local ",
                "programs involved.",
            ]
        ),
        html.H2("Quick start"),
        html.Ul(
            [
                html.Li("Start TapMap."),
                html.Li(
                    [
                        "If a 'Missing GeoIP databases' window appears:",
                        html.Ul(
                            [
                                html.Li("Click Open data folder."),
                                html.Li(
                                    "Copy GeoLite2-City.mmdb and GeoLite2-ASN.mmdb into that "
                                    "folder."
                                ),
                                html.Li("Click Recheck GeoIP databases."),
                            ]
                        ),
                    ]
                ),
                html.Li("Hover map markers for a summary."),
                html.Li("Click map markers for detailed information."),
                html.Li(
                    "Use the mouse or Plotly tools (top right) to pan, zoom, or reset the view."
                ),
            ]
        ),
        html.H2("Definitions"),
        html.Table(
            className="mx-table mx-kv",
            children=[
                html.Tbody(
                    [
                        html.Tr(
                            [
                                html.Td("Snapshot"),
                                html.Td(
                                    "A readout of network connections at a specific moment "
                                    "(refreshed regularly)."
                                ),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("Service"),
                                html.Td(
                                    "A service on the other side, identified by protocol, IP, and "
                                    "port."
                                ),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("Socket"),
                                html.Td(
                                    [
                                        "One local process using one socket entry in the snapshot.",
                                        html.Br(),
                                        "Multiple sockets can refer to the same service.",
                                    ]
                                ),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("Map marker"),
                                html.Td(
                                    [
                                        "A location on the map.",
                                        html.Br(),
                                        "One marker can represent multiple services "
                                        "if they share the same rounded coordinates.",
                                    ]
                                ),
                            ]
                        ),
                    ]
                ),
            ],
        ),
        html.P(
            [
                "Scope describes where an address belongs:",
                html.Br(),
                "external internet (PUBLIC), your local network (LAN), or your own "
                "machine (LOCAL).",
            ]
        ),
        html.H3("Scope"),
        html.Table(
            className="mx-table mx-kv",
            children=[
                html.Tbody(
                    [
                        html.Tr([html.Td("PUBLIC"), html.Td("External internet address.")]),
                        html.Tr(
                            [
                                html.Td("LAN"),
                                html.Td(
                                    "Private network address, for example 192.168.x.x or 10.x.x.x."
                                ),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("LOCAL"),
                                html.Td("Loopback address, for example 127.0.0.1 or ::1."),
                            ]
                        ),
                    ]
                ),
            ],
        ),
        html.P(
            "Map markers represent PUBLIC services with geolocation. "
            "LAN and LOCAL services are not shown on the map."
        ),
        html.H2("Map legend"),
        html.Ul(
            [
                html.Li(
                    [
                        html.Span("Magenta", style={"color": "magenta", "fontSize": "larger"}),
                        " markers and lines show PUBLIC services with geolocation.",
                    ]
                ),
                html.Li(
                    [
                        html.Span("Yellow", style={"color": "yellow", "fontSize": "larger"}),
                        " markers and lines indicate nearby locations.",
                    ]
                ),
                html.Li(
                    [
                        html.Span("Cyan", style={"color": "cyan", "fontSize": "larger"}),
                        " marker shows your location, if enabled.",
                    ]
                ),
            ]
        ),
        html.P(
            [
                "Yellow is a visual hint. Zoom in or change view direction to separate "
                "nearby locations.",
                html.Br(),
                "Location grouping is separate. PUBLIC services with the same rounded "
                "coordinates are shown as one marker.",
            ]
        ),
        html.H2("Controls"),
        html.Table(
            className="mx-table",
            children=[
                html.Colgroup(
                    [
                        html.Col(style={"width": "50px"}),
                        html.Col(),
                        html.Col(style={"width": "75px"}),
                    ]
                ),
                html.Thead(
                    html.Tr(
                        [
                            html.Th("Key"),
                            html.Th("Action"),
                            html.Th("Result"),
                        ]
                    )
                ),
                html.Tbody(
                    [
                        html.Tr(
                            [
                                html.Td("U"),
                                html.Td("Show unmapped public services (missing geolocation)"),
                                html.Td("Window"),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("L"),
                                html.Td("Show established LAN and LOCAL services"),
                                html.Td("Window"),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("O"),
                                html.Td("Show open ports (TCP LISTEN and UDP bound)"),
                                html.Td("Window"),
                            ]
                        ),
                        html.Tr(
                            [html.Td("T"), html.Td("Show cache in terminal"), html.Td("Status")]
                        ),
                        html.Tr([html.Td("C"), html.Td("Clear cache"), html.Td("Status")]),
                        html.Tr(
                            [html.Td("R"), html.Td("Recheck GeoIP databases"), html.Td("Status")]
                        ),
                        html.Tr([html.Td("H"), html.Td("Help"), html.Td("Window")]),
                        html.Tr([html.Td("A"), html.Td("About"), html.Td("Window")]),
                        html.Tr([html.Td("ESC"), html.Td("Close window"), html.Td("Window")]),
                    ]
                ),
            ],
        ),
        html.H2("Unmapped public services"),
        html.P(
            "The Unmapped window lists PUBLIC services that are not shown on the map because "
            "geolocation is missing."
        ),
        html.P(
            "Scope in this window describes where the service address belongs. "
            "LAN and LOCAL services are excluded from this view."
        ),
        html.P(
            "Count shows how many sockets were merged into the row for the latest snapshot. "
            "Rows are grouped by scope, protocol, IP, port, PID, and process."
        ),
        html.P(
            "In narrow windows, some fields may be truncated. Hover a cell to see the full value."
        ),
        html.H2("Established LAN/LOCAL services"),
        html.P(
            "This window lists established TCP sockets where the service is LAN or LOCAL. "
            "These services are not shown on the map."
        ),
        html.P(
            "Count shows how many sockets were merged into the row for the latest snapshot. "
            "Rows are grouped by scope, protocol, IP, port, PID, and process for the other side."
        ),
        html.P("Scope in this window describes where the service address belongs."),
        html.H2("Open ports"),
        html.P(
            [
                "The Open ports window lists local TCP sockets in LISTEN state and UDP sockets "
                "bound to local ports."
            ]
        ),
        html.P(
            "TCP LISTEN means a local process waits for incoming connections. "
            "UDP bound means a local process can receive datagrams on that port."
        ),
        html.P("This is a local view only. Services on the other side are not shown."),
        html.P(
            "Scope in this window describes how the local process is bound: "
            "loopback only, LAN only, or all interfaces."
        ),
        html.P("System processes are hidden by default. Use the toggle to include them."),
        html.H2("Show cache in terminal"),
        html.P("Print the current cache contents to the terminal where TapMap is running."),
        html.H2("Status line"),
        html.P(
            "Short status messages may appear after commands such as Clear cache or "
            "Recheck databases."
        ),
        html.H3("STATUS: WAIT | OK | OFFLINE | ERROR"),
        html.Table(
            className="mx-table mx-kv",
            children=[
                html.Tbody(
                    [
                        html.Tr([html.Td("WAIT"), html.Td("No snapshot received yet.")]),
                        html.Tr([html.Td("OK"), html.Td("Snapshot received successfully.")]),
                        html.Tr(
                            [
                                html.Td("OFFLINE"),
                                html.Td(
                                    "Snapshot received, but no internet connectivity detected."
                                ),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("ERROR"),
                                html.Td("Failed to fetch or enrich data. See terminal."),
                            ]
                        ),
                    ]
                ),
            ],
        ),
        html.H3("LIVE"),
        html.P("LIVE shows counters from the current snapshot."),
        html.Table(
            className="mx-table mx-kv",
            children=[
                html.Tbody(
                    [
                        html.Tr(
                            [
                                html.Td("TCP"),
                                html.Td(
                                    "Total TCP entries in the snapshot, across all TCP states."
                                ),
                            ]
                        ),
                        html.Tr([html.Td("EST"), html.Td("TCP entries in state ESTABLISHED.")]),
                        html.Tr(
                            [
                                html.Td("LST"),
                                html.Td("Listening TCP sockets on the local machine."),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("UDP R"),
                                html.Td("UDP entries that have a remote address available."),
                            ]
                        ),
                        html.Tr([html.Td("UDP B"), html.Td("UDP entries bound to a local port.")]),
                    ]
                ),
            ],
        ),
        html.P("TCP includes states such as TIME_WAIT, SYN_SENT, and CLOSE_WAIT."),
        html.H3("CACHE"),
        html.P("CACHE shows aggregated counters since the last Clear cache or app start."),
        html.Table(
            className="mx-table mx-kv",
            children=[
                html.Tbody(
                    [
                        html.Tr(
                            [
                                html.Td("SOCK"),
                                html.Td("Unique sockets (proto, IP, port, PID or process)."),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("SERV"),
                                html.Td("Unique services (proto, IP, port)."),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("MAP"),
                                html.Td("Unique mapped public services (have geolocation)."),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("UNM"),
                                html.Td("Unique unmapped public services (missing geolocation)."),
                            ]
                        ),
                        html.Tr([html.Td("LOC"), html.Td("Unique LAN and loopback services.")]),
                    ]
                ),
            ],
        ),
        html.P("SERV is derived from SOCK by ignoring PID and process."),
        html.H3("UPDATED"),
        html.P("Time of the last snapshot."),
        html.H3("MYLOC: FIXED | AUTO | AUTO (NO GEO) | OFF"),
        html.P("Shows your local map location based on the MY_LOCATION setting in config.py."),
        html.Table(
            className="mx-table mx-kv",
            children=[
                html.Tbody(
                    [
                        html.Tr(
                            [html.Td("FIXED"), html.Td("Uses fixed coordinates from config.py.")]
                        ),
                        html.Tr(
                            [html.Td("AUTO"), html.Td("Location detected from your public IP.")]
                        ),
                        html.Tr(
                            [
                                html.Td("AUTO (NO GEO)"),
                                html.Td("Public IP detected, but no geolocation available."),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("OFF"),
                                html.Td("Local marker and connection lines are hidden."),
                            ]
                        ),
                    ]
                ),
            ],
        ),
        html.H2("GeoIP databases (MaxMind GeoLite2)"),
        html.P(
            "TapMap uses local MaxMind mmdb files for geolocation. The databases are not included."
        ),
        html.P("Required files:"),
        html.Ul([html.Li("GeoLite2-City.mmdb"), html.Li("GeoLite2-ASN.mmdb")]),
        html.P("If the databases are missing, a setup window appears at startup."),
        html.P(
            "Open the data folder from that window or from About. Copy the files into it and use "
            "Recheck GeoIP databases to enable geolocation without restarting."
        ),
        html.P(
            [
                "The databases are free from MaxMind but require an account and acceptance of "
                "license terms. Download them here: ",
                html.A(
                    "MaxMind GeoLite2 download page",
                    href="https://dev.maxmind.com/geoip/geolite2-free-geolocation-data",
                    target="_blank",
                ),
                ".",
            ]
        ),
        html.P("Update the databases regularly, for example monthly."),
        html.H2("Configuration (config.py)"),
        html.P("TapMap reads settings from config.py. Edit this file to adjust behavior."),
        html.P("Common settings:"),
        html.Table(
            className="mx-table mx-kv",
            children=[
                html.Colgroup([html.Col(style={"width": "130px"}), html.Col()]),
                html.Tbody(
                    [
                        html.Tr(
                            [
                                html.Td("SERVER_PORT"),
                                html.Td(
                                    "Default port used by the local Dash server. "
                                    "Can be overridden at startup using the "
                                    "TAPMAP_PORT environment variable."
                                ),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("MY_LOCATION"),
                                html.Td(
                                    "'none' hides the local marker. Use (lon, lat) for fixed "
                                    "coordinates, or 'auto' to detect from public IP."
                                ),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("POLL_INTERVAL_MS"),
                                html.Td("Snapshot refresh interval in milliseconds."),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("COORD_PRECISION"),
                                html.Td(
                                    "Decimal precision used to group PUBLIC services into one "
                                    "marker. 3 is approximately 100 meters."
                                ),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td("ZOOM_NEAR_KM"),
                                html.Td(
                                    "Distance threshold for marking locations as nearby in yellow."
                                ),
                            ]
                        ),
                    ]
                ),
            ],
        ),
        html.H2("Network and location notes"),
        html.P("IP based geolocation is approximate."),
        html.P(
            "ASN and ASN organization identify the network operator, not necessarily the "
            "service owner."
        ),
        html.P("CDNs and hosting providers can make a service appear in another country."),
        html.P("VPN and Tor can hide the true origin of a PUBLIC service location."),
        html.H2("Privacy and safety"),
        html.P("TapMap runs locally and reads local network connections."),
        html.P("Geolocation lookups are performed locally using the mmdb files."),
        html.P(
            "If MY_LOCATION is set to 'auto', TapMap may query external services to detect the "
            "public IP address. It stops after the first valid result."
        ),
        html.P(
            [
                "To detect OFFLINE status, TapMap performs short connection checks to ",
                "1.1.1.1 and 8.8.8.8.",
            ]
        ),
    ]

build_table(*, class_name, columns, header_cells, body_rows)

Build a Dash HTML table with colgroup, thead and tbody.

Source code in ui/tables.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def build_table(
    *,
    class_name: str,
    columns: Sequence[ColumnSpec],
    header_cells: Sequence[str],
    body_rows: Iterable[Any],
) -> html.Table:
    """Build a Dash HTML table with colgroup, thead and tbody."""
    colgroup = html.Colgroup(
        [html.Col(style={"width": col.width}) if col.width else html.Col() for col in columns]
    )

    thead = html.Thead(html.Tr([html.Th(h) for h in header_cells]))

    tbody = html.Tbody(list(body_rows))

    return html.Table(
        className=class_name,
        children=[colgroup, thead, tbody],
    )

cell(text, *, title=None)

Render a table cell with truncation and tooltip.

Source code in ui/tables.py
24
25
26
27
28
29
def cell(text: str, *, title: str | None = None) -> html.Td:
    """Render a table cell with truncation and tooltip."""
    value = text or ""
    tooltip = title if title is not None else value
    tooltip = tooltip if tooltip else None
    return html.Td(html.Span(value, className="mx-cell-text", title=tooltip))