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