Files
barcode_reader_pc/server/config.py
T
2026-11-22 16:08:17 +01:00

80 lines
3.1 KiB
Python

import json
import os
import socket
import sys
from pathlib import Path
def _resolve_config_file() -> Path:
"""Restituisce un percorso persistente e scrivibile per config.json (anche in binary PyInstaller)."""
if getattr(sys, "frozen", False):
exe_path = Path(sys.executable).resolve()
exe_dir = exe_path.parent
candidate = exe_dir / "config.json"
is_appimage = sys.platform.startswith("linux") and bool(os.environ.get("APPIMAGE"))
is_mac_bundle = sys.platform == "darwin" and ".app/" in str(exe_path)
is_win_installer = sys.platform == "win32" and (exe_dir / "unins000.exe").exists()
# Mantieni portable solo per binari standalone non gestiti da AppImage/bundle/installer
if not is_appimage and not is_mac_bundle and not is_win_installer:
if candidate.exists():
if os.access(candidate, os.W_OK):
return candidate
elif os.access(exe_dir, os.W_OK):
return candidate
# Directory configurazione utente persistente tra gli aggiornamenti
if sys.platform == "win32":
base_dir = Path(os.environ.get("APPDATA", Path.home())) / "BarcodeReaderServer"
elif sys.platform == "darwin":
base_dir = Path.home() / "Library" / "Application Support" / "BarcodeReaderServer"
else:
base_dir = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "barcode_reader_server"
return base_dir / "config.json"
return Path(__file__).resolve().parent / "config.json"
CONFIG_FILE = _resolve_config_file()
DEFAULT_CONFIG = {
"host": "0.0.0.0",
"port": 8765,
"udp_discovery_port": 8766,
"server_name": socket.gethostname(),
"pin": "", # Empty means no PIN required; or 4-digit code
"suffix": "enter", # "enter", "tab", "none" or custom string
"prefix": "",
"typing_delay": 0.005, # Delay between keystrokes in seconds
"mode": "type", # "type" or "paste"
"listening": True, # Whether the server actively processes and types barcodes
"minimize_to_tray": True, # Close/minimize button hides to system tray
"log_history": True,
"check_updates": True, # Check for app updates on startup
"update_url": "", # Optional custom release metadata URL
"language": "auto", # "auto", "it", "en"
}
def load_config() -> dict:
if CONFIG_FILE.exists():
try:
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
config = {**DEFAULT_CONFIG, **data}
if not config.get("server_name"):
config["server_name"] = socket.gethostname()
return config
except Exception as e:
print(f"Avviso: Errore nella lettura di {CONFIG_FILE}: {e}. Uso configurazione predefinita.")
return DEFAULT_CONFIG.copy()
def save_config(config: dict) -> None:
try:
CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(config, f, indent=4)
except Exception as e:
print(f"Errore nel salvataggio della configurazione: {e}")