Example #1
0
    def finish_initializing(self, builder):
        """finish_initalizing should be called after parsing the ui definition
        and creating a AboutXratersDialog object with it in order to finish
        initializing the start of the new AboutXratersDialog 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 = "xraters"
        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/Xraters/Preferences"
        self.__preferences = self.get_preferences()
        #TODO:code for other initialization actions should be added here
        
        self.__entryWiiAddress = self.builder.get_object("entry_WiiAddress")
        self.__entryWiiAddress.set_text(self.__preferences['wiiAddress'])
        self.__filechooserOutput = self.builder.get_object("filechooser_output")
        self.__filechooserOutput.set_filename(self.__preferences['outputDir'])
    def test_selected_id_property(self):
        #create some records
        db = CouchDatabase(self.dbname, create=True)
        id1 = db.put_record(
            Record({
                "key1_1": "val1_1",
                "key1_2": "val1_2",
                "key1_3": "val1_3",
                "record_type": self.record_type
            }))
        id2 = db.put_record(
            Record({
                "key1_1": "val2_1",
                "key1_2": "val2_2",
                "key1_3": "val2_3",
                "record_type": self.record_type
            }))

        #build the CouchGrid
        cw = CouchGrid(self.dbname)
        cw.record_type = self.record_type

        #make sure the record ids are selected properly
        cw.selected_record_ids = [id1]
        self.assertEqual(cw.selected_record_ids[0], id1)
        cw.selected_record_ids = [id2]
        self.assertEqual(cw.selected_record_ids[0], id2)
Example #3
0
    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 test_dont_delete_selected_rows(self):
        #create some records
        db = CouchDatabase(self.dbname, create=True)
        ids = []
        for i in xrange(0, 10):
            ids.append(
                db.put_record(
                    Record({
                        "key1_1": "val1_%s" % str(i),
                        "iter_count": i,
                        "record_type": self.record_type
                    })))

        #build the CouchGrid
        cw = CouchGrid(self.dbname, record_type=self.record_type)
        cw.selected_record_ids = [ids[0], ids[5], ids[9]]
        cw.remove_selected_rows(delete=False)
        cw.selected_record_ids = [ids[1], ids[4], ids[8]]
        cw.remove_selected_rows()
        self.assertEqual(self.db.get_record(ids[0]) is not None, True)
        self.assertEqual(self.db.get_record(ids[5]) is not None, True)
        self.assertEqual(self.db.get_record(ids[9]) is not None, True)

        self.assertEqual(self.db.get_record(ids[1]) is not None, True)
        self.assertEqual(self.db.get_record(ids[2]) is not None, True)
        self.assertEqual(self.db.get_record(ids[3]) is not None, True)
        self.assertEqual(self.db.get_record(ids[4]) is not None, True)
        self.assertEqual(self.db.get_record(ids[6]) is not None, True)
        self.assertEqual(self.db.get_record(ids[7]) is not None, True)
        self.assertEqual(self.db.get_record(ids[8]) is not None, True)
  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 database(self, db_name):
     if self.uri:
         self._db = CouchDatabase(db_name, create=True, uri=self.uri)
     else:
         self._db = CouchDatabase(db_name, create=True)
     if self.record_type != None:
         self._refresh_treeview()#first time treeview is reset
    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 PreferencesGsqlDinkyDialog object with it in order to
        finish initializing the start of the new PerferencesGsqlDinkyDialog
        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 = "gsql-dinky"
        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/GsqlDinky/"
            "Preferences")
        self._preferences = self.get_preferences()
Example #8
0
  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)
    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 PreferencesSimplePlayer1Dialog object with it in order to
        finish initializing the start of the new PerferencesSimplePlayer1Dialog
        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 = "simple-player1"
        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/SimplePlayer1/"
            "Preferences")
        self._preferences = self.get_preferences()
    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 finish_initializing(self, builder):
        """finish_initalizing should be called after parsing the ui definition
        and creating a AboutPhotobombDialog object with it in order to finish
        initializing the start of the new AboutPhotobombDialog 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 = "photobomb"
        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/Photobomb/Preferences"
        self.__preferences = self.get_preferences()
Example #12
0
    def migrate_from_couch(self):
        try:
            from desktopcouch.records.server import CouchDatabase
            from desktopcouch.records.record import Record
            imported = True
        except ImportError:
            return

        db = 0
        try:
            db = CouchDatabase('indicator-remindor-alarms', create=False)
        except:
            return

        if not db.view_exists("list", "app"):
            map_js = """function(doc) { emit(doc._id, doc) }"""
            db.add_view("list", map_js, None, "app")

        result = db.execute_view("list", "app")
        result_list = list(result)

        for row in result_list:
            time_s = datetimeutil.format_time(row.value["hour"], row.value["minute"], row.value["am_pm"])
            sound_length = 0
            sound_loop = False

            try:
                sound_length = row.value["sound_length"]
            except KeyError:
                sound_length = 0

            try:
                sound_loop = row.value["sound_loop"]
            except KeyError:
                sound_loop = False

            self.execute("""INSERT INTO alarms (label, notes, time, date, sound, sound_length,
                sound_loop, notification, command) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)""",
                (row.value["label"], row.value["notes"], time_s, row.value["date"],
                row.value["sound"], sound_length, sound_loop,
                row.value["notification"], row.value["command"]))
Example #13
0
    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):
        #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()
Example #15
0
    def finish_initializing(self, builder):
        """finish_initalizing should be called after parsing the ui definition
        and creating a AboutLxproxyDialog object with it in order to finish
        initializing the start of the new AboutLxproxyDialog 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 = "lxproxy"
        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/Lxproxy/Preferences"
        self.__preferences = self.get_preferences()
    def test_all_from_database(self):
        #create some records
        db = CouchDatabase(self.dbname, create=True)
        db.put_record(
            Record({
                "key1_1": "val1_1",
                "key1_2": "val1_2",
                "key1_3": "val1_3",
                "record_type": self.record_type
            }))
        db.put_record(
            Record({
                "key1_1": "val2_1",
                "key1_2": "val2_2",
                "key1_3": "val2_3",
                "record_type": self.record_type
            }))

        #build the CouchGrid
        cw = CouchGrid(self.dbname)
        cw.record_type = self.record_type
        #make sure there are three columns and two rows
        self.assertEqual(cw.get_model().get_n_columns(), 4)
        self.assertEqual(len(cw.get_model()), 2)
Example #17
0
# [SNIPPET_NAME: Fetch Records]
# [SNIPPET_CATEGORIES: DesktopCouch]
# [SNIPPET_DESCRIPTION: Fetch records from the desktop couch database]
# [SNIPPET_AUTHOR: Huntly Cameron <*****@*****.**>]
# [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

#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"]
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 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,))
    def __init__(
            self, database_name, record_type=None, dictionaries=None, editable=False, keys=None, type_hints=None, uri=None):
        """Create a new Couchwidget
        arguments:
        database_name - specify the name of the database in the desktop
        couchdb to use. If the specified database does not exist, it
        will be created.

        optional arguments:
        record_type - a string to specify the record_type to use in
        retrieving and creating records. Note that if no records exist
        in the CouchDB then the keys argument must also be used or
        a RuntimeError will result.

        dictionaries - a list of dictionaries to initialize in the 
        grid. If these haven't been added to desktopcouch, the will
        be automatically persisted and updated using the recored_type
        specified. Any previously saved data of the same record_type will
        also be displayed. 

        keys - a list of strings specifying keys to use in
        the columns of the CouchGrid. The keys will also be used for the
        column titles and keys in desktop couch.

        If a record does not contain a value for a specified key
        the CouchGrid will simply display an empty cell of the 
        appropriate type. If the widget is set to editable, 
        the user will be able to add values to the database.

        The types for the columns will be inferred by the key based on
        some conventions. the key "id" is assumed to be an integer, as
        is any key ending in " count". A key ending in "?" is assumed
        to be a Boolean displayed with a checkbox. The key "price" is
        assumed to be currency, as is any key ending in "count". There
        may be others. Defaults can be overridden using type-hints. All
        other keys will be assumed to be strings.
        
        type-hints - a dictionary containing keys specificed for the
        TreeView and GridColumns. Used to override types inferred
        by convention, or for changing the type of a column from
        the default of a string to something else.

        uri - A uri for the DesktopCouch. This is only used to 
        choose a Couch database running remotely. The default is
        to use the local desktopcouch database.

        """

        if type(database_name) is not type(str()):
            raise TypeError("database_name is required and must be a string")

        #set up the database before trying to use it
        self.uri = uri
        self._record_type = None
        self._db = None
        if record_type is not None:
            self._record_type = record_type

        if dictionaries is not None and keys is None:
            DictionaryGrid.__init__(self, None, editable, keys, type_hints)
        else:
            DictionaryGrid.__init__(self, None, editable, keys, type_hints)

        if self.uri:
            self._db = CouchDatabase(database_name, create=True, uri=self.uri)
        else:
            self._db = CouchDatabase(database_name, create=True)

        if dictionaries is not None:
            for d in dictionaries:
                self._persist_dict_to_couch(d)

        self._refresh_treeview()
Example #21
0
# [SNIPPET_NAME: Add record]
# [SNIPPET_CATEGORIES: DesktopCouch]
# [SNIPPET_DESCRIPTION: Add a new record into the database]
# [SNIPPET_AUTHOR: Huntly Cameron <*****@*****.**>]
# [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

#create the database
db = CouchDatabase("addrecordexample", create=True)

#Records work like python dictionaries, and *should* have an
#online description of how the record should look like.
record_type = "http://example.com/somerecordtype.html"
new_record = Record({
    "a field": "a value",
    "another field": "another value"
}, record_type)

#put our new record into the datbase
db.put_record(new_record)

#run xdg-open /home/$USER/.local/share/desktop-couch/couchdb.html
#from the terminal to view the desktopcouch
Example #22
0
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 = "brazo"
        self._key = None
        self._database = None
        
        self._record_type = (
            "http://wiki.ubuntu.com/Quickly/RecordTypes/Brazo/"
            "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,))
Example #23
0
# [SNIPPET_NAME: Add an attachment to a Desktopcouch Record]
# [SNIPPET_CATEGORIES: DesktopCouch]
# [SNIPPET_DESCRIPTION: Shows how to add an attachment to a Desktopcouch Record that will be stored and replicated by CouchDB]
# [SNIPPET_AUTHOR: Manuel de la Pena <*****@*****.**>]
# [SNIPPET_DOCS: http://www.themacaque.com/wiki/doku.php?id=desktopcouch:create_attachments]
# [SNIPPET_LICENSE: GPL]
import sys
from desktopcouch.records.record import Record
from desktopcouch.records.server import CouchDatabase

# get the jpg to add from the command line

if len(sys.argv) > 1:
    path = sys.argv[0]
    db = CouchDatabase("addattachment", create=True)
    record = Record(record_type="url")
    record.attach(path, "blob", "image/jpg")
    db.put_record(record)
else:
    print "Please pass the path of the jpg to add."

# got to /home/$USER/.local/share/desktop-couch/couchdb.html to see the
# attached file
Example #24
0
# [SNIPPET_NAME: Add record]
# [SNIPPET_CATEGORIES: DesktopCouch]
# [SNIPPET_DESCRIPTION: Add a new record into the database]
# [SNIPPET_AUTHOR: Huntly Cameron <*****@*****.**>]
# [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

#create the database
db = CouchDatabase("addrecordexample", create=True)

#Records work like python dictionaries, and *should* have an
#online description of how the record should look like.
record_type = "http://example.com/somerecordtype.html"
new_record = Record({"a field" : "a value", 
                     "another field" : "another value"}, record_type)

#put our new record into the datbase
db.put_record(new_record)

#run xdg-open /home/$USER/.local/share/desktop-couch/couchdb.html 
#from the terminal to view the desktopcouch
Example #25
0
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
# [SNIPPET_NAME: Create a Database]
# [SNIPPET_CATEGORIES: DesktopCouch]
# [SNIPPET_DESCRIPTION: Creating a new database in desktopcouch]
# [SNIPPET_AUTHOR: Huntly Cameron <*****@*****.**>]
# [SNIPPET_DOCS: http://www.freedesktop.org/wiki/Specifications/desktopcouch/Documentation/SimpleGuide]
# [SNIPPET_LICENSE: GPL]

from desktopcouch.records.server import CouchDatabase

#Create a database object. Your database needs to exist.
#If it doesn't, you can create it by passing create=True.
db = CouchDatabase('createdatabaseexample', create=True)

#run xdg-open /home/$USER/.local/share/desktop-couch/couchdb.html
#from the terminal to view the desktopcouch
Example #27
0
class User_dict(IterableUserDict):
    ''' 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):
        IterableUserDict.__init__(self)
        # Set up couchdb.
        self._db_name = "simple-player"
        self._key = None

        self._record_type = (
            "http://wiki.ubuntu.com/Quickly/RecordTypes/SimplePlayer/"
            "Preferences")
        
        # set up signals in a separate class
        # because IterableUserDict uses self.data (documented)
        # and gtk.Invisible appears to use self.data.
        class Publisher(gtk.Invisible):
            __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):
        # logging.basicConfig will be called now
        self._database = CouchDatabase(self._db_name, create=True)

    def save(self):
        # couchdb
        self._database.update_fields(self._key, self.data)

 
    def load(self):
        # 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.data))
        else:
            self.update(results.rows[0].value)
            del self['_rev']
            self._key = results.rows[0].value["_id"]
        self.emit('loaded', None)

    def update(self, new_data):
        """ interface for dictionary 
        
        send changed signal when appropriate """
        changed_keys = []
        for key in new_data.keys():
            if new_data.get(key) != self.data.get(key):
                changed_keys.append(key)
        self.data.update(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 != self.data.get(key):
            self.data[key] =  value
            self.emit('changed', (key,))
Example #28
0
 def db_connect(self):
     # logging.basicConfig will be called now
     self._database = CouchDatabase(self._db_name, create=True)
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")
Example #30
0
 def db_connect(self):
     '''connect to couchdb
     
     create if necessary'''
     # logging.basicConfig will be called now
     self._database = CouchDatabase(self._db_name, create=True)
Example #31
0
#!/usr/bin/env python
#
# [SNIPPET_NAME: Delete Records]
# [SNIPPET_CATEGORIES: DesktopCouch]
# [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"]
class CouchGrid(DictionaryGrid):
    def __init__(
            self, database_name, record_type=None, dictionaries=None, editable=False, keys=None, type_hints=None, uri=None):
        """Create a new Couchwidget
        arguments:
        database_name - specify the name of the database in the desktop
        couchdb to use. If the specified database does not exist, it
        will be created.

        optional arguments:
        record_type - a string to specify the record_type to use in
        retrieving and creating records. Note that if no records exist
        in the CouchDB then the keys argument must also be used or
        a RuntimeError will result.

        dictionaries - a list of dictionaries to initialize in the 
        grid. If these haven't been added to desktopcouch, the will
        be automatically persisted and updated using the recored_type
        specified. Any previously saved data of the same record_type will
        also be displayed. 

        keys - a list of strings specifying keys to use in
        the columns of the CouchGrid. The keys will also be used for the
        column titles and keys in desktop couch.

        If a record does not contain a value for a specified key
        the CouchGrid will simply display an empty cell of the 
        appropriate type. If the widget is set to editable, 
        the user will be able to add values to the database.

        The types for the columns will be inferred by the key based on
        some conventions. the key "id" is assumed to be an integer, as
        is any key ending in " count". A key ending in "?" is assumed
        to be a Boolean displayed with a checkbox. The key "price" is
        assumed to be currency, as is any key ending in "count". There
        may be others. Defaults can be overridden using type-hints. All
        other keys will be assumed to be strings.
        
        type-hints - a dictionary containing keys specificed for the
        TreeView and GridColumns. Used to override types inferred
        by convention, or for changing the type of a column from
        the default of a string to something else.

        uri - A uri for the DesktopCouch. This is only used to 
        choose a Couch database running remotely. The default is
        to use the local desktopcouch database.

        """

        if type(database_name) is not type(str()):
            raise TypeError("database_name is required and must be a string")

        #set up the database before trying to use it
        self.uri = uri
        self._record_type = None
        self._db = None
        if record_type is not None:
            self._record_type = record_type

        if dictionaries is not None and keys is None:
            DictionaryGrid.__init__(self, None, editable, keys, type_hints)
        else:
            DictionaryGrid.__init__(self, None, editable, keys, type_hints)

        if self.uri:
            self._db = CouchDatabase(database_name, create=True, uri=self.uri)
        else:
            self._db = CouchDatabase(database_name, create=True)

        if dictionaries is not None:
            for d in dictionaries:
                self._persist_dict_to_couch(d)

        self._refresh_treeview()

    @property
    def database(self):
        """database - gets an instance to the CouchDB.
        Set to a string to change the database.

        """
        return self._db

    @database.setter
    def database(self, db_name):
        if self.uri:
            self._db = CouchDatabase(db_name, create=True, uri=self.uri)
        else:
            self._db = CouchDatabase(db_name, create=True)
        if self.record_type != None:
            self._refresh_treeview()#first time treeview is reset

    @property
    def record_type(self):
        """record_type - a string specifying the record type of
        the documents to retrieve from the CouchDB.

        Will cause the TreeView to refresh when set.
        """
        return self._record_type

    @record_type.setter
    def record_type(self, record_type):

        #store the record type string
        self._record_type = record_type
        self._refresh_treeview()

    @property
    def selected_record_ids(self):
        """ selected_record_ids - a list of document ids that are
        selected in the CouchGrid. Throws an IndexError if
        a specified id is not found in the list when setting
        this property.

        This property is read/write

        """
        ids = []
        for row in self.selected_rows:
            id_ = None
            
            if "__desktopcouch_id" in row:
                id_ = row["__desktopcouch_id"]
            ids.append(id_)
        return ids

    @selected_record_ids.setter
    def selected_record_ids(self, indexes):
        rows = [] #a list of rows to select
        for id in indexes:
            id_found = False #track if the id was found

            for i,r in enumerate(self.list_store):
                dictionary = r[len(self.keys)] #this dictionary always last column
                if "__desktopcouch_id" in dictionary:
                    if dictionary["__desktopcouch_id"] == id:
                        id_found = True #id was good
                        if r not in rows: #don't have duplicates to select
                            rows.append(i)
            if not id_found: #stop if a requested id was not in the list
                raise IndexError("id %s not found" %id)

        #select the requested ids
        selection = self.get_selection()
        selection.unselect_all()
        for r in rows:
            selection.select_path(r)

    def remove_selected_rows(self, delete=False):
        rows_to_delete = self.selected_rows
        if delete:
            for r in rows_to_delete:
                self.database.delete_record(r["__desktopcouch_id"])
        DictionaryGrid.remove_selected_rows(self)

    def _refresh_treeview(self):
        """
        _refresh_treeview: internal function to handle rebuilding
        the gtk.TreeView along with columns and cell renderers. extends
        DictionaryGrid._refresh_treeview by retrieving stored desktopcouch
        records before calling DictionaryGrid._refresh_treeview. 

        _refresh_treeview is not typically called directly,
        but may be useful to override in subclasses.

        """

        #if the database is not set up, just return
        if self._db is None or self._record_type is None:
            return

        #if keys aren't set, infer them from the collection
        if len(self._dictionaries) > 0 and self.keys is None:
            self._infer_keys_from_dictionaries()        

        #retrieve the docs for the record_type, if any
        results = self._db.get_records(
            record_type=self._record_type,create_view=True)


        #if there are no rows and no keys set, there is no
        #way to build the grid, just raise an error
        if len(results) == 0 and self._keys is None:
            raise RuntimeError("Cannot infer columns for CouchGrid")

        dicts = []
        for r in results:
            d = r.value

            #hmmm, maybe make these so they get hidden rather than delete them
            #hide the desktopcouch variabls
            for key in d:
                if key.startswith("_") and not key.startswith("__desktopcouch"):
                    d["__desktopcouch" + key] = d[key]
                    del(d[key])

            d["__record_type"] = d["record_type"]
            del(d["record_type"])
            dicts.append(d)

        self._dictionaries = dicts
        DictionaryGrid._refresh_treeview(self)

        for c in self.get_columns():
            if type(c) == CheckColumn:
                c.renderer.connect("toggled",self._edited_toggled, c)
            else:
                c.renderer.connect("edited",self._edited, c)

    def append_row(self, dictionary):
        """append_row: add a row to the TreeView and to DesktopCouch. 
        If keys are already set up only the the keys in the dictionary 
        matching the keys used for columns will be displayed, though 
        all the key value pairs will be saved to the DesktopCouch. 
        If no keys are set up, and this is the first row, keys will be
        inferred from the dictionary keys.

        arguments:
        dictionary - a dictionary to add to the Treeview and to DesktopCouch

        """

        if dictionary is None:
            dictionary = {}

        #Here we add rows to desktopcouch if needed
        if "__desktopcouch_id" not in dictionary:
            self._persist_dict_to_couch(dictionary)
        DictionaryGrid.append_row(self,dictionary)

    def _persist_dict_to_couch(self,dictionary):
        """ _persist_dict_to_couch - internal implementation. may be useful
        a subclass of CouchGrid, but not normally called directly.

        """

        dictionary["record_type"] = self.record_type
        rec = Record(dictionary)
        #meh, best not to save an empty row
        if len(dictionary) > 1:
            doc_id = self._db.put_record(rec)
            dictionary["__desktopcouch_id"] = doc_id
            dictionary["__record_type"] = self.record_type
            del(dictionary["record_type"])
                
    def _edited_toggled(self, cell, path, col):
        """ _edited_toggled - internal signal handler.
        Updates the database if a cell in the Treeview
        has been edited special cased for CheckColumns.

        """

        iter = self.list_store.get_iter(path)
        key = col.key
        active = not cell.get_active()
        self._edited(cell, path, active, col)

    def _edited(self, cell, path, new_val, col):
        """ _edited - internal signal handler.
        Updates the database if a cell in the Treeview
        has been edited.

        """
        iter = self.list_store.get_iter(path)
        key = col.key
        dictionary = self.list_store.get_value(iter,len(self.keys))

        if "__desktopcouch_id" not in dictionary: #the row has not been stored
            #create a document
            dictionary["record_type"] = self.record_type
            rec = Record(dictionary)
            doc_id = self._db.put_record(rec)
            dictionary["__desktopcouch_id"] = doc_id
            self.list_store.set_value(iter, len(self.keys), dictionary)

        else: #it has been saved
            #get the record id from the dictionary
            #then update the datbase with the change
            id = dictionary["__desktopcouch_id"]
            key = col.key
            self._db.update_fields(id,{key:new_val})
 def setUp(self):
     TestCase.setUp(self)
     self.dbname = self._testMethodName
     self.db = CouchDatabase(self.dbname, create=True)
     self.record_type = "test_record_type"
class PreferencesGsqlDinkyDialog(gtk.Dialog):
    __gtype_name__ = "PreferencesGsqlDinkyDialog"
    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 PreferencesGsqlDinkyDialog object.
        """
        builder = get_builder('PreferencesGsqlDinkyDialog')
        new_object = builder.get_object("preferences_gsql_dinky_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 PreferencesGsqlDinkyDialog object with it in order to
        finish initializing the start of the new PerferencesGsqlDinkyDialog
        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 = "gsql-dinky"
        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/GsqlDinky/"
            "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 gsql-dinky.

        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
Example #35
0
# [SNIPPET_NAME: Fetch Records]
# [SNIPPET_CATEGORIES: DesktopCouch]
# [SNIPPET_DESCRIPTION: Fetch records from the desktop couch database]
# [SNIPPET_AUTHOR: Huntly Cameron <*****@*****.**>]
# [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

#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
Example #36
0
# [SNIPPET_NAME: Add an attachment to a Desktopcouch Record]
# [SNIPPET_CATEGORIES: DesktopCouch]
# [SNIPPET_DESCRIPTION: Shows how to add an attachment to a Desktopcouch Record that will be stored and replicated by CouchDB]
# [SNIPPET_AUTHOR: Manuel de la Pena <*****@*****.**>]
# [SNIPPET_DOCS: http://www.themacaque.com/wiki/doku.php?id=desktopcouch:create_attachments]
# [SNIPPET_LICENSE: GPL]
import sys
from desktopcouch.records.record import Record
from desktopcouch.records.server import CouchDatabase

# get the jpg to add from the command line

if len(sys.argv) > 1:
    path = sys.argv[0]
    db = CouchDatabase("addattachment", create=True)
    record = Record(record_type="url")
    record.attach(path, "blob", "image/jpg")
    db.put_record(record)
else:
    print "Please pass the path of the jpg to add."

# got to /home/$USER/.local/share/desktop-couch/couchdb.html to see the 
# attached file
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
 def db_connect(self):
     '''connect to couchdb
     
     create if necessary'''
     # logging.basicConfig will be called now
     self._database = CouchDatabase(self._db_name, create=True)
Example #39
0
# [SNIPPET_NAME: Listen to changes in CouchDatabase]
# [SNIPPET_CATEGORIES: DesktopCouch]
# [SNIPPET_DESCRIPTION: Register a callback that will listen to changes in the CouchDatabase]
# [SNIPPET_AUTHOR: Manuel de la Pena <*****@*****.**>]
# [SNIPPET_DOCS: http://www.themacaque.com/wiki/doku.php?id=desktopcouch:listen_to_changes]
# [SNIPPET_LICENSE: GPL]
import time
from desktopcouch.records.server import CouchDatabase

# we are going to be listening to the changes in this callback
def changes_cb(seq=None, id=None, changes=None):
    print seq
    print id
    print changes
 
db = CouchDatabase("listenchangesexample", create=True)

# is better, use glib main loop or twisted task!
while True:
    db.report_changes(changes_cb)
    time.sleep(30)

# got to /home/$USER/.local/share/desktop-couch/couchdb.html and make
# changes to the listenchangesexample to see the callback output