|
| 1 | +import os, json |
| 2 | +from typing import Dict |
1 | 3 | from os import environ, getenv |
2 | 4 |
|
3 | 5 | from wyzebridge.build_config import BUILD_STR |
|
23 | 25 |
|
24 | 26 | # TODO: change TOKEN_PATH to /config for all: |
25 | 27 | TOKEN_PATH: str = "/config/" if HASS_TOKEN else "/tokens/" |
| 28 | +IP_OVERRIDES_FILE = os.path.join(TOKEN_PATH, "ip_overrides.json") |
26 | 29 | IMG_PATH: str = f'/{env_bool("IMG_DIR", r"/media/wyze/img").strip("/")}/' |
27 | 30 |
|
28 | 31 | LATITUDE: float = float(getenv("LATITUDE", "0")) |
|
93 | 96 | print(f"\n[!] WARNING: In {BUILD_STR}, {key} is deprecated! Please use {new_key} instead\n") |
94 | 97 | environ.pop(key, None) |
95 | 98 | environ[new_key] = value |
| 99 | + |
| 100 | + |
| 101 | +def _parse_overrides_text(text: str) -> Dict[str, str]: |
| 102 | + """Accept nickname:ip or nickname=ip, separated by newlines/commas/semicolons.""" |
| 103 | + mapping: Dict[str, str] = {} |
| 104 | + if not text: |
| 105 | + return mapping |
| 106 | + text = text.replace(",", "\n").replace(";", "\n") |
| 107 | + for line in text.splitlines(): |
| 108 | + line = line.strip() |
| 109 | + if not line: |
| 110 | + continue |
| 111 | + if ":" in line: |
| 112 | + k, v = line.split(":", 1) |
| 113 | + elif "=" in line: |
| 114 | + k, v = line.split("=", 1) |
| 115 | + else: |
| 116 | + continue |
| 117 | + k, v = k.strip(), v.strip() |
| 118 | + if k and v: |
| 119 | + mapping[k] = v |
| 120 | + return mapping |
| 121 | + |
| 122 | +def load_ip_overrides() -> Dict[str, str]: |
| 123 | + """ |
| 124 | + Return merged {nickname: ip} from file + env (env wins). |
| 125 | + - File path: /config/ip_overrides.json (if present) |
| 126 | + - Env var : WB_IP_OVERRIDES (from HA add-on Configuration) |
| 127 | + """ |
| 128 | + file_map: Dict[str, str] = {} |
| 129 | + try: |
| 130 | + with open(IP_OVERRIDES_FILE, "r", encoding="utf-8") as f: |
| 131 | + raw = json.load(f) |
| 132 | + file_map = {str(k).strip(): str(v).strip() for k, v in raw.items()} |
| 133 | + except Exception: |
| 134 | + file_map = {} |
| 135 | + |
| 136 | + env_map = _parse_overrides_text(os.getenv("WB_IP_OVERRIDES", "")) |
| 137 | + return {**file_map, **env_map} |
| 138 | + |
| 139 | +def save_ip_overrides(mapping: Dict[str, str]) -> bool: |
| 140 | + """Persist overrides from any UI path that writes to disk.""" |
| 141 | + try: |
| 142 | + os.makedirs(TOKEN_PATH, exist_ok=True) |
| 143 | + with open(IP_OVERRIDES_FILE, "w", encoding="utf-8") as f: |
| 144 | + json.dump(mapping, f, indent=2, ensure_ascii=False) |
| 145 | + return True |
| 146 | + except Exception: |
| 147 | + return False |
0 commit comments