Coverage for downtify/discovery.py: 50%

74 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Announcing the server on the local network (mDNS / DNS-SD). 

2 

3The Android app's "Found on this network" list: the server registers a 

4``_downtify._tcp`` service with a TXT record the app reads before it 

5connects - server id, name, version, API version, port and scheme - so a 

6phone on the same network finds it without anyone typing an address. 

7 

8Uses ``python-zeroconf`` (pure Python, plus its one small dependency, 

9``ifaddr``): mDNS has to answer multicast queries for as long as the 

10server runs, which is not something to hand-roll, and the alternative - 

11Avahi over D-Bus - isn't there in the Alpine image or on Windows/macOS. 

12 

13Multicast only reaches the LAN when the server is on it: in Docker's 

14default bridge network the announcement stays inside the container 

15network. ``network_mode: host`` fixes that; otherwise the app's manual 

16address entry still works. ``DOWNTIFY_DISCOVERY=false`` turns the 

17announcement off. 

18""" 

19 

20from __future__ import annotations 

21 

22import os 

23import socket 

24from typing import Any, Optional 

25 

26import ifaddr 

27from loguru import logger 

28from zeroconf import ServiceInfo 

29from zeroconf.asyncio import AsyncZeroconf 

30 

31from .server_identity import API_VERSION, ServerIdentity 

32 

33SERVICE_TYPE = '_downtify._tcp.local.' 

34 

35_VIRTUAL_PREFIXES = ('docker', 'br-', 'veth', 'virbr', 'cni', 'flannel') 

36 

37 

38def discovery_enabled() -> bool: 

39 raw = os.getenv('DOWNTIFY_DISCOVERY', '').strip().lower() 

40 return raw not in {'0', 'false', 'no', 'off'} 

41 

42 

43def instance_name(name: str) -> str: 

44 """A DNS-SD instance label for *name*: no dots, at most 63 bytes.""" 

45 

46 text = ' '.join(str(name or 'Downtify').replace('.', ' ').split()) 

47 encoded = text.encode()[:63] 

48 return encoded.decode(errors='ignore').strip() or 'Downtify' 

49 

50 

51def txt_record( 

52 identity: ServerIdentity, *, version: str, port: int, scheme: str 

53) -> dict[str, str]: 

54 """What the app reads before connecting.""" 

55 

56 return { 

57 'id': identity.server_id, 

58 'name': identity.name, 

59 'version': version, 

60 'api': str(API_VERSION), 

61 'port': str(port), 

62 'scheme': scheme, 

63 'path': '/', 

64 } 

65 

66 

67def local_addresses(host: str = '') -> list[str]: 

68 """The addresses to announce: the one the server is bound to, or - 

69 bound to all (``0.0.0.0``/``::``) - every non-loopback IPv4 address 

70 of the machine.""" 

71 

72 if host and host not in {'0.0.0.0', '::', ''}: 

73 return [host] 

74 found = [] 

75 for adapter in ifaddr.get_adapters(): 

76 # Container and VM bridges aren't where the phones are. 

77 if str(adapter.nice_name).startswith(_VIRTUAL_PREFIXES): 

78 continue 

79 for ip in adapter.ips: 

80 if ( 

81 isinstance(ip.ip, str) 

82 and not ip.ip.startswith('127.') 

83 and not ip.ip.startswith('169.254.') 

84 ): 

85 found.append(ip.ip) 

86 return sorted(set(found)) 

87 

88 

89class Announcer: 

90 """Registers (and keeps up to date) this server's mDNS service.""" 

91 

92 def __init__( 

93 self, 

94 identity: ServerIdentity, 

95 *, 

96 version: str, 

97 port: int, 

98 host: str = '', 

99 scheme: str = 'http', 

100 ) -> None: 

101 self._identity = identity 

102 self._version = version 

103 self._port = port 

104 self._host = host 

105 self._scheme = scheme 

106 self._zc: Any = None 

107 self._info: Any = None 

108 

109 def _service_info(self) -> Any: 

110 addresses = local_addresses(self._host) 

111 return ServiceInfo( 

112 SERVICE_TYPE, 

113 f'{instance_name(self._identity.name)}.{SERVICE_TYPE}', 

114 addresses=[socket.inet_aton(a) for a in addresses if '.' in a], 

115 port=self._port, 

116 properties=txt_record( 

117 self._identity, 

118 version=self._version, 

119 port=self._port, 

120 scheme=self._scheme, 

121 ), 

122 server=f'downtify-{self._identity.server_id[:8]}.local.', 

123 ) 

124 

125 async def start(self) -> bool: 

126 try: 

127 self._info = self._service_info() 

128 self._zc = AsyncZeroconf() 

129 await self._zc.async_register_service( 

130 self._info, allow_name_change=True 

131 ) 

132 except Exception: 

133 logger.opt(exception=True).warning( 

134 'LAN discovery: could not announce the server' 

135 ) 

136 await self.stop() 

137 return False 

138 logger.info( 

139 'LAN discovery: announced "{}" on port {} ({})', 

140 self._identity.name, 

141 self._port, 

142 ', '.join(local_addresses(self._host)) or 'no addresses', 

143 ) 

144 return True 

145 

146 async def update(self, _name: Optional[str] = None) -> None: 

147 """Announce again after the server was renamed.""" 

148 

149 if self._zc is None or self._info is None: 

150 return 

151 try: 

152 await self._zc.async_unregister_service(self._info) 

153 self._info = self._service_info() 

154 await self._zc.async_register_service( 

155 self._info, allow_name_change=True 

156 ) 

157 except Exception: 

158 logger.opt(exception=True).warning( 

159 'LAN discovery: could not update the announcement' 

160 ) 

161 

162 async def stop(self) -> None: 

163 if self._zc is None: 

164 return 

165 try: 

166 if self._info is not None: 

167 await self._zc.async_unregister_service(self._info) 

168 await self._zc.async_close() 

169 except Exception: 

170 logger.opt(exception=True).debug('LAN discovery: stop failed') 

171 self._zc = None 

172 self._info = None