webcam: improve default host handling

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
This commit is contained in:
Eric Callahan 2022-08-27 08:19:03 -04:00
parent e8999363ed
commit b52b0bd98a
No known key found for this signature in database
GPG Key ID: 5A1EB336DFB4C71B
1 changed files with 20 additions and 5 deletions

View File

@ -58,14 +58,14 @@ class WebcamManager:
"/server/webcams/test", ["POST"], self._handle_webcam_test
)
self.server.register_notification("webcam:webcams_changed")
self.server.register_event_handler(
"machine:public_ip_changed", self._set_default_host_ip
)
async def component_init(self) -> None:
machine: Machine = self.server.lookup_component("machine")
pubnet = await machine.get_public_network()
ip: Optional[str] = pubnet.get("address")
if ip:
default_host = f"http://{ip}"
WebCam.set_default_host(default_host)
if machine.public_ip:
self._set_default_host_ip(machine.public_ip)
db: MoonrakerDatabase = self.server.lookup_component("database")
saved_cams: Dict[str, Any] = await db.get_item("webcams", default={})
for cam_data in saved_cams.values():
@ -78,6 +78,21 @@ class WebcamManager:
logging.exception("Failed to process webcam from db")
continue
def _set_default_host_ip(self, ip: str) -> None:
default_host = "http://127.0.0.1"
if ip:
try:
addr = ipaddress.ip_address(ip)
except Exception:
logging.debug(f"Invalid IP Recd: {ip}")
else:
if addr.version == 6:
default_host = f"http://[{addr}]"
else:
default_host = f"http://{addr}"
WebCam.set_default_host(default_host)
logging.info(f"Default public webcam address set: {default_host}")
def get_webcams(self) -> Dict[str, WebCam]:
return self.webcams