forked from albertlauncher/python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurrency_converter.py
85 lines (66 loc) · 2.87 KB
/
currency_converter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# -*- coding: utf-8 -*-
"""Convert currencies.
Current backends: ECB, Yahoo.
Synopsis: <amount> <src currency> [to|as|in] <dest currency>"""
import re
import time
from urllib.request import urlopen
from xml.etree import ElementTree
from albertv0 import *
__iid__ = "PythonInterface/v0.1"
__prettyname__ = "Currency converter"
__version__ = "1.0"
__author__ = "Manuel Schneider"
__dependencies__ = []
iconPath = iconLookup('accessories-calculator')
if not iconPath:
iconPath = ":python_module"
class EuropeanCentralBank:
url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
def __init__(self):
self.lastUpdate = 0
self.exchange_rates = dict()
self.name = "European Central Bank"
def convert(self, amount, src, dst):
if self.lastUpdate < time.time()-10800: # Update every 3 hours
self.exchange_rates.clear()
with urlopen(EuropeanCentralBank.url) as response:
tree = ElementTree.fromstring(response.read().decode())
for child in tree[2][0]:
curr = child.attrib['currency']
rate = float(child.attrib['rate'])
self.exchange_rates[curr] = rate
self.exchange_rates["EUR"] = 1.0 # For simpler algorithmic
info("%s: Updated foreign exchange rates." % __prettyname__)
debug(str(self.exchange_rates))
self.lastUpdate = time.time()
if src in self.exchange_rates and dst in self.exchange_rates:
src_rate = self.exchange_rates[src]
dst_rate = self.exchange_rates[dst]
return str(amount / src_rate * dst_rate)
class Yahoo:
def __init__(self):
self.name = "Yahoo"
def convert(self, amount, src, dst):
url = 'https://search.yahoo.com/search?p=%s+%s+to+%s' % (amount, src, dst)
with urlopen(url) as response:
html = response.read().decode()
m = re.search('<span class=.*convert-to.*>(\d+(\.\d+)?)', html)
if m:
return m.group(1)
providers = [EuropeanCentralBank(), Yahoo()]
regex = re.compile(r"(\d+\.?\d*)\s+(\w{3})(?:\s+(?:to|in|as))?\s+(\w{3})")
def handleQuery(query):
match = regex.fullmatch(query.string.strip())
if match:
prep = (float(match.group(1)), match.group(2).upper(), match.group(3).upper())
item = Item(id=__prettyname__, icon=iconPath, completion=query.rawString)
for provider in providers:
result = provider.convert(*prep)
if result:
item.text = result
item.subtext = "Value of %s %s in %s (Source: %s)" % (*prep, provider.name)
item.addAction(ClipAction("Copy result to clipboard", result))
return item
else:
warning("None of the foreign exchange rate providers came up with a result for %s" % str(prep))