Beispiel #1
0
def check_opts(choice):
	""" Parse up the user input and run whatever commands
		are needed.
	"""
	if type(choice) is int: return choice
	elif 'info' in choice:
		Error('\'info\' not implemented yet.')
		choice = -1
	elif 'help' in choice:
		help()
		choice = -1
	elif 'set' in choice:
		opts = choice.split(' ')
		if opts[1] is None or opts[2] is None:
			return
		print '[!] Setting ' + color.YELLOW + '%s'%opts[1] + color.END + \
						'-> ' + color.GREEN + '%s..'%opts[2] + color.END
		config.set(opts[1], opts[2])
		choice = -1
	elif 'opts' in choice:
		config.dump()
		choice = -1
	elif 'quit' in choice or 'exit' in choice:
		# hard quit
		os._exit(1)
	elif 'bg' in choice:
		background()
	return choice
Beispiel #2
0
def create_emulator(options):
  name = options['name']
  target = options['sdk_version']
  config.set('emulator', name)
  p = Popen(['android', '-s', 'create', 'avd', '-n', name, '-f', '-t',  target], stdin=PIPE)
  print p.communicate(input='no\n')[0]
  print '> Created new emulator: -name ' + name + ' -sdk-version: ' + target  
Beispiel #3
0
def check_opts(choice):
    """ Parse up the user input and run whatever commands
        are needed.
    """
    choice_opts = choice.split(' ')
    if len(choice_opts) == 1:
        if type(choice) is int:
            return choice
        elif 'help' in choice:
            help()
            choice = -1
        elif 'gops' in choice:
            config.dump()
            choice = -1
        elif 'quit' in choice or 'exit' in choice:
            # hard quit
            os._exit(1)
        elif 'bg' in choice:
            background()
    else:
        if 'set' in choice_opts[0]:
            opts = choice.split(' ')
            if opts[1] is None or opts[2] is None:
                return
            print '[!] Setting ' + color.YELLOW + '%s' % opts[1] + color.END + \
                        '-> ' + color.GREEN + '%s..' % opts[2] + color.END
            config.set(opts[1], opts[2])
            choice = -1
    return choice
Beispiel #4
0
def credentials(save = None):
    clientId = config.get('clientId')
    clientSecret = config.get('clientSecret')
    if not clientId:
        clientId = DEFAULT_CLIENT_ID
        clientSecret = DEFAULT_CLIENT_SECRET

    refreshToken = config.get('refreshToken')
    if refreshToken:
        LOGGER.debug('Using stored refresh token...')

        return oauth2client.client.OAuth2Credentials(None, clientId,
                clientSecret, refreshToken, None,
                oauth2client.GOOGLE_TOKEN_URI, None)

    flow = oauth2client.client.OAuth2WebServerFlow(clientId, clientSecret,
            OAUTH_SCOPE, REDIRECT_URI,
            access_type = 'offline', approval_prompt = 'force')

    url = flow.step1_get_authorize_url()
    print 'Please open the following URL: '
    print url
    authorizationCode = raw_input('Copy and paste the authorization code: ').strip()

    LOGGER.debug('Requesting new refresh token...')
    credentials = flow.step2_exchange(authorizationCode)

    refreshToken = credentials.refresh_token
    print 'Refresh token: ' + refreshToken

    if utils.firstNonNone(save, False):
        config.set('refreshToken', refreshToken)
        config.save()

    return credentials
Beispiel #5
0
def settings():
    if request.method == 'POST':
        setting = request.form.get('setting')
        value = request.form.get('value_0')
        # strip whitespaces
        value = value.replace(' ', '')
        if not setting or not value:
            abort(400)
        
        if setting not in config.options():
            abort(400)

        config.set(setting, value)
        return redirect(url_for('admin_settings'))

    # load settings
    setting_list = [
        'facebook_integration', 'facebook_app_id', 'facebook_app_secret',
        'feedback_address', 'imprint_uri', 'account_activation',
        'posts_per_page', 'templates', 'default_template', 'debug',
        'setup', 'file_extensions', 'max_file_size', 'registration',
        'posts_per_page_options', 'upload_destination'
    ]
    settings = {}
    for setting in setting_list:
        settings[setting] = config.get(setting)

    return render_template('admin/settings.html', settings=settings)
Beispiel #6
0
 def onOK(self, event):
     for key in self.sliderOptions:
         config.set(key, self.sliderOptions[key].GetValue())
     for key in self.checkOptions:
         config.set(key, self.checkOptions[key].GetValue())
     for key in self.colorOptions:
         config.setColor(key, self.colorOptions[key].GetBackgroundColour())
     self.Destroy()
Beispiel #7
0
def opsmgr_install(stack):
	params = {
		"ignore_warnings": "true"
	}
	install = json.load(opsmgr_post(stack, "/api/installation", urllib.urlencode(params)))
	install_id = str(install["install"]["id"])
	config.set("stack-" + stack["StackName"], "opsmgr-install", install_id)
	return install_id
Beispiel #8
0
 def test_rejects_expired_token(self):
     """Tests that an expired token is rejected."""
     config.set(xsrf_token_key='abcdef')
     tool = utils.XsrfTool()
     token = tool.generate_token(12345, 'test_action')
     utils.set_utcnow_for_test(XsrfToolTests.TEST_NOW +
                               datetime.timedelta(hours=4, minutes=1))
     self.assertFalse(tool.verify_token(token, 12345, 'test_action'))
Beispiel #9
0
    def onJoinedRaid(self):
        self.keyJoinButton.SetLabel("Leave Raid")
        self.keyJoinButton.Enable()
        self.keyStatus.SetLabel("")

        self.addToConsole("Joined raid.")

        config.set("lastRaidKey", self.keyBox.GetValue())
def toggle_fs():
    flags = 0
    fs = config.getboolean("settings", "fullscreen") ^ True
    if "linux" not in sys.platform:
        if fs: flags ^= FULLSCREEN
        pygame.display.set_mode([800, 600], flags)
    else: pygame.display._toggle_fullscreen()
    config.set("settings", "fullscreen", str(fs))
    def test_analytics_id(self):
        """Checks that the analytics_id config is used for analytics."""
        doc = self.go('/haiti/create')
        assert 'getTracker(' not in doc.content

        config.set(analytics_id='analytics_id_xyz')

        doc = self.go('/haiti/create')
        assert "getTracker('analytics_id_xyz')" in doc.content
Beispiel #12
0
    def onSetEnrageTime(self, event):
        dialog = wx.TextEntryDialog(self, "Set enrage timer (seconds)", "Enrage Timer", "0.0")

        enrageTime = config.get("customEnrageTime")
        if enrageTime:
            dialog.SetValue(enrageTime)

        if dialog.ShowModal():
            config.set("customEnrageTime", dialog.GetValue())
Beispiel #13
0
def build_occplug():
	header("BUILDING OCCPLUG")
	config.refresh() 
	config.rebase('TEMP', '@TEMP_ROOT@/occPlug')
	remove_dir(config.get('TEMP'))

	src_ext = '/tools/occplug' 
	dist_ext = '/distribution/deb-pkg'

	#srcpath = concat([config.get('TEMP'), '/src', src_ext])
	#mkdir(srcpath)
	
	#distpath = concat([config.get('TEMP'), '/src', dist_ext])
	#mkdir(distpath)
	config.set('OCCPLUG_DISTRIBUTION', 
						concat([config.get('SVN'), dist_ext]))

	#config.rebase('SOURCE_OCCPLUG', srcpath)

	make_destdirs()
	remove_dir(concat([config.get('TEMP'), '/', config.get('PACKAGE_NAME')]))

	# remove_and_create_dir(config.get('TEMP'))
	# remove_and_create_dir(config.get('DEST_OCCPLUG'))	

	print 'SOURCE OCCPLUG: %s' % config.get('SOURCE_OCCPLUG')

	#checkout_to(concat([config.get('SVN_TRUNK'), src_ext]), config.get('SOURCE_OCCPLUG'))
	#checkout_to(concat([config.get('SVN_TRUNK'), dist_ext]), distpath)

	zipfile = 'ErrorList-1.9-bin.zip'
	jarfile = 'ErrorList.jar'

	with pushd():
		cd(config.get('SOURCE_OCCPLUG'))
		cmd(build_command(['wget', config.get('ERRORLIST_URL')]))
		unzip_file_into_dir(zipfile, config.get('DEST_OCCPLUG_JARS'))
	
		# Move the ErrorList straight to the destination; we can build against it there.
		#cmd(build_command(['mv', jarfile, config.get('DEST_OCCPLUG')]))
		cmd(build_command(['ant', 
											'-Djedit.install.dir=/usr/share/jedit', 
											concat(['-Dinstall.dir=', config.get('DEST_OCCPLUG_JARS')]),
											concat(['-Dbuild.dir=', config.get('TEMP')]),
											concat(['-lib ', config.get('DEST_OCCPLUG_JARS')])  ]))	

	# Insert the ubuntu.props file into the .jar
	with pushd():
		cd(config.get('OCCPLUG_DISTRIBUTION'))

		cmd(build_command([
				'jar -uf', 
				concat([config.get('DEST_OCCPLUG_JARS'), '/', 'OccPlug.jar']),
				'ubuntu.props'
				]))
	
	config.set('BUILD_ARCHITECTURE', 'all')
Beispiel #14
0
 def test_rejects_invalid_tokens(self):
     """Tests that an invalid token is rejected."""
     config.set(xsrf_token_key='abcdef')
     tool = utils.XsrfTool()
     self.assertFalse(tool.verify_token(
         'ThisTokenDoesNotEvenHaveASlash', 12345, 'test_action'))
     timestamp = utils.get_timestamp(XsrfToolTests.TEST_NOW)
     self.assertFalse(
         tool.verify_token('NotTheRightDigest/%f' % timestamp, 12345,
                           'test_action'))
Beispiel #15
0
    def test_clean_up_in_test_mode_multi_tasks(self):
        """Test the clean up in test mode when it is broken into multiple
        tasks."""

        class Listener(object):
            def before_deletion(self, person):
                # This will be implemented later using mock.
                assert False

        tasks.CleanUpInTestMode.DELETION_AGE_SECONDS = 2 * 3600  # 2 hours
        utcnow = datetime.datetime(2010, 1, 1, 7, 0, 0)
        set_utcnow_for_test(utcnow)
        self.mox = mox.Mox()
        cleanup = \
            test_handler.initialize_handler(tasks.CleanUpInTestMode,
                                            tasks.CleanUpInTestMode.ACTION)
        listener = Listener()
        cleanup.set_listener(listener)

        # Simulates add_task_for_repo() because it doesn't work in unit tests.
        def add_task_for_repo(repo, task_name, action, **kwargs):
            cleanup = test_handler.initialize_handler(
                tasks.CleanUpInTestMode, action, repo=repo, params=kwargs)
            cleanup.set_listener(listener)
            cleanup.get()

        self.mox.StubOutWithMock(cleanup, 'add_task_for_repo')
        (cleanup.add_task_for_repo(
                'haiti',
                mox.IsA(str),
                mox.IsA(str),
                utcnow=str(calendar.timegm(utcnow.utctimetuple())),
                cursor=mox.IsA(str),
                queue_name=mox.IsA(str)).
            WithSideEffects(add_task_for_repo).MultipleTimes())

        def raise_deadline_exceeded_error(_):
            raise runtime.DeadlineExceededError()

        self.mox.StubOutWithMock(listener, 'before_deletion')
        listener.before_deletion(self.key_p1)
        listener.before_deletion(self.key_p2).WithSideEffects(
            raise_deadline_exceeded_error)
        listener.before_deletion(self.key_p2)

        self.mox.ReplayAll()

        config.set(test_mode=True, repo='haiti')
        # This should run multiple tasks and finally deletes all records.
        cleanup.get()
        assert db.get(self.key_p1) is None
        assert db.get(self.key_p2) is None

        self.mox.UnsetStubs()
        self.mox.VerifyAll()
Beispiel #16
0
def check_new_machine():

    current_path = os.path.dirname(os.path.abspath(__file__))
    if current_path != config.get(["update", "last_path"], ""):
        config.set(["update", "last_path"], current_path)
        config.save()

        if sys.platform == "win32" and platform.release() == "XP":
            notify_install_tcpz_for_winXp()

        logging.info("generate desktop shortcut")
        create_desktop_shortcut()
Beispiel #17
0
def check_new_machine():

    current_path = os.path.dirname(os.path.abspath(__file__))
    if current_path != config.get(["update", "last_path"], ""):
        config.set(["update", "last_path"], current_path)
        config.save()

        if sys.platform == "win32" and platform.release() == "XP":
            notify_install_tcpz_for_winXp()

        xlog.info("generate desktop shortcut")
        create_desktop_shortcut()
Beispiel #18
0
 def OnVolumeSlider(self, event):
     config.set('Sounds', 'Volume', self.volumeSlider.Value)
     with self.client.sounds.cache_lock:
         # Volume didn't change
         if self.client.sounds.volume == self.volumeSlider.Value:
             return
         self.client.sounds.volume = self.volumeSlider.Value
         playpacket = PlaySound()
         playpacket.steamid = 0
         playpacket.sound_hash = self.client.sounds.get_random(
             GameEvent.HEADSHOT, None)
     self.client.sounds.play(playpacket)
Beispiel #19
0
    def test_good_with_no_prior_key(self):
        """Tests a good token when a token key has to be autogenerated.

        If the config doesn't already have an XSRF token key set, the XSRF tool
        will generate one automatically.
        """
        # config seems to be shared across tests, so we have to specifically set
        # it to None.
        config.set(xsrf_token_key=None)
        tool = utils.XsrfTool()
        token = tool.generate_token(12345, 'test_action')
        self.assertTrue(tool.verify_token(token, 12345, 'test_action'))
Beispiel #20
0
def main():
    # change path to launcher
    global __file__
    __file__ = os.path.abspath(__file__)
    if os.path.islink(__file__):
        __file__ = getattr(os, 'readlink', lambda x: x)(__file__)
    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    current_version = update_from_github.current_version()

    xlog.info("start XX-Net %s", current_version)

    web_control.confirm_xxnet_exit()

    setup_win_python.check_setup()

    last_run_version = config.get(["modules", "launcher", "last_run_version"],
                                  "0.0.0")
    if last_run_version != current_version:
        import post_update
        post_update.run(last_run_version)
        config.set(["modules", "launcher", "last_run_version"],
                   current_version)
        config.save()

    allow_remote = 0
    if len(sys.argv) > 1:
        for s in sys.argv[1:]:
            xlog.info("command args:%s", s)
            if s == "-allow_remote":
                allow_remote = 1
                module_init.xargs["allow_remote"] = 1

    module_init.start_all_auto()
    web_control.start(allow_remote)

    if has_desktop and config.get(["modules", "launcher", "popup_webui"],
                                  1) == 1:
        host_port = config.get(["modules", "launcher", "control_port"], 8085)
        import webbrowser
        webbrowser.open("http://127.0.0.1:%s/" % host_port)

    update.start()

    if config.get(["modules", "launcher", "show_systray"], 1):
        sys_tray.serve_forever()
    else:
        while True:
            time.sleep(100)

    module_init.stop_all()
    sys.exit()
Beispiel #21
0
def set_by_key(key):
    """Overwrite/set only 1 config key"""
    """
    {
        'data': data
    }
    """
    try:
        data = json.loads(bytes_to_str(request.data))
    except (JSONDecodeError, KeyError):
        abort(400)
    config.set(key, data, True)
    return Response('success')
Beispiel #22
0
 def test_content_security_policy_for_react(self):
     """Verify CSP is set when the React UI is enabled."""
     config.set(enable_react_ui=True)
     request = setup_request('/')
     response = webapp.Response()
     handler = main.Main(request, response)
     with patch('utils.generate_random_key') as generate_random_key_mock:
         generate_random_key_mock.return_value = 'totallyrandomkey'
         handler.get()
         assert 'Content-Security-Policy' in response.headers
         assert ('nonce-totallyrandomkey' in
                 response.headers['Content-Security-Policy'])
         assert 'nonce="totallyrandomkey"' in response.body
 def test_content_security_policy_for_react(self):
     """Verify CSP is set when the React UI is enabled."""
     config.set(enable_react_ui=True)
     request = setup_request('/')
     response = webapp.Response()
     handler = main.Main(request, response)
     with patch('utils.generate_random_key') as generate_random_key_mock:
         generate_random_key_mock.return_value = 'totallyrandomkey'
         handler.get()
         assert 'Content-Security-Policy' in response.headers
         assert ('nonce-totallyrandomkey'
                 in response.headers['Content-Security-Policy'])
         assert 'nonce="totallyrandomkey"' in response.body
Beispiel #24
0
    def test_should_notify(self):
        # If email is empty, always False is returned.
        config.set(notification_email='', unreviewed_notes_threshold=9)
        self.assert_(not self.handler._should_notify(10))

        config.set(notification_email='*****@*****.**',
                   unreviewed_notes_threshold=100)
        # The number of unreviewed_notes larger than threshold: True
        self.assert_(self.handler._should_notify(101))
        # The number of unreviewed_notes is equal to threshold: False
        self.assert_(not self.handler._should_notify(100))
        # The number of unreviewed_notes is smaller than threshold: False
        self.assert_(not self.handler._should_notify(99))
Beispiel #25
0
def main():
    # change path to launcher
    global __file__
    __file__ = os.path.abspath(__file__)
    if os.path.islink(__file__):
        __file__ = getattr(os, 'readlink', lambda x: x)(__file__)
    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    current_version = update_from_github.current_version()

    xlog.info("start XX-Net %s", current_version)

    web_control.confirm_xxnet_exit()

    setup_win_python.check_setup()

    last_run_version = config.get(["modules", "launcher", "last_run_version"], "0.0.0")
    if last_run_version != current_version:
        import post_update
        post_update.run(last_run_version)
        config.set(["modules", "launcher", "last_run_version"], current_version)
        config.save()

    allow_remote = 0
    if len(sys.argv) > 1:
        for s in sys.argv[1:]:
            xlog.info("command args:%s", s)
            if s == "-allow_remote":
                allow_remote = 1
                module_init.xargs["allow_remote"] = 1

    module_init.start_all_auto()
    web_control.start(allow_remote)

    if has_desktop and config.get(["modules", "launcher", "popup_webui"], 1) == 1:
        host_port = config.get(["modules", "launcher", "control_port"], 8085)
        import webbrowser
        webbrowser.open("http://127.0.0.1:%s/" % host_port)

    update.start()

    update_from_github.delete_to_save_disk()
    
    if config.get(["modules", "launcher", "show_systray"], 1):
        sys_tray.serve_forever()
    else:
        while True:
            time.sleep(100)

    module_init.stop_all()
    sys.exit()
Beispiel #26
0
def print_menu(arr):
    global buffered
    """Main menu printer
	   @param arr is the menu array to print.  Fetches input, 
		parses and built-in command keywords, and returns the selected idx.
	"""

    if not buffered is None:
        # buffered input, return
        if len(buffered) > 0:
            return buffered.pop(0)
        else:
            buffered = None

    tmp = Cmd()
    arr = ['\t[%d] %s' % (x + 1, arr[x]) for x in xrange(len(arr))]
    tmp.columnize(arr, 35)
    print '\n0) Back'
    try:
        choice = raw_input('> ')
        if 'info' in choice:
            Error('\'info\' not implemented yet.')
            choice = -1
        elif 'set' in choice:
            opts = choice.split(' ')
            if opts[1] is None or opts[2] is None:
                return
            print '[!] Setting \033[33m%s\033[0m -> \033[32m%s\033[0m..' % (
                opts[1], opts[2])
            config.set(opts[1], opts[2])
            choice = -1
        elif 'opts' in choice:
            config.dump()
            choice = -1
        elif 'quit' in choice or 'exit' in choice:
            # hard quit
            os._exit(1)
        elif 'bg' in choice:
            background()
        else:
            # buffered input
            choice = choice.split(' ')
            if len(choice) > 1:
                buffered = []
                for entry in choice[1:]:
                    buffered.append(int(entry))
            choice = int(choice[0])
    except Exception:
        os.system('clear')
        choice = -1
    return choice
Beispiel #27
0
    def req_config_handler(self):
        req = urlparse.urlparse(self.path).query
        reqs = urlparse.parse_qs(req, keep_blank_values=True)
        data = ''

        if reqs['cmd'] == ['get_config']:
            config.load()
            data = '{ "check_update": "%d", "popup_webui": %d, "auto_start": %d }' %\
                   (config.get(["update", "check_update"], 1)
                    , config.get(["modules", "launcher", "popup_webui"], 1)
                    , config.get(["modules", "launcher", "auto_start"], 0))
        elif reqs['cmd'] == ['set_config']:
            if 'check_update' in reqs:
                check_update = int(reqs['check_update'][0])
                if check_update != 0 and check_update != 1:
                    data = '{"res":"fail, check_update:%s"}' % check_update
                else:
                    config.config["update"]["check_update"] = int(check_update)
                    config.save()

                    data = '{"res":"success"}'

            elif 'popup_webui' in reqs:
                popup_webui = int(reqs['popup_webui'][0])
                if popup_webui != 0 and popup_webui != 1:
                    data = '{"res":"fail, popup_webui:%s"}' % popup_webui
                else:
                    config.set(["modules", "launcher", "popup_webui"],
                               popup_webui)
                    config.save()

                    data = '{"res":"success"}'
            elif 'auto_start' in reqs:
                auto_start = int(reqs['auto_start'][0])
                if auto_start != 0 and auto_start != 1:
                    data = '{"res":"fail, auto_start:%s"}' % auto_start
                else:
                    if auto_start:
                        autorun.enable()
                    else:
                        autorun.disable()

                    config.set(["modules", "launcher", "auto_start"],
                               auto_start)
                    config.save()

                    data = '{"res":"success"}'
            else:
                data = '{"res":"fail"}'

        self.send_response('application/json', data)
Beispiel #28
0
    def test_bad_with_no_prior_key(self):
        """Tests a bad token when a token key has to be autogenerated.

        If the config doesn't already have an XSRF token key set, the XSRF tool
        will generate one automatically.
        """
        # config seems to be shared across tests, so we have to specifically set
        # it to None.
        config.set(xsrf_token_key=None)
        tool = utils.XsrfTool()
        timestamp = utils.get_timestamp(XsrfToolTests.TEST_NOW)
        self.assertFalse(
            tool.verify_token('NotTheRightDigest/%f' % timestamp, 12345,
                              'test_action'))
Beispiel #29
0
    def enableGlobalSmartRouter_(self, _):
        try:
            helperDisableAutoProxy(currentService)
            helperEnableSmartRouterProxy(currentService)
        except:
            disableAutoProxyCommand   = getDisableAutoProxyCommand(currentService)
            enableSmartRouterCommand  = getEnableSmartRouterProxyCommand(currentService)
            executeCommand            = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, enableSmartRouterCommand)

            xlog.info("try enable global smart-router proxy:%s", executeCommand)
            subprocess.call(['osascript', '-e', executeCommand])
        config.set(["modules", "launcher", "proxy"], "smart_router")
        config.save()
        self.updateStatusBarMenu()
Beispiel #30
0
def check():
    import update_from_github
    current_version = update_from_github.current_version()
    last_run_version = config.get(["modules", "launcher", "last_run_version"], "0.0.0")
    if last_run_version == "0.0.0":
        postUpdateStat = "isNew"
    elif last_run_version != current_version:
        postUpdateStat = "isPostUpdate"
        run(last_run_version)
    else:
        return
    config.set(["update", "postUpdateStat"], postUpdateStat)
    config.set(["modules", "launcher", "last_run_version"], current_version)
    config.save()
Beispiel #31
0
    def enableGlobalSmartRouter_(self, _):
        try:
            helperDisableAutoProxy(currentService)
            helperEnableSmartRouterProxy(currentService)
        except:
            disableAutoProxyCommand   = getDisableAutoProxyCommand(currentService)
            enableSmartRouterCommand  = getEnableSmartRouterProxyCommand(currentService)
            executeCommand            = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, enableSmartRouterCommand)

            xlog.info("try enable global smart-router proxy:%s", executeCommand)
            subprocess.call(['osascript', '-e', executeCommand])
        config.set(["modules", "launcher", "proxy"], "smart_router")
        config.save()
        self.updateStatusBarMenu()
Beispiel #32
0
def respawn_script(ble_thread=None):
    if ble_thread is not None:
        logger.info('Daily or on update re-spawn, stopping BLE thread...')
        blescan.is_running = False
        ble_thread.join()
        logger.info('BLE thread stopped.')

    logger.info('Restarting script...')
    config.set('DEVICE', 'last_respawn_date',
               datetime.now().strftime("%Y-%m-%d"))
    config.save()

    subprocess.call([config.HCICONFIG_FILE_PATH, 'hci0', 'down'])
    os.execv(config.BASE_APP_PATH + 'ivigilate.py', sys.argv)
Beispiel #33
0
 def disableProxy_(self, _):
     try:
         helperDisableAutoProxy(currentService)
         helperDisableGlobalProxy(currentService)
     except:
         disableAutoProxyCommand   = getDisableAutoProxyCommand(currentService)
         disableGlobalProxyCommand = getDisableGlobalProxyCommand(currentService)
         executeCommand            = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, disableGlobalProxyCommand)
         
         xlog.info("try disable proxy:%s", executeCommand)
         subprocess.call(['osascript', '-e', executeCommand])
     config.set(["modules", "launcher", "proxy"], "disable")
     config.save()
     self.updateStatusBarMenu()
Beispiel #34
0
def set_by_key(key):
    '''Overwrite/set only 1 config key'''
    '''
    {
        'data': data
    }
    '''
    try:
        data = json.loads(onionrutils.OnionrUtils.bytesToStr(
            request.data))['data']
    except (json.JSONDecodeError, KeyError):
        abort(400)
    config.set(key, data, True)
    return Response('success')
Beispiel #35
0
    def test_bad_with_no_prior_key(self):
        """Tests a bad token when a token key has to be autogenerated.

        If the config doesn't already have an XSRF token key set, the XSRF tool
        will generate one automatically.
        """
        # config seems to be shared across tests, so we have to specifically set
        # it to None.
        config.set(xsrf_token_key=None)
        tool = utils.XsrfTool()
        timestamp = utils.get_timestamp(XsrfToolTests.TEST_NOW)
        self.assertFalse(
            tool.verify_token('NotTheRightDigest/%f' % timestamp, 12345,
                              'test_action'))
Beispiel #36
0
def main(debug=False):
	""" Read the configuration file """
	config.init(CONFIGFILE)
	ltime = config.get('Run','time')
	ntime = now()
	if ltime is not None:
		print 'Last time was {}.'.format(ltime)
		otime = asc2time(ltime)
	else:
		print 'Never run before.'
		otime = ntime - 30*24*60*60
	print 'Current time is {}.'.format(time2asc(ntime))
	if ntime - otime < 86400:
		otime = (int(ntime/3600)-24)*3600
	print 'Reading since {}.'.format(time2asc(otime))

	""" Read the database """
	d = {'time': [ntime,otime], 'data': {}, 'keys': {}}
	with getdb() as db:
		d = db.run(d)

	""" Form the document """
	docfn = "{}_{}.pdf".format(
		config.get('Report','namebase','report'),
		time2fmt('%Y-%m-%d(%H)',ntime))
	print docfn
	#try:
	report(docfn,d)
	#except Exception, exc:
	#	config.close()
	#	raise exc

	""" Email the document """
	txt = EMAILMSG.format(
		config.get('Site','name'),
		time2esk(ntime),
		time2hms(ntime),
		time2esk(conf2time('Run','from',otime)),
		time2hms(conf2time('Run','from',otime)),
		time2esk(conf2time('Run','to',ntime)),
		time2hms(conf2time('Run','to',ntime))
		)
	if debug:
                emailer.nsend(txt)
        else:
        	emailer.send(txt,[docfn])

	""" Saving configuration """
	config.set('Run','time',time2asc(ntime))
	config.close()
Beispiel #37
0
def print_menu(arr):
	global buffered
	"""Main menu printer
	   @param arr is the menu array to print.  Fetches input, 
		parses and built-in command keywords, and returns the selected idx.
	"""

	if not buffered is None:
		# buffered input, return
		if len(buffered) > 0: 
			return buffered.pop(0)
		else:	
			buffered = None

	tmp = Cmd()
	arr = ['\t[%d] %s'%(x+1,arr[x]) for x in xrange(len(arr))] 
	tmp.columnize(arr,35)
	print '\n0) Back'
	try:
		choice = raw_input('> ')
		if 'info' in choice:
			Error('\'info\' not implemented yet.')
			choice = -1
		elif 'set' in choice:
			opts = choice.split(' ')
			if opts[1] is None or opts[2] is None:
				return
			print '[!] Setting \033[33m%s\033[0m -> \033[32m%s\033[0m..'%(opts[1], opts[2])
			config.set(opts[1], opts[2])
			choice = -1
		elif 'opts' in choice:
			config.dump()
			choice = -1
		elif 'quit' in choice or 'exit' in choice:
			# hard quit
			os._exit(1)
		elif 'bg' in choice:
			background()
		else:
			# buffered input
			choice = choice.split(' ')
			if len(choice) > 1: 
				buffered = []
				for entry in choice[1:]:
					buffered.append(int(entry))
			choice = int(choice[0])
	except Exception:
		os.system('clear')
		choice = -1
	return choice
Beispiel #38
0
 def test_get(self):
     """Tests GET requests."""
     # We set it to "really" ping index servers for the test. Since we're
     # also mocking out requests.get though, it won't really succeed in
     # pinging anything.
     config.set(ping_sitemap_indexers=True)
     with mock.patch('requests.get') as requests_mock:
         res = self.run_task('/global/tasks/sitemap_ping',
                             {'search_engine': 'google'})
         self.assertEqual(len(requests_mock.call_args_list), 1)
         call_args, _ = requests_mock.call_args_list[0]
         self.assertEqual(call_args[0],
                          ('https://www.google.com/ping?sitemap='
                           'https%3A//testserver/global/sitemap'))
Beispiel #39
0
def register(host):
    """Connect to a lambda edge network by providing the master host address"""

    # send CREATE connections to the master host
    r = requests.post(url=host + '/workers/')

    # if the connection is accepted, store the host information to ~/.ledge/config.yaml
    if r.status_code == 200:
        config.set('MASTER_HOST', host)
        print("Connected")
        print(config.get('MASTER_HOST'))
    # handle error
    else:
        print("Error: can't connect to the master host")
Beispiel #40
0
def save():
    output = ""
    output = output + render_template('header.html')
    #output = output+ '<div id="content">'
    output = output + "<h1>Saving new configuration...</h1>"

    additionalLightingDuration = request.args.get('additionalLightingDuration')
    checkSensorsInterval = request.args.get('checkSensorsInterval')
    criticalHumidity = request.args.get('criticalHumidity')
    criticalBrightness = request.args.get('criticalBrightness')

    if additionalLightingDuration and checkSensorsInterval and criticalHumidity and criticalBrightness:

        config = ConfigParser()
        config.read('userproperties.ini')
        config.set('IntelligenterBlumentopf', 'additionalLightingDuration',
                   additionalLightingDuration)
        config.set('IntelligenterBlumentopf', 'checkSensorsInterval',
                   checkSensorsInterval)
        config.set('IntelligenterBlumentopf', 'criticalHumidity',
                   criticalHumidity)
        config.set('IntelligenterBlumentopf', 'criticalBrightness',
                   criticalBrightness)
        with open('userproperties.ini', 'w') as configfile:
            config.write(configfile)

        output = output + "<p>Successful. Please reboot</p>"
        output = output + '<br><form method="get" action="/reboot"><button type="submit">Reboot!</button></form>'

    else:
        output = output + "<p>Failed: Configuration values are invalid.</p>"
    output = output + '</div></body></html>'
    return output
Beispiel #41
0
 def disableProxy_(self, _):
     try:
         helperDisableAutoProxy(currentService)
         helperDisableGlobalProxy(currentService)
     except:
         disableAutoProxyCommand   = getDisableAutoProxyCommand(currentService)
         disableGlobalProxyCommand = getDisableGlobalProxyCommand(currentService)
         executeCommand            = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, disableGlobalProxyCommand)
         
         xlog.info("try disable proxy:%s", executeCommand)
         subprocess.call(['osascript', '-e', executeCommand])
     config.set(["modules", "launcher", "proxy"], "disable")
     config.save()
     self.updateStatusBarMenu()
Beispiel #42
0
    def test_should_notify(self):
        # If email is empty, always False is returned.
        config.set(notification_email='',
                   unreviewed_notes_threshold=9)
        self.assert_(not self.handler._should_notify(10))

        config.set(notification_email='*****@*****.**',
                   unreviewed_notes_threshold=100)
        # The number of unreviewed_notes larger than threshold: True
        self.assert_(self.handler._should_notify(101))
        # The number of unreviewed_notes is equal to threshold: False
        self.assert_(not self.handler._should_notify(100))
        # The number of unreviewed_notes is smaller than threshold: False
        self.assert_(not self.handler._should_notify(99))
Beispiel #43
0
def setup_config():
    if not os.path.exists(config._configfile):
        # this is the default config, it will be overwritten if a config file already exists. Else, it saves it
        conf_data = readstatic.read_static('default_config.json', ret_bin=False)
        config.set_config(json.loads(conf_data))

        config.save()

    config.reload()

    settings = 0b000
    if config.get('log.console.color', True):
        settings = settings | USE_ANSI
    if config.get('log.console.output', True):
        settings = settings | OUTPUT_TO_CONSOLE
    if config.get('log.file.output', True):
        settings = settings | OUTPUT_TO_FILE
    set_settings(settings)

    verbosity = str(config.get('log.verbosity', 'default')).lower().strip()
    if not verbosity in ['default', 'null', 'none', 'nil']:
        map = {
            str(LEVEL_DEBUG) : LEVEL_DEBUG,
            'verbose' : LEVEL_DEBUG,
            'debug' : LEVEL_DEBUG,
            str(LEVEL_INFO) : LEVEL_INFO,
            'info' : LEVEL_INFO,
            'information' : LEVEL_INFO,
            str(LEVEL_WARN) : LEVEL_WARN,
            'warn' : LEVEL_WARN,
            'warning' : LEVEL_WARN,
            'warnings' : LEVEL_WARN,
            str(LEVEL_ERROR) : LEVEL_ERROR,
            'err' : LEVEL_ERROR,
            'error' : LEVEL_ERROR,
            'errors' : LEVEL_ERROR,
            str(LEVEL_FATAL) : LEVEL_FATAL,
            'fatal' : LEVEL_FATAL,
            str(LEVEL_IMPORTANT) : LEVEL_IMPORTANT,
            'silent' : LEVEL_IMPORTANT,
            'quiet' : LEVEL_IMPORTANT,
            'important' : LEVEL_IMPORTANT
        }

        if verbosity in map:
            set_level(map[verbosity])
        else:
            logger.warn('Verbosity level %s is not valid, using default verbosity.' % verbosity)

    if type(config.get('client.webpassword')) is type(None):
        config.set('client.webpassword', base64.b16encode(os.urandom(32)).decode('utf-8'), savefile=True)
    if type(config.get('client.client.port')) is type(None):
        randomPort = netcontroller.get_open_port()
        config.set('client.client.port', randomPort, savefile=True)
    if type(config.get('client.public.port')) is type(None):
        randomPort = netcontroller.get_open_port()
        config.set('client.public.port', randomPort, savefile=True)
    if type(config.get('client.api_version')) is type(None):
        config.set('client.api_version', onionrvalues.API_VERSION, savefile=True)
Beispiel #44
0
    def req_config_handler(self):
        req = urlparse.urlparse(self.path).query
        reqs = urlparse.parse_qs(req, keep_blank_values=True)
        data = ''

        if reqs['cmd'] == ['get_config']:
            config.load()
            data = '{ "check_update": "%d", "popup_webui": %d, "auto_start": %d }' %\
                   (config.get(["update", "check_update"], 1)
                    , config.get(["modules", "launcher", "popup_webui"], 1)
                    , config.get(["modules", "launcher", "auto_start"], 0))
        elif reqs['cmd'] == ['set_config']:
            if 'check_update' in reqs:
                check_update = int(reqs['check_update'][0])
                if check_update != 0 and check_update != 1:
                    data = '{"res":"fail, check_update:%s"}' % check_update
                else:
                    config.config["update"]["check_update"] = int(check_update)
                    config.save()

                    data = '{"res":"success"}'

            elif 'popup_webui' in reqs :
                popup_webui = int(reqs['popup_webui'][0])
                if popup_webui != 0 and popup_webui != 1:
                    data = '{"res":"fail, popup_webui:%s"}' % popup_webui
                else:
                    config.set(["modules", "launcher", "popup_webui"], popup_webui)
                    config.save()

                    data = '{"res":"success"}'
            elif 'auto_start' in reqs :
                auto_start = int(reqs['auto_start'][0])
                if auto_start != 0 and auto_start != 1:
                    data = '{"res":"fail, auto_start:%s"}' % auto_start
                else:
                    if auto_start:
                        autorun.enable()
                    else:
                        autorun.disable()

                    config.set(["modules", "launcher", "auto_start"], auto_start)
                    config.save()

                    data = '{"res":"success"}'
            else:
                data = '{"res":"fail"}'

        self.send_response('application/json', data)
Beispiel #45
0
def check():
    import update_from_github
    current_version = update_from_github.current_version()
    last_run_version = config.get(["modules", "launcher", "last_run_version"],
                                  "0.0.0")
    if last_run_version == "0.0.0":
        postUpdateStat = "isNew"
    elif last_run_version != current_version:
        postUpdateStat = "isPostUpdate"
        run(last_run_version)
    else:
        return
    config.set(["update", "postUpdateStat"], postUpdateStat)
    config.set(["modules", "launcher", "last_run_version"], current_version)
    config.save()
Beispiel #46
0
def baozhan(bus, func):
    v = config.get('bus', bus).split(';')
    pause_days, interval, cnt = int(v[0]), int(v[2]), int(v[3])
    if pause_days < 0:
        #print "%s不报站"%bus
        log.warn("%s不报站" % bus)
    elif pause_days > 0:
        log.warn("今日%s暂停报站,将在%d天后恢复报站。" % (bus, pause_days))
        config.set('bus', bus,
                   '%d;%s;%d;%d' % (pause_days - 1, v[1], interval, cnt))
        config.save()
    else:
        for i in range(0, cnt):
            threading.Thread(target=func).start()
            time.sleep(interval)
Beispiel #47
0
    def configure(self):
        '''
            Displays something from the configuration file, or sets it
        '''

        if len(sys.argv) >= 4:
            config.reload()
            config.set(sys.argv[2], sys.argv[3], True)
            logger.debug('Configuration file updated.')
        elif len(sys.argv) >= 3:
            config.reload()
            logger.info(logger.colors.bold + sys.argv[2] + ': ' + logger.colors.reset + str(config.get(sys.argv[2], logger.colors.fg.red + 'Not set.')))
        else:
            logger.info(logger.colors.bold + 'Get a value: ' + logger.colors.reset + sys.argv[0] + ' ' + sys.argv[1] + ' <key>')
            logger.info(logger.colors.bold + 'Set a value: ' + logger.colors.reset + sys.argv[0] + ' ' + sys.argv[1] + ' <key> <value>')
Beispiel #48
0
def bootup ():
    try:
        opts, args = getopt.getopt (sys.argv[1:], "hc:p:", ["config=", "pid-file="])
    except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)
    verbose = False
    config_file = None
    pidfile = None
    for o, a in opts:
        if o == "-v":
            verbose = True
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-c", "--config"):
            config_file = a
        if o in ("-p", "--pid-file"):
            pidfile = a
    if config_file == None:
        # print help information and exit:
        usage()
        sys.exit(2)

    config.initialise(config_file)

    if pidfile is not None:
        #Command line override
        config.set('dbAlerter', 'pid_file', pidfile)

    if (config.has_option('dbAlerter', 'pid_file')):
        pidfile = config.get('dbAlerter', 'pid_file')
        try:
            pf = file(pidfile,'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if pid:
            message = "pidfile %s already exists. dbAlerter may already be running,\ncheck the process / task list and dbAlerter log file for any\nouststanding issues before removing the existing pidfile.\n"
            sys.stderr.write(message % pidfile)
            sys.exit(1)

    daemonize('/dev/null', config.get('dbAlerter','dbalerter_log'), config.get('dbAlerter','dbalerter_log'))

    main()
Beispiel #49
0
def settotime(n):
	ta = config.get('Run','to')
	tt = ta and asc2data(ta)
	if type(n) == list:
		if not n:
			M = tt or time2data(now())
		else:
			M = max(n)
			if tt:
				M = max(M,tt)
	elif tt:
		M = max(n,tt)
	else:
		M = n
	config.set('Run','to',data2asc(M))
	return M
Beispiel #50
0
def configure(ctx, kimai_url, username, password):
    """Configure the Kimai-CLI"""
    config.set('KimaiUrl', kimai_url)

    r = kimai.authenticate(username, password)

    if not r.successful:
        print_error('Authentication failed.')
        return

    config.set('ApiKey', r.apiKey)

    ctx.invoke(download_projects)
    ctx.invoke(download_tasks)

    print_success('Configuration complete')
Beispiel #51
0
def check():
    '''
        Checks to make sure files exist
    '''

    config.reload()

    if not config.is_set('plugins'):
        logger.debug('Generating plugin config data...')
        config.set('plugins', {'enabled': []}, True)

    if not os.path.exists(os.path.dirname(get_plugins_folder())):
        logger.debug('Generating plugin data folder...')
        os.makedirs(os.path.dirname(get_plugins_folder()))

    return
Beispiel #52
0
def setfromtime(n):
	ta = config.get('Run','from')
	tf = ta and asc2data(ta)
	if type(n) == list:
		if not n:
			m = tf or time2data(now())-1
		else:
			m = min(n)
			if tf:
				m = min(m,tf)
	elif tf:
		m = min(n,tf)
	else:
		m = n
	config.set('Run','from',data2asc(m))
	return m
Beispiel #53
0
    def make_settings_zone(self):
        self.preferHeadshotsChk = wx.CheckBox(
            self.panel, label="Prefer headshot sounds over killstreak sounds"
        )

        openSoundDirBtn = wx.Button(self.panel, label="Open sounds directory")
        self.updateSoundsBtn = wx.Button(self.panel, label="Update sounds")
        AsyncBind(wx.EVT_BUTTON, self.OpenSoundsDir, openSoundDirBtn)
        AsyncBind(wx.EVT_BUTTON, self.UpdateSounds, self.updateSoundsBtn)

        soundBtns = wx.BoxSizer(wx.HORIZONTAL)
        soundBtns.Add(openSoundDirBtn)
        soundBtns.Add(self.updateSoundsBtn)

        settingsBox = wx.StaticBoxSizer(wx.VERTICAL, self.panel, label="Settings")
        settingsBox.Add(self.preferHeadshotsChk, border=5, flag=wx.ALL)
        settingsBox.Add(soundBtns, border=5, flag=wx.ALIGN_CENTER | wx.UP | wx.DOWN)

        preferHeadshots = config.config["Sounds"].getboolean("PreferHeadshots", False)
        self.preferHeadshotsChk.SetValue(preferHeadshots)
        self.Bind(
            wx.EVT_CHECKBOX,
            lambda e: config.set(
                "Sounds", "PreferHeadshots", self.preferHeadshotsChk.Value
            ),
            self.preferHeadshotsChk,
        )

        return settingsBox
Beispiel #54
0
 def testPingIndexer(self):
     # We set it to "really" ping index servers for the test. Since we're
     # also mocking out requests.get though, it won't really succeed in
     # pinging anything.
     config.set(ping_sitemap_indexers=True)
     with patch('requests.get') as requests_mock:
         handler = test_handler.initialize_handler(
             sitemap.SiteMapPing,
             action='sitemap/ping',
             repo='global',
             params={'search_engine': 'google'})
         handler.get()
         assert len(requests_mock.call_args_list) == 1
         call_args, _ = requests_mock.call_args_list[0]
         assert call_args[0] == ('https://www.google.com/ping?sitemap='
                                 'https%3A//localhost/global/sitemap')
Beispiel #55
0
def check():
    '''
        Checks to make sure files exist
    '''

    if not config.is_set('plugins'):
        logger.debug('Generating plugin configuration data...')
        config.set('plugins', {'enabled': []}, True)

    if not os.path.exists(os.path.dirname(get_plugins_folder())):
        logger.debug('Generating plugin data folder...')
        try:
            os.makedirs(os.path.dirname(get_plugins_folder()))
        except FileExistsError:
            pass
    return
def test_get_cognito_pool_name():
    config.set("app_environment", "prod")
    assert config.get_cognito_pool_name() == "corona-cognito-pool-prod"
    config.set("app_environment", "production")
    assert config.get_cognito_pool_name() == "corona-cognito-pool-prod"
    config.set("app_environment", "staging")
    assert config.get_cognito_pool_name() == "corona-cognito-pool-staging"
    config.set("app_environment", "testing")
    assert config.get_cognito_pool_name() == "corona-cognito-pool-development"
Beispiel #57
0
 def OnStartMSE(self,evt):
     import os.path
     from os.path import join
     from config import MSE_PATH
     if not os.path.isfile(MSE_PATH):
         dlg = wx.FileDialog(self, "Where is MSE ?", self.dir, "", "All Files(*.*)|*.*", wx.OPEN)
         try:
             if dlg.ShowModal() == wx.ID_OK:
                 # Your code
                 filename=dlg.GetPath()
                 import config
                 config.MSE_PATH=MSE_PATH=filename
                 config.set('mse','path',MSE_PATH)
         finally:
             dlg.Destroy()
     from os import startfile
     startfile(MSE_PATH)
Beispiel #58
0
def disable(name, stop_event=True):
    '''
        Disables a plugin
    '''

    check()

    if is_enabled(name):
        enabled_plugins = get_enabled_plugins()
        enabled_plugins.remove(name)
        config.set('plugins.enabled', enabled_plugins, True)

    if exists(name):
        events.call(get_plugin(name), 'disable')

        if stop_event is True:
            stop(name)
Beispiel #59
0
def install_module(module, new_version):
    import module_init
    import os, subprocess, sys

    current_path = os.path.dirname(os.path.abspath(__file__))
    new_module_version_path = os.path.abspath(
        os.path.join(current_path, os.pardir, os.pardir, module, new_version))

    #check path exist
    if not os.path.isdir(new_module_version_path):
        logging.error("install module %s dir %s not exist", module,
                      new_module_version_path)
        return

    #call setup.py
    setup_script = os.path.join(new_module_version_path, "setup.py")
    if not os.path.isfile(setup_script):
        logging.warn("update %s fail. setup script %s not exist", module,
                     setup_script)
        return

    config.set(["modules", module, "current_version"], str(new_version))
    config.save()

    if module == "launcher":
        module_init.stop_all()
        import web_control
        web_control.stop()

        subprocess.Popen([sys.executable, setup_script], shell=False)

        os._exit(0)

    else:
        logging.info("Setup %s version %s ...", module, new_version)
        try:
            module_init.stop(module)

            subprocess.call([sys.executable, setup_script], shell=False)
            logging.info("Finished new version setup.")

            logging.info("Restarting new version ...")
            module_init.start(module)
        except Exception as e:
            logging.error("install module %s %s fail:%s", module, new_version,
                          e)