def create_profile(name, color=None): if not color: color = XoColor() client = gconf.client_get_default() client.set_string('/desktop/sugar/user/nick', name) client.set_string('/desktop/sugar/user/color', color.to_string()) client.suggest_sync() if profile.get_pubkey() and profile.get_profile().privkey_hash: logging.info('Valid key pair found, skipping generation.') return # Generate keypair import commands keypath = os.path.join(env.get_profile_path(), 'owner.key') if os.path.exists(keypath): os.rename(keypath, keypath + '.broken') logging.warning('Existing private key %s moved to %s.broken', keypath, keypath) if os.path.exists(keypath + '.pub'): os.rename(keypath + '.pub', keypath + '.pub.broken') logging.warning('Existing public key %s.pub moved to %s.pub.broken', keypath, keypath) cmd = "ssh-keygen -q -t dsa -f %s -C '' -N ''" % (keypath, ) (s, o) = commands.getstatusoutput(cmd) if s != 0: logging.error('Could not generate key pair: %d %s', s, o)
def __init__(self): BaseBuddyModel.__init__(self) client = gconf.client_get_default() self.props.nick = client.get_string('/desktop/sugar/user/nick') color = client.get_string('/desktop/sugar/user/color') self.props.color = XoColor(color) self.props.key = get_profile().pubkey self.connect('notify::nick', self.__property_changed_cb) self.connect('notify::color', self.__property_changed_cb) bus = dbus.SessionBus() bus.add_signal_receiver( self.__name_owner_changed_cb, signal_name='NameOwnerChanged', dbus_interface='org.freedesktop.DBus') bus_object = bus.get_object(dbus.BUS_DAEMON_NAME, dbus.BUS_DAEMON_PATH) for service in bus_object.ListNames( dbus_interface=dbus.BUS_DAEMON_IFACE): if service.startswith(CONNECTION + '.'): path = '/%s' % service.replace('.', '/') Connection(service, path, bus, ready_handler=self.__connection_ready_cb)
def _get_published_name(self): """Construct the published name based on the public key Limit the name to be only 8 characters maximum. The avahi service name has a 64 character limit. It consists of the room name, the published name and the host name. """ public_key_hash = sha1(get_profile().pubkey).hexdigest() return public_key_hash[:8]
def _seed_xs_cookie(): ''' Create a HTTP Cookie to authenticate with the Schoolserver ''' client = gconf.client_get_default() backup_url = client.get_string('/desktop/sugar/backup_url') if not backup_url: _logger.debug('seed_xs_cookie: Not registered with Schoolserver') return jabber_server = client.get_string( '/desktop/sugar/collaboration/jabber_server') pubkey = profile.get_profile().pubkey cookie_data = {'color': profile.get_color().to_string(), 'pkey_hash': sha.new(pubkey).hexdigest()} db_path = os.path.join(_profile_path, 'cookies.sqlite') try: cookies_db = sqlite3.connect(db_path) c = cookies_db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS moz_cookies (id INTEGER PRIMARY KEY, name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER, isSecure INTEGER, isHttpOnly INTEGER)''') c.execute('''SELECT id FROM moz_cookies WHERE name=? AND host=? AND path=?''', ('xoid', jabber_server, '/')) if c.fetchone(): _logger.debug('seed_xs_cookie: Cookie exists already') return expire = int(time.time()) + 10*365*24*60*60 c.execute('''INSERT INTO moz_cookies (name, value, host, path, expiry, lastAccessed, isSecure, isHttpOnly) VALUES(?,?,?,?,?,?,?,?)''', ('xoid', cjson.encode(cookie_data), jabber_server, '/', expire, 0, 0, 0 )) cookies_db.commit() cookies_db.close() except sqlite3.Error, e: _logger.error('seed_xs_cookie: %s' % e)
def register_laptop(url=_REGISTER_URL): profile = get_profile() client = gconf.client_get_default() if _have_ofw_tree(): sn = _read_mfg_data(os.path.join(_OFW_TREE, _MFG_SN)) uuid_ = _read_mfg_data(os.path.join(_OFW_TREE, _MFG_UUID)) elif _have_proc_device_tree(): sn = _read_mfg_data(os.path.join(_PROC_TREE, _MFG_SN)) uuid_ = _read_mfg_data(os.path.join(_PROC_TREE, _MFG_UUID)) else: sn = _generate_serial_number() uuid_ = str(uuid.uuid1()) sn = sn or 'SHF00000000' uuid_ = uuid_ or '00000000-0000-0000-0000-000000000000' setting_name = '/desktop/sugar/collaboration/jabber_server' jabber_server = client.get_string(setting_name) _store_identifiers(sn, uuid_, jabber_server) if jabber_server: url = 'http://' + jabber_server + ':8080/' nick = client.get_string('/desktop/sugar/user/nick') if sys.hexversion < 0x2070000: server = xmlrpclib.ServerProxy(url, _TimeoutTransport()) else: socket.setdefaulttimeout(_REGISTER_TIMEOUT) server = xmlrpclib.ServerProxy(url) try: data = server.register(sn, nick, uuid_, profile.pubkey) except (xmlrpclib.Error, TypeError, socket.error): logging.exception('Registration: cannot connect to server') raise RegisterError(_('Cannot connect to the server.')) finally: socket.setdefaulttimeout(None) if data['success'] != 'OK': logging.error('Registration: server could not complete request: %s', data['error']) raise RegisterError(_('The server could not complete the request.')) client.set_string('/desktop/sugar/collaboration/jabber_server', data['jabberserver']) client.set_string('/desktop/sugar/backup_url', data['backupurl']) return True
def check_profile(): profile = get_profile() path = os.path.join(os.path.expanduser('~/.sugar'), 'debug') if not os.path.exists(path): profile.create_debug_file() path = os.path.join(env.get_profile_path(), 'config') if os.path.exists(path): profile.convert_profile() if not profile.is_valid(): win = IntroWindow() win.show_all() gtk.main()
def __init__(self, ps, bus): """Initialize the ShellOwner instance ps -- presenceservice.PresenceService object bus -- a connection to the D-Bus session bus Retrieves initial property values from the profile module. Loads the buddy icon from file as well. XXX note: no error handling on that calls GenericOwner.__init__ """ client = gconf.client_get_default() profile = get_profile() key_hash = profile.privkey_hash key = profile.pubkey color = client.get_string("/desktop/sugar/user/color") tags = client.get_string("/desktop/sugar/user/tags") nick = client.get_string("/desktop/sugar/user/nick") if not isinstance(nick, unicode): nick = unicode(nick, 'utf-8') GenericOwner.__init__(self, ps, bus, 'keyid/' + psutils.pubkey_to_keyid(key), key=key, nick=nick, color=color, icon=None, key_hash=key_hash, tags=tags) # Ask to get notifications on Owner object property changes in the # shell. If it's not currently running, no problem - we'll get the # signals when it does run for (signal, cb) in (('IconChanged', self._icon_changed_cb), ('ColorChanged', self._color_changed_cb), ('NickChanged', self._nick_changed_cb), ('TagsChanged', self._tags_changed_cb), ('CurrentActivityChanged', self._cur_activity_changed_cb)): self._bus.add_signal_receiver(cb, signal_name=signal, dbus_interface=self._SHELL_OWNER_INTERFACE, bus_name=self._SHELL_SERVICE, path=self._SHELL_PATH) # we already know our own nick, color, key self._awaiting = None
def _ensure_server_account(self, account_paths): for account_path in account_paths: if 'gabble' in account_path: logging.debug('Already have a Gabble account') account = _Account(account_path) account.enable() return account logging.debug('Still dont have a Gabble account, creating one') client = gconf.client_get_default() nick = client.get_string('/desktop/sugar/user/nick') server = client.get_string('/desktop/sugar/collaboration' '/jabber_server') key_hash = get_profile().privkey_hash params = { 'account': self._get_jabber_account_id(), 'password': key_hash, 'server': server, 'resource': 'sugar', 'require-encryption': True, 'ignore-ssl-errors': True, 'register': True, 'old-ssl': True, 'port': dbus.UInt32(5223), } properties = { ACCOUNT + '.Enabled': True, ACCOUNT + '.Nickname': nick, ACCOUNT + '.ConnectAutomatically': True, } bus = dbus.Bus() obj = bus.get_object(ACCOUNT_MANAGER_SERVICE, ACCOUNT_MANAGER_PATH) account_manager = dbus.Interface(obj, ACCOUNT_MANAGER) account_path = account_manager.CreateAccount('gabble', 'jabber', 'jabber', params, properties) return _Account(account_path)
def __init__(self,handle): activity.Activity.__init__(self,handle) self._name = handle self.set_title( 'graph' ) # Attach sugar toolbox toolbox = activity.ActivityToolbox( self ) self.set_toolbox( toolbox ) toolbox.show() # Create the main container self._main_view = gtk.VBox() # Read the user's profile prof = profile.get_profile() # Import our class and load it self.graph = Graph() # Setup the color scheme c1 = profile.get_color().get_fill_color() c2 = profile.get_color().get_stroke_color() #self.graph.set_colors( c1, c2 ) # Remove the widget's parent if self.graph.widget.parent: self.graph.widget.parent.remove( self.graph.widget ) # Attach the widget to our window self._main_view.pack_start( self.graph.widget ) # Display everything self.graph.widget.show() self._main_view.show() self.set_canvas( self._main_view ) self.show_all()
def _get_jabber_account_id(self): public_key_hash = sha1(get_profile().pubkey).hexdigest() client = gconf.client_get_default() server = client.get_string('/desktop/sugar/collaboration' '/jabber_server') return '%s@%s' % (public_key_hash, server)
def main(): gobject.idle_add(_shell_started_cb) logsmanager.setup() logger.start('shell') _save_session_info() _start_matchbox() _setup_translations() hw_manager = hardwaremanager.get_manager() hw_manager.startup() icons_path = os.path.join(config.data_path, 'icons') gtk.icon_theme_get_default().append_search_path(icons_path) # Do initial setup if needed if not get_profile().is_valid(): win = intro.IntroWindow() win.show_all() gtk.main() if os.environ.has_key("SUGAR_TP_DEBUG"): # Allow the user time to start up telepathy connection managers # using the Sugar DBus bus address import time from telepathy.client import ManagerRegistry registry = ManagerRegistry() registry.LoadManagers() debug_flags = os.environ["SUGAR_TP_DEBUG"].split(',') for cm_name in debug_flags: if cm_name not in ["gabble", "salut"]: continue try: cm = registry.services[cm_name] except KeyError: print RuntimeError("%s connection manager not found!" % cm_name) while not check_cm(cm['busname']): print "Waiting for %s on: DBUS_SESSION_BUS_ADDRESS=%s" % \ (cm_name, os.environ["DBUS_SESSION_BUS_ADDRESS"]) try: time.sleep(5) except KeyboardInterrupt: print "Got Ctrl+C, continuing..." break model = ShellModel() shell = Shell(model) service = ShellService(shell) if os.environ.has_key("SUGARBOT_EMULATOR"): sys.path.append(os.environ['SUGARBOT_PATH']) from sugarbotlauncher import SugarbotLauncher sbLauncher = SugarbotLauncher(shell, model) try: gtk.main() except KeyboardInterrupt: print 'Ctrl+C pressed, exiting...' session_info_file = os.path.join(env.get_profile_path(), "session.info") os.remove(session_info_file)
def __init__(self, handle): #handle object contains command line inputs to this activity self.handle = handle _logger.debug('Activity id:%s.Object id: %s. uri:%s' % (handle.activity_id, handle.object_id, handle.uri)) self.passed_in_ds_object = None if handle.object_id and handle.object_id != '': self.passed_in_ds_object = datastore.get(handle.object_id) if self.passed_in_ds_object: d = self.passed_in_ds_object.metadata #log_dict(d,'initial datastore metadata ==>:') else: ds_object = self.get_new_dsobject() if hasattr(ds_object, 'get_object_id'): handle.object_id = ds_object.get_object_id() else: handle.object_id = ds_object.object_id _logger.debug( 'no initial datastore object id passed in via handle') #Save a global poiinter so remote procedure calls can communicate with pydebug global pydebug_instance pydebug_instance = self start_clock = time.clock() #init variables self.make_paths() self.save_icon_clicked = False self.source_directory = None self.data_file = None self.help = None self.help_x11 = None self.dirty = False self.sock = None #self.last_filename = None self.debug_dict = {} self.activity_dict = {} self.manifest_treeview = None #set up to recognize an re-display of playpen #self.set_title(_('PyDebug Activity')) self.ds = None #datastore pointer self._logger = _logger self.traceback = 'Context' self.abandon_changes = False self.delete_after_load = None self.find_window = None self.icon_outline = 'icon_square' self.icon_window = None self.last_icon_file = None self.activity_data_changed = False self.icon_basename = None #sugar 0.82 has a different way of getting colors and dies during init unless the following self.profile = profile.get_profile() self.profile.color = XoColor() #get the persistent data across all debug sessions and start using it self.get_config() #give the server a chance to get started so terminal can connect to it self.non_blocking_server() #glib.idle_add(self.non_blocking_server) """ if self.request_new_jobject and self.debug_dict.get('jobject_id','') != '': self.request_new_jobject = False #keep on using the same journal entry if self.debug_dict.get('jobject_id','') != '': handle.object_id = self.debug_dict.get('jobject_id','') """ # init the Classes we are subclassing _logger.debug('about to init superclass activity. Elapsed time: %f'%\ (time.clock()-start_clock)) Activity.__init__(self, handle, create_jobject=False) """ if self.request_new_jobject: #check to see if the object was created if self._jobject: self.debug_dict['jobject_id'] = str(self._jobject.object_id) else: _logger.debug('failed to create jobject in Activity.__init__') """ self.connect('realize', self.realize_cb) self.accelerator = gtk.AccelGroup() self.add_accel_group(self.accelerator) #set up the PANES for the different functions of the debugger _logger.debug('about to set up Menu panes. Elapsed time: %f' % (time.clock() - start_clock)) self.panes = {} PANES = ['TERMINAL', 'EDITOR', 'PROJECT', 'HELP'] for i in range(len(PANES)): self.panes[PANES[i]] = i #toolbox needs to be available during init of modules self.toolbox = pytoolbar.ActivityToolbox(self) self.toolbox.connect_after('current_toolbar_changed', self._toolbar_changed_cb) self.toolbox.set_current_toolbar(self.panes['TERMINAL']) ######################################################################################### #init the sub functions TerminalGui.__init__(self, self, self.toolbox) EditorGui.__init__(self, self) ProjectGui.__init__(self, self) self.help = Help(self) self.util = Utilities(self) ######################################################################################### #if first time run on this machine, set up home directory if not os.path.isfile(os.path.join(self.debugger_home, '.bashrc')): self.setup_home_directory() # setup the search options self.s_opts = SearchOptions( where=S_WHERE.file, use_regex=False, ignore_caps=True, replace_all=False, #defaults to avoid creating #a new SearchOptions object for normal searches #should never be changed, just make a copy like: #SearchOptions(self.s_opts, forward=False) forward=True, stay=False) self.safe_to_replace = False #get the sugar version (major, minor, micro, release) = self._activity.util.sugar_version() _logger.debug('sugar version major:%s minor:%s micro:%s release:%s' % (major, minor, micro, release)) if not minor: minor = 70 self.sugar_minor = minor ######################################################################################### _logger.debug( 'All app objects created. about to set up Display . Elapsed time: %f' % (time.clock() - start_clock)) self.canvas_list = [] self.canvas_list.append(self._get_terminal_canvas()) self.canvas_list.append(self._get_edit_canvas()) self.canvas_list.append(self._get_project_canvas()) self.canvas_list.append(self._get_help_canvas()) nb = gtk.Notebook() nb.show() nb.set_show_tabs(False) for c in self.canvas_list: nb.append_page(c) self.pydebug_notebook = nb #the following call to the activity code puts our notebook under the stock toolbar self.set_canvas(nb) helpbar = self.help.get_help_toolbar() self.toolbox.add_toolbar(_('Edit'), self.get_editbar()) self.toolbox.add_toolbar(_('Project'), self.get_projectbar()) self.toolbox.add_toolbar(_('Help'), self.help.get_help_toolbar()) self.set_toolbox(self.toolbox) self.toolbox.show() #set which PANE is visible initially self.set_visible_canvas(self.panes['PROJECT']) self.set_toolbar(self.panes['PROJECT']) _logger.debug('about to setup_project_page. Elapsed time: %f' % (time.clock() - start_clock)) self.setup_project_page() _logger.debug( 'about Returned from setup_project_page. Elapsed time: %f' % (time.clock() - start_clock)) #get the journal datastore information and resume previous activity #self.metadata = self.ds if self.passed_in_ds_object and self.passed_in_ds_object.get_file_path( ): ds_file = self.passed_in_ds_object.get_file_path() else: ds_file = '' _logger.debug('about to call read routine Elapsed time: %f' % (time.clock() - start_clock)) self.read_file(ds_file) _logger.debug('about (end of init) Elapsed time: %f' % (time.clock() - start_clock))
os.environ['SUGAR_BUNDLE_ID'] = bundle_id if version and version >= 0.839: #do 0.84 stuff cmd_args = activityfactory.get_command(bundle_info) else: from sugar.activity.registry import get_registry registry = get_registry() registry.add_bundle(child_path) activity_list = registry.find_activity(bundle_id) if len(activity_list) == 0: _logger.error('Activity %s not found'%bundle_id) print 'Activity %s not found'%bundle_id exit(1) cmd_args = activityfactory.get_command(activity_list[0]) myprofile = profile.get_profile() myprofile.color = XoColor() _logger.debug('command args:%r'%cmd_args) #need to get activity root, but activity bases off of HOME which some applications need to change #following will not work if storage system changes with new OS #required because debugger needs to be able to change home so that foreign apps will work activity_root = os.path.join('/home/olpc/.sugar/default/',bundle_id) os.environ['SUGAR_ACTIVITY_ROOT'] = activity_root _logger.debug('sugar_activity_root set to %s'%activity_root) #sugar makes the activity directories, so we need to also #put this in a try block, so that if permissions reject operation, we don't die try: if not os.path.isdir(activity_root):