Make Onionr more user friendly

This commit mostly just made messages more readable, worked on logger, and fixed a few bugs
This commit is contained in:
Arinerron 2018-11-10 19:25:40 -08:00
parent 22115891f2
commit bb08162019
No known key found for this signature in database
GPG key ID: 99383627861C62F0
16 changed files with 245 additions and 152 deletions

View file

@ -38,13 +38,12 @@ class OnionrCLIUI:
pass
def refresh(self):
for i in range(100):
print('')
print('\n' * 80 + logger.colors.reset)
def start(self):
'''Main CLI UI interface menu'''
showMenu = True
isOnline = "No"
isOnline = 'No'
firstRun = True
choice = ''
@ -53,7 +52,7 @@ class OnionrCLIUI:
while showMenu:
if firstRun:
logger.info("please wait while Onionr starts...")
logger.info('Please wait while Onionr starts...'')
daemon = subprocess.Popen(["./onionr.py", "start"], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL)
time.sleep(30)
firstRun = False
@ -63,9 +62,8 @@ class OnionrCLIUI:
else:
isOnline = "No"
print('''
Daemon Running: ''' + isOnline + '''
logger.info('''Daemon Running: ''' + isOnline + '''
1. Flow (Anonymous public chat, use at your own risk)
2. Mail (Secure email-like service)
3. File Sharing
@ -83,7 +81,7 @@ Daemon Running: ''' + isOnline + '''
elif choice in ("2", "mail"):
self.subCommand("mail")
elif choice in ("3", "file sharing", "file"):
print("Not supported yet")
logger.warn("Not supported yet")
elif choice in ("4", "user settings", "settings"):
try:
self.setName()
@ -91,21 +89,21 @@ Daemon Running: ''' + isOnline + '''
pass
elif choice in ("5", "daemon"):
if isOnline == "Yes":
print("Onionr daemon will shutdown...")
logger.info("Onionr daemon will shutdown...")
self.myCore.daemonQueueAdd('shutdown')
try:
daemon.kill()
except UnboundLocalError:
pass
else:
print("Starting Daemon...")
logger.info("Starting Daemon...")
daemon = subprocess.Popen(["./onionr.py", "start"], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
elif choice in ("6", "quit"):
showMenu = False
elif choice == "":
pass
else:
print("Invalid choice")
logger.error("Invalid choice")
return
def setName(self):

View file

@ -71,7 +71,7 @@ class PlainEncryption:
plaintext = data
encrypted = self.api.get_core()._crypto.pubKeyEncrypt(plaintext, pubkey, anonymous=True, encodedData=True)
encrypted = self.api.get_core()._utils.bytesToStr(encrypted)
print('ONIONR ENCRYPTED DATA %s END ENCRYPTED DATA' % (encrypted,))
logger.info('Encrypted Message: \n\nONIONR ENCRYPTED DATA %s END ENCRYPTED DATA' % (encrypted,))
def decrypt(self):
plaintext = ""
data = ""
@ -89,10 +89,10 @@ class PlainEncryption:
myPub = self.api.get_core()._crypto.pubKey
decrypted = self.api.get_core()._crypto.pubKeyDecrypt(encrypted, privkey=self.api.get_core()._crypto.privKey, anonymous=True, encodedData=True)
if decrypted == False:
print("Decryption failed")
logger.error("Decryption failed")
else:
data = json.loads(decrypted)
print(data['data'])
logger.info('Decrypted Message: \n\n%s' % data['data'])
try:
logger.info("Signing public key: %s" % (data['signer'],))
assert self.api.get_core()._crypto.edVerify(data['data'], data['signer'], data['sig']) != False
@ -101,7 +101,7 @@ class PlainEncryption:
else:
logger.info("Message has good signature.")
return
def on_init(api, data = None):
'''
@ -114,4 +114,4 @@ def on_init(api, data = None):
encrypt = PlainEncryption(pluginapi)
api.commands.register(['encrypt'], encrypt.encrypt)
api.commands.register(['decrypt'], encrypt.decrypt)
return
return

View file

@ -132,10 +132,10 @@ def createRepository(plugins):
contents = {'plugins' : plugins, 'author' : getpass.getuser(), 'compiled-by' : plugin_name}
block = Block(core = pluginapi.get_core())
block.setType('repository')
block.setContent(json.dumps(contents))
return block.save(True)
def check():
@ -217,7 +217,7 @@ def pluginToBlock(plugin, import_block = True):
info = ''
with open(directory + 'info.json').read() as file:
info = json.loads(file.read())
if 'author' in info:
author = info['author']
if 'description' in info:
@ -228,10 +228,10 @@ def pluginToBlock(plugin, import_block = True):
metadata = {'author' : author, 'date' : str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')), 'name' : plugin, 'info' : info, 'compiled-by' : plugin_name, 'content' : data.decode('utf-8'), 'description' : description}
block = Block(core = pluginapi.get_core())
block.setType('plugin')
block.setContent(json.dumps(metadata))
hash = block.save(True)
# hash = pluginapi.get_core().insertBlock(, header = 'plugin', sign = True)
@ -390,12 +390,12 @@ def commandInstallPlugin():
except Exception as e:
logger.warn('Failed to lookup plugin in repositories.', timestamp = False)
logger.error('asdf', error = e, timestamp = False)
return True
if pkobh is None:
logger.error('No key for this plugin found in keystore or repositories, please specify.', timestamp = False)
return True
valid_hash = pluginapi.get_utils().validateHash(pkobh)
@ -552,49 +552,48 @@ def commandPublishPlugin():
logger.error('Plugin %s does not exist.' % pluginname, timestamp = False)
else:
logger.info(sys.argv[0] + ' ' + sys.argv[1] + ' <plugin>')
def commandCreateRepository():
if len(sys.argv) >= 3:
check()
plugins = list()
script = sys.argv[0]
del sys.argv[:2]
success = True
for pluginname in sys.argv:
distributor = None
if ':' in pluginname:
split = pluginname.split(':')
pluginname = split[0]
distributor = split[1]
pluginname = sanitize(pluginname)
if distributor is None:
distributor = getKey(pluginname)
if distributor is None:
logger.error('No distributor key was found for the plugin %s.' % pluginname, timestamp = False)
success = False
plugins.append([pluginname, distributor])
if not success:
logger.error('Please correct the above errors, then recreate the repository.')
return True
blockhash = createRepository(plugins)
print(blockhash)
if not blockhash is None:
logger.info('Successfully created repository. Execute the following command to add the repository:\n ' + logger.colors.underline + '%s --add-repository %s' % (script, blockhash))
else:
logger.error('Failed to create repository, an unknown error occurred.')
else:
logger.info(sys.argv[0] + ' ' + sys.argv[1] + ' [plugins...]')
return True
# event listeners
def on_init(api, data = None):

View file

@ -66,7 +66,7 @@ class OnionrMail:
self.sentboxList = []
self.sentMessages = {}
return
def inbox(self):
blockCount = 0
pmBlockMap = {}
@ -87,7 +87,7 @@ class OnionrMail:
continue
blockCount += 1
pmBlockMap[blockCount] = blockHash
block = pmBlocks[blockHash]
senderKey = block.signer
try:
@ -102,7 +102,7 @@ class OnionrMail:
displayList.append('%s. %s - %s: %s' % (blockCount, blockDate, senderDisplay[:12], blockHash))
#displayList.reverse()
for i in displayList:
print(i)
logger.info(i)
try:
choice = logger.readline('Enter a block number, -r to refresh, or -q to stop: ').strip().lower()
except (EOFError, KeyboardInterrupt):
@ -129,16 +129,16 @@ class OnionrMail:
else:
cancel = ''
readBlock.verifySig()
print('Message recieved from %s' % (self.myCore._utils.bytesToStr(readBlock.signer,)))
print('Valid signature:', readBlock.validSig)
logger.info('Message recieved from %s' % (self.myCore._utils.bytesToStr(readBlock.signer,)))
logger.info('Valid signature: %s' % readBlock.validSig)
if not readBlock.validSig:
logger.warn('This message has an INVALID signature. ANYONE could have sent this message.')
cancel = logger.readline('Press enter to continue to message, or -q to not open the message (recommended).')
if cancel != '-q':
print(draw_border(self.myCore._utils.escapeAnsi(readBlock.bcontent.decode().strip())))
input("Press enter to continue")
logger.readline("Press enter to continue")
return
def sentbox(self):
'''
Display sent mail messages
@ -146,7 +146,7 @@ class OnionrMail:
entering = True
while entering:
self.getSentList()
print('Enter block number or -q to return')
logger.info('Enter block number or -q to return')
try:
choice = input('>')
except (EOFError, KeyboardInterrupt) as e:
@ -158,21 +158,21 @@ class OnionrMail:
try:
self.sentboxList[int(choice) - 1]
except IndexError:
print('Invalid block')
logger.warn('Invalid block.')
else:
logger.info('Sent to: ' + self.sentMessages[self.sentboxList[int(choice) - 1]][1])
# Print ansi escaped sent message
print(self.myCore._utils.escapeAnsi(self.sentMessages[self.sentboxList[int(choice) - 1]][0]))
logger.info(self.myCore._utils.escapeAnsi(self.sentMessages[self.sentboxList[int(choice) - 1]][0]))
input('Press enter to continue...')
return
def getSentList(self):
count = 1
for i in self.sentboxTools.listSent():
self.sentboxList.append(i['hash'])
self.sentMessages[i['hash']] = (i['message'], i['peer'])
print('%s. %s - %s - %s' % (count, i['hash'], i['peer'][:12], i['date']))
logger.info('%s. %s - %s - %s' % (count, i['hash'], i['peer'][:12], i['date']))
count += 1
def draftMessage(self):
@ -198,7 +198,7 @@ class OnionrMail:
# if -q or ctrl-c/d, exit function here, otherwise we successfully got the public key
return
print('Enter your message, stop by entering -q on a new line.')
logger.info('Enter your message, stop by entering -q on a new line.')
while newLine != '-q':
try:
newLine = input()
@ -209,7 +209,7 @@ class OnionrMail:
newLine += '\n'
message += newLine
print('Inserting encrypted message as Onionr block....')
logger.info('Inserting encrypted message as Onionr block....')
blockID = self.myCore.insertBlock(message, header='pm', encryptType='asym', asymPeer=recip, sign=True)
self.sentboxTools.addToSent(blockID, recip, message)
@ -217,7 +217,7 @@ class OnionrMail:
choice = ''
while True:
print(self.strings.programTag + '\n\nOur ID: ' + self.myCore._crypto.pubKey + self.strings.mainMenu.title()) # print out main menu
logger.info(self.strings.programTag + '\n\nOur ID: ' + self.myCore._crypto.pubKey + self.strings.mainMenu.title()) # print out main menu
try:
choice = logger.readline('Enter 1-%s:\n' % (len(self.strings.mainMenuChoices))).lower().strip()
@ -251,4 +251,4 @@ def on_init(api, data = None):
mail = OnionrMail(pluginapi)
api.commands.register(['mail'], mail.menu)
api.commands.register_help('mail', 'Interact with OnionrMail')
return
return

View file

@ -2,6 +2,7 @@
"general" : {
"dev_mode" : true,
"display_header" : true,
"minimum_block_pow": 5,
"minimum_send_pow": 5,
@ -34,7 +35,20 @@
"client" : {
},
"log": {
"plugins" : {
"enabled" : {
},
"disabled" : {
}
},
"log" : {
"verbosity" : "default",
"file": {
"output": false,
"path": "data/output.log"

View file

@ -3,9 +3,9 @@ P G'
P G''
P G'' '
P G''''''
P :G;'''''P:
P ::G;'''P::
P :::G;;P:::
P :G''''''P:
P ::G''''P::
P :::G''P:::
P ::::::::
P ::::::::::::
P :::::::::::::::
@ -20,6 +20,7 @@ P :::: ::::: ::::: ::: W :::: :: :: :: ::::: :: :: :: ::
P :::: :::::: :::::: ::::
P :::: :::::::::::: :::: GvPBV
P ::::: :::::::: ::::
P ::::: ::::::
P ::::: :::::
P ::::::::::::::::
P :::::::