コード例 #1
0
def configure_logging():
    log_filename = 'transpyle-{}.log'.format(datetime.datetime.now().strftime(r'%Y%m%d-%H%M%S'))
    logging_config = {
        'formatters': {
            'brief': {
                '()': 'colorlog.ColoredFormatter',
                'style': '{',
                'format': '{name} [{log_color}{levelname}{reset}] {message}'},
            'precise': {
                'style': '{',
                'format': '{asctime} {name} [{levelname}] {message}'}},
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'formatter': 'brief',
                'level': logging_level_from_envvar('LOGGING_LEVEL', default=logging.WARNING),
                'stream': 'ext://sys.stdout'},
            'file': {
                'class': 'logging.handlers.RotatingFileHandler',
                'formatter': 'precise',
                'level': logging.NOTSET,
                'filename': normalize_path(str(LOGS_PATH.joinpath(log_filename))),
                'maxBytes': 1 * 1024 * 1024,
                'backupCount': 10}},
        'root': {
            'handlers': ['console', 'file'],
            'level': logging.NOTSET},
        'version': 1,
        'disable_existing_loggers': False}
    logging.config.dictConfig(logging_config)
コード例 #2
0
def configure_basic_logging():
    # logging.basicConfig(level=logging.DEBUG)
    # logging.basicConfig(level=logging.INFO)
    log_filename = 'transpyle-{}.log'.format(datetime.datetime.now().strftime(r'%Y%m%d'))
    logging.basicConfig(
        level=logging_level_from_envvar('LOGGING_LEVEL', default=logging.WARNING),
        filename=normalize_path(str(LOGS_PATH.joinpath(log_filename))))
コード例 #3
0
ファイル: imap_connection.py プロジェクト: mbdevpl/maildaemon
    def _connect_oauth(self) -> tuple:
        token_path = pathlib.Path(normalize_path(
            self.oauth_data['token_path']))

        token_valid = False
        if token_path.is_file():
            with token_path.open() as token_file:
                token = json.load(token_file)

            expiration_time = datetime.datetime.fromtimestamp(
                token['expires_at'])
            if datetime.datetime.now() + datetime.timedelta(
                    seconds=60 * 30) < expiration_time:
                token_valid = True
                _LOG.info('OAUTH token will expire on %s', expiration_time)
            else:
                _LOG.warning('OAUTH token will expire on %s', expiration_time)
                oauth = OAuth2Session(self.oauth_data['client_id'],
                                      token=token)
                # token['refresh_token'] is used below
                token = oauth.refresh_token(
                    self.oauth_data['token_uri'],
                    client_id=self.oauth_data['client_id'],
                    client_secret=self.oauth_data['client_secret'])
                with token_path.open('w') as token_file:
                    json.dump(token, token_file)
                token_valid = True

        if not token_valid:
            oauth = OAuth2Session(self.oauth_data['client_id'],
                                  redirect_uri='https://localhost/',
                                  scope=self.oauth_data['scopes'])
            authorization_url, state = oauth.authorization_url(
                self.oauth_data['auth_uri'],
                **self.oauth_data['auth_uri_params'])
            print(f'state: {state}')
            print(
                f'Please go to {authorization_url} and authorize access for {self.login}.'
            )
            authorization_response = input('Enter the full callback URL: ')
            token = oauth.fetch_token(
                self.oauth_data['token_uri'],
                authorization_response=authorization_response,
                client_secret=self.oauth_data['client_secret'])
            with token_path.open('w') as token_file:
                json.dump(token, token_file)

        with token_path.open() as token_file:
            token = json.load(token_file)
        auth_string = f'''user={self._login}\1auth=Bearer {token['access_token']}\1\1'''

        def auth_handler(response: bytes):
            _LOG.debug('auth_handler got: %s', Response(response))
            if not response:
                _LOG.debug('auth_handler returning: %s', auth_string)
                return auth_string.encode()
            return ''

        return self._link.authenticate('XOAUTH2', auth_handler)
コード例 #4
0
def configure(quick: bool = False):
    colorama.init()

    config_path = normalize_path(CONFIG_PATH)
    if not config_path.is_dir():
        config_path.mkdir(parents=True)
    logs_path = normalize_path(LOGS_PATH)
    if not logs_path.is_dir():
        logs_path.mkdir(parents=True)

    if quick:
        configure_basic_logging()
        return

    # try:
    #     import git
    #     git.Repo(str(PROJECT_ROOT_PATH), search_parent_directories=True)
    #     running_from_repo = True
    # except git.exc.InvalidGitRepositoryError:
    #     running_from_repo = False
    # unittest_verbosity = unittest_verbosity()
    configure_logging()
コード例 #5
0
ファイル: config.py プロジェクト: mbdevpl/maildaemon
def load_config(path: pathlib.Path = DEFAULT_CONFIG_PATH):
    """Load maildaemon configuration from file."""
    config = file_to_json(path)
    if 'private-key' in config:
        _LOG.debug('decrypting configuration...')
        try:
            config = decrypt_json(
                config, normalize_path(pathlib.Path(config['private-key'])))
            _LOG.debug('decrypted configuration')
        except rsa.pkcs1.DecryptionError as err:
            raise ValueError('failed to decrypt using {}'.format(
                config['private-key'])) from err
    try:
        validate_config(config)
    except AssertionError as err:
        raise ValueError(f'{path} is an invalid maildaemon config') from err
    return config