From a313a86b8b6eb39b8836c47cc8c107058a6da6ed Mon Sep 17 00:00:00 2001 From: tituspijean Date: Tue, 21 Sep 2021 00:09:49 +0200 Subject: [PATCH] [mdns] Allow for multiple yunohost.local --- bin/yunomdns | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/bin/yunomdns b/bin/yunomdns index dfd58deee..aa0697f5f 100755 --- a/bin/yunomdns +++ b/bin/yunomdns @@ -10,7 +10,7 @@ from time import sleep from typing import List, Dict import ifaddr -from zeroconf import Zeroconf, ServiceInfo +from zeroconf import Zeroconf, ServiceInfo, ServiceBrowser def get_network_local_interfaces() -> Dict[str, Dict[str, List[str]]]: @@ -32,6 +32,23 @@ def get_network_local_interfaces() -> Dict[str, Dict[str, List[str]]]: } return interfaces +# Listener class, to detect duplicates on the network +# Stores the list of servers in its list property +class Listener: + + def __init__(self): + self.list = [] + + def remove_service(self, zeroconf, type, name): + info = zeroconf.get_service_info(type, name) + self.list.remove(info.server) + + def update_service(self, zeroconf, type, name): + pass + + def add_service(self, zeroconf, type, name): + info = zeroconf.get_service_info(type, name) + self.list.append(info.server[:-1]) def main() -> bool: ### @@ -51,8 +68,25 @@ def main() -> bool: print("No interface listed for broadcast.") return True - if "yunohost.local" not in config["domains"]: - config["domains"].append("yunohost.local") + # Let's discover currently published .local domains accross the network + zc = Zeroconf() + listener = Listener() + browser = ServiceBrowser(zc, "_device-info._tcp.local.", listener) + sleep(2) + browser.cancel() + zc.close() + # If yunohost.local already exists, try yunohost-2.local, and so on. + def yunohost_local(i): + return "yunohost.local" if i < 2 else "yunohost-"+str(i)+".local" + i=1 + while yunohost_local(i) in listener.list: + print("Uh oh, "+yunohost_local(i)+" already exists on the network...") + if yunohost_local(i) in config['domains']: + config['domains'].remove(yunohost_local(i)) + i += 1 + if yunohost_local(i) not in config['domains']: + print("Adding "+yunohost_local(i)+" to the domains to publish.") + config['domains'].append(yunohost_local(i)) zcs: Dict[Zeroconf, List[ServiceInfo]] = {}