Changed all tabs to 4 spaces for python style

This commit is contained in:
Justin Gallardo
2006-12-04 11:12:24 -08:00
parent f5ae066248
commit b9f9ef0fe9
110 changed files with 9987 additions and 9987 deletions
+41 -41
View File
@@ -24,53 +24,53 @@ from sugar import env
class ClipboardDBusServiceHelper(dbus.service.Object):
_CLIPBOARD_DBUS_INTERFACE = "org.laptop.Clipboard"
_CLIPBOARD_OBJECT_PATH = "/org/laptop/Clipboard"
_CLIPBOARD_DBUS_INTERFACE = "org.laptop.Clipboard"
_CLIPBOARD_OBJECT_PATH = "/org/laptop/Clipboard"
def __init__(self, parent):
self._parent = parent
def __init__(self, parent):
self._parent = parent
bus = dbus.SessionBus()
bus_name = dbus.service.BusName(self._CLIPBOARD_DBUS_INTERFACE, bus=bus)
dbus.service.Object.__init__(self, bus_name, self._CLIPBOARD_OBJECT_PATH)
@dbus.service.method(_CLIPBOARD_DBUS_INTERFACE,
in_signature="sss", out_signature="")
def add_object(self, name, mimeType, fileName):
self.object_added(name, mimeType, fileName)
logging.debug('Added object of type ' + mimeType + ' with path at ' + fileName)
bus = dbus.SessionBus()
bus_name = dbus.service.BusName(self._CLIPBOARD_DBUS_INTERFACE, bus=bus)
dbus.service.Object.__init__(self, bus_name, self._CLIPBOARD_OBJECT_PATH)
@dbus.service.method(_CLIPBOARD_DBUS_INTERFACE,
in_signature="sss", out_signature="")
def add_object(self, name, mimeType, fileName):
self.object_added(name, mimeType, fileName)
logging.debug('Added object of type ' + mimeType + ' with path at ' + fileName)
@dbus.service.method(_CLIPBOARD_DBUS_INTERFACE,
in_signature="s", out_signature="")
def delete_object(self, fileName):
self.object_deleted(fileName)
logging.debug('Deleted object with path at ' + fileName)
@dbus.service.method(_CLIPBOARD_DBUS_INTERFACE,
in_signature="si", out_signature="")
def set_object_state(self, fileName, percent):
logging.debug('Changed object with path at ' + fileName + ' with percent ' + str(percent))
self.object_state_changed(fileName, percent)
@dbus.service.method(_CLIPBOARD_DBUS_INTERFACE,
in_signature="s", out_signature="")
def delete_object(self, fileName):
self.object_deleted(fileName)
logging.debug('Deleted object with path at ' + fileName)
@dbus.service.method(_CLIPBOARD_DBUS_INTERFACE,
in_signature="si", out_signature="")
def set_object_state(self, fileName, percent):
logging.debug('Changed object with path at ' + fileName + ' with percent ' + str(percent))
self.object_state_changed(fileName, percent)
@dbus.service.signal(_CLIPBOARD_DBUS_INTERFACE, signature="sss")
def object_added(self, name, mimeType, fileName):
pass
@dbus.service.signal(_CLIPBOARD_DBUS_INTERFACE, signature="sss")
def object_added(self, name, mimeType, fileName):
pass
@dbus.service.signal(_CLIPBOARD_DBUS_INTERFACE, signature="s")
def object_deleted(self, fileName):
pass
@dbus.service.signal(_CLIPBOARD_DBUS_INTERFACE, signature="s")
def object_deleted(self, fileName):
pass
@dbus.service.signal(_CLIPBOARD_DBUS_INTERFACE, signature="si")
def object_state_changed(self, fileName, percent):
pass
@dbus.service.signal(_CLIPBOARD_DBUS_INTERFACE, signature="si")
def object_state_changed(self, fileName, percent):
pass
class ClipboardService(object):
def __init__(self):
self._dbus_helper = ClipboardDBusServiceHelper(self)
def __init__(self):
self._dbus_helper = ClipboardDBusServiceHelper(self)
def run(self):
loop = gobject.MainLoop()
try:
loop.run()
except KeyboardInterrupt:
print 'Ctrl+C pressed, exiting...'
def run(self):
loop = gobject.MainLoop()
try:
loop.run()
except KeyboardInterrupt:
print 'Ctrl+C pressed, exiting...'
+92 -92
View File
@@ -22,111 +22,111 @@ import gtk
import hippo
class Bubble(hippo.CanvasBox, hippo.CanvasItem):
__gtype_name__ = 'NetworkBubble'
__gtype_name__ = 'NetworkBubble'
__gproperties__ = {
'fill-color': (object, None, None,
gobject.PARAM_READWRITE),
'stroke-color': (object, None, None,
gobject.PARAM_READWRITE),
'progress-color': (object, None, None,
gobject.PARAM_READWRITE),
'percent' : (object, None, None,
gobject.PARAM_READWRITE),
}
__gproperties__ = {
'fill-color': (object, None, None,
gobject.PARAM_READWRITE),
'stroke-color': (object, None, None,
gobject.PARAM_READWRITE),
'progress-color': (object, None, None,
gobject.PARAM_READWRITE),
'percent' : (object, None, None,
gobject.PARAM_READWRITE),
}
def __init__(self, **kwargs):
self._stroke_color = 0xFFFFFFFF
self._fill_color = 0xFFFFFFFF
self._progress_color = 0x000000FF
self._percent = 0
self._radius = 8
def __init__(self, **kwargs):
self._stroke_color = 0xFFFFFFFF
self._fill_color = 0xFFFFFFFF
self._progress_color = 0x000000FF
self._percent = 0
self._radius = 8
hippo.CanvasBox.__init__(self, **kwargs)
hippo.CanvasBox.__init__(self, **kwargs)
def do_set_property(self, pspec, value):
if pspec.name == 'fill-color':
self._fill_color = value
self.emit_paint_needed(0, 0, -1, -1)
elif pspec.name == 'stroke-color':
self._stroke_color = value
self.emit_paint_needed(0, 0, -1, -1)
elif pspec.name == 'progress-color':
self._progress_color = value
self.emit_paint_needed(0, 0, -1, -1)
elif pspec.name == 'percent':
self._percent = value
self.emit_paint_needed(0, 0, -1, -1)
def do_set_property(self, pspec, value):
if pspec.name == 'fill-color':
self._fill_color = value
self.emit_paint_needed(0, 0, -1, -1)
elif pspec.name == 'stroke-color':
self._stroke_color = value
self.emit_paint_needed(0, 0, -1, -1)
elif pspec.name == 'progress-color':
self._progress_color = value
self.emit_paint_needed(0, 0, -1, -1)
elif pspec.name == 'percent':
self._percent = value
self.emit_paint_needed(0, 0, -1, -1)
def do_get_property(self, pspec):
if pspec.name == 'fill-color':
return self._fill_color
elif pspec.name == 'stroke-color':
return self._stroke_color
elif pspec.name == 'progress-color':
return self._progress_color
elif pspec.name == 'percent':
return self._percent
def do_get_property(self, pspec):
if pspec.name == 'fill-color':
return self._fill_color
elif pspec.name == 'stroke-color':
return self._stroke_color
elif pspec.name == 'progress-color':
return self._progress_color
elif pspec.name == 'percent':
return self._percent
def _int_to_rgb(self, int_color):
red = (int_color >> 24) & 0x000000FF
green = (int_color >> 16) & 0x000000FF
blue = (int_color >> 8) & 0x000000FF
alpha = int_color & 0x000000FF
return (red / 255.0, green / 255.0, blue / 255.0)
def _int_to_rgb(self, int_color):
red = (int_color >> 24) & 0x000000FF
green = (int_color >> 16) & 0x000000FF
blue = (int_color >> 8) & 0x000000FF
alpha = int_color & 0x000000FF
return (red / 255.0, green / 255.0, blue / 255.0)
def do_paint_below_children(self, cr, damaged_box):
[width, height] = self.get_allocation()
def do_paint_below_children(self, cr, damaged_box):
[width, height] = self.get_allocation()
line_width = 3.0
x = line_width
y = line_width
width -= line_width * 2
height -= line_width * 2
line_width = 3.0
x = line_width
y = line_width
width -= line_width * 2
height -= line_width * 2
cr.move_to(x + self._radius, y);
cr.arc(x + width - self._radius, y + self._radius,
self._radius, math.pi * 1.5, math.pi * 2);
cr.arc(x + width - self._radius, x + height - self._radius,
self._radius, 0, math.pi * 0.5);
cr.arc(x + self._radius, y + height - self._radius,
self._radius, math.pi * 0.5, math.pi);
cr.arc(x + self._radius, y + self._radius, self._radius,
math.pi, math.pi * 1.5);
cr.move_to(x + self._radius, y);
cr.arc(x + width - self._radius, y + self._radius,
self._radius, math.pi * 1.5, math.pi * 2);
cr.arc(x + width - self._radius, x + height - self._radius,
self._radius, 0, math.pi * 0.5);
cr.arc(x + self._radius, y + height - self._radius,
self._radius, math.pi * 0.5, math.pi);
cr.arc(x + self._radius, y + self._radius, self._radius,
math.pi, math.pi * 1.5);
color = self._int_to_rgb(self._fill_color)
cr.set_source_rgb(*color)
cr.fill_preserve();
color = self._int_to_rgb(self._fill_color)
cr.set_source_rgb(*color)
cr.fill_preserve();
color = self._int_to_rgb(self._stroke_color)
cr.set_source_rgb(*color)
cr.set_line_width(line_width)
cr.stroke();
color = self._int_to_rgb(self._stroke_color)
cr.set_source_rgb(*color)
cr.set_line_width(line_width)
cr.stroke();
if self._percent > 0:
self._paint_progress_bar(cr, x, y, width, height, line_width)
if self._percent > 0:
self._paint_progress_bar(cr, x, y, width, height, line_width)
def _paint_progress_bar(self, cr, x, y, width, height, line_width):
prog_x = x + line_width
prog_y = y + line_width
prog_width = (width - (line_width * 2)) * (self._percent / 100.0)
prog_height = (height - (line_width * 2))
def _paint_progress_bar(self, cr, x, y, width, height, line_width):
prog_x = x + line_width
prog_y = y + line_width
prog_width = (width - (line_width * 2)) * (self._percent / 100.0)
prog_height = (height - (line_width * 2))
x = prog_x
y = prog_y
width = prog_width
height = prog_height
x = prog_x
y = prog_y
width = prog_width
height = prog_height
cr.move_to(x + self._radius, y);
cr.arc(x + width - self._radius, y + self._radius,
self._radius, math.pi * 1.5, math.pi * 2);
cr.arc(x + width - self._radius, x + height - self._radius,
self._radius, 0, math.pi * 0.5);
cr.arc(x + self._radius, y + height - self._radius,
self._radius, math.pi * 0.5, math.pi);
cr.arc(x + self._radius, y + self._radius, self._radius,
math.pi, math.pi * 1.5);
cr.move_to(x + self._radius, y);
cr.arc(x + width - self._radius, y + self._radius,
self._radius, math.pi * 1.5, math.pi * 2);
cr.arc(x + width - self._radius, x + height - self._radius,
self._radius, 0, math.pi * 0.5);
cr.arc(x + self._radius, y + height - self._radius,
self._radius, math.pi * 0.5, math.pi);
cr.arc(x + self._radius, y + self._radius, self._radius,
math.pi, math.pi * 1.5);
color = self._int_to_rgb(self._progress_color)
cr.set_source_rgb(*color)
cr.fill_preserve();
color = self._int_to_rgb(self._progress_color)
cr.set_source_rgb(*color)
cr.fill_preserve();
+750 -750
View File
File diff suppressed because it is too large Load Diff
+345 -345
View File
@@ -26,65 +26,65 @@ import logging
import nmclient
try:
from sugar import env
from sugar import env
except ImportError:
pass
pass
NM_INFO_IFACE='org.freedesktop.NetworkManagerInfo'
NM_INFO_PATH='/org/freedesktop/NetworkManagerInfo'
class NoNetworks(dbus.DBusException):
def __init__(self):
dbus.DBusException.__init__(self)
self._dbus_error_name = NM_INFO_IFACE + '.NoNetworks'
def __init__(self):
dbus.DBusException.__init__(self)
self._dbus_error_name = NM_INFO_IFACE + '.NoNetworks'
class CanceledKeyRequestError(dbus.DBusException):
def __init__(self):
dbus.DBusException.__init__(self)
self._dbus_error_name = NM_INFO_IFACE + '.CanceledError'
def __init__(self):
dbus.DBusException.__init__(self)
self._dbus_error_name = NM_INFO_IFACE + '.CanceledError'
class NetworkInvalidError(Exception):
pass
pass
class NMConfig(ConfigParser.ConfigParser):
def get_bool(self, section, name):
opt = self.get(section, name)
if type(opt) == type(""):
if opt.lower() == 'yes' or opt.lower() == 'true':
return True
elif opt.lower() == 'no' or opt.lower() == 'false':
return False
raise ValueError("Invalid format for %s/%s. Should be one of [yes, no, true, false]." % (section, name))
def get_bool(self, section, name):
opt = self.get(section, name)
if type(opt) == type(""):
if opt.lower() == 'yes' or opt.lower() == 'true':
return True
elif opt.lower() == 'no' or opt.lower() == 'false':
return False
raise ValueError("Invalid format for %s/%s. Should be one of [yes, no, true, false]." % (section, name))
def get_list(self, section, name):
opt = self.get(section, name)
if type(opt) == type(""):
if not len(opt):
return []
try:
return opt.split()
except Exception:
pass
raise ValueError("Invalid format for %s/%s. Should be a space-separate list." % (section, name))
def get_list(self, section, name):
opt = self.get(section, name)
if type(opt) == type(""):
if not len(opt):
return []
try:
return opt.split()
except Exception:
pass
raise ValueError("Invalid format for %s/%s. Should be a space-separate list." % (section, name))
def get_int(self, section, name):
opt = self.get(section, name)
try:
return int(opt)
except Exception:
pass
raise ValueError("Invalid format for %s/%s. Should be a valid integer." % (section, name))
def get_int(self, section, name):
opt = self.get(section, name)
try:
return int(opt)
except Exception:
pass
raise ValueError("Invalid format for %s/%s. Should be a valid integer." % (section, name))
def get_float(self, section, name):
opt = self.get(section, name)
try:
return float(opt)
except Exception:
pass
raise ValueError("Invalid format for %s/%s. Should be a valid float." % (section, name))
def get_float(self, section, name):
opt = self.get(section, name)
try:
return float(opt)
except Exception:
pass
raise ValueError("Invalid format for %s/%s. Should be a valid float." % (section, name))
IW_AUTH_CIPHER_NONE = 0x00000001
@@ -102,366 +102,366 @@ NETWORK_TYPE_INVALID = 2
class Security(object):
def __init__(self, we_cipher):
self._we_cipher = we_cipher
def __init__(self, we_cipher):
self._we_cipher = we_cipher
def read_from_config(self, cfg, name):
pass
def read_from_config(self, cfg, name):
pass
def read_from_args(self, args):
pass
def read_from_args(self, args):
pass
def new_from_config(cfg, name):
security = None
try:
we_cipher = cfg.get_int(name, "we_cipher")
if we_cipher == IW_AUTH_CIPHER_NONE:
security = Security(we_cipher)
elif we_cipher == IW_AUTH_CIPHER_WEP40 or we_cipher == IW_AUTH_CIPHER_WEP104:
security = WEPSecurity(we_cipher)
else:
# FIXME: find a way to make WPA config option matrix not
# make you want to throw up
raise ValueError("Unsupported security combo")
security.read_from_config(cfg, name)
except (ConfigParser.NoOptionError, ValueError), e:
return None
return security
new_from_config = staticmethod(new_from_config)
def new_from_config(cfg, name):
security = None
try:
we_cipher = cfg.get_int(name, "we_cipher")
if we_cipher == IW_AUTH_CIPHER_NONE:
security = Security(we_cipher)
elif we_cipher == IW_AUTH_CIPHER_WEP40 or we_cipher == IW_AUTH_CIPHER_WEP104:
security = WEPSecurity(we_cipher)
else:
# FIXME: find a way to make WPA config option matrix not
# make you want to throw up
raise ValueError("Unsupported security combo")
security.read_from_config(cfg, name)
except (ConfigParser.NoOptionError, ValueError), e:
return None
return security
new_from_config = staticmethod(new_from_config)
def new_from_args(we_cipher, args):
security = None
try:
if we_cipher == IW_AUTH_CIPHER_NONE:
security = Security(we_cipher)
elif we_cipher == IW_AUTH_CIPHER_WEP40 or we_cipher == IW_AUTH_CIPHER_WEP104:
security = WEPSecurity(we_cipher)
else:
# FIXME: find a way to make WPA config option matrix not
# make you want to throw up
raise ValueError("Unsupported security combo")
security.read_from_args(args)
except ValueError, e:
logging.debug("Error reading security information: %s" % e)
del security
return None
return security
new_from_args = staticmethod(new_from_args)
def new_from_args(we_cipher, args):
security = None
try:
if we_cipher == IW_AUTH_CIPHER_NONE:
security = Security(we_cipher)
elif we_cipher == IW_AUTH_CIPHER_WEP40 or we_cipher == IW_AUTH_CIPHER_WEP104:
security = WEPSecurity(we_cipher)
else:
# FIXME: find a way to make WPA config option matrix not
# make you want to throw up
raise ValueError("Unsupported security combo")
security.read_from_args(args)
except ValueError, e:
logging.debug("Error reading security information: %s" % e)
del security
return None
return security
new_from_args = staticmethod(new_from_args)
def get_properties(self):
return [dbus.Int32(self._we_cipher)]
def get_properties(self):
return [dbus.Int32(self._we_cipher)]
def write_to_config(self, section, config):
config.set(section, "we_cipher", self._we_cipher)
def write_to_config(self, section, config):
config.set(section, "we_cipher", self._we_cipher)
class WEPSecurity(Security):
def read_from_args(self, args):
if len(args) != 2:
raise ValueError("not enough arguments")
key = args[0]
auth_alg = args[1]
if isinstance(key, unicode):
key = key.encode()
if not isinstance(key, str):
raise ValueError("wrong argument type for key")
if not isinstance(auth_alg, int):
raise ValueError("wrong argument type for auth_alg")
self._key = key
self._auth_alg = auth_alg
def read_from_args(self, args):
if len(args) != 2:
raise ValueError("not enough arguments")
key = args[0]
auth_alg = args[1]
if isinstance(key, unicode):
key = key.encode()
if not isinstance(key, str):
raise ValueError("wrong argument type for key")
if not isinstance(auth_alg, int):
raise ValueError("wrong argument type for auth_alg")
self._key = key
self._auth_alg = auth_alg
def read_from_config(self, cfg, name):
# Key should be a hex encoded string
self._key = cfg.get(name, "key")
if self._we_cipher == IW_AUTH_CIPHER_WEP40 and len(self._key) != 10:
raise ValueError("Key length not right for 40-bit WEP")
if self._we_cipher == IW_AUTH_CIPHER_WEP104 and len(self._key) != 26:
raise ValueError("Key length not right for 104-bit WEP")
def read_from_config(self, cfg, name):
# Key should be a hex encoded string
self._key = cfg.get(name, "key")
if self._we_cipher == IW_AUTH_CIPHER_WEP40 and len(self._key) != 10:
raise ValueError("Key length not right for 40-bit WEP")
if self._we_cipher == IW_AUTH_CIPHER_WEP104 and len(self._key) != 26:
raise ValueError("Key length not right for 104-bit WEP")
try:
a = binascii.a2b_hex(self._key)
except TypeError:
raise ValueError("Key was not a hexadecimal string.")
self._auth_alg = cfg.get_int(name, "auth_alg")
if self._auth_alg != IW_AUTH_ALG_OPEN_SYSTEM and self._auth_alg != IW_AUTH_ALG_SHARED_KEY:
raise ValueError("Invalid authentication algorithm %d" % self._auth_alg)
try:
a = binascii.a2b_hex(self._key)
except TypeError:
raise ValueError("Key was not a hexadecimal string.")
self._auth_alg = cfg.get_int(name, "auth_alg")
if self._auth_alg != IW_AUTH_ALG_OPEN_SYSTEM and self._auth_alg != IW_AUTH_ALG_SHARED_KEY:
raise ValueError("Invalid authentication algorithm %d" % self._auth_alg)
def get_properties(self):
args = Security.get_properties(self)
args.append(dbus.String(self._key))
args.append(dbus.Int32(self._auth_alg))
return args
def get_properties(self):
args = Security.get_properties(self)
args.append(dbus.String(self._key))
args.append(dbus.Int32(self._auth_alg))
return args
def write_to_config(self, section, config):
Security.write_to_config(self, section, config)
config.set(section, "key", self._key)
config.set(section, "auth_alg", self._auth_alg)
def write_to_config(self, section, config):
Security.write_to_config(self, section, config)
config.set(section, "key", self._key)
config.set(section, "auth_alg", self._auth_alg)
class Network:
def __init__(self, ssid):
self.ssid = ssid
self.timestamp = int(time.time())
self.bssids = []
self.we_cipher = 0
self._security = None
def __init__(self, ssid):
self.ssid = ssid
self.timestamp = int(time.time())
self.bssids = []
self.we_cipher = 0
self._security = None
def get_properties(self):
bssid_list = dbus.Array([], signature="s")
for item in self.bssids:
bssid_list.append(dbus.String(item))
args = [dbus.String(self.ssid), dbus.Int32(self.timestamp), dbus.Boolean(True), bssid_list]
args += self._security.get_properties()
return tuple(args)
def get_properties(self):
bssid_list = dbus.Array([], signature="s")
for item in self.bssids:
bssid_list.append(dbus.String(item))
args = [dbus.String(self.ssid), dbus.Int32(self.timestamp), dbus.Boolean(True), bssid_list]
args += self._security.get_properties()
return tuple(args)
def get_security(self):
return self._security.get_properties()
def get_security(self):
return self._security.get_properties()
def set_security(self, security):
self._security = security
def set_security(self, security):
self._security = security
def read_from_args(self, auto, bssid, we_cipher, args):
if auto == False:
self.timestamp = int(time.time())
if not bssid in self.bssids:
self.bssids.append(bssid)
def read_from_args(self, auto, bssid, we_cipher, args):
if auto == False:
self.timestamp = int(time.time())
if not bssid in self.bssids:
self.bssids.append(bssid)
self._security = Security.new_from_args(we_cipher, args)
if not self._security:
raise NetworkInvalidError("Invalid security information")
self._security = Security.new_from_args(we_cipher, args)
if not self._security:
raise NetworkInvalidError("Invalid security information")
def read_from_config(self, config):
try:
self.timestamp = config.get_int(self.ssid, "timestamp")
except (ConfigParser.NoOptionError, ValueError), e:
raise NetworkInvalidError(e)
def read_from_config(self, config):
try:
self.timestamp = config.get_int(self.ssid, "timestamp")
except (ConfigParser.NoOptionError, ValueError), e:
raise NetworkInvalidError(e)
self._security = Security.new_from_config(config, self.ssid)
if not self._security:
raise NetworkInvalidError(e)
self._security = Security.new_from_config(config, self.ssid)
if not self._security:
raise NetworkInvalidError(e)
# The following don't need to be present
try:
self.bssids = config.get_list(self.ssid, "bssids")
except (ConfigParser.NoOptionError, ValueError), e:
pass
# The following don't need to be present
try:
self.bssids = config.get_list(self.ssid, "bssids")
except (ConfigParser.NoOptionError, ValueError), e:
pass
def write_to_config(self, config):
try:
config.add_section(self.ssid)
config.set(self.ssid, "timestamp", self.timestamp)
if len(self.bssids) > 0:
opt = " "
opt.join(self.bssids)
config.set(self.ssid, "bssids", opt)
self._security.write_to_config(self.ssid, config)
except Exception, e:
logging.debug("Error writing '%s': %s" % (self.ssid, e))
def write_to_config(self, config):
try:
config.add_section(self.ssid)
config.set(self.ssid, "timestamp", self.timestamp)
if len(self.bssids) > 0:
opt = " "
opt.join(self.bssids)
config.set(self.ssid, "bssids", opt)
self._security.write_to_config(self.ssid, config)
except Exception, e:
logging.debug("Error writing '%s': %s" % (self.ssid, e))
class NotFoundError(dbus.DBusException):
pass
pass
class UnsupportedError(dbus.DBusException):
pass
pass
class NMInfoDBusServiceHelper(dbus.service.Object):
def __init__(self, parent):
self._parent = parent
bus = dbus.SystemBus()
def __init__(self, parent):
self._parent = parent
bus = dbus.SystemBus()
# If NMI is already around, don't grab the NMI service
bus_object = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
name = None
try:
name = bus_object.GetNameOwner("org.freedesktop.NetworkManagerInfo", \
dbus_interface='org.freedesktop.DBus')
except dbus.DBusException:
pass
if name:
logging.debug("NMI service already owned by %s, won't claim it." % name)
raise RuntimeError
# If NMI is already around, don't grab the NMI service
bus_object = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
name = None
try:
name = bus_object.GetNameOwner("org.freedesktop.NetworkManagerInfo", \
dbus_interface='org.freedesktop.DBus')
except dbus.DBusException:
pass
if name:
logging.debug("NMI service already owned by %s, won't claim it." % name)
raise RuntimeError
bus_name = dbus.service.BusName(NM_INFO_IFACE, bus=bus)
dbus.service.Object.__init__(self, bus_name, NM_INFO_PATH)
bus_name = dbus.service.BusName(NM_INFO_IFACE, bus=bus)
dbus.service.Object.__init__(self, bus_name, NM_INFO_PATH)
@dbus.service.method(NM_INFO_IFACE, in_signature='i', out_signature='as')
def getNetworks(self, net_type):
ssids = self._parent.get_networks(net_type)
if len(ssids) > 0:
return dbus.Array(ssids)
@dbus.service.method(NM_INFO_IFACE, in_signature='i', out_signature='as')
def getNetworks(self, net_type):
ssids = self._parent.get_networks(net_type)
if len(ssids) > 0:
return dbus.Array(ssids)
raise NoNetworks()
raise NoNetworks()
@dbus.service.method(NM_INFO_IFACE, in_signature='si', async_callbacks=('async_cb', 'async_err_cb'))
def getNetworkProperties(self, ssid, net_type, async_cb, async_err_cb):
self._parent.get_network_properties(ssid, net_type, async_cb, async_err_cb)
@dbus.service.method(NM_INFO_IFACE, in_signature='si', async_callbacks=('async_cb', 'async_err_cb'))
def getNetworkProperties(self, ssid, net_type, async_cb, async_err_cb):
self._parent.get_network_properties(ssid, net_type, async_cb, async_err_cb)
@dbus.service.method(NM_INFO_IFACE)
def updateNetworkInfo(self, ssid, bauto, bssid, cipher, *args):
self._parent.update_network_info(ssid, bauto, bssid, cipher, args)
@dbus.service.method(NM_INFO_IFACE)
def updateNetworkInfo(self, ssid, bauto, bssid, cipher, *args):
self._parent.update_network_info(ssid, bauto, bssid, cipher, args)
@dbus.service.method(NM_INFO_IFACE, async_callbacks=('async_cb', 'async_err_cb'))
def getKeyForNetwork(self, dev_path, net_path, ssid, attempt, new_key, async_cb, async_err_cb):
self._parent.get_key_for_network(dev_path, net_path, ssid,
attempt, new_key, async_cb, async_err_cb)
@dbus.service.method(NM_INFO_IFACE, async_callbacks=('async_cb', 'async_err_cb'))
def getKeyForNetwork(self, dev_path, net_path, ssid, attempt, new_key, async_cb, async_err_cb):
self._parent.get_key_for_network(dev_path, net_path, ssid,
attempt, new_key, async_cb, async_err_cb)
@dbus.service.method(NM_INFO_IFACE)
def cancelGetKeyForNetwork(self):
self._parent.cancel_get_key_for_network()
@dbus.service.method(NM_INFO_IFACE)
def cancelGetKeyForNetwork(self):
self._parent.cancel_get_key_for_network()
class NMInfo(object):
def __init__(self, client):
try:
profile_path = env.get_profile_path()
except NameError:
home = os.path.expanduser("~")
profile_path = os.path.join(home, ".sugar", "default")
self._cfg_file = os.path.join(profile_path, "nm", "networks.cfg")
self._nmclient = client
self._allowed_networks = self._read_config()
self._dbus_helper = NMInfoDBusServiceHelper(self)
def __init__(self, client):
try:
profile_path = env.get_profile_path()
except NameError:
home = os.path.expanduser("~")
profile_path = os.path.join(home, ".sugar", "default")
self._cfg_file = os.path.join(profile_path, "nm", "networks.cfg")
self._nmclient = client
self._allowed_networks = self._read_config()
self._dbus_helper = NMInfoDBusServiceHelper(self)
def save_config(self):
self._write_config(self._allowed_networks)
def save_config(self):
self._write_config(self._allowed_networks)
def _read_config(self):
if not os.path.exists(os.path.dirname(self._cfg_file)):
os.makedirs(os.path.dirname(self._cfg_file), 0755)
if not os.path.exists(self._cfg_file):
self._write_config({})
return {}
def _read_config(self):
if not os.path.exists(os.path.dirname(self._cfg_file)):
os.makedirs(os.path.dirname(self._cfg_file), 0755)
if not os.path.exists(self._cfg_file):
self._write_config({})
return {}
config = NMConfig()
config.read(self._cfg_file)
networks = {}
for name in config.sections():
if not isinstance(name, unicode):
name = unicode(name)
net = Network(name)
try:
net.read_from_config(config)
networks[name] = net
except NetworkInvalidError, e:
logging.debug("Error: invalid stored network config: %s" % e)
del net
del config
return networks
config = NMConfig()
config.read(self._cfg_file)
networks = {}
for name in config.sections():
if not isinstance(name, unicode):
name = unicode(name)
net = Network(name)
try:
net.read_from_config(config)
networks[name] = net
except NetworkInvalidError, e:
logging.debug("Error: invalid stored network config: %s" % e)
del net
del config
return networks
def _write_config(self, networks):
fp = open(self._cfg_file, 'w')
config = NMConfig()
for net in networks.values():
net.write_to_config(config)
config.write(fp)
fp.close()
del config
def _write_config(self, networks):
fp = open(self._cfg_file, 'w')
config = NMConfig()
for net in networks.values():
net.write_to_config(config)
config.write(fp)
fp.close()
del config
def get_networks(self, net_type):
if net_type != NETWORK_TYPE_ALLOWED:
raise ValueError("Bad network type")
nets = []
for net in self._allowed_networks.values():
nets.append(net.ssid)
logging.debug("Returning networks: %s" % nets)
return nets
def get_networks(self, net_type):
if net_type != NETWORK_TYPE_ALLOWED:
raise ValueError("Bad network type")
nets = []
for net in self._allowed_networks.values():
nets.append(net.ssid)
logging.debug("Returning networks: %s" % nets)
return nets
def get_network_properties(self, ssid, net_type, async_cb, async_err_cb):
if not isinstance(ssid, unicode):
async_err_cb(ValueError("Invalid arguments; ssid must be unicode."))
if net_type != NETWORK_TYPE_ALLOWED:
async_err_cb(ValueError("Bad network type"))
if not self._allowed_networks.has_key(ssid):
async_err_cb(NotFoundError("Network '%s' not found." % ssid))
network = self._allowed_networks[ssid]
props = network.get_properties()
def get_network_properties(self, ssid, net_type, async_cb, async_err_cb):
if not isinstance(ssid, unicode):
async_err_cb(ValueError("Invalid arguments; ssid must be unicode."))
if net_type != NETWORK_TYPE_ALLOWED:
async_err_cb(ValueError("Bad network type"))
if not self._allowed_networks.has_key(ssid):
async_err_cb(NotFoundError("Network '%s' not found." % ssid))
network = self._allowed_networks[ssid]
props = network.get_properties()
# DBus workaround: the normal method return handler wraps
# the returned arguments in a tuple and then converts that to a
# struct, but NetworkManager expects a plain list of arguments.
# It turns out that the async callback method return code _doesn't_
# wrap the returned arguments in a tuple, so as a workaround use
# the async callback stuff here even though we're not doing it
# asynchronously.
async_cb(*props)
# DBus workaround: the normal method return handler wraps
# the returned arguments in a tuple and then converts that to a
# struct, but NetworkManager expects a plain list of arguments.
# It turns out that the async callback method return code _doesn't_
# wrap the returned arguments in a tuple, so as a workaround use
# the async callback stuff here even though we're not doing it
# asynchronously.
async_cb(*props)
def update_network_info(self, ssid, auto, bssid, we_cipher, args):
if not isinstance(ssid, unicode):
raise ValueError("Invalid arguments; ssid must be unicode.")
if self._allowed_networks.has_key(ssid):
del self._allowed_networks[ssid]
net = Network(ssid)
try:
net.read_from_args(auto, bssid, we_cipher, args)
logging.debug("Updated network information for '%s'." % ssid)
self._allowed_networks[ssid] = net
self.save_config()
except NetworkInvalidError, e:
logging.debug("Error updating network information: %s" % e)
del net
def update_network_info(self, ssid, auto, bssid, we_cipher, args):
if not isinstance(ssid, unicode):
raise ValueError("Invalid arguments; ssid must be unicode.")
if self._allowed_networks.has_key(ssid):
del self._allowed_networks[ssid]
net = Network(ssid)
try:
net.read_from_args(auto, bssid, we_cipher, args)
logging.debug("Updated network information for '%s'." % ssid)
self._allowed_networks[ssid] = net
self.save_config()
except NetworkInvalidError, e:
logging.debug("Error updating network information: %s" % e)
del net
def get_key_for_network(self, dev_op, net_op, ssid, attempt, new_key, async_cb, async_err_cb):
if not isinstance(ssid, unicode):
raise ValueError("Invalid arguments; ssid must be unicode.")
if self._allowed_networks.has_key(ssid) and not new_key:
# We've got the info already
net = self._allowed_networks[ssid]
async_cb(tuple(net.get_security()))
return
def get_key_for_network(self, dev_op, net_op, ssid, attempt, new_key, async_cb, async_err_cb):
if not isinstance(ssid, unicode):
raise ValueError("Invalid arguments; ssid must be unicode.")
if self._allowed_networks.has_key(ssid) and not new_key:
# We've got the info already
net = self._allowed_networks[ssid]
async_cb(tuple(net.get_security()))
return
# Otherwise, ask the user for it
net = None
dev = self._nmclient.get_device(dev_op)
if not dev:
async_err_cb(NotFoundError("Device was unknown."))
return
# Otherwise, ask the user for it
net = None
dev = self._nmclient.get_device(dev_op)
if not dev:
async_err_cb(NotFoundError("Device was unknown."))
return
if dev.get_type() == nmclient.DEVICE_TYPE_802_3_ETHERNET:
# We don't support wired 802.1x yet...
async_err_cb(UnsupportedError("Device type is unsupported by NMI."))
return
if dev.get_type() == nmclient.DEVICE_TYPE_802_3_ETHERNET:
# We don't support wired 802.1x yet...
async_err_cb(UnsupportedError("Device type is unsupported by NMI."))
return
net = dev.get_network(net_op)
if not net:
async_err_cb(NotFoundError("Network was unknown."))
return
net = dev.get_network(net_op)
if not net:
async_err_cb(NotFoundError("Network was unknown."))
return
self._nmclient.get_key_for_network(net, async_cb, async_err_cb)
self._nmclient.get_key_for_network(net, async_cb, async_err_cb)
def get_key_for_network_cb(self, net, key, auth_alg, async_cb, async_err_cb, canceled=False):
"""
Called by the NMClient when the Wireless Network Key dialog
is closed.
"""
if canceled:
e = CanceledKeyRequestError("Request was canceled.")
# key dialog dialog was canceled; send the error back to NM
async_err_cb(e)
return
def get_key_for_network_cb(self, net, key, auth_alg, async_cb, async_err_cb, canceled=False):
"""
Called by the NMClient when the Wireless Network Key dialog
is closed.
"""
if canceled:
e = CanceledKeyRequestError("Request was canceled.")
# key dialog dialog was canceled; send the error back to NM
async_err_cb(e)
return
if not key or not auth_alg:
# no key returned, *** BUG ***; the key dialog
# should always return either a key + auth_alg, or a
#cancel error
raise RuntimeError("No key or auth alg given! Bug!")
if not key or not auth_alg:
# no key returned, *** BUG ***; the key dialog
# should always return either a key + auth_alg, or a
#cancel error
raise RuntimeError("No key or auth alg given! Bug!")
we_cipher = None
if len(key) == 26:
we_cipher = IW_AUTH_CIPHER_WEP104
elif len(key) == 10:
we_cipher = IW_AUTH_CIPHER_WEP40
else:
raise RuntimeError("Invalid key length!")
we_cipher = None
if len(key) == 26:
we_cipher = IW_AUTH_CIPHER_WEP104
elif len(key) == 10:
we_cipher = IW_AUTH_CIPHER_WEP40
else:
raise RuntimeError("Invalid key length!")
# Stuff the returned key and auth algorithm into a security object
# and return it to NetworkManager
sec = Security.new_from_args(we_cipher, (key, auth_alg))
if not sec:
raise RuntimeError("Invalid security arguments.")
props = sec.get_properties()
a = tuple(props)
async_cb(*a)
# Stuff the returned key and auth algorithm into a security object
# and return it to NetworkManager
sec = Security.new_from_args(we_cipher, (key, auth_alg))
if not sec:
raise RuntimeError("Invalid security arguments.")
props = sec.get_properties()
a = tuple(props)
async_cb(*a)
def cancel_get_key_for_network(self):
# Tell the NMClient to close the key request dialog
self._nmclient.cancel_get_key_for_network()
def cancel_get_key_for_network(self):
# Tell the NMClient to close the key request dialog
self._nmclient.cancel_get_key_for_network()
+40 -40
View File
@@ -22,60 +22,60 @@ IW_AUTH_ALG_OPEN_SYSTEM = 0x00000001
IW_AUTH_ALG_SHARED_KEY = 0x00000002
class WEPKeyDialog(gtk.Dialog):
def __init__(self, net, async_cb, async_err_cb):
gtk.Dialog.__init__(self)
self.set_title("Wireless Key Required")
def __init__(self, net, async_cb, async_err_cb):
gtk.Dialog.__init__(self)
self.set_title("Wireless Key Required")
self._net = net
self._async_cb = async_cb
self._async_err_cb = async_err_cb
self._net = net
self._async_cb = async_cb
self._async_err_cb = async_err_cb
self.set_has_separator(False)
self.set_has_separator(False)
label = gtk.Label("A wireless encryption key is required for\n" \
" the wireless network '%s'." % net.get_ssid())
self.vbox.pack_start(label)
label = gtk.Label("A wireless encryption key is required for\n" \
" the wireless network '%s'." % net.get_ssid())
self.vbox.pack_start(label)
self._entry = gtk.Entry()
self._entry.props.visibility = False
self._entry.connect('changed', self._entry_changed_cb)
self.vbox.pack_start(self._entry)
self.vbox.show_all()
self._entry = gtk.Entry()
self._entry.props.visibility = False
self._entry.connect('changed', self._entry_changed_cb)
self.vbox.pack_start(self._entry)
self.vbox.show_all()
self.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_OK, gtk.RESPONSE_OK)
self.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_OK, gtk.RESPONSE_OK)
self.set_default_response(gtk.RESPONSE_OK)
self._update_response_sensitivity()
self.set_default_response(gtk.RESPONSE_OK)
self._update_response_sensitivity()
def get_key(self):
return self._entry.get_text()
def get_key(self):
return self._entry.get_text()
def get_auth_alg(self):
return IW_AUTH_ALG_OPEN_SYSTEM
def get_auth_alg(self):
return IW_AUTH_ALG_OPEN_SYSTEM
def get_network(self):
return self._net
def get_network(self):
return self._net
def get_callbacks(self):
return (self._async_cb, self._async_err_cb)
def get_callbacks(self):
return (self._async_cb, self._async_err_cb)
def _entry_changed_cb(self, entry):
self._update_response_sensitivity()
def _entry_changed_cb(self, entry):
self._update_response_sensitivity()
def _update_response_sensitivity(self):
key = self.get_key()
def _update_response_sensitivity(self):
key = self.get_key()
is_hex = True
for c in key:
if not 'a' <= c <= 'f' and not '0' <= c <= '9':
is_hex = False
is_hex = True
for c in key:
if not 'a' <= c <= 'f' and not '0' <= c <= '9':
is_hex = False
valid_len = (len(key) == 10 or len(key) == 26)
self.set_response_sensitive(gtk.RESPONSE_OK, is_hex and valid_len)
valid_len = (len(key) == 10 or len(key) == 26)
self.set_response_sensitive(gtk.RESPONSE_OK, is_hex and valid_len)
if __name__ == "__main__":
dialog = WEPKeyDialog()
dialog.run()
dialog = WEPKeyDialog()
dialog.run()
print dialog.get_key()
print dialog.get_key()
+126 -126
View File
@@ -22,155 +22,155 @@ ACTIVITY_DBUS_INTERFACE = "org.laptop.Presence.Activity"
class ActivityDBusHelper(dbus.service.Object):
def __init__(self, parent, bus_name, object_path):
self._parent = parent
self._bus_name = bus_name
self._object_path = object_path
dbus.service.Object.__init__(self, bus_name, self._object_path)
def __init__(self, parent, bus_name, object_path):
self._parent = parent
self._bus_name = bus_name
self._object_path = object_path
dbus.service.Object.__init__(self, bus_name, self._object_path)
@dbus.service.method(ACTIVITY_DBUS_INTERFACE,
in_signature="s", out_signature="ao")
def getServicesOfType(self, stype):
ret = []
for serv in self._parent.get_services_of_type(stype):
ret.append(serv.object_path())
return ret
@dbus.service.method(ACTIVITY_DBUS_INTERFACE,
in_signature="s", out_signature="ao")
def getServicesOfType(self, stype):
ret = []
for serv in self._parent.get_services_of_type(stype):
ret.append(serv.object_path())
return ret
@dbus.service.method(ACTIVITY_DBUS_INTERFACE,
in_signature="", out_signature="ao")
def getServices(self):
ret = []
for serv in self._parent.get_services():
ret.append(serv.object_path())
return ret
@dbus.service.method(ACTIVITY_DBUS_INTERFACE,
in_signature="", out_signature="ao")
def getServices(self):
ret = []
for serv in self._parent.get_services():
ret.append(serv.object_path())
return ret
@dbus.service.method(ACTIVITY_DBUS_INTERFACE,
in_signature="", out_signature="s")
def getId(self):
return self._parent.get_id()
@dbus.service.method(ACTIVITY_DBUS_INTERFACE,
in_signature="", out_signature="s")
def getId(self):
return self._parent.get_id()
@dbus.service.method(ACTIVITY_DBUS_INTERFACE,
in_signature="", out_signature="s")
def getColor(self):
return self._parent.get_color()
@dbus.service.method(ACTIVITY_DBUS_INTERFACE,
in_signature="", out_signature="s")
def getColor(self):
return self._parent.get_color()
@dbus.service.method(ACTIVITY_DBUS_INTERFACE,
in_signature="", out_signature="ao")
def getJoinedBuddies(self):
ret = []
for buddy in self._parent.get_joined_buddies():
ret.append(buddy.object_path())
return ret
@dbus.service.signal(ACTIVITY_DBUS_INTERFACE,
signature="o")
def ServiceAppeared(self, object_path):
pass
@dbus.service.method(ACTIVITY_DBUS_INTERFACE,
in_signature="", out_signature="ao")
def getJoinedBuddies(self):
ret = []
for buddy in self._parent.get_joined_buddies():
ret.append(buddy.object_path())
return ret
@dbus.service.signal(ACTIVITY_DBUS_INTERFACE,
signature="o")
def ServiceAppeared(self, object_path):
pass
@dbus.service.signal(ACTIVITY_DBUS_INTERFACE,
signature="o")
def ServiceDisappeared(self, object_path):
pass
@dbus.service.signal(ACTIVITY_DBUS_INTERFACE,
signature="o")
def ServiceDisappeared(self, object_path):
pass
@dbus.service.signal(ACTIVITY_DBUS_INTERFACE,
signature="o")
def BuddyJoined(self, object_path):
pass
@dbus.service.signal(ACTIVITY_DBUS_INTERFACE,
signature="o")
def BuddyJoined(self, object_path):
pass
@dbus.service.signal(ACTIVITY_DBUS_INTERFACE,
signature="o")
def BuddyLeft(self, object_path):
pass
@dbus.service.signal(ACTIVITY_DBUS_INTERFACE,
signature="o")
def BuddyLeft(self, object_path):
pass
class Activity(object):
def __init__(self, bus_name, object_id, initial_service):
if not initial_service.get_activity_id():
raise ValueError("Service must have a valid Activity ID")
self._activity_id = initial_service.get_activity_id()
def __init__(self, bus_name, object_id, initial_service):
if not initial_service.get_activity_id():
raise ValueError("Service must have a valid Activity ID")
self._activity_id = initial_service.get_activity_id()
self._buddies = []
self._services = {} # service type -> list of Services
self._color = None
self._valid = False
self._buddies = []
self._services = {} # service type -> list of Services
self._color = None
self._valid = False
self._object_id = object_id
self._object_path = "/org/laptop/Presence/Activities/%d" % self._object_id
self._dbus_helper = ActivityDBusHelper(self, bus_name, self._object_path)
self.add_service(initial_service)
self._object_id = object_id
self._object_path = "/org/laptop/Presence/Activities/%d" % self._object_id
self._dbus_helper = ActivityDBusHelper(self, bus_name, self._object_path)
self.add_service(initial_service)
def object_path(self):
return dbus.ObjectPath(self._object_path)
def object_path(self):
return dbus.ObjectPath(self._object_path)
def is_valid(self):
"""An activity is only valid when it's color is available."""
return self._valid
def is_valid(self):
"""An activity is only valid when it's color is available."""
return self._valid
def get_id(self):
return self._activity_id
def get_id(self):
return self._activity_id
def get_color(self):
return self._color
def get_color(self):
return self._color
def get_services(self):
ret = []
for serv_list in self._services.values():
for service in serv_list:
if service not in ret:
ret.append(service)
return ret
def get_services(self):
ret = []
for serv_list in self._services.values():
for service in serv_list:
if service not in ret:
ret.append(service)
return ret
def get_services_of_type(self, stype):
if self._services.has_key(stype):
return self._services[stype]
return []
def get_services_of_type(self, stype):
if self._services.has_key(stype):
return self._services[stype]
return []
def get_joined_buddies(self):
buddies = []
for serv_list in self._services.values():
for serv in serv_list:
owner = serv.get_owner()
if owner and not owner in buddies and owner.is_valid():
buddies.append(owner)
return buddies
def get_joined_buddies(self):
buddies = []
for serv_list in self._services.values():
for serv in serv_list:
owner = serv.get_owner()
if owner and not owner in buddies and owner.is_valid():
buddies.append(owner)
return buddies
def add_service(self, service):
stype = service.get_type()
if not self._services.has_key(stype):
self._services[stype] = []
def add_service(self, service):
stype = service.get_type()
if not self._services.has_key(stype):
self._services[stype] = []
if not self._color:
color = service.get_one_property('color')
if color:
self._color = color
self._valid = True
if not self._color:
color = service.get_one_property('color')
if color:
self._color = color
self._valid = True
# Send out the BuddyJoined signal if this is the first
# service from the buddy that we've seen
buddies = self.get_joined_buddies()
serv_owner = service.get_owner()
if serv_owner and serv_owner not in buddies and serv_owner.is_valid():
self._dbus_helper.BuddyJoined(serv_owner.object_path())
serv_owner.add_activity(self)
# Send out the BuddyJoined signal if this is the first
# service from the buddy that we've seen
buddies = self.get_joined_buddies()
serv_owner = service.get_owner()
if serv_owner and serv_owner not in buddies and serv_owner.is_valid():
self._dbus_helper.BuddyJoined(serv_owner.object_path())
serv_owner.add_activity(self)
if not service in self._services[stype]:
self._services[stype].append(service)
self._dbus_helper.ServiceAppeared(service.object_path())
if not service in self._services[stype]:
self._services[stype].append(service)
self._dbus_helper.ServiceAppeared(service.object_path())
def remove_service(self, service):
stype = service.get_type()
if not self._services.has_key(stype):
return
self._services[stype].remove(service)
self._dbus_helper.ServiceDisappeared(service.object_path())
if len(self._services[stype]) == 0:
del self._services[stype]
def remove_service(self, service):
stype = service.get_type()
if not self._services.has_key(stype):
return
self._services[stype].remove(service)
self._dbus_helper.ServiceDisappeared(service.object_path())
if len(self._services[stype]) == 0:
del self._services[stype]
# Send out the BuddyLeft signal if this is the last
# service from the buddy
buddies = self.get_joined_buddies()
serv_owner = service.get_owner()
if serv_owner and serv_owner not in buddies and serv_owner.is_valid():
serv_owner.remove_activity(self)
self._dbus_helper.BuddyLeft(serv_owner.object_path())
# Send out the BuddyLeft signal if this is the last
# service from the buddy
buddies = self.get_joined_buddies()
serv_owner = service.get_owner()
if serv_owner and serv_owner not in buddies and serv_owner.is_valid():
serv_owner.remove_activity(self)
self._dbus_helper.BuddyLeft(serv_owner.object_path())
+406 -406
View File
@@ -30,433 +30,433 @@ _BUDDY_KEY_COLOR = 'color'
_BUDDY_KEY_CURACT = 'curact'
class NotFoundError(Exception):
pass
pass
class BuddyDBusHelper(dbus.service.Object):
def __init__(self, parent, bus_name, object_path):
self._parent = parent
self._bus_name = bus_name
self._object_path = object_path
dbus.service.Object.__init__(self, bus_name, self._object_path)
def __init__(self, parent, bus_name, object_path):
self._parent = parent
self._bus_name = bus_name
self._object_path = object_path
dbus.service.Object.__init__(self, bus_name, self._object_path)
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="o")
def ServiceAppeared(self, object_path):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="o")
def ServiceAppeared(self, object_path):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="o")
def ServiceDisappeared(self, object_path):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="o")
def ServiceDisappeared(self, object_path):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="")
def Disappeared(self):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="")
def Disappeared(self):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="ao")
def CurrentActivityChanged(self, activities):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="ao")
def CurrentActivityChanged(self, activities):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="")
def IconChanged(self):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="")
def IconChanged(self):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="o")
def JoinedActivity(self, object_path):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="o")
def JoinedActivity(self, object_path):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="o")
def LeftActivity(self, object_path):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="o")
def LeftActivity(self, object_path):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="as")
def PropertyChanged(self, prop_list):
pass
@dbus.service.signal(BUDDY_DBUS_INTERFACE,
signature="as")
def PropertyChanged(self, prop_list):
pass
@dbus.service.method(BUDDY_DBUS_INTERFACE,
in_signature="", out_signature="ay")
def getIcon(self):
icon = self._parent.get_icon()
if not icon:
return ""
return icon
@dbus.service.method(BUDDY_DBUS_INTERFACE,
in_signature="", out_signature="ay")
def getIcon(self):
icon = self._parent.get_icon()
if not icon:
return ""
return icon
@dbus.service.method(BUDDY_DBUS_INTERFACE,
in_signature="so", out_signature="o")
def getServiceOfType(self, stype, activity_op):
activity = None
# "/" is the placeholder for None
if activity_op != "/":
for act in self._parent.get_joined_activities():
if act.object_path() == activity_op:
activity = act
if not activity:
raise NotFoundError("Not found")
@dbus.service.method(BUDDY_DBUS_INTERFACE,
in_signature="so", out_signature="o")
def getServiceOfType(self, stype, activity_op):
activity = None
# "/" is the placeholder for None
if activity_op != "/":
for act in self._parent.get_joined_activities():
if act.object_path() == activity_op:
activity = act
if not activity:
raise NotFoundError("Not found")
service = self._parent.get_service_of_type(stype, activity)
if not service:
raise NotFoundError("Not found")
return service.object_path()
service = self._parent.get_service_of_type(stype, activity)
if not service:
raise NotFoundError("Not found")
return service.object_path()
@dbus.service.method(BUDDY_DBUS_INTERFACE,
in_signature="", out_signature="ao")
def getJoinedActivities(self):
acts = []
for act in self._parent.get_joined_activities():
acts.append(act.object_path())
return acts
@dbus.service.method(BUDDY_DBUS_INTERFACE,
in_signature="", out_signature="ao")
def getJoinedActivities(self):
acts = []
for act in self._parent.get_joined_activities():
acts.append(act.object_path())
return acts
@dbus.service.method(BUDDY_DBUS_INTERFACE,
in_signature="", out_signature="a{sv}")
def getProperties(self):
props = {}
props['name'] = self._parent.get_name()
addr = self._parent.get_address()
if addr:
props['ip4_address'] = addr
props['owner'] = self._parent.is_owner()
color = self._parent.get_color()
if color:
props[_BUDDY_KEY_COLOR] = self._parent.get_color()
return props
@dbus.service.method(BUDDY_DBUS_INTERFACE,
in_signature="", out_signature="a{sv}")
def getProperties(self):
props = {}
props['name'] = self._parent.get_name()
addr = self._parent.get_address()
if addr:
props['ip4_address'] = addr
props['owner'] = self._parent.is_owner()
color = self._parent.get_color()
if color:
props[_BUDDY_KEY_COLOR] = self._parent.get_color()
return props
@dbus.service.method(BUDDY_DBUS_INTERFACE,
in_signature="", out_signature="o")
def getCurrentActivity(self):
activity = self._parent.get_current_activity()
if not activity:
raise NotFoundError()
return activity.object_path()
@dbus.service.method(BUDDY_DBUS_INTERFACE,
in_signature="", out_signature="o")
def getCurrentActivity(self):
activity = self._parent.get_current_activity()
if not activity:
raise NotFoundError()
return activity.object_path()
class Buddy(object):
"""Represents another person on the network and keeps track of the
activities and resources they make available for sharing."""
"""Represents another person on the network and keeps track of the
activities and resources they make available for sharing."""
def __init__(self, bus_name, object_id, service, icon_cache):
if not bus_name:
raise ValueError("DBus bus name must be valid")
if not object_id or not isinstance(object_id, int):
raise ValueError("object id must be a valid number")
# Normal Buddy objects must be created with a valid service,
# owner objects do not
if not isinstance(self, Owner):
if not isinstance(service, Service.Service):
raise ValueError("service must be a valid service object")
def __init__(self, bus_name, object_id, service, icon_cache):
if not bus_name:
raise ValueError("DBus bus name must be valid")
if not object_id or not isinstance(object_id, int):
raise ValueError("object id must be a valid number")
# Normal Buddy objects must be created with a valid service,
# owner objects do not
if not isinstance(self, Owner):
if not isinstance(service, Service.Service):
raise ValueError("service must be a valid service object")
self._services = {}
self._activities = {}
self._services = {}
self._activities = {}
self._icon_cache = icon_cache
self._icon_cache = icon_cache
self._nick_name = None
self._address = None
if service is not None:
self._nick_name = service.get_name()
self._address = service.get_source_address()
self._color = None
self._current_activity = None
self._valid = False
self._icon = None
self._icon_tries = 0
self._nick_name = None
self._address = None
if service is not None:
self._nick_name = service.get_name()
self._address = service.get_source_address()
self._color = None
self._current_activity = None
self._valid = False
self._icon = None
self._icon_tries = 0
self._object_id = object_id
self._object_path = BUDDY_DBUS_OBJECT_PATH + str(self._object_id)
self._dbus_helper = BuddyDBusHelper(self, bus_name, self._object_path)
self._object_id = object_id
self._object_path = BUDDY_DBUS_OBJECT_PATH + str(self._object_id)
self._dbus_helper = BuddyDBusHelper(self, bus_name, self._object_path)
self._buddy_presence_service = None
if service is not None:
self.add_service(service)
self._buddy_presence_service = None
if service is not None:
self.add_service(service)
def object_path(self):
return dbus.ObjectPath(self._object_path)
def object_path(self):
return dbus.ObjectPath(self._object_path)
def _request_buddy_icon_cb(self, result_status, response, user_data):
"""Callback when icon request has completed."""
from sugar.p2p import network
icon = response
service = user_data
if result_status == network.RESULT_SUCCESS:
if icon and len(icon):
icon = base64.b64decode(icon)
self._set_icon(icon)
self._icon_cache.add_icon(icon)
def _request_buddy_icon_cb(self, result_status, response, user_data):
"""Callback when icon request has completed."""
from sugar.p2p import network
icon = response
service = user_data
if result_status == network.RESULT_SUCCESS:
if icon and len(icon):
icon = base64.b64decode(icon)
self._set_icon(icon)
self._icon_cache.add_icon(icon)
if (result_status == network.RESULT_FAILED or not icon) and self._icon_tries < 3:
self._icon_tries = self._icon_tries + 1
if self._icon_tries >= 3:
logging.debug("Failed to retrieve buddy icon for '%s'." % self._nick_name)
gobject.timeout_add(1000, self._get_buddy_icon, service, True)
return False
if (result_status == network.RESULT_FAILED or not icon) and self._icon_tries < 3:
self._icon_tries = self._icon_tries + 1
if self._icon_tries >= 3:
logging.debug("Failed to retrieve buddy icon for '%s'." % self._nick_name)
gobject.timeout_add(1000, self._get_buddy_icon, service, True)
return False
def _get_buddy_icon(self, service, retry=False):
"""Get the buddy's icon. Check the cache first, if its
not there get the icon from the buddy over the network."""
if retry != True:
# Only hit the cache once
icon_hash = service.get_one_property('icon-hash')
if icon_hash is not None:
icon = self._icon_cache.get_icon(icon_hash)
if icon:
logging.debug("%s: icon cache hit for %s." % (self._nick_name, icon_hash))
self._set_icon(icon)
return False
logging.debug("%s: icon cache miss, fetching icon from buddy..." % self._nick_name)
def _get_buddy_icon(self, service, retry=False):
"""Get the buddy's icon. Check the cache first, if its
not there get the icon from the buddy over the network."""
if retry != True:
# Only hit the cache once
icon_hash = service.get_one_property('icon-hash')
if icon_hash is not None:
icon = self._icon_cache.get_icon(icon_hash)
if icon:
logging.debug("%s: icon cache hit for %s." % (self._nick_name, icon_hash))
self._set_icon(icon)
return False
logging.debug("%s: icon cache miss, fetching icon from buddy..." % self._nick_name)
from sugar.p2p import Stream
buddy_stream = Stream.Stream.new_from_service(service, start_reader=False)
writer = buddy_stream.new_writer(service)
success = writer.custom_request("get_buddy_icon", self._request_buddy_icon_cb, service)
if not success:
del writer, buddy_stream
gobject.timeout_add(1000, self._get_buddy_icon, service, True)
return False
from sugar.p2p import Stream
buddy_stream = Stream.Stream.new_from_service(service, start_reader=False)
writer = buddy_stream.new_writer(service)
success = writer.custom_request("get_buddy_icon", self._request_buddy_icon_cb, service)
if not success:
del writer, buddy_stream
gobject.timeout_add(1000, self._get_buddy_icon, service, True)
return False
def _get_service_key(self, service):
return (service.get_type(), service.get_activity_id())
def _get_service_key(self, service):
return (service.get_type(), service.get_activity_id())
def add_service(self, service):
"""Adds a new service to this buddy's service list, returning
True if the service was successfully added, and False if it was not."""
if service.get_name() != self._nick_name:
logging.error("Service and buddy nick names doesn't match: " \
"%s %s" % (service.get_name(), self._nick_name))
return False
def add_service(self, service):
"""Adds a new service to this buddy's service list, returning
True if the service was successfully added, and False if it was not."""
if service.get_name() != self._nick_name:
logging.error("Service and buddy nick names doesn't match: " \
"%s %s" % (service.get_name(), self._nick_name))
return False
source_addr = service.get_source_address()
if source_addr != self._address:
logging.error("Service source and buddy address doesn't " \
"match: %s %s" % (source_addr, self._address))
return False
return self._internal_add_service(service)
source_addr = service.get_source_address()
if source_addr != self._address:
logging.error("Service source and buddy address doesn't " \
"match: %s %s" % (source_addr, self._address))
return False
return self._internal_add_service(service)
def _internal_add_service(self, service):
service_key = self._get_service_key(service)
if service_key in self._services.keys():
logging.error("Service already known: %s %s" % (service_key[0],
service_key[1]))
return False
def _internal_add_service(self, service):
service_key = self._get_service_key(service)
if service_key in self._services.keys():
logging.error("Service already known: %s %s" % (service_key[0],
service_key[1]))
return False
if service.get_type() == PRESENCE_SERVICE_TYPE and self._buddy_presence_service:
# already have a presence service for this buddy
logging.debug("!!! Tried to add a buddy presence service when " \
"one already existed.")
return False
if service.get_type() == PRESENCE_SERVICE_TYPE and self._buddy_presence_service:
# already have a presence service for this buddy
logging.debug("!!! Tried to add a buddy presence service when " \
"one already existed.")
return False
logging.debug("Buddy %s added service type %s id %s" % (self._nick_name,
service.get_type(), service.get_activity_id()))
self._services[service_key] = service
service.set_owner(self)
logging.debug("Buddy %s added service type %s id %s" % (self._nick_name,
service.get_type(), service.get_activity_id()))
self._services[service_key] = service
service.set_owner(self)
if service.get_type() == PRESENCE_SERVICE_TYPE:
self._buddy_presence_service = service
# A buddy isn't valid until its official presence
# service has been found and resolved
self._valid = True
self._get_buddy_icon(service)
self._color = service.get_one_property(_BUDDY_KEY_COLOR)
self._current_activity = service.get_one_property(_BUDDY_KEY_CURACT)
# Monitor further buddy property changes, like current activity
# and color
service.connect('property-changed',
self.__buddy_presence_service_property_changed_cb)
if service.get_type() == PRESENCE_SERVICE_TYPE:
self._buddy_presence_service = service
# A buddy isn't valid until its official presence
# service has been found and resolved
self._valid = True
self._get_buddy_icon(service)
self._color = service.get_one_property(_BUDDY_KEY_COLOR)
self._current_activity = service.get_one_property(_BUDDY_KEY_CURACT)
# Monitor further buddy property changes, like current activity
# and color
service.connect('property-changed',
self.__buddy_presence_service_property_changed_cb)
if self._valid:
self._dbus_helper.ServiceAppeared(service.object_path())
return True
if self._valid:
self._dbus_helper.ServiceAppeared(service.object_path())
return True
def __buddy_presence_service_property_changed_cb(self, service, keys):
if _BUDDY_KEY_COLOR in keys:
new_color = service.get_one_property(_BUDDY_KEY_COLOR)
if new_color and self._color != new_color:
self._color = new_color
self._dbus_helper.PropertyChanged([_BUDDY_KEY_COLOR])
if _BUDDY_KEY_CURACT in keys:
# Three cases here:
# 1) Buddy didn't publish a 'curact' key at all; we do nothing
# 2) Buddy published a blank/zero-length 'curact' key; we send
# a current-activity-changed signal for no activity
# 3) Buddy published a non-zero-length 'curact' key; we send
# a current-activity-changed signal if we know about the
# activity already, if not we postpone until the activity
# is found on the network and added to the buddy
new_curact = service.get_one_property(_BUDDY_KEY_CURACT)
if new_curact and self._current_activity != new_curact:
if not len(new_curact):
new_curact = None
self._current_activity = new_curact
if self._activities.has_key(self._current_activity):
# Case (3) above, valid activity id
activity = self._activities[self._current_activity]
if activity.is_valid():
self._dbus_helper.CurrentActivityChanged([activity.object_path()])
elif not self._current_activity:
# Case (2) above, no current activity
self._dbus_helper.CurrentActivityChanged([])
def __buddy_presence_service_property_changed_cb(self, service, keys):
if _BUDDY_KEY_COLOR in keys:
new_color = service.get_one_property(_BUDDY_KEY_COLOR)
if new_color and self._color != new_color:
self._color = new_color
self._dbus_helper.PropertyChanged([_BUDDY_KEY_COLOR])
if _BUDDY_KEY_CURACT in keys:
# Three cases here:
# 1) Buddy didn't publish a 'curact' key at all; we do nothing
# 2) Buddy published a blank/zero-length 'curact' key; we send
# a current-activity-changed signal for no activity
# 3) Buddy published a non-zero-length 'curact' key; we send
# a current-activity-changed signal if we know about the
# activity already, if not we postpone until the activity
# is found on the network and added to the buddy
new_curact = service.get_one_property(_BUDDY_KEY_CURACT)
if new_curact and self._current_activity != new_curact:
if not len(new_curact):
new_curact = None
self._current_activity = new_curact
if self._activities.has_key(self._current_activity):
# Case (3) above, valid activity id
activity = self._activities[self._current_activity]
if activity.is_valid():
self._dbus_helper.CurrentActivityChanged([activity.object_path()])
elif not self._current_activity:
# Case (2) above, no current activity
self._dbus_helper.CurrentActivityChanged([])
def __find_service_by_activity_id(self, actid):
for serv in self._services.values():
if serv.get_activity_id() == actid:
return serv
return None
def __find_service_by_activity_id(self, actid):
for serv in self._services.values():
if serv.get_activity_id() == actid:
return serv
return None
def add_activity(self, activity):
if activity in self._activities.values():
return
actid = activity.get_id()
if not self.__find_service_by_activity_id(actid):
raise RuntimeError("Tried to add activity for which we had no service")
self._activities[actid] = activity
if activity.is_valid():
self._dbus_helper.JoinedActivity(activity.object_path())
def add_activity(self, activity):
if activity in self._activities.values():
return
actid = activity.get_id()
if not self.__find_service_by_activity_id(actid):
raise RuntimeError("Tried to add activity for which we had no service")
self._activities[actid] = activity
if activity.is_valid():
self._dbus_helper.JoinedActivity(activity.object_path())
# If when we received a current activity update from the buddy,
# but didn't know about that activity yet, and now we do know about
# it, we need to send out the changed activity signal
if actid == self._current_activity:
self._dbus_helper.CurrentActivityChanged([activity.object_path()])
# If when we received a current activity update from the buddy,
# but didn't know about that activity yet, and now we do know about
# it, we need to send out the changed activity signal
if actid == self._current_activity:
self._dbus_helper.CurrentActivityChanged([activity.object_path()])
def remove_service(self, service):
"""Remove a service from a buddy; ie, the activity was closed
or the buddy went away."""
if service.get_source_address() != self._address:
return
if service.get_name() != self._nick_name:
return
def remove_service(self, service):
"""Remove a service from a buddy; ie, the activity was closed
or the buddy went away."""
if service.get_source_address() != self._address:
return
if service.get_name() != self._nick_name:
return
if service.get_type() == PRESENCE_SERVICE_TYPE \
and self._buddy_presence_service \
and service != self._buddy_presence_service:
logging.debug("!!! Tried to remove a spurious buddy presence service.")
return
if service.get_type() == PRESENCE_SERVICE_TYPE \
and self._buddy_presence_service \
and service != self._buddy_presence_service:
logging.debug("!!! Tried to remove a spurious buddy presence service.")
return
service_key = self._get_service_key(service)
if self._services.has_key(service_key):
if self._valid:
self._dbus_helper.ServiceDisappeared(service.object_path())
del self._services[service_key]
service_key = self._get_service_key(service)
if self._services.has_key(service_key):
if self._valid:
self._dbus_helper.ServiceDisappeared(service.object_path())
del self._services[service_key]
if service.get_type() == PRESENCE_SERVICE_TYPE:
self._valid = False
self._dbus_helper.Disappeared()
if service.get_type() == PRESENCE_SERVICE_TYPE:
self._valid = False
self._dbus_helper.Disappeared()
def remove_activity(self, activity):
actid = activity.get_id()
if not self._activities.has_key(actid):
return
del self._activities[actid]
if activity.is_valid():
self._dbus_helper.LeftActivity(activity.object_path())
def remove_activity(self, activity):
actid = activity.get_id()
if not self._activities.has_key(actid):
return
del self._activities[actid]
if activity.is_valid():
self._dbus_helper.LeftActivity(activity.object_path())
# If we just removed the buddy's current activity,
# send out a signal
if actid == self._current_activity:
self._current_activity = None
self._dbus_helper.CurrentActivityChanged([])
# If we just removed the buddy's current activity,
# send out a signal
if actid == self._current_activity:
self._current_activity = None
self._dbus_helper.CurrentActivityChanged([])
def get_joined_activities(self):
acts = []
for act in self._activities.values():
if act.is_valid():
acts.append(act)
return acts
def get_joined_activities(self):
acts = []
for act in self._activities.values():
if act.is_valid():
acts.append(act)
return acts
def get_service_of_type(self, stype, activity=None):
"""Return a service of a certain type, or None if the buddy
doesn't provide that service."""
if not stype:
raise RuntimeError("Need to specify a service type.")
def get_service_of_type(self, stype, activity=None):
"""Return a service of a certain type, or None if the buddy
doesn't provide that service."""
if not stype:
raise RuntimeError("Need to specify a service type.")
if activity and not activity.is_valid():
raise RuntimeError("Activity is not yet valid.")
if activity and not activity.is_valid():
raise RuntimeError("Activity is not yet valid.")
if activity:
key = (stype, activity.get_id())
else:
key = (stype, None)
if self._services.has_key(key):
return self._services[key]
return None
if activity:
key = (stype, activity.get_id())
else:
key = (stype, None)
if self._services.has_key(key):
return self._services[key]
return None
def is_valid(self):
"""Return whether the buddy is valid or not. A buddy is
not valid until its official presence service has been found
and successfully resolved."""
return self._valid
def is_valid(self):
"""Return whether the buddy is valid or not. A buddy is
not valid until its official presence service has been found
and successfully resolved."""
return self._valid
def get_icon(self):
"""Return the buddies icon, if any."""
return self._icon
def get_address(self):
return self._address
def get_icon(self):
"""Return the buddies icon, if any."""
return self._icon
def get_address(self):
return self._address
def get_name(self):
return self._nick_name
def get_name(self):
return self._nick_name
def get_color(self):
return self._color
def get_color(self):
return self._color
def get_current_activity(self):
if not self._current_activity:
return None
if not self._activities.has_key(self._current_activity):
return None
return self._activities[self._current_activity]
def get_current_activity(self):
if not self._current_activity:
return None
if not self._activities.has_key(self._current_activity):
return None
return self._activities[self._current_activity]
def _set_icon(self, icon):
"""Can only set icon for other buddies. The Owner
takes care of setting it's own icon."""
if icon != self._icon:
self._icon = icon
self._dbus_helper.IconChanged()
def _set_icon(self, icon):
"""Can only set icon for other buddies. The Owner
takes care of setting it's own icon."""
if icon != self._icon:
self._icon = icon
self._dbus_helper.IconChanged()
def is_owner(self):
return False
def is_owner(self):
return False
class Owner(Buddy):
"""Class representing the owner of the machine. This is the client
portion of the Owner, paired with the server portion in Owner.py."""
def __init__(self, ps, bus_name, object_id, icon_cache):
Buddy.__init__(self, bus_name, object_id, None, icon_cache)
self._nick_name = profile.get_nick_name()
self._color = profile.get_color()
self._ps = ps
"""Class representing the owner of the machine. This is the client
portion of the Owner, paired with the server portion in Owner.py."""
def __init__(self, ps, bus_name, object_id, icon_cache):
Buddy.__init__(self, bus_name, object_id, None, icon_cache)
self._nick_name = profile.get_nick_name()
self._color = profile.get_color()
self._ps = ps
def add_service(self, service):
"""Adds a new service to this buddy's service list, returning
True if the service was successfully added, and False if it was not."""
if service.get_name() != self._nick_name:
logging.error("Service and buddy nick names doesn't match: " \
"%s %s" % (service.get_name(), self._nick_name))
return False
def add_service(self, service):
"""Adds a new service to this buddy's service list, returning
True if the service was successfully added, and False if it was not."""
if service.get_name() != self._nick_name:
logging.error("Service and buddy nick names doesn't match: " \
"%s %s" % (service.get_name(), self._nick_name))
return False
# The Owner initially doesn't have an address, so the first
# service added to the Owner determines the owner's address
source_addr = service.get_source_address()
if self._address is None and service.is_local():
self._address = source_addr
self._dbus_helper.PropertyChanged(['ip4_address'])
# The Owner initially doesn't have an address, so the first
# service added to the Owner determines the owner's address
source_addr = service.get_source_address()
if self._address is None and service.is_local():
self._address = source_addr
self._dbus_helper.PropertyChanged(['ip4_address'])
# The owner bypasses address checks and only cares if
# avahi says the service is a local service
if not service.is_local():
logging.error("Cannot add remote service to owner object.")
return False
# The owner bypasses address checks and only cares if
# avahi says the service is a local service
if not service.is_local():
logging.error("Cannot add remote service to owner object.")
return False
logging.debug("Adding owner service %s.%s at %s:%d." % (service.get_name(),
service.get_type(), service.get_source_address(),
service.get_port()))
return self._internal_add_service(service)
logging.debug("Adding owner service %s.%s at %s:%d." % (service.get_name(),
service.get_type(), service.get_source_address(),
service.get_port()))
return self._internal_add_service(service)
def is_owner(self):
return True
def is_owner(self):
return True
#################################################################
@@ -468,62 +468,62 @@ import Service
__objid_seq = 0
def _next_objid():
global __objid_seq
__objid_seq = __objid_seq + 1
return __objid_seq
global __objid_seq
__objid_seq = __objid_seq + 1
return __objid_seq
class BuddyTestCase(unittest.TestCase):
_DEF_NAME = u"Tommy"
_DEF_STYPE = unicode(PRESENCE_SERVICE_TYPE)
_DEF_DOMAIN = u"local"
_DEF_ADDRESS = u"1.1.1.1"
_DEF_PORT = 1234
_DEF_NAME = u"Tommy"
_DEF_STYPE = unicode(PRESENCE_SERVICE_TYPE)
_DEF_DOMAIN = u"local"
_DEF_ADDRESS = u"1.1.1.1"
_DEF_PORT = 1234
def __init__(self, name):
self._bus = dbus.SessionBus()
self._bus_name = dbus.service.BusName('org.laptop.Presence', bus=self._bus)
unittest.TestCase.__init__(self, name)
def __init__(self, name):
self._bus = dbus.SessionBus()
self._bus_name = dbus.service.BusName('org.laptop.Presence', bus=self._bus)
unittest.TestCase.__init__(self, name)
def __del__(self):
del self._bus_name
del self._bus
def __del__(self):
del self._bus_name
del self._bus
def _test_init_fail(self, service, fail_msg):
"""Test something we expect to fail."""
try:
objid = _next_objid()
buddy = Buddy(self._bus_name, objid, service, owner=False)
except ValueError, exc:
pass
else:
self.fail("expected a ValueError for %s." % fail_msg)
def _test_init_fail(self, service, fail_msg):
"""Test something we expect to fail."""
try:
objid = _next_objid()
buddy = Buddy(self._bus_name, objid, service, owner=False)
except ValueError, exc:
pass
else:
self.fail("expected a ValueError for %s." % fail_msg)
def testService(self):
service = None
self._test_init_fail(service, "invalid service")
def testService(self):
service = None
self._test_init_fail(service, "invalid service")
def testGoodInit(self):
objid = _next_objid()
service = Service.Service(self._bus_name, objid, self._DEF_NAME, self._DEF_STYPE, self._DEF_DOMAIN,
self._DEF_ADDRESS, self._DEF_PORT)
objid = _next_objid()
buddy = Buddy(self._bus_name, objid, service)
assert buddy.get_name() == self._DEF_NAME, "buddy name wasn't correct after init."
assert buddy.get_address() == self._DEF_ADDRESS, "buddy address wasn't correct after init."
assert buddy.object_path() == BUDDY_DBUS_OBJECT_PATH + str(objid)
def testGoodInit(self):
objid = _next_objid()
service = Service.Service(self._bus_name, objid, self._DEF_NAME, self._DEF_STYPE, self._DEF_DOMAIN,
self._DEF_ADDRESS, self._DEF_PORT)
objid = _next_objid()
buddy = Buddy(self._bus_name, objid, service)
assert buddy.get_name() == self._DEF_NAME, "buddy name wasn't correct after init."
assert buddy.get_address() == self._DEF_ADDRESS, "buddy address wasn't correct after init."
assert buddy.object_path() == BUDDY_DBUS_OBJECT_PATH + str(objid)
def addToSuite(suite):
suite.addTest(BuddyTestCase("testService"))
suite.addTest(BuddyTestCase("testGoodInit"))
addToSuite = staticmethod(addToSuite)
def addToSuite(suite):
suite.addTest(BuddyTestCase("testService"))
suite.addTest(BuddyTestCase("testGoodInit"))
addToSuite = staticmethod(addToSuite)
def main():
suite = unittest.TestSuite()
BuddyTestCase.addToSuite(suite)
runner = unittest.TextTestRunner()
runner.run(suite)
suite = unittest.TestSuite()
BuddyTestCase.addToSuite(suite)
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == "__main__":
main()
main()
+49 -49
View File
@@ -19,59 +19,59 @@ from sugar import env
from sugar import util
class BuddyIconCache(object):
"""Caches icons on disk and finds them based on md5 hash."""
def __init__(self):
ppath = env.get_profile_path()
self._cachepath = os.path.join(ppath, "cache", "buddy-icons")
if not os.path.exists(self._cachepath):
os.makedirs(self._cachepath)
"""Caches icons on disk and finds them based on md5 hash."""
def __init__(self):
ppath = env.get_profile_path()
self._cachepath = os.path.join(ppath, "cache", "buddy-icons")
if not os.path.exists(self._cachepath):
os.makedirs(self._cachepath)
self._cache = {}
self._cache = {}
# Read all cached icons and their sums
for fname in os.listdir(self._cachepath):
m = md5.new()
data = self._get_icon_data(fname)
if len(data) == 0:
continue
m.update(data)
printable_hash = util.printable_hash(m.digest())
self._cache[printable_hash] = fname
del m
# Read all cached icons and their sums
for fname in os.listdir(self._cachepath):
m = md5.new()
data = self._get_icon_data(fname)
if len(data) == 0:
continue
m.update(data)
printable_hash = util.printable_hash(m.digest())
self._cache[printable_hash] = fname
del m
def _get_icon_data(self, fname):
fd = open(os.path.join(self._cachepath, fname), "r")
data = fd.read()
fd.close()
del fd
return data
def _get_icon_data(self, fname):
fd = open(os.path.join(self._cachepath, fname), "r")
data = fd.read()
fd.close()
del fd
return data
def get_icon(self, printable_hash):
if not isinstance(printable_hash, unicode):
raise RuntimeError("printable_hash must be a unicode string.")
try:
fname = self._cache[printable_hash]
return self._get_icon_data(fname)
except KeyError:
pass
return None
def get_icon(self, printable_hash):
if not isinstance(printable_hash, unicode):
raise RuntimeError("printable_hash must be a unicode string.")
try:
fname = self._cache[printable_hash]
return self._get_icon_data(fname)
except KeyError:
pass
return None
def add_icon(self, icon_data):
if len(icon_data) == 0:
return
def add_icon(self, icon_data):
if len(icon_data) == 0:
return
m = md5.new()
m.update(icon_data)
printable_hash = util.printable_hash(m.digest())
if self._cache.has_key(printable_hash):
del m
return
m = md5.new()
m.update(icon_data)
printable_hash = util.printable_hash(m.digest())
if self._cache.has_key(printable_hash):
del m
return
# Write the icon to disk and add an entry to our cache for it
m.update(time.asctime())
fname = util.printable_hash(m.digest())
fd = open(os.path.join(self._cachepath, fname), "w")
fd.write(icon_data)
fd.close()
self._cache[printable_hash] = fname
del m
# Write the icon to disk and add an entry to our cache for it
m.update(time.asctime())
fname = util.printable_hash(m.digest())
fd = open(os.path.join(self._cachepath, fname), "w")
fd.write(icon_data)
fd.close()
self._cache[printable_hash] = fname
del m
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff