Exemplo n.º 1
0
def setup(hass, config):
    """Set up N26 Component."""
    user = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]

    from n26 import api, config as api_config
    api = api.Api(api_config.Config(user, password))

    from requests import HTTPError
    try:
        api.get_token()
    except HTTPError as err:
        _LOGGER.error(str(err))
        return False

    api_data = N26Data(api)
    api_data.update()

    hass.data[DOMAIN] = {}
    hass.data[DOMAIN][DATA] = api_data

    # Load components for supported devices
    for component in N26_COMPONENTS:
        load_platform(hass, component, DOMAIN, {}, config)

    return True
Exemplo n.º 2
0
def setup(hass, config):
    """Set up N26 Component."""
    acc_list = config[DOMAIN]

    api_data_list = []

    for acc in acc_list:
        user = acc[CONF_USERNAME]
        password = acc[CONF_PASSWORD]

        api = n26_api.Api(n26_config.Config(user, password))

        try:
            api.get_token()
        except HTTPError as err:
            _LOGGER.error(str(err))
            return False

        api_data = N26Data(api)
        api_data.update()

        api_data_list.append(api_data)

    hass.data[DOMAIN] = {}
    hass.data[DOMAIN][DATA] = api_data_list

    # Load components for supported devices
    for component in N26_COMPONENTS:
        load_platform(hass, component, DOMAIN, {}, config)

    return True
Exemplo n.º 3
0
def card_unblock():
    """ Unblocks the card. """
    card = api.Api()
    for i in card.get_cards():
        card_id = i['id']
        card.unblock_card(card_id)
        print('Unblocked card: ' + card_id)
Exemplo n.º 4
0
 def test_init_with_config(self):
     conf = config.Config(username='******',
                          password='******',
                          login_data_store_path=None)
     api_client = api.Api(conf)
     self.assertIsNotNone(api_client.config)
     self.assertEqual(api_client.config, conf)
Exemplo n.º 5
0
 def test_init_with_config(self):
     from container_app_conf.source.yaml_source import YamlSource
     conf = config.Config(
         singleton=False,
         data_sources=[YamlSource("test_creds", "./tests/")])
     api_client = api.Api(conf)
     self.assertIsNotNone(api_client.config)
     self.assertEqual(api_client.config, conf)
Exemplo n.º 6
0
def test_get_token():
    with mock.patch('n26.api.requests.post') as mock_post:
        mock_post.return_value.json.return_value = {
            'access_token': 'some token'
        }
        new_api = api.Api(conf)
        token = new_api.get_token()
    assert token == 'some token'
Exemplo n.º 7
0
    def setUp(self):
        """
        This method is called BEFORE each individual test case
        """
        from n26 import api, config

        # use test file path instead of real one
        config.CONFIG_FILE_PATH = self.CONFIG_FILE

        self._underTest = api.Api()
Exemplo n.º 8
0
def info():
    """ Get account information """
    account_info = api.Api()
    print('Account info:')
    print('-------------')
    # TODO: make it python2 compatible using unicode
    print('Name: ' + str(account_info.get_account_info()['firstName'] + ' ' +
                         account_info.get_account_info()['lastName']))
    print('Email: ' + account_info.get_account_info()['email'])
    print('Nationality: ' + account_info.get_account_info()['nationality'])
    print('Phone: ' + account_info.get_account_info()['mobilePhoneNumber'])
Exemplo n.º 9
0
def test_get_token():
    with mock.patch('n26.api.requests.post') as mock_post:
        mock_post.return_value.json.return_value = {
            'access_token': '12345678-1234-1234-1234-123456789012',
            'token_type': 'bearer',
            'refresh_token': '12345678-1234-1234-1234-123456789012',
            'expires_in': 1798,
            'scope': 'trust',
            'host_url': 'https://api.tech26.de'
        }
        new_api = api.Api(conf)
        token = new_api._get_token()
    assert token == 'some token'
Exemplo n.º 10
0
def spaces():
    """ Show spaces """
    spaces = api.Api()
    print('Spaces:')
    print('----------------')
    for space in spaces.get_spaces():
        balance = space['balance']['availableBalance']
        string = str(space['name']) + ': ' + str(balance)
        if 'goal' in space:
            goal = space['goal']['amount']
            percentage = balance / goal
            string += '/' + str(goal) + ' <- ' + '{:.2%}'.format(percentage)
        print(string)
Exemplo n.º 11
0
def spaces():
    """ Show spaces """
    spaces = api.Api()
    print('Spaces:')
    print('----------------')
    print('Total balance: ' + str(spaces.get_spaces()['totalBalance']))
    for space in spaces.get_spaces()['spaces']:
        balance = space['balance']['availableBalance']
        string = str(space['name']) + ': ' + str(balance)
        if "goal" in space:
            goal = space['goal']['amount']
            percentage = balance/goal
            string += "/" + str(goal) + ' <- ' + "{:.2%}".format(percentage)
        print(string)
Exemplo n.º 12
0
    def setUp(self):
        """
        This method is called BEFORE each individual test case
        """
        from n26 import api

        self._underTest = api.Api(self.config)

        logger = logging.getLogger("n26")
        logger.setLevel(logging.DEBUG)
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        ch.setFormatter(formatter)
        logger.addHandler(ch)
Exemplo n.º 13
0
    def setUp(self):
        """
        This method is called BEFORE each individual test case
        """
        from n26 import api, config

        # use test file path instead of real one
        config.CONFIG_FILE_PATH = self.CONFIG_FILE

        self._underTest = api.Api()

        logger = logging.getLogger("n26")
        logger.setLevel(logging.DEBUG)
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        ch.setFormatter(formatter)
        logger.addHandler(ch)
Exemplo n.º 14
0
def transactions(limit):
    """ Show transactions (default: 20) """
    transactions = api.Api()
    output = transactions.get_transactions_limited(str(limit))
    print('Transactions:')
    print('-------------')
    li = []
    for i, val in enumerate(output):
        li.append([
            str(val.get('amount')),
            insertNewlines(val.get('merchantName', val.get('partnerName')), 30),
            insertNewlines(val.get('referenceText'), 100),
            datetime.datetime.fromtimestamp(val.get('confirmed', 0)/1000).strftime('%Y-%m-%d %H:%M:%S')
        ])

    # Tabulate
    table = li
    headers = ['amount', 'partner/merchant', 'reference-text', 'confirmed']
    print(tabulate(table, headers, tablefmt='simple', numalign='right', floatfmt=".2f"))
Exemplo n.º 15
0
def transactions(limit):
    """ Show transactions (default: 5) """
    transactions = api.Api()
    output = transactions.get_transactions_limited(str(limit))
    print('Transactions:')
    print('-------------')
    li = []
    for i, val in enumerate(output):
        try:
            if val['merchantName'] in val.values():
                li.append([i, str(val['amount']), val['merchantName']])
        except KeyError:
            if val['referenceText'] in val.values():
                li.append([i, str(val['amount']), val['referenceText']])
            else:
                li.append([i, str(val['amount']), 'no details available'])

    # Tabulate
    table = li
    headers = ['index', 'amount', 'details']
    print(tabulate(table, headers, tablefmt='simple', numalign='right'))
Exemplo n.º 16
0
import logging
import webbrowser
from datetime import datetime, timezone
from typing import Tuple

import click
from requests import HTTPError
from tabulate import tabulate

import n26.api as api
from n26.config import Config
from n26.const import AMOUNT, CURRENCY, REFERENCE_TEXT, ATM_WITHDRAW, CARD_STATUS_ACTIVE, DATETIME_FORMATS

LOGGER = logging.getLogger(__name__)

API_CLIENT = api.Api()

JSON_OUTPUT = False
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


def auth_decorator(func: callable):
    """
    Decorator ensuring authentication before making api requests
    :param func: function to patch
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        new_auth = False
        try:
            API_CLIENT.refresh_authentication()
Exemplo n.º 17
0
def test_init_explicit():
    new_api = api.Api(conf)
    assert new_api.config == conf
Exemplo n.º 18
0
def test_init_implicit(patched_config):
    patched_config.return_value = conf
    new_api = api.Api()
    assert new_api.config == conf
Exemplo n.º 19
0
def api_object():
    new_api = api.Api(conf)
    return new_api
Exemplo n.º 20
0
 def get_balance(self):
     n26_api = api.Api(self._prepare_conf())
     return n26_api.get_balance()['usableBalance']
Exemplo n.º 21
0
 def get_transactions(self, limit=50):
     n26_api = api.Api(self._prepare_conf())
     return n26_api.get_transactions_limited(limit)
Exemplo n.º 22
0
import webbrowser
from datetime import datetime, timezone

import click
from tabulate import tabulate

import n26.api as api
from n26.const import AMOUNT, CURRENCY, REFERENCE_TEXT, ATM_WITHDRAW

API_CLIENT = api.Api()

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


# Cli returns command line requests
@click.group(context_settings=CONTEXT_SETTINGS)
def cli():
    """Interact with the https://n26.com API via the command line."""


client = api.Api()


@cli.command()
def addresses():
    """ Show account addresses """
    addresses_data = API_CLIENT.get_addresses().get('data')

    headers = [
        'Type', 'Country', 'City', 'Zip code', 'Street', 'Number',
        'Address line 1', 'Address line 2', 'Created', 'Updated'
Exemplo n.º 23
0
 def test_get_token(self):
     expected = '12345678-1234-1234-1234-123456789012'
     api_client = api.Api(self.config)
     result = api_client.get_token()
     self.assertEqual(result, expected)
Exemplo n.º 24
0
 def test_init_without_config(self):
     api_client = api.Api()
     self.assertIsNotNone(api_client.config)
Exemplo n.º 25
0
def balance():
    """ Show account balance """
    balance = api.Api()
    print('Current balance:')
    print('----------------')
    print(str(balance.get_balance()['availableBalance']))
Exemplo n.º 26
0
def main(cat_mappings):
    conf = config.Config(os.getenv("N26_USER"), os.getenv("N26_PASSWORD"),
                         'store/n26_creds')
    client = api.Api(conf)

    #s to ms - CET Local
    now = int(time.time() * 1E3)
    # -5min
    minus5 = int(now - 3E5)
    print(minus5, now)

    response = client.get_transactions(limit=200,
                                       from_time=minus5,
                                       to_time=now)

    print(datetime.fromtimestamp(math.floor(minus5 / 1E3)), '-',
          datetime.fromtimestamp(math.floor(now / 1E3)))

    transactions_payload = list()

    print("Transactions to process: " + str(len(response)))

    for transaction in response:
        category_name = mappings[next(
            (index for (index, d) in enumerate(mappings)
             if d["id"] == transaction["category"]), None)]["name"]
        is_sepa = 'partnerName' in transaction

        if not 'confirmed' in transaction or 'paymentScheme' in transaction:
            continue

        try:
            transaction_time = time.strftime(
                "%Y-%m-%d", time.localtime(transaction["confirmed"] / 1E3))

            is_debit = transaction["amount"] < 0

            payload = {
                'type': "withdrawal" if is_debit else "deposit",
                'external_id': transaction["linkId"],
                'date': transaction_time,
                'amount': abs(transaction["amount"]),
                'currency_code': transaction["currencyCode"],
                'category_name': category_name,
                'tags': ['N26 importer']
            }

            if is_sepa:
                payload["destination_name"] = transaction["partnerName"]
                if 'partnerIban' in transaction:
                    payload["destination_iban"] = transaction["partnerIban"]
                if 'referenceText' in transaction:
                    payload["description"] = transaction["referenceText"]

                payload["source_name"] = "N26" if is_debit else transaction[
                    "partnerName"]
                payload["destination_name"] = transaction[
                    "partnerName"] if is_debit else "N26"

            else:
                payload["source_name"] = "N26" if is_debit else transaction[
                    "merchantName"]
                payload["destination_name"] = transaction[
                    "merchantName"] if is_debit else "N26"
                payload["description"] = "(empty description)"

            transactions_payload.append(payload)
        except Exception as e:
            writeLog(transaction, e)

    if len(transactions_payload) == 0:
        print("Nothing to do")
        return

    data = {'transactions': transactions_payload}

    headers = {
        'Authorization': 'Bearer ' + os.getenv("FFIII_AUTH_TOKEN"),
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    try:
        r = requests.post(url=os.getenv("FFIII_API_ENDPOINT"),
                          json=data,
                          headers=headers)
        r.raise_for_status()
        print(r.text)
    except Exception as e:
        printLog(r.text, e)
        printLog(data)

    print("Job done")
Exemplo n.º 27
0
def limits():
    """ Show n26 account limits  """
    limits = api.Api()
    print(limits.get_account_limits())
Exemplo n.º 28
0
def contacts():
    """ Show your n26 contacts  """
    contacts = api.Api()
    print('Contacts:')
    print('---------')
    print(contacts.get_contacts())
Exemplo n.º 29
0
def statements():
    """ Show your n26 statements  """
    statements = api.Api()
    print('Statements:')
    print('-----------')
    print(statements.get_statements())