Improve history output; Add json output history; Add nocolor option for history
This commit is contained in:
parent
c31a2a47ad
commit
3c89b2b662
11
history.py
11
history.py
|
@ -6,6 +6,8 @@ from shutil import copyfile
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from lib.historylib import History
|
from lib.historylib import History
|
||||||
|
|
||||||
|
VERSION = 0.1
|
||||||
|
|
||||||
# Get variables environment
|
# Get variables environment
|
||||||
if not os.path.isfile('.env'):
|
if not os.path.isfile('.env'):
|
||||||
copyfile(".env.template", ".env")
|
copyfile(".env.template", ".env")
|
||||||
|
@ -14,6 +16,7 @@ load_dotenv(dotenv_path)
|
||||||
|
|
||||||
dunikey = os.getenv('DUNIKEY')
|
dunikey = os.getenv('DUNIKEY')
|
||||||
node = os.getenv('NODE')
|
node = os.getenv('NODE')
|
||||||
|
# referential = os.getenv('REFERENTIAL')
|
||||||
if not node:
|
if not node:
|
||||||
sys.stderr.write("Please fill a Duniter node in .env file\n")
|
sys.stderr.write("Please fill a Duniter node in .env file\n")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
@ -23,12 +26,14 @@ parser = argparse.ArgumentParser()
|
||||||
parser.add_argument('-p', '--pubkey', help="Clé publique du compte visé")
|
parser.add_argument('-p', '--pubkey', help="Clé publique du compte visé")
|
||||||
parser.add_argument('-n', '--node', help="Sélection d'un noeud Duniter à utiliser")
|
parser.add_argument('-n', '--node', help="Sélection d'un noeud Duniter à utiliser")
|
||||||
parser.add_argument('-k', '--key', help="Chemin vers notre fichier de trousseau (PubSec)")
|
parser.add_argument('-k', '--key', help="Chemin vers notre fichier de trousseau (PubSec)")
|
||||||
parser.add_argument('--mempool', action='store_true', help="Utilise les sources en Mempool")
|
parser.add_argument('-j', '--json', action='store_true', help="Affiche le résultat en format JSON")
|
||||||
|
parser.add_argument('--nocolors', action='store_true', help="Affiche le résultat en noir et blanc")
|
||||||
|
parser.add_argument('--version', action='store_true', help="Affiche la version actuelle du programme")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
if args.node: node = args.node
|
if args.node: node = args.node
|
||||||
if args.key: dunikey = args.key
|
if args.key: dunikey = args.key
|
||||||
|
|
||||||
# Create transaction and send it
|
# Create transaction and send it
|
||||||
hist = History(dunikey, node, args.pubkey, args.mempool)
|
hist = History(dunikey, node, args.pubkey)
|
||||||
result = hist.history()
|
hist.history(args.json, args.nocolors)
|
||||||
|
|
|
@ -11,10 +11,9 @@ PUBKEY_REGEX = "(?![OIl])[1-9A-Za-z]{42,45}"
|
||||||
|
|
||||||
class History:
|
class History:
|
||||||
|
|
||||||
def __init__(self, dunikey, node, pubkey, useMempool=False):
|
def __init__(self, dunikey, node, pubkey):
|
||||||
self.dunikey = dunikey
|
self.dunikey = dunikey
|
||||||
self.pubkey = pubkey if pubkey else get_privkey(dunikey, "pubsec").pubkey
|
self.pubkey = pubkey if pubkey else get_privkey(dunikey, "pubsec").pubkey
|
||||||
self.useMempool = useMempool
|
|
||||||
self.node = node
|
self.node = node
|
||||||
if not re.match(PUBKEY_REGEX, self.pubkey) or len(self.pubkey) > 45:
|
if not re.match(PUBKEY_REGEX, self.pubkey) or len(self.pubkey) > 45:
|
||||||
sys.stderr.write("La clé publique n'est pas au bon format.\n")
|
sys.stderr.write("La clé publique n'est pas au bon format.\n")
|
||||||
|
@ -87,6 +86,7 @@ class History:
|
||||||
i = 0
|
i = 0
|
||||||
|
|
||||||
currentBase = int(self.historyDoc['currentUd']['base'])
|
currentBase = int(self.historyDoc['currentUd']['base'])
|
||||||
|
self.UD = self.historyDoc['currentUd']['amount']/100
|
||||||
|
|
||||||
for sens in 'received','sent','receiving','sending':
|
for sens in 'received','sent','receiving','sending':
|
||||||
res = self.historyDoc['transactionsHistory'][sens]
|
res = self.historyDoc['transactionsHistory'][sens]
|
||||||
|
@ -108,7 +108,10 @@ class History:
|
||||||
amount = int(output.split(':')[0])
|
amount = int(output.split(':')[0])
|
||||||
base = int(output.split(':')[1])
|
base = int(output.split(':')[1])
|
||||||
applyBase = base-currentBase
|
applyBase = base-currentBase
|
||||||
trans[i].append(round(amount*pow(10,applyBase)/100, 2))
|
amount = round(amount*pow(10,applyBase)/100, 2)
|
||||||
|
# if referential == 'DU': amount = round(amount/UD, 2)
|
||||||
|
trans[i].append(amount)
|
||||||
|
trans[i].append(round(amount/self.UD, 2))
|
||||||
trans[i].append(bloc['comment'])
|
trans[i].append(bloc['comment'])
|
||||||
trans[i].append(base)
|
trans[i].append(base)
|
||||||
i += 1
|
i += 1
|
||||||
|
@ -119,48 +122,107 @@ class History:
|
||||||
# Keep only base if there is base change
|
# Keep only base if there is base change
|
||||||
lastBase = 0
|
lastBase = 0
|
||||||
for i in trans:
|
for i in trans:
|
||||||
if i[5] == lastBase:
|
if i[6] == lastBase: i[6] = None
|
||||||
i.pop(5)
|
else: lastBase = i[6]
|
||||||
else:
|
|
||||||
lastBase = i[5]
|
return trans
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def printHistory(self, trans, noColors):
|
||||||
# Get balance
|
# Get balance
|
||||||
balance = self.historyDoc['balance']['amount']
|
balance = self.historyDoc['balance']['amount']/100
|
||||||
balance = balance/100
|
balanceUD = round(balance/self.UD, 2)
|
||||||
|
|
||||||
# Get currency
|
# Get currency
|
||||||
currency = self.historyDoc['node']['peer']['currency']
|
currency = self.historyDoc['node']['peer']['currency']
|
||||||
if currency == 'g1': currency = 'Ḡ1'
|
if currency == 'g1': currency = 'Ḡ1'
|
||||||
|
elif currency == 'g1-test': currency = 'GT'
|
||||||
|
# if referential == 'DU': currency = 'DU/' + currency.lower()
|
||||||
|
|
||||||
# Get terminal size
|
# Get terminal size
|
||||||
rows = int(os.popen('stty size', 'r').read().split()[1])
|
rows = int(os.popen('stty size', 'r').read().split()[1])
|
||||||
|
|
||||||
print('-'.center(rows, '-'))
|
# Display history
|
||||||
print("\033[1m{: <20} | {: <45} | {: <7} | {: <30}\033[0m".format(" Date"," De / À (clé publique)","Montant ({0})".format(currency),"Commentaire"))
|
print('+', end='')
|
||||||
|
print('-'.center(rows-1, '-'))
|
||||||
|
if noColors: isBold = isBoldEnd = ''
|
||||||
|
else:
|
||||||
|
isBold = '\033[1m'
|
||||||
|
isBoldEnd = '\033[0m'
|
||||||
|
print(isBold + "|{: <19} | {: <14} | {: <7} | {: <7} | {: <30}".format(" Date"," De / À"," {0}".format(currency)," DU/{0}".format(currency.lower()),"Commentaire") + isBoldEnd)
|
||||||
|
print('|', end='')
|
||||||
for t in trans:
|
for t in trans:
|
||||||
if t[0] == "received":
|
if t[0] == "received": color = "green"
|
||||||
color = "green"
|
elif t[0] == "receiving": color = "yellow"
|
||||||
elif t[0] == "receiving":
|
elif t[0] == "sending": color = "red"
|
||||||
color = "yellow"
|
|
||||||
elif t[0] == "sending":
|
|
||||||
color = "red"
|
|
||||||
else: color = "blue"
|
else: color = "blue"
|
||||||
|
if noColors:
|
||||||
|
color = None
|
||||||
|
if t[0] in ('sent','sending'):
|
||||||
|
amount = '-' + str(t[3])
|
||||||
|
amountUD = '-' + str(t[4])
|
||||||
|
else:
|
||||||
|
amount = t[3]
|
||||||
|
amountUD = t[4]
|
||||||
|
if t[0] in ('receiving','sending'):
|
||||||
|
comment = '(EN ATTENTE) ' + t[5]
|
||||||
|
else:
|
||||||
|
comment = t[5]
|
||||||
|
else:
|
||||||
|
amount = t[3]
|
||||||
|
amountUD = t[4]
|
||||||
|
comment = t[5]
|
||||||
|
|
||||||
date = datetime.fromtimestamp(t[1]).strftime("%d/%m/%Y à %H:%M")
|
date = datetime.fromtimestamp(t[1]).strftime("%d/%m/%Y à %H:%M")
|
||||||
print('-'.center(rows, '-'))
|
print('-'.center(rows-1, '-'))
|
||||||
if len(t) > 5:
|
if t[6]:
|
||||||
print(' Changement de base : {0} '.format(t[5]).center(rows, '#'))
|
print('|', end='')
|
||||||
print('-'.center(rows, '-'))
|
print(' Changement de base : {0} '.format(t[6]).center(rows-1, '#'))
|
||||||
print(colored("| {: <18} | {: <45} | {: <12} | {: <30}".format(date, *t[2:]), color))
|
print('|', end='')
|
||||||
print('-'.center(rows, '-'))
|
print('-'.center(rows-1, '-'))
|
||||||
print('\033[1mSolde du compte: {0} {1}\033[0m'.format(balance,currency).center(rows, ' '))
|
print('|', end='')
|
||||||
print('-'.center(rows, '-'))
|
printKey = t[2][0:8] + '\u2026\u2026' + t[2][-3:]
|
||||||
print(colored('Reçus', 'green'), '-', colored('En cours de réception', 'yellow'), '-', colored('Envoyé', 'blue'), '-', colored("En cours d'envoi", 'red'))
|
print(colored(" {: <18} | {: <14} | {: <7} | {: <7} | {: <30}".format(date, printKey, amount, amountUD, comment), color))
|
||||||
|
print('|', end='')
|
||||||
|
print('-'.center(rows-1, '-'))
|
||||||
|
print('|', end='')
|
||||||
|
print(isBold + 'Solde du compte: {0} {1} ({2} DU/{3})'.format(balance, currency, balanceUD, currency.lower()).center(rows-1, ' ') + isBoldEnd)
|
||||||
|
print('+', end='')
|
||||||
|
print(''.center(rows-1, '-'))
|
||||||
|
if not noColors:
|
||||||
|
print(colored('Reçus', 'green'), '-', colored('En cours de réception', 'yellow'), '-', colored('Envoyé', 'blue'), '-', colored("En cours d'envoi", 'red'))
|
||||||
|
|
||||||
def history(self):
|
return trans
|
||||||
|
|
||||||
|
def jsonHistory(self, transList):
|
||||||
|
dailyJSON = []
|
||||||
|
for i, trans in enumerate(transList):
|
||||||
|
dailyJSON.append(i)
|
||||||
|
dailyJSON[i] = {}
|
||||||
|
dailyJSON[i]['date'] = trans[1]
|
||||||
|
dailyJSON[i]['pubkey'] = trans[2]
|
||||||
|
if trans[0] in ('sent','sending'):
|
||||||
|
dailyJSON[i]['amount'] = float('-' + str(trans[3]))
|
||||||
|
dailyJSON[i]['amountUD'] = float('-' + str(trans[4]))
|
||||||
|
else:
|
||||||
|
dailyJSON[i]['amount'] = trans[3]
|
||||||
|
dailyJSON[i]['amountUD'] = trans[4]
|
||||||
|
dailyJSON[i]['comment'] = trans[5]
|
||||||
|
|
||||||
|
dailyJSON = json.dumps(dailyJSON, indent=2)
|
||||||
|
# If we want to write JSON to a file
|
||||||
|
#jsonFile = open("history-{0}.json".format(self.pubkey[0:8]), "w")
|
||||||
|
#jsonFile.writelines(dailyJSON + '\n')
|
||||||
|
#jsonFile.close()
|
||||||
|
return dailyJSON
|
||||||
|
|
||||||
|
|
||||||
|
def history(self, isJSON=False, noColors=False):
|
||||||
self.sendDoc()
|
self.sendDoc()
|
||||||
self.parseHistory()
|
transList = self.parseHistory()
|
||||||
|
|
||||||
|
if isJSON:
|
||||||
|
transJson = self.jsonHistory(transList)
|
||||||
|
print(transJson)
|
||||||
|
else:
|
||||||
|
self.printHistory(transList, noColors)
|
||||||
|
|
||||||
|
|
Reference in New Issue