# -*- coding: utf-8 -*-
# Copyright © 2017-2022 Xavier G. <xavier.woobank@kindwolf.org>
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See the COPYING file for more details.
"""
This module provides various functions and constants used by the woobank-utils
tools.
"""
import os
import sys
import time
import json
import errno
from termcolor import colored
DEFAULT_CONF_DIR = '~/.config/woobank-utils'
MAX_AGE = 24 * 60 * 60
UNUSUAL_THRESHOLD = 500.0
WORRYING_THRESHOLD = 100.0
HOLYSHIT_THRESHOLD = 0
CURRENCIES = {
'EUR': '€',
'USD': '$',
'GBP': '£',
'YEN': '¥'
}
DEFAULT_CURRENCY = 'EUR'
COLORING_NONE = 0
COLORING_SIMPLE = 1
COLORING_THRESHOLD = 2
COLORING_MAX = 3
def format_timestamp_colored(timestamp, max_age):
"""
Format the given Unix timestamp for puny humans.
Additionally, the timestamp is colored: red if older than max_age, false
otherwise. This is useful to show whether cached data are obsolete.
"""
result = format_timestamp(timestamp)
color = 'red' if timestamp + max_age < time.time() else 'green'
return colored(result, color)
def format_timestamp(timestamp):
"""
Format the given Unix timestamp for puny humans.
"""
return time.strftime('%A %Y-%m-%d %H:%M:%S %Z', time.localtime(timestamp))
def format_amount(amount, currency=DEFAULT_CURRENCY, coloring=None):
"""
Format the given amount and currency into an optionally colored string.
"""
amount_format = '%12.2f ' + CURRENCIES.get(currency, currency)
result = amount_format % amount
if coloring < COLORING_SIMPLE or coloring >= COLORING_MAX:
return result
amount_color = 'green'
amount_attr = []
if coloring == COLORING_SIMPLE:
if amount < 0:
amount_color = 'red'
else:
# Assume COLORING_THRESHOLD:
if amount < HOLYSHIT_THRESHOLD:
amount_color = 'red'
amount_attr = ['blink']
elif amount < WORRYING_THRESHOLD:
amount_color = 'red'
elif amount < UNUSUAL_THRESHOLD:
amount_color = 'yellow'
return colored(result, amount_color, attrs=amount_attr)
def mkdir(path, mode):
"""
Create a directory along with all missing parents.
All created directories get assigned the given Unix mode.
"""
try:
os.makedirs(path, mode)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def load_json(json_path):
"""
Return the contents of a JSON file, given its path.
"""
if json_path == '-':
return json.load(sys.stdin)
else:
with open(json_path, 'r') as filedesc:
return json.load(filedesc)