[Deskbar] Currency Convertor extension



Hi,

thanks a lot for Deskbar, I like it...

I was missing calculator extension (BTW should be includeded in main
stream program by default), and also currency convertor - which I
haven't found at all..

So I made one - based on tutorial from wiki pages..

BTW I'm not sure if the downloading of rates from web is correct, it's
done in separate thread...

Some more refactoring, maybe GUI would be nice, but this runs for me,
so I'm sending it out if anybody else would like to run it too.. or
maybe make the code more nice.. :-)

Have a nice time

Klokan Petr Pridal

Currency Convertor extension for Deskbar
----------------------------------------
How does it run:
- if you type three letter code of currency, like USD - it shows you
exchange rate of that currency
- if you continue by some number (like "USD 1200") it shows you
exchange of that amount
- you can type then new currency code in the end to set other then
default target currency (like "USD 1200 CZK" shows "Exchange of
26602.25 CZK = 1200 USD"
- you can always click on it - it's one of actions, with nice icon :-)
- and then the exchange string is copied into clipboard...
- default target currency is "EUR", but its possible to change it in
code - variable "MYCURRENCY".
- exchange rate is downloaded during initialization of deskbar, once
per day at maximum, from webpage of European Central Bank
"""
Currency Convertor extension for Deskbar
----------------------------------------
How does it run:
- if you type three letter code of currency, like USD - it shows you exchange rate of that currency
- if you continue by some number (like "USD 1200") it shows you exchange of that amount
- you can type then new currency code in the end to set other then default target currency (like "USD 1200 CZK" shows "Exchange of 26602.25 CZK = 1200 USD"
- you can always click on it - it's one of actions, with nice icon :-) - and then the exchange string is copied into clipboard...
- default target currency is "EUR", but its possible to change in code - variable "MYCURRENCY".
- exchange rate is downloaded during initialization of deskbar, once per day at maximum, from webpage of European Central Bank

Copyright (C) 2006 Klokan Petr Pridal - www.klokan.cz
"""

from gettext import gettext as _

import gtk
import deskbar
from deskbar.Handler import Handler
from deskbar.Match import Match

import re
import os
from os.path import expanduser
import time, threading
#import traceback

MYCURRENCY="EUR" # One day from locale, or asked in GUI?

HANDLERS = {
        "CurrencyHandler" : {
                "name": _("Currency convertor"),
                "description": _("Type text like \"USD 34.5 EUR\", result is copied to clipboard"),
        }
}

RATESFILE = expanduser('~/.gnome2/deskbar-applet/eurofxref-daily.xml')

NUMBEREXPR = re.compile(r"(\d+(\.\d*)?|\.\d+)")

SUPPORTED = {
 "USD":"US Dollar", 
 "JPY":"Japanese Yen",
 "DKK":"Danish Krone",
 "GBP":"Pound Sterling",        
 "SEK":"Swedish Krona",
 "CHF":"Swiss Franc", 
 "ISK":"Icelandic Krona",
 "NOK":"Norwegian Krone",
 "BGN":"Bulgarian Lev",
 "CYP":"Cyprus Pound",
 "CZK":"Czech Koruna",
 "EEK":"Estonian Kroon",
 "HUF":"Hungarian Forint",
 "LTL":"Lithuanian Litas",
 "LVL":"Latvian Lats",
 "MTL":"Maltese Lira",
 "PLN":"Polish Zloty",
 "ROL":"Romanian Leu",
 "SIT":"Slovenian Tolar",
 "SKK":"Slovakian Koruna",
 "TRL":"Old Turkish Lira (to 2004)",
 "TRY":"New Turkish Lira (2005)",
 "AUD":"Australian Dollar",
 "CAD":"Canadian Dollar",
 "HKD":"Hong Kong Dollar",
 "NZD":"New Zealand Dollar",
 "SGD":"Singapore Dollar",
 "KRW":"South Korean Won",
 "EUR":"European Euro",
 "ZAR":"South African Rand"
}

def download_rates():
        conn = HTTPConnection("www.ecb.int")
        conn.request('GET','/stats/eurofxref/eurofxref-daily.xml')
        r = conn.getresponse()
        s = r.read()
        conn.close()
        f = open(RATESFILE, 'w')
        f.write(s)
        f.close()

class CurrencyMatch(Match):
        def __init__(self, backend, **args):
                deskbar.Match.Match.__init__(self, backend, **args)
                
        def action(self, text=None):
                for clipboard in ('CLIPBOARD', 'PRIMARY'):
                        gtk.clipboard_get(clipboard).set_text(self.name)

        def get_category(self):
                return "actions"

        def get_verb(self):
                return _("Exchange of <b>%(name)s</b> (copy to clipboard)")
        
        def get_hash(self, text=None):
                return self.name

class CurrencyHandler(Handler):
        def __init__(self):
                deskbar.Handler.Handler.__init__(self, "gnome-finance")
                self.rates = None

        def initialize(self):
                if not os.path.isfile(RATESFILE) or ((time.time() - os.path.getmtime(RATESFILE)) / 3600 > 24):
                        thr = threading.Thread(target= download_rates)
                        thr.start()

        def load_rates(self):
                f = open(RATESFILE)
                s = f.read()
                f.close()
                l = re.findall(r"currency='([\w]*)' rate='([0-9\.]*)'", s)
                self.rates = { 'EUR' : 1 }
                for i in l:
                    self.rates[i[0]] = float( i[1] )

        def query(self, query):
                try:
                        query = query.upper()
                        if not self.rates:
                            self.load_rates()
                        result = ""
                        if SUPPORTED.has_key(query[:3]):
                            currency_from = query[:3]
                            currency_to = MYCURRENCY
                            if SUPPORTED.has_key(query[3:][-3:]):
                                currency_to = query[-3:]
                            amount = 1
                            if len(query) > 3:
                                amount = NUMBEREXPR.search(query[3:]).group(1)
                            result = "%.2f %s = %s %s" % (  self.rates[currency_to] / self.rates[currency_from] * float(amount),
                                currency_to, amount, currency_from)
                        else:
                            raise
                        return [CurrencyMatch(self, name=result)]
                except:
                        #print traceback.format_exc()
                        return []


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]