Merge branch 'refactoring2' of gitlab.com:beardog/Onionr into refactoring2

master
Kevin Froman 2018-07-18 02:36:17 -05:00
commit 02cb3d3fd4
No known key found for this signature in database
GPG Key ID: 0D414D0FE405B63B
4 changed files with 36 additions and 27 deletions

View File

@ -18,6 +18,7 @@
along with this program. If not, see <https://www.gnu.org/licenses/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
''' '''
import sqlite3, os, sys, time, math, base64, tarfile, getpass, simplecrypt, hashlib, nacl, logger, json, netcontroller, math, config import sqlite3, os, sys, time, math, base64, tarfile, getpass, simplecrypt, hashlib, nacl, logger, json, netcontroller, math, config
from onionrblockapi import Block
import onionrutils, onionrcrypto, onionrproofs, onionrevents as events, onionrexceptions, onionrvalues import onionrutils, onionrcrypto, onionrproofs, onionrevents as events, onionrexceptions, onionrvalues

View File

@ -134,7 +134,7 @@ def raw(data, fd = sys.stdout):
with open(_outputfile, "a+") as f: with open(_outputfile, "a+") as f:
f.write(colors.filter(data) + '\n') f.write(colors.filter(data) + '\n')
def log(prefix, data, color = '', timestamp=True, fd = sys.stdout): def log(prefix, data, color = '', timestamp=True, fd = sys.stdout, prompt = True):
''' '''
Logs the data Logs the data
prefix : The prefix to the output prefix : The prefix to the output
@ -145,7 +145,7 @@ def log(prefix, data, color = '', timestamp=True, fd = sys.stdout):
if timestamp: if timestamp:
curTime = time.strftime("%m-%d %H:%M:%S") + ' ' curTime = time.strftime("%m-%d %H:%M:%S") + ' '
output = colors.reset + str(color) + '[' + colors.bold + str(prefix) + colors.reset + str(color) + '] ' + curTime + str(data) + colors.reset output = colors.reset + str(color) + ('[' + colors.bold + str(prefix) + colors.reset + str(color) + '] ' if prompt is True else '') + curTime + str(data) + colors.reset
if not get_settings() & USE_ANSI: if not get_settings() & USE_ANSI:
output = colors.filter(output) output = colors.filter(output)
@ -201,31 +201,37 @@ def confirm(default = 'y', message = 'Are you sure %s? '):
return default == 'y' return default == 'y'
# debug: when there is info that could be useful for debugging purposes only # debug: when there is info that could be useful for debugging purposes only
def debug(data, timestamp=True): def debug(data, error = None, timestamp = True, prompt = True):
if get_level() <= LEVEL_DEBUG: if get_level() <= LEVEL_DEBUG:
log('/', data, timestamp=timestamp) log('/', data, timestamp=timestamp, prompt = prompt)
if not error is None:
debug('Error: ' + str(error) + parse_error())
# info: when there is something to notify the user of, such as the success of a process # info: when there is something to notify the user of, such as the success of a process
def info(data, timestamp=False): def info(data, timestamp = False, prompt = True):
if get_level() <= LEVEL_INFO: if get_level() <= LEVEL_INFO:
log('+', data, colors.fg.green, timestamp=timestamp) log('+', data, colors.fg.green, timestamp = timestamp, prompt = prompt)
# warn: when there is a potential for something bad to happen # warn: when there is a potential for something bad to happen
def warn(data, timestamp=True): def warn(data, error = None, timestamp = True, prompt = True):
if not error is None:
debug('Error: ' + str(error) + parse_error())
if get_level() <= LEVEL_WARN: if get_level() <= LEVEL_WARN:
log('!', data, colors.fg.orange, timestamp=timestamp) log('!', data, colors.fg.orange, timestamp = timestamp, prompt = prompt)
# error: when only one function, module, or process of the program encountered a problem and must stop # error: when only one function, module, or process of the program encountered a problem and must stop
def error(data, error=None, timestamp=True): def error(data, error = None, timestamp = True, prompt = True):
if get_level() <= LEVEL_ERROR: if get_level() <= LEVEL_ERROR:
log('-', data, colors.fg.red, timestamp=timestamp, fd = sys.stderr) log('-', data, colors.fg.red, timestamp = timestamp, fd = sys.stderr, prompt = prompt)
if not error is None: if not error is None:
debug('Error: ' + str(error) + parse_error()) debug('Error: ' + str(error) + parse_error())
# fatal: when the something so bad has happened that the program must stop # fatal: when the something so bad has happened that the program must stop
def fatal(data, timestamp=True): def fatal(data, error = None, timestamp=True, prompt = True):
if not error is None:
debug('Error: ' + str(error) + parse_error())
if get_level() <= LEVEL_FATAL: if get_level() <= LEVEL_FATAL:
log('#', data, colors.bg.red + colors.fg.green + colors.bold, timestamp=timestamp, fd = sys.stderr) log('#', data, colors.bg.red + colors.fg.green + colors.bold, timestamp=timestamp, fd = sys.stderr, prompt = prompt)
# returns a formatted error message # returns a formatted error message
def parse_error(): def parse_error():

View File

@ -56,15 +56,15 @@ class Block:
if self.getCore() is None: if self.getCore() is None:
self.core = onionrcore.Core() self.core = onionrcore.Core()
if not self.core._utils.validateHash(self.hash):
raise onionrexceptions.InvalidHexHash('specified block hash is not valid')
# update the blocks' contents if it exists # update the blocks' contents if it exists
if not self.getHash() is None: if not self.getHash() is None:
if not self.update(): if not self.core._utils.validateHash(self.hash):
logger.debug('Block hash %s is invalid.' % self.getHash())
raise onionrexceptions.InvalidHexHash('Block hash is invalid.')
elif not self.update():
logger.debug('Failed to open block %s.' % self.getHash()) logger.debug('Failed to open block %s.' % self.getHash())
else: else:
logger.debug('Did not update block') logger.debug('Did not update block.')
# logic # logic
@ -471,6 +471,8 @@ class Block:
if not signer is None: if not signer is None:
if isinstance(signer, (str,)): if isinstance(signer, (str,)):
signer = [signer] signer = [signer]
if isinstance(signer, (bytes,)):
signer = [signer.decode()]
isSigner = False isSigner = False
for key in signer: for key in signer:
@ -483,12 +485,13 @@ class Block:
if relevant: if relevant:
relevant_blocks.append(block) relevant_blocks.append(block)
if bool(reverse): if bool(reverse):
relevant_blocks.reverse() relevant_blocks.reverse()
return relevant_blocks return relevant_blocks
except Exception as e: except Exception as e:
logger.debug(('Failed to get blocks: %s' % str(e)) + logger.parse_error()) logger.debug('Failed to get blocks.', error = e)
return list() return list()

View File

@ -47,25 +47,24 @@ class OnionrFlow:
self.flowRunning = False self.flowRunning = False
if len(message) > 0: if len(message) > 0:
self.myCore.insertBlock(message) Block(content = message, type = 'txt', core = self.myCore).save()
logger.info("Flow is exiting, goodbye") logger.info("Flow is exiting, goodbye")
return return
def showOutput(self): def showOutput(self):
while self.flowRunning: while self.flowRunning:
for blockHash in self.myCore.getBlocksByType('txt'): for block in Block.getBlocks(type = 'txt', core = self.myCore):
if blockHash in self.alreadyOutputed: if block.getHash() in self.alreadyOutputed:
continue continue
if not self.flowRunning: if not self.flowRunning:
break break
logger.info('\n------------------------') logger.info('\n------------------------', prompt = False)
block = Block(blockHash, self.myCore)
content = block.getContent() content = block.getContent()
# Escape new lines, remove trailing whitespace, and escape ansi sequences # Escape new lines, remove trailing whitespace, and escape ansi sequences
content = self.myCore._utils.escapeAnsi(content.replace('\n', '\\n').replace('\r', '\\r').strip()) content = self.myCore._utils.escapeAnsi(content.replace('\n', '\\n').replace('\r', '\\r').strip())
logger.info("\n" + block.getDate().strftime("%m/%d %H:%M") + ' - ' + '\033[0;0m' + content) logger.info(block.getDate().strftime("%m/%d %H:%M") + ' - ' + logger.colors.reset + content, prompt = False)
self.alreadyOutputed.append(blockHash) self.alreadyOutputed.append(block.getHash())
try: try:
time.sleep(5) time.sleep(5)
except KeyboardInterrupt: except KeyboardInterrupt:
@ -84,6 +83,6 @@ def on_init(api, data = None):
global pluginapi global pluginapi
pluginapi = api pluginapi = api
flow = OnionrFlow() flow = OnionrFlow()
api.commands.register(['flow'], flow.start) api.commands.register('flow', flow.start)
api.commands.register_help('flow', 'Open the flow messaging interface') api.commands.register_help('flow', 'Open the flow messaging interface')
return return