using Makaretu.Dns; namespace VideoDownloader.Server; /// /// mDNS 서비스 광고(_videodl._tcp) — MOBILE_PLAN §3 아키텍처. /// QR 페어링이 주 경로이고 광고는 발견 보조이므로, 멀티캐스트가 막힌 네트워크에서의 /// 실패는 서버 기동을 막지 않는다(ServerHost 가 MdnsError 로 드러냄). /// public sealed class MdnsAdvertiser : IDisposable { public const string ServiceType = "_videodl._tcp"; private readonly ServiceProfile _profile; private ServiceDiscovery? _sd; public MdnsAdvertiser(string deviceName, int port) => _profile = BuildProfile(deviceName, (ushort)port); /// /// 광고 프로필 구성(순수 로직). 점은 DNS 라벨 구분자와 충돌하므로 대시로 정리. /// Makaretu WireWriter 가 TXT/라벨에 ASCII 만 허용 → 기기명은 퍼센트 인코딩으로 무손실 보존, /// 인스턴스 라벨은 ASCII 로 접는다(클라이언트는 TXT device 를 디코드해 표시). /// public static ServiceProfile BuildProfile(string deviceName, ushort port) { var display = string.IsNullOrWhiteSpace(deviceName) ? "VideoDownloader" : deviceName.Trim(); var profile = new ServiceProfile(ToAsciiLabel(display), ServiceType, port); profile.AddProperty("device", Uri.EscapeDataString(display)); return profile; } private static string ToAsciiLabel(string s) { var label = new string(s.Replace('.', '-').Where(c => c >= ' ' && c < (char)0x7f).ToArray()).Trim(); return label.Length == 0 ? "VideoDownloader" : label; } /// 광고 시작. 멀티캐스트 소켓 실패는 그대로 던진다(호출측이 보조 기능으로 취급). public void Start() { _sd ??= new ServiceDiscovery(); _sd.Advertise(_profile); } public void Dispose() { if (_sd == null) return; try { _sd.Unadvertise(); // goodbye 패킷은 규격상 best-effort — 네트워크가 이미 죽었으면 보낼 수 없다 } catch (Exception ex) when (ex is System.Net.Sockets.SocketException or ObjectDisposedException) { } _sd.Dispose(); _sd = null; } }