Beispiel #1
0
def create_database(echo=True):
    with session_scope(echo=echo) as session:
        Base.metadata.create_all(session.connection())

    file_path = os.path.realpath(__file__)
    app_path = os.path.dirname(os.path.dirname(file_path))
    config_path = os.path.join(app_path, 'migrations', 'alembic.ini')

    alembic_config = Config(config_path)
    command.stamp(alembic_config, 'head')
Beispiel #2
0
def repository():
    from bitcoin_acks.models.repositories import Repositories
    from bitcoin_acks.database.session import session_scope
    r = Repositories()
    r.path = 'bitcoin'
    r.name = 'bitcoin'
    with session_scope() as session:
        session.add(r)
        session.flush()
        session.expunge(r)
    return r
Beispiel #3
0
    def after_request(response):
        """ Logging after every request. """

        record = Logs()
        if request.headers.getlist("X-Forwarded-For"):
            record.ip = request.headers.getlist("X-Forwarded-For")[0]
        else:
            record.ip = request.remote_addr
        record.method = request.method
        record.full_path = request.full_path
        record.path = request.path
        record.user_agent = request.user_agent.string
        record.status = response.status_code

        with session_scope() as log_session:
            log_session.add(record)
        return response
Beispiel #4
0
def send_tweet(pull_request_number=None):
    with session_scope() as session:
        now = datetime.datetime.utcnow()
        yesterday = now - datetime.timedelta(days=1)
        twitter = Twython(os.environ['BTC_TWITTER_APP_KEY'],
                          os.environ['BTC_TWITTER_APP_SECRET'],
                          os.environ['BTC_TWITTER_OAUTH_TOKEN'],
                          os.environ['BTC_TWITTER_OAUTH_TOKEN_SECRET'])
        if pull_request_number:
            next_pull_request = (session.query(PullRequests).filter(
                PullRequests.number == pull_request_number).first())
        else:
            next_pull_request = (session.query(PullRequests).order_by(
                PullRequests.merged_at.asc()).filter(
                    PullRequests.merged_at > yesterday).filter(
                        PullRequests.tweet_id.is_(None)).filter(
                            PullRequests.merged_at.isnot(None)).first())
        if next_pull_request is None:
            log.debug('No pull requests found.')
            return
        commits_url = 'https://api.github.com/repos/bitcoin/bitcoin/commits'
        params = {'author': next_pull_request.author.login}
        response = requests.get(commits_url, params=params)
        log.debug('github response', response=response)
        response_json = response.json()
        author_name = next_pull_request.author.name or next_pull_request.author.login
        if len(response_json) > 1 and next_pull_request.number != 14802:
            status = 'Merged PR from {0}: {1} {2}' \
                .format(author_name,
                        next_pull_request.title,
                        next_pull_request.html_url)
        else:
            status = '''
            {0}'s first merged PR: {1}
            Congratulations!  🎉🍾🎆
            '''.format(author_name, next_pull_request.html_url)
        log.debug('tweet status', status=status)
        tweet = twitter.update_status(status=status)
        log.debug('tweet', tweet=tweet)
        new_tweet = Tweets()
        new_tweet.id = tweet['id']
        new_tweet.pull_request_id = next_pull_request.number
        session.add(new_tweet)
        next_pull_request.tweet_id = tweet['id']
Beispiel #5
0
    def github_logged_in(github_blueprint, token):
        if not token:
            flash("Failed to log in.", category="error")
            return redirect(url_for("github.login"))

        user_resp = github_blueprint.session.get("/user")
        log.debug('user response', resp=user_resp.json())
        emails_resp = github_blueprint.session.get("/user/emails")
        log.debug('user emails response', resp=emails_resp.json())
        if not emails_resp.ok:
            log.error('github_logged_in error',
                      resp=emails_resp.json(),
                      token=token)
            msg = "Failed to fetch user info."
            flash(msg, category="error")
            return False

        info = user_resp.json()
        user_id = info["node_id"]
        email = [e for e in emails_resp.json() if e['primary']][0]['email']

        with session_scope() as db_session:
            try:
                user = db_session.query(Users).filter(
                    Users.id == user_id).one()
            except NoResultFound:
                user = Users(id=user_id)
                db_session.add(user)
            user.is_active = True
            user.email = email
            try:
                db_session.query(OAuth).filter_by(
                    provider=github_blueprint.name,
                    provider_user_id=user_id).one()
            except NoResultFound:
                oauth = OAuth(provider=github_blueprint.name,
                              provider_user_id=user_id,
                              user_id=user_id,
                              token=token)
                db_session.add(oauth)
            login_user(user)
            flash("Successfully signed in.")
        return False
Beispiel #6
0
def create_or_update_database(echo=True):
    file_path = os.path.realpath(__file__)
    app_path = os.path.dirname(os.path.dirname(file_path))
    config_path = os.path.join(app_path, 'migrations', 'alembic.ini')

    alembic_config = Config(config_path)

    try:
        with session_scope(echo=echo) as session:
            directory = script.ScriptDirectory.from_config(alembic_config)
            get_head = set(directory.get_heads())
            current_head = get_current_head(connectable=session.bind.engine)
            if current_head == get_head:
                return
            elif not current_head:
                Base.metadata.create_all(session.connection())
                command.stamp(alembic_config, 'head')
            else:
                command.upgrade(alembic_config, 'head')

    except OperationalError as e:
        print(e)
        time.sleep(10)
        create_or_update_database(echo=echo)
Beispiel #7
0
def send_toot():
    with session_scope() as session:
        now = datetime.datetime.utcnow()
        yesterday = now - datetime.timedelta(days=1)

        next_pull_request = (session.query(PullRequests).order_by(
            PullRequests.merged_at.asc()).filter(
                PullRequests.merged_at > yesterday).filter(
                    PullRequests.toot_id.is_(None)).filter(
                        PullRequests.merged_at.isnot(None)).first())
        if next_pull_request is None:
            return
        mastodon = login()

        commits_url = 'https://api.github.com/repos/bitcoin/bitcoin/commits'
        params = {'author': next_pull_request.author.login}
        response = requests.get(commits_url, params=params)
        response_json = response.json()

        if len(response_json) > 1:
            status = 'Merged PR from {0}: {1} {2}' \
                .format(next_pull_request.author.login,
                        next_pull_request.title,
                        next_pull_request.html_url)
        else:
            status = '''
            {0}'s first merged PR: {1}
            Congratulations!  🎉🍾🎆
            '''.format(next_pull_request.author.login,
                       next_pull_request.html_url)
        toot = mastodon.toot(status)
        new_tweet = Toots()
        new_tweet.id = toot['id']
        new_tweet.pull_request_id = next_pull_request.number
        session.add(new_tweet)
        next_pull_request.toot_id = toot['id']
Beispiel #8
0
def drop_database(echo=True):
    with session_scope(echo=echo) as session:
        Base.metadata.drop_all(session.connection())
Beispiel #9
0
def drop_database(echo=True):
    with session_scope(echo=echo) as session:
        Base.metadata.drop_all(session.connection())
        session.execute('DROP TABLE github.public.alembic_version;')