diff --git a/config/config.example.yaml b/config/config.example.yaml index c2eb20a..3cd4fce 100644 --- a/config/config.example.yaml +++ b/config/config.example.yaml @@ -112,6 +112,9 @@ reports: # Количество последних сессий, отображаемых в соответствующих разделах. recent_sessions_limit: 10 + # Количество сессий на странице Capture Sessions по умолчанию. + sessions_page_limit: 20 + # Настройки журналирования приложения. logging: # Уровень подробности журналов. diff --git a/gui/app.py b/gui/app.py index 9c7e5f3..2f2a6c8 100644 --- a/gui/app.py +++ b/gui/app.py @@ -58,8 +58,10 @@ from reports.hashcat import ( ) from reports.trips_page import render_trips_page from reports.wifitrip import ( + WifitripError, export_wifitrip, import_wifitrip, + select_wifitrip_session_ids, validate_wifitrip, ) from reports.session_page import render_session_page @@ -2039,7 +2041,8 @@ def reports_dashboard(): def reports_capture_sessions(): return render_report( - generate_capture_sessions + generate_capture_sessions, + sessions_page_limit=request.args.get("limit"), ) @app.route("/reports/trips/") @@ -2050,50 +2053,114 @@ def reports_trips(): ) -@app.route("/reports/trips/export") -def reports_trips_export(): - - filename = ( - "wifi-gps-mapper-" - f"{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}.wifitrip" - ) - - temp_file = tempfile.NamedTemporaryFile( - prefix="wifitrip-", - suffix=".tmp", - delete=False, - ) - - temp_path = Path( - temp_file.name - ) - - temp_file.close() - - output_path = ( - temp_path.with_name( - filename - ) - ) - - temp_path.unlink( - missing_ok=True - ) +@app.route("/reports/trips/preview") +def reports_trips_preview(): conn = connect_database() try: + session_ids = select_wifitrip_session_ids( + conn, + mode=request.args.get("mode", "all"), + limit=request.args.get("limit", "1"), + date_from=request.args.get("date_from"), + date_to=request.args.get("date_to"), + ) + + available_count = conn.execute( + "SELECT COUNT(*) FROM capture_sessions" + ).fetchone()[0] + + except WifitripError as exc: + return jsonify( + { + "error": str(exc), + } + ), 400 + + finally: + close_database(conn) + + return jsonify( + { + "count": len(session_ids), + "available_count": available_count, + } + ) + + +@app.route("/reports/trips/export") +def reports_trips_export(): + + conn = connect_database() + output_path = None + + try: + session_ids = select_wifitrip_session_ids( + conn, + mode=request.args.get("mode", "all"), + limit=request.args.get("limit", "1"), + date_from=request.args.get("date_from"), + date_to=request.args.get("date_to"), + ) + + if not session_ids: + return jsonify( + { + "error": "No capture sessions match the selected criteria.", + } + ), 400 + + filename = ( + "wifi-gps-mapper-" + f"{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}.wifitrip" + ) + + temp_file = tempfile.NamedTemporaryFile( + prefix="wifitrip-", + suffix=".tmp", + delete=False, + ) + + temp_path = Path( + temp_file.name + ) + + temp_file.close() + + output_path = temp_path.with_name( + filename + ) + + temp_path.unlink( + missing_ok=True + ) result = export_wifitrip( conn, output_path=output_path, + session_ids=session_ids, ) + except WifitripError as exc: + + if output_path is not None: + output_path.unlink( + missing_ok=True + ) + + return jsonify( + { + "error": str(exc), + } + ), 400 + except Exception: - output_path.unlink( - missing_ok=True - ) + if output_path is not None: + output_path.unlink( + missing_ok=True + ) raise diff --git a/reports/config.py b/reports/config.py index b89b50b..eb8984f 100644 --- a/reports/config.py +++ b/reports/config.py @@ -56,6 +56,15 @@ RECENT_SESSIONS_LIMIT = REPORTS_CONFIG.get( 10 ) +try: + SESSIONS_PAGE_LIMIT = int( + REPORTS_CONFIG.get("sessions_page_limit", 20) + ) + if SESSIONS_PAGE_LIMIT <= 0: + raise ValueError +except (TypeError, ValueError): + SESSIONS_PAGE_LIMIT = 20 + TIMEZONE = CONFIG.get("timezone", "Europe/Moscow") @lru_cache(maxsize=1) diff --git a/reports/dashboard.py b/reports/dashboard.py index 1ef2947..34ede71 100644 --- a/reports/dashboard.py +++ b/reports/dashboard.py @@ -20,6 +20,7 @@ from pathlib import Path from .config import ( RECENT_SESSIONS_LIMIT, + SESSIONS_PAGE_LIMIT, ) from .utils import ( @@ -807,8 +808,21 @@ def generate_dashboard( def generate_capture_sessions( conn, context=None, + sessions_page_limit=None, ): + if sessions_page_limit is None: + display_limit = SESSIONS_PAGE_LIMIT + elif str(sessions_page_limit).lower() == "all": + display_limit = "all" + else: + try: + display_limit = int(sessions_page_limit) + if display_limit <= 0: + raise ValueError + except (TypeError, ValueError): + display_limit = SESSIONS_PAGE_LIMIT + sessions = all_sessions( conn ) @@ -957,7 +971,7 @@ Total sessions: {len(sessions)} """) - html += """ + html += f"""
@@ -981,12 +995,40 @@ Total sessions: {len(sessions)} ↓ + + + + + + + +
""" @@ -1002,13 +1044,83 @@ Total sessions: {len(sessions)} const list = document.getElementById("session-list"); const sortSelect = document.getElementById("session-sort"); const directionButton = document.getElementById("session-sort-direction"); + const limitSelect = document.getElementById("session-limit"); + const customLimitInput = document.getElementById("session-custom-limit"); + const sessionCount = document.getElementById("session-count"); - if (!list || !sortSelect || !directionButton) { + if ( + !list || + !sortSelect || + !directionButton || + !limitSelect || + !customLimitInput || + !sessionCount + ) { return; } let descending = true; + const defaultLimit = Number(list.dataset.defaultLimit) || 20; + const initialLimit = list.dataset.displayLimit; + const predefinedLimits = ["10", "20", "50", "100", "500", "all"]; + + function getDisplayLimit() { + + if (limitSelect.value === "all") { + return "all"; + } + + if (limitSelect.value === "custom") { + const value = Number(customLimitInput.value); + + if ( + !Number.isInteger(value) || + value <= 0 + ) { + return defaultLimit; + } + + return value; + } + + return Number(limitSelect.value) || defaultLimit; + } + + function updateUrl() { + + const params = new URLSearchParams(window.location.search); + const limit = getDisplayLimit(); + + params.set("limit", String(limit)); + + const query = params.toString(); + const newUrl = window.location.pathname + + (query ? "?" + query : "") + + window.location.hash; + + window.history.replaceState({}, "", newUrl); + } + + function applyDisplayLimit() { + + const cards = Array.from( + list.querySelectorAll(".session-compact-card") + ); + + const limit = getDisplayLimit(); + const visibleCount = limit === "all" + ? cards.length + : Math.min(cards.length, limit); + + cards.forEach(function (card, index) { + card.style.display = index >= visibleCount ? "none" : ""; + }); + + sessionCount.textContent = + "Showing " + visibleCount + " of " + cards.length; + } + function sortSessions() { const sortBy = sortSelect.value; @@ -1071,6 +1183,8 @@ Total sessions: {len(sessions)} directionButton.textContent = descending ? "↓" : "↑"; list.dataset.sortDirection = descending ? "desc" : "asc"; + + applyDisplayLimit(); } sortSelect.addEventListener("change", function () { @@ -1087,6 +1201,51 @@ Total sessions: {len(sessions)} sortSessions(); }); + limitSelect.addEventListener("change", function () { + + if (limitSelect.value !== "custom") { + customLimitInput.value = ""; + } + + if (limitSelect.value === "custom") { + customLimitInput.focus(); + } + + applyDisplayLimit(); + updateUrl(); + }); + + customLimitInput.addEventListener("input", function () { + + limitSelect.value = "custom"; + + const value = Number(customLimitInput.value); + + if ( + Number.isInteger(value) && + value > 0 + ) { + applyDisplayLimit(); + updateUrl(); + } else { + applyDisplayLimit(); + } + }); + + if (initialLimit === "all") { + + limitSelect.value = "all"; + + } else if (predefinedLimits.includes(initialLimit)) { + + limitSelect.value = initialLimit; + + } else { + + limitSelect.value = "custom"; + customLimitInput.value = initialLimit; + } + sortSessions(); })(); diff --git a/reports/static/report.css b/reports/static/report.css index c57504c..4602644 100644 --- a/reports/static/report.css +++ b/reports/static/report.css @@ -593,11 +593,13 @@ code { margin-bottom: 18px; } -.session-list-toolbar label { +.session-list-toolbar label, +.session-list-toolbar #session-count { color: var(--muted); } -.session-list-toolbar select { +.session-list-toolbar select, +.session-list-toolbar input[type="number"] { background: var(--surface); color: var(--text); @@ -1727,3 +1729,167 @@ body .maplibregl-popup-close-button:hover { cursor: pointer; font-weight: 600; } + + +/* ============================================================ + WiFiTrip export selection + ============================================================ */ + +.wifitrip-export-options { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 18px; + margin-top: 22px; +} + +.wifitrip-export-mode { + min-width: 0; + padding: 16px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 9px; + transition: + border-color 0.15s ease, + background 0.15s ease; +} + +.wifitrip-export-mode:has(.wifitrip-mode-tab input:checked) { + border-color: var(--accent); + background: var(--surface-light); +} + +.wifitrip-mode-tab { + display: flex; + align-items: center; + gap: 10px; + min-height: 24px; + color: var(--muted); + font-size: 15px; + font-weight: 700; + cursor: pointer; +} + +.wifitrip-mode-tab input { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; + pointer-events: none; +} + +.wifitrip-mode-tab span { + display: block; + width: 100%; + padding: 5px 0 12px; + border-bottom: 2px solid transparent; + transition: + color 0.15s ease, + border-color 0.15s ease; +} + +.wifitrip-mode-tab input:checked + span { + color: var(--text); + border-bottom-color: var(--accent); +} + +.wifitrip-mode-tab input:focus-visible + span { + outline: 2px solid var(--accent); + outline-offset: 4px; +} + +.wifitrip-mode-content { + display: flex; + flex-direction: column; + gap: 9px; + margin-top: 16px; +} + +.wifitrip-mode-content label { + color: var(--muted); + font-size: 13px; +} + +.wifitrip-mode-content .session-list-toolbar label { + font-size: inherit; +} + +.wifitrip-mode-content > select, +.wifitrip-mode-content input[type="date"] { + width: 100%; + min-height: 38px; + padding: 8px 12px; + background: var(--surface); + color: var(--text); + border: 1px solid var(--border); + border-radius: 7px; + font-family: "Bender", Arial, Helvetica, sans-serif; + font-size: 14px; + color-scheme: dark; +} + +.wifitrip-mode-content select:focus, +.wifitrip-mode-content input[type="date"]:focus, +.wifitrip-mode-content input[type="number"]:focus { + outline: none; + border-color: var(--accent); + box-shadow: 0 0 0 2px rgba(105, 167, 255, 0.12); +} + +.wifitrip-mode-content select:disabled, +.wifitrip-mode-content input[type="date"]:disabled, +.wifitrip-mode-content input[type="number"]:disabled { + opacity: 0.45; + cursor: not-allowed; +} + + + +.wifitrip-date-fields { + gap: 14px; +} + +.wifitrip-date-fields > div { + display: flex; + flex-direction: column; + gap: 9px; +} + +.wifitrip-export-footer { + display: flex; + flex-direction: column; + align-items: center; + gap: 14px; + margin-top: 24px; + text-align: center; +} + +.wifitrip-export-footer p { + margin: 0; + color: var(--text); + font-weight: 700; +} + +.wifitrip-export-footer .button { + min-width: 220px; + text-align: center; +} + +.wifitrip-export-footer .button:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +@media (max-width: 700px) { + .wifitrip-export-options { + grid-template-columns: 1fr; + gap: 12px; + } + + .wifitrip-export-mode { + padding: 14px; + } + + .wifitrip-export-footer .button { + width: 100%; + } +} diff --git a/reports/trips_page.py b/reports/trips_page.py index 7c4043b..931617d 100644 --- a/reports/trips_page.py +++ b/reports/trips_page.py @@ -234,12 +234,6 @@ def render_trips_page( page="trips", ) - session_count = conn.execute( - """ - SELECT COUNT(*) AS count - FROM capture_sessions - """ - ).fetchone()["count"] html = page_begin( "Trips", @@ -257,44 +251,450 @@ def render_trips_page( ) html += """ +
-

Export capture sessions

+

Экспорт поездок

-Export all capture sessions into one -.wifitrip package. +Выберите поездки, которые нужно включить +в пакет .wifitrip.

-The package contains logical session data: -GPS track, access-point observations, -handshakes and credentials. Physical capture -files are not included. +Пакет содержит данные поездок: GPS-треки, +наблюдения точек доступа и рукопожатия. +Файлы захвата и пароли не включаются.

-
-""" - - html += _stat_card( - "Sessions available", - session_count, - ) - - html += """ -
- +
+ +
+ + +
+
+ + + + + + + +
+
+
+ +
+ + +
+
+ + + +
+ +
+ + + +
+
+
+ +
+ +
+ +
""" diff --git a/reports/wifitrip.py b/reports/wifitrip.py index aea4846..6473284 100644 --- a/reports/wifitrip.py +++ b/reports/wifitrip.py @@ -24,7 +24,7 @@ logger = logging.getLogger(__name__) WIFITRIP_FORMAT = "wifitrip" -WIFITRIP_VERSION = 1 +WIFITRIP_VERSION = 2 SESSION_HASH_VERSION = 1 REQUIRED_FILES = ( @@ -34,7 +34,6 @@ REQUIRED_FILES = ( "access_points.json", "observations.json", "handshakes.json", - "credentials.json", ) SHA256_RE = re.compile(r"^[0-9a-f]{64}$") @@ -167,6 +166,12 @@ def _read_package(path): "Archive contains duplicate file names." ) + if "credentials.json" in names: + raise WifitripError( + "Archive contains unsupported file: " + "credentials.json" + ) + missing = [ name for name in REQUIRED_FILES @@ -212,7 +217,6 @@ def _validate_package(data): access_points = data["access_points.json"] observations = data["observations.json"] handshakes = data["handshakes.json"] - credentials = data["credentials.json"] _require_dict( manifest, @@ -238,10 +242,6 @@ def _validate_package(data): handshakes, "handshakes.json", ) - _require_list( - credentials, - "credentials.json", - ) if manifest.get("format") != WIFITRIP_FORMAT: raise WifitripError( @@ -659,97 +659,6 @@ def _validate_package(data): f"handshakes.json[{index}].speed", ) - for index, credential in enumerate( - credentials - ): - _require_dict( - credential, - f"credentials.json[{index}]", - ) - - session_hash = credential.get( - "session_hash" - ) - bssid = credential.get( - "bssid" - ) - handshake_key = credential.get( - "handshake_key" - ) - - _validate_hash( - session_hash, - f"credentials.json[{index}].session_hash", - ) - - _require_bssid( - bssid, - f"credentials.json[{index}].bssid", - ) - - if session_hash not in session_versions: - raise WifitripError( - "Credential references unknown session: " - f"{session_hash}" - ) - - if bssid not in ap_map: - raise WifitripError( - "Credential references unknown BSSID: " - f"{bssid}" - ) - - if handshake_key is not None: - _require_string( - handshake_key, - f"credentials.json[{index}].handshake_key", - ) - - if handshake_key not in handshake_keys.get( - session_hash, - set(), - ): - raise WifitripError( - "Credential references unknown handshake_key: " - f"{session_hash}: {handshake_key}" - ) - - _require_string( - credential.get("password"), - f"credentials.json[{index}].password", - ) - - if not credential.get("password"): - raise WifitripError( - "Credential password must not be empty." - ) - - _require_string( - credential.get("source"), - f"credentials.json[{index}].source", - allow_none=True, - ) - - _require_string( - credential.get("created_at"), - f"credentials.json[{index}].created_at", - allow_none=True, - ) - - verified = credential.get( - "verified" - ) - - _require_integer( - verified, - f"credentials.json[{index}].verified", - allow_none=False, - ) - - if verified not in (0, 1): - raise WifitripError( - "Credential verified must be 0 or 1." - ) def _session_hash(conn, session_id): @@ -891,7 +800,110 @@ def _zip_write_json(archive, filename, value): ) -def export_wifitrip(conn, output_path=None): +def select_wifitrip_session_ids( + conn, + mode="all", + limit=1, + date_from=None, + date_to=None, +): + if mode == "latest": + if str(limit).lower() == "all": + rows = conn.execute( + """ + SELECT id + FROM capture_sessions + ORDER BY start_time DESC, id DESC + """ + ).fetchall() + + else: + try: + limit = int(limit) + except (TypeError, ValueError): + raise WifitripError( + "Invalid session limit." + ) + + available_count = conn.execute( + "SELECT COUNT(*) FROM capture_sessions" + ).fetchone()[0] + + if limit < 1 or limit > available_count: + raise WifitripError( + "Session limit must be between 1 and " + f"{available_count}, or all." + ) + + rows = conn.execute( + """ + SELECT id + FROM capture_sessions + ORDER BY start_time DESC, id DESC + LIMIT ? + """, + (limit,), + ).fetchall() + + elif mode == "range": + try: + start_date = datetime.strptime( + date_from, + "%Y-%m-%d", + ).date() + end_date = datetime.strptime( + date_to, + "%Y-%m-%d", + ).date() + except (TypeError, ValueError): + raise WifitripError( + "A valid start and end date are required." + ) + + if start_date > end_date: + raise WifitripError( + "Start date must not be later than end date." + ) + + rows = conn.execute( + """ + SELECT id + FROM capture_sessions + WHERE substr(start_time, 1, 10) + BETWEEN ? AND ? + ORDER BY start_time DESC, id DESC + """, + ( + start_date.isoformat(), + end_date.isoformat(), + ), + ).fetchall() + + elif mode == "all": + rows = conn.execute( + """ + SELECT id + FROM capture_sessions + ORDER BY start_time DESC, id DESC + """ + ).fetchall() + + else: + raise WifitripError( + "Invalid session selection mode." + ) + + return [ + row["id"] + for row in rows + ] + + +def export_wifitrip( + conn, + output_path=None, + session_ids=None, +): started = time.monotonic() if output_path is None: @@ -909,18 +921,47 @@ def export_wifitrip(conn, output_path=None): exist_ok=True, ) - sessions = conn.execute( - """ - SELECT - id, - start_time, - end_time, - session_hash, - session_hash_version - FROM capture_sessions - ORDER BY id - """ - ).fetchall() + if session_ids is None: + sessions = conn.execute( + """ + SELECT + id, + start_time, + end_time, + session_hash, + session_hash_version + FROM capture_sessions + ORDER BY id + """ + ).fetchall() + + else: + selected_ids = [ + int(session_id) + for session_id in session_ids + ] + + if selected_ids: + placeholders = ",".join( + "?" for _ in selected_ids + ) + + sessions = conn.execute( + f""" + SELECT + id, + start_time, + end_time, + session_hash, + session_hash_version + FROM capture_sessions + WHERE id IN ({placeholders}) + ORDER BY start_time DESC, id DESC + """, + selected_ids, + ).fetchall() + else: + sessions = [] session_by_id = {} exported_sessions = [] @@ -1118,7 +1159,6 @@ def export_wifitrip(conn, output_path=None): session_ids, ).fetchall() - handshake_key_by_id = {} handshake_records = {} handshakes = [] @@ -1137,13 +1177,6 @@ def export_wifitrip(conn, output_path=None): f"h{len(records) + 1:06d}" ) - handshake_key_by_id[ - row["id"] - ] = ( - session_hash, - handshake_key, - ) - records.append( handshake_key ) @@ -1163,111 +1196,6 @@ def export_wifitrip(conn, output_path=None): } ) - session_ap_ids = {} - - for row in observation_rows: - session_ap_ids.setdefault( - row["session_id"], - set(), - ).add( - row["bssid"] - ) - - for row in handshake_rows: - session_ap_ids.setdefault( - row["session_id"], - set(), - ).add( - row["bssid"] - ) - - credentials_rows = conn.execute( - """ - SELECT - credentials.id, - credentials.access_point_id, - credentials.handshake_id, - access_points.bssid, - credentials.password, - credentials.source, - credentials.created_at, - credentials.verified, - handshakes.session_id AS handshake_session_id - FROM credentials - JOIN access_points - ON access_points.id = - credentials.access_point_id - LEFT JOIN handshakes - ON handshakes.id = - credentials.handshake_id - ORDER BY credentials.id - """ - ).fetchall() - - credentials = [] - - for row in credentials_rows: - if row["handshake_session_id"] is not None: - session_id = row[ - "handshake_session_id" - ] - - if session_id not in session_by_id: - continue - - session_hash = session_by_id[ - session_id - ]["session_hash"] - - handshake_ref = ( - handshake_key_by_id.get( - row["handshake_id"] - ) - ) - - handshake_key = ( - handshake_ref[1] - if handshake_ref - else None - ) - - credentials.append( - { - "session_hash": session_hash, - "bssid": row["bssid"], - "handshake_key": handshake_key, - "password": row["password"], - "source": row["source"], - "created_at": row["created_at"], - "verified": row["verified"], - } - ) - - continue - - for session_id, bssids in ( - session_ap_ids.items() - ): - if row["bssid"] not in bssids: - continue - - if session_id not in session_by_id: - continue - - credentials.append( - { - "session_hash": session_by_id[ - session_id - ]["session_hash"], - "bssid": row["bssid"], - "handshake_key": None, - "password": row["password"], - "source": row["source"], - "created_at": row["created_at"], - "verified": row["verified"], - } - ) - bssids = set() for observation in observations: @@ -1280,11 +1208,6 @@ def export_wifitrip(conn, output_path=None): handshake["bssid"] ) - for credential in credentials: - bssids.add( - credential["bssid"] - ) - access_points = [ { "bssid": bssid @@ -1368,12 +1291,6 @@ def export_wifitrip(conn, output_path=None): handshakes, ) - _zip_write_json( - archive, - "credentials.json", - credentials, - ) - os.replace( temporary_path, output_path, @@ -1408,9 +1325,6 @@ def export_wifitrip(conn, output_path=None): "handshakes": len( handshakes ), - "credentials": len( - credentials - ), "file": str(output_path), "size": size, "duration": duration, @@ -1419,11 +1333,10 @@ def export_wifitrip(conn, output_path=None): logger.info( "Completed .wifitrip export: " "sessions=%d observations=%d handshakes=%d " - "credentials=%d file=%s size=%d duration=%.3fs", + "file=%s size=%d duration=%.3fs", result["sessions"], result["observations"], result["handshakes"], - result["credentials"], output_path, size, duration, @@ -1604,221 +1517,6 @@ def _session_id_by_hash( return row["id"] -def _map_existing_handshake_ids( - conn, - session_id, - session_handshakes, -): - rows = conn.execute( - """ - SELECT - handshakes.id, - access_points.bssid, - handshakes.type, - handshakes.hash22000, - handshakes.message_pair, - handshakes.captured_at, - handshakes.latitude, - handshakes.longitude, - handshakes.speed - FROM handshakes - JOIN access_points - ON access_points.id = - handshakes.access_point_id - WHERE handshakes.session_id=? - ORDER BY handshakes.id - """, - (session_id,), - ).fetchall() - - if len(rows) != len(session_handshakes): - raise WifitripError( - "Existing session handshake count does not " - "match the .wifitrip package." - ) - - expected_keys = [ - f"h{index:06d}" - for index in range( - 1, - len(session_handshakes) + 1, - ) - ] - - package_keys = { - handshake["handshake_key"] - for handshake in session_handshakes - } - - if package_keys != set(expected_keys): - raise WifitripError( - "Existing session handshake keys do not " - "match the exported sequence." - ) - - fields = ( - "bssid", - "type", - "hash22000", - "message_pair", - "captured_at", - "latitude", - "longitude", - "speed", - ) - - local_ids_by_signature = {} - - for row in rows: - signature = tuple( - row[field] - for field in fields - ) - - local_ids_by_signature.setdefault( - signature, - [], - ).append(row["id"]) - - signature_positions = {} - handshake_ids = {} - - ordered_handshakes = sorted( - session_handshakes, - key=lambda handshake: ( - handshake["handshake_key"] - ), - ) - - for handshake in ordered_handshakes: - signature = tuple( - handshake[field] - for field in fields - ) - - local_ids = local_ids_by_signature.get( - signature, - ) - - position = signature_positions.get( - signature, - 0, - ) - - if local_ids is None or position >= len(local_ids): - raise WifitripError( - "Existing session handshake mapping " - "does not match the .wifitrip package." - ) - - handshake_ids[ - handshake["handshake_key"] - ] = local_ids[position] - - signature_positions[signature] = position + 1 - - return handshake_ids - - -def _import_session_credentials( - conn, - session_credentials, - ap_ids, - handshake_ids, -): - for credential in session_credentials: - access_point_id = ap_ids[ - credential["bssid"] - ] - - handshake_id = None - - if credential["handshake_key"] is not None: - handshake_id = handshake_ids[ - credential["handshake_key"] - ] - - existing_verified = conn.execute( - """ - SELECT COALESCE(MAX(verified), 0) - FROM credentials - WHERE access_point_id=? - AND password=? - """, - ( - access_point_id, - credential["password"], - ), - ).fetchone()[0] - - effective_verified = int( - bool(existing_verified) - or bool(credential["verified"]) - ) - - existing_credential = conn.execute( - """ - SELECT id - FROM credentials - WHERE access_point_id=? - AND handshake_id IS ? - AND password=? - LIMIT 1 - """, - ( - access_point_id, - handshake_id, - credential["password"], - ), - ).fetchone() - - if existing_credential is None: - conn.execute( - """ - INSERT INTO credentials ( - access_point_id, - handshake_id, - password, - source, - created_at, - verified - ) - VALUES (?, ?, ?, ?, ?, ?) - """, - ( - access_point_id, - handshake_id, - credential["password"], - credential["source"], - credential["created_at"], - effective_verified, - ), - ) - - if effective_verified: - conn.execute( - """ - UPDATE credentials - SET verified=1 - WHERE access_point_id=? - AND password=? - """, - ( - access_point_id, - credential["password"], - ), - ) - - conn.execute( - """ - UPDATE access_points - SET is_cracked=1 - WHERE id=? - """, - (access_point_id,), - ) - - def import_wifitrip(conn, package_path): started = time.monotonic() @@ -1836,12 +1534,10 @@ def import_wifitrip(conn, package_path): gps_tracks = package["gps_tracks.json"] observations = package["observations.json"] handshakes = package["handshakes.json"] - credentials = package["credentials.json"] gps_by_session = {} observations_by_session = {} handshakes_by_session = {} - credentials_by_session = {} for point in gps_tracks: gps_by_session.setdefault( @@ -1861,12 +1557,6 @@ def import_wifitrip(conn, package_path): [], ).append(handshake) - for credential in credentials: - credentials_by_session.setdefault( - credential["session_hash"], - [], - ).append(credential) - result = { "file": str(package_path), "sessions": len(sessions), @@ -1917,62 +1607,11 @@ def import_wifitrip(conn, package_path): f"calculated {calculated_hash}" ) - session_handshakes = ( - handshakes_by_session.get( - session_hash, - [], - ) - ) - - session_credentials = ( - credentials_by_session.get( - session_hash, - [], - ) - ) - - bssids = { - handshake["bssid"] - for handshake in session_handshakes - } - - bssids.update( - credential["bssid"] - for credential in session_credentials - ) - - created_access_points = set() - ap_ids = {} - - for bssid in sorted(bssids): - ap_ids[bssid] = ( - _get_or_create_import_ap( - conn, - bssid, - created_access_points, - ) - ) - - handshake_ids = ( - _map_existing_handshake_ids( - conn, - existing_id, - session_handshakes, - ) - ) - - _import_session_credentials( - conn, - session_credentials, - ap_ids, - handshake_ids, - ) - conn.commit() logger.info( - "Updated duplicate .wifitrip session " - "credentials: hash=%s local_id=%s", + "Validated duplicate .wifitrip session: " + "hash=%s local_id=%s", session_hash, existing_id, ) @@ -2040,13 +1679,6 @@ def import_wifitrip(conn, package_path): ) ) - session_credentials = ( - credentials_by_session.get( - session_hash, - [], - ) - ) - bssids = set() for observation in session_observations: @@ -2059,11 +1691,6 @@ def import_wifitrip(conn, package_path): handshake["bssid"] ) - for credential in session_credentials: - bssids.add( - credential["bssid"] - ) - for bssid in sorted(bssids): ap_ids[bssid] = ( _get_or_create_import_ap( @@ -2181,8 +1808,6 @@ def import_wifitrip(conn, package_path): latest_observation, ) - handshake_ids = {} - for handshake in session_handshakes: access_point_id = ap_ids[ handshake["bssid"] @@ -2218,10 +1843,6 @@ def import_wifitrip(conn, package_path): ), ) - handshake_ids[ - handshake["handshake_key"] - ] = cursor.lastrowid - if handshake["type"] == "PMKID": conn.execute( """ @@ -2255,13 +1876,6 @@ def import_wifitrip(conn, package_path): f"calculated {calculated_hash}" ) - _import_session_credentials( - conn, - session_credentials, - ap_ids, - handshake_ids, - ) - conn.commit() result["imported"] += 1 @@ -2342,9 +1956,6 @@ def validate_wifitrip(package_path): "handshakes": len( package["handshakes.json"] ), - "credentials": len( - package["credentials.json"] - ), "session_hash_versions": manifest[ "session_hash_versions" ], diff --git a/src/lifecycle_manager.py b/src/lifecycle_manager.py index a2a83be..3d45aab 100644 --- a/src/lifecycle_manager.py +++ b/src/lifecycle_manager.py @@ -59,6 +59,42 @@ def log(message): ) +def colorize(message, color, stream=None): + stream = stream or sys.stdout + + if "NO_COLOR" in os.environ or not stream.isatty(): + return message + + colors = { + "green": "\033[1;92m", + "yellow": "\033[1;93m", + "red": "\033[1;91m", + "reset": "\033[0m" + } + + return f"{colors[color]}{message}{colors['reset']}" + + +def print_success(message): + print(colorize(message, "green"), flush=True) + + +def print_warning(message): + print(colorize(message, "yellow"), flush=True) + + +def print_error(message): + print( + colorize(message, "red", sys.stderr), + file=sys.stderr, + flush=True + ) + + +def print_info(message): + print(message, flush=True) + + def project_python(): return PROJECT_ROOT / "venv" / "bin" / "python" @@ -663,9 +699,11 @@ def start_service(): ) if active_project == PROJECT_ROOT: - log("Менеджер уже запущен из текущего проекта.") + print_warning( + "Менеджер уже запущен из текущего проекта." + ) else: - log( + print_warning( "Менеджер уже запущен из другого проекта: " f"{active_project}. Второй экземпляр не запущен." ) @@ -687,6 +725,7 @@ def start_service(): command = [ "systemd-run", + "--quiet", "--user", f"--unit={UNIT_NAME}", "--service-type=exec", @@ -700,7 +739,8 @@ def start_service(): subprocess.run( command, - check=True + check=True, + stdout=subprocess.DEVNULL ) send_sudo_authentication() @@ -721,7 +761,7 @@ def start_service(): timeout=1 ) as response: if response.status == 200: - log( + print_success( f"Приложение запущено: " f"http://{APP_HOST}:{APP_PORT}" ) @@ -739,7 +779,7 @@ def start_service(): def stop_service(): if not unit_is_active(): - log("Менеджер не запущен.") + print_warning("Менеджер уже остановлен.") return 0 active_project = active_service_project() @@ -765,7 +805,7 @@ def stop_service(): f"{UNIT_NAME}.service" ) - log( + print_warning( "Запрошено штатное завершение. " "Если сканер активен, останови его в веб-интерфейсе." ) @@ -774,33 +814,32 @@ def stop_service(): while unit_is_active(): if not notified: - log( + print_warning( "Ожидание завершения приложения и фоновых задач..." ) notified = True time.sleep(1) - log("Сервис остановлен.") + print_success("Сервис успешно остановлен.") return 0 def show_status(): active = unit_is_active() - print( - "Application:", - "RUNNING" if active else "STOPPED" - ) + if active: + print_success("Application: RUNNING") + else: + print_error("Application: STOPPED") if active: active_project = active_service_project() - print( - "Active project:", - active_project if active_project is not None else "UNKNOWN" + print_info( + "Active project: " + f"{active_project if active_project is not None else 'UNKNOWN'}" ) - if active: try: with urllib.request.urlopen( f"http://{APP_HOST}:{APP_PORT}/api/status", @@ -827,23 +866,38 @@ def show_status(): f"STOPPED (health: {scanner_health})" ) - print("Scanner:", scanner_state) - print( - "GPS test:", - gps.get("state", "unknown") - ) - print( - "Network action:", - "BUSY" if data.get("network_actions_busy") else "IDLE" - ) + if scanner_health == "ACTIVE": + print_success(f"Scanner: {scanner_state}") + elif scanner_health in {"WARNING", "STOPPING"}: + print_warning(f"Scanner: {scanner_state}") + elif scanner_health == "STOPPED": + print_error(f"Scanner: {scanner_state}") + else: + print_info(f"Scanner: {scanner_state}") + + gps_state = gps.get("state", "unknown") + + if gps_state in {"FIX", "CONNECTED"}: + print_success(f"GPS test: {gps_state}") + elif gps_state in {"STARTING", "NMEA"}: + print_warning(f"GPS test: {gps_state}") + elif gps_state == "ERROR": + print_error(f"GPS test: {gps_state}") + else: + print_info(f"GPS test: {gps_state}") + + if data.get("network_actions_busy"): + print_warning("Network action: BUSY") + else: + print_success("Network action: IDLE") except Exception as error: - print(f"Application API: unavailable ({error})") + print_error(f"Application API: unavailable ({error})") - print( - "TileServer:", - "AVAILABLE" if style_is_available() else "UNAVAILABLE" - ) + if style_is_available(): + print_success("TileServer: AVAILABLE") + else: + print_error("TileServer: UNAVAILABLE") if active: result = systemctl_user( @@ -855,7 +909,7 @@ def show_status(): ) if result.returncode == 0: - print(result.stdout.strip()) + print_info(result.stdout.strip()) def install(): @@ -970,7 +1024,15 @@ def main(): return stop_service() if args.command == "restart": - stop_service() + if unit_is_active(): + print_info("Перезапуск: остановка сервиса.") + stop_service() + else: + print_warning( + "Сервис уже остановлен. Этап остановки пропущен." + ) + + print_info("Перезапуск: запуск сервиса.") return start_service() parser.print_help() @@ -981,10 +1043,7 @@ def main(): subprocess.CalledProcessError, OSError ) as error: - print( - f"Ошибка: {error}", - file=sys.stderr - ) + print_error(f"Ошибка: {error}") return 1 diff --git a/src/wifitrip.py b/src/wifitrip.py deleted file mode 100644 index 2cd0e7f..0000000 --- a/src/wifitrip.py +++ /dev/null @@ -1,2731 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -""" -WiFi GPS Mapper — .wifitrip import/export service. - -Формат .wifitrip представляет собой ZIP-контейнер с логическим -содержимым одной или нескольких capture sessions. - -Модуль не открывает SQLite самостоятельно. -Соединение передаётся вызывающим коду. - -Используется одновременно: - • CLI; - • server-side Reports. - -Локальные SQLite IDs никогда не являются идентификаторами обмена. -""" - -import hashlib -import json -import logging -import os -import tempfile -import zipfile - -from datetime import datetime, timezone -from pathlib import Path - - -# ============================================================ -# Constants -# ============================================================ - -WIFITRIP_FORMAT = "wifitrip" -WIFITRIP_VERSION = 1 -SESSION_HASH_VERSION = 1 - -REQUIRED_FILES = ( - "manifest.json", - "sessions.json", - "access_points.json", - "gps_tracks.json", - "observations.json", - "handshakes.json", - "credentials.json", -) - -MAX_JSON_SIZE = 512 * 1024 * 1024 - - -logger = logging.getLogger( - "wifi-gps-mapper.wifitrip" -) - - -# ============================================================ -# Exceptions -# ============================================================ - -class WifitripError(Exception): - """Base exception for .wifitrip errors.""" - - -class WifitripValidationError(WifitripError): - """Archive validation failed.""" - - -class WifitripHashMismatchError(WifitripError): - """Imported session hash does not match restored data.""" - - -# ============================================================ -# Result helpers -# ============================================================ - -def _new_session_result( - session_hash, -): - return { - "session_hash": session_hash, - "status": "FAILED", - "error": None, - "access_points": 0, - "gps_points": 0, - "observations": 0, - "handshakes": 0, - "credentials": 0, - } - - -# ============================================================ -# JSON helpers -# ============================================================ - -def _json_dump( - value, -): - return json.dumps( - value, - ensure_ascii=False, - indent=2, - sort_keys=True, - allow_nan=False, - ) - - -def _read_json( - archive, - filename, -): - try: - info = archive.getinfo( - filename - ) - except KeyError as error: - raise WifitripValidationError( - f"Required file is missing: {filename}" - ) from error - - if info.file_size > MAX_JSON_SIZE: - raise WifitripValidationError( - f"File is too large: {filename}" - ) - - try: - content = archive.read( - filename - ).decode( - "utf-8" - ) - except UnicodeDecodeError as error: - raise WifitripValidationError( - f"File is not valid UTF-8: {filename}" - ) from error - - try: - return json.loads( - content - ) - except json.JSONDecodeError as error: - raise WifitripValidationError( - f"Invalid JSON in {filename}: " - f"{error}" - ) from error - - -def _ensure_list( - value, - filename, -): - if not isinstance( - value, - list, - ): - raise WifitripValidationError( - f"{filename} must contain a JSON array." - ) - - return value - - -def _ensure_dict( - value, - filename, -): - if not isinstance( - value, - dict, - ): - raise WifitripValidationError( - f"{filename} must contain a JSON object." - ) - - return value - - -# ============================================================ -# General helpers -# ============================================================ - -def _utc_now(): - return datetime.now( - timezone.utc - ).isoformat().replace( - "+00:00", - "Z" - ) - - -def _normalise_bssid( - value, -): - if value is None: - return "" - - return str( - value - ).strip().lower() - - -def _require_string( - record, - field, - context, -): - value = record.get( - field - ) - - if not isinstance( - value, - str, - ): - raise WifitripValidationError( - f"{context}: {field} must be a string." - ) - - if not value.strip(): - raise WifitripValidationError( - f"{context}: {field} must not be empty." - ) - - return value - - -def _optional_number( - value, - field, - context, -): - if value is None: - return None - - if isinstance( - value, - bool, - ): - raise WifitripValidationError( - f"{context}: {field} must be numeric or null." - ) - - if not isinstance( - value, - (int, float), - ): - raise WifitripValidationError( - f"{context}: {field} must be numeric or null." - ) - - return value - - -def _optional_integer( - value, - field, - context, -): - if value is None: - return None - - if isinstance( - value, - bool, - ): - raise WifitripValidationError( - f"{context}: {field} must be an integer or null." - ) - - if not isinstance( - value, - int, - ): - raise WifitripValidationError( - f"{context}: {field} must be an integer or null." - ) - - return value - - -def _validate_bssid( - value, - context, -): - bssid = _normalise_bssid( - value - ) - - compact = bssid.replace( - ":", - "" - ).replace( - "-", - "" - ) - - if len(compact) != 12: - raise WifitripValidationError( - f"{context}: invalid BSSID: {value}" - ) - - try: - int( - compact, - 16, - ) - except ValueError as error: - raise WifitripValidationError( - f"{context}: invalid BSSID: {value}" - ) from error - - return bssid - - -# ============================================================ -# Session hash -# ============================================================ - -def _canonical_json( - value, -): - return json.dumps( - value, - ensure_ascii=False, - separators=(",", ":"), - allow_nan=False, - ) - - -def _calculate_session_hash( - conn, - session_id, -): - session = conn.execute( - """ - SELECT - start_time, - end_time - FROM capture_sessions - WHERE id=? - """, - ( - session_id, - ) - ).fetchone() - - if session is None: - raise WifitripError( - f"Session not found: {session_id}" - ) - - gps_rows = conn.execute( - """ - SELECT - timestamp, - latitude, - longitude - FROM gps_track - WHERE session_id=? - ORDER BY sequence_no - """, - ( - session_id, - ) - ).fetchall() - - handshake_rows = conn.execute( - """ - SELECT - access_points.bssid, - handshakes.type, - handshakes.hash22000, - handshakes.message_pair, - handshakes.captured_at - FROM handshakes - JOIN access_points - ON access_points.id = - handshakes.access_point_id - WHERE handshakes.session_id=? - ORDER BY - access_points.bssid, - handshakes.type, - handshakes.hash22000, - handshakes.message_pair, - handshakes.captured_at - """, - ( - session_id, - ) - ).fetchall() - - handshake_data = [ - [ - row["bssid"], - row["type"], - row["hash22000"], - row["message_pair"], - row["captured_at"], - ] - for row in handshake_rows - ] - - if gps_rows: - gps_data = [ - [ - row["timestamp"], - row["latitude"], - row["longitude"], - ] - for row in gps_rows - ] - - canonical = [ - "GPS_SESSION_V1", - gps_data, - handshake_data, - ] - - else: - observation_rows = conn.execute( - """ - SELECT - observations.observed_at, - access_points.bssid - FROM access_point_observations AS observations - JOIN access_points - ON access_points.id = - observations.access_point_id - WHERE observations.session_id=? - ORDER BY - observations.observed_at, - access_points.bssid - """, - ( - session_id, - ) - ).fetchall() - - observation_data = [ - [ - row["observed_at"], - row["bssid"], - ] - for row in observation_rows - ] - - canonical = [ - "NON_GPS_SESSION_V1", - session["start_time"], - session["end_time"], - observation_data, - handshake_data, - ] - - payload = _canonical_json( - canonical - ).encode( - "utf-8" - ) - - return hashlib.sha256( - payload - ).hexdigest() - - -# ============================================================ -# Export queries -# ============================================================ - -def _get_sessions_for_export( - conn, - session_ids=None, -): - if session_ids is None: - return conn.execute( - """ - SELECT - id, - start_time, - end_time, - session_hash, - session_hash_version - FROM capture_sessions - WHERE - session_hash IS NOT NULL - AND TRIM(session_hash) != '' - AND session_hash_version IS NOT NULL - ORDER BY id - """ - ).fetchall() - - ids = list( - session_ids - ) - - if not ids: - return [] - - placeholders = ",".join( - "?" - for _ in ids - ) - - return conn.execute( - f""" - SELECT - id, - start_time, - end_time, - session_hash, - session_hash_version - FROM capture_sessions - WHERE - id IN ({placeholders}) - AND session_hash IS NOT NULL - AND TRIM(session_hash) != '' - AND session_hash_version IS NOT NULL - ORDER BY id - """, - ids, - ).fetchall() - - -def _get_session_type( - conn, - session_id, -): - gps_count = conn.execute( - """ - SELECT COUNT(*) - FROM gps_track - WHERE session_id=? - """, - ( - session_id, - ) - ).fetchone()[0] - - if gps_count: - return "gps" - - return "non_gps" - - -def _get_access_points( - conn, - session_ids, -): - if not session_ids: - return [] - - placeholders = ",".join( - "?" - for _ in session_ids - ) - - rows = conn.execute( - f""" - SELECT DISTINCT - access_points.bssid - FROM access_points - WHERE access_points.id IN ( - SELECT access_point_id - FROM access_point_observations - WHERE session_id IN ({placeholders}) - - UNION - - SELECT access_point_id - FROM handshakes - WHERE session_id IN ({placeholders}) - - UNION - - SELECT access_point_id - FROM credentials - WHERE access_point_id IN ( - SELECT access_point_id - FROM handshakes - WHERE session_id IN ({placeholders}) - ) - ) - ORDER BY access_points.bssid - """, - ( - *session_ids, - *session_ids, - *session_ids, - ), - ).fetchall() - - return [ - { - "bssid": row["bssid"], - } - for row in rows - ] - - -def _get_gps_tracks( - conn, - sessions, -): - records = [] - - for session in sessions: - rows = conn.execute( - """ - SELECT - sequence_no, - latitude, - longitude, - speed, - timestamp - FROM gps_track - WHERE session_id=? - ORDER BY sequence_no - """, - ( - session["id"], - ) - ).fetchall() - - for row in rows: - records.append( - { - "session_hash": - session["session_hash"], - "sequence_no": - row["sequence_no"], - "latitude": - row["latitude"], - "longitude": - row["longitude"], - "speed": - row["speed"], - "timestamp": - row["timestamp"], - } - ) - - return records - - -def _get_observations( - conn, - sessions, -): - records = [] - - for session in sessions: - rows = conn.execute( - """ - SELECT - access_points.bssid, - observations.observed_at, - observations.latitude, - observations.longitude, - observations.speed, - observations.rssi, - observations.channel, - observations.frequency, - observations.essid, - observations.encryption, - observations.cipher, - observations.akm, - observations.country - FROM access_point_observations AS observations - JOIN access_points - ON access_points.id = - observations.access_point_id - WHERE observations.session_id=? - ORDER BY - observations.observed_at, - access_points.bssid, - observations.id - """, - ( - session["id"], - ) - ).fetchall() - - for row in rows: - records.append( - { - "session_hash": - session["session_hash"], - "bssid": - row["bssid"], - "observed_at": - row["observed_at"], - "latitude": - row["latitude"], - "longitude": - row["longitude"], - "speed": - row["speed"], - "rssi": - row["rssi"], - "channel": - row["channel"], - "frequency": - row["frequency"], - "essid": - row["essid"], - "encryption": - row["encryption"], - "cipher": - row["cipher"], - "akm": - row["akm"], - "country": - row["country"], - } - ) - - return records - - -def _get_handshakes( - conn, - sessions, -): - records = [] - handshake_maps = {} - - for session in sessions: - rows = conn.execute( - """ - SELECT - handshakes.id, - access_points.bssid, - handshakes.type, - handshakes.hash22000, - handshakes.message_pair, - handshakes.captured_at, - handshakes.latitude, - handshakes.longitude, - handshakes.speed - FROM handshakes - JOIN access_points - ON access_points.id = - handshakes.access_point_id - WHERE handshakes.session_id=? - ORDER BY handshakes.id - """, - ( - session["id"], - ) - ).fetchall() - - session_map = {} - - for index, row in enumerate( - rows, - start=1, - ): - handshake_key = ( - f"h{index:06d}" - ) - - session_map[ - row["id"] - ] = handshake_key - - records.append( - { - "session_hash": - session["session_hash"], - "handshake_key": - handshake_key, - "bssid": - row["bssid"], - "type": - row["type"], - "hash22000": - row["hash22000"], - "message_pair": - row["message_pair"], - "captured_at": - row["captured_at"], - "latitude": - row["latitude"], - "longitude": - row["longitude"], - "speed": - row["speed"], - } - ) - - handshake_maps[ - session["id"] - ] = session_map - - return records, handshake_maps - - -def _get_credentials( - conn, - sessions, - handshake_maps, -): - records = [] - - for session in sessions: - rows = conn.execute( - """ - SELECT - credentials.id, - access_points.bssid, - credentials.handshake_id, - credentials.password, - credentials.source, - credentials.created_at, - credentials.verified - FROM credentials - JOIN access_points - ON access_points.id = - credentials.access_point_id - WHERE - credentials.handshake_id IN ( - SELECT id - FROM handshakes - WHERE session_id=? - ) - OR ( - credentials.handshake_id IS NULL - AND credentials.access_point_id IN ( - SELECT access_point_id - FROM access_point_observations - WHERE session_id=? - ) - ) - ORDER BY credentials.id - """, - ( - session["id"], - session["id"], - ) - ).fetchall() - - session_map = handshake_maps.get( - session["id"], - {}, - ) - - for row in rows: - handshake_key = None - - if row["handshake_id"] is not None: - handshake_key = session_map.get( - row["handshake_id"] - ) - - if handshake_key is None: - raise WifitripError( - "Credential references a handshake " - "outside the exported session." - ) - - records.append( - { - "session_hash": - session["session_hash"], - "bssid": - row["bssid"], - "handshake_key": - handshake_key, - "password": - row["password"], - "source": - row["source"], - "created_at": - row["created_at"], - "verified": - row["verified"], - } - ) - - return records - - -# ============================================================ -# Export -# ============================================================ - -def _build_export_package( - conn, - session_ids=None, -): - sessions = _get_sessions_for_export( - conn, - session_ids, - ) - - session_records = [] - session_hashes = set() - - for session in sessions: - session_hash = str( - session["session_hash"] - ).strip() - - if session_hash in session_hashes: - raise WifitripError( - f"Duplicate session hash in database: " - f"{session_hash}" - ) - - session_hashes.add( - session_hash - ) - - calculated_hash = _calculate_session_hash( - conn, - session["id"], - ) - - if calculated_hash != session_hash: - raise WifitripHashMismatchError( - "Stored session hash does not match " - f"session {session['id']}: " - f"{session_hash}" - ) - - session_records.append( - { - "session_hash": - session_hash, - "session_hash_version": - session["session_hash_version"], - "start_time": - session["start_time"], - "end_time": - session["end_time"], - "session_type": - _get_session_type( - conn, - session["id"], - ), - } - ) - - access_points = _get_access_points( - conn, - [ - session["id"] - for session in sessions - ], - ) - - gps_tracks = _get_gps_tracks( - conn, - sessions, - ) - - observations = _get_observations( - conn, - sessions, - ) - - handshakes, handshake_maps = _get_handshakes( - conn, - sessions, - ) - - credentials = _get_credentials( - conn, - sessions, - handshake_maps, - ) - - manifest = { - "format": WIFITRIP_FORMAT, - "format_version": WIFITRIP_VERSION, - "created_at": _utc_now(), - "sessions": len( - session_records - ), - "session_hash_versions": sorted( - { - record["session_hash_version"] - for record in session_records - } - ), - } - - return { - "manifest": manifest, - "sessions": session_records, - "access_points": access_points, - "gps_tracks": gps_tracks, - "observations": observations, - "handshakes": handshakes, - "credentials": credentials, - } - - -def export_wifitrip( - conn, - output_path, - session_ids=None, -): - started_at = datetime.now( - timezone.utc - ) - - output_path = Path( - output_path - ) - - output_path.parent.mkdir( - parents=True, - exist_ok=True, - ) - - package = _build_export_package( - conn, - session_ids, - ) - - output_fd = None - temporary_path = None - - try: - output_fd, temporary_path = tempfile.mkstemp( - prefix=".wifitrip-", - suffix=".tmp", - dir=str( - output_path.parent - ), - ) - - os.close( - output_fd - ) - output_fd = None - - with zipfile.ZipFile( - temporary_path, - "w", - compression=zipfile.ZIP_DEFLATED, - compresslevel=6, - ) as archive: - - for filename in REQUIRED_FILES: - key = filename[:-5] - - archive.writestr( - filename, - _json_dump( - package[key] - ).encode( - "utf-8" - ), - ) - - os.replace( - temporary_path, - output_path, - ) - - temporary_path = None - - finally: - if output_fd is not None: - os.close( - output_fd - ) - - if temporary_path is not None: - try: - os.unlink( - temporary_path - ) - except FileNotFoundError: - pass - - size = output_path.stat().st_size - - duration = ( - datetime.now( - timezone.utc - ) - started_at - ).total_seconds() - - result = { - "output": str( - output_path - ), - "size": size, - "duration": duration, - "sessions": len( - package["sessions"] - ), - "access_points": len( - package["access_points"] - ), - "gps_points": len( - package["gps_tracks"] - ), - "observations": len( - package["observations"] - ), - "handshakes": len( - package["handshakes"] - ), - "credentials": len( - package["credentials"] - ), - } - - logger.info( - "wifitrip export completed: " - "file=%s size=%d sessions=%d " - "access_points=%d gps_points=%d " - "observations=%d handshakes=%d " - "credentials=%d duration=%.3fs", - output_path, - size, - result["sessions"], - result["access_points"], - result["gps_points"], - result["observations"], - result["handshakes"], - result["credentials"], - duration, - ) - - return result - - -# ============================================================ -# Package validation -# ============================================================ - -def _validate_manifest( - manifest, -): - _ensure_dict( - manifest, - "manifest.json", - ) - - if manifest.get( - "format" - ) != WIFITRIP_FORMAT: - raise WifitripValidationError( - "Unsupported package format." - ) - - if manifest.get( - "format_version" - ) != WIFITRIP_VERSION: - raise WifitripValidationError( - "Unsupported .wifitrip format version: " - f"{manifest.get('format_version')}" - ) - - sessions = manifest.get( - "sessions" - ) - - if not isinstance( - sessions, - int, - ) or isinstance( - sessions, - bool, - ): - raise WifitripValidationError( - "manifest.sessions must be an integer." - ) - - if sessions < 0: - raise WifitripValidationError( - "manifest.sessions must not be negative." - ) - - versions = manifest.get( - "session_hash_versions" - ) - - if not isinstance( - versions, - list, - ): - raise WifitripValidationError( - "manifest.session_hash_versions " - "must be an array." - ) - - for version in versions: - if version != SESSION_HASH_VERSION: - raise WifitripValidationError( - "Unsupported session hash version: " - f"{version}" - ) - - -def _validate_sessions( - records, -): - sessions = {} - versions = set() - - for index, record in enumerate( - records - ): - context = ( - f"sessions.json[{index}]" - ) - - _ensure_dict( - record, - context, - ) - - session_hash = _require_string( - record, - "session_hash", - context, - ) - - session_hash_version = _optional_integer( - record.get( - "session_hash_version" - ), - "session_hash_version", - context, - ) - - if session_hash_version != SESSION_HASH_VERSION: - raise WifitripValidationError( - f"{context}: unsupported " - "session_hash_version." - ) - - if session_hash in sessions: - raise WifitripValidationError( - f"{context}: duplicate session_hash." - ) - - start_time = _require_string( - record, - "start_time", - context, - ) - - end_time = record.get( - "end_time" - ) - - if end_time is not None and not isinstance( - end_time, - str, - ): - raise WifitripValidationError( - f"{context}: end_time must be " - "a string or null." - ) - - session_type = record.get( - "session_type" - ) - - if session_type not in ( - "gps", - "non_gps", - ): - raise WifitripValidationError( - f"{context}: invalid session_type." - ) - - sessions[ - session_hash - ] = { - "session_hash": - session_hash, - "session_hash_version": - session_hash_version, - "start_time": - start_time, - "end_time": - end_time, - "session_type": - session_type, - } - - versions.add( - session_hash_version - ) - - return sessions, versions - - -def _validate_access_points( - records, -): - access_points = {} - - for index, record in enumerate( - records - ): - context = ( - f"access_points.json[{index}]" - ) - - _ensure_dict( - record, - context, - ) - - bssid = _validate_bssid( - record.get( - "bssid" - ), - context, - ) - - if bssid in access_points: - raise WifitripValidationError( - f"{context}: duplicate BSSID." - ) - - access_points[ - bssid - ] = { - "bssid": bssid, - } - - return access_points - - -def _validate_gps_tracks( - records, - sessions, -): - sequence_numbers = {} - - for index, record in enumerate( - records - ): - context = ( - f"gps_tracks.json[{index}]" - ) - - _ensure_dict( - record, - context, - ) - - session_hash = _require_string( - record, - "session_hash", - context, - ) - - if session_hash not in sessions: - raise WifitripValidationError( - f"{context}: unknown session_hash." - ) - - sequence_no = _optional_integer( - record.get( - "sequence_no" - ), - "sequence_no", - context, - ) - - if sequence_no is None or sequence_no < 0: - raise WifitripValidationError( - f"{context}: invalid sequence_no." - ) - - key = ( - session_hash, - sequence_no, - ) - - if key in sequence_numbers: - raise WifitripValidationError( - f"{context}: duplicate sequence_no." - ) - - sequence_numbers[key] = True - - for field in ( - "latitude", - "longitude", - "speed", - ): - _optional_number( - record.get( - field - ), - field, - context, - ) - - timestamp = record.get( - "timestamp" - ) - - if timestamp is not None and not isinstance( - timestamp, - str, - ): - raise WifitripValidationError( - f"{context}: timestamp must " - "be a string or null." - ) - - -def _validate_observations( - records, - sessions, - access_points, -): - for index, record in enumerate( - records - ): - context = ( - f"observations.json[{index}]" - ) - - _ensure_dict( - record, - context, - ) - - session_hash = _require_string( - record, - "session_hash", - context, - ) - - if session_hash not in sessions: - raise WifitripValidationError( - f"{context}: unknown session_hash." - ) - - bssid = _validate_bssid( - record.get( - "bssid" - ), - context, - ) - - if bssid not in access_points: - raise WifitripValidationError( - f"{context}: unknown BSSID." - ) - - _require_string( - record, - "observed_at", - context, - ) - - for field in ( - "latitude", - "longitude", - "speed", - ): - _optional_number( - record.get( - field - ), - field, - context, - ) - - for field in ( - "rssi", - "channel", - "frequency", - ): - _optional_integer( - record.get( - field - ), - field, - context, - ) - - for field in ( - "essid", - "encryption", - "cipher", - "akm", - "country", - ): - value = record.get( - field - ) - - if value is not None and not isinstance( - value, - str, - ): - raise WifitripValidationError( - f"{context}: {field} must " - "be a string or null." - ) - - -def _validate_handshakes( - records, - sessions, - access_points, -): - handshake_keys = {} - - for index, record in enumerate( - records - ): - context = ( - f"handshakes.json[{index}]" - ) - - _ensure_dict( - record, - context, - ) - - session_hash = _require_string( - record, - "session_hash", - context, - ) - - if session_hash not in sessions: - raise WifitripValidationError( - f"{context}: unknown session_hash." - ) - - handshake_key = _require_string( - record, - "handshake_key", - context, - ) - - key = ( - session_hash, - handshake_key, - ) - - if key in handshake_keys: - raise WifitripValidationError( - f"{context}: duplicate handshake_key." - ) - - handshake_keys[key] = True - - bssid = _validate_bssid( - record.get( - "bssid" - ), - context, - ) - - if bssid not in access_points: - raise WifitripValidationError( - f"{context}: unknown BSSID." - ) - - _require_string( - record, - "type", - context, - ) - - for field in ( - "hash22000", - "message_pair", - "captured_at", - ): - value = record.get( - field - ) - - if value is not None and not isinstance( - value, - str, - ): - raise WifitripValidationError( - f"{context}: {field} must " - "be a string or null." - ) - - for field in ( - "latitude", - "longitude", - "speed", - ): - _optional_number( - record.get( - field - ), - field, - context, - ) - - return handshake_keys - - -def _validate_credentials( - records, - sessions, - access_points, - handshake_keys, -): - for index, record in enumerate( - records - ): - context = ( - f"credentials.json[{index}]" - ) - - _ensure_dict( - record, - context, - ) - - session_hash = _require_string( - record, - "session_hash", - context, - ) - - if session_hash not in sessions: - raise WifitripValidationError( - f"{context}: unknown session_hash." - ) - - bssid = _validate_bssid( - record.get( - "bssid" - ), - context, - ) - - if bssid not in access_points: - raise WifitripValidationError( - f"{context}: unknown BSSID." - ) - - password = _require_string( - record, - "password", - context, - ) - - handshake_key = record.get( - "handshake_key" - ) - - if handshake_key is not None: - if not isinstance( - handshake_key, - str, - ): - raise WifitripValidationError( - f"{context}: handshake_key must " - "be a string or null." - ) - - if ( - session_hash, - handshake_key, - ) not in handshake_keys: - raise WifitripValidationError( - f"{context}: unknown handshake_key." - ) - - for field in ( - "source", - "created_at", - ): - value = record.get( - field - ) - - if value is not None and not isinstance( - value, - str, - ): - raise WifitripValidationError( - f"{context}: {field} must " - "be a string or null." - ) - - verified = record.get( - "verified" - ) - - if not isinstance( - verified, - (int, bool), - ): - raise WifitripValidationError( - f"{context}: verified must be numeric." - ) - - -def _load_package( - path, -): - path = Path( - path - ) - - if not path.exists(): - raise FileNotFoundError( - f"File not found:\n{path}" - ) - - if not path.is_file(): - raise ValueError( - f"Not a regular file:\n{path}" - ) - - try: - archive = zipfile.ZipFile( - path, - "r", - ) - except zipfile.BadZipFile as error: - raise WifitripValidationError( - "Input file is not a valid ZIP archive." - ) from error - - try: - names = archive.namelist() - - if len(names) != len( - set(names) - ): - raise WifitripValidationError( - "Archive contains duplicate file names." - ) - - missing = [ - filename - for filename in REQUIRED_FILES - if filename not in names - ] - - if missing: - raise WifitripValidationError( - "Archive is missing required files: " - + ", ".join( - missing - ) - ) - - manifest = _read_json( - archive, - "manifest.json", - ) - - sessions = _read_json( - archive, - "sessions.json", - ) - - access_points = _read_json( - archive, - "access_points.json", - ) - - gps_tracks = _read_json( - archive, - "gps_tracks.json", - ) - - observations = _read_json( - archive, - "observations.json", - ) - - handshakes = _read_json( - archive, - "handshakes.json", - ) - - credentials = _read_json( - archive, - "credentials.json", - ) - - finally: - archive.close() - - _validate_manifest( - manifest - ) - - sessions = _ensure_list( - sessions, - "sessions.json", - ) - - access_points = _ensure_list( - access_points, - "access_points.json", - ) - - gps_tracks = _ensure_list( - gps_tracks, - "gps_tracks.json", - ) - - observations = _ensure_list( - observations, - "observations.json", - ) - - handshakes = _ensure_list( - handshakes, - "handshakes.json", - ) - - credentials = _ensure_list( - credentials, - "credentials.json", - ) - - session_map, versions = _validate_sessions( - sessions - ) - - if manifest["sessions"] != len( - sessions - ): - raise WifitripValidationError( - "manifest.sessions does not match sessions.json." - ) - - if set( - manifest["session_hash_versions"] - ) != versions: - raise WifitripValidationError( - "manifest.session_hash_versions " - "does not match sessions.json." - ) - - access_point_map = _validate_access_points( - access_points - ) - - _validate_gps_tracks( - gps_tracks, - session_map, - ) - - _validate_observations( - observations, - session_map, - access_point_map, - ) - - handshake_keys = _validate_handshakes( - handshakes, - session_map, - access_point_map, - ) - - _validate_credentials( - credentials, - session_map, - access_point_map, - handshake_keys, - ) - - return { - "manifest": manifest, - "sessions": sessions, - "access_points": access_points, - "gps_tracks": gps_tracks, - "observations": observations, - "handshakes": handshakes, - "credentials": credentials, - } - - -def preflight_wifitrip( - path, -): - started_at = datetime.now( - timezone.utc - ) - - package = _load_package( - path - ) - - session_hashes = { - record["session_hash"] - for record in package["sessions"] - } - - result = { - "valid": True, - "file": str( - path - ), - "format_version": - package["manifest"]["format_version"], - "sessions": len( - package["sessions"] - ), - "access_points": len( - package["access_points"] - ), - "gps_points": len( - package["gps_tracks"] - ), - "observations": len( - package["observations"] - ), - "handshakes": len( - package["handshakes"] - ), - "credentials": len( - package["credentials"] - ), - "session_hashes": len( - session_hashes - ), - "duration": ( - datetime.now( - timezone.utc - ) - started_at - ).total_seconds(), - } - - logger.info( - "wifitrip preflight successful: " - "file=%s sessions=%d access_points=%d " - "gps_points=%d observations=%d " - "handshakes=%d credentials=%d", - path, - result["sessions"], - result["access_points"], - result["gps_points"], - result["observations"], - result["handshakes"], - result["credentials"], - ) - - return result - - -# ============================================================ -# Import helpers -# ============================================================ - -def _session_exists_by_hash( - conn, - session_hash, - session_hash_version, -): - row = conn.execute( - """ - SELECT id - FROM capture_sessions - WHERE - session_hash=? - AND session_hash_version=? - LIMIT 1 - """, - ( - session_hash, - session_hash_version, - ), - ).fetchone() - - if row is None: - return None - - return row["id"] - - -def _get_or_create_import_ap( - conn, - bssid, -): - row = conn.execute( - """ - SELECT id - FROM access_points - WHERE bssid=? - """, - ( - bssid, - ), - ).fetchone() - - if row is not None: - return row["id"], False - - cursor = conn.execute( - """ - INSERT INTO access_points ( - bssid - ) - VALUES (?) - """, - ( - bssid, - ), - ) - - return cursor.lastrowid, True - - -def _import_gps_tracks( - conn, - session_id, - session_hash, - gps_tracks, -): - records = [ - record - for record in gps_tracks - if record["session_hash"] == session_hash - ] - - for record in sorted( - records, - key=lambda value: value["sequence_no"], - ): - conn.execute( - """ - INSERT INTO gps_track ( - session_id, - sequence_no, - latitude, - longitude, - speed, - timestamp - ) - VALUES (?, ?, ?, ?, ?, ?) - """, - ( - session_id, - record["sequence_no"], - record["latitude"], - record["longitude"], - record["speed"], - record["timestamp"], - ), - ) - - return len( - records - ) - - -def _import_observations( - conn, - session_id, - session_hash, - observations, - ap_map, -): - records = [ - record - for record in observations - if record["session_hash"] == session_hash - ] - - for record in records: - bssid = _normalise_bssid( - record["bssid"] - ) - - access_point_id = ap_map[ - bssid - ] - - conn.execute( - """ - INSERT INTO access_point_observations ( - access_point_id, - session_id, - observed_at, - latitude, - longitude, - speed, - rssi, - channel, - frequency, - essid, - encryption, - cipher, - akm, - country - ) - VALUES ( - ?, ?, ?, ?, ?, ?, ?, ?, - ?, ?, ?, ?, ?, ? - ) - """, - ( - access_point_id, - session_id, - record["observed_at"], - record["latitude"], - record["longitude"], - record["speed"], - record["rssi"], - record["channel"], - record["frequency"], - record["essid"], - record["encryption"], - record["cipher"], - record["akm"], - record["country"], - ), - ) - - return len( - records - ) - - -def _import_handshakes( - conn, - session_id, - session_hash, - handshakes, - ap_map, -): - records = [ - record - for record in handshakes - if record["session_hash"] == session_hash - ] - - handshake_map = {} - - for record in records: - bssid = _normalise_bssid( - record["bssid"] - ) - - access_point_id = ap_map[ - bssid - ] - - cursor = conn.execute( - """ - INSERT INTO handshakes ( - access_point_id, - session_id, - type, - hash22000, - message_pair, - captured_at, - latitude, - longitude, - speed - ) - VALUES ( - ?, ?, ?, ?, ?, ?, ?, ?, ? - ) - """, - ( - access_point_id, - session_id, - record["type"], - record["hash22000"], - record["message_pair"], - record["captured_at"], - record["latitude"], - record["longitude"], - record["speed"], - ), - ) - - local_id = cursor.lastrowid - - handshake_map[ - record["handshake_key"] - ] = local_id - - if record["type"] == "PMKID": - conn.execute( - """ - UPDATE access_points - SET has_pmkid=1 - WHERE id=? - """, - ( - access_point_id, - ), - ) - - if record["type"] == "EAPOL": - conn.execute( - """ - UPDATE access_points - SET has_handshake=1 - WHERE id=? - """, - ( - access_point_id, - ), - ) - - return len( - records - ), handshake_map - - -def _update_imported_ap_statistics( - conn, - ap_map, - session_id, -): - for access_point_id in ap_map.values(): - row = conn.execute( - """ - SELECT - COUNT(*) AS count, - MIN(observed_at) AS first_seen, - MAX(observed_at) AS last_seen - FROM access_point_observations - WHERE - access_point_id=? - AND session_id=? - """, - ( - access_point_id, - session_id, - ), - ).fetchone() - - if row["count"] == 0: - continue - - latest = conn.execute( - """ - SELECT - observed_at, - latitude, - longitude, - speed, - rssi, - channel, - frequency, - essid, - encryption, - cipher, - akm, - country - FROM access_point_observations - WHERE - access_point_id=? - AND session_id=? - ORDER BY - observed_at DESC, - id DESC - LIMIT 1 - """, - ( - access_point_id, - session_id, - ), - ).fetchone() - - current = conn.execute( - """ - SELECT - first_seen, - last_seen - FROM access_points - WHERE id=? - """, - ( - access_point_id, - ), - ).fetchone() - - first_seen = row["first_seen"] - - if current["first_seen"] is not None: - first_seen = min( - current["first_seen"], - first_seen, - ) - - last_seen = row["last_seen"] - - if current["last_seen"] is not None: - last_seen = max( - current["last_seen"], - last_seen, - ) - - conn.execute( - """ - UPDATE access_points - SET - first_seen=?, - last_seen=?, - times_seen= - COALESCE(times_seen, 0) - + ?, - last_rssi=?, - last_latitude=?, - last_longitude=?, - last_speed=?, - channel=?, - frequency=?, - essid=?, - encryption=?, - cipher=?, - akm=?, - country=? - WHERE id=? - """, - ( - first_seen, - last_seen, - row["count"], - latest["rssi"], - latest["latitude"], - latest["longitude"], - latest["speed"], - latest["channel"], - latest["frequency"], - latest["essid"], - latest["encryption"], - latest["cipher"], - latest["akm"], - latest["country"], - access_point_id, - ), - ) - - -def _import_credentials( - conn, - session_hash, - credentials, - ap_map, - handshake_map, -): - records = [ - record - for record in credentials - if record["session_hash"] == session_hash - ] - - imported = 0 - - for record in records: - bssid = _normalise_bssid( - record["bssid"] - ) - - access_point_id = ap_map[ - bssid - ] - - handshake_id = None - - if record["handshake_key"] is not None: - handshake_id = handshake_map[ - record["handshake_key"] - ] - - existing = conn.execute( - """ - SELECT id - FROM credentials - WHERE - access_point_id=? - AND password=? - LIMIT 1 - """, - ( - access_point_id, - record["password"], - ), - ).fetchone() - - if existing is not None: - continue - - conn.execute( - """ - INSERT INTO credentials ( - access_point_id, - handshake_id, - password, - source, - created_at, - verified - ) - VALUES ( - ?, ?, ?, ?, ?, ? - ) - """, - ( - access_point_id, - handshake_id, - record["password"], - record["source"], - record["created_at"], - record["verified"], - ), - ) - - conn.execute( - """ - UPDATE access_points - SET is_cracked=1 - WHERE id=? - """, - ( - access_point_id, - ), - ) - - imported += 1 - - return imported - - -def _import_session( - conn, - package, - session_record, -): - session_hash = session_record[ - "session_hash" - ] - - session_hash_version = session_record[ - "session_hash_version" - ] - - result = _new_session_result( - session_hash - ) - - existing_id = _session_exists_by_hash( - conn, - session_hash, - session_hash_version, - ) - - if existing_id is not None: - result["status"] = "DUPLICATE" - return result - - try: - conn.execute( - "BEGIN" - ) - - cursor = conn.execute( - """ - INSERT INTO capture_sessions ( - start_time, - end_time, - capture_file, - session_hash, - session_hash_version - ) - VALUES (?, ?, ?, ?, ?) - """, - ( - session_record["start_time"], - session_record["end_time"], - "imported.wifitrip", - session_hash, - session_hash_version, - ), - ) - - session_id = cursor.lastrowid - - ap_records = package[ - "access_points" - ] - - referenced_bssids = set() - - for record in package[ - "observations" - ]: - if record["session_hash"] == session_hash: - referenced_bssids.add( - _normalise_bssid( - record["bssid"] - ) - ) - - for record in package[ - "handshakes" - ]: - if record["session_hash"] == session_hash: - referenced_bssids.add( - _normalise_bssid( - record["bssid"] - ) - ) - - for record in package[ - "credentials" - ]: - if record["session_hash"] == session_hash: - referenced_bssids.add( - _normalise_bssid( - record["bssid"] - ) - ) - - package_bssids = { - _normalise_bssid( - record["bssid"] - ) - for record in ap_records - } - - ap_map = {} - - for bssid in sorted( - referenced_bssids - ): - if bssid not in package_bssids: - raise WifitripValidationError( - "Session references an AP not present " - "in access_points.json: " - f"{bssid}" - ) - - access_point_id, _ = ( - _get_or_create_import_ap( - conn, - bssid, - ) - ) - - ap_map[ - bssid - ] = access_point_id - - result["access_points"] = len( - ap_map - ) - - result["gps_points"] = _import_gps_tracks( - conn, - session_id, - session_hash, - package["gps_tracks"], - ) - - result["observations"] = _import_observations( - conn, - session_id, - session_hash, - package["observations"], - ap_map, - ) - - ( - result["handshakes"], - handshake_map, - ) = _import_handshakes( - conn, - session_id, - session_hash, - package["handshakes"], - ap_map, - ) - - calculated_hash = _calculate_session_hash( - conn, - session_id, - ) - - if calculated_hash != session_hash: - raise WifitripHashMismatchError( - "Session hash mismatch: " - f"expected {session_hash}, " - f"calculated {calculated_hash}" - ) - - _update_imported_ap_statistics( - conn, - ap_map, - session_id, - ) - - result["credentials"] = _import_credentials( - conn, - session_hash, - package["credentials"], - ap_map, - handshake_map, - ) - - conn.commit() - - result["status"] = "NEW" - - logger.info( - "wifitrip session imported: " - "hash=%s access_points=%d " - "gps_points=%d observations=%d " - "handshakes=%d credentials=%d", - session_hash, - result["access_points"], - result["gps_points"], - result["observations"], - result["handshakes"], - result["credentials"], - ) - - return result - - except Exception as error: - conn.rollback() - - result["status"] = "FAILED" - result["error"] = str( - error - ) - - logger.error( - "wifitrip session import failed: " - "hash=%s error=%s", - session_hash, - error, - ) - - return result - - -# ============================================================ -# Import -# ============================================================ - -def import_wifitrip( - conn, - path, -): - started_at = datetime.now( - timezone.utc - ) - - package = _load_package( - path - ) - - results = [] - - for session_record in package[ - "sessions" - ]: - result = _import_session( - conn, - package, - session_record, - ) - - results.append( - result - ) - - imported = sum( - 1 - for result in results - if result["status"] == "NEW" - ) - - duplicates = sum( - 1 - for result in results - if result["status"] == "DUPLICATE" - ) - - failed = sum( - 1 - for result in results - if result["status"] == "FAILED" - ) - - duration = ( - datetime.now( - timezone.utc - ) - started_at - ).total_seconds() - - result = { - "file": str( - path - ), - "valid": True, - "sessions": len( - results - ), - "imported": imported, - "duplicates": duplicates, - "failed": failed, - "results": results, - "duration": duration, - } - - logger.info( - "wifitrip import completed: " - "file=%s sessions=%d imported=%d " - "duplicates=%d failed=%d duration=%.3fs", - path, - result["sessions"], - imported, - duplicates, - failed, - duration, - ) - - return result