gonets/SRV/api/v1/subnet.py
2025-06-20 11:22:54 +05:00

159 lines
No EOL
7.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from fastapi import APIRouter, HTTPException
from typing import List, Dict
from models.subnet import SubnetScanResult
from models.wifi import WifiScanResult
from models.request import NoteRequest, WifiConnectRequest, WifiDisconnectRequest
from services.subnet_service import SubnetService
from services.wifi_service import WifiService
from services.connect_service import WifiConnectionService
router = APIRouter()
@router.get("/devices", response_model=SubnetScanResult)
def scan_subnet(subnet: str = "192.168.1.0/24", ports: List[int] = None):
"""Сканирует локальную подсеть и возвращает данные об устройствах"""
try:
subnet_service = SubnetService()
result = subnet_service.scan_subnet(subnet, ports)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=f"Ошибка сканирования: {str(e)}")
@router.get("/wifi", response_model=WifiScanResult)
def scan_wifi(timeout: int = 30):
"""Сканирует Wi-Fi точки доступа и возвращает данные о них"""
try:
wifi_service = WifiService()
result = wifi_service.scan_wifi(timeout=timeout)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=f"Ошибка сканирования Wi-Fi: {str(e)}")
@router.post("/devices/{mac}/note")
def add_note(mac: str, request: NoteRequest):
"""Добавляет заметку для устройства по MAC-адресу"""
try:
subnet_service = SubnetService()
success, error_message = subnet_service.add_note(mac, request.note)
if not success:
if "не найдено" in error_message:
raise HTTPException(status_code=404, detail=error_message)
elif "уже существует" in error_message:
raise HTTPException(status_code=400, detail=error_message)
return {"message": f"Заметка '{request.note}' добавлена для устройства {mac}"}
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=f"Ошибка добавления заметки: {str(e)}")
@router.put("/devices/{mac}/note")
def update_note(mac: str, request: NoteRequest):
"""Обновляет заметку для устройства по MAC-адресу"""
try:
subnet_service = SubnetService()
success, error_message = subnet_service.update_note(mac, request.note)
if not success:
if "не найдено" in error_message:
raise HTTPException(status_code=404, detail=error_message)
elif "не существует" in error_message:
raise HTTPException(status_code=400, detail=error_message)
return {"message": f"Заметка '{request.note}' обновлена для устройства {mac}"}
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=f"Ошибка обновления заметки: {str(e)}")
@router.delete("/devices/{mac}/note")
def delete_note(mac: str):
"""Удаляет заметку для устройства по MAC-адресу"""
try:
subnet_service = SubnetService()
success, error_message = subnet_service.delete_note(mac)
if not success:
if "не найдено" in error_message:
raise HTTPException(status_code=404, detail=error_message)
elif "не существует" in error_message:
raise HTTPException(status_code=400, detail=error_message)
return {"message": f"Заметка удалена для устройства {mac}"}
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=f"Ошибка удаления заметки: {str(e)}")
@router.post("/wifi/{ssid}/note")
def add_wifi_note(ssid: str, request: NoteRequest):
"""Добавляет заметку для сети Wi-Fi по SSID"""
try:
wifi_service = WifiService()
success, error_message = wifi_service.add_note(ssid, request.note)
if not success:
if "не найдена" in error_message:
raise HTTPException(status_code=404, detail=error_message)
elif "уже существует" in error_message:
raise HTTPException(status_code=400, detail=error_message)
return {"message": f"Заметка '{request.note}' добавлена для сети с SSID {ssid}"}
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=f"Ошибка добавления заметки: {str(e)}")
@router.put("/wifi/{ssid}/note")
def update_wifi_note(ssid: str, request: NoteRequest):
"""Обновляет заметку для сети Wi-Fi по SSID"""
try:
wifi_service = WifiService()
success, error_message = wifi_service.update_note(ssid, request.note)
if not success:
if "не найдена" in error_message:
raise HTTPException(status_code=404, detail=error_message)
elif "не существует" in error_message:
raise HTTPException(status_code=400, detail=error_message)
return {"message": f"Заметка '{request.note}' обновлена для сети с SSID {ssid}"}
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=f"Ошибка обновления заметки: {str(e)}")
@router.delete("/wifi/{ssid}/note")
def delete_wifi_note(ssid: str):
"""Удаляет заметку для сети Wi-Fi по SSID"""
try:
wifi_service = WifiService()
success, error_message = wifi_service.delete_note(ssid)
if not success:
if "не найдена" in error_message:
raise HTTPException(status_code=404, detail=error_message)
elif "не существует" in error_message:
raise HTTPException(status_code=400, detail=error_message)
return {"message": f"Заметка удалена для сети с SSID {ssid}"}
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=f"Ошибка удаления заметки: {str(e)}")
@router.post("/wifi/connect")
def connect_to_wifi(request: WifiConnectRequest):
"""Подключается к Wi-Fi сети по SSID и паролю."""
wifi_service = WifiConnectionService()
success, message = wifi_service.connect(request.ssid, request.password)
if not success:
raise HTTPException(status_code=400, detail=message)
return {"message": f"Успешно подключено к {request.ssid}"}
@router.post("/wifi/disconnect")
def disconnect_from_wifi(request: WifiDisconnectRequest):
"""Отключается от Wi-Fi сети по указанному SSID."""
wifi_service = WifiConnectionService()
success, message = wifi_service.disconnect(request.ssid)
if not success:
raise HTTPException(status_code=400, detail=message)
return {"message": message or f"Успешно отключено от {request.ssid}"}
@router.get("/wifi/status")
def get_wifi_status():
"""Проверяет статус текущего подключения к Wi-Fi."""
wifi_service = WifiConnectionService()
success, message = wifi_service.get_status()
if not success:
raise HTTPException(status_code=400, detail=message)
return {"status": "connected", "ssid": message}