Exemplo n.º 1
0
def main():
    """The main method of futaam, loads the selected interface and
    then hands off execution to the interface's main method."""
    import sys
    import os
    import imp
    import traceback
    import subprocess
    import json
    import hashlib
    import futaam.interfaces.common.utils as utils
    from futaam.interfaces import get_interface
    colors = utils.colors()
    confpath = os.path.join(os.environ['HOME'], '.futaam')
    if os.path.exists(confpath):
        conf_file = open(confpath, 'r')
        conf = json.load(conf_file)
        conf_file.close()
    else:
        conf = {}

    sha256 = lambda x: 'sha256:' + \
        hashlib.sha256(x).hexdigest() if x != None else None
    write_rules = {'default.password': sha256}

    def load(filepath):
        """Loads filepath"""
        try:
            interface_file = open(filepath, 'U')
            return imp.load_module(filepath.split('/')[-1:][0].split('.')[0],
			interface_file, os.path.realpath(filepath), ('.py', 'U', 1))
        except (IOError, ImportError) as info:
            print((colors.fail + 'Could not load submodule: ' +
                  filepath + colors.default))
            print(('--- ' + str(info) + ' ---'))
            print(traceback.format_exc())
            exit(1)

    def print_help(intf):
        """Prints help information"""
        if intf == '':
            ret = colors.header + 'Usage:' + colors.default + ' ' + \
                sys.argv[0] + ' [filename] [--interfacename] [options]\n\n'
            ret += '\t--help or -h prints this help page\n'
            ret += "\t--interfaces or -i prints the list of available " + \
            "interfaces\n"
            ret += '\t--INTERFACENAME starts Futaam on the desired interface,'+\
            colors.warning + '\n\t replace "INTERFACENAME" with one of the'+\
            'available interfaces' + colors.default + '\n'
            return ret
        else:
            if os.path.exists(os.path.join(path, 'interfaces/')
			+ intf[1:] + '.py'):
                return load(os.path.join(path, 'interfaces/') +
				intf[1:] + '.py').print_help()
            elif os.path.exists(os.path.join(path, 'interfaces/')
			+ intf[1:] + '.js'):
                return subprocess.Popen(['node', os.path.join(path,
				'interfaces/') + intf[1:] + '.js', '--help'],
				stdout=subprocess.PIPE).communicate()[0]

    arguments = []
    path = os.path.dirname(os.path.realpath(__file__))
    interface_list = get_interface(os.path.join(path, 'interfaces/'))
    interface = None
    if len(sys.argv) == 1:
        sys.argv.append('--help')
    for i, arg in enumerate(sys.argv):
        if i == 0:
            continue
        if arg[:6] == '--help':
            print((print_help(arg[6:])))
            sys.exit(0)
        elif arg[:2] == '-h':
            print((print_help(arg[2:])))
            sys.exit(0)
        elif arg == '--interfaces' or arg == '-i' or arg == '--modules' \
        or arg == '-m':
            sys.stdout.write(
                colors.header + 'Available interfaces: ' + colors.green)
            txt = ''
            for i in interface_list:
                txt += i + ', '
            txt = txt[:-2] + '.'
            sys.stdout.write(txt + colors.default)
            print('\n\nTo obtain help on them, use --help-interface, replacing \
            \'interface\' with the name you want')
            sys.exit(0)
        elif arg.lower() in ['--conf', '--config']:
            if len(sys.argv) <= i + 1:
                print('Missing argument for ' + arg)
                sys.exit(1)
            elif sys.argv[i + 1].startswith('--'):
                print('Missing argument for ' + arg)
                sys.exit(1)

            key = sys.argv[i + 1]
            if key.find('=') != -1:
                key = key.split('=')
                value = key[1]
                key = key[0]
            else:
                if len(sys.argv) <= i + 2:
                    if key in conf:
                        print('Unsetting ' + key)
                    else:
                        print('Key not found')
                        sys.exit(1)
                    value = None
                else:
                    value = sys.argv[i + 2]

            if key in write_rules:
                value = write_rules[key](value)

            conf[key] = value
            conf_file = open(confpath, 'w')
            conf_file.write(json.dumps(conf))
            conf_file.close()

            sys.exit(0)
        elif arg[:2] == '--':
            if arg[2:] in interface_list:
                if interface != None:
                    print((colors.warning + 'Ignoring argument --' + interface +
                          '. Make sure interfaces don\'t conflict with \
						  internal triggers.' + colors.default))
                interface = arg[2:]
            else:
                arguments.append(arg)
        else:
            arguments.append(arg)

    if interface == None:
        if os.name != 'nt':
            interface = 'text'
        else:
            interface = 'gui'

    if os.path.exists(os.path.join(path, 'interfaces/') + interface + '.py'):
        load(os.path.join(path, 'interfaces/')
             + interface + '.py').main(arguments, __version__)
    elif os.path.exists(os.path.join(path, 'interfaces/') + interface + '.js'):
        subprocess.Popen(
            ['node', os.path.join(path, 'interfaces/') + interface + '.js']
            + arguments)
Exemplo n.º 2
0
else:
    CONFS = {}

try:
    PS1 = CONFS["PS1"]
except LookupError:
    PS1 = "[%green%%N%default%]> "
if PS1 == None:
    PS1 = "[%green%%N%default%]> "
if PS1[-1:] != " ":
    PS1 += " "

NYAA = utils.NyaaWrapper()
ANN = utils.ANNWrapper()
VNDB = utils.VNDB("Futaam", "0.1", debug="--verbose" in sys.argv)
COLORS = utils.colors()
COLORS.enable()


def rebuild_ids(database):
    """ Rebuilds database ids"""
    for entry_id in range(0, database.dictionary["count"]):
        database.dictionary["items"][entry_id]["id"] = entry_id
    database.save()


def pick_entry(index, database):
    """Returns the entry at index in the specified database"""
    if index.isdigit() == False:
        print(COLORS.fail + "Argument must be the index number" + COLORS.default)
        return None
Exemplo n.º 3
0
"""
try:
    import readline
except ImportError:
    print("Module readline unavailable.")
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")

import os
import sys
from futaam.interfaces import ARGS
from futaam.interfaces.common.utils import colors
from futaam.interfaces.common.parser import Parser

COLORS = colors()
COLORS.enable()

def main(argv, version):
    dbfile = []
    host = ''
    port = 8500
    password = ''
	# gather arguments
    dbfile = ARGS.database
    host = ''
    if ARGS.host:
        host = ARGS.host
    if ARGS.password:
        password = ARGS.password
    if ARGS.port:
Exemplo n.º 4
0
"""
try:
    import readline
except ImportError:
    print("Module readline unavailable.")
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")

import os
import sys
from futaam.interfaces import ARGS
from futaam.interfaces.common.utils import colors
from futaam.interfaces.common.parser import Parser

COLORS = colors()
COLORS.enable()


def main(argv, version):
    dbfile = []
    host = ''
    port = 8500
    password = ''
    # gather arguments
    dbfile = ARGS.database
    host = ''
    if ARGS.host:
        host = ARGS.host
    if ARGS.password:
        password = ARGS.password
Exemplo n.º 5
0
else:
    CONFS = {}

try:
    PS1 = CONFS['PS1']
except LookupError:
    PS1 = '[%green%%N%default%]> '
if PS1 == None:
    PS1 = '[%green%%N%default%]> '
if PS1[-1:] != ' ':
    PS1 += ' '

NYAA = utils.NyaaWrapper()
ANN = utils.ANNWrapper()
VNDB = utils.VNDB('Futaam', '0.1', debug='--verbose' in sys.argv)
COLORS = utils.colors()
COLORS.enable()


def rebuild_ids(database):
    """ Rebuilds database ids"""
    for entry_id in range(0, database.dictionary['count']):
        database.dictionary['items'][entry_id]['id'] = entry_id
    database.save()


def pick_entry(index, database):
    """Returns the entry at index in the specified database"""
    if index.isdigit() == False:
        print((COLORS.fail + 'Argument must be the index number' +\
  COLORS.default))
Exemplo n.º 6
0
Arquivo: gui.py Projeto: HarHar/Futaam
def main(argv, version):
    global model
    global ui
    global uiPrefix
    global ANN
    global DB_FILE
    global DBS
    global USERNAME
    global PASSWORD
    global PORT 
    global HOST
    global HOOKS

    ANN = utils.ANNWrapper()
    ANN.init()

    confpath = os.path.join(
        os.getenv('USERPROFILE') or os.getenv('HOME'), '.futaam')
    if os.path.exists(confpath):
        f = open(confpath, 'r')
        confs = json.load(f)
        f.close()
    else:
        confs = {}

    colors = utils.colors()
    colors.enable()

    uiPrefix = None
    if os.name == "nt":
        if os.path.exists(sys.prefix + "\\Scripts\\futaam"):
            uiPrefix = sys.prefix + "\\Scripts\\futaam\\"
    else:
        if os.path.exists("/usr/share/futaam/"):
            uiPrefix = "/usr/share/futaam/"
        elif os.path.exists("/usr/local/share/futaam"):
            uiPrefix = "/usr/local/share/futaam/"
    if uiPrefix == None:
        uiPrefix = cur_dir() + "/ui/"

    app = QtGui.QApplication(argv)

    for x in argv:
        if os.path.exists(x):
            break
    else:
        filename = QtGui.QFileDialog.getOpenFileName(
            None, "Open Data File", "", 
            "Futaam Database (*.db);; All Files (*)")
        if filename != None:
            argv.append(filename)

    # gather arguments
    DB_FILE = ARGS.database
    if ARGS.host:
       HOST = ARGS.host
    if ARGS.password:
       PASSWORD = ARGS.password
    if ARGS.username:
        USERNAME = ARGS.username
    if ARGS.port:
        PORT = ARGS.port
    if ARGS.hooks:
        HOOKS = ARGS.hooks

    if len(DB_FILE) == 0 and HOST == '':
        print(colors.fail + 'No database file specified' + colors.default)
        help()
        sys.exit(1)
    if HOST == '':
        DBS = []
        for fn in DB_FILE:
            DBS.append(parser.Parser(fn, hooks=HOOKS))
        currentdb = 0
    else:
        if USERNAME == '':
            if 'default.user' in confs:
                print('[' + colors.blue + 'info' + colors.default +\
                '] using default user')
                USERNAME = confs['default.user']
            else:
                USERNAME = input('Username for \'' + HOST + '\': ')
        if 'default.password' in confs:
            print('[' + colors.blue + 'info' + colors.default +\
            '] using default password')
            PASSWORD = confs['default.password']
        else:
            PASSWORD = getpass.getpass(
                'Password for ' + USERNAME + '@' + HOST + ': ')
        DBS = []
        try:
            DBS.append(
                parser.Parser(HOST=host, PORT=port, username=USERNAME, 
                password=password, hooks=HOOKS))
        except Exception as e:
            print('[' + colors.fail + 'error' + colors.default + '] ' +\
            str(e).replace('305 ', ''))
            sys.exit(1)
        currentdb = 0

    ui = uic.loadUi(uiPrefix + "gui.ui")
    ui.show()

    model = TableModel(parent=ui.centralwidget)
    if len(argv) == 0:
        help()
    if len(DB_FILE) == 0 and len(DBS) > 0:
        DB_FILE = ['']
    model.load_db(DB_FILE[0], DBS[0])
    ui.tableView.setModel(model)
    rowHeader = ui.tableView.verticalHeader()
    rowHeader.setMovable(True)
    reloadTable()
    ui.tableView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
    ui.tableView.customContextMenuRequested.connect(table_menu)

    QtCore.QObject.connect(
        ui.actionQuit, QtCore.SIGNAL("triggered()"), ui.close)
    QtCore.QObject.connect(
        ui.actionOpen, QtCore.SIGNAL("triggered()"), showOpenDbDialog)
    QtCore.QObject.connect(
        ui.actionSave, QtCore.SIGNAL("triggered()"), model.db.save)
    QtCore.QObject.connect(
        ui.actionDelete_Entry, QtCore.SIGNAL("triggered()"), 
        showDeleteEntryDialog)
    QtCore.QObject.connect(
        ui.actionAdd_Entry, QtCore.SIGNAL("triggered()"), showAddEntryDialog)
    QtCore.QObject.connect(
        ui.actionSwap_Entries, QtCore.SIGNAL("triggered()"), 
        showSwapEntriesDialog)
    QtCore.QObject.connect(
        ui.actionAbout_Futaam, QtCore.SIGNAL("triggered()"), showAboutDialog)
    QtCore.QObject.connect(
        ui.actionEdit_Entry, QtCore.SIGNAL("triggered()"), showEditEntryDialog)
    QtCore.QObject.connect(
        ui.actionViewDetails, QtCore.SIGNAL("triggered()"), showInfoDialog)
    QtCore.QObject.connect(
        ui.actionNew, QtCore.SIGNAL("triggered()"), showNewDbDialog)
    QtCore.QObject.connect(
        ui.actionStats, QtCore.SIGNAL("triggered()"), showStatsDialog)
    QtCore.QObject.connect(
        ui.actionReadme, QtCore.SIGNAL("triggered()"), openReadme)
    QtCore.QObject.connect(ui.tableView, QtCore.SIGNAL(
        "doubleClicked(QModelIndex)"), showInfoDialog_preselected)
    QtCore.QObject.connect(
        rowHeader, QtCore.SIGNAL("sectionMoved(int, int, int)"), dragSwap)
    exit(app.exec_())
Exemplo n.º 7
0
def main(argv, version):
    global model
    global ui
    global uiPrefix
    global ANN
    global DB_FILE
    global DBS
    global USERNAME
    global PASSWORD
    global PORT 
    global HOST
    global HOOKS

    ANN = utils.ANNWrapper()
    ANN.init()

    confpath = os.path.join(
        os.getenv('USERPROFILE') or os.getenv('HOME'), '.futaam')
    if os.path.exists(confpath):
        f = open(confpath, 'r')
        confs = json.load(f)
        f.close()
    else:
        confs = {}

    colors = utils.colors()
    colors.enable()

    uiPrefix = None
    if os.name == "nt":
        if os.path.exists(sys.prefix + "\\Scripts\\futaam"):
            uiPrefix = sys.prefix + "\\Scripts\\futaam\\"
    else:
        if os.path.exists("/usr/share/futaam/"):
            uiPrefix = "/usr/share/futaam/"
        elif os.path.exists("/usr/local/share/futaam"):
            uiPrefix = "/usr/local/share/futaam/"
    if uiPrefix == None:
        uiPrefix = cur_dir() + "/ui/"

    app = QtGui.QApplication(argv)

    for x in argv:
        if os.path.exists(x):
            break
    else:
        filename = QtGui.QFileDialog.getOpenFileName(
            None, "Open Data File", "", 
            "Futaam Database (*.db);; All Files (*)")
        if filename != None:
            argv.append(filename)

    # gather arguments
    DB_FILE = ARGS.database
    if ARGS.host:
       HOST = ARGS.host
    if ARGS.password:
       PASSWORD = ARGS.password
    if ARGS.username:
        USERNAME = ARGS.username
    if ARGS.port:
        PORT = ARGS.port
    if ARGS.hooks:
        HOOKS = ARGS.hooks

    if len(DB_FILE) == 0 and HOST == '':
        print((colors.fail + 'No database file specified' + colors.default))
        help()
        sys.exit(1)
    if HOST == '':
        DBS = []
        for fn in DB_FILE:
            DBS.append(parser.Parser(fn, hooks=HOOKS))
        currentdb = 0
    else:
        if USERNAME == '':
            if 'default.user' in confs:
                print(('[' + colors.blue + 'info' + colors.default +\
                '] using default user'))
                USERNAME = confs['default.user']
            else:
                USERNAME = eval(input('Username for \'' + HOST + '\': '))
        if 'default.password' in confs:
            print(('[' + colors.blue + 'info' + colors.default +\
            '] using default password'))
            PASSWORD = confs['default.password']
        else:
            PASSWORD = getpass.getpass(
                'Password for ' + USERNAME + '@' + HOST + ': ')
        DBS = []
        try:
            DBS.append(
                parser.Parser(HOST=host, PORT=port, username=USERNAME, 
                password=password, hooks=HOOKS))
        except Exception as e:
            print(('[' + colors.fail + 'error' + colors.default + '] ' +\
            str(e).replace('305 ', '')))
            sys.exit(1)
        currentdb = 0

    ui = uic.loadUi(uiPrefix + "gui.ui")
    ui.show()

    model = TableModel(parent=ui.centralwidget)
    if len(argv) == 0:
        help()
    if len(DB_FILE) == 0 and len(DBS) > 0:
        DB_FILE = ['']
    model.load_db(DB_FILE[0], DBS[0])
    ui.tableView.setModel(model)
    rowHeader = ui.tableView.verticalHeader()
    rowHeader.setMovable(True)
    reloadTable()
    ui.tableView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
    ui.tableView.customContextMenuRequested.connect(table_menu)

    QtCore.QObject.connect(
        ui.actionQuit, QtCore.SIGNAL("triggered()"), ui.close)
    QtCore.QObject.connect(
        ui.actionOpen, QtCore.SIGNAL("triggered()"), showOpenDbDialog)
    QtCore.QObject.connect(
        ui.actionSave, QtCore.SIGNAL("triggered()"), model.db.save)
    QtCore.QObject.connect(
        ui.actionDelete_Entry, QtCore.SIGNAL("triggered()"), 
        showDeleteEntryDialog)
    QtCore.QObject.connect(
        ui.actionAdd_Entry, QtCore.SIGNAL("triggered()"), showAddEntryDialog)
    QtCore.QObject.connect(
        ui.actionSwap_Entries, QtCore.SIGNAL("triggered()"), 
        showSwapEntriesDialog)
    QtCore.QObject.connect(
        ui.actionAbout_Futaam, QtCore.SIGNAL("triggered()"), showAboutDialog)
    QtCore.QObject.connect(
        ui.actionEdit_Entry, QtCore.SIGNAL("triggered()"), showEditEntryDialog)
    QtCore.QObject.connect(
        ui.actionViewDetails, QtCore.SIGNAL("triggered()"), showInfoDialog)
    QtCore.QObject.connect(
        ui.actionNew, QtCore.SIGNAL("triggered()"), showNewDbDialog)
    QtCore.QObject.connect(
        ui.actionStats, QtCore.SIGNAL("triggered()"), showStatsDialog)
    QtCore.QObject.connect(
        ui.actionReadme, QtCore.SIGNAL("triggered()"), openReadme)
    QtCore.QObject.connect(ui.tableView, QtCore.SIGNAL(
        "doubleClicked(QModelIndex)"), showInfoDialog_preselected)
    QtCore.QObject.connect(
        rowHeader, QtCore.SIGNAL("sectionMoved(int, int, int)"), dragSwap)
    exit(app.exec_())