diff --git a/zen/ipns_TAG_refresh.sh b/zen/ipns_TAG_refresh.sh index 490a576..5486095 100755 --- a/zen/ipns_TAG_refresh.sh +++ b/zen/ipns_TAG_refresh.sh @@ -131,9 +131,10 @@ do echo "$PubFromDunikey" > $HOME/.zen/ipfs/.${IPFSNODEID}/KEY/${MEDIAKEY}/MEDIAPUBKEY fi MEDIAPUBKEY=$(cat $HOME/.zen/ipfs/.${IPFSNODEID}/KEY/${MEDIAKEY}/MEDIAPUBKEY) + BALANCE=$(~/.zen/astrXbian/zen/jaklis/jaklis.py balance ${MEDIAPUBKEY}) ## DEMO PERIOD -## NICE FINAL STREAMING PAGE +## NICE FINAL STREAMING PAGE # TODO ACTIVATE DOWNLOAD FOR AVI or MKV FILETYPE="${LOCALTUBELINK##*.}" MIMETYPE="video/$FILETYPE" && HTMLTAG="video" [[ "$FILETYPE" == "avi" ]] && MIMETYPE="video/x-msvideo" diff --git a/zen/jaklis/.env b/zen/jaklis/.env index ea6bd51..22d31e4 100644 --- a/zen/jaklis/.env +++ b/zen/jaklis/.env @@ -1,5 +1,10 @@ -DUNIKEY="/.zen/secret.dunikey" # Chemin du fichier de trousseau Ḡ1 de l'émetteur, au format PubSec -POD="https://data.gchange.fr" # Noeud Gchange utilisé pour l'envoi du message -#POD="https://g1.data.duniter.fr" # Noeud Cecium+ utilisé pour l'envoi du message -#POD="https://g1.data.le-sou.org" # Adresse du pod Cesium de secours -#POD="https://g1.data.e-is.pro" +# Chemin de la clé privé Ḡ1 de l'émetteur, au format PubSec +DUNIKEY=/.zen/secret.dunikey + +# Noeud Duniter +NODE=https://g1.librelois.fr/gva + +# Adresse du pod Cesium ou Gchange à utiliser +POD=https://g1.data.le-sou.org +#POD=https://g1.data.duniter.fr +#POD=https://data.gchange.fr diff --git a/zen/jaklis/.env.template b/zen/jaklis/.env.template index dd81446..462b319 100755 --- a/zen/jaklis/.env.template +++ b/zen/jaklis/.env.template @@ -1,6 +1,10 @@ -DUNIKEY="" # Chemin de la clé privé Ḡ1 de l'émetteur, au format PubSec -#POD="https://g1.data.duniter.fr" # Adresse du pod Cesium ou Gchange à utiliser -POD="https://g1.data.le-sou.org" # Adresse du pod Cesium de secours -#POD="https://data.gchange.fr" # Adresse du pod ḠChange à utiliser +# Chemin de la clé privé Ḡ1 de l'émetteur, au format PubSec +DUNIKEY= -NODE="https://g1.librelois.fr/gva" +# Noeud Duniter +NODE=https://g1.librelois.fr/gva + +# Adresse du pod Cesium ou Gchange à utiliser +POD=https://g1.data.le-sou.org +#POD=https://g1.data.duniter.fr +#POD=https://data.gchange.fr diff --git a/zen/jaklis/README.md b/zen/jaklis/README.md index e0ff54d..9d7e950 100755 --- a/zen/jaklis/README.md +++ b/zen/jaklis/README.md @@ -22,7 +22,7 @@ Renseignez optionnellement le fichier **.env** (Généré lors de la première t ``` ``` -usage: jaklis.py [-h] [-v] [-k KEY] [-n NODE] {read,send,delete,get,set,erase,like,unlike,pay,history,balance} ... +usage: jaklis.py [-h] [-v] [-k KEY] [-n NODE] {read,send,delete,get,set,erase,stars,unstars,getoffer,setoffer,deleteoffer,pay,history,balance,id,idBalance} ... Client CLI pour Cesium+ et Ḡchange @@ -33,19 +33,23 @@ optional arguments: -n NODE, --node NODE Adresse du noeud Cesium+, Gchange ou Duniter à utiliser Commandes de jaklis: - {read,send,delete,get,set,erase,like,unlike,pay,history,balance} + {read,send,delete,get,set,erase,stars,unstars,getoffer,setoffer,deleteoffer,pay,history,balance,id,idBalance} read Lecture des messages send Envoi d'un message delete Supression d'un message get Voir un profile Cesium+ set Configurer son profile Cesium+ erase Effacer son profile Cesium+ - like Voir les likes d'un profile / Liker un profile (option -s NOTE) - unlike Supprimer un like + stars Voir les étoiles d'un profile / Noter un profile (option -s NOTE) + unstars Supprimer un star + getoffer Obtenir les informations d'une annonce gchange + setoffer Créer une annonce gchange + deleteoffer Supprimer une annonce gchange pay Payer en Ḡ1 history Voir l'historique des transactions d'un compte Ḡ1 balance Voir le solde d'un compte Ḡ1 - + id Voir l'identité d'une clé publique/username + idBalance Voir l'identité d'une clé publique/username et son solde ``` Utilisez `./jaklis CMD -h` où `CMD` est la commande souhaité pour obtenir l'aide détaillé de cette commande. diff --git a/zen/jaklis/jaklis.py b/zen/jaklis/jaklis.py index 24ffc17..0a13eb2 100755 --- a/zen/jaklis/jaklis.py +++ b/zen/jaklis/jaklis.py @@ -6,7 +6,7 @@ from shutil import copyfile from dotenv import load_dotenv from duniterpy.key import SigningKey -__version__ = "0.0.2" +__version__ = "0.0.4" MY_PATH = os.path.realpath(os.path.dirname(sys.argv[0])) + '/' @@ -37,6 +37,9 @@ deleteoffer_cmd = subparsers.add_parser('deleteoffer', help="Supprimer une annon pay_cmd = subparsers.add_parser('pay', help="Payer en Ḡ1") history_cmd = subparsers.add_parser('history', help="Voir l'historique des transactions d'un compte Ḡ1") balance_cmd = subparsers.add_parser('balance', help="Voir le solde d'un compte Ḡ1") +id_cmd = subparsers.add_parser('id', help="Voir l'identité d'une clé publique/username") +id_balance_cmd = subparsers.add_parser('idBalance', help="Voir l'identité d'une clé publique/username et son solde") +currentUd = subparsers.add_parser('currentUd', help="Affiche la montant actuel du dividende Universel") # Messages management read_cmd.add_argument('-n', '--number',type=int, default=3, help="Affiche les NUMBER derniers messages") @@ -94,6 +97,10 @@ history_cmd.add_argument('--nocolors', action='store_true', help="Affiche le r balance_cmd.add_argument('-p', '--pubkey', help="Clé publique du compte visé") balance_cmd.add_argument('-m', '--mempool', action='store_true', help="Utilise les sources en Mempool") +id_cmd.add_argument('-p', '--pubkey', help="Clé publique du compte visé") +id_cmd.add_argument('-u', '--username', help="Username du compte visé") +id_balance_cmd.add_argument('-p', '--pubkey', help="Pubkey du compte visé") +currentUd.add_argument('-p', '--pubkey', help="Pubkey du compte visé") args = parser.parse_args() @@ -130,7 +137,7 @@ try: except: profile = False -if cmd in ('history','balance','get') and (pubkey or profile): +if cmd in ('history','balance','get','id','idBalance') and (pubkey or profile): noNeedDunikey = True keyPath = False try: @@ -220,7 +227,7 @@ if cmd in ("read","send","delete","set","get","erase","stars","unstars","getoffe cesium.deleteOffer(args.id) # Construct GVA object -elif cmd in ("pay","history","balance"): +elif cmd in ("pay","history","balance","id","idBalance","currentUd"): from lib.gva import GvaApi if args.node: @@ -239,10 +246,16 @@ elif cmd in ("pay","history","balance"): if cmd == "pay": gva.pay(args.amount, args.comment, args.mempool, args.verbose) - if cmd == "history": + elif cmd == "history": gva.history(args.json, args.nocolors, args.number) - if cmd == "balance": + elif cmd == "balance": gva.balance(args.mempool) + elif cmd == "id": + gva.id(args.pubkey, args.username) + elif cmd == "idBalance": + gva.idBalance(args.pubkey) + elif cmd == "currentUd": + gva.currentUd() if keyPath: diff --git a/zen/jaklis/lib/__pycache__/cesium.cpython-36.pyc b/zen/jaklis/lib/__pycache__/cesium.cpython-36.pyc deleted file mode 100644 index b284515..0000000 Binary files a/zen/jaklis/lib/__pycache__/cesium.cpython-36.pyc and /dev/null differ diff --git a/zen/jaklis/lib/__pycache__/cesiumCommon.cpython-36.pyc b/zen/jaklis/lib/__pycache__/cesiumCommon.cpython-36.pyc deleted file mode 100644 index 3d7cd6b..0000000 Binary files a/zen/jaklis/lib/__pycache__/cesiumCommon.cpython-36.pyc and /dev/null differ diff --git a/zen/jaklis/lib/__pycache__/likes.cpython-36.pyc b/zen/jaklis/lib/__pycache__/likes.cpython-36.pyc deleted file mode 100644 index 30b06f6..0000000 Binary files a/zen/jaklis/lib/__pycache__/likes.cpython-36.pyc and /dev/null differ diff --git a/zen/jaklis/lib/__pycache__/messaging.cpython-36.pyc b/zen/jaklis/lib/__pycache__/messaging.cpython-36.pyc deleted file mode 100644 index c7bb055..0000000 Binary files a/zen/jaklis/lib/__pycache__/messaging.cpython-36.pyc and /dev/null differ diff --git a/zen/jaklis/lib/__pycache__/natools.cpython-36.pyc b/zen/jaklis/lib/__pycache__/natools.cpython-36.pyc deleted file mode 100644 index dca2c57..0000000 Binary files a/zen/jaklis/lib/__pycache__/natools.cpython-36.pyc and /dev/null differ diff --git a/zen/jaklis/lib/__pycache__/offers.cpython-36.pyc b/zen/jaklis/lib/__pycache__/offers.cpython-36.pyc deleted file mode 100644 index 5e5d84f..0000000 Binary files a/zen/jaklis/lib/__pycache__/offers.cpython-36.pyc and /dev/null differ diff --git a/zen/jaklis/lib/__pycache__/profiles.cpython-36.pyc b/zen/jaklis/lib/__pycache__/profiles.cpython-36.pyc deleted file mode 100644 index adfa3b3..0000000 Binary files a/zen/jaklis/lib/__pycache__/profiles.cpython-36.pyc and /dev/null differ diff --git a/zen/jaklis/lib/cesium.py b/zen/jaklis/lib/cesium.py index e755519..e822529 100755 --- a/zen/jaklis/lib/cesium.py +++ b/zen/jaklis/lib/cesium.py @@ -2,7 +2,7 @@ import re, string, random, base64 from lib.cesiumCommon import CesiumCommon, PUBKEY_REGEX from lib.messaging import ReadFromCesium, SendToCesium, DeleteFromCesium from lib.profiles import Profiles -from lib.likes import ReadLikes, SendLikes, UnLikes +from lib.stars import ReadLikes, SendLikes, UnLikes from lib.offers import Offers class CesiumPlus(CesiumCommon): @@ -100,13 +100,14 @@ class CesiumPlus(CesiumCommon): document = setOffer.configDocSet(title, description, city, localisation, category, price, picture) result = setOffer.sendDocumentSet(document,'set') - print(result) + # print(result) return result def getOffer(self, id, avatar=None): getOffer = Offers(self.dunikey, self.pod, self.noNeedDunikey) - + resultJSON = getOffer.sendDocumentGet(id, 'get') + # print(resultJSON) result = getOffer.parseJSON(resultJSON) print(result) diff --git a/zen/jaklis/lib/currentUd.py b/zen/jaklis/lib/currentUd.py new file mode 100644 index 0000000..f038ac5 --- /dev/null +++ b/zen/jaklis/lib/currentUd.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 + +import sys, re, os.path, json, ast +from termcolor import colored +from lib.natools import fmt, sign, get_privkey +from gql import gql, Client +from gql.transport.aiohttp import AIOHTTPTransport + +class currentUd: + + def __init__(self, node): + # Define Duniter GVA node + transport = AIOHTTPTransport(url=node) + self.client = Client(transport=transport, fetch_schema_from_transport=True) + + def sendDoc(self): + # Build UD generation document + queryBuild = gql( + """ + query { + currentUd { + amount + } + } + """ + ) + paramsBuild = { + } + + # Send UD document + try: + udValue = self.client.execute(queryBuild, variable_values=paramsBuild) + except Exception as e: + message = ast.literal_eval(str(e))["message"] + sys.stderr.write("Echec de récupération du DU:\n" + message + "\n") + sys.exit(1) + + udValueFinal = udValue['currentUd']['amount'] + + return udValueFinal diff --git a/zen/jaklis/lib/gva.py b/zen/jaklis/lib/gva.py index 0ec1ad6..c4173c9 100755 --- a/zen/jaklis/lib/gva.py +++ b/zen/jaklis/lib/gva.py @@ -1,8 +1,10 @@ +from lib.currentUd import currentUd import sys, re from lib.natools import get_privkey from lib.gvaPay import Transaction, PUBKEY_REGEX from lib.gvaHistory import History from lib.gvaBalance import Balance +from lib.gvaID import Id class GvaApi(): def __init__(self, dunikey, node, pubkey, noNeedDunikey=False): @@ -57,3 +59,18 @@ class GvaApi(): gva = Balance(self.dunikey, self.node, self.destPubkey, useMempool) balanceValue = gva.sendDoc() print(balanceValue) + + def id(self, pubkey, username): + gva = Id(self.dunikey, self.node, pubkey, username) + result = gva.sendDoc() + print(result) + + def idBalance(self, pubkey): + gva = Id(self.dunikey, self.node, pubkey) + result = gva.sendDoc(True) + print(result) + + def currentUd(self): + gva = currentUd(self.node) + result = gva.sendDoc() + print(result) \ No newline at end of file diff --git a/zen/jaklis/lib/gvaBalance.py b/zen/jaklis/lib/gvaBalance.py index b148e7e..1a20ea2 100755 --- a/zen/jaklis/lib/gvaBalance.py +++ b/zen/jaklis/lib/gvaBalance.py @@ -26,7 +26,7 @@ class Balance: # Build balance generation document queryBuild = gql( """ - query ($pubkey: String!){ + query ($pubkey: PkOrScriptGva!){ balance(script: $pubkey) { amount } @@ -44,7 +44,10 @@ class Balance: message = ast.literal_eval(str(e))["message"] sys.stderr.write("Echec de récupération du solde:\n" + message + "\n") sys.exit(1) + + if (balanceResult['balance'] == None): balanceValue = 'null' + else: + balanceValue = balanceResult['balance']['amount']/100 - balanceValue = balanceResult['balance']['amount']/100 # print(balanceValue) return balanceValue diff --git a/zen/jaklis/lib/gvaHistory.py b/zen/jaklis/lib/gvaHistory.py index cfcad0f..39563a7 100755 --- a/zen/jaklis/lib/gvaHistory.py +++ b/zen/jaklis/lib/gvaHistory.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 -import sys, re, os.path, json, ast, time +import sys, re, os.path, json, ast, time, hashlib from datetime import datetime +from duniterpy.key import base58 from termcolor import colored from lib.natools import fmt, sign, get_privkey from gql import gql, Client @@ -27,9 +28,9 @@ class History: # Build history generation document queryBuild = gql( """ - query ($pubkey: String!, $number: Int!){ + query ($pubkey: PubKeyGva!, $script: PkOrScriptGva!, $number: Int!){ txsHistoryBc( - pubkeyOrScript: $pubkey + script: $script pagination: { pageSize: $number, ord: DESC } ) { both { @@ -55,17 +56,17 @@ class History: issuers comment outputs - writtenTime + receivedTime } receiving { currency issuers comment outputs - writtenTime + receivedTime } } - balance(script: $pubkey) { + balance(script: $script) { amount base } @@ -83,7 +84,8 @@ class History: ) paramsBuild = { "pubkey": self.pubkey, - "number": number + "number": number, + "script": f"SIG({self.pubkey})", } # Send history document @@ -176,8 +178,12 @@ class History: def printHistory(self, trans, noColors): # Get balance - balance = self.historyDoc['balance']['amount']/100 - balanceUD = round(balance/self.UD, 2) + if (self.historyDoc['balance'] == None): + balance = balanceUD = 'null' + else: + + balance = self.historyDoc['balance']['amount']/100 + balanceUD = round(balance/self.UD, 2) # Get currency currency = self.historyDoc['node']['peer']['currency'] @@ -220,11 +226,12 @@ class History: print('|', end='') print('-'.center(rows-1, '-')) print('|', end='') - printKey = t[2][0:8] + '\u2026' + t[2][-3:] + checksum = self.gen_checksum(t[2]) + shortPubkey = t[2][0:4] + '\u2026' + t[2][-4:] + ':' + checksum if noColors: - print(" {: <18} | {: <12} | {: <7} | {: <7} | {: <30}".format(date, printKey, t[3], t[4], comment)) + print(" {: <18} | {: <12} | {: <7} | {: <7} | {: <30}".format(date, shortPubkey, t[3], t[4], comment)) else: - print(colored(" {: <18} | {: <12} | {: <7} | {: <7} | {: <30}".format(date, printKey, t[3], t[4], comment), color)) + print(colored(" {: <18} | {: <12} | {: <7} | {: <7} | {: <30}".format(date, shortPubkey, t[3], t[4], comment), color)) print('|', end='') print('-'.center(rows-1, '-')) print('|', end='') @@ -235,6 +242,15 @@ class History: print(colored('Reçus', 'green'), '-', colored('En cours de réception', 'yellow'), '-', colored('Envoyé', 'blue'), '-', colored("En cours d'envoi", 'red')) return trans + + def gen_checksum(self, pubkey): + """ + Returns the checksum of the input pubkey (encoded in b58) + thx Matograine + """ + pubkey_byte = base58.Base58Encoder.decode(str.encode(pubkey)) + hash = hashlib.sha256(hashlib.sha256(pubkey_byte).digest()).digest() + return base58.Base58Encoder.encode(hash)[:3] def jsonHistory(self, transList): dailyJSON = [] diff --git a/zen/jaklis/lib/gvaID.py b/zen/jaklis/lib/gvaID.py new file mode 100644 index 0000000..023a144 --- /dev/null +++ b/zen/jaklis/lib/gvaID.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 + +import sys, re, os.path, json, ast +from termcolor import colored +from lib.natools import fmt, sign, get_privkey +from gql import gql, Client +from gql.transport.aiohttp import AIOHTTPTransport + +PUBKEY_REGEX = "(?![OIl])[1-9A-Za-z]{42,45}" + +class Id: + + def __init__(self, dunikey, node, pubkey='', username=''): + + self.dunikey = dunikey + self.pubkey = pubkey if pubkey else get_privkey(dunikey, "pubsec").pubkey + self.username = username + # 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.exit(1) + + # Define Duniter GVA node + transport = AIOHTTPTransport(url=node) + self.client = Client(transport=transport, fetch_schema_from_transport=True) + + def sendDoc(self, getBalance=False): + # Build balance generation document + if (getBalance): + queryBuild = gql( + """ + query ($pubkey: PubKeyGva!, $script: PkOrScriptGva!){ + idty (pubkey: $pubkey) { + isMember + username + } + balance(script: $script) { + amount + } + } + """ + ) + else: + queryBuild = gql( + """ + query ($pubkey: PubKeyGva!){ + idty (pubkey: $pubkey) { + isMember + username + } + } + """ + ) + + paramsBuild = { + "pubkey": self.pubkey, + "script": f"SIG({self.pubkey})" + } + + # Send balance document + try: + queryResult = self.client.execute(queryBuild, variable_values=paramsBuild) + except Exception as e: + sys.stderr.write("Echec de récupération du solde:\n" + str(e) + "\n") + sys.exit(1) + + jsonBrut = queryResult + + if (getBalance): + if (queryResult['balance'] == None): + jsonBrut['balance'] = {"amount": 0.0} + else: + jsonBrut['balance'] = queryResult['balance']['amount']/100 + + if (queryResult['idty'] == None): + username = 'Matiou' + isMember = False + else: + username = queryResult['idty']['username'] + isMember = queryResult['idty']['isMember'] + + return json.dumps(jsonBrut, indent=2) diff --git a/zen/jaklis/lib/gvaPay.py b/zen/jaklis/lib/gvaPay.py index e017c88..caa084f 100755 --- a/zen/jaklis/lib/gvaPay.py +++ b/zen/jaklis/lib/gvaPay.py @@ -6,7 +6,7 @@ from lib.natools import fmt, sign, get_privkey from gql import gql, Client from gql.transport.aiohttp import AIOHTTPTransport -PUBKEY_REGEX = "(?![OIl])[1-9A-Za-z]{42,45}" +PUBKEY_REGEX = "(?![OIl])[0-9A-Za-z]{42,45}" class Transaction: @@ -46,7 +46,7 @@ class Transaction: if self.verbose: print("useMempool:", str(self.useMempool)) queryBuild = gql( """ - query ($recipient: String!, $issuer: String!, $amount: Int!, $comment: String!, $useMempool: Boolean!){ genTx( + query ($recipient: PkOrScriptGva!, $issuer: PubKeyGva!, $amount: Int!, $comment: String!, $useMempool: Boolean!){ genTx( amount: $amount comment: $comment issuer: $issuer diff --git a/zen/jaklis/lib/messaging.py b/zen/jaklis/lib/messaging.py index 93541a6..2165182 100755 --- a/zen/jaklis/lib/messaging.py +++ b/zen/jaklis/lib/messaging.py @@ -1,6 +1,7 @@ import os, sys, ast, requests, json, base58, base64 from time import time from datetime import datetime +from termcolor import colored from lib.natools import fmt, get_privkey, box_decrypt, box_encrypt from lib.cesiumCommon import CesiumCommon, pp_json, PUBKEY_REGEX @@ -56,11 +57,11 @@ class ReadFromCesium(CesiumCommon): nbrMsg = totalMsg if totalMsg == 0: - print("Aucun message à afficher.") + print(colored("Aucun message à afficher.", 'yellow')) return True else: infoTotal = " Nombre de messages: " + str(nbrMsg) + "/" + str(totalMsg) + " " - print(infoTotal.center(rows, '#')) + print(colored(infoTotal.center(rows, '#'), "yellow")) for hits in msgJSON["hits"]: self.idMsg = hits["_id"] msgSrc = hits["_source"] @@ -76,19 +77,19 @@ class ReadFromCesium(CesiumCommon): headerMsg = startHeader + date + "(ID: {})".format(self.idMsg) + " " print('-'.center(rows, '-')) - print(headerMsg.center(rows+9, '-')) + print(colored(headerMsg, "blue").center(rows+9, '-')) print('-'.center(rows, '-')) try: self.title = decrypt(msgSrc["title"]) self.content = decrypt(msgSrc["content"]) except Exception as e: - sys.stderr.write(str(e) + '\n') + sys.stderr.write(colored(str(e), 'red') + '\n') pp_json(hits) continue print('\033[1m' + self.title + '\033[0m') print(self.content) - print(infoTotal.center(rows, '#')) + print(colored(infoTotal.center(rows, '#'), "yellow")) # Parse JSON result and display messages def jsonMessages(self, msgJSON, nbrMsg, outbox): @@ -124,7 +125,7 @@ class ReadFromCesium(CesiumCommon): self.title = decrypt(msgSrc["title"]) self.content = decrypt(msgSrc["content"]) except Exception as e: - sys.stderr.write(str(e) + '\n') + sys.stderr.write(colored(str(e), 'red') + '\n') pp_json(hits) continue @@ -182,7 +183,7 @@ class SendToCesium(CesiumCommon): sys.exit(1) else: if result.status_code == 200: - print("Message envoyé avec succès !") + print(colored("Message envoyé avec succès !", "green")) print("ID: " + result.text) return result else: @@ -225,11 +226,11 @@ class DeleteFromCesium(CesiumCommon): elif result.status_code == 403: raise ValueError("Vous n'êtes pas l'auteur de ce message.") except Exception as e: - sys.stderr.write("Impossible de supprimer le message {0}:\n".format(idMsg) + str(e) + "\n") + sys.stderr.write(colored("Impossible de supprimer le message {0}:\n".format(idMsg), 'red') + str(e) + "\n") return False else: if result.status_code == 200: - print("Message {0} supprimé avec succès !".format(idMsg)) + print(colored("Message {0} supprimé avec succès !".format(idMsg), "green")) return result else: sys.stderr.write("Erreur inconnue.") diff --git a/zen/jaklis/lib/offers.py b/zen/jaklis/lib/offers.py index c8358a2..5af44f4 100644 --- a/zen/jaklis/lib/offers.py +++ b/zen/jaklis/lib/offers.py @@ -25,9 +25,8 @@ class Offers(CesiumCommon): data['thumbnail']['_content'] = picture data['thumbnail']['_content_type'] = "image/png" # if category: data['category'] = category - # else: data['category'] = {"parent":"cat24","localizedNames":{"en":"CD / Music","es-ES":"CDs / M\u00fasica","fr-FR":"CD / Musique"},"name":"CD / Musique","id":"cat26"} - # data['category'] = {"parent":"cat90","localizedNames":{"en":"Fruits & Vegetables","es-ES":"Frutas y Vegetales","fr-FR":"Fruits & Légumes"},"name":"Fruits & Légumes","id":"cat92"} - data['category'] = {"parent":"cat24","localizedNames":{"en":"DVD / Films","es-ES":"DVDs / Cine","fr-FR":"DVD / Films"},"name":"DVD / Films","id":"cat25"} + # else: + data['category'] = {"parent":"cat90","localizedNames":{"en":"Fruits & Vegetables","es-ES":"Frutas y Vegetales","fr-FR":"Fruits & Légumes"},"name":"Fruits & Légumes","id":"cat92"} if price: data['price'] = float(price) * 100 data['type'] = 'offer' data['time'] = timeSent @@ -95,11 +94,13 @@ class Offers(CesiumCommon): if type == 'set': reqQuery = '{0}/market/record'.format(self.pod) elif type == 'get': - reqQuery = '{0}/market/record/{1}?_source=category,title,description,issuer,time,creationTime,location,address,city,price,unit,currency,thumbnail._content_type,picturesCount,type,stock,fees,feesCurrency,geoPoint,pubkey,freePrice'.format(self.pod, id) + reqQuery = '{0}/market/record/{1}?_source=category,title,description,issuer,time,creationTime,location,address,city,price,unit,currency,thumbnail._content_type,thumbnail._content,picturesCount,type,stock,fees,feesCurrency,geoPoint,pubkey,freePrice'.format(self.pod, id) elif type == 'erase': reqQuery = '{0}/market/delete'.format(self.pod) + result = requests.get(reqQuery, headers=headers) + # print(result) if result.status_code == 200: # print(result.text) return result.text diff --git a/zen/jaklis/lib/profiles.py b/zen/jaklis/lib/profiles.py index 5386c89..cfe2592 100755 --- a/zen/jaklis/lib/profiles.py +++ b/zen/jaklis/lib/profiles.py @@ -68,7 +68,7 @@ class Profiles(CesiumCommon): } },"from":0, "size":100, - "_source":["title", avatar,"description","city","address","socials.url","creationTime","membersCount","type"], + "_source":["title", avatar,"description","city","address","socials.url","creationTime","membersCount","type","geoPoint"], "indices_boost":{"user":100,"page":1,"group":0.01 } } diff --git a/zen/jaklis/lib/qrcode-reader.py b/zen/jaklis/lib/qrcode-reader.py new file mode 100755 index 0000000..f92bfcd --- /dev/null +++ b/zen/jaklis/lib/qrcode-reader.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 + +from io import BytesIO +import base64, base58, varint, os, json +# from lib.cesium import CesiumPlus as cs + +## BytesIO adds a stream interface to bytes +## Exemple: +qr = BytesIO(bytes.fromhex("8316140212c28e52e034ecaf684fa3e5d755db519074f27ad086bddffd26b386e55f3b623ca01f0177c0f8ce5f6a69764c7bc10263ec")) + +## Read from a file: +# qr = open("qrcode-AXfA-M5faml2THvBAmPs.bin","rb") +# qr = BytesIO(qr.read()) + +## Check magic number +assert qr.read(3) == b"\x83\x16\x14" + +## Read data type +data_type = varint.decode_stream(qr) + +## Read price type +raw_price_type = varint.decode_stream(qr) +price_type = raw_price_type >> 4 +amount_len = raw_price_type & 0b1111 + +## Read pubkey +pubkey = qr.read(32) +pubkey_b58 = base58.b58encode(pubkey) +# print("Pubkey: {}".format(pubkey_b58.decode("utf-8"))) + +## Read amount + +if price_type == 0: # Free price, ignore amount + qr.read(amount_len) + print("Free price") + +elif price_type == 1: # Units + amount = varint.decode_stream(qr) + # print("Price: {} Ğ1".format(amount/100)) + +elif price_type == 2: # UD + amount_n = varint.decode_stream(qr) + amount_e = varint.decode_stream(qr) + amount = amount_n * 10 ** -amount_e + # print("Price: {} UD_Ğ1".format(amount.decode("utf-8"))) + +else: + qr.read(amount_len) + print("Error: unknown price type, ignoring price") + +## Read data + +if data_type == 0: # No data + data = None + print("There is no data") + +elif data_type == 1: # Plain text + data = qr.read() + print("Data:") + print(data) + +elif data_type == 2: # Ğchange ad + data = base64.urlsafe_b64encode(qr.read(16)) + # print("Ğchange ad ID: {}".format(data.decode("utf-8"))) + + +## Get gchange-pod datas + +item = os.popen("./../jaklis/jaklis.py getoffer -i {0}".format(data.decode("utf-8"))) +# item = cs.getOffer(id) + + +jsonR = json.load(item) +item_time = jsonR['creationTime'] +item_name = jsonR['title'] +item_description = jsonR['description'] +item_image = jsonR['thumbnail'] +isImage = '_content' in item_image +if (isImage): + print(item_image['_content']) + +# print(jsonR) +print(item_time) +print(item_name) +print(item_description) + diff --git a/zen/jaklis/lib/likes.py b/zen/jaklis/lib/stars.py similarity index 96% rename from zen/jaklis/lib/likes.py rename to zen/jaklis/lib/stars.py index ade2a38..5eee339 100755 --- a/zen/jaklis/lib/likes.py +++ b/zen/jaklis/lib/stars.py @@ -3,6 +3,7 @@ from lib.natools import fmt, sign, get_privkey, box_decrypt, box_encrypt from time import sleep from hashlib import sha256 from datetime import datetime +from termcolor import colored from lib.cesiumCommon import CesiumCommon, PUBKEY_REGEX class ReadLikes(CesiumCommon): @@ -111,7 +112,7 @@ class SendLikes(CesiumCommon): def configDoc(self, profile, likes): if not profile: profile = self.pubkey if likes not in range(0, 6): - sys.stderr.write('Votre like doit être compris entre 0 et 5.\n') + sys.stderr.write(colored('Votre like doit être compris entre 0 et 5.\n', 'red')) return False @@ -155,7 +156,7 @@ class SendLikes(CesiumCommon): result = requests.post('{0}/user/profile/:id/_like'.format(self.pod), headers=headers, data=document) if result.status_code == 200: - print("Profile liké avec succès !") + print(colored("Profile liké avec succès !", 'green')) return result.text elif result.status_code == 400: resultJson = json.loads(result.text) @@ -235,7 +236,7 @@ class UnLikes(CesiumCommon): if result.status_code == 200: if not silent: - print("Like supprimé avec succès !") + print(colored("Like supprimé avec succès !", 'green')) return result.text else: sys.stderr.write("Echec de l'envoi du document de lecture des messages...\n" + result.text + '\n') diff --git a/zen/jaklis/requirements.txt b/zen/jaklis/requirements.txt index afcf4b4..67be260 100755 --- a/zen/jaklis/requirements.txt +++ b/zen/jaklis/requirements.txt @@ -1,7 +1,9 @@ wheel base58 pybase64 -duniterpy +duniterpy==0.62.0 termcolor python-dotenv +gql==3.0.0a5 +#gql==2.0 requests