]> git.meshlink.io Git - catta/blob - avahi-python/avahi-discover/avahi-discover.in
ac6b65783332b3d372f79d3951450ef2b0a1246c
[catta] / avahi-python / avahi-discover / avahi-discover.in
1 #!@PYTHON@
2 # -*-python-*-
3 # This file is part of avahi.
4 #
5 # avahi is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation; either version 2 of the
8 # License, or (at your option) any later version.
9 #
10 # avahi is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
13 # License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with avahi; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18 # USA.
19
20 import os, sys
21
22 try:
23     import avahi, gettext, gtk, gobject, dbus, avahi.ServiceTypeDatabase
24     _ = gettext.gettext
25 except ImportError, e:
26     print "Sorry, to use this tool you need to install Avahi, pygtk and python-dbus.\n Error: %s" % e
27     sys.exit(1)
28 except Exception, e:
29     print "Failed to initialize: %s" % e
30     sys.exit(1)
31
32
33 ## !!NOTE!! ##
34 # It's really important to do this, else you won't see any events
35 ##
36 try:
37     from dbus import DBusException
38     import dbus.glib
39 except ImportError, e:
40     pass
41
42 service_type_browsers = {}
43 service_browsers = {}
44
45 def error_msg(msg):
46     d = gtk.MessageDialog(parent=None, flags=gtk.DIALOG_MODAL,
47                           type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK)
48     d.set_markup(msg)
49     d.show_all()
50     d.run()
51     d.destroy()
52
53 ui_dir = "@interfacesdir@"
54
55 service_type_db = avahi.ServiceTypeDatabase.ServiceTypeDatabase()
56
57 class Main_window:
58     def __init__(self, path="avahi-discover.ui", root="main_window", domain=None, **kwargs):
59         path = os.path.join(ui_dir, path)
60         gtk.window_set_default_icon_name("network-wired")
61         self.ui = gtk.Builder()
62         self.ui.add_from_file(path)
63         self.ui.connect_signals(self)
64         self.tree_view = self.ui.get_object("tree_view")
65         self.info_label = self.ui.get_object("info_label")
66         self.new()
67
68     def on_tree_view_cursor_changed(self, widget, *args):
69         (model, iter) = widget.get_selection().get_selected()
70         stype = None
71         if iter is not None:
72             (name,interface,protocol,stype,domain) = self.treemodel.get(iter,1,2,3,4,5)
73         if stype == None:
74             self.info_label.set_markup("<i>No service currently selected.</i>")
75             return
76         #Asynchronous resolving
77         self.server.ResolveService( int(interface), int(protocol), name, stype, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0), reply_handler=self.service_resolved, error_handler=self.print_error)
78
79     def protoname(self,protocol):
80         if protocol == avahi.PROTO_INET:
81             return "IPv4"
82         if protocol == avahi.PROTO_INET6:
83             return "IPv6"
84         return "n/a"
85
86     def siocgifname(self, interface):
87         if interface <= 0:
88             return "n/a"
89         else:
90             return self.server.GetNetworkInterfaceNameByIndex(interface)
91
92     def get_interface_name(self, interface, protocol):
93         if interface == avahi.IF_UNSPEC and protocol == avahi.PROTO_UNSPEC:
94             return "Wide Area"
95         else:
96             return str(self.siocgifname(interface)) + " " + str(self.protoname(protocol))
97
98     def service_resolved(self, interface, protocol, name, stype, domain, host, aprotocol, address, port, txt, flags):
99         print "Service data for service '%s' of type '%s' in domain '%s' on %i.%i:" % (name, stype, domain, interface, protocol)
100
101         print "\tHost %s (%s), port %i, TXT data: %s" % (host, address, port, str(avahi.txt_array_to_string_array(txt)))
102
103         self.update_label(interface, protocol, name, stype, domain, host, aprotocol, address, port, avahi.txt_array_to_string_array(txt))
104
105     def print_error(self, err):
106         error_label = "<b>Error:</b> %s" % (err)
107         self.info_label.set_markup(error_label)
108         print "Error:", str(err)
109
110     def lookup_type(self, stype):
111         global service_type_db
112
113         try:
114             return service_type_db[stype]
115         except KeyError:
116             return stype
117
118     def new_service(self, interface, protocol, name, stype, domain, flags):
119         print "Found service '%s' of type '%s' in domain '%s' on %i.%i." % (name, stype, domain, interface, protocol)
120         if self.zc_ifaces.has_key((interface,protocol)) == False:
121
122             ifn = self.get_interface_name(interface, protocol)
123
124             self.zc_ifaces[(interface,protocol)] = self.insert_row(self.treemodel, None, ifn, None,interface,protocol,None,domain)
125         if self.zc_domains.has_key((interface,protocol,domain)) == False:
126             self.zc_domains[(interface,protocol,domain)] = self.insert_row(self.treemodel, self.zc_ifaces[(interface,protocol)], domain,None,interface,protocol,None,domain)
127         if self.zc_types.has_key((interface,protocol,stype,domain)) == False:
128             thisDomain = self.zc_domains[(interface,protocol,domain)]
129             self.zc_types[(interface,protocol,stype,domain)] = self.insert_row(self.treemodel, thisDomain, self.lookup_type(stype), name, interface,None,None,None)
130         treeiter = self.insert_row(self.treemodel,self.zc_types[(interface,protocol,stype,domain)], name, name, interface,protocol,stype,domain)
131         self.services_browsed[(interface, protocol, name, stype, domain)] = treeiter
132         # expand the tree of this path
133         self.tree_view.expand_to_path(self.treemodel.get_path(treeiter))
134
135     def remove_service(self, interface, protocol, name, stype, domain, flags):
136         print "Service '%s' of type '%s' in domain '%s' on %i.%i disappeared." % (name, stype, domain, interface, protocol)
137         self.info_label.set_markup("")
138         treeiter=self.services_browsed[(interface, protocol, name, stype, domain)]
139         parent = self.treemodel.iter_parent(treeiter)
140         self.treemodel.remove(treeiter)
141         del self.services_browsed[(interface, protocol, name, stype, domain)]
142         if self.treemodel.iter_has_child(parent) == False:
143             treeiter=self.zc_types[(interface,protocol,stype,domain)]
144             parent = self.treemodel.iter_parent(treeiter)
145             self.treemodel.remove(treeiter)
146             del self.zc_types[(interface,protocol,stype,domain)]
147             if self.treemodel.iter_has_child(parent) == False:
148                 treeiter=self.zc_domains[(interface,protocol,domain)]
149                 parent = self.treemodel.iter_parent(treeiter)
150                 self.treemodel.remove(treeiter)
151                 del self.zc_domains[(interface,protocol,domain)]
152                 if self.treemodel.iter_has_child(parent) == False:
153                     treeiter=self.zc_ifaces[(interface,protocol)]
154                     parent = self.treemodel.iter_parent(treeiter)
155                     self.treemodel.remove(treeiter)
156                     del self.zc_ifaces[(interface,protocol)]
157
158     def new_service_type(self, interface, protocol, stype, domain, flags):
159         global service_browsers
160
161         # Are we already browsing this domain for this type?
162         if service_browsers.has_key((interface, protocol, stype, domain)):
163             return
164
165         print "Browsing for services of type '%s' in domain '%s' on %i.%i ..." % (stype, domain, interface, protocol)
166
167         b = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.ServiceBrowserNew(interface, protocol, stype, domain, dbus.UInt32(0))),  avahi.DBUS_INTERFACE_SERVICE_BROWSER)
168         b.connect_to_signal('ItemNew', self.new_service)
169         b.connect_to_signal('ItemRemove', self.remove_service)
170
171         service_browsers[(interface, protocol, stype, domain)] = b
172
173     def browse_domain(self, interface, protocol, domain):
174         global service_type_browsers
175
176         # Are we already browsing this domain?
177         if service_type_browsers.has_key((interface, protocol, domain)):
178             return
179
180         if self.stype is None:
181             print "Browsing domain '%s' on %i.%i ..." % (domain, interface, protocol)
182
183             try:
184                 b = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.ServiceTypeBrowserNew(interface, protocol, domain, dbus.UInt32(0))),  avahi.DBUS_INTERFACE_SERVICE_TYPE_BROWSER)
185             except DBusException, e:
186                 print e
187                 error_msg("You should check that the avahi daemon is running.\n\nError : %s" % e)
188                 sys.exit(0)
189
190             b.connect_to_signal('ItemNew', self.new_service_type)
191
192             service_type_browsers[(interface, protocol, domain)] = b
193         else:
194             new_service_type(interface, protocol, stype, domain)
195
196     def new_domain(self,interface, protocol, domain, flags):
197         if self.zc_ifaces.has_key((interface,protocol)) == False:
198             ifn = self.get_interface_name(interface, protocol)
199             self.zc_ifaces[(interface,protocol)] = self.insert_row(self.treemodel, None, ifn,None,interface,protocol,None,domain)
200         if self.zc_domains.has_key((interface,protocol,domain)) == False:
201             self.zc_domains[(interface,protocol,domain)] = self.insert_row(self.treemodel, self.zc_ifaces[(interface,protocol)], domain,None,interface,protocol,None,domain)
202         if domain != "local":
203             self.browse_domain(interface, protocol, domain)
204
205     def pair_to_dict(self, l):
206         res = dict()
207         for el in l:
208             if "=" not in el:
209                 res[el]=''
210             else:
211                 tmp = el.split('=',1)
212                 if len(tmp[0]) > 0:
213                     res[tmp[0]] = tmp[1]
214         return res
215
216
217     def update_label(self,interface, protocol, name, stype, domain, host, aprotocol, address, port, txt):
218         if len(txt) != 0:
219             txts = ""
220             txtd = self.pair_to_dict(txt)
221             for k,v in txtd.items():
222                 txts+="<b>TXT <i>%s</i></b> = %s\n" % (k,v)
223         else:
224             txts = "<b>TXT Data:</b> <i>empty</i>"
225
226         infos = "<b>Service Type:</b> %s\n<b>Service Name:</b> %s\n<b>Domain Name:</b> %s\n<b>Interface:</b> %s %s\n<b>Address:</b> %s/%s:%i\n%s" % (stype, name, domain, self.siocgifname(interface), self.protoname(protocol), host, address, port, txts.strip())
227         self.info_label.set_markup(infos)
228
229     def insert_row(self, model,parent,
230                    content, name, interface,protocol,stype,domain):
231         myiter=model.insert_after(parent,None)
232         model.set(myiter,0,content,1,name,2,interface,3,protocol,4,stype,5,domain)
233         return myiter
234
235     def new(self):
236         self.treemodel=gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
237         self.tree_view.set_model(self.treemodel)
238
239         #creating the columns headers
240         self.tree_view.set_headers_visible(False)
241         renderer=gtk.CellRendererText()
242         column=gtk.TreeViewColumn("",renderer, text=0)
243         column.set_resizable(True)
244         column.set_sizing("GTK_TREE_VIEW_COLUMN_GROW_ONLY");
245         column.set_expand(True);
246         self.tree_view.append_column(column)
247
248         self.domain = None
249         self.stype = None
250         self.zc_ifaces = {}
251         self.zc_domains = {}
252         self.zc_types = {}
253         self.services_browsed = {}
254
255         try:
256             self.bus = dbus.SystemBus()
257             self.server = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER)
258         except Exception, e:
259             print "Failed to connect to Avahi Server (Is it running?): %s" % e
260             sys.exit(1)
261
262         if self.domain is None:
263             # Explicitly browse .local
264             self.browse_domain(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, "local")
265
266             # Browse for other browsable domains
267             db = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.DomainBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, "", avahi.DOMAIN_BROWSER_BROWSE, dbus.UInt32(0))), avahi.DBUS_INTERFACE_DOMAIN_BROWSER)
268             db.connect_to_signal('ItemNew', self.new_domain)
269         else:
270             # Just browse the domain the user wants us to browse
271             self.browse_domain(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, domain)
272
273     def gtk_main_quit(self, *args):
274         gtk.main_quit()
275
276 def main():
277     main_window = Main_window()
278     gtk.main()
279
280 if __name__ == "__main__":
281     main()