def __init__(self): if CouchDatabase: self.db = sqlite3.connect(SQLITE_DB_FILENAME) sqlite_accounts = json.loads(self.List()) try: accounts = CouchDatabase(COUCH_DB_ACCOUNTS, create=False) records = accounts.get_records() except NoSuchDatabase: log.logger.info("Nothing to migrate from desktopcouch") return migrate = {} log.logger.info("Looking for accounts to migrate from desktopcouch to sqlite") for record in records: id = str(record["value"]["protocol"] + "-" + record["value"]["username"]) migrate[id] = True if len(sqlite_accounts) > 0: for sqlite_account in sqlite_accounts: if record["value"]["protocol"] == sqlite_account["service"] and record["value"]["username"] == sqlite_account["username"]: migrate[id] = False if migrate[id]: new_account = {} new_account["service"] = record["value"]["protocol"] new_account["id"] = record["value"]["_id"] for param in SERVICES[record["value"]["protocol"]]["config"]: key = param.replace('private:','') new_account[key] = record["value"][key] log.logger.info("Found account %s - %s that needs to be migrated", new_account["service"], new_account["username"]) self.Create(json.dumps(new_account))
def __init__(self): if CouchDatabase: self.gwibber = GwibberPublic() sqlite_accounts = json.loads(self.gwibber.GetAccounts()) try: accounts = CouchDatabase(COUCH_DB_ACCOUNTS, create=False) records = accounts.get_records() except NoSuchDatabase: logger.info("Nothing to migrate from desktopcouch") return migrate = {} needs_auth = [] logger.info("Looking for accounts to migrate from desktopcouch to sqlite") for record in records: id = str(record["value"]["protocol"] + "-" + record["value"]["username"]) migrate[id] = True if len(sqlite_accounts) > 0: for sqlite_account in sqlite_accounts: if record["value"]["protocol"] == sqlite_account["service"] and record["value"]["username"] == sqlite_account["username"]: migrate[id] = False if not SERVICES.has_key(record["value"]["protocol"]): migrate[id] = False if migrate[id]: new_account = {} new_account["service"] = record["value"]["protocol"] new_account["id"] = record["value"]["_id"] for param in SERVICES[record["value"]["protocol"]]["config"]: key = param.replace('private:','') new_account[key] = record["value"].get(key, None) if key == "access_token" and record["value"].has_key("secret_key"): new_account[key] = record["value"]["secret_key"] if (key == "secret_token" or key == "access_token") and new_account[key] is None and new_account["id"] not in needs_auth: needs_auth.append (new_account["id"]) if key == "uid" and new_account[key] is None and new_account["id"] not in needs_auth: needs_auth.append (new_account["id"]) logger.info("Found account %s - %s that needs to be migrated", new_account["service"], new_account["username"]) self.gwibber.accounts.Create(json.dumps(new_account)) logger.debug("ACCOUNTS NEED RE-AUTH: %s", needs_auth) if len(needs_auth) > 0: cmd = [] cmd.append ("-a") cmd.append (string.join (needs_auth, ",")) cmd.append ("-c") cmd.append ("info") cmd.append ("-m") cmd.append (_("Authorize")) if os.path.exists (os.path.join ("bin", "gwibber-accounts")): cmd.insert (0, os.path.join ("bin", "gwibber-accounts")) else: cmd.insert (0, "gwibber-accounts") process = subprocess.Popen (cmd)
class User_dict(dict): ''' a dictionary with extra methods: persistence: load, save and db_connect gobject signals: connect and emit. Don't use this directly. Please use the preferences instance.''' def __init__(self, *args, **kwds): dict.__init__(self, *args, **kwds) # Set up couchdb. self._db_name = "ubuntu-pomadoro-tasks" self._key = None self._database = None self._record_type = ( "http://wiki.ubuntu.com/Quickly/RecordTypes/UbuntuPomadoroTasks/" "Preferences") class Publisher(gtk.Invisible): # pylint: disable=R0904 '''set up signals in a separate class gtk.Invisible has 230 public methods''' __gsignals__ = {'changed' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)), 'loaded' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,))} publisher = Publisher() self.emit = publisher.emit self.connect = publisher.connect def db_connect(self): '''connect to couchdb create if necessary''' # logging.basicConfig will be called now self._database = CouchDatabase(self._db_name, create=True) def save(self): 'save to couchdb' self._database.update_fields(self._key, self) def load(self): 'load from couchdb' self.update({"record_type": self._record_type}) results = self._database.get_records( record_type=self._record_type, create_view=True) if len(results.rows) == 0: # No preferences have ever been saved # save them before returning. self._key = self._database.put_record(Record(self)) else: self.update(results.rows[0].value) del self['_rev'] self._key = results.rows[0].value["_id"] self.emit('loaded', None) def update(self, *args, **kwds): ''' interface for dictionary send changed signal when appropriate ''' # parse args new_data = {} new_data.update(*args, **kwds) changed_keys = [] for key in new_data.keys(): if new_data.get(key) != dict.get(self, key): changed_keys.append(key) dict.update(self, new_data) if changed_keys: self.emit('changed', tuple(changed_keys)) def __setitem__(self, key, value): ''' interface for dictionary send changed signal when appropriate ''' if value != dict.get(self, key): dict.__setitem__(self, key, value) self.emit('changed', (key,))
# [SNIPPET_LICENSE: GPL] from desktopcouch.records.server import CouchDatabase from desktopcouch.records.record import Record #First, we want to put a record into a database and then get it out #create the database db = CouchDatabase("fetchrecordsexample", create=True) #Create some records record_type = "http://example.com/fetch-record-type.html" new_record = Record({"afield" : "a value", "anotherfield" : "another value"}, record_type) another_record = Record({"afield" : "some value", "anotherfield" : "some other value"}, record_type) #put our new records into the datbase db.put_record(new_record) db.put_record(another_record) #Fetch all the records in the database and display them results = db.get_records(record_type = record_type, create_view = True) for records in results: record = records.value print "a field: %s" % record["afield"] print "another field: %s" % record["anotherfield"]
class PreferencesCalculatorDialog(gtk.Dialog): __gtype_name__ = "PreferencesCalculatorDialog" preferences = {} def __new__(cls): """Special static method that's automatically called by Python when constructing a new instance of this class. Returns a fully instantiated PreferencesCalculatorDialog object. """ builder = get_builder("PreferencesCalculatorDialog") new_object = builder.get_object("preferences_calculator_dialog") new_object.finish_initializing(builder) return new_object def finish_initializing(self, builder): """Called while initializing this instance in __new__ finish_initalizing should be called after parsing the ui definition and creating a PreferencesCalculatorDialog object with it in order to finish initializing the start of the new PerferencesCalculatorDialog instance. Put your initialization code in here and leave __init__ undefined. """ # Get a reference to the builder and set up the signals. self.builder = builder self.builder.connect_signals(self) # Set up couchdb and the preference info. self._db_name = "calculator" self._database = CouchDatabase(self._db_name, create=True) self._preferences = None self._key = None # Set the record type and then initalize the preferences. self._record_type = "http://wiki.ubuntu.com/Quickly/RecordTypes/Calculator/" "Preferences" self._preferences = self.get_preferences() # TODO: code for other initialization actions should be added here def get_preferences(self): """Return a dict of preferences for calculator. Creates a couchdb record if necessary. """ if self._preferences == None: # The dialog is initializing. self._load_preferences() # If there were no saved preference, this. return self._preferences def _load_preferences(self): # TODO: add preferences to the self._preferences dict default # preferences that will be overwritten if some are saved self._preferences = {"record_type": self._record_type} results = self._database.get_records(record_type=self._record_type, create_view=True) if len(results.rows) == 0: # No preferences have ever been saved, save them before returning. self._key = self._database.put_record(Record(self._preferences)) else: self._preferences = results.rows[0].value del self._preferences["_rev"] self._key = results.rows[0].value["_id"] def _save_preferences(self): self._database.update_fields(self._key, self._preferences) def ok(self, widget, data=None): """The user has elected to save the changes. Called before the dialog returns gtk.RESONSE_OK from run(). """ # Make any updates to self._preferences here. e.g. # self._preferences["preference1"] = "value2" self._save_preferences() def cancel(self, widget, data=None): """The user has elected cancel changes. Called before the dialog returns gtk.RESPONSE_CANCEL for run() """ # Restore any changes to self._preferences here. pass
class PreferencesWiitrackerDialog(gtk.Dialog): __gtype_name__ = "PreferencesWiitrackerDialog" prefernces = {} def __init__(self): """__init__ - This function is typically not called directly. Creation of a PreferencesWiitrackerDialog requires redeading the associated ui file and parsing the ui definition extrenally, and then calling PreferencesWiitrackerDialog.finish_initializing(). Use the convenience function NewPreferencesWiitrackerDialog to create NewAboutWiitrackerDialog objects. """ pass def finish_initializing(self, builder): """finish_initalizing should be called after parsing the ui definition and creating a AboutWiitrackerDialog object with it in order to finish initializing the start of the new AboutWiitrackerDialog instance. """ #get a reference to the builder and set up the signals self.builder = builder self.builder.connect_signals(self) #set up couchdb and the preference info self.__db_name = "wiitracker" self.__database = CouchDatabase(self.__db_name, create=True) self.__preferences = None self.__key = None #set the record type and then initalize the preferences self.__record_type = "http://wiki.ubuntu.com/Quickly/RecordTypes/Wiitracker/Preferences" self.__preferences = self.get_preferences() #TODO:code for other initialization actions should be added here self.addressEntry = self.builder.get_object("AddressEntry") self.addressEntry.set_text(self.__preferences['wiiAddress']) self.dampingScale = self.builder.get_object("dampingScale") self.dampingScale.set_range(1, 100) self.dampingScale.set_value(self.__preferences['filterSize']) def get_preferences(self): """get_preferences -returns a dictionary object that contain preferences for wiitracker. Creates a couchdb record if necessary. """ if self.__preferences == None: #the dialog is initializing self.__load_preferences() #if there were no saved preference, this return self.__preferences def __load_preferences(self): #TODO: add prefernces to the self.__preferences dict #default preferences that will be overwritten if some are saved self.__preferences = {"record_type":self.__record_type, "wiiAddress": "00:17:AB:39:49:98", "filterSize": 15} results = self.__database.get_records(record_type=self.__record_type, create_view=True) # self.__key = self.__database.put_record(Record(self.__preferences)) if len(results.rows) == 0: #no preferences have ever been saved #save them before returning self.__key = self.__database.put_record(Record(self.__preferences)) else: self.__preferences = results.rows[0].value self.__key = results.rows[0].value["_id"] def __save_preferences(self): self.__database.update_fields(self.__key, self.__preferences) def ok(self, widget, data=None): """ok - The user has elected to save the changes. Called before the dialog returns gtk.RESONSE_OK from run(). """ #make any updates to self.__preferences here #self.__preferences["preference1"] = "value2" self.__preferences["wiiAddress"] = self.addressEntry.get_text() self.__preferences["filterSize"] = self.dampingScale.get_value() self.__save_preferences() def cancel(self, widget, data=None): """cancel - The user has elected cancel changes. Called before the dialog returns gtk.RESPONSE_CANCEL for run() """ #restore any changes to self.__preferences here pass
class JottyWindow(Window): __gtype_name__ = "JottyWindow" def finish_initializing(self, builder): """Set up the main window""" super(JottyWindow, self).finish_initializing(builder) self.AboutDialog = AboutJottyDialog self.PreferencesDialog = PreferencesJottyDialog # Code for other initialization actions should be added here. self.database = CouchDatabase("jotty", create=True) def on_mnu_save_activate(self, widget, data=None): #get the title for the note title = self.ui.entry1.get_text() #get the string buff = self.ui.textview1.get_buffer() start_iter = buff.get_start_iter() end_iter = buff.get_end_iter() text = buff.get_text(start_iter,end_iter) #get all the records record_type = "http://wiki.ubuntu.com/Quickly/JottyDoc" results = self.database.get_records(record_type = record_type, create_view = True) #update a record that has the same title for result in results: document = result.value if document["title"] == title: key = document["_id"] self.database.update_fields(key, {"text":text}) return #if no records had the title, create it new_rec = Record({"record_type":record_type, "title":title, "text":text}) self.database.put_record(new_rec) def on_mnu_open_activate(self, widget, data=None): #get the name of the document to open title = self.ui.entry1.get_text() text = "" #get all the records record_type = "http://wiki.ubuntu.com/Quickly/JottyDoc" results = self.database.get_records(record_type = record_type,create_view = True) #get the text if there is a matching title for result in results: document = result.value if document["title"] == title: text = document["text"] #set the UI to display the string buff = self.ui.textview1.get_buffer() buff.set_text(text) def on_mnu_new_activate(self, widget, data=None): self.ui.entry1.set_text("Note Title") buff = self.ui.textview1.get_buffer() buff.set_text("")
class PreferencesFooDialog(gtk.Dialog): __gtype_name__ = "PreferencesFooDialog" preferences = {} def __new__(cls): """Special static method that's automatically called by Python when constructing a new instance of this class. Returns a fully instantiated PreferencesFooDialog object. """ builder = get_builder('PreferencesFooDialog') new_object = builder.get_object("preferences_foo_dialog") new_object.finish_initializing(builder) return new_object def finish_initializing(self, builder): """Called while initializing this instance in __new__ finish_initalizing should be called after parsing the ui definition and creating a PreferencesFooDialog object with it in order to finish initializing the start of the new PerferencesFooDialog instance. Put your initialization code in here and leave __init__ undefined. """ # Get a reference to the builder and set up the signals. self.builder = builder self.builder.connect_signals(self) # Set up couchdb and the preference info. self._db_name = "foo" self._database = CouchDatabase(self._db_name, create=True) self._preferences = None self._key = None # Set the record type and then initalize the preferences. self._record_type = ( "http://wiki.ubuntu.com/Quickly/RecordTypes/Foo/" "Preferences") self._preferences = self.get_preferences() # TODO: code for other initialization actions should be added here def get_preferences(self): """Return a dict of preferences for foo. Creates a couchdb record if necessary. """ if self._preferences == None: # The dialog is initializing. self._load_preferences() # If there were no saved preference, this. return self._preferences def _load_preferences(self): # TODO: add preferences to the self._preferences dict default # preferences that will be overwritten if some are saved self._preferences = {"record_type": self._record_type} results = self._database.get_records( record_type=self._record_type, create_view=True) if len(results.rows) == 0: # No preferences have ever been saved, save them before returning. self._key = self._database.put_record(Record(self._preferences)) else: self._preferences = results.rows[0].value del self._preferences['_rev'] self._key = results.rows[0].value["_id"] def _save_preferences(self): self._database.update_fields(self._key, self._preferences) def ok(self, widget, data=None): """The user has elected to save the changes. Called before the dialog returns gtk.RESONSE_OK from run(). """ # Make any updates to self._preferences here. e.g. #self._preferences["preference1"] = "value2" self._save_preferences() def cancel(self, widget, data=None): """The user has elected cancel changes. Called before the dialog returns gtk.RESPONSE_CANCEL for run() """ # Restore any changes to self._preferences here. pass
class User_dict(dict): ''' a dictionary with extra methods: persistence: load, save and db_connect gobject signals: connect and emit. Don't use this directly. Please use the preferences instance.''' def __init__(self, *args, **kwds): dict.__init__(self, *args, **kwds) # Set up couchdb. self._db_name = "gopu" self._key = None self._database = None self._record_type = ("http://wiki.ubuntu.com/Quickly/RecordTypes/Gopu/" "Preferences") class Publisher(gtk.Invisible): # pylint: disable=R0904 '''set up signals in a separate class gtk.Invisible has 230 public methods''' __gsignals__ = { 'changed': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, )), 'loaded': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, )) } publisher = Publisher() self.emit = publisher.emit self.connect = publisher.connect def db_connect(self): '''connect to couchdb create if necessary''' # logging.basicConfig will be called now self._database = CouchDatabase(self._db_name, create=True) def save(self): 'save to couchdb' self._database.update_fields(self._key, self) def load(self): 'load from couchdb' self.update({"record_type": self._record_type}) results = self._database.get_records(record_type=self._record_type, create_view=True) if len(results.rows) == 0: # No preferences have ever been saved # save them before returning. self._key = self._database.put_record(Record(self)) else: self.update(results.rows[0].value) del self['_rev'] self._key = results.rows[0].value["_id"] self.emit('loaded', None) def update(self, *args, **kwds): ''' interface for dictionary send changed signal when appropriate ''' # parse args new_data = {} new_data.update(*args, **kwds) changed_keys = [] for key in new_data.keys(): if new_data.get(key) != dict.get(self, key): changed_keys.append(key) dict.update(self, new_data) if changed_keys: self.emit('changed', tuple(changed_keys)) def __setitem__(self, key, value): ''' interface for dictionary send changed signal when appropriate ''' if value != dict.get(self, key): dict.__setitem__(self, key, value) self.emit('changed', (key, ))
class HudsonNotifierConfig(object): def __init__(self): #set up couchdb and the preference info self.__db_name = "hudson-notifier" self.__database = CouchDatabase(self.__db_name, create=True) self.__preferences = None self.__key = None #set the record type and then initalize the preferences self.__record_type = "http://wiki.ubuntu.com/Quickly/RecordTypes/Hudsonnotifier/Preferences" self.__preferences = self.__get_preferences() #configuration change event self.configurationChanged = Event() def __get_preferences(self): """get_preferences -returns a dictionary object that contain preferences for hudsonnotifier. Creates a couchdb record if necessary. """ if self.__preferences == None: #the dialog is initializing self.__load_preferences() #if there were no saved preference, this return self.__preferences def __load_preferences(self): #TODO: add prefernces to the self.__preferences dict #default preferences that will be overwritten if some are saved self.__preferences = {"record_type":self.__record_type} results = self.__database.get_records(record_type=self.__record_type, create_view=True) if len(results.rows) == 0: #no preferences have ever been saved #save them before returning self.__key = self.__database.put_record(Record(self.__preferences)) else: self.__preferences = results.rows[0].value del self.__preferences['_rev'] self.__key = results.rows[0].value["_id"] def __save_preferences(self): self.__database.update_fields(self.__key, self.__preferences) self.configurationChanged(self) def getUrl(self): return self.__preferences.get("url", None) def setUrl(self, url): self.__preferences["url"] = url self.__save_preferences() def save_project(self, project, value): self.__preferences["project_%s"%(project)] = value self.__save_preferences() def get_project(self, project): print "Loading project %s"%project return self.__preferences.get("project_%s"%(project), True) url = property(getUrl, setUrl, doc="Url to connect to the hudson build server on")
# [SNIPPET_DESCRIPTION: Delete records from the desktop couch database] # [SNIPPET_AUTHOR: Andy Breiner <*****@*****.**>] # [SNIPPET_DOCS: http://www.freedesktop.org/wiki/Specifications/desktopcouch/Documentation/SimpleGuide] # [SNIPPET_LICENSE: GPL] from desktopcouch.records.server import CouchDatabase from desktopcouch.records.record import Record #Similar to the fetchrecord.py by Huntly Cameron #See fetchrecord.py for additional information db = CouchDatabase("deleterecordsexample", create=True) record_type = "http://example.com/delete-record-type.html" record = Record({"first" : "Andy", "last" : "Breiner"}, record_type) db.put_record(record) record = Record({"first" : "Jono", "last" : "Bacon"}, record_type) db.put_record(record) results = db.get_records(record_type = record_type, create_view = True) for records in results: record = records.value print "First: %s" % record["first"] print "Last : %s" % record["last"] if record["first"] == "Andy": db.delete_record(record["_id"])