add a 'clear cache' button in the settings
authorRyan Campbell <campbellr@gmail.com>
Sat, 22 Jan 2011 06:25:01 +0000 (23:25 -0700)
committerRyan Campbell <campbellr@gmail.com>
Sun, 23 Jan 2011 21:46:29 +0000 (14:46 -0700)
add a clear cache button in settings
make sure we have a ~/.mevemon/ dir before setting up logging

package/src/apicache.py
package/src/constants.py
package/src/fetchimg.py
package/src/mevemon.py
package/src/ui/fremantle/dialogs.py
package/src/ui/fremantle/gui.py
package/src/ui/fremantle/menu.py

index f2cfbb2..9e19723 100644 (file)
@@ -1,10 +1,11 @@
 import time
-import tempfile
 import cPickle
 import zlib
 import os
 from os.path import join, exists
 
+from constants import APICACHE_PATH
+
 class cache_handler( object ):
     # adapted from http://home.wanadoo.nl/ntt/eve/library/files/api/apitest.py (does this satisfy the terms of the license?), will need work, but we need basic cache functionality... I feel guilty for abusing the server. FIXME --danny
     
@@ -12,69 +13,72 @@ class cache_handler( object ):
         self.debug = debug
         self.count = 0
         self.cache = {}
-        self.tempdir = join( tempfile.gettempdir(), "eveapi" )
-        if not exists( self.tempdir ):
-            os.makedirs( self.tempdir )
+        self.tempdir = APICACHE_PATH
+        if not exists(self.tempdir):
+            os.makedirs(self.tempdir)
             
     # remove this later --danny
     def log( self, what ):
         if self.debug:
-            print "[%d] %s" % ( self.count, what )
+            print "[%d] %s" % (self.count, what)
 
-    def retrieve( self, host, path, params ):
+    def retrieve(self, host, path, params):
         # eveapi asks if we have this request cached
-        key = hash( ( host, path, frozenset( params.items() ) ) )
+        key = hash((host, path, frozenset( params.items())))
 
         # for logging
         self.count += 1
         
         # see if we have the requested page cached...
-        cached = self.cache.get( key, None )
+        cached = self.cache.get(key, None)
         if cached:
             cacheFile = None
         else:
             # not in memory, maybe on disk --danny
-            cacheFile = join( self.tempdir, str( key ) + ".cache" )
-            if exists( cacheFile ):
-                self.log( "%s: retreiving from disk." % path )
-                f = open( cacheFile, "rb" )
-                cached = self.cache[key] = cPickle.loads( zlib.decompress( f.read() ) )
+            cacheFile = join(self.tempdir, str(key) + ".cache")
+            if exists(cacheFile):
+                self.log("%s: retreiving from disk." % path)
+                f = open(cacheFile, "rb")
+                cached = self.cache[key] = cPickle.loads(zlib.decompress(f.read()))
                 f.close()
 
         if cached:
             # check if the cached object is fresh enough
             if time.time() < cached[0]:
-                self.log( "%s: returning cached document." % path )
+                self.log("%s: returning cached document." % path)
                 # return the cached object
                 return cached[1]
 
                 # if it's stale, purge it --danny
-                self.log( "%s: cache expired, purging!" % path )
+                self.log("%s: cache expired, purging!" % path)
                 del self.cache[key]
                 if cacheFile:
-                    os.remove( cacheFile )
+                    os.remove(cacheFile)
 
-            self.log( "%s: not cached, fetching from server..." % path )
+            self.log("%s: not cached, fetching from server..." % path)
             # We didn't get a cache hit so return None to indicate that the data should be requested from server
             return None
     
-    def store( self, host, path, params, doc, obj ):
+    def store(self, host, path, params, doc, obj):
         # eveapi is asking us to cache an item
-        key = hash( ( host, path, frozenset( params.items() ) ) )
+        if not exists(self.tempdir):
+            os.makedirs(self.tempdir)
+        
+        key = hash((host, path, frozenset( params.items())))
         
         cachedFor = obj.cachedUntil - obj.currentTime
         if cachedFor:
-            self.log( "%s: cached (%d seconds)." % ( path, cachedFor ) )
+            self.log("%s: cached (%d seconds)." % (path, cachedFor))
             
             cachedUntil = time.time() + cachedFor
 
             # store in memory
-            cached = self.cache[key] = ( cachedUntil, obj )
+            cached = self.cache[key] = (cachedUntil, obj)
             
             # store in cache folder
-            cacheFile = join( self.tempdir, str( key ) + ".cache" )
-            f = open( cacheFile, "wb" )
-            f.write( zlib.compress( cPickle.dumps( cached, -1 ) ) )
+            cacheFile = join(self.tempdir, str(key) + ".cache")
+            f = open(cacheFile, "wb")
+            f.write(zlib.compress(cPickle.dumps(cached, -1)))
             f.close
 
 
index 9bd8396..2cd44a3 100644 (file)
@@ -1,9 +1,12 @@
 """ Contains all the constants that mevemon uses """
 import os
+import tempfile
 
 CONFIG_DIR = os.path.expanduser("~/.mevemon/")
 CONFIG_NAME = "mevemon.cfg"
 CONFIG_PATH = os.path.join(CONFIG_DIR, CONFIG_NAME)
+IMG_CACHE_PATH = os.path.join(CONFIG_DIR, "imgs")
+APICACHE_PATH = os.path.join(tempfile.gettempdir(), "eveapi")
 
 # Logging constants
 LOGNAME = "mevemon.log"
index d9d98e0..4480c58 100644 (file)
@@ -1,11 +1,13 @@
 import urllib
 import os.path
 
+from constants import CONFIG_DIR
+
 def portrait_filename( char_id, img_size ):
 
     err_img = "/usr/share/mevemon/imgs/error.jpg"
    
-    img_dir = os.path.expanduser("~/.mevemon/imgs/")
+    img_dir = os.path.join(CONFIG_DIR, "imgs/")
 
 
     # if asked for the large version, save it under a diff name --danny
index 9ee2bb5..8e116c9 100755 (executable)
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 #
 
-import os.path
+import os
 import time
 import sys
 import logging
 import logging.handlers
+import shutil
 
 import hildon
 import gtk
@@ -32,7 +33,8 @@ from eveapi import eveapi
 import fetchimg
 import apicache
 import file_settings as settings
-from constants import LOGPATH, MAXBYTES, LOGCOUNT
+from constants import LOGPATH, MAXBYTES, LOGCOUNT, CONFIG_DIR, IMG_CACHE_PATH
+from constants import APICACHE_PATH
 
 #ugly hack to check maemo version. any better way?
 if hasattr(hildon, "StackableWindow"):
@@ -169,7 +171,7 @@ class mEveMon:
 
         ui_char_list = []
         err_img = "/usr/share/mevemon/imgs/error.jpg"
-        err_txt = "Problem fetching info for account"
+        err_txt = "Problem fetching info for account (or no accounts added)"
 
         placeholder_chars = (err_txt, err_img, None)
         
@@ -283,6 +285,13 @@ class mEveMon:
 
         return (spps * time_diff) 
 
+    def clear_cache(self):
+        """ Clears all cached data (images and eveapi cache) """
+        try:
+            shutil.rmtree(IMG_CACHE_PATH)
+            shutil.rmtree(APICACHE_PATH)
+        except OSError, e:
+            logging.getLogger('mevemon').exception("Failed to clear cache")
 
 def excepthook(ex_type, value, tb):
     """ a replacement for the default exception handler that logs errors"""
@@ -291,6 +300,8 @@ def excepthook(ex_type, value, tb):
 
 def setupLogger():
     """ sets up the logging """
+    if not os.path.exists(CONFIG_DIR):
+        os.makedirs(CONFIG_DIR)
 
     logger = logging.getLogger("mevemon")
     logger.setLevel(logging.DEBUG)
index 1ad96d4..2db5a9e 100644 (file)
@@ -20,6 +20,11 @@ class SettingsDialog(gtk.Dialog):
 
         self.accounts = AccountsTreeView(gtk.HILDON_UI_MODE_NORMAL, self.controller)
         vbox.pack_start(self.accounts, False, False, 1)
+
+        clear_button = hildon.GtkButton(gtk.HILDON_SIZE_FINGER_HEIGHT | gtk.HILDON_SIZE_HALFSCREEN_WIDTH)
+        clear_button.set_label("Clear Cache")
+        clear_button.connect("clicked", self.on_clear_cache_clicked)
+        vbox.pack_start(clear_button, False, False, 1)
         
         # add butttons
         # all stock responses are negative, so we can use any positive value
@@ -47,6 +52,9 @@ class SettingsDialog(gtk.Dialog):
 
         self.destroy()
 
+    def on_clear_cache_clicked(self, button):
+        self.controller.clear_cache()
+
     def on_new_account_clicked(self):
         NewAccountDialog(self.win, self.controller)
         self.accounts.refresh()
index 8c8d045..a811d5f 100644 (file)
@@ -38,6 +38,7 @@ class mEveMonUI:
 
         # Create menu
         menu = Menu(self.win, self.controller)
+        menu.set_refresh_cb(self.refresh_clicked)
         # Attach menu to the window
         self.win.set_app_menu(menu)
 
@@ -71,6 +72,9 @@ class mEveMonUI:
             CharacterSheetUI(self.controller, char_name, uid)
         else:
             pass
+    
+    def report_error(self, error):
+        hildon.hildon_banner_show_information(self.win.get_toplevel(), '', error)
 
 
 class CharactersTreeView(hildon.GtkTreeView):
@@ -98,5 +102,6 @@ class CharactersTreeView(hildon.GtkTreeView):
         column.set_property("expand", True)
         self.append_column(column)
 
-    def refresh():
+    def refresh(self):
         self.char_model.get_characters()
+    
index d497e6b..fc7a378 100644 (file)
@@ -13,8 +13,12 @@ class Menu(hildon.AppMenu):
         hildon.AppMenu.__init__(self)
         self.win = win
         self.controller = controller
+        self.callback = lambda *args: None
         self.build_buttons()
 
+    def set_refresh_cb(self, callback):
+        self.callback = callback
+
     def build_buttons(self):
         for button_name in self.MENU_ITEMS:
             self.create_menu_button(button_name)
@@ -27,7 +31,7 @@ class Menu(hildon.AppMenu):
         self.append(button)
 
     def on_refresh_clicked(self, button):
-        pass
+        self.callback(button)
 
     def on_settings_clicked(self, button):
         setting_dialog = dialogs.SettingsDialog(self.win, self.controller)