URI: 
       trequest history rates asynchronously - electrum - Electrum Bitcoin wallet
  HTML git clone https://git.parazyd.org/electrum
   DIR Log
   DIR Files
   DIR Refs
   DIR Submodules
       ---
   DIR commit 6cd00eb36b9759bd9e4d4c725c60e76dcc40ab42
   DIR parent 692f49e7af9af6fabd8c4deac67a32070bfb3f4e
  HTML Author: ThomasV <thomasv@gitorious>
       Date:   Fri, 19 Sep 2014 13:36:30 +0200
       
       request history rates asynchronously
       
       Diffstat:
         M gui/qt/main_window.py               |      10 +---------
         M gui/qt/util.py                      |       9 +++++++++
         M plugins/exchange_rate.py            |     162 ++++++++++++++++---------------
       
       3 files changed, 95 insertions(+), 86 deletions(-)
       ---
   DIR diff --git a/gui/qt/main_window.py b/gui/qt/main_window.py
       t@@ -49,19 +49,11 @@ from qrtextedit import QRTextEdit
        
        from decimal import Decimal
        
       -import platform
        import httplib
        import socket
        import webbrowser
        import csv
        
       -if platform.system() == 'Windows':
       -    MONOSPACE_FONT = 'Lucida Console'
       -elif platform.system() == 'Darwin':
       -    MONOSPACE_FONT = 'Monaco'
       -else:
       -    MONOSPACE_FONT = 'monospace'
       -
        
        
        # status of payment requests
       t@@ -77,7 +69,7 @@ import re
        
        from util import MyTreeWidget, HelpButton, EnterButton, line_dialog, text_dialog, ok_cancel_buttons, close_button, WaitingDialog
        from util import filename_field, ok_cancel_buttons2, address_field
       -
       +from util import MONOSPACE_FONT
        
        def format_status(x):
            if x == PR_UNPAID:
   DIR diff --git a/gui/qt/util.py b/gui/qt/util.py
       t@@ -6,6 +6,15 @@ import time
        import traceback
        import sys
        import threading
       +import platform
       +
       +if platform.system() == 'Windows':
       +    MONOSPACE_FONT = 'Lucida Console'
       +elif platform.system() == 'Darwin':
       +    MONOSPACE_FONT = 'Monaco'
       +else:
       +    MONOSPACE_FONT = 'monospace'
       +
        
        class WaitingDialog(QThread):
            def __init__(self, parent, message, run_task, on_complete=None):
   DIR diff --git a/plugins/exchange_rate.py b/plugins/exchange_rate.py
       t@@ -347,6 +347,8 @@ class Plugin(BasePlugin):
                self.win = self.gui.main_window
                self.win.connect(self.win, SIGNAL("refresh_currencies()"), self.win.update_status)
                self.btc_rate = Decimal("0.0")
       +        self.resp_hist = {}
       +        self.tx_list = {}
                if self.exchanger is None:
                    # Do price discovery
                    self.exchanger = Exchanger(self)
       t@@ -416,103 +418,109 @@ class Plugin(BasePlugin):
                    tx_list[tx_hash] = {'value': value, 'timestamp': timestamp, 'balance': balance}
        
                self.tx_list = tx_list
       +        self.cur_exchange = self.config.get('use_exchange', "Blockchain")
       +        threading.Thread(target=self.request_history_rates, args=()).start()
        
        
            def requires_settings(self):
                return True
        
        
       -    @hook
       -    def history_tab_update(self):
       -        if self.config.get('history_rates', 'unchecked') == "checked":
       -            cur_exchange = self.config.get('use_exchange', "Blockchain")
       +    def request_history_rates(self):
       +        if self.config.get('history_rates') != "checked":
       +            return
       +        if not self.tx_list:
       +            return
       +
       +        try:
       +            mintimestr = datetime.datetime.fromtimestamp(int(min(self.tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
       +        except Exception:
       +            return
       +        maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
       +
       +        if self.cur_exchange == "CoinDesk":
                    try:
       -                tx_list = self.tx_list
       +                self.resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
                    except Exception:
                        return
       -
       +        elif self.cur_exchange == "Winkdex":
                    try:
       -                mintimestr = datetime.datetime.fromtimestamp(int(min(tx_list.items(), key=lambda x: x[1]['timestamp'])[1]['timestamp'])).strftime('%Y-%m-%d')
       +                self.resp_hist = self.exchanger.get_json('winkdex.com', "/api/v0/series?start_time=1342915200")['series'][0]['results']
                    except Exception:
                        return
       -            maxtimestr = datetime.datetime.now().strftime('%Y-%m-%d')
       -
       -            if cur_exchange == "CoinDesk":
       +        elif self.cur_exchange == "BitcoinVenezuela":
       +            cur_currency = self.fiat_unit()
       +            if cur_currency == "VEF":
                        try:
       -                    resp_hist = self.exchanger.get_json('api.coindesk.com', "/v1/bpi/historical/close.json?start=" + mintimestr + "&end=" + maxtimestr)
       +                    self.resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['VEF_BTC']
                        except Exception:
                            return
       -            elif cur_exchange == "Winkdex":
       +            elif cur_currency == "ARS":
                        try:
       -                    resp_hist = self.exchanger.get_json('winkdex.com', "/api/v0/series?start_time=1342915200")['series'][0]['results']
       +                    self.resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['ARS_BTC']
                        except Exception:
                            return
       -            elif cur_exchange == "BitcoinVenezuela":
       -                cur_currency = self.fiat_unit()
       -                if cur_currency == "VEF":
       -                    try:
       -                        resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['VEF_BTC']
       -                    except Exception:
       -                        return
       -                elif cur_currency == "ARS":
       -                    try:
       -                        resp_hist = self.exchanger.get_json('api.bitcoinvenezuela.com', "/historical/index.php?coin=BTC")['ARS_BTC']
       -                    except Exception:
       -                        return
       -                else:
       -                    return
       +            else:
       +                return
       +
       +        self.win.need_update.set()
       +
       +    @hook
       +    def history_tab_update(self):
       +        if self.config.get('history_rates') != "checked":
       +            return
       +        if not self.resp_hist:
       +            return
        
       -            self.gui.main_window.is_edit = True
       -            self.gui.main_window.history_list.setColumnCount(6)
       -            self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
       -            root = self.gui.main_window.history_list.invisibleRootItem()
       -            childcount = root.childCount()
       -            for i in range(childcount):
       -                item = root.child(i)
       +        self.gui.main_window.is_edit = True
       +        self.gui.main_window.history_list.setColumnCount(6)
       +        self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
       +        root = self.gui.main_window.history_list.invisibleRootItem()
       +        childcount = root.childCount()
       +        for i in range(childcount):
       +            item = root.child(i)
       +            try:
       +                tx_info = self.tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
       +            except Exception:
       +                newtx = self.wallet.get_tx_history()
       +                v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
       +                tx_info = {'timestamp':int(time.time()), 'value': v }
       +                pass
       +            tx_time = int(tx_info['timestamp'])
       +            if self.cur_exchange == "CoinDesk":
       +                tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
                        try:
       -                    tx_info = tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
       -                except Exception:
       -                    newtx = self.wallet.get_tx_history()
       -                    v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][3]
       +                    tx_fiat_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(self.resp_hist['bpi'][tx_time_str]), "USD")
       +                except KeyError:
       +                    tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/100000000 , "USD")
       +            elif self.cur_exchange == "Winkdex":
       +                tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d') + "T16:00:00-04:00"
       +                try:
       +                    tx_rate = self.resp_hist[[x['timestamp'] for x in self.resp_hist].index(tx_time_str)]['price']
       +                    tx_fiat_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(tx_rate)/Decimal("100.0"), "USD")
       +                except ValueError:
       +                    tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/100000000 , "USD")
       +                except KeyError:
       +                    tx_fiat_val = _("No data")
       +            elif self.cur_exchange == "BitcoinVenezuela":
       +                tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
       +                try:
       +                    num = self.resp_hist[tx_time_str].replace(',','')
       +                    tx_fiat_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(num), cur_currency)
       +                except KeyError:
       +                    tx_fiat_val = _("No data")
        
       -                    tx_info = {'timestamp':int(time.time()), 'value': v }
       -                    pass
       -                tx_time = int(tx_info['timestamp'])
       -                if cur_exchange == "CoinDesk":
       -                    tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
       -                    try:
       -                        tx_USD_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(resp_hist['bpi'][tx_time_str]), "USD")
       -                    except KeyError:
       -                        tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/100000000 , "USD")
       -                elif cur_exchange == "Winkdex":
       -                    tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d') + "T16:00:00-04:00"
       -                    try:
       -                        tx_rate = resp_hist[[x['timestamp'] for x in resp_hist].index(tx_time_str)]['price']
       -                        tx_USD_val = "%.2f %s" % (Decimal(tx_info['value']) / 100000000 * Decimal(tx_rate)/Decimal("100.0"), "USD")
       -                    except ValueError:
       -                        tx_USD_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/100000000 , "USD")
       -                    except KeyError:
       -                        tx_USD_val = _("No data")
       -                elif cur_exchange == "BitcoinVenezuela":
       -                    tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
       -                    try:
       -                        num = resp_hist[tx_time_str].replace(',','')
       -                        tx_BTCVEN_val = "%.2f %s" % (Decimal(str(tx_info['value'])) / 100000000 * Decimal(num), cur_currency)
       -                    except KeyError:
       -                        tx_BTCVEN_val = _("No data")
       -
       -                if cur_exchange in ["CoinDesk", "Winkdex"]:
       -                    item.setText(5, tx_USD_val)
       -                elif cur_exchange == "BitcoinVenezuela":
       -                    item.setText(5, tx_BTCVEN_val)
       -                if Decimal(str(tx_info['value'])) < 0:
       -                    item.setForeground(5, QBrush(QColor("#BC1E1E")))
       -
       -            for i, width in enumerate(self.gui.main_window.column_widths['history']):
       -                self.gui.main_window.history_list.setColumnWidth(i, width)
       -            self.gui.main_window.history_list.setColumnWidth(4, 140)
       -            self.gui.main_window.history_list.setColumnWidth(5, 120)
       -            self.gui.main_window.is_edit = False
       +            tx_fiat_val = " "*(12-len(tx_fiat_val)) + tx_fiat_val
       +            item.setText(5, tx_fiat_val)
       +            item.setFont(5, QFont(MONOSPACE_FONT))
       +            if Decimal(str(tx_info['value'])) < 0:
       +                item.setForeground(5, QBrush(QColor("#BC1E1E")))
       +
       +        for i, width in enumerate(self.gui.main_window.column_widths['history']):
       +            self.gui.main_window.history_list.setColumnWidth(i, width)
       +        self.gui.main_window.history_list.setColumnWidth(4, 140)
       +        self.gui.main_window.history_list.setColumnWidth(5, 120)
       +        self.gui.main_window.is_edit = False
        
        
            def settings_widget(self, window):
       t@@ -574,7 +582,7 @@ class Plugin(BasePlugin):
                def on_change_hist(checked):
                    if checked:
                        self.config.set_key('history_rates', 'checked')
       -                self.history_tab_update()
       +                self.request_history_rates()
                    else:
                        self.config.set_key('history_rates', 'unchecked')
                        self.gui.main_window.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )