From 29dc7486bd3d6206f77fe9805affb2484e94bd09 Mon Sep 17 00:00:00 2001 From: poka Date: Thu, 3 Dec 2020 02:11:09 +0100 Subject: [PATCH] Add json output for read messages --- jaklis.py | 3 ++- lib/cesium.py | 58 +++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/jaklis.py b/jaklis.py index d331632..d5cdcfb 100755 --- a/jaklis.py +++ b/jaklis.py @@ -37,6 +37,7 @@ if len(sys.argv) <= 1 or not sys.argv[1] in ('read','send','delete','set','get', # Messages management read_cmd.add_argument('-n', '--number',type=int, default=3, help="Affiche les NUMBER derniers messages") +read_cmd.add_argument('-j', '--json', action='store_true', help="Sort au format JSON") read_cmd.add_argument('-o', '--outbox', action='store_true', help="Lit les messages envoyés") send_cmd.add_argument('-d', '--destinataire', required=True, help="Destinataire du message") @@ -100,7 +101,7 @@ if not os.path.isfile(dunikey): # Build cesiumMessaging class if sys.argv[1] == "read": messages = ReadFromCesium(dunikey, pod) - messages.read(args.number, args.outbox) + messages.read(args.number, args.outbox, args.json) elif sys.argv[1] == "send": if args.fichier: with open(args.fichier, 'r') as f: diff --git a/lib/cesium.py b/lib/cesium.py index 0d346e3..8ab331a 100644 --- a/lib/cesium.py +++ b/lib/cesium.py @@ -115,11 +115,65 @@ class ReadFromCesium: print(self.content) print(colored(infoTotal.center(rows, '#'), "yellow")) + + # Parse JSON result and display messages + def jsonMessages(self, msgJSON, nbrMsg, outbox): + def decrypt(msg): + msg64 = base64.b64decode(msg) + return box_decrypt(msg64, get_privkey(self.dunikey, "pubsec"), self.issuer, nonce).decode() + + totalMsg = msgJSON["total"] + if nbrMsg > totalMsg: + nbrMsg = totalMsg + + if totalMsg == 0: + print("Aucun message à afficher") + return True + else: + data = [] + # data.append({}) + # data[0]['total'] = totalMsg + for i, hits in enumerate(msgJSON["hits"]): + self.idMsg = hits["_id"] + msgSrc = hits["_source"] + self.issuer = msgSrc["issuer"] + nonce = msgSrc["nonce"] + nonce = base58.b58decode(nonce) + self.date = msgSrc["time"] + + if outbox: + pubkey = msgSrc["recipient"] + else: + pubkey = self.issuer + + try: + self.title = decrypt(msgSrc["title"]) + self.content = decrypt(msgSrc["content"]) + except Exception as e: + sys.stderr.write(colored(str(e), 'red') + '\n') + pp_json(hits) + continue + + data.append(i) + data[i] = {} + data[i]['id'] = self.idMsg + data[i]['date'] = self.date + data[i]['pubkey'] = pubkey + data[i]['title'] = self.title + data[i]['content'] = self.content + + data = json.dumps(data, indent=2) + return data + - def read(self, nbrMsg, outbox): + def read(self, nbrMsg, outbox, isJSON): jsonMsg = self.sendDocument(nbrMsg, outbox) - self.readMessages(jsonMsg, nbrMsg, outbox) + if isJSON: + jsonFormat = self.jsonMessages(jsonMsg, nbrMsg, outbox) + print(jsonFormat) + else: + self.readMessages(jsonMsg, nbrMsg, outbox)