jaklis upgrade
This commit is contained in:
parent
1169ffe6e4
commit
2b4038dc67
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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:
|
||||
|
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -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)
|
||||
|
|
|
@ -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)
|
|
@ -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
|
||||
|
|
|
@ -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 = []
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -1,241 +0,0 @@
|
|||
import os, sys, ast, requests, json, base58, base64, time, string, random, re
|
||||
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 lib.cesiumCommon import CesiumCommon, PUBKEY_REGEX
|
||||
|
||||
class ReadLikes(CesiumCommon):
|
||||
# Configure JSON document to send
|
||||
def configDoc(self, profile):
|
||||
if not profile: profile = self.pubkey
|
||||
|
||||
data = {}
|
||||
data['query'] = {}
|
||||
data['query']['bool'] = {}
|
||||
data['query']['bool']['filter'] = [
|
||||
{'term': {'index': 'user'}},
|
||||
{'term': {'type': 'profile'}},
|
||||
{'term': {'id': profile}},
|
||||
{'term': {'kind': 'STAR'}}
|
||||
]
|
||||
# data['query']['bool']['should'] = {'term':{'issuer': self.issuer}}
|
||||
data['size'] = 5000
|
||||
data['_source'] = ['issuer','level']
|
||||
data['aggs'] = {
|
||||
'level_sum': {
|
||||
'sum': {
|
||||
'field': 'level'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return json.dumps(data)
|
||||
|
||||
def sendDocument(self, document):
|
||||
|
||||
headers = {
|
||||
'Content-type': 'application/json',
|
||||
}
|
||||
|
||||
# Send JSON document and get JSON result
|
||||
result = requests.post('{0}/like/record/_search'.format(self.pod), headers=headers, data=document)
|
||||
|
||||
if result.status_code == 200:
|
||||
# print(result.text)
|
||||
return result.text
|
||||
else:
|
||||
sys.stderr.write("Echec de l'envoi du document de lecture des messages...\n" + result.text + '\n')
|
||||
|
||||
def parseResult(self, result):
|
||||
result = json.loads(result)
|
||||
totalLikes = result['hits']['total']
|
||||
totalValue = result['aggregations']['level_sum']['value']
|
||||
if totalLikes:
|
||||
score = totalValue/totalLikes
|
||||
else:
|
||||
score = 0
|
||||
raw = result['hits']['hits']
|
||||
finalPrint = {}
|
||||
finalPrint['likes'] = []
|
||||
for i in raw:
|
||||
issuer = i['_source']['issuer']
|
||||
# print(issuer)
|
||||
gProfile = self.getProfile(issuer)
|
||||
try:
|
||||
pseudo = gProfile['title']
|
||||
except:
|
||||
pseudo = ''
|
||||
try:
|
||||
payTo = gProfile['pubkey']
|
||||
except:
|
||||
payTo = ''
|
||||
id = i['_id']
|
||||
level = i['_source']['level']
|
||||
if issuer == self.pubkey:
|
||||
finalPrint['yours'] = { 'id' : id, 'pseudo' : pseudo, 'payTo' : payTo, 'level' : level }
|
||||
else:
|
||||
finalPrint['likes'].append({ 'issuer' : issuer, 'pseudo' : pseudo, 'payTo' : payTo, 'level' : level })
|
||||
finalPrint['score'] = score
|
||||
|
||||
return json.dumps(finalPrint)
|
||||
|
||||
def getProfile(self, profile):
|
||||
headers = {
|
||||
'Content-type': 'application/json',
|
||||
}
|
||||
|
||||
data = {}
|
||||
data['query'] = {}
|
||||
data['query']['bool'] = {}
|
||||
data['query']['bool']['filter'] = [
|
||||
{'term': {'_index': 'user'}},
|
||||
{'term': {'_type': 'profile'}},
|
||||
{'term': {'_id': profile}}
|
||||
]
|
||||
data['_source'] = ['title','pubkey']
|
||||
|
||||
data = json.dumps(data)
|
||||
|
||||
result = requests.post('{0}/user/profile/_search'.format(self.pod), headers=headers, data=data)
|
||||
result = json.loads(result.text)['hits']['hits']
|
||||
for i in result:
|
||||
return i['_source']
|
||||
|
||||
|
||||
#################### Like class ####################
|
||||
|
||||
|
||||
class SendLikes(CesiumCommon):
|
||||
# Configure JSON document to send
|
||||
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')
|
||||
return False
|
||||
|
||||
|
||||
timeSent = int(time.time())
|
||||
|
||||
data = {}
|
||||
data['version'] = 2
|
||||
data['index'] = "user"
|
||||
data['type'] = "profile"
|
||||
data['id'] = profile
|
||||
data['kind'] = "STAR"
|
||||
data['level'] = likes
|
||||
data['time'] = timeSent
|
||||
data['issuer'] = self.pubkey
|
||||
|
||||
document = json.dumps(data)
|
||||
|
||||
# Generate hash of document
|
||||
hashDoc = sha256(document.encode()).hexdigest().upper()
|
||||
|
||||
# Generate signature of document
|
||||
signature = fmt["64"](sign(hashDoc.encode(), get_privkey(self.dunikey, "pubsec"))[:-len(hashDoc.encode())]).decode()
|
||||
|
||||
# Build final document
|
||||
data = {}
|
||||
data['hash'] = hashDoc
|
||||
data['signature'] = signature
|
||||
signJSON = json.dumps(data)
|
||||
finalJSON = {**json.loads(signJSON), **json.loads(document)}
|
||||
finalDoc = json.dumps(finalJSON)
|
||||
|
||||
return finalDoc
|
||||
|
||||
def sendDocument(self, document, pubkey):
|
||||
|
||||
headers = {
|
||||
'Content-type': 'application/json',
|
||||
}
|
||||
|
||||
# Send JSON document and get JSON result
|
||||
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 !")
|
||||
return result.text
|
||||
elif result.status_code == 400:
|
||||
resultJson = json.loads(result.text)
|
||||
if 'DuplicatedDocumentException' in resultJson['error']:
|
||||
rmLike = UnLikes(self.dunikey, self.pod)
|
||||
idLike = rmLike.checkLike(pubkey)
|
||||
if idLike:
|
||||
document = rmLike.configDoc(idLike)
|
||||
rmLike.sendDocument(document, True)
|
||||
sleep(0.5)
|
||||
self.sendDocument(document, pubkey)
|
||||
return resultJson['error']
|
||||
else:
|
||||
sys.stderr.write("Echec de l'envoi du document de lecture des messages...\n" + resultJson['error'] + '\n')
|
||||
else:
|
||||
resultJson = json.loads(result.text)
|
||||
sys.stderr.write("Echec de l'envoi du document de lecture des messages...\n" + resultJson['error'] + '\n')
|
||||
|
||||
|
||||
#################### Unlike class ####################
|
||||
|
||||
|
||||
class UnLikes(CesiumCommon):
|
||||
# Check if you liked this profile
|
||||
def checkLike(self, pubkey):
|
||||
readProfileLikes = ReadLikes(self.dunikey, self.pod)
|
||||
document = readProfileLikes.configDoc(pubkey)
|
||||
result = readProfileLikes.sendDocument(document)
|
||||
result = readProfileLikes.parseResult(result)
|
||||
result = json.loads(result)
|
||||
|
||||
if 'yours' in result:
|
||||
myLike = result['yours']['id']
|
||||
return myLike
|
||||
else:
|
||||
sys.stderr.write("Vous n'avez pas liké ce profile\n")
|
||||
return False
|
||||
|
||||
# Configure JSON document to send
|
||||
def configDoc(self, idLike):
|
||||
timeSent = int(time.time())
|
||||
|
||||
data = {}
|
||||
data['version'] = 2
|
||||
data['index'] = "like"
|
||||
data['type'] = "record"
|
||||
data['id'] = idLike
|
||||
data['issuer'] = self.pubkey
|
||||
data['time'] = timeSent
|
||||
|
||||
document = json.dumps(data)
|
||||
|
||||
# Generate hash of document
|
||||
hashDoc = sha256(document.encode()).hexdigest().upper()
|
||||
|
||||
# Generate signature of document
|
||||
signature = fmt["64"](sign(hashDoc.encode(), get_privkey(self.dunikey, "pubsec"))[:-len(hashDoc.encode())]).decode()
|
||||
|
||||
# Build final document
|
||||
data = {}
|
||||
data['hash'] = hashDoc
|
||||
data['signature'] = signature
|
||||
signJSON = json.dumps(data)
|
||||
finalJSON = {**json.loads(signJSON), **json.loads(document)}
|
||||
finalDoc = json.dumps(finalJSON)
|
||||
|
||||
return finalDoc
|
||||
|
||||
def sendDocument(self, document, silent):
|
||||
|
||||
headers = {
|
||||
'Content-type': 'application/json',
|
||||
}
|
||||
|
||||
# Send JSON document and get JSON result
|
||||
result = requests.post('{0}/history/delete'.format(self.pod), headers=headers, data=document)
|
||||
|
||||
if result.status_code == 200:
|
||||
if not silent:
|
||||
print("Like supprimé avec succès !")
|
||||
return result.text
|
||||
else:
|
||||
sys.stderr.write("Echec de l'envoi du document de lecture des messages...\n" + result.text + '\n')
|
|
@ -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.")
|
||||
|
|
|
@ -25,8 +25,7 @@ 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"}
|
||||
# else:
|
||||
data['category'] = {"parent":"cat24","localizedNames":{"en":"DVD / Films","es-ES":"DVDs / Cine","fr-FR":"DVD / Films"},"name":"DVD / Films","id":"cat25"}
|
||||
if price: data['price'] = float(price) * 100
|
||||
data['type'] = 'offer'
|
||||
|
@ -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
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,9 @@
|
|||
wheel
|
||||
base58
|
||||
pybase64
|
||||
duniterpy
|
||||
duniterpy==0.62.0
|
||||
termcolor
|
||||
python-dotenv
|
||||
gql==3.0.0a5
|
||||
#gql==2.0
|
||||
requests
|
||||
|
|
|
@ -19,6 +19,14 @@ SMSADMIN="$(cat /home/pi/.zen/SMSADMIN)" ## FRENCH NUMBER
|
|||
[[ ${SMSADMIN#"$prefix"} != "${SMSADMIN}" ]] && smsadmin=0${SMSADMIN#"$prefix"} || smsadmin="${SMSADMIN}" ## 06
|
||||
|
||||
########################################################################
|
||||
## CHECK MADEINZION INTERNET SERVICES CONNEXION
|
||||
ping -q -w 1 -c 1 data.gchange.fr 2>&1>/dev/null && echo "GCHANGE+ OK" && GCHANGE=1 || GCHANGE=0
|
||||
ping -q -w 1 -c 1 g1.data.e-is.pro 2>&1>/dev/null && echo "CESIUM+ OK" && CESIUM=1 || CESIUM=0
|
||||
ping -q -w 1 -c 1 oasis.astroport.com 2>&1>/dev/null && echo "OASIS OK" && OASIS=1 || OASIS=0
|
||||
ping -q -w 1 -c 1 taurus.copylaradio.com 2>&1>/dev/null && echo "TAURUS OK" && TAURUS=1 || TAURUS=0
|
||||
########################################################################
|
||||
|
||||
########################################################################
|
||||
# GET INCOMING SMS CONTENT
|
||||
########################################################################
|
||||
########################################################################
|
||||
|
@ -31,7 +39,20 @@ PHONE="$SMS_1_NUMBER" # gammu-smsd
|
|||
|
||||
TEXT="$SMS_1_TEXT" # gammu-smsd
|
||||
[[ ! ${TEXT} ]] && TEXT="$2" # CLI MODE
|
||||
[[ "${TEXT}" == "" ]] && TEXT="TEST : ABC : 12345*" # TEST MESSAGE
|
||||
[[ "${TEXT}" == "" ]] && echo "SMS IS EMPTY - EXIT -" && exit 1
|
||||
|
||||
########################################################################
|
||||
# INTERNET CONNEXION NOT OK
|
||||
########################################################################
|
||||
if [[ $GCHANGE == 0 ]]; then
|
||||
echo "GCHANGE UNREACHABLE => CREATING timestamp.replay.sh - EXIT -"
|
||||
echo "#!/bin/bash
|
||||
sudo $MY_PATH/sms_received \"${PHONE}\" \"${TEXT}\"" > /home/${YOU}/.zen/SMS/$(date -u +%s%N | cut -b1-13).replay.sh
|
||||
exit 1
|
||||
fi
|
||||
########################################################################
|
||||
# INTERNET CONNEXION NOT OK
|
||||
########################################################################
|
||||
|
||||
########################################################################
|
||||
## LOG
|
||||
|
@ -43,7 +64,7 @@ echo "TEXT: $TEXT"
|
|||
########################################################################
|
||||
|
||||
########################################################################
|
||||
# SWITCH CASE
|
||||
# SWITCH CASE DEPENDING ON SMS TEXT FIRST WORD
|
||||
########################################################################
|
||||
CMD=$(echo "$TEXT" | awk '{print toupper($1)}')
|
||||
echo "COMMAND = $CMD"
|
||||
|
@ -55,11 +76,6 @@ case "$CMD" in
|
|||
$MY_PATH/sms/AIDE.sh "$phone" &
|
||||
;;
|
||||
|
||||
TEST)
|
||||
echo "TEST: sending ___ $TEXT _to_ $phone"
|
||||
gammu-smsd-inject TEXT "$phone" -text "$TEXT"
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "MESSAGE DE $phone POUR $CMD"
|
||||
MESSAGE=$(echo "$TEXT" | cut -d ' ' -f 2-)
|
||||
|
@ -81,5 +97,5 @@ esac
|
|||
# [[ "$phone" != "$smsadmin" ]] && gammu-smsd-inject TEXT "$smsadmin" -text "$phone : $TEXT"
|
||||
|
||||
## FILESYSTEM RIGHTS CORRECTION
|
||||
chown -R pi:pi /home/pi/.zen
|
||||
chown -R pi:pi /home/pi/.zen/SMS
|
||||
exit 0
|
||||
|
|
Loading…
Reference in New Issue