Add help menu, refactor code

This commit is contained in:
Arinerron 2018-02-21 23:24:25 -08:00
parent 005273b52c
commit 8acef01b68
No known key found for this signature in database
GPG Key ID: 99383627861C62F0
3 changed files with 127 additions and 42 deletions

View File

@ -78,60 +78,67 @@ _type = OUTPUT_TO_CONSOLE | USE_ANSI # the default settings for logging
_level = LEVEL_DEBUG # the lowest level to log _level = LEVEL_DEBUG # the lowest level to log
_outputfile = './output.log' # the file to log to _outputfile = './output.log' # the file to log to
def set_settings(type):
''' '''
Set the settings for the logger using bitwise operators Set the settings for the logger using bitwise operators
''' '''
def set_settings(type):
global _type global _type
_type = type _type = type
def get_settings():
''' '''
Get settings from the logger Get settings from the logger
''' '''
def get_settings():
return _type return _type
def set_level(level):
''' '''
Set the lowest log level to output Set the lowest log level to output
''' '''
def set_level(level):
global _level global _level
_level = level _level = level
def get_level():
''' '''
Get the lowest log level currently being outputted Get the lowest log level currently being outputted
''' '''
def get_level():
return _level return _level
def raw(data):
''' '''
Outputs raw data to console without formatting Outputs raw data to console without formatting
''' '''
def raw(data):
if get_settings() & OUTPUT_TO_CONSOLE: if get_settings() & OUTPUT_TO_CONSOLE:
print(data) print(data)
if get_settings() & OUTPUT_TO_FILE: if get_settings() & OUTPUT_TO_FILE:
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 = ''):
''' '''
Logs the data Logs the data
prefix : The prefix to the output prefix : The prefix to the output
data : The actual data to output data : The actual data to output
color : The color to output before the data color : The color to output before the data
''' '''
def log(prefix, data, color = ''):
output = colors.reset + str(color) + '[' + colors.bold + str(prefix) + colors.reset + str(color) + '] ' + str(data) + colors.reset output = colors.reset + str(color) + '[' + colors.bold + str(prefix) + colors.reset + str(color) + '] ' + str(data) + colors.reset
if not get_settings() & USE_ANSI: if not get_settings() & USE_ANSI:
output = colors.filter(output) output = colors.filter(output)
raw(output) raw(output)
def readline(message = ''):
''' '''
Takes in input from the console, not stored in logs Takes in input from the console, not stored in logs
message: The message to display before taking input message: The message to display before taking input
''' '''
def readline(message = 'Enter input: '):
color = colors.fg.green + colors.bold color = colors.fg.green + colors.bold
output = colors.reset + str(color) + '... ' + colors.reset + str(message) + colors.reset output = colors.reset + str(color) + '... ' + colors.reset + str(message) + colors.reset
@ -142,12 +149,13 @@ def readline(message = 'Enter input: '):
return input() return input()
def confirm(default = 'y', message = 'Are you sure %s? '):
''' '''
Displays an "Are you sure" message, returns True for Y and False for N Displays an "Are you sure" message, returns True for Y and False for N
message: The confirmation message, use %s for (y/n) message: The confirmation message, use %s for (y/n)
default: which to prefer-- y or n default: which to prefer-- y or n
''' '''
def confirm(default = 'y', message = 'Are you sure %s? '):
color = colors.fg.green + colors.bold color = colors.fg.green + colors.bold
default = default.lower() default = default.lower()

View File

@ -133,7 +133,24 @@ class Onionr:
'add-peer': self.addPeer 'add-peer': self.addPeer
} }
def getHelp(self):
return {
'help': 'Displays this Onionr help menu',
'version': 'Displays the Onionr version',
'start': 'Starts the Onionr daemon',
'stop': 'Stops the Onionr daemon',
'stats': 'Displays node statistics',
'list-peers': 'Displays a list of peers (?)',
'add-peer': 'Adds a peer (?)',
'add-msg': 'Broadcasts a message to the Onionr network',
'pm': 'Adds a private message (?)',
'gui': 'Opens a graphical interface for Onionr'
}
def execute(self, argument): def execute(self, argument):
'''
Executes a command
'''
argument = argument[argument.startswith('--') and len('--'):] # remove -- if it starts with it argument = argument[argument.startswith('--') and len('--'):] # remove -- if it starts with it
# define commands # define commands
@ -146,12 +163,21 @@ class Onionr:
THIS SECTION DEFINES THE COMMANDS THIS SECTION DEFINES THE COMMANDS
''' '''
def version(self): def version(self, verbosity=5):
logger.info('Onionr ' + ONIONR_VERSION + ' (' + platform.machine() + ') : API v' + API_VERSION) '''
Displays the Onionr version
'''
logger.info('Onionr ' + ONIONR_VERSION + ' (' + platform.machine() + ') - API v' + API_VERSION)
if verbosity >= 1:
logger.info('Anonymous P2P Platform - GPLv3 - onionr.voidnet.tech')
if verbosity >= 2:
logger.info('Running on ' + platform.platform() + ' ' + platform.release()) logger.info('Running on ' + platform.platform() + ' ' + platform.release())
def sendEncrypt(self): def sendEncrypt(self):
'''Create a private message and send it''' '''
Create a private message and send it
'''
while True: while True:
peer = logger.readline('Peer to send to: ') peer = logger.readline('Peer to send to: ')
if self.onionrUtils.validateID(peer): if self.onionrUtils.validateID(peer):
@ -164,14 +190,26 @@ class Onionr:
def openGUI(self): def openGUI(self):
'''
Opens a graphical interface for Onionr
'''
gui.OnionrGUI(self.onionrCore) gui.OnionrGUI(self.onionrCore)
def listPeers(self): def listPeers(self):
'''
Displays a list of peers (?)
'''
logger.info('Peer list:\n') logger.info('Peer list:\n')
for i in self.onionrCore.listPeers(): for i in self.onionrCore.listPeers():
logger.info(i) logger.info(i)
def addPeer(self): def addPeer(self):
'''
Adds a peer (?)
'''
try: try:
newPeer = sys.argv[2] newPeer = sys.argv[2]
except: except:
@ -181,21 +219,38 @@ class Onionr:
self.onionrCore.addPeer(newPeer) self.onionrCore.addPeer(newPeer)
def addMessage(self): def addMessage(self):
'''
Broadcasts a message to the Onionr network
'''
while True: while True:
messageToAdd = '-txt-' + logger.readline('Broadcast message to network: ') messageToAdd = '-txt-' + logger.readline('Broadcast message to network: ')
if len(messageToAdd) >= 1: if len(messageToAdd) >= 1:
break break
addedHash = self.onionrCore.setData(messageToAdd) addedHash = self.onionrCore.setData(messageToAdd)
self.onionrCore.addToBlockDB(addedHash, selfInsert=True) self.onionrCore.addToBlockDB(addedHash, selfInsert=True)
self.onionrCore.setBlockType(addedHash, 'txt') self.onionrCore.setBlockType(addedHash, 'txt')
def notFound(self): def notFound(self):
'''
Displays a "command not found" message
'''
logger.error('Command not found.') logger.error('Command not found.')
def showHelpSuggestion(self): def showHelpSuggestion(self):
'''
Displays a message suggesting help
'''
logger.info('Do ' + logger.colors.bold + sys.argv[0] + ' --help' + logger.colors.reset + logger.colors.fg.green + ' for Onionr help.') logger.info('Do ' + logger.colors.bold + sys.argv[0] + ' --help' + logger.colors.reset + logger.colors.fg.green + ' for Onionr help.')
def start(self): def start(self):
'''
Starts the Onionr daemon
'''
if os.path.exists('.onionr-lock'): if os.path.exists('.onionr-lock'):
logger.fatal('Cannot start. Daemon is already running, or it did not exit cleanly.\n(if you are sure that there is not a daemon running, delete .onionr-lock & try again).') logger.fatal('Cannot start. Daemon is already running, or it did not exit cleanly.\n(if you are sure that there is not a daemon running, delete .onionr-lock & try again).')
else: else:
@ -208,7 +263,9 @@ class Onionr:
os.remove('.onionr-lock') os.remove('.onionr-lock')
def daemon(self): def daemon(self):
''' Start the Onionr communication daemon ''' '''
Starts the Onionr communication daemon
'''
if not os.environ.get("WERKZEUG_RUN_MAIN") == "true": if not os.environ.get("WERKZEUG_RUN_MAIN") == "true":
if self._developmentMode: if self._developmentMode:
logger.warn('DEVELOPMENT MODE ENABLED (THIS IS LESS SECURE!)') logger.warn('DEVELOPMENT MODE ENABLED (THIS IS LESS SECURE!)')
@ -226,7 +283,9 @@ class Onionr:
return return
def killDaemon(self): def killDaemon(self):
''' Shutdown the Onionr Daemon ''' '''
Shutdown the Onionr daemon
'''
logger.warn('Killing the running daemon') logger.warn('Killing the running daemon')
net = NetController(self.config['CLIENT']['PORT']) net = NetController(self.config['CLIENT']['PORT'])
@ -240,13 +299,31 @@ class Onionr:
return return
def showStats(self): def showStats(self):
''' Display statistics and exit ''' '''
Displays statistics and exits
'''
return return
def showHelp(self): def showHelp(self, command = None):
''' Show help for Onionr ''' '''
Show help for Onionr
'''
helpmenu = self.getHelp()
if command is None and len(sys.argv) >= 3:
for cmd in sys.argv[2:]:
self.showHelp(cmd)
elif not command is None:
if command.lower() in helpmenu:
logger.info(logger.colors.bold + command + logger.colors.reset + logger.colors.fg.blue + ' : ' + logger.colors.reset + helpmenu[command.lower()])
else:
logger.warn(logger.colors.bold + command + logger.colors.reset + logger.colors.fg.blue + ' : ' + logger.colors.reset + 'No help menu entry was found')
else:
self.version(0)
for command, helpmessage in helpmenu.items():
self.showHelp(command)
return return
Onionr() Onionr()

View File

@ -28,7 +28,7 @@ class OnionrTests(unittest.TestCase):
logger.debug('--------------------------') logger.debug('--------------------------')
logger.info('Running simple program run test...') logger.info('Running simple program run test...')
# Test just running ./onionr with no arguments # Test just running ./onionr with no arguments
blank = os.system('./onionr.py') blank = os.system('./onionr.py --version')
if blank != 0: if blank != 0:
self.assertTrue(False) self.assertTrue(False)
else: else: