Release WiFi GPS Mapper v2.3.0
This commit is contained in:
+252
-5
@@ -2,13 +2,60 @@ from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from scapy.all import PcapNgReader
|
||||
|
||||
from .config import CAPTURES_DIR, get_timezone
|
||||
from .template import card
|
||||
from .utils import esc
|
||||
|
||||
|
||||
def _capture_duration_seconds(capture_file):
|
||||
reader = None
|
||||
first_timestamp = None
|
||||
last_timestamp = None
|
||||
|
||||
try:
|
||||
reader = PcapNgReader(str(capture_file))
|
||||
|
||||
for packet in reader:
|
||||
try:
|
||||
timestamp = float(packet.time)
|
||||
except (AttributeError, TypeError, ValueError, OverflowError):
|
||||
continue
|
||||
|
||||
if first_timestamp is None or timestamp < first_timestamp:
|
||||
first_timestamp = timestamp
|
||||
|
||||
if last_timestamp is None or timestamp > last_timestamp:
|
||||
last_timestamp = timestamp
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
finally:
|
||||
if reader is not None:
|
||||
reader.close()
|
||||
|
||||
if first_timestamp is None or last_timestamp is None:
|
||||
return 0
|
||||
|
||||
return max(0, last_timestamp - first_timestamp)
|
||||
|
||||
|
||||
def _has_recoverable_capture(session_dir):
|
||||
minimum_duration = MIN_RECOVERY_DURATION.total_seconds()
|
||||
|
||||
return (
|
||||
_capture_duration_seconds(
|
||||
session_dir / "capture.pcapng"
|
||||
) >= minimum_duration
|
||||
)
|
||||
|
||||
|
||||
MIN_RECOVERY_DURATION = timedelta(minutes=5)
|
||||
|
||||
|
||||
MIN_STALE_AGE = timedelta(minutes=15)
|
||||
MAX_STALE_AGE = timedelta(hours=24)
|
||||
|
||||
SESSION_FILES = (
|
||||
"capture.pcapng",
|
||||
@@ -42,9 +89,7 @@ def _file_is_stale(path, now):
|
||||
|
||||
age = now - modified
|
||||
|
||||
return (
|
||||
MIN_STALE_AGE <= age <= MAX_STALE_AGE
|
||||
)
|
||||
return age >= MIN_STALE_AGE
|
||||
|
||||
|
||||
def _capture_is_interrupted(path, end_time, now):
|
||||
@@ -106,6 +151,32 @@ def _parser_was_interrupted(parser_log):
|
||||
return last_started >= 0 and last_started > last_finished
|
||||
|
||||
|
||||
def _parser_was_completed(parser_log):
|
||||
last_started = -1
|
||||
last_finished = -1
|
||||
|
||||
try:
|
||||
with parser_log.open(
|
||||
"r",
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
) as file:
|
||||
for index, line in enumerate(file):
|
||||
if "Parser started" in line:
|
||||
last_started = index
|
||||
|
||||
if "Parser finished" in line:
|
||||
last_finished = index
|
||||
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
return (
|
||||
last_started >= 0
|
||||
and last_finished > last_started
|
||||
)
|
||||
|
||||
|
||||
def _session_counts(conn, session_id):
|
||||
counts = {}
|
||||
|
||||
@@ -179,6 +250,34 @@ def _collect_files(session_dir):
|
||||
return result
|
||||
|
||||
|
||||
def _session_sources_are_stale(session_dir, now):
|
||||
source_paths = [
|
||||
session_dir / filename
|
||||
for filename in SESSION_FILES
|
||||
]
|
||||
|
||||
existing_paths = []
|
||||
|
||||
for source_path in source_paths:
|
||||
try:
|
||||
if source_path.is_file():
|
||||
existing_paths.append(source_path.stat().st_mtime)
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
if not existing_paths:
|
||||
return False
|
||||
|
||||
latest_modified = max(existing_paths)
|
||||
|
||||
modified = datetime.fromtimestamp(
|
||||
latest_modified,
|
||||
tz=timezone.utc,
|
||||
)
|
||||
|
||||
return now - modified >= MIN_STALE_AGE
|
||||
|
||||
|
||||
def find_recovery_candidates(
|
||||
conn,
|
||||
captures_dir=None,
|
||||
@@ -209,6 +308,7 @@ def find_recovery_candidates(
|
||||
""").fetchall()
|
||||
|
||||
candidates = []
|
||||
known_session_dirs = set()
|
||||
|
||||
for row in rows:
|
||||
session_id = row[0]
|
||||
@@ -224,9 +324,19 @@ def find_recovery_candidates(
|
||||
if session_dir is None or not session_dir.is_dir():
|
||||
continue
|
||||
|
||||
known_session_dirs.add(
|
||||
session_dir.resolve()
|
||||
)
|
||||
|
||||
capture_path = session_dir / "capture.pcapng"
|
||||
parser_log = session_dir / "parser.log"
|
||||
|
||||
if (
|
||||
parser_log.is_file()
|
||||
and _parser_was_completed(parser_log)
|
||||
):
|
||||
continue
|
||||
|
||||
capture_interrupted = _capture_is_interrupted(
|
||||
capture_path,
|
||||
end_time,
|
||||
@@ -247,6 +357,9 @@ def find_recovery_candidates(
|
||||
session_id,
|
||||
)
|
||||
|
||||
if not _has_recoverable_capture(session_dir):
|
||||
continue
|
||||
|
||||
reasons = []
|
||||
|
||||
if capture_interrupted:
|
||||
@@ -295,6 +408,81 @@ def find_recovery_candidates(
|
||||
),
|
||||
})
|
||||
|
||||
captures_root = Path(captures_dir).resolve()
|
||||
|
||||
try:
|
||||
session_directories = captures_root.iterdir()
|
||||
except OSError:
|
||||
session_directories = ()
|
||||
|
||||
for entry in session_directories:
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
|
||||
session_dir = entry.resolve()
|
||||
|
||||
if session_dir.parent != captures_root:
|
||||
continue
|
||||
|
||||
if session_dir in known_session_dirs:
|
||||
continue
|
||||
|
||||
try:
|
||||
start_time = datetime.strptime(
|
||||
session_dir.name,
|
||||
"%Y%m%d_%H%M%S",
|
||||
).replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
parser_log = session_dir / "parser.log"
|
||||
|
||||
if (
|
||||
parser_log.is_file()
|
||||
and _parser_was_completed(parser_log)
|
||||
):
|
||||
continue
|
||||
|
||||
if not _session_sources_are_stale(
|
||||
session_dir,
|
||||
now,
|
||||
):
|
||||
continue
|
||||
|
||||
if not _has_recoverable_capture(session_dir):
|
||||
continue
|
||||
|
||||
candidates.append({
|
||||
"id": None,
|
||||
"title": (
|
||||
f"Каталог {session_dir.name} "
|
||||
"(запись в БД отсутствует)"
|
||||
),
|
||||
"session_dir": str(session_dir),
|
||||
"start_time": _format_datetime(
|
||||
start_time.isoformat(),
|
||||
display_timezone,
|
||||
),
|
||||
"kind": "capture",
|
||||
"counts": {
|
||||
"gps": 0,
|
||||
"access_points": 0,
|
||||
"handshakes": 0,
|
||||
},
|
||||
"files": _collect_files(session_dir),
|
||||
"reasons": [
|
||||
"Найдены исходные файлы поездки, "
|
||||
"которые не обновлялись более 15 минут. "
|
||||
"Запись этой поездки в capture_sessions отсутствует."
|
||||
],
|
||||
"actions": (
|
||||
"Проверить исходные файлы и восстановить "
|
||||
"запись поездки в базе данных."
|
||||
),
|
||||
})
|
||||
|
||||
return candidates
|
||||
|
||||
|
||||
@@ -309,6 +497,11 @@ def recovery_block(conn):
|
||||
for candidate in candidates:
|
||||
counts = candidate["counts"]
|
||||
|
||||
title = candidate.get(
|
||||
"title",
|
||||
f"Поездка #{candidate['id']}",
|
||||
)
|
||||
|
||||
files_html = "".join(
|
||||
"<li>{} — {} байт</li>".format(
|
||||
esc(item["name"]),
|
||||
@@ -322,9 +515,61 @@ def recovery_block(conn):
|
||||
for reason in candidate["reasons"]
|
||||
)
|
||||
|
||||
recovery_html = ""
|
||||
|
||||
if candidate.get("id") is None:
|
||||
|
||||
directory_name = Path(
|
||||
candidate["session_dir"]
|
||||
).name
|
||||
|
||||
recovery_html = f"""
|
||||
<form method="post"
|
||||
action="/reports/recovery/{esc(directory_name)}">
|
||||
<button type="submit" class="button">
|
||||
Восстановить поездку
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p>
|
||||
Если восстановление не требуется, каталог можно удалить вручную:
|
||||
</p>
|
||||
|
||||
<p class="recovery-directory">
|
||||
<code>{esc(candidate["session_dir"])}</code>
|
||||
<button
|
||||
type="button"
|
||||
class="recovery-copy-button"
|
||||
data-copy-path="{esc(candidate["session_dir"])}"
|
||||
onclick="copyRecoveryPath(this)"
|
||||
title="Копировать путь"
|
||||
aria-label="Копировать путь"
|
||||
><svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.8"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<rect x="8" y="8" width="13" height="13" rx="2"/>
|
||||
<path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>
|
||||
</svg></button>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Удаление безвозвратно уничтожит файлы поездки.
|
||||
Приложение автоматически файлы не удаляет.
|
||||
</p>
|
||||
"""
|
||||
|
||||
html.append(f"""
|
||||
<div class="card">
|
||||
<h3>Поездка #{candidate["id"]}</h3>
|
||||
<h3>{esc(title)}</h3>
|
||||
|
||||
<p>
|
||||
<strong>Дата начала:</strong>
|
||||
@@ -357,6 +602,8 @@ def recovery_block(conn):
|
||||
<strong>Возможное дальнейшее действие:</strong>
|
||||
{esc(candidate["actions"])}
|
||||
</p>
|
||||
|
||||
{recovery_html}
|
||||
</div>
|
||||
""")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user