Ejemplo n.º 1
0
def main():
    # parse arguments:
    logger.info("Parsing command line arguments")
    parser.prog = "hiob_gui"
    args = parser.parse_args()

    # create Configurator
    logger.info("Creating configurator object")
    ros_config = None
    if args.ros_publish is not None or args.ros_subscribe is not None:
        ros_config = {
            'subscribe': args.ros_subscribe,
            'publish': args.ros_publish
        }
    conf = Configurator(hiob_path=hiob_path,
                        environment_path=args.environment,
                        tracker_path=args.tracker,
                        ros_config=ros_config)

    # enable or disable se, depending on arg given
    conf.tracker["scale_estimator"]["use_scale_estimation"] = args.use_se

    # execute app app and run tracking
    logger.info("Initiate tracking process in app app")
    app = App(logger, conf)
    app.run()
Ejemplo n.º 2
0
class AppTest(unittest.TestCase):
    def setUp(self):
        self.app = App()
        self.app.load_config_file('sessions.yaml')

    def test_telnet_session(self):
        session = self.app.telnet_session

        res = session.command('cd download; pwd')
        print(res)
        res = session.command('ls -lrt')
        print(res)

    def test_ssh_session(self):
        session = self.app.ssh_session

        # res = session.command('cd download; pwd')
        # print(res)
        res = session.command('^C')
        print(res)

        # res = session.command('ls -lrt')
        # print(res)

    def test_pick(self):
        self.app.ssh_session.command('ls')
        with open('test_pickle.txt', 'w') as f:
            cPickle.dump(self.app, f)

        app = cPickle.load(open('test_pickle.txt'))
        app.ssh_session.command('ls')
Ejemplo n.º 3
0
Archivo: amdh.py Proyecto: idkwim/AMDH
def amdh():
    arguments = args_parse()

    if arguments.adb_path:
        adb_path = arguments.adb_path

    dump_apks = False
    apks_dump_folder = ""
    if arguments.apks_dump_folder:
        dump_apks = True
        apks_dump_folder = arguments.apks_dump_folder

    adb_instance = ADB(adb_path)
    device_id = device_choice(adb_instance)
    adb_instance = ADB(adb_path, device_id)
    settings_check = None

    packages = []
    if arguments.app_type:
        packages = adb_instance.list_installed_packages(arguments.app_type)

    report_apps = {}
    for package in packages:
        dumpsys_out = adb_instance.dumpsys(["package", package])
        perm_list = adb_instance.get_req_perms_dumpsys_package(dumpsys_out)
        app = App(adb_instance, package, dump_apks, apks_dump_folder,
                  perm_list)
        perms, dangerous_perms = app.check_apps()
        print("")
        if dangerous_perms.items():
            print_warning_header("Package " + package +
                                 " have some dangerous permissions: ")
            for perm, desc in dangerous_perms.items():
                print_warning("\t " + perm + " : ")
                print_warning("\t\t" + desc)
            report_apps[package] = {
                "permissions": perms,
                "dangerous_perms": dangerous_perms
            }
            print("")
            print(
                "************************************************************************"
            )
        else:
            print_info("Package " + package + " have no dangerous permissions")
            print("")
            print(
                "************************************************************************"
            )

    if arguments.H:
        settings_check = Settings(settings_file, adb_instance, True)
    else:
        settings_check = Settings(settings_file, adb_instance)

    settings_check.check()
Ejemplo n.º 4
0
 def get_songs(self):
     app = App()
     app.collection_importer = LastFmLibraryTracks
     app.collection_importer_params = {
         'api_key':    config['lastfm']['api_key'],
         'api_secret': config['lastfm']['api_secret'],
         'username':   self.data['username'],
         'limit':      int(self.data['limit']) or None
     }
     return list(app.collection())
Ejemplo n.º 5
0
    def __init__(self, data):
        self.data = data

        app = App()
        app.collection_exporter = ExFmTracks
        app.collection_exporter_params = {
            'username': config['exfm']['username'],
            'password': config['exfm']['password'],
            'limit': None
        }
        self.exporter = app.collection_exporter(**app.collection_exporter_params)
Ejemplo n.º 6
0
    def __init__(self):
        ApplicationBase.__init__(self)
        self.prefs = Preferences()
        self.prefs.load()
        self.model = App(view=self)
        self._setupActions()
        self.mainWindow = MainWindow(app=self)
        self.aboutBox = AboutBox(self.mainWindow, self, withreg=False)
        self._progress = Progress(self.mainWindow)

        self.connect(self, SIGNAL('applicationFinishedLaunching()'),
                     self.applicationFinishedLaunching)
        self.connect(QCoreApplication.instance(), SIGNAL('aboutToQuit()'),
                     self.applicationWillTerminate)
        self._progress.finished.connect(self.jobFinished)
Ejemplo n.º 7
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.columns = config['playlist']['columns']

        app = App.get_instance()

        app.audio.current_track.subscribe(self.set_distinguished_item)
Ejemplo n.º 8
0
 def __init__(self):
     logging.basicConfig(level=logging.WARNING,
                         format='%(levelname)s %(message)s')
     cocoa.install_exception_hook()
     cocoa.install_cocoa_logger()
     self.progress = cocoa.ThreadedJobPerformer()
     model = App(self)
     PyBaseApp.__init__(self, model)
Ejemplo n.º 9
0
 async def on_delete(self, playlists_names: List[str]):
     session = db.get_session()
     app = App.get_instance()
     yesno = (await
              app.window.input("Delete selected playlists? (y/n)") == "y")
     if yesno:
         session.query(Playlist).filter(
             Playlist.name.in_(playlists_names)).delete(
                 synchronize_session=False)
         session.commit()
         self.load_playlists()
Ejemplo n.º 10
0
class AppTest(unittest.TestCase):
    def setUp(self):
        self.app = App()
        self.app.load_config_file('sessions.yaml')

    def test_multi_input(self):
        session = self.app.ssh_session

        session.command('cd {}'.format(os.getcwd()))
        res = session.command('python mulit_input.py',
                              prompt=[('Please input node password:'******'aaaa'), ('Please confirm \[y/n\]', 'n')])
        pprint(res)

    def test_sleep_input(self):
        session = self.app.ssh_session
        session.command('cd {}'.format(os.getcwd()))
        res = session.command('python sleep_input.py',
                              prompt=[('Please input node password:'******'aaaa'), ('Please confirm \[y/n\]', 'n')],
                              timeout=10)
        pprint(res)
Ejemplo n.º 11
0
 def __init__(self):
     ApplicationBase.__init__(self)
     self.prefs = Preferences()
     self.prefs.load()
     self.model = App(view=self)
     self._setupActions()
     self.mainWindow = MainWindow(app=self)
     self.aboutBox = AboutBox(self.mainWindow, self, withreg=False)
     self._progress = Progress(self.mainWindow)
     
     self.connect(self, SIGNAL('applicationFinishedLaunching()'), self.applicationFinishedLaunching)
     self.connect(QCoreApplication.instance(), SIGNAL('aboutToQuit()'), self.applicationWillTerminate)
     self._progress.finished.connect(self.jobFinished)
Ejemplo n.º 12
0
def main(args):

    if args.gpu < 0:
        cuda = False
    else:
        cuda = True
        torch.cuda.set_device(args.gpu)

    default_path = create_default_path()
    print('\n*** Set default saving/loading path to:', default_path)

    if args.dataset == AIFB or args.dataset == MUTAG:
        module = importlib.import_module(MODULE.format('dglrgcn'))
        data = module.load_dglrgcn(args.data_path)
        data = to_cuda(data) if cuda else data
        mode = NODE_CLASSIFICATION
    elif args.dataset == MUTAGENICITY or args.dataset == PTC_MR or args.dataset == PTC_MM or args.dataset == PTC_FR or args.dataset == PTC_FM:
        module = importlib.import_module(MODULE.format('dortmund'))
        data = module.load_dortmund(args.data_path)
        data = to_cuda(data) if cuda else data
        mode = GRAPH_CLASSIFICATION
    else:
        raise ValueError('Unable to load dataset', args.dataset)

    print_graph_stats(data[GRAPH])

    config_params = read_params(args.config_fpath, verbose=True)

    # create GNN model
    model = Model(g=data[GRAPH],
                  config_params=config_params[0],
                  n_classes=data[N_CLASSES],
                  n_rels=data[N_RELS] if N_RELS in data else None,
                  n_entities=data[N_ENTITIES] if N_ENTITIES in data else None,
                  is_cuda=cuda,
                  mode=mode)

    if cuda:
        model.cuda()

    # 1. Training
    app = App()
    learning_config = {
        'lr': args.lr,
        'n_epochs': args.n_epochs,
        'weight_decay': args.weight_decay,
        'batch_size': args.batch_size,
        'cuda': cuda
    }
    print('\n*** Start training ***\n')
    app.train(data, config_params[0], learning_config, default_path, mode=mode)

    # 2. Testing
    print('\n*** Start testing ***\n')
    app.test(data, default_path, mode=mode)

    # 3. Delete model
    remove_model(default_path)
Ejemplo n.º 13
0
from core.app import App

if __name__ == "__main__":
    # Creating core
    app = App()
    # Running core
    app()
Ejemplo n.º 14
0
import os

if __name__ == '__main__':
    os.environ['__PACKAGE_NAME__'] = 'SyncView'
    os.environ[
        '__SECRET_KEY__'] = 'Dr4N5fXz6P88LcYvcfnCtlCK3-qoaisD6gQmz-kQj2c='
    os.environ['release_version'] = '1.0.2'

    from core.app import App

    app = App('SyncView')
    app.run()
    app.MainLoop()
Ejemplo n.º 15
0
def amdh():
    global out
    global adb_path

    if platform == "linux" or platform == "linux2":
        out = Out("Linux")
    elif platform == "darwin":
        out = Out("Darwin")
    elif platform == "win32":
        out = Out("Windows")

    arguments = args_parse()

    # ADB binary path
    if arguments.adb_path:
        adb_path = arguments.adb_path
    else:
        if platform == "linux" or platform == "linux2" or platform == "Darwin":
            if not os.path.isfile(adb_path):
                out.print_error(
                    "adb not found please use '-d' to specify the path")
                args_parse(True)
                sys.exit(1)
        else:  # Windows
            if not os.path.isfile(adb_windows_path):
                out.print_error(
                    "adb not found please use '-d' to specify the path")
                sys.exit(1)

    # Related to APKs dump
    dump_apks = False
    apks_dump_folder = ""
    if arguments.apks_dump_folder:
        dump_apks = True
        apks_dump_folder = arguments.apks_dump_folder

    # Related to scan
    scan_settings = False
    if arguments.sS:
        scan_settings = True

    scan_applications = False
    if arguments.sA:
        scan_applications = True

    # Hardening param
    harden = False
    if arguments.H:
        harden = True

    list_apps = False
    if arguments.l:
        list_apps = True

    # Check if one of the operation are chosen
    if not scan_settings and not scan_applications and not dump_apks and not harden and not list_apps:
        out.print_error("Please choose an operation")
        args_parse(True)
        exit(1)

    adb_instance = ADB(adb_path)
    device_id = device_choice(adb_instance)
    adb_instance = ADB(adb_path, device_id)
    settings_check = None

    packages = []
    if arguments.app_type:
        packages = adb_instance.list_installed_packages(arguments.app_type)

    report_apps = {}
    if scan_applications or dump_apks or list_apps:
        for package in packages:
            out.print_info(package)
            dumpsys_out = adb_instance.dumpsys(["package", package])
            perm_list = adb_instance.get_req_perms_dumpsys_package(dumpsys_out)
            app = App(adb_instance, package, scan_applications, dump_apks,
                      apks_dump_folder, perm_list)
            perms, dangerous_perms, is_device_owner = app.check_app()
            print("")
            if scan_applications:

                if dangerous_perms.items():
                    out.print_warning_header(
                        "Package " + package +
                        " has some dangerous permissions: ")
                    for perm, desc in dangerous_perms.items():
                        out.print_warning("\t " + perm + " : ")
                        out.print_warning("\t\t" + desc)
                    report_apps[package] = {
                        "permissions": perms,
                        "dangerous_perms": dangerous_perms
                    }

                else:
                    out.print_info("Package " + package +
                                   " has no dangerous permissions")

                if is_device_owner:
                    message = "/!\ \t" + package + " is device owner\t/!\ "
                    padding = len(message)
                    out.print_warning("-" * padding)
                    out.print_warning(message)
                    out.print_warning("-" * padding)

                    if arguments.rar:
                        removed, dpm = app.remove_device_admin_for_app()
                        if removed:
                            out.print_info("Device admin receivers for " +
                                           app.package_name + " removed\n")
                        else:
                            out.print_error(
                                "An error occured while removing the device admin "
                                + dpm + " .")

                # Revoke all Dangerous permissions
                if arguments.R and app.dangerous_perms:
                    successed = app.revoke_dangerous_perms()
                    if successed:
                        out.print_info("Dangerous permissions revoked\n")
                    else:
                        out.print_error(
                            "An error occured while revoking permission " +
                            perm + " to package " + app.package_name)
                elif arguments.R and not app.dangerous_perms:
                    out.print_info(
                        "No dangerous permissions granted for this package\n")

                if app.malware_confidence > 0:
                    out.print_high_warning(
                        "----------------------------MALWARE SCAN--------------------------------"
                    )
                    out.print_high_warning(
                        "The application uses some malwares permissions ")
                    out.print_high_warning(
                        str(app.malware_confidence) +
                        " malwares permissions combinations ")

                if app.score < 0:
                    out.print_high_warning(
                        "The application uses frequent malwares permissions ")

                print(
                    "************************************************************************"
                )
                time.sleep(0.5)
    if list_apps:
        print(
            "************************************************************************"
        )
        out.print_info("List of installed packages: ")
        for package in packages:
            out.print_info("\t[" + str(packages.index(package) + 1) + "] " +
                           package)
        print("")
        apps_choice = input("Select application(s) (separated by comma ','): ")
        apps_choice_list = apps_choice.replace(" ", "").split(",")

        if arguments.app_type == 'e':
            out.print_high_warning(
                "Uninstalling or disabling system Apps can break your system")

        action = ""
        while True:
            out.print_info("choose an action")
            out.print_info("\td: disable selected apps")
            out.print_info("\tu: uninstall selected apps")
            out.print_info("\ts: skip")
            print("")
            action = input("Action: ")
            action = action.replace(" ", "")
            if action == 'd' or action == 'u' or action == 's':
                break
            else:
                print("action " + action + " this")
                out.print_error("Invalid action")
                continue

        for id_app in apps_choice_list:

            if action == 'd':
                try:
                    adb_instance.disable_app(packages[int(id_app) - 1])
                    out.print_success(packages[int(id_app) - 1] + " disabled")
                except Exception as e:
                    out.print_error("An Error occured while disabling " +
                                    packages[int(id_app) - 1])
            elif action == 'u':
                try:
                    adb_instance.uninstall_app(packages[int(id_app) - 1])
                    out.print_success(packages[int(id_app) - 1] +
                                      " uninstalled")
                except Exception as e:
                    out.print_error("An Error occured while uninstalling " +
                                    packages[int(id_app) - 1])
            elif action == 's':
                break

    if harden:
        settings_check = Settings(settings_file, adb_instance, True, out=out)
    else:
        settings_check = Settings(settings_file, adb_instance, out=out)

    if scan_settings:
        settings_check.check()
Ejemplo n.º 16
0
class PdfMasher(ApplicationBase):
    LOGO_NAME = 'logo'

    def __init__(self):
        ApplicationBase.__init__(self)
        self.prefs = Preferences()
        self.prefs.load()
        self.model = App(view=self)
        self._setupActions()
        self.mainWindow = MainWindow(app=self)
        self.aboutBox = AboutBox(self.mainWindow, self, withreg=False)
        self._progress = Progress(self.mainWindow)

        self.connect(self, SIGNAL('applicationFinishedLaunching()'),
                     self.applicationFinishedLaunching)
        self.connect(QCoreApplication.instance(), SIGNAL('aboutToQuit()'),
                     self.applicationWillTerminate)
        self._progress.finished.connect(self.jobFinished)

    #--- Public
    def askForRegCode(self):
        self.reg.ask_for_code()

    #--- Private
    def _setupActions(self):
        ACTIONS = [
            ('actionLoadProject', 'Ctrl+Shift+O', '', tr("Load Project"),
             self.model.load_project),
            ('actionSaveProject', 'Ctrl+S', '', tr("Save Project"),
             self.model.save_project),
            ('actionQuit', 'Ctrl+Q', '', tr("Quit"), self.quitTriggered),
            ('actionShowHelp', 'F1', '', tr("PdfMasher Help"),
             self.showHelpTriggered),
            ('actionAbout', '', '', tr("About PdfMasher"),
             self.showAboutBoxTriggered),
            ('actionCheckForUpdate', '', '', tr("Check for Update"),
             self.checkForUpdateTriggered),
            ('actionOpenDebugLog', '', '', tr("Open Debug Log"),
             self.openDebugLogTriggered),
        ]
        createActions(ACTIONS, self)

        if ISLINUX:
            self.actionCheckForUpdate.setVisible(
                False)  # This only works on Windows

    #--- Event Handling
    def applicationFinishedLaunching(self):
        self.mainWindow.show()

    def applicationWillTerminate(self):
        self.prefs.save()

    def jobFinished(self, jobid):
        self.model._job_completed(jobid)

    def checkForUpdateTriggered(self):
        QProcess.execute('updater.exe', ['/checknow'])

    def openDebugLogTriggered(self):
        appdata = getAppData()
        debugLogPath = op.join(appdata, 'debug.log')
        url = QUrl.fromLocalFile(debugLogPath)
        QDesktopServices.openUrl(url)

    def quitTriggered(self):
        self.mainWindow.close()

    def showAboutBoxTriggered(self):
        self.aboutBox.show()

    def showHelpTriggered(self):
        url = QUrl.fromLocalFile(op.abspath(op.join(HELP_PATH, 'index.html')))
        QDesktopServices.openUrl(url)

    #--- model --> view
    @staticmethod
    def open_path(path):
        url = QUrl.fromLocalFile(path)
        QDesktopServices.openUrl(url)

    @staticmethod
    def reveal_path(path):
        PdfMasher.open_path(op.dirname(path))

    def open_url(self, url):
        url = QUrl(url)
        QDesktopServices.openUrl(url)

    def show_message(self, msg):
        QMessageBox.information(self.mainWindow, '', msg)

    def start_job(self, jobid, func, *args):
        title = JOBID2TITLE[jobid]
        try:
            j = self._progress.create_job()
            args = tuple([j] + list(args))
            self._progress.run(jobid, title, func, args=args)
        except job.JobInProgressError:
            msg = "A previous action is still hanging in there. You can't start a new one yet. Wait a few seconds, then try again."
            QMessageBox.information(self.mainWindow, "Action in progress", msg)

    def get_default(self, key):
        return self.prefs.get_value(key)

    def set_default(self, key, value):
        self.prefs.set_value(key, value)

    def query_load_path(self, prompt, allowed_exts):
        myfilters = [
            "{} file (*.{})".format(ext.upper(), ext) for ext in allowed_exts
        ]
        files = ';;'.join(myfilters + ["All Files (*.*)"])
        return QFileDialog.getOpenFileName(self.mainWindow, prompt, '', files)

    def query_save_path(self, prompt, allowed_exts):
        myfilters = [
            "{} file (*.{})".format(ext.upper(), ext) for ext in allowed_exts
        ]
        files = ';;'.join(myfilters + ["All Files (*.*)"])
        return QFileDialog.getSaveFileName(self.mainWindow, prompt, '', files)
Ejemplo n.º 17
0
def main():
    app = App(guide)
    app.run()
Ejemplo n.º 18
0
 def on_select(self, track: Track):
     App.get_instance().audio.play_track(track)
Ejemplo n.º 19
0
def process_applications(adb_instance, device_id=""):
    packages = []
    report_apps = {}

    if main_settings.app_type:
        packages = adb_instance.list_installed_packages(
            main_settings.app_type.value)
    try:
        for package in packages:
            if not main_settings.list_apps:
                main_settings.out[device_id].print_info(package)

            report_apps[package] = dict()
            app = App(adb_instance, package, main_settings.scan_applications,
                      main_settings.dump_apks,
                      main_settings.apks_dump_folder + "/" + device_id)

            perms, dangerous_perms, is_device_admin, known_malware = app.check_app(
            )

            if known_malware:
                main_settings.out[device_id].print_error(
                    f"{package} is known as malware")
                report_apps[package]["malware"] = True

            if main_settings.scan_applications:
                if len(dangerous_perms) and dangerous_perms.items():
                    main_settings.out[device_id].print_warning_header(
                        "Package {} has some dangerous permissions: ".format(
                            package))

                    for perm, desc in dangerous_perms.items():
                        main_settings.out[device_id].print_warning("\t " +
                                                                   perm + ": ")
                        main_settings.out[device_id].print_warning("\t\t" +
                                                                   desc)

                    report_apps[package]["permissions"] = dict()
                    report_apps[package]["permissions"] = {
                        "all_permissions": list(perms.keys()),
                        "dangerous_perms": dangerous_perms
                    }
                    report_apps[package]["is_device_admin"] = is_device_admin

                else:
                    main_settings.out[device_id].print_info(
                        "Package {} has no dangerous permissions".format(
                            package))

                if is_device_admin:
                    message = f"/!\ \t {package} is device admin \t /!\ "
                    padding = len(message)
                    main_settings.out[device_id].print_warning("-" * padding)
                    main_settings.out[device_id].print_warning(message)
                    main_settings.out[device_id].print_warning("-" * padding)

                    report_apps[package] = {"device_admin": is_device_admin}

                    if main_settings.rm_admin_recv:
                        removed, dpm = app.remove_device_admin_for_app()
                        if removed:
                            main_settings.out[device_id][package] = {
                                "device_admin_revoked": True
                            }
                            main_settings.out[device_id].print_info(
                                "Device admin receivers for {} removed\n".
                                format(app.package_name))
                        else:
                            main_settings.out[device_id].print_error(
                                "An error occured while removing the device admin "
                                + dpm + " .")

                # Revoke all Dangerous permissions
                if main_settings.revoke and app.dangerous_perms:
                    succeeded = app.revoke_dangerous_perms()

                    if succeeded:
                        report_apps[package][
                            "revoked_dangerous_pemissions"] = "succeeded"
                        main_settings.out[device_id].print_info(
                            "Dangerous permissions revoked\n")
                    else:
                        main_settings.out[device_id].print_error(
                            f"An error occured while revoking"
                            "permission {perm} to package {app.package_name}")

                elif main_settings.revoke and not app.dangerous_perms:
                    main_settings.out[device_id].print_info(
                        "No dangerous permissions granted for this package\n")

                main_settings.out[device_id].print_info(
                    "----------------------------MALWARE SCAN--------------------------------"
                )
                if app.score > 0:
                    main_settings.out[device_id].print_high_warning(
                        f'The application uses some permissions used also by malware. Percentage : {app.score}%'
                    )
                if app.malware_combination > 0:
                    main_settings.out[device_id].print_high_warning(
                        f'{str(app.malware_combination)} permissions '
                        f'combinations used also by malware')
                if app.malware_only_perms > 0:
                    main_settings.out[device_id].print_high_warning(
                        f'{str(app.malware_only_perms)} permissions '
                        f' used by malware only.')
                main_settings.out[device_id].print_info(
                    "-----------------------------------------------------------------------------\n"
                )
    except Exception as e:
        print(e)

    if main_settings.scan_applications:
        with open(f"{main_settings.output_dir}/{device_id}_report_apps.json",
                  'w') as fp:
            json.dump(report_apps, fp, indent=4)
        main_settings.out["std"].print_info(
            "Report generated: %s_report_apps.json" % device_id)

    return report_apps
Ejemplo n.º 20
0
def run():
    app = App()
    app.open()
Ejemplo n.º 21
0
"""

if __name__ == "__main__":
    import argparse
    import configparser

    from core.app import App
    from lastfm import LastFmLovedTracks, LastFmLibraryTracks
    from exfm import ExFmTracks
    # from grooveshark import GrooveSharkTracks

    config = configparser.ConfigParser()
    config.read('config.ini')


    app = App()
    parser = argparse.ArgumentParser()

    parser.add_argument("-s", "--source", dest = "source", default = "loved", help="Last.fm track source")
    # parser.add_argument("-d", "--dest", dest = "dest", default = "exfm", help="Track destination: exfm. Default exfm")
    parser.add_argument("-l", "--limit", dest = "limit", default = None, help="Number of tracks to process")
    parser.add_argument("-r", "--resume", dest = "resume", default = True, help="Resume import from the same page.")
    args = parser.parse_args()

    source = args.source
    # dest = args.dest
    limit = args.limit
    resume = args.resume
    if source == "loved":
        app.collection_importer = LastFmLovedTracks
    elif source == "library":
Ejemplo n.º 22
0
# -*- coding:utf-8 -*-

from core.app import App

app = App()
app.run()

Ejemplo n.º 23
0
from core.hooks import create_or_update_session, set_session_cookie
from importlib import reload
import settings
from flask_admin import Admin

from models.vcb_card import VCBBank
from models.certificate_key import CertificateKey
from models.product import Product
from models.user import User
from models.user_group import UserGroup
from models.vpb_card import VPBBank

reload(sys)
mail = Mail()

app = App(__name__, template_folder='./webapp/templates', static_folder='./webapp/static')
app.config.from_object(settings)
db = MongoEngine(app)
mail.init_app(app)

toolbar = DebugToolbarExtension(app)

admin = Admin(app, template_mode='bootstrap3')
admin.add_view(ModelView(User, endpoint='Manage User'))
admin.add_view(ModelView(Product, endpoint='Manage Product'))
admin.add_view(ModelView(UserGroup, endpoint='User Group'))
admin.add_view(ModelView(VCBBank, endpoint='VCB Cards'))
admin.add_view(ModelView(VPBBank, endpoint='VPB Cards'))
admin.add_view(ModelView(CertificateKey, endpoint='Certificate Key'))

app.auto_register_blueprint()
Ejemplo n.º 24
0
def main():
    win = Tk()
    app = App(win)
    app.run()
Ejemplo n.º 25
0
def interactive_list_apps(adb_instance, device_id):
    main_settings.lock.acquire()
    if main_settings.app_type:
        packages = adb_instance.list_installed_packages(
            main_settings.app_type.value)
        if main_settings.app_type.value == 'e':
            print(
                "Uninstalling or disabling system Apps can break your system")

    print("List of installed packages on device %s: " % device_id)
    nbr_listed_apps = 0
    apps_choice_list = []
    for package in packages:
        if nbr_listed_apps < LIST_APPS_MAX_PRINT and \
                packages.index(package) < (len(packages) - 1):
            print("\t[" + str(packages.index(package) + 1) + "] " + package)
            nbr_listed_apps = nbr_listed_apps + 1
        else:
            if packages.index(package) == (len(packages) - 1):
                print("\t[" + str(packages.index(package) + 1) + "] " +
                      package)
            while True:
                choice = input(
                    "Select application(s) (separated by comma ','), 'c' to continue"
                    " listing apps and 'A' for actions menu: ")
                if choice == 'c':
                    nbr_listed_apps = 1
                    break

                if choice == 'A':
                    break

                else:
                    chosen_apps = choice.replace(" ", "").split(",")
                    for c in chosen_apps:
                        if c.isdigit() and (0 < int(c) < len(packages) + 1):
                            apps_choice_list = apps_choice_list + [c]

                        else:
                            print(f"option {c} does not exist")

            if choice == 'A':
                break

    if not len(apps_choice_list):
        print("No application selected")
        main_settings.lock.release()
        return

    while True:
        print("choose an action")
        print("\td: disable selected apps")
        print("\tu: uninstall selected apps")
        print("\ts: static analysis")
        print("\te: exit")
        print("")

        action = input("Action: ")
        action = action.replace(" ", "")

        if action == 'd' or action == 'u' or action == 'e':
            main_settings.lock.release()
            break
        elif action == 's':
            break
        else:
            print("ERROR: Invalid action")
            continue

    for id_app in apps_choice_list:
        if action == 'd':
            try:
                adb_instance.disable_app(packages[int(id_app) - 1])
                main_settings.out["std"].print_success(packages[int(id_app) -
                                                                1] +
                                                       " disabled")

            except Exception as e:
                main_settings.out["std"].print_error(
                    "An Error occurred while disabling " +
                    packages[int(id_app) - 1])

        elif action == 'u':
            try:
                adb_instance.uninstall_app(packages[int(id_app) - 1])
                main_settings.out["std"].print_success(packages[int(id_app) -
                                                                1] +
                                                       " uninstalled")

            except Exception as e:
                main_settings.out["std"].print_error(
                    "An Error occurred while uninstalling " +
                    packages[int(id_app) - 1])

        elif action == 's':
            # TO-DO: Do analysis in other thread and log in file/DB
            app = App(adb_instance,
                      packages[int(id_app) - 1],
                      dump_apk=True,
                      out_dir=main_settings.apks_dump_folder)
            main_settings.out["std"].print_info(
                f"Package {packages[int(id_app) - 1]}")
            package_info = app.static_analysis()
            print(package_info)
            main_settings.out["std"].print_info("\tMalware identification")

            for key, value in package_info["detected_malware"].items():
                if value > 0:
                    main_settings.out["std"].print_error("\t\t " + key + ": " +
                                                         str(value) +
                                                         " positives tests")
                else:
                    main_settings.out["std"].print_info("\t\t " + key + ": " +
                                                        str(value) +
                                                        " positive test")

            if package_info and package_info["packed_file"] and \
                    package_info["packed_file"][packages[int(id_app) - 1]].keys():

                main_settings.out["std"].print_info("\tPacked files")
                main_settings.out["std"].print_error(
                    f"The package {packages[int(id_app) - 1]} has another Application (APK) inside"
                )

                for file in package_info["packed_file"][packages[int(id_app) -
                                                                 1]]:
                    for perm in package_info["packed_file"][packages[
                            int(id_app) - 1]][file]:
                        main_settings.out["std"].print_error(
                            "\tDangerous Permission: " + perm)
        elif action == 'e':
            break

        main_settings.lock.release()
Ejemplo n.º 26
0
from modules.sentry import Sentry
from core.app import App
from dotenv import load_dotenv
from colorama import init
import sys
import signal
if __name__ == '__main__':
    print('loisproBot by @x1dan')
    load_dotenv()
    Sentry.init()
    init(convert=True)
    App.start()
Ejemplo n.º 27
0
Archivo: main.py Proyecto: bboczar/py
import sys

from config import configuration
from core.app import App
from PyQt5 import QtWidgets

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    explorer = App(configuration)
    explorer.show()
    explorer.run()
    sys.exit(app.exec_())
Ejemplo n.º 28
0
    # Set up server
    if passed_args.address:
        core.SERVER_ADDRESS = passed_args.address
    else:
        core.SERVER_ADDRESS = str(core.CONFIG['Server']['serverhost'])
    if passed_args.port:
        core.SERVER_PORT = passed_args.port
    else:
        core.SERVER_PORT = core.CONFIG['Server']['serverport']

    # mount and configure applications
    if core.CONFIG['Server']['customwebroot']:
        core.URL_BASE = core.CONFIG['Server']['customwebrootpath']

    root = cherrypy.tree.mount(App(),
                               u'{}/'.format(core.URL_BASE),
                               'core/conf_app.ini'
                               )
    cherrypy.tree.mount(api.API(),
                        u'{}/api'.format(core.URL_BASE),
                        'core/conf_api.ini'
                        )

    cherrypy.tree.mount(postprocessing.Postprocessing(),
                        u'{}/postprocessing'.format(core.URL_BASE),
                        'core/conf_postprocessing.ini'
                        )

    cherrypy.tree.mount(App.auth,
                        u'{}/auth'.format(core.URL_BASE),
Ejemplo n.º 29
0
 def setUp(self):
     self.app = App()
     self.app.load_config_file('sessions.yaml')
Ejemplo n.º 30
0
def main():
    app = App()
    app.run()
Ejemplo n.º 31
0
class PdfMasher(ApplicationBase):
    LOGO_NAME = 'logo'
    
    def __init__(self):
        ApplicationBase.__init__(self)
        self.prefs = Preferences()
        self.prefs.load()
        self.model = App(view=self)
        self._setupActions()
        self.mainWindow = MainWindow(app=self)
        self.aboutBox = AboutBox(self.mainWindow, self, withreg=False)
        self._progress = Progress(self.mainWindow)
        
        self.connect(self, SIGNAL('applicationFinishedLaunching()'), self.applicationFinishedLaunching)
        self.connect(QCoreApplication.instance(), SIGNAL('aboutToQuit()'), self.applicationWillTerminate)
        self._progress.finished.connect(self.jobFinished)
    
    #--- Public
    def askForRegCode(self):
        self.reg.ask_for_code()
    
    #--- Private
    def _setupActions(self):
        ACTIONS = [
            ('actionLoadProject', 'Ctrl+Shift+O', '', tr("Load Project"), self.model.load_project),
            ('actionSaveProject', 'Ctrl+S', '', tr("Save Project"), self.model.save_project),
            ('actionQuit', 'Ctrl+Q', '', tr("Quit"), self.quitTriggered),
            ('actionShowHelp', 'F1', '', tr("PdfMasher Help"), self.showHelpTriggered),
            ('actionAbout', '', '', tr("About PdfMasher"), self.showAboutBoxTriggered),
            ('actionCheckForUpdate', '', '', tr("Check for Update"), self.checkForUpdateTriggered),
            ('actionOpenDebugLog', '', '', tr("Open Debug Log"), self.openDebugLogTriggered),
        ]
        createActions(ACTIONS, self)
        
        if ISLINUX:
            self.actionCheckForUpdate.setVisible(False) # This only works on Windows
    
    #--- Event Handling
    def applicationFinishedLaunching(self):
        self.mainWindow.show()
    
    def applicationWillTerminate(self):
        self.prefs.save()
    
    def jobFinished(self, jobid):
        self.model._job_completed(jobid)
    
    def checkForUpdateTriggered(self):
        QProcess.execute('updater.exe', ['/checknow'])
    
    def openDebugLogTriggered(self):
        appdata = getAppData()
        debugLogPath = op.join(appdata, 'debug.log')
        url = QUrl.fromLocalFile(debugLogPath)
        QDesktopServices.openUrl(url)
    
    def quitTriggered(self):
        self.mainWindow.close()
    
    def showAboutBoxTriggered(self):
        self.aboutBox.show()
    
    def showHelpTriggered(self):
        url = QUrl.fromLocalFile(op.abspath(op.join(HELP_PATH, 'index.html')))
        QDesktopServices.openUrl(url)
    
    #--- model --> view
    @staticmethod
    def open_path(path):
        url = QUrl.fromLocalFile(path)
        QDesktopServices.openUrl(url)
    
    @staticmethod
    def reveal_path(path):
        PdfMasher.open_path(op.dirname(path))
    
    def open_url(self, url):
        url = QUrl(url)
        QDesktopServices.openUrl(url)
    
    def show_message(self, msg):
        QMessageBox.information(self.mainWindow, '', msg)
    
    def start_job(self, jobid, func, *args):
        title = JOBID2TITLE[jobid]
        try:
            j = self._progress.create_job()
            args = tuple([j] + list(args))
            self._progress.run(jobid, title, func, args=args)
        except job.JobInProgressError:
            msg = "A previous action is still hanging in there. You can't start a new one yet. Wait a few seconds, then try again."
            QMessageBox.information(self.mainWindow, "Action in progress", msg)
    
    def get_default(self, key):
        return self.prefs.get_value(key)
    
    def set_default(self, key, value):
        self.prefs.set_value(key, value)
    
    def query_load_path(self, prompt, allowed_exts):
        myfilters = ["{} file (*.{})".format(ext.upper(), ext) for ext in allowed_exts]
        files = ';;'.join(myfilters + ["All Files (*.*)"])
        return QFileDialog.getOpenFileName(self.mainWindow, prompt, '', files)
    
    def query_save_path(self, prompt, allowed_exts):
        myfilters = ["{} file (*.{})".format(ext.upper(), ext) for ext in allowed_exts]
        files = ';;'.join(myfilters + ["All Files (*.*)"])
        return QFileDialog.getSaveFileName(self.mainWindow, prompt, '', files)
Ejemplo n.º 32
0
"""
from grooveshark import GrooveSharkTrack, GrooveSharkTracks

if __name__ == "__main__":
    import argparse
    import configparser

    from core.app import App
    from lastfm import LastFmLovedTracks, LastFmLibraryTracks
    from exfm import ExFmTrack, ExFmTracks

    config = configparser.ConfigParser()
    config.read('config.ini')


    app = App()
    parser = argparse.ArgumentParser()

    parser.add_argument("-s", "--source", dest = "source", default = "loved", help="Last.fm track source")
    parser.add_argument("-d", "--dest", dest = "dest", default = "exfm", help="Track destination: exfm|grooveshark. Default exfm")
    parser.add_argument("-l", "--limit", dest = "limit", default = None, help="Number of tracks to process")
    args = parser.parse_args()

    source = args.source
    dest= args.dest
    limit = args.limit
    if source == "loved":
        app.collection_importer = LastFmLovedTracks
    elif source == "library":
        app.collection_importer = LastFmLibraryTracks
    else:
Ejemplo n.º 33
0
    # Set up server
    if passed_args.address:
        core.SERVER_ADDRESS = passed_args.address
    else:
        core.SERVER_ADDRESS = str(core.CONFIG['Server']['serverhost'])
    if passed_args.port:
        core.SERVER_PORT = passed_args.port
    else:
        core.SERVER_PORT = core.CONFIG['Server']['serverport']

    # mount and configure applications
    if core.CONFIG['Server']['customwebroot']:
        core.URL_BASE = core.CONFIG['Server']['customwebrootpath']

    root = cherrypy.tree.mount(App(), u'{}/'.format(core.URL_BASE),
                               'core/conf_app.ini')
    cherrypy.tree.mount(api.API(), u'{}/api'.format(core.URL_BASE),
                        'core/conf_api.ini')

    cherrypy.tree.mount(postprocessing.Postprocessing(),
                        u'{}/postprocessing'.format(core.URL_BASE),
                        'core/conf_postprocessing.ini')

    cherrypy.tree.mount(App.auth, u'{}/auth'.format(core.URL_BASE),
                        'core/conf_auth.ini')

    # if everything goes well so far, open the browser
    if passed_args.browser or core.CONFIG['Server']['launchbrowser']:
        webbrowser.open(u"http://{}:{}{}".format(core.SERVER_ADDRESS,
                                                 core.SERVER_PORT,
Ejemplo n.º 34
0
def process(device_id):
    adb_instance = ADB(adb_path, device_id)
    report_apps = dict()
    out = Out(filename=device_id + ".log")

    packages = []

    if app_type:
        packages = adb_instance.list_installed_packages(app_type.value)

    if adb_instance.check_pending_update():
        out.print_warning("%s: The system has a pending update!" % device_id)

    if scan_applications or dump_apks or list_apps:
        for package in packages:
            if not list_apps:
                out.print_info(package)

            report_apps[package] = dict()

            dumpsys_out = adb_instance.dumpsys(["package", package])
            perm_list = adb_instance.get_req_perms_dumpsys_package(dumpsys_out)
            app = App(adb_instance, package, scan_applications, dump_apks,
                      apks_dump_folder, perm_list)
            perms, dangerous_perms, is_device_admin, known_malware = app.check_app(
            )

            if known_malware:
                report_apps[package]["malware"] = True
                out.print_error("{} is known as malware".format(package))

            if scan_applications:
                if dangerous_perms is not None and dangerous_perms.items():
                    out.print_warning_header(
                        "Package {} has some dangerous permissions: ".format(
                            package))

                    for perm, desc in dangerous_perms.items():
                        out.print_warning("\t " + perm + ": ")
                        out.print_warning("\t\t" + desc)

                    report_apps[package]["permissions"] = dict()
                    report_apps[package]["permissions"] = {
                        "all_permissions": list(perms.keys()),
                        "dangerous_perms": dangerous_perms
                    }
                    report_apps[package]["is_device_admin"] = is_device_admin

                else:
                    out.print_info(
                        "Package {} has no dangerous permissions".format(
                            package))

                if is_device_admin:
                    message = f"/!\ \t {package} is device admin \t /!\ "
                    padding = len(message)
                    out.print_warning("-" * padding)
                    out.print_warning(message)
                    out.print_warning("-" * padding)

                    report_apps[package] = {"device_admin": is_device_admin}

                    if rm_admin_recv:
                        removed, dpm = app.remove_device_admin_for_app()
                        if removed:
                            report_apps[package] = {
                                "device_admin_revoked": True
                            }
                            out.print_info(
                                "Device admin receivers for {} removed\n".
                                format(app.package_name))
                        else:
                            out.print_error(
                                "An error occured while removing the device admin "
                                + dpm + " .")

                # Revoke all Dangerous permissions
                if revoke and app.dangerous_perms:

                    succeeded = app.revoke_dangerous_perms()

                    if succeeded:
                        report_apps[package][
                            "revoked_dangerous_pemissions"] = "succeeded"
                        out.print_info("Dangerous permissions revoked\n")
                    else:
                        out.print_error(
                            f"An error occured while revoking permission {perm} to package {app.package_name}"
                        )

                elif revoke and not app.dangerous_perms:
                    out.print_info(
                        "No dangerous permissions granted for this package\n")

                if app.malware_confidence > 0 or app.score < 0:
                    out.print_high_warning(
                        "----------------------------MALWARE SCAN--------------------------------"
                    )
                    out.print_high_warning(
                        "The application uses some permissions used also by malware"
                    )
                    if app.malware_confidence > 0:
                        out.print_high_warning(
                            str(app.malware_confidence) +
                            " permissions combinations used also by "
                            "malware")

                if app.score < 0:
                    out.print_high_warning(
                        "The application uses frequent malware permissions ")

        if scan_applications:
            with open(device_id + "_report_apps.json", 'w') as fp:
                json.dump(report_apps, fp, indent=4)

            out.print_info("Report generated: %s_report_apps.json" % device_id)

    if list_apps:
        lock.acquire()
        print("List of installed packages on device %s: " % device_id)
        nbr_listed_apps = 0
        apps_choice_list = []
        for package in packages:
            if nbr_listed_apps < LIST_APPS_MAX_PRINT and packages.index(
                    package) < (len(packages) - 1):
                print("\t[" + str(packages.index(package) + 1) + "] " +
                      package)
                nbr_listed_apps = nbr_listed_apps + 1
            else:
                choice = ''
                if packages.index(package) == (len(packages) - 1):
                    print("\t[" + str(packages.index(package) + 1) + "] " +
                          package)
                while True:
                    choice = input(
                        "Select application(s) (separated by comma ','), 'c' to continue"
                        " listing apps and 'A' for actions menu: ")
                    if choice == 'c':
                        nbr_listed_apps = 1
                        break

                    if choice == 'A':
                        break

                    else:
                        chosen_apps = choice.replace(" ", "").split(",")
                        for c in chosen_apps:
                            if c.isdigit() and (0 < int(c) <
                                                len(packages) + 1):
                                apps_choice_list = apps_choice_list + [c]

                            else:
                                print("option " + c + " does not exist")

                if choice == 'A':
                    break

        if app_type.value == 'e':
            print(
                "Uninstalling or disabling system Apps can break your system")

        while True:
            print("choose an action")
            print("\td: disable selected apps")
            print("\tu: uninstall selected apps")
            print("\tS: Static analysis")
            print("\ts: skip")
            print("")

            action = input("Action: ")
            action = action.replace(" ", "")

            if action == 'd' or action == 'u' or action == 's' or action == 'S':
                lock.release()
                break
            else:
                print("ERROR: Invalid action")
                continue

        for id_app in apps_choice_list:
            if action == 'd':
                try:
                    adb_instance.disable_app(packages[int(id_app) - 1])
                    out.print_success(packages[int(id_app) - 1] + " disabled")
                except Exception as e:
                    out.print_error("An Error occurred while disabling " +
                                    packages[int(id_app) - 1])

            elif action == 'u':
                try:
                    adb_instance.uninstall_app(packages[int(id_app) - 1])
                    out.print_success(packages[int(id_app) - 1] +
                                      " uninstalled")
                except Exception as e:
                    out.print_error("An Error occurred while uninstalling " +
                                    packages[int(id_app) - 1])

            elif action == "S":
                app = App(adb_instance,
                          packages[int(id_app) - 1],
                          dump_apk=True,
                          out_dir=apks_dump_folder)
                out.print_info("Package {}".format(packages[int(id_app) - 1]))
                package_info = app.static_analysis()
                out.print_info("\tMalware identification")

                for key, value in package_info["detected_malware"].items():
                    if value > 0:
                        out.print_error("\t\t " + key + ": " + str(value) +
                                        " positives tests")
                    else:
                        out.print_info("\t\t " + key + ": " + str(value) +
                                       " positive test")

                if package_info and package_info["packed_file"] and \
                        package_info["packed_file"][packages[int(id_app) - 1]].keys():

                    out.print_info("\tPacked files")
                    out.print_error(
                        "The package {} has another Application (APK) inside".
                        format(packages[int(id_app) - 1]))

                    for file in package_info["packed_file"][packages[
                            int(id_app) - 1]]:
                        for perm in package_info["packed_file"][packages[
                                int(id_app) - 1]][file]:
                            out.print_error("\tDangerous Permission: " + perm)

            elif action == 's':
                break

    if harden:
        settings_check = Settings(SETTINGS_FILE, adb_instance, True, out=out)
    else:
        settings_check = Settings(SETTINGS_FILE, adb_instance, out=out)

    if scan_settings:
        settings_check.check()

    if list_processes:
        lock.acquire()
        process_choice_list = []
        current_processes = adb_instance.list_backgroud_apps().split("\n")
        print("Current running user processes on the device %s" % device_id)

        for i in range(0, len(current_processes) - 1):
            print("   {}- {}".format(i + 1, current_processes[i]))

        print("")
        choice = input(
            "Select id(s) of process(es) to kill (separated by comma ','): ")
        chosen_processes = choice.replace(" ", "").split(",")
        for c in chosen_processes:
            if c.isdigit() and (0 < int(c) < len(current_processes) + 1):
                process_choice_list = process_choice_list + [c]
                lock.release()
            else:
                print("[X] ERROR: process does not exist")
                print("Exiting device %s" % device_id)

        for process in process_choice_list:
            adb_instance.force_stop_app(current_processes[int(process) - 1])

    if snapshot:
        with lock:
            input("Unlock device %s and press ENTER key to continue" %
                  device_id)

        # set stay_awake to 1
        adb_instance.content_insert_settings("global",
                                             "stay_on_while_plugged_in", "1",
                                             "i")

        out.print_info("Starting snapshot")
        if not os.path.isdir(snapshot_dir):
            os.makedirs(snapshot_dir)

        snapshot_path = snapshot_dir + "/" + device_id + str(
            datetime.now()).replace(" ", "_")
        if not os.path.isdir(snapshot_path):
            os.makedirs(snapshot_path)

        if app_type:
            snapshot_obj = Snapshot(adb_instance,
                                    app_type.value,
                                    out_dir=snapshot_path)
        else:
            snapshot_obj = Snapshot(adb_instance, out_dir=snapshot_path)
        report = snapshot_obj.get_report()

        with open(snapshot_path + "/snapshot.json", 'w') as fp:
            json.dump(report, fp, indent=4)

        adb_instance.content_insert_settings("global",
                                             "stay_on_while_plugged_in", "0",
                                             "i")
        out.print_info("Snapshot finished")
Ejemplo n.º 35
0
class TestApp(unittest.TestCase):
    """docstring for TestApp"""
    def setUp(self):
        #setUp before each test
        self.app = App('test/test_app')
        self.app.new()
        self.app.load()

    def tearDown(self):
        # tearDown after each test
        shutil.rmtree('test/test_app')

    def test_load(self):
        self.assertEqual(self.app.config['app']['name'], 'app name')
        # print app.config

    def test_new(self):
        #done in setUP
        pass

    def test_setParameters(self):
        self.app.parameters['Inputs']['bam']={'data': [{"name":"/path/to/data1"}, {"name":"/path/to/data2"}]}
        self.app.setParameters()
        self.assertEqual(self.app['inputs']['bam'][0].path, "/path/to/data1")
        self.assertEqual(self.app['outputs']['results'][0].path, "/var/data/80bad55acc41d5fde324415808d0a700.tgz")
        #try setParameters ater newParameters
        self.app.newParameters('test/test_app/test_parameter.yaml')
        self.app.parameters['Parameters']['workspace']['value'] = '/path/to/data3'
        self.app.setParameters()
        self.assertEqual(self.app['parameters']['workspace'].__str__(), '/path/to/data3')

    def test_newParameters(self):
        self.app.newParameters()
        self.app.newParameters('test/test_app/test_parameter.yaml')
        self.app.newParameters()
        # print self.app.parameters

    def test_newParameters_after_setParameters(self):
        self.app.setParameters()
        self.app.newParameters('test/test_app/test_parameter.yaml')

    def test_newParameters_before_setParameters(self):
        self.app.newParameters('test/test_app/test_parameter.yaml')
        self.app.setParameters()

    def test_newParameters_and_setParameters_more(self):
        self.app.newParameters('test/test_app/test_parameter.yaml')
        self.app.setParameters()
        self.app.newParameters('test/test_app/test_parameter.yaml')
        self.app.setParameters()

    def test_newParameters_and_setParameters_more2(self):
        self.app.setParameters()
        self.app.newParameters('test/test_app/test_parameter.yaml')
        self.app.setParameters()
        self.app.newParameters('test/test_app/test_parameter.yaml')

    def test_loadParameters(self):
        self.app.newParameters('test/test_app/test_parameter.yaml')
        self.app.loadParameters('test/test_app/test_parameter.yaml')

    def test_loadParameters_None(self):
        self.assertRaises(ValueError, self.app.loadParameters)

    def test_nodes(self):
        load_case = {'bam': {'alias': 'load bam', 'node_id': 'loaddata_bam', 'name': 'loaddata', 'parameters': None, 'inputs': None, 'outputs': {'data': {'enid': 'bam'}}, 'type': 'system', 'app_id': '55128c58f6f4067d63b956b5'}}
        self.assertEqual(cmp(self.app.nodes('load'), load_case), 0)
        store_case = {'results': {'alias': 'store results', 'node_id': 'storedata_results', 'name': 'storedata', 'parameters': {'description': {'variable': True, 'value': None}, 'name': {'variable': True, 'value': None}}, 'inputs': {'data': {'enid': 'results'}}, 'outputs': None, 'type': 'system', 'app_id': '55128c94f6f4067d63b956b6'}}
        self.assertEqual(cmp(self.app.nodes('store'), store_case), 0)
        app_case = {'app name': {'inputs': {'bam': [{'enid': 'bam'}]}, 'name': 'app name', 'parameters': {'workspace': {'variable': False, 'value': None}, 'is_genedock': {'variable': False, 'value': None}}, 'outputs': {'results': [{'enid': 'results'}]}, 'app_id': '', 'alias': 'app name', 'node_id': 'app_name', 'type': 'private'}}
        self.assertEqual(cmp(self.app.nodes('app'), app_case), 0)

    def test_workflow(self):
        self.app.buildTestWorkflow()
        test_case = {'workflow': {'account': '*****@*****.**', 'version': 1, 'nodelist': [{'alias': 'load bam', 'node_id': 'loaddata_bam', 'name': 'loaddata', 'parameters': None, 'inputs': None, 'outputs': {'data': {'enid': 'bam'}}, 'type': 'system', 'app_id': '55128c58f6f4067d63b956b5'}, {'inputs': {'bam': [{'enid': 'bam'}]}, 'name': 'app name', 'parameters': {'workspace': {'variable': False, 'value': None}, 'is_genedock': {'variable': False, 'value': None}}, 'outputs': {'results': [{'enid': 'results'}]}, 'app_id': '', 'alias': 'app name', 'node_id': 'app_name', 'type': 'private'}, {'alias': 'store results', 'node_id': 'storedata_results', 'name': 'storedata', 'parameters': {'description': {'variable': True, 'value': None}, 'name': {'variable': True, 'value': None}}, 'inputs': {'data': {'enid': 'results'}}, 'outputs': None, 'type': 'system', 'app_id': '55128c94f6f4067d63b956b6'}], 'name': 'test_app name', 'description': 'test_app name'}}
        self.assertEqual(cmp(self.app.workflow, test_case), 0)

    def test_renderScript(self):
        self.app.newParameters()
        self.app.parameters['Parameters']['is_genedock']['value']=True
        self.app.config['app']['outputs']=None
        self.app.setParameters()
        self.app.renderScript()
        # print [self.app.script]
        self.assertEqual(self.app.script, u'\nmkdir -p /data/project/id;\n\nln -s /var/data/540ef712ea55aa2db8a4cfea4782c74d.bam /data/project/id/samplename.bam;\n\n')

    def test_build(self):
        test_case = u'\nmkdir -p /data/project/id;\n\nln -s /var/data/540ef712ea55aa2db8a4cfea4782c74d.bam /data/project/id/samplename.bam;\n\n'
        self.app.build(None, '/dev/null')
        self.assertEqual(self.app.script, test_case)
        self.app.newParameters('test/test_app/test_parameter.yaml')
        self.app.build('test/test_app/test_parameter.yaml', '/dev/null')
        self.assertEqual(self.app.script, test_case)

    def test_dumpYaml(self):
        self.app.setParameters()
        self.app.renderScript()
Ejemplo n.º 36
0
def run():
    app = App()
    app.open()
Ejemplo n.º 37
0
import os
from flask import Flask
from core.app import App
from core.utils import auto_import_module

# os.environ['JAVA_HOME'] = 'C:\Program Files\Java\jdk1.8.0_251'
# os.environ['JAVA_HOME'] = '/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands'
# os.environ['PYSPARK_PYTHON'] = '/Library/Frameworks/Python.framework/Versions/3.7'
os.environ['PYSPARK_PYTHON'] = '/usr/local/bin/python3.7'
os.environ['HADOOP_USER_NAME'] = 'hadoop'
# os.environ['HADOOP_CONF_DIR'] = '/usr/local/hadoop/etc/hadoop'
# os.environ['HADOOP_CLASSPATH'] = '/usr/local/hadoop:/usr/local/hbase/lib/*'

app = Flask(__name__)

# 这里放每个应用的视图包,自动加载,主要用于自定路径路由注册
auto_import_module('scheduler')  # view包,业务代码写到此包中

BASE_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "owlai")

# test develop production
env = os.getenv('FLASK_ENV') if not os.getenv('FLASK_ENV') else "test"
App(BASE_DIR).run(env)

if __name__ == '__main__':
    app.run()


Ejemplo n.º 38
0
 def setUp(self):
     #setUp before each test
     self.app = App('test/test_app')
     self.app.new()
     self.app.load()
Ejemplo n.º 39
0
    if passed_args.address:
        core.SERVER_ADDRESS = passed_args.address
    else:
        core.SERVER_ADDRESS = str(core.CONFIG['Server']['serverhost'])
    if passed_args.port:
        core.SERVER_PORT = passed_args.port
    else:
        core.SERVER_PORT = core.CONFIG['Server']['serverport']

    # mount and configure applications
    if core.CONFIG['Server']['customwebroot']:
        core.URL_BASE = core.CONFIG['Server']['customwebrootpath']

    core.SERVER_URL = 'http://{}:{}{}'.format(core.SERVER_ADDRESS, core.SERVER_PORT, core.URL_BASE)

    root = cherrypy.tree.mount(App(), '{}/'.format(core.URL_BASE), 'core/conf_app.ini')

    # Start plugins
    if passed_args.daemon:
        if core.PLATFORM == '*nix':
            Daemonizer(cherrypy.engine).subscribe()
        elif core.PLATFORM == 'windows':
            from cherrypysytray import SysTrayPlugin  # noqa
            menu_options = (('Open Browser', None, lambda *args: webbrowser.open(core.SERVER_URL)),)
            systrayplugin = SysTrayPlugin(cherrypy.engine, 'core/favicon.ico', 'Watcher', menu_options)
            systrayplugin.subscribe()
            systrayplugin.start()

    scheduler.create_plugin()

    if passed_args.pid:
Ejemplo n.º 40
0
#!/usr/bin/env python

from core.app import App

app = App()

app.load("test.sim")

app.run()