Merge branch 'refactoring2' into new-pm

This commit is contained in:
Kevin Froman 2018-07-18 02:36:40 -05:00
commit 732fe70ff4
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/>.
'''
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

View File

@ -134,7 +134,7 @@ def raw(data, fd = sys.stdout):
with open(_outputfile, "a+") as f:
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
prefix : The prefix to the output
@ -145,7 +145,7 @@ def log(prefix, data, color = '', timestamp=True, fd = sys.stdout):
if timestamp:
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:
output = colors.filter(output)
@ -201,31 +201,37 @@ def confirm(default = 'y', message = 'Are you sure %s? '):
return default == 'y'
# 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:
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
def info(data, timestamp=False):
def info(data, timestamp = False, prompt = True):
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
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:
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
def error(data, error=None, timestamp=True):
def error(data, error = None, timestamp = True, prompt = True):
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:
debug('Error: ' + str(error) + parse_error())
# 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:
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
def parse_error():

View File

@ -57,16 +57,16 @@ class Block:
# handle arguments
if self.getCore() is None:
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
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())
else:
logger.debug('Did not update block')
logger.debug('Did not update block.')
# logic
@ -514,6 +514,8 @@ class Block:
if not signer is None:
if isinstance(signer, (str,)):
signer = [signer]
if isinstance(signer, (bytes,)):
signer = [signer.decode()]
isSigner = False
for key in signer:
@ -526,12 +528,13 @@ class Block:
if relevant:
relevant_blocks.append(block)
if bool(reverse):
relevant_blocks.reverse()
return relevant_blocks
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()

View File

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