2025-06-09 10:17:12 +05:00
|
|
|
|
import time
|
|
|
|
|
|
import logging
|
|
|
|
|
|
import subprocess
|
|
|
|
|
|
import re
|
|
|
|
|
|
from functools import lru_cache
|
2025-06-17 11:40:20 +05:00
|
|
|
|
from typing import List, Optional, Dict, Tuple
|
2025-06-09 10:17:12 +05:00
|
|
|
|
from mac_vendor_lookup import MacLookup
|
|
|
|
|
|
import pywifi
|
|
|
|
|
|
from models.wifi import WifiAccessPoint, WifiScanResult
|
2025-06-17 11:40:20 +05:00
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
import json
|
2025-07-15 13:07:14 +05:00
|
|
|
|
from utils.i18n import get_translations
|
2025-07-08 15:57:42 +05:00
|
|
|
|
from babel.support import Translations
|
|
|
|
|
|
from fastapi import Depends
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
2025-07-15 13:07:14 +05:00
|
|
|
|
# Настройка логирования
|
2025-06-12 16:32:05 +05:00
|
|
|
|
logging.basicConfig(
|
2025-06-12 16:47:27 +05:00
|
|
|
|
level=logging.DEBUG,
|
2025-07-15 13:07:14 +05:00
|
|
|
|
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
|
|
|
|
)
|
2025-06-09 10:17:12 +05:00
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
2025-06-17 11:40:20 +05:00
|
|
|
|
class WifiStorage:
|
2025-10-21 09:20:50 +05:00
|
|
|
|
"""Класс для хранения данных о Wi-Fi сетях и их заметках по SSID.
|
2025-10-14 11:42:57 +05:00
|
|
|
|
|
2025-10-21 10:51:32 +05:00
|
|
|
|
Формат::
|
|
|
|
|
|
|
2025-10-14 11:42:57 +05:00
|
|
|
|
{
|
|
|
|
|
|
"networks": [{"ssid": str, "note": Optional[str]}]
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
Поведение:
|
2025-10-21 10:51:32 +05:00
|
|
|
|
|
|
|
|
|
|
- Создаёт директорию хранения при инициализации, ведёт логирование путей.
|
|
|
|
|
|
- Валидирует структуру при чтении и безопасно записывает JSON с Unicode и отступами.
|
2025-10-14 11:42:57 +05:00
|
|
|
|
"""
|
2025-07-15 15:12:01 +05:00
|
|
|
|
def __init__(self, storage_path: str = "storage/wifi/wifi.json", translations: Translations = Depends(get_translations())):
|
2025-06-17 11:40:20 +05:00
|
|
|
|
self.storage_file = Path(storage_path)
|
|
|
|
|
|
self.storage_file.parent.mkdir(parents=True, exist_ok=True)
|
2025-07-08 15:57:42 +05:00
|
|
|
|
self.translations = translations
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.info(f"Wi-Fi storage initialized at: {self.storage_file.absolute()}")
|
2025-06-17 11:40:20 +05:00
|
|
|
|
|
|
|
|
|
|
def load_notes(self) -> Dict[str, Optional[str]]:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Загружает заметки по SSID из файла хранения."""
|
2025-06-17 11:40:20 +05:00
|
|
|
|
try:
|
|
|
|
|
|
if self.storage_file.exists():
|
|
|
|
|
|
with open(self.storage_file, "r", encoding="utf-8") as f:
|
|
|
|
|
|
data = json.load(f)
|
2025-07-15 13:07:14 +05:00
|
|
|
|
if not isinstance(data, dict) or "networks" not in data:
|
|
|
|
|
|
logger.warning(f"Invalid JSON structure in {self.storage_file}, expected {'networks': [...]}, got {data}")
|
|
|
|
|
|
return {}
|
2025-06-17 11:40:20 +05:00
|
|
|
|
return {item["ssid"]: item.get("note") for item in data.get("networks", [])}
|
|
|
|
|
|
return {}
|
2025-07-15 13:07:14 +05:00
|
|
|
|
except json.JSONDecodeError as e:
|
|
|
|
|
|
logger.error(f"JSON decode error in {self.storage_file}: {str(e)}")
|
|
|
|
|
|
return {}
|
2025-06-17 11:40:20 +05:00
|
|
|
|
except Exception as e:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.error(f"Error loading notes from {self.storage_file}: {str(e)}")
|
2025-06-17 11:40:20 +05:00
|
|
|
|
return {}
|
|
|
|
|
|
|
|
|
|
|
|
def save_notes(self, notes: Dict[str, Optional[str]]) -> None:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Сохраняет заметки по SSID в файл."""
|
2025-06-17 11:40:20 +05:00
|
|
|
|
try:
|
|
|
|
|
|
data = {"networks": [{"ssid": ssid, "note": note} for ssid, note in notes.items()]}
|
|
|
|
|
|
with open(self.storage_file, "w", encoding="utf-8") as f:
|
|
|
|
|
|
json.dump(data, f, indent=2, ensure_ascii=False)
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.info(f"Saved {len(notes)} notes to {self.storage_file.absolute()}")
|
|
|
|
|
|
except PermissionError as e:
|
|
|
|
|
|
logger.error(f"Permission denied writing to {self.storage_file}: {str(e)}")
|
|
|
|
|
|
raise
|
2025-06-17 11:40:20 +05:00
|
|
|
|
except Exception as e:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.error(f"Error saving notes to {self.storage_file}: {str(e)}")
|
2025-07-08 15:57:42 +05:00
|
|
|
|
raise Exception(self.translations.gettext("Ошибка при сохранении заметок: {error}").format(error=str(e)))
|
2025-06-12 16:32:05 +05:00
|
|
|
|
|
2025-06-09 10:17:12 +05:00
|
|
|
|
class WifiService:
|
2025-10-21 09:20:50 +05:00
|
|
|
|
"""Сервис для сканирования текущих Wi-Fi точек доступа и заметок.
|
2025-10-14 11:42:57 +05:00
|
|
|
|
|
|
|
|
|
|
Источники данных:
|
|
|
|
|
|
- `pywifi` для базового сканирования и получения списка AP.
|
|
|
|
|
|
- `iw dev <iface> scan` для уточнения частоты, сигнала и безопасности.
|
|
|
|
|
|
- `MacLookup` для определения вендора по BSSID.
|
|
|
|
|
|
|
|
|
|
|
|
Политики:
|
|
|
|
|
|
- Выбор лучшего AP по SSID по уровню сигнала.
|
|
|
|
|
|
- Кэширование определения вендора.
|
|
|
|
|
|
- Сохранение SSID даже без заметок для будущих операций.
|
|
|
|
|
|
"""
|
2025-07-15 15:12:01 +05:00
|
|
|
|
def __init__(self, translations: Translations = Depends(get_translations())):
|
2025-06-09 10:17:12 +05:00
|
|
|
|
self.mac_lookup = MacLookup()
|
|
|
|
|
|
self.wifi = pywifi.PyWiFi()
|
|
|
|
|
|
self.interface = self._get_wifi_interface()
|
2025-07-15 13:07:14 +05:00
|
|
|
|
if not hasattr(translations, 'gettext'):
|
|
|
|
|
|
logger.warning("Translations object does not support gettext, using fallback")
|
|
|
|
|
|
self.translations = Translations.load("utils/locales/en/LC_MESSAGES/services.mo")
|
|
|
|
|
|
else:
|
|
|
|
|
|
self.translations = translations
|
2025-06-17 11:40:20 +05:00
|
|
|
|
self.storage = WifiStorage()
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
|
|
|
|
|
def _get_wifi_interface(self) -> Optional[object]:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Автоматически определяет активный Wi-Fi-интерфейс."""
|
2025-06-09 10:17:12 +05:00
|
|
|
|
try:
|
|
|
|
|
|
interfaces = self.wifi.interfaces()
|
|
|
|
|
|
if not interfaces:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(self.translations.gettext("Не найдено сетевых интерфейсов"))
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return None
|
|
|
|
|
|
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.debug(f"Available interfaces: {[iface.name() for iface in interfaces]}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
|
|
|
|
|
for iface in interfaces:
|
|
|
|
|
|
iface_name = iface.name()
|
2025-06-17 11:40:20 +05:00
|
|
|
|
if "p2p" in iface_name.lower():
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.debug(f"Skipped interface {iface_name} (P2P)")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
continue
|
|
|
|
|
|
try:
|
|
|
|
|
|
iface.scan()
|
|
|
|
|
|
time.sleep(1)
|
|
|
|
|
|
results = iface.scan_results()
|
|
|
|
|
|
if results:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.info(f"Selected Wi-Fi interface: {iface_name}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return iface
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.debug(f"Interface {iface_name} returned no scan results")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
except Exception as e:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.debug(f"Interface {iface_name} inactive: {str(e)}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(self.translations.gettext("Не найден активный Wi-Fi-интерфейс"))
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return None
|
|
|
|
|
|
except Exception as e:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"Error determining Wi-Fi interface: {str(e)}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
@lru_cache(maxsize=1000)
|
|
|
|
|
|
def get_vendor(self, mac: str) -> str:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Определяет вендора по MAC-адресу с использованием кэширования."""
|
2025-06-09 10:17:12 +05:00
|
|
|
|
try:
|
|
|
|
|
|
return self.mac_lookup.lookup(mac)
|
|
|
|
|
|
except Exception as e:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.warning(f"Failed to determine vendor for MAC {mac}: {str(e)}")
|
2025-07-08 15:57:42 +05:00
|
|
|
|
return self.translations.gettext("Неизвестный")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
|
|
|
|
|
def _get_encryption_from_iw(self, ap_info: Dict) -> str:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Определяет тип шифрования из данных, полученных через iw."""
|
2025-06-09 10:17:12 +05:00
|
|
|
|
security = ap_info.get("security", "")
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.debug(f"Encryption for BSSID {ap_info.get('bssid')}: {security}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
if "WPA3" in security:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
return self.translations.gettext("WPA3")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
elif "WPA2" in security or "RSN" in security:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
return self.translations.gettext("WPA2")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
elif "WPA" in security:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
return self.translations.gettext("WPA")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
elif "WEP" in security:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
return self.translations.gettext("WEP")
|
|
|
|
|
|
return self.translations.gettext("Открытая")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
|
|
|
|
|
def _get_channel(self, frequency: Optional[int]) -> Optional[int]:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Преобразует частоту в номер канала."""
|
2025-06-09 10:17:12 +05:00
|
|
|
|
if frequency is None:
|
|
|
|
|
|
return None
|
|
|
|
|
|
try:
|
|
|
|
|
|
if 2412 <= frequency <= 2472:
|
|
|
|
|
|
return (frequency - 2412) // 5 + 1
|
|
|
|
|
|
elif 5180 <= frequency <= 5825:
|
|
|
|
|
|
return (frequency - 5180) // 5 + 36
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.debug(f"Frequency {frequency} outside 2.4/5 GHz range")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return None
|
|
|
|
|
|
except Exception as e:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.debug(f"Error determining channel for frequency {frequency}: {str(e)}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def _get_frequency(self, frequency: Optional[int]) -> Optional[str]:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Определяет частотный диапазон на основе частоты."""
|
2025-06-09 10:17:12 +05:00
|
|
|
|
if frequency is None:
|
|
|
|
|
|
return None
|
|
|
|
|
|
try:
|
|
|
|
|
|
if 2412 <= frequency <= 2472:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
return self.translations.gettext("2.4 ГГц")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
elif 5180 <= frequency <= 5825:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
return self.translations.gettext("5 ГГц")
|
|
|
|
|
|
logger.debug(f"Frequency {frequency} outside 2.4/5 GHz range")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return None
|
|
|
|
|
|
except Exception as e:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.debug(f"Error determining band for frequency {frequency}: {str(e)}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def _get_iw_scan_data(self) -> List[Dict]:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Получает данные сканирования Wi-Fi через команду iw."""
|
2025-06-09 10:17:12 +05:00
|
|
|
|
try:
|
|
|
|
|
|
if not self.interface:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(self.translations.gettext("Интерфейс не определён"))
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return []
|
|
|
|
|
|
cmd = ["sudo", "iw", "dev", self.interface.name(), "scan"]
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.debug(f"Executing command: {' '.join(cmd)}")
|
2025-07-15 13:07:14 +05:00
|
|
|
|
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
|
2025-06-09 10:17:12 +05:00
|
|
|
|
if result.returncode != 0:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"iw scan error: {result.stderr}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return []
|
|
|
|
|
|
output = result.stdout
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.debug(f"iw scan output (first 500 chars): {output[:500]}...")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
|
|
|
|
|
aps = []
|
|
|
|
|
|
current_ap = None
|
|
|
|
|
|
bssid_pattern = re.compile(r"BSS ([0-9a-f:]{17})")
|
|
|
|
|
|
ssid_pattern = re.compile(r"SSID: ?(.*)")
|
|
|
|
|
|
freq_pattern = re.compile(r"freq: (\d+)")
|
|
|
|
|
|
signal_pattern = re.compile(r"signal: ([-\d.]+) dBm")
|
|
|
|
|
|
rsn_pattern = re.compile(r"RSN:")
|
|
|
|
|
|
wpa_pattern = re.compile(r"WPA:")
|
|
|
|
|
|
security_type_pattern = re.compile(r"\* (WPA3|WPA2|WPA|WEP)")
|
|
|
|
|
|
|
|
|
|
|
|
for line in output.splitlines():
|
|
|
|
|
|
line = line.strip()
|
|
|
|
|
|
if bssid_match := bssid_pattern.match(line):
|
|
|
|
|
|
if current_ap:
|
|
|
|
|
|
aps.append(current_ap)
|
2025-07-15 13:07:14 +05:00
|
|
|
|
current_ap = {"bssid": bssid_match.group(1).lower(), "security": ""}
|
2025-06-09 10:17:12 +05:00
|
|
|
|
elif current_ap:
|
|
|
|
|
|
if ssid_match := ssid_pattern.match(line):
|
2025-07-15 13:07:14 +05:00
|
|
|
|
current_ap["ssid"] = ssid_match.group(1).strip() if ssid_match.group(1).strip() else ""
|
2025-06-09 10:17:12 +05:00
|
|
|
|
elif freq_match := freq_pattern.match(line):
|
|
|
|
|
|
current_ap["frequency"] = int(freq_match.group(1))
|
|
|
|
|
|
elif signal_match := signal_pattern.match(line):
|
|
|
|
|
|
current_ap["signal"] = float(signal_match.group(1))
|
|
|
|
|
|
elif rsn_pattern.match(line):
|
|
|
|
|
|
current_ap["security"] += "RSN;"
|
|
|
|
|
|
elif wpa_pattern.match(line):
|
|
|
|
|
|
current_ap["security"] += "WPA;"
|
2025-07-15 13:07:14 +05:00
|
|
|
|
elif security_type_match := security_type_pattern.search(line):
|
|
|
|
|
|
current_ap["security"] += security_type_match.group(1) + ";"
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
|
|
|
|
|
if current_ap:
|
|
|
|
|
|
aps.append(current_ap)
|
|
|
|
|
|
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.debug(f"Found {len(aps)} access points via iw: {[ap['bssid'] for ap in aps]}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return aps
|
|
|
|
|
|
except subprocess.CalledProcessError as e:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"Error executing iw scan: {e.stderr}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return []
|
|
|
|
|
|
except subprocess.TimeoutExpired:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(self.translations.gettext("Таймаут при выполнении iw scan"))
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return []
|
|
|
|
|
|
except Exception as e:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"Error parsing iw scan: {str(e)}")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
|
|
def scan_wifi(self, timeout: int = 30) -> WifiScanResult:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Сканирует текущие Wi-Fi точки доступа."""
|
2025-06-09 10:17:12 +05:00
|
|
|
|
start_time = time.time()
|
|
|
|
|
|
aps = []
|
|
|
|
|
|
|
|
|
|
|
|
if not self.interface:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(self.translations.gettext("Wi-Fi-интерфейс не доступен"))
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return WifiScanResult(access_points=aps)
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.info(f"Starting Wi-Fi scan on interface {self.interface.name()}")
|
|
|
|
|
|
max_attempts = 3
|
|
|
|
|
|
for attempt in range(max_attempts):
|
|
|
|
|
|
self.interface.scan()
|
|
|
|
|
|
time.sleep(min(timeout, 5))
|
|
|
|
|
|
py_results = self.interface.scan_results()
|
|
|
|
|
|
if py_results:
|
|
|
|
|
|
logger.info(f"Found {len(py_results)} access points via pywifi after attempt {attempt + 1}")
|
|
|
|
|
|
break
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.warning(f"Scan attempt {attempt + 1} failed, trying again (FAIL-BUSY?)")
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.error("All scan attempts failed")
|
|
|
|
|
|
return WifiScanResult(access_points=aps)
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
|
|
|
|
|
iw_results = self._get_iw_scan_data()
|
2025-06-17 11:40:20 +05:00
|
|
|
|
iw_by_bssid = {ap["bssid"]: ap for ap in iw_results if ap.get("bssid")}
|
|
|
|
|
|
|
|
|
|
|
|
best_aps_by_ssid: Dict[str, WifiAccessPoint] = {}
|
|
|
|
|
|
saved_notes = self.storage.load_notes()
|
|
|
|
|
|
|
2025-06-09 10:17:12 +05:00
|
|
|
|
for ap in py_results:
|
|
|
|
|
|
bssid = ap.bssid.lower() if ap.bssid else None
|
|
|
|
|
|
if not bssid:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.debug("Skipped access point without BSSID")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
continue
|
2025-07-15 13:07:14 +05:00
|
|
|
|
ssid = ap.ssid if ap.ssid else f"Hidden_{bssid}"
|
|
|
|
|
|
hidden = not ap.ssid
|
2025-06-09 10:17:12 +05:00
|
|
|
|
signal = ap.signal if ap.signal else None
|
|
|
|
|
|
iw_data = iw_by_bssid.get(bssid, {})
|
|
|
|
|
|
|
|
|
|
|
|
frequency = iw_data.get("frequency")
|
|
|
|
|
|
channel = self._get_channel(frequency)
|
|
|
|
|
|
freq_band = self._get_frequency(frequency)
|
|
|
|
|
|
encryption = self._get_encryption_from_iw(iw_data)
|
|
|
|
|
|
vendor = self.get_vendor(bssid)
|
|
|
|
|
|
|
2025-06-11 11:52:56 +05:00
|
|
|
|
current_ap = WifiAccessPoint(
|
2025-06-09 10:17:12 +05:00
|
|
|
|
ssid=ssid,
|
|
|
|
|
|
bssid=bssid,
|
|
|
|
|
|
channel=channel,
|
|
|
|
|
|
signal=signal if signal else iw_data.get("signal"),
|
|
|
|
|
|
encryption=encryption,
|
|
|
|
|
|
frequency=freq_band,
|
|
|
|
|
|
vendor=vendor,
|
2025-06-12 16:32:05 +05:00
|
|
|
|
hidden=hidden,
|
2025-07-15 13:07:14 +05:00
|
|
|
|
note=saved_notes.get(ssid) if ap.ssid else None,
|
2025-06-09 10:17:12 +05:00
|
|
|
|
)
|
2025-07-15 13:07:14 +05:00
|
|
|
|
logger.debug(f"Processed AP: {current_ap.model_dump()}")
|
2025-06-11 11:52:56 +05:00
|
|
|
|
|
2025-06-12 16:32:05 +05:00
|
|
|
|
if ssid not in best_aps_by_ssid or (
|
2025-06-12 16:47:27 +05:00
|
|
|
|
current_ap.signal and best_aps_by_ssid[ssid].signal
|
|
|
|
|
|
and current_ap.signal > best_aps_by_ssid[ssid].signal):
|
2025-07-15 13:07:14 +05:00
|
|
|
|
current_ap.note = saved_notes.get(ssid) if ap.ssid else None
|
2025-06-11 11:52:56 +05:00
|
|
|
|
best_aps_by_ssid[ssid] = current_ap
|
|
|
|
|
|
|
|
|
|
|
|
aps = list(best_aps_by_ssid.values())
|
2025-07-15 13:07:14 +05:00
|
|
|
|
# Сохраняем хотя бы SSID, если заметок нет
|
2025-06-17 11:40:20 +05:00
|
|
|
|
notes_to_save = {ap.ssid: ap.note for ap in aps if ap.ssid}
|
2025-07-15 13:07:14 +05:00
|
|
|
|
if not notes_to_save and aps:
|
|
|
|
|
|
notes_to_save = {ap.ssid: None for ap in aps if ap.ssid} # Сохраняем SSID без заметок
|
|
|
|
|
|
if notes_to_save:
|
|
|
|
|
|
self.storage.save_notes(notes_to_save)
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.warning("No notes or SSIDs to save, skipping file write")
|
|
|
|
|
|
|
|
|
|
|
|
logger.info(f"Wi-Fi scan completed, found {len(aps)} unique networks")
|
2025-06-09 10:17:12 +05:00
|
|
|
|
return WifiScanResult(access_points=aps)
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"Error scanning Wi-Fi: {str(e)}")
|
2025-06-12 16:32:05 +05:00
|
|
|
|
return WifiScanResult(access_points=aps)
|
2025-06-17 11:40:20 +05:00
|
|
|
|
|
|
|
|
|
|
def add_note(self, ssid: str, note: str) -> Tuple[bool, Optional[str]]:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Добавляет заметку к сети Wi-Fi по SSID."""
|
2025-06-17 11:40:20 +05:00
|
|
|
|
try:
|
|
|
|
|
|
saved_notes = self.storage.load_notes()
|
|
|
|
|
|
if ssid not in saved_notes or saved_notes[ssid] is None:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.info(f"Added new note for network with SSID {ssid}")
|
2025-06-17 11:40:20 +05:00
|
|
|
|
elif saved_notes[ssid] is not None:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"Note for network with SSID {ssid} already exists")
|
|
|
|
|
|
return False, self.translations.gettext("Заметка для сети с SSID {ssid} уже существует").format(ssid=ssid)
|
2025-06-17 11:40:20 +05:00
|
|
|
|
saved_notes[ssid] = note
|
|
|
|
|
|
self.storage.save_notes(saved_notes)
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.info(f"Added note '{note}' for network with SSID {ssid}")
|
2025-06-17 11:40:20 +05:00
|
|
|
|
return True, None
|
|
|
|
|
|
except Exception as e:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"Error adding note for SSID {ssid}: {str(e)}")
|
|
|
|
|
|
return False, self.translations.gettext("Внутренняя ошибка сервера: {error}").format(error=str(e))
|
2025-06-17 11:40:20 +05:00
|
|
|
|
|
|
|
|
|
|
def update_note(self, ssid: str, note: str) -> Tuple[bool, Optional[str]]:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Обновляет заметку сети Wi-Fi по SSID."""
|
2025-06-17 11:40:20 +05:00
|
|
|
|
try:
|
|
|
|
|
|
saved_notes = self.storage.load_notes()
|
|
|
|
|
|
if ssid not in saved_notes:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.warning(f"Network with SSID {ssid} not found")
|
|
|
|
|
|
return False, self.translations.gettext("Сеть с SSID {ssid} не найдена").format(ssid=ssid)
|
2025-06-17 11:40:20 +05:00
|
|
|
|
if saved_notes[ssid] is None:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"Note for network with SSID {ssid} does not exist")
|
|
|
|
|
|
return False, self.translations.gettext("Заметка для сети с SSID {ssid} не существует").format(ssid=ssid)
|
2025-06-17 11:40:20 +05:00
|
|
|
|
saved_notes[ssid] = note
|
|
|
|
|
|
self.storage.save_notes(saved_notes)
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.info(f"Updated note '{note}' for network with SSID {ssid}")
|
2025-06-17 11:40:20 +05:00
|
|
|
|
return True, None
|
|
|
|
|
|
except Exception as e:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"Error updating note for SSID {ssid}: {str(e)}")
|
|
|
|
|
|
return False, self.translations.gettext("Внутренняя ошибка сервера: {error}").format(error=str(e))
|
2025-06-17 11:40:20 +05:00
|
|
|
|
|
|
|
|
|
|
def delete_note(self, ssid: str) -> Tuple[bool, Optional[str]]:
|
2025-07-15 13:07:14 +05:00
|
|
|
|
"""Удаляет заметку сети Wi-Fi по SSID."""
|
2025-06-17 11:40:20 +05:00
|
|
|
|
try:
|
|
|
|
|
|
saved_notes = self.storage.load_notes()
|
|
|
|
|
|
if ssid not in saved_notes:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.warning(f"Network with SSID {ssid} not found")
|
|
|
|
|
|
return False, self.translations.gettext("Сеть с SSID {ssid} не найдена").format(ssid=ssid)
|
2025-06-17 11:40:20 +05:00
|
|
|
|
if saved_notes[ssid] is None:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"Note for network with SSID {ssid} does not exist")
|
|
|
|
|
|
return False, self.translations.gettext("Заметка для сети с SSID {ssid} не существует").format(ssid=ssid)
|
2025-06-17 11:40:20 +05:00
|
|
|
|
saved_notes[ssid] = None
|
|
|
|
|
|
self.storage.save_notes(saved_notes)
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.info(f"Deleted note for network with SSID {ssid}")
|
2025-06-17 11:40:20 +05:00
|
|
|
|
return True, None
|
|
|
|
|
|
except Exception as e:
|
2025-07-08 15:57:42 +05:00
|
|
|
|
logger.error(f"Error deleting note for SSID {ssid}: {str(e)}")
|
2025-10-21 10:51:32 +05:00
|
|
|
|
return False, self.translations.gettext("Внутренняя ошибка сервера: {error}").format(error=str(e))
|