Author: dmeyer
Date: Sat Sep 15 07:52:26 2007
New Revision: 2808

Log:
refactor, code cleanup

Modified:
   trunk/beacon/src/__init__.py
   trunk/beacon/src/client.py
   trunk/beacon/src/db.py
   trunk/beacon/src/file.py
   trunk/beacon/src/item.py
   trunk/beacon/src/query.py
   trunk/beacon/src/server/db.py
   trunk/beacon/src/server/monitor.py
   trunk/beacon/src/server/parser.py
   trunk/beacon/src/server/server.py

Modified: trunk/beacon/src/__init__.py
==============================================================================
--- trunk/beacon/src/__init__.py        (original)
+++ trunk/beacon/src/__init__.py        Sat Sep 15 07:52:26 2007
@@ -42,7 +42,7 @@
 
 # kaa.beacon imports
 from version import VERSION
-from client import Client, CONNECTED, ConnectError
+from client import Client, ConnectError
 import thumbnail
 from thumbnail import NORMAL as THUMBNAIL_NORMAL
 from thumbnail import LARGE as THUMBNAIL_LARGE
@@ -153,7 +153,7 @@
         connect()
     return _client.add_item(url, type, parent, **kwargs)
 
-    
+
 def register_file_type_attrs(name, **kwargs):
     """
     Register new attrs and types for files.
@@ -180,7 +180,7 @@
     """
     if not _client:
         connect()
-    while not _client.status == CONNECTED:
+    while not _client.is_connected():
         kaa.notifier.step()
     return _client._db.get_db_info()
 
@@ -191,6 +191,6 @@
     """
     if not _client:
         connect()
-    while not _client.status == CONNECTED:
+    while not _client.is_connected():
         kaa.notifier.step()
     return _client.delete_media(id)

Modified: trunk/beacon/src/client.py
==============================================================================
--- trunk/beacon/src/client.py  (original)
+++ trunk/beacon/src/client.py  Sat Sep 15 07:52:26 2007
@@ -148,6 +148,13 @@
         self.rpc('item.delete', item._beacon_id)
 
 
+    def is_connected(self):
+        """
+        Return if the client is connected to a server
+        """
+        return self.status == CONNECTED
+
+
     def monitor(self, directory):
         """
         Monitor a directory with subdirectories for changes. This is done in
@@ -265,11 +272,12 @@
         """
         Update item in next main loop interation.
         """
+        if not self.status == CONNECTED:
+            return
         if not item._beacon_id:
             # Item has no beacon id, request the data before
-            # schedule the update. If we are not connected the
-            # update will be lost.
-            item._beacon_request(self._beacon_update, item)
+            # schedule the update.
+            item.scan().connect(self._beacon_update, item)
             return
         if not self._changed:
             # register timer to do the changes
@@ -370,7 +378,7 @@
             log.error('Error: unknown message from server: %s' % msg)
             return
         log.error('query %s not found', id)
-        
+
 
     @kaa.rpc.expose('device.changed')
     def media_changed(self, id, prop):

Modified: trunk/beacon/src/db.py
==============================================================================
--- trunk/beacon/src/db.py      (original)
+++ trunk/beacon/src/db.py      Sat Sep 15 07:52:26 2007
@@ -53,25 +53,60 @@
 MAX_BUFFER_CHANGES = 30
 
 # Item generation mapping
-from file import File as create_file
-from item import create_item
+from file import File
+from item import Item
 
 # The db uses the following helper functions to create the correct item
-# create_item (not a file or directory)
-# create_file (file or directory, based on parameter)
-# create_directory (directory)
-# create_by_type (item, file or directory based on data)
+
+def create_item(data, parent):
+    """
+    Create an Item that is neither dir nor file.
+    """
+    data = dict(data)
+    dbid = (data['type'], data['id'])
+    if 'url' in data:
+        # url is stored in the data
+        return Item(dbid, data['url'], data, parent, parent._beacon_media)
+    if '://' in data['name']:
+        # url is stored in the name (remote items in directory)
+        return Item(dbid, data['name'], data, parent, parent._beacon_media)
+
+    # generate url based on name and parent url
+    url = parent.url
+    if data['name']:
+        if parent.url.endswith('/'):
+            url = parent.url + data['name']
+        else:
+            url = parent.url + '/' + data['name']
+    if data.get('scheme'):
+        url = data.get('scheme') + url[url.find('://')+3:]
+    return Item(dbid, url, data, parent, parent._beacon_media)
+
+
+def create_file(data, parent, overlay=False, isdir=False):
+    """
+    Create a file or directory
+    """
+    return File(data, parent, overlay, isdir)
+
+
+def create_directory(data, parent):
+    """
+    Create a directory
+    """
+    return create_file(data, parent, isdir=True)
+
 
 def create_by_type(data, parent, overlay=False, isdir=False):
-    # if the data indicates it is not a file or the parent is not
-    # a directory, make it an Item, not a File.
+    """
+    Create file, directory or any other kind of item.
+    If the data indicates it is not a file or the parent is not
+    a directory, make it an Item, not a File.
+    """
     if (data.get('name').find('://') > 0) or (parent and not parent.isdir()):
         return create_item(data, parent)
     return create_file(data, parent, overlay, isdir)
 
-def create_directory(data, parent):
-    # create directory item
-    return create_file(data, parent, isdir=True)
 
 class Database(object):
     """

Modified: trunk/beacon/src/file.py
==============================================================================
--- trunk/beacon/src/file.py    (original)
+++ trunk/beacon/src/file.py    Sat Sep 15 07:52:26 2007
@@ -43,7 +43,6 @@
 # get logging object
 log = logging.getLogger('beacon')
 
-CONNECTED = 'connected'
 
 class File(Item):
     """
@@ -119,8 +118,20 @@
         Interface to kaa.beacon: List all files in the directory.
         """
         if recursive:
-            return self.get_controller().query(parent=self, recursive=True)
-        return self.get_controller().query(parent=self)
+            return self._beacon_controller().query(parent=self, recursive=True)
+        return self._beacon_controller().query(parent=self)
+
+
+    def scan(self):
+        """
+        Request the item to be scanned. (Client API only)
+        Returns either False if not connected or an InProgress object.
+        """
+        if not self._beacon_controller().is_connected():
+            return False
+        rpc = self._beacon_controller().rpc('item.request', self.filename)
+        rpc.connect_once(self._beacon_database_update)
+        return rpc
 
 
     # -------------------------------------------------------------------------
@@ -223,26 +234,6 @@
         return s + '>'
 
 
-    # -------------------------------------------------------------------------
-    # Internal API for client
-    # -------------------------------------------------------------------------
-
-    def _beacon_request(self, callback=None, *args, **kwargs):
-        """
-        Request the item to be scanned. (Client API only)
-        """
-
-        if not self.get_controller().status == CONNECTED:
-            return False
-        rpc = self.get_controller().rpc('item.request', self.filename)
-        rpc.connect_once(self._beacon_database_update, callback, *args, 
**kwargs)
-        return True
-
-
-    # -------------------------------------------------------------------------
-    # Internal API for server
-    # -------------------------------------------------------------------------
-
     def _beacon_mtime(self):
         """
         Return modification time of the item itself.

Modified: trunk/beacon/src/item.py
==============================================================================
--- trunk/beacon/src/item.py    (original)
+++ trunk/beacon/src/item.py    Sat Sep 15 07:52:26 2007
@@ -83,18 +83,15 @@
 
 
     # -------------------------------------------------------------------------
-    # Public API for the client
+    # Public API
     # -------------------------------------------------------------------------
 
-    def get(self, key, request=False):
+    def get(self, key):
         """
         Interface to kaa.beacon. Return the value of a given attribute. If
         the attribute is not in the db, return None. If the key starts with
         'tmp:', the data will be fetched from a dict that is not stored in
-        the db. Loosing the item object will remove that attribute. If
-        request is True, scan the item if it is not in the db. If request is
-        False and the item is not in the db, results will be very limited.
-        When request is True this function may call kaa.notifier.step()
+        the db. Loosing the item object will remove that attribute.
         """
         if key.startswith('tmp:'):
             return self._beacon_tmpdata.get(key[4:])
@@ -130,21 +127,12 @@
             t = self._beacon_data.get('title')
             if t:
                 return t
-            return str_to_unicode(get_title(self._beacon_data['name'], 
self.isfile()))
+            # generate some title and save local it for future use
+            t = str_to_unicode(get_title(self._beacon_data['name'], 
self.isfile()))
+            self._beacon_data['title'] = t
+            return t
 
-        if request and not self._beacon_id:
-            log.info('requesting data for %s', self)
-            if not self._beacon_request():
-                # unable to do this right now
-                return None
-
-            # FIXME: remove notifier.step() here!
-            while not self._beacon_id:
-                kaa.notifier.step()
-
-        if self._beacon_data.has_key(key):
-            return self._beacon_data[key]
-        return None
+        return self._beacon_data.get(key)
 
 
     def __getitem__(self, key):
@@ -162,7 +150,7 @@
             return
         self._beacon_data[key] = value
         if not self._beacon_changes:
-            self.get_controller()._beacon_update(self)
+            self._beacon_controller()._beacon_update(self)
         self._beacon_changes[key] = value
 
 
@@ -194,7 +182,7 @@
         """
         if not self._beacon_id:
             return []
-        return self.get_controller().query(parent=self)
+        return self._beacon_controller().query(parent=self)
 
 
     def isdir(self):
@@ -215,54 +203,44 @@
         """
         Delete item from the database (does not work on files)
         """
-        return self.get_controller().delete_item(self)
-
+        return self._beacon_controller().delete_item(self)
 
-    # -------------------------------------------------------------------------
-    # Internal API for client and server
-    # -------------------------------------------------------------------------
 
-    def _beacon_database_update(self, data, callback=None, *args, **kwargs):
+    def scan(self):
         """
-        Callback from db with new data
+        Request the item to be scanned.
         """
-        self._beacon_isdir = (data['type'] == 'dir')
-        self._beacon_data = dict(data)
-        self._beacon_id = (data['type'], data['id'])
-        for key, value in self._beacon_changes.items():
-            self._beacon_data[key] = value
-        if callback:
-            callback(*args, **kwargs)
+        return False
 
 
-    def __repr__(self):
+    def get_ancestors(self):
         """
-        Convert object to string (usefull for debugging)
+        Return an iterator to walk through the parents.
         """
-        return '<beacon.Item %s>' % self.url
+        return ParentIterator(self)
 
 
     # -------------------------------------------------------------------------
-    # Internal API for client
+    # Internal API
     # -------------------------------------------------------------------------
 
-    def get_controller(self):
+    def _beacon_database_update(self, data):
         """
-        Get the controller (the client or the server)
+        Callback from db with new data
         """
-        return self._beacon_media.get_controller()
+        self._beacon_isdir = (data['type'] == 'dir')
+        self._beacon_data = dict(data)
+        self._beacon_id = (data['type'], data['id'])
+        for key, value in self._beacon_changes.items():
+            self._beacon_data[key] = value
 
 
-    def _beacon_request(self):
+    def _beacon_controller(self):
         """
-        Request the item to be scanned.
+        Get the controller (the client or the server)
         """
-        return False
-
+        return self._beacon_media.get_controller()
 
-    # -------------------------------------------------------------------------
-    # Internal API for server
-    # -------------------------------------------------------------------------
 
     def _beacon_mtime(self):
         """
@@ -271,19 +249,12 @@
         return None
 
 
-    def _beacon_changed(self):
+    def __repr__(self):
         """
-        Return if the item is changed (based on modification time of
-        the data and in the database).
+        Convert object to string (usefull for debugging)
         """
-        return self._beacon_mtime() != self._beacon_data.get('mtime')
-
+        return '<beacon.Item %s>' % self.url
 
-    def _beacon_tree(self):
-        """
-        Return an iterator to walk through the parents.
-        """
-        return ParentIterator(self)
 
 
 class ParentIterator(object):
@@ -302,22 +273,3 @@
         ret = self.item
         self.item = self.item._beacon_parent
         return ret
-
-
-def create_item(data, parent):
-    data = dict(data)
-    if 'url' in data:
-        url = data['url']
-    elif '://' in data['name']:
-        url = data['name']
-    else:
-        url = parent.url
-        if data['name']:
-            if parent.url.endswith('/'):
-                url = parent.url + data['name']
-            else:
-                url = parent.url + '/' + data['name']
-        if data.get('scheme'):
-            url = data.get('scheme') + url[url.find('://')+3:]
-    return Item((data['type'], data['id']), url, data, parent,
-                parent._beacon_media)

Modified: trunk/beacon/src/query.py
==============================================================================
--- trunk/beacon/src/query.py   (original)
+++ trunk/beacon/src/query.py   Sat Sep 15 07:52:26 2007
@@ -43,8 +43,6 @@
 # get logging object
 log = logging.getLogger('beacon')
 
-CONNECTED = 'connected'
-
 _query_filter = {}
 
 def register_filter(name, function):
@@ -98,7 +96,7 @@
         if self.monitoring == status:
             # Nothing to do
             return
-        if not self._client.status == CONNECTED:
+        if not self._client.is_connected():
             # If the client is not connected yet, it will do this later.
             # Rememeber that we wanted to connect
             self.monitoring = status
@@ -110,7 +108,7 @@
                 if not parent._beacon_id:
                     # We need the get the id first. Call the function again
                     # when there is an id.
-                    parent._beacon_request(self.monitor, status)
+                    parent.scan().connect(self.monitor, status)
                     return
                 query['parent'] = parent._beacon_id
             self._rpc('monitor.add', self._client.id, self.id, query)
@@ -184,7 +182,7 @@
         """
         Start the database query.
         """
-        if self._client.status != CONNECTED:
+        if not self._client.is_connected():
             # wait until the client is connected
             wait = kaa.notifier.YieldCallback()
             self._client.signals['connect'].connect_once(wait)
@@ -197,7 +195,7 @@
             # request the real database id and do the query when done.
             parent = query['parent']
             log.info('force data for %s', parent)
-            parent._beacon_request(self._beacon_start_query, query)
+            parent.scan().connect(self._beacon_start_query, query)
             return
 
         # we have to wait until we are sure that the db is free for

Modified: trunk/beacon/src/server/db.py
==============================================================================
--- trunk/beacon/src/server/db.py       (original)
+++ trunk/beacon/src/server/db.py       Sat Sep 15 07:52:26 2007
@@ -51,11 +51,6 @@
 
 MAX_BUFFER_CHANGES = 200
 
-# Item generation mapping
-from kaa.beacon.file import File as create_file
-from kaa.beacon.item import create_item
-
-
 class ReadLock(object):
     """
     Read lock for the database.

Modified: trunk/beacon/src/server/monitor.py
==============================================================================
--- trunk/beacon/src/server/monitor.py  (original)
+++ trunk/beacon/src/server/monitor.py  Sat Sep 15 07:52:26 2007
@@ -231,7 +231,7 @@
                 # stop it and continue in the next step
                 yield YieldContinue
             # TODO: maybe also check parents?
-            if i._beacon_changed():
+            if i._beacon_mtime() != i._beacon_data.get('mtime'):
                 changed.append(i)
 
         if not changed:

Modified: trunk/beacon/src/server/parser.py
==============================================================================
--- trunk/beacon/src/server/parser.py   (original)
+++ trunk/beacon/src/server/parser.py   Sat Sep 15 07:52:26 2007
@@ -120,7 +120,7 @@
         # return an InProgress object! This has to be made clear.
         r = db.query(name=item._beacon_data['name'], parent=parent)
         if r:
-            item._beacon_database_update(r[0])
+            item._beacon_database_update(r[0]._beacon_data)
 
     if item._beacon_data.get('mtime') == mtime:
         # The item already is in the database and the mtime is unchanged.

Modified: trunk/beacon/src/server/server.py
==============================================================================
--- trunk/beacon/src/server/server.py   (original)
+++ trunk/beacon/src/server/server.py   Sat Sep 15 07:52:26 2007
@@ -292,7 +292,7 @@
             yield data
             data = data()
         items = []
-        for i in data._beacon_tree():
+        for i in data.get_ancestors():
             if i._beacon_id:
                 break
             items.append(i)
@@ -373,7 +373,7 @@
             yield data
             data = data()
         items = []
-        for i in data._beacon_tree():
+        for i in data.get_ancestors():
             if i._beacon_id:
                 break
             items.append(i)

-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2005.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
_______________________________________________
Freevo-cvslog mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/freevo-cvslog

Reply via email to