gonets/SRV/services/settings_service.py

84 lines
3.5 KiB
Python
Raw Normal View History

import json
import logging
from utils.i18n import get_translations, _
from babel.support import Translations
from fastapi import Depends
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class SettingsService:
"""Сервис для управления настройками и очистки данных сети."""
def __init__(self, translations: Translations = Depends(get_translations())):
self.subnet_file = "storage/devices/devices.json"
self.wifi_file = "storage/wifi/wifi.json"
self.translations = translations
def clear_subnet(self) -> bool:
"""Очищает данные узлов подсети в файле devices.json.
Returns:
bool: True, если очистка успешна.
Raises:
Exception: Если произошла ошибка при записи в файл.
"""
try:
with open(self.subnet_file, "w") as f:
json.dump([], f)
logger.info("Subnet nodes data successfully cleared")
return True
except FileNotFoundError:
logger.info("Devices file not found, clearing considered successful")
return True
except Exception as e:
logger.error(f"Error clearing subnet nodes: {str(e)}")
raise Exception(self.translations.gettext("Ошибка очистки узлов подсети: {error}").format(error=str(e)))
def clear_wifi(self) -> bool:
"""Очищает данные точек доступа Wi-Fi в файле wifi.json.
Returns:
bool: True, если очистка успешна.
Raises:
Exception: Если произошла ошибка при записи в файл.
"""
try:
with open(self.wifi_file, "w") as f:
json.dump([], f)
logger.info("Wi-Fi access points data successfully cleared")
return True
except FileNotFoundError:
logger.info("Wi-Fi file not found, clearing considered successful")
return True
except Exception as e:
logger.error(f"Error clearing Wi-Fi access points: {str(e)}")
raise Exception(self.translations.gettext("Ошибка очистки точек доступа Wi-Fi: {error}").format(error=str(e)))
def clear_all_data(self) -> bool:
"""Очищает данные узлов подсети и точек доступа Wi-Fi в обоих файлах.
Returns:
bool: True, если очистка успешна.
Raises:
Exception: Если произошла ошибка при записи в один из файлов.
"""
try:
try:
with open(self.subnet_file, "w") as f:
json.dump([], f)
except FileNotFoundError:
logger.info("Devices file not found, clearing considered successful")
try:
with open(self.wifi_file, "w") as f:
json.dump([], f)
except FileNotFoundError:
logger.info("Wi-Fi file not found, clearing considered successful")
logger.info("All network data successfully cleared")
return True
except Exception as e:
logger.error(f"Error clearing all network data: {str(e)}")
raise Exception(self.translations.gettext("Ошибка очистки всех сетевых данных: {error}").format(error=str(e)))