mopidy / mopidy
1 2
import logging
2 2
import string
3

4 2
logger = logging.getLogger(__name__)
5

6 2
try:
7 2
    import dbus
8 2
except ImportError:
9 2
    dbus = None
10

11 2
_AVAHI_IF_UNSPEC = -1
12 2
_AVAHI_PROTO_UNSPEC = -1
13 2
_AVAHI_PUBLISHFLAGS_NONE = 0
14

15

16 2
def _is_loopback_address(host):
17 0
    return (
18
        host.startswith("127.")
19
        or host.startswith("::ffff:127.")
20
        or host == "::1"
21
    )
22

23

24 2
def _convert_text_list_to_dbus_format(text_list):
25 0
    array = dbus.Array(signature="ay")
26 0
    for text in text_list:
27 0
        array.append([dbus.Byte(ord(c)) for c in text])
28 0
    return array
29

30

31 2
class Zeroconf:
32

33
    """Publish a network service with Zeroconf.
34

35
    Currently, this only works on Linux using Avahi via D-Bus.
36

37
    :param str name: human readable name of the service, e.g. 'MPD on neptune'
38
    :param str stype: service type, e.g. '_mpd._tcp'
39
    :param int port: TCP port of the service, e.g. 6600
40
    :param str domain: local network domain name, defaults to ''
41
    :param str host: interface to advertise the service on, defaults to ''
42
    :param text: extra information depending on ``stype``, defaults to empty
43
        list
44
    :type text: list of str
45
    """
46

47 2
    def __init__(self, name, stype, port, domain="", host="", text=None):
48 0
        self.stype = stype
49 0
        self.port = port
50 0
        self.domain = domain
51 0
        self.host = host
52 0
        self.text = text or []
53

54 0
        self.bus = None
55 0
        self.server = None
56 0
        self.group = None
57 0
        self.display_hostname = None
58 0
        self.name = None
59

60 0
        if dbus:
61 0
            try:
62 0
                self.bus = dbus.SystemBus()
63 0
                self.server = dbus.Interface(
64
                    self.bus.get_object("org.freedesktop.Avahi", "/"),
65
                    "org.freedesktop.Avahi.Server",
66
                )
67 0
                self.display_hostname = f"{self.server.GetHostName()}"
68 0
                self.name = string.Template(name).safe_substitute(
69
                    hostname=self.display_hostname, port=port
70
                )
71 0
            except dbus.exceptions.DBusException as e:
72 0
                logger.debug("%s: Server failed: %s", self, e)
73

74 2
    def __str__(self):
75 0
        return (
76
            f"Zeroconf service {self.name!r} "
77
            f"({self.stype} at [{self.host}]:{self.port:d})"
78
        )
79

80 2
    def publish(self):
81
        """Publish the service.
82

83
        Call when your service starts.
84
        """
85

86 0
        if _is_loopback_address(self.host):
87 0
            logger.debug(
88
                "%s: Publish on loopback interface is not supported.", self
89
            )
90 0
            return False
91

92 0
        if not dbus:
93 0
            logger.debug("%s: dbus not installed; publish failed.", self)
94 0
            return False
95

96 0
        if not self.bus:
97 0
            logger.debug("%s: Bus not available; publish failed.", self)
98 0
            return False
99

100 0
        if not self.server:
101 0
            logger.debug("%s: Server not available; publish failed.", self)
102 0
            return False
103

104 0
        try:
105 0
            if not self.bus.name_has_owner("org.freedesktop.Avahi"):
106 0
                logger.debug(
107
                    "%s: Avahi service not running; publish failed.", self
108
                )
109 0
                return False
110

111 0
            self.group = dbus.Interface(
112
                self.bus.get_object(
113
                    "org.freedesktop.Avahi", self.server.EntryGroupNew()
114
                ),
115
                "org.freedesktop.Avahi.EntryGroup",
116
            )
117

118 0
            self.group.AddService(
119
                _AVAHI_IF_UNSPEC,
120
                _AVAHI_PROTO_UNSPEC,
121
                dbus.UInt32(_AVAHI_PUBLISHFLAGS_NONE),
122
                self.name,
123
                self.stype,
124
                self.domain,
125
                self.host,
126
                dbus.UInt16(self.port),
127
                _convert_text_list_to_dbus_format(self.text),
128
            )
129

130 0
            self.group.Commit()
131 0
            logger.debug("%s: Published", self)
132 0
            return True
133 0
        except dbus.exceptions.DBusException as e:
134 0
            logger.debug("%s: Publish failed: %s", self, e)
135 0
            return False
136

137 2
    def unpublish(self):
138
        """Unpublish the service.
139

140
        Call when your service shuts down.
141
        """
142

143 0
        if self.group:
144 0
            try:
145 0
                self.group.Reset()
146 0
                logger.debug("%s: Unpublished", self)
147 0
            except dbus.exceptions.DBusException as e:
148 0
                logger.debug("%s: Unpublish failed: %s", self, e)
149
            finally:
150 0
                self.group = None

Read our documentation on viewing source code .

Loading