2022-02-28 20:03:21 +00:00
|
|
|
# Twisted/Klein imports
|
2022-07-15 10:09:54 +00:00
|
|
|
import urllib
|
|
|
|
from json import dumps, loads
|
|
|
|
from time import time
|
2022-02-28 20:03:21 +00:00
|
|
|
|
|
|
|
# Other library imports
|
|
|
|
import requests
|
2022-07-15 10:09:54 +00:00
|
|
|
import util
|
2022-04-09 18:59:22 +00:00
|
|
|
from lib.serde.truelayer import AccountBalancesRoot
|
|
|
|
from serde import ValidationError
|
2023-02-09 07:20:00 +00:00
|
|
|
|
2022-02-28 20:03:21 +00:00
|
|
|
# Project imports
|
|
|
|
from settings import settings
|
2022-07-15 10:09:54 +00:00
|
|
|
from simplejson.errors import JSONDecodeError
|
|
|
|
from twisted.internet.task import LoopingCall
|
2022-02-28 20:03:21 +00:00
|
|
|
|
|
|
|
|
2022-03-05 21:52:31 +00:00
|
|
|
class TrueLayer(util.Base):
|
2022-02-28 20:03:21 +00:00
|
|
|
"""
|
|
|
|
Class to manage calls to Open Banking APIs through TrueLayer.
|
|
|
|
"""
|
|
|
|
|
2022-03-07 19:59:30 +00:00
|
|
|
def __init__(self, sinks):
|
2022-03-05 21:52:31 +00:00
|
|
|
super().__init__()
|
2022-03-07 19:59:30 +00:00
|
|
|
self.sinks = sinks
|
2022-03-06 18:51:16 +00:00
|
|
|
self.tokens = {}
|
2022-03-07 19:59:30 +00:00
|
|
|
self.banks = {}
|
2022-03-08 20:42:47 +00:00
|
|
|
self.refresh_tokens = {}
|
|
|
|
self.authed = False
|
2022-03-07 19:59:30 +00:00
|
|
|
|
|
|
|
# Get the banks from the config and cache them
|
|
|
|
self.get_mapped_accounts()
|
2022-03-06 18:51:16 +00:00
|
|
|
|
|
|
|
# account we are authenticating - where to store the refresh keys
|
2022-03-07 19:59:30 +00:00
|
|
|
self.current_authcode_bank = None
|
2022-03-06 18:51:16 +00:00
|
|
|
self.lc = LoopingCall(self.get_new_tokens_all)
|
2022-03-07 19:59:30 +00:00
|
|
|
# self.get_new_tokens_all()
|
|
|
|
# self.get_new_token(bank)
|
|
|
|
# -> set self.tokens[bank] = access_token
|
|
|
|
self.lc.start(int(settings.TrueLayer.TokenRefreshSec))
|
|
|
|
|
2022-03-08 20:42:47 +00:00
|
|
|
def __authed__(self):
|
|
|
|
"""
|
|
|
|
Called when we have received all the API tokens.
|
|
|
|
"""
|
|
|
|
# Get the account information and pass it to the main function
|
|
|
|
self.log.info("All accounts authenticated: " + ", ".join(self.tokens.keys()))
|
|
|
|
account_infos = self.get_all_account_info()
|
|
|
|
self.sinks.got_account_info("truelayer", account_infos)
|
|
|
|
|
2022-03-07 19:59:30 +00:00
|
|
|
self.lc_tx = LoopingCall(self.transaction_loop)
|
|
|
|
self.lc_tx.start(int(settings.TrueLayer.RefreshSec))
|
|
|
|
|
|
|
|
def transaction_loop(self):
|
|
|
|
for bank in self.banks:
|
|
|
|
for account_id in self.banks[bank]:
|
|
|
|
# account_data = self.get_account(bank, account_id)
|
|
|
|
transactions = self.get_transactions(bank, account_id)
|
2022-03-25 18:46:08 +00:00
|
|
|
self.sinks.got_transactions("truelayer", account_id, transactions)
|
2022-02-28 20:03:21 +00:00
|
|
|
|
2022-03-06 18:51:16 +00:00
|
|
|
def add_refresh_token(self, refresh_token):
|
|
|
|
"""
|
|
|
|
Add an API key to the configuration.
|
|
|
|
Data type: {"monzo": refresh_token,
|
|
|
|
"revolut": refresh_token}
|
|
|
|
"""
|
2022-03-07 19:59:30 +00:00
|
|
|
account = self.current_authcode_bank
|
2022-03-06 18:51:16 +00:00
|
|
|
if not account:
|
|
|
|
return False
|
|
|
|
existing_entry = loads(settings.TrueLayer.RefreshKeys)
|
|
|
|
existing_entry[account] = refresh_token
|
|
|
|
settings.TrueLayer.RefreshKeys = dumps(existing_entry)
|
2022-03-07 19:59:30 +00:00
|
|
|
# Set the cached entry
|
|
|
|
self.refresh_tokens = existing_entry
|
2022-03-06 18:51:16 +00:00
|
|
|
settings.write()
|
|
|
|
|
2022-03-07 19:59:30 +00:00
|
|
|
# def get_refresh_tokens(self):
|
|
|
|
# existing_entry = loads(settings.TrueLayer.RefreshKeys)
|
|
|
|
# return existing_entry
|
2022-03-06 18:51:16 +00:00
|
|
|
|
2022-03-07 19:59:30 +00:00
|
|
|
def get_key(self, bank):
|
|
|
|
if bank in self.tokens:
|
|
|
|
return self.tokens[bank]
|
2022-03-06 18:51:16 +00:00
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
2022-03-07 19:59:30 +00:00
|
|
|
def create_auth_url(self, bank):
|
2022-03-01 20:39:22 +00:00
|
|
|
query = urllib.parse.urlencode(
|
|
|
|
{
|
|
|
|
"response_type": "code",
|
|
|
|
"response_mode": "form_post",
|
|
|
|
"client_id": settings.TrueLayer.ID,
|
|
|
|
"scope": "info accounts balance transactions offline_access",
|
|
|
|
"nonce": int(time()),
|
|
|
|
"redirect_uri": settings.TrueLayer.CallbackURL,
|
|
|
|
"enable_mock": "true",
|
|
|
|
}
|
|
|
|
)
|
|
|
|
auth_uri = f"{settings.TrueLayer.AuthBase}/?{query}&redirect_uri={settings.TrueLayer.CallbackURL}"
|
2022-03-07 19:59:30 +00:00
|
|
|
self.current_authcode_bank = bank
|
2022-03-01 20:39:22 +00:00
|
|
|
return auth_uri
|
|
|
|
|
|
|
|
def handle_authcode_received(self, authcode):
|
2022-02-28 20:03:21 +00:00
|
|
|
data = {
|
|
|
|
"client_id": settings.TrueLayer.ID,
|
|
|
|
"client_secret": settings.TrueLayer.Key,
|
2022-03-01 20:39:22 +00:00
|
|
|
"code": authcode,
|
|
|
|
"grant_type": "authorization_code",
|
|
|
|
"redirect_uri": settings.TrueLayer.CallbackURL,
|
2022-02-28 20:03:21 +00:00
|
|
|
}
|
2022-03-01 20:39:22 +00:00
|
|
|
r = requests.post(f"{settings.TrueLayer.AuthBase}/connect/token", data=data)
|
2022-02-28 20:03:21 +00:00
|
|
|
try:
|
|
|
|
parsed = r.json()
|
|
|
|
except JSONDecodeError:
|
|
|
|
return False
|
2022-03-01 20:39:22 +00:00
|
|
|
if "error" in parsed:
|
2022-03-06 18:51:16 +00:00
|
|
|
self.log.error("Error requesting refresh token: {parsed['error']}")
|
2022-02-28 20:03:21 +00:00
|
|
|
return False
|
|
|
|
|
2022-03-06 18:51:16 +00:00
|
|
|
# Extract the access tokens
|
|
|
|
refresh_token = parsed["refresh_token"]
|
|
|
|
access_token = parsed["access_token"]
|
|
|
|
|
|
|
|
# Add the refresh token
|
|
|
|
self.add_refresh_token(refresh_token)
|
|
|
|
|
|
|
|
# Add the access
|
2022-03-07 19:59:30 +00:00
|
|
|
if self.current_authcode_bank:
|
|
|
|
self.tokens[self.current_authcode_bank] = access_token
|
2022-03-06 18:51:16 +00:00
|
|
|
else:
|
2022-06-04 12:42:25 +00:00
|
|
|
self.log.error("Received an authcode we didn't ask for")
|
2022-03-06 18:51:16 +00:00
|
|
|
return
|
2022-07-15 10:09:54 +00:00
|
|
|
self.log.info(
|
|
|
|
f"Retrieved access/refresh tokens for {self.current_authcode_bank}"
|
|
|
|
)
|
2022-03-06 18:51:16 +00:00
|
|
|
|
|
|
|
def get_new_tokens_all(self):
|
2022-03-07 19:59:30 +00:00
|
|
|
refresh_tokens = loads(settings.TrueLayer.RefreshKeys)
|
|
|
|
# Set the cached entry
|
|
|
|
self.refresh_tokens = refresh_tokens
|
2022-03-08 20:42:47 +00:00
|
|
|
|
2022-03-07 19:59:30 +00:00
|
|
|
for bank in refresh_tokens:
|
2022-03-08 20:42:47 +00:00
|
|
|
rtrn = self.get_new_token(bank)
|
|
|
|
if not rtrn:
|
|
|
|
self.log.error(f"Error getting token for {bank}")
|
|
|
|
return
|
2022-03-06 18:51:16 +00:00
|
|
|
|
2022-03-07 19:59:30 +00:00
|
|
|
def get_new_token(self, bank):
|
2022-02-28 20:03:21 +00:00
|
|
|
"""
|
|
|
|
Exchange our refresh token for an access token.
|
2022-03-06 18:51:16 +00:00
|
|
|
:param account: account to refresh the token for
|
|
|
|
:type account:
|
2022-02-28 20:03:21 +00:00
|
|
|
"""
|
2022-03-07 19:59:30 +00:00
|
|
|
if bank not in self.refresh_tokens:
|
2022-03-08 20:42:47 +00:00
|
|
|
self.log.error(f"Bank {bank} not in refresh tokens")
|
2022-03-01 20:39:22 +00:00
|
|
|
return
|
2022-03-06 18:51:16 +00:00
|
|
|
|
2022-02-28 20:09:19 +00:00
|
|
|
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
|
|
|
data = {
|
|
|
|
"grant_type": "refresh_token",
|
2022-03-07 19:59:30 +00:00
|
|
|
"refresh_token": self.refresh_tokens[bank],
|
2022-02-28 20:09:19 +00:00
|
|
|
"client_id": settings.TrueLayer.ID,
|
|
|
|
"client_secret": settings.TrueLayer.Key,
|
|
|
|
}
|
2022-04-12 21:06:28 +00:00
|
|
|
r = requests.post(
|
|
|
|
f"{settings.TrueLayer.AuthBase}/connect/token",
|
|
|
|
data=data,
|
|
|
|
headers=headers,
|
|
|
|
)
|
2022-02-28 20:09:19 +00:00
|
|
|
try:
|
|
|
|
parsed = r.json()
|
|
|
|
except JSONDecodeError:
|
2022-03-08 20:42:47 +00:00
|
|
|
self.log.error(f"Failed to decode JSON: {r.content}")
|
2022-02-28 20:09:19 +00:00
|
|
|
return False
|
|
|
|
if r.status_code == 200:
|
|
|
|
if "access_token" in parsed.keys():
|
2022-03-07 19:59:30 +00:00
|
|
|
self.tokens[bank] = parsed["access_token"]
|
2022-03-08 20:42:47 +00:00
|
|
|
# self.log.info(f"Refreshed access token for {bank}")
|
2022-07-15 10:09:54 +00:00
|
|
|
if (
|
|
|
|
len(self.refresh_tokens.keys()) == len(self.tokens.keys())
|
|
|
|
and not self.authed
|
|
|
|
):
|
2022-03-08 20:42:47 +00:00
|
|
|
# We are now fully authenticated and ready to start loops!
|
|
|
|
self.__authed__()
|
|
|
|
self.authed = True
|
2022-02-28 20:09:19 +00:00
|
|
|
return True
|
|
|
|
else:
|
2022-03-08 20:42:47 +00:00
|
|
|
self.log.error(f"Token refresh didn't contain access token: {parsed}")
|
2022-02-28 20:09:19 +00:00
|
|
|
return False
|
|
|
|
else:
|
2022-03-08 20:42:47 +00:00
|
|
|
self.log.error(f"Cannot refresh token: {parsed}")
|
2022-02-28 20:09:19 +00:00
|
|
|
return False
|
2022-02-28 20:03:21 +00:00
|
|
|
|
2022-03-07 19:59:30 +00:00
|
|
|
def get_accounts(self, bank):
|
2022-02-28 20:03:21 +00:00
|
|
|
"""
|
2022-03-01 20:39:22 +00:00
|
|
|
Get a list of accounts.
|
2022-02-28 20:03:21 +00:00
|
|
|
"""
|
2022-03-07 19:59:30 +00:00
|
|
|
token = self.get_key(bank)
|
2022-03-06 18:51:16 +00:00
|
|
|
headers = {"Authorization": f"Bearer {token}"}
|
2022-03-04 21:06:54 +00:00
|
|
|
path = f"{settings.TrueLayer.DataBase}/accounts"
|
2022-03-01 20:39:22 +00:00
|
|
|
r = requests.get(path, headers=headers)
|
2022-02-28 20:03:21 +00:00
|
|
|
try:
|
|
|
|
parsed = r.json()
|
|
|
|
except JSONDecodeError:
|
2022-07-15 10:09:54 +00:00
|
|
|
self.log.error(
|
|
|
|
"Error parsing accounts response: {content}", content=r.content
|
|
|
|
)
|
2022-02-28 20:03:21 +00:00
|
|
|
return False
|
2022-03-04 21:06:54 +00:00
|
|
|
|
2022-02-28 20:03:21 +00:00
|
|
|
return parsed
|
2022-03-05 21:52:31 +00:00
|
|
|
|
2022-03-07 19:59:30 +00:00
|
|
|
def _get_account(self, bank, account_id):
|
|
|
|
token = self.get_key(bank)
|
|
|
|
headers = {"Authorization": f"Bearer {token}"}
|
|
|
|
path = f"{settings.TrueLayer.DataBase}/accounts/{account_id}"
|
|
|
|
r = requests.get(path, headers=headers)
|
|
|
|
try:
|
|
|
|
parsed = r.json()
|
|
|
|
except JSONDecodeError:
|
2022-03-08 20:42:47 +00:00
|
|
|
self.log.error(f"Error parsing accounts response: {r.content}")
|
2022-03-07 19:59:30 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
return parsed
|
|
|
|
|
|
|
|
def get_mapped_accounts(self):
|
|
|
|
existing_entry = loads(settings.TrueLayer.Maps)
|
|
|
|
self.banks = existing_entry
|
|
|
|
|
2022-03-08 20:42:47 +00:00
|
|
|
def get_all_account_info(self):
|
|
|
|
to_return = {}
|
|
|
|
for bank in self.banks:
|
|
|
|
for account_id in self.banks[bank]:
|
|
|
|
account_data = self.get_account(bank, account_id)
|
|
|
|
if bank in to_return:
|
|
|
|
to_return[bank].append(account_data)
|
|
|
|
else:
|
|
|
|
to_return[bank] = [account_data]
|
|
|
|
return to_return
|
|
|
|
|
2022-03-07 19:59:30 +00:00
|
|
|
def get_account(self, bank, account_id):
|
|
|
|
account_data = self._get_account(bank, account_id)
|
|
|
|
if "results" not in account_data:
|
|
|
|
return False
|
|
|
|
if not len(account_data["results"]) == 1:
|
|
|
|
return False
|
|
|
|
if not len(account_data) == 2:
|
|
|
|
return False
|
|
|
|
if not account_data["status"] == "Succeeded":
|
|
|
|
return False
|
|
|
|
base = account_data["results"][0]
|
|
|
|
return base
|
|
|
|
|
|
|
|
def map_account(self, bank, account_id):
|
|
|
|
"""
|
|
|
|
Map an account_id at a bank to an account_name.
|
|
|
|
This enables the account for fetching.
|
|
|
|
Data type: {"monzo": [account, ids, here],
|
|
|
|
"revolut": [account, ids, here]}
|
|
|
|
"""
|
|
|
|
account_data = self.get_account(bank, account_id)
|
|
|
|
currency = account_data["currency"]
|
|
|
|
|
|
|
|
existing_entry = loads(settings.TrueLayer.Maps)
|
|
|
|
if bank in existing_entry:
|
|
|
|
if account_id not in existing_entry[bank]:
|
|
|
|
existing_entry[bank].append(account_id)
|
|
|
|
else:
|
|
|
|
existing_entry[bank] = [account_id]
|
|
|
|
settings.TrueLayer.Maps = dumps(existing_entry)
|
|
|
|
self.banks = existing_entry
|
|
|
|
settings.write()
|
|
|
|
|
|
|
|
return currency
|
|
|
|
|
|
|
|
def get_transactions(self, bank, account_id):
|
2022-03-05 21:52:31 +00:00
|
|
|
"""
|
|
|
|
Get a list of transactions from an account.
|
|
|
|
:param account_id: account to fetch transactions for
|
|
|
|
:return: list of transactions
|
|
|
|
:rtype: dict
|
|
|
|
"""
|
2022-03-07 19:59:30 +00:00
|
|
|
token = self.get_key(bank)
|
2022-03-06 18:51:16 +00:00
|
|
|
headers = {"Authorization": f"Bearer {token}"}
|
2022-03-05 21:52:31 +00:00
|
|
|
path = f"{settings.TrueLayer.DataBase}/accounts/{account_id}/transactions"
|
|
|
|
r = requests.get(path, headers=headers)
|
|
|
|
try:
|
|
|
|
parsed = r.json()
|
|
|
|
except JSONDecodeError:
|
2022-03-08 20:42:47 +00:00
|
|
|
self.log.error(f"Error parsing transactions response: {r.content}")
|
2022-04-09 18:59:22 +00:00
|
|
|
return (False, False)
|
2022-03-08 20:42:47 +00:00
|
|
|
if "results" in parsed:
|
|
|
|
return parsed["results"]
|
|
|
|
else:
|
2022-04-09 18:59:22 +00:00
|
|
|
return (False, False)
|
|
|
|
|
|
|
|
def get_balance(self, bank, account_id):
|
|
|
|
"""
|
|
|
|
Get the balance of an account.
|
|
|
|
:param bank: the bank to check
|
|
|
|
:param account_id: the account ID
|
|
|
|
:return: tuple of (currency, amount)
|
|
|
|
:rtype: tuple
|
|
|
|
"""
|
|
|
|
token = self.get_key(bank)
|
|
|
|
headers = {"Authorization": f"Bearer {token}"}
|
|
|
|
path = f"{settings.TrueLayer.DataBase}/accounts/{account_id}/balance"
|
|
|
|
r = requests.get(path, headers=headers)
|
|
|
|
try:
|
|
|
|
obj = AccountBalancesRoot.from_json(r.content)
|
|
|
|
except ValidationError as err:
|
|
|
|
self.log.error(f"Validation error: {err}")
|
|
|
|
return
|
|
|
|
parsed = obj.to_dict()["results"]
|
|
|
|
total = 0
|
|
|
|
currency = None
|
|
|
|
for entry in parsed:
|
|
|
|
if currency:
|
|
|
|
if not currency == entry["currency"]:
|
|
|
|
self.log.error("Different currencies in balance query.")
|
|
|
|
return
|
|
|
|
total += entry["available"]
|
|
|
|
currency = entry["currency"]
|
|
|
|
return (currency, total)
|
|
|
|
|
|
|
|
def get_total_map(self):
|
|
|
|
"""
|
|
|
|
Return a dictionary keyed by currencies with the amounts as values.
|
|
|
|
:return: dict keyed by currency, values are amounts
|
|
|
|
:rtype: dict
|
|
|
|
"""
|
|
|
|
totals = {}
|
|
|
|
for bank in self.banks:
|
|
|
|
for account_id in self.banks[bank]:
|
|
|
|
currency, amount = self.get_balance(bank, account_id)
|
|
|
|
if not amount:
|
|
|
|
continue
|
|
|
|
if currency in totals:
|
|
|
|
totals[currency] += amount
|
|
|
|
else:
|
|
|
|
totals[currency] = amount
|
|
|
|
return totals
|