def init_app(self, app):
        endpoint = app.config.setdefault("GITHUB_WEBHOOK_ENDPOINT",
                                         "/postreceive")
        secret = app.config.setdefault("GITHUB_WEBHOOK_SECRET", None)

        self._webhook = Webhook(app, endpoint=endpoint, secret=secret)

        app.extensions = getattr(app, "extensions", {})
        app.extensions["github_webhook"] = self
Exemplo n.º 2
0
    def init_app(self, app):
        endpoint = app.config.setdefault('GITHUB_WEBHOOK_ENDPOINT',
                                         '/postreceive')
        secret = app.config.setdefault('GITHUB_WEBHOOK_SECRET', None)

        self._webhook = Webhook(app, endpoint=endpoint, secret=secret)

        app.extensions = getattr(app, 'extensions', {})
        app.extensions['github_webhook'] = self
Exemplo n.º 3
0
def create_app():
    app = Flask(__name__)   # Standard Flask app
    webhook = Webhook(app)  # Defines '/postreceive' endpoint
    gitRepo = git.Repo("/meta")
    o = gitRepo.remotes.origin
    gitRepo.heads.master.set_tracking_branch(o.refs.master)
    gitRepo.heads.master.checkout()

    @app.route("/")         # Standard Flask endpoint
    def on_get():
        o.fetch()
        now = datetime.now()
        d1 = now.strftime("%Y/%m/%d %H:%M:%S")
        print(d1+" Git repo updated !")
        return "Git repo updated !"


    @webhook.hook()         # Defines a handler for the 'push' event
    def on_push(data):
        print("Got push with: {0}".format(data))
        o.fetch()
        gitRepo.git.clean("-f")
        gitRepo.git.reset("--hard", "origin/master")
        print("Git repo updated !")
        return "Git repo updated !"
    return app
Exemplo n.º 4
0
class GithubWebhook(object):
    def __init__(self, app=None):
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        endpoint = app.config.setdefault('GITHUB_WEBHOOK_ENDPOINT',
                                         '/postreceive')
        secret = app.config.setdefault('GITHUB_WEBHOOK_SECRET', None)

        self._webhook = Webhook(app, endpoint=endpoint, secret=secret)

        app.extensions = getattr(app, 'extensions', {})
        app.extensions['github_webhook'] = self

    def hook(self, event_type='push'):
        return self._webhook.hook(event_type=event_type)
class GithubWebhook(object):
    def __init__(self, app=None):
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        endpoint = app.config.setdefault("GITHUB_WEBHOOK_ENDPOINT",
                                         "/postreceive")
        secret = app.config.setdefault("GITHUB_WEBHOOK_SECRET", None)

        self._webhook = Webhook(app, endpoint=endpoint, secret=secret)

        app.extensions = getattr(app, "extensions", {})
        app.extensions["github_webhook"] = self

    def hook(self, event_type="push"):
        return self._webhook.hook(event_type=event_type)
Exemplo n.º 6
0
    def do(self, event=None):
        app = Flask(__name__)

        @app.route("/")  # Standard Flask endpoint
        def ping():
            logging.info('got ping')
            event.set()
            return 'OK'

        webhook = Webhook(app)

        @webhook.hook()
        def on_push(data):
            logging.info('got github push')
            event.set()
            return 'OK'

        port = int(os.environ.get('UPDATER_PORT', '9345'))
        logging.info(f'running http server to updater in port {port}')

        app.run(host="0.0.0.0", port=port)
Exemplo n.º 7
0
    def __init__(
        self,
        config: Config,
        store: Storage,
        github: Github,
        repo: Repository,
    ):
        self.config = config
        self.github = github
        self.repo = repo
        self.command_handler = CommandHandler(config, store, repo)

        # Start a flash webserver
        self.app = Flask(__name__)

        webhook = Webhook(
            self.app,
            endpoint=self.config.webhook_path,
            secret=self.config.webhook_secret,
        )

        @self.app.route("/")
        def hello_world():
            return "Hello, world!"

        @webhook.hook("issue_comment")
        def on_issue_comment(data):
            log.debug(
                f"Got comment: {json.dumps(data, indent=4, sort_keys=True)}")
            self._process_comment(data)

        @webhook.hook("pull_request_review_comment")
        def on_pull_request_review_comment(data):
            log.debug(
                f"Got PR review comment: {json.dumps(data, indent=4, sort_keys=True)}"
            )
            self._process_comment(data)
                   redirect, url_for, abort)
from github_webhook import Webhook
from dmsa import ddl, erd, __version__
from dmsa.utility import (get_template_models, get_service_version,
                          get_template_dialects, ReverseProxied, dmsa_version)
import dmsa.cache

PERIODIC_REFRESH_DELAY = 3600  # seconds
POST_HOOK_REFRESH_DELAY = 10

app = Flask('dmsa')
app.wsgi_app = ReverseProxied(app.wsgi_app)
dmsa.cache.set_cache_dir(app.instance_path)

hmac_key = os.environ.get('DMSA_WEBHOOK_SECRET')
webhook = Webhook(app, endpoint='/refresh', secret=hmac_key)


def refresh_data_models_template():
    """Retrieve the data models from the service and cache them"""
    get_template_models(app.config['service'], force_refresh=True)


def refresh_data_models_template_and_reschedule(delay=None):
    """Refresh the data models summary data and optionally reschedule

    Arguments:
        delay - delay in seconds (to reschedule), or None (to not reschedule)
    """
    refresh_data_models_template()
    if delay:
Exemplo n.º 9
0
from github_webhook import Webhook
from flask import Flask
import os

app = Flask(__name__)  # Standard Flask app
webhook = Webhook(app) # Defines '/postreceive' endpoint

@app.route("/")        # Standard Flask endpoint
def hello_world():
    return "Hello, World!"

@webhook.hook()        # Defines a handler for the 'push' event
def on_push(data):
    print("Got push")
    os.system('sh deploy.sh ')

if __name__ == "__main__":
  app.run(host="0.0.0.0", port=808)
Exemplo n.º 10
0
import logging
import os

from functools import wraps

import requests

from flask import abort, Flask, request
from flask import logging as flask_logging
from github_webhook import Webhook
from ipaddress import ip_address, ip_network

app = Flask(__name__)
webhook = Webhook(app,
                  endpoint='/postreceive',
                  secret=os.environ.get('GITHUB_WEBHOOK_SECRET'))


@app.before_first_request
def setup_logging():
    if app.debug:
        return
    # Add handler to Flask logger to send records to gunicorn stderr.
    # https://github.com/benoitc/gunicorn/issues/379
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter(flask_logging.PROD_LOG_FORMAT))
    app.logger.addHandler(handler)
    app.logger.setLevel(logging.INFO)
    # ... and disable existing handlers to avoid duplicated entries
    app.config['LOGGER_HANDLER_POLICY'] = 'never'
Exemplo n.º 11
0
    app.config[
        "SQLALCHEMY_DATABASE_URI"] = f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}/{MYSQL_DATABASE}"
elif DATABASE_TYPE == "sqlite":
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database/sponsorcord.db"
else:
    raise Exception(f"invalid DATABASE_TYPE {DATABASE_TYPE}")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

# init db
db.init_app(app)

with app.app_context():
    db.create_all()

webhook = Webhook(app,
                  endpoint="/github/webhook",
                  secret=GITHUB_WEBHOOK_SECRET)


def github_login_url():
    return "https://github.com/login/oauth/authorize?%s" % "&".join((
        f"client_id={GITHUB_CLIENT_ID}",
        f"redirect_uri={GITHUB_REDIRECT_URI}",
    ))


def get_github_user_id(code):
    data = {
        "client_id": GITHUB_CLIENT_ID,
        "client_secret": GITHUB_CLIENT_SECRET,
        "code": code,
Exemplo n.º 12
0
from github_webhook import Webhook
from flask import Flask

application = Flask(__name__)  # Standard Flask application
webhook = Webhook(application)  # Defines '/postreceive' endpoint


@application.route("/")  # Standard Flask endpoint
def hello_world():
    return "Hello, World!"


@webhook.hook()  # Defines a handler for the 'push' event
def on_push(data):
    print("Got push with: {0}".format(data))


if __name__ == "__main__":
    application.run(host="0.0.0.0", port=3000)
Exemplo n.º 13
0
from flask import Flask
from github_webhook import Webhook
import telepot
import utils

GITHUB_URL = "https://github.com/"
TOKEN = "484527904:AAHVkzp5hHuxWVfR0tYkIFPV-sgQkXQKqAQ"
# CHANNEL = "-1001084328317"
CHANNEL = "-398468065"
SECRET = "Singapore2017"
Bot = telepot.Bot(TOKEN)
message = "<a href='{pusher_url}'>{pusher}</a> pushed to <a href='{branch_url}'>{branch_name}</a>:\n"
commit_message = "{msg}<a href='{url}'>...</a>\n"

application = Flask(__name__)
webhook = Webhook(application, endpoint="/", secret=SECRET)


@application.route("/hello")
def hello():
    print(1)
    return "<h1>Hello There!</h1>"


@webhook.hook(event_type="ping")  # Defines a handler for the 'push' event
def on_ping(data):
    print("Got ping with: {0}".format(data))


@webhook.hook(event_type="push")  # Defines a handler for the 'push' event
def on_push(data):
Exemplo n.º 14
0
rocketChatDomain = os.environ.get('ROCKET_DOMAIN')
rocketChatChannel = os.environ.get('ROCKET_CHANNEL')
webhookSecret = os.environ.get('WEBHOOK_SECRET')
webhookPort = os.environ.get('WEBHOOOK_PORT')

g = Github(ghAccessToken)

rocketAPI = RocketChatAPI(
    settings={
        'username': rocketChatBotUsername,
        'password': rocketChatBotPassword,
        'domain': rocketChatDomain
    })

app = Flask(__name__)
webhook = Webhook(app, secret=webhookSecret)


def notifyInboundSolutionFocusTicket(data):
    app.logger.info('Checking if event is suitible...')
    # Check we really want to notift about this post
    if data['action'] != 'created':
        app.logger.info('Action is not type created, ignoring')
        return
    app.logger.info('Generating message')
    sender = data['sender']['login']
    contentUrl = data['project_card']['content_url']
    issueId = contentUrl.rsplit('/', 1)[-1]
    githubRepo = g.get_repo(data['repository']['id'])
    githubIssue = githubRepo.get_issue(int(issueId))
    htmlURL = 'https://github.com/' + data['repository'][
Exemplo n.º 15
0
from datetime import datetime

from flask import current_app, request
from github_webhook import Webhook

from txsentinel.github import cache
from txsentinel.github.tasks import maybe_merge

webhook = Webhook(current_app,
                  secret=current_app.config['GITHUB_WEBHOOK_SECRET'])


@webhook.hook(event_type='push')
def on_push(data):
    print('Got push with: {0}'.format(data))


@webhook.hook(event_type='pull_request_review')
def on_pull_request_review(data):
    if data['review']['state'].lower() != 'approved':
        return

    print('Got pull request review with: {0}'.format(data))

    maybe_merge.delay(data['repository']['full_name'],
                      data['pull_request']['number'])


@webhook.hook(event_type='status')
def on_status(data):
    if data['state'] != 'success':
Exemplo n.º 16
0
from app import app, db
from github_webhook import Webhook

url = app.config.get('GITHUB_WEBHOOK_URL', '/api/webhook')
secret = app.config.get('GITHUB_WEBHOOK_SECRET')
webhook = Webhook(app, url, secret)


@webhook.hook()
def on_push(data):
    print data


@webhook.hook()
def on_issues(data):
    print data


@webhook.hook()
def on_issue_comment(data):
    print data


@webhook.hook()
def on_commit_comment(data):
    print data


@webhook.hook()
def on_pull_request_review(data):
    print data
Exemplo n.º 17
0
from github_webhook import Webhook
from flask import Flask, jsonify
import os, json, re, requests
from distutils.util import strtobool
import heroku3
import traceback

app = Flask(__name__)
webhook = Webhook(app, secret=os.getenv("GITHUB_WEBHOOK_SECRET_TOKEN"))
# Get connection to heroku api
heroku_conn = heroku3.from_key(os.getenv('HEROKU_KEY'))


# Handle uncaught 500 Internal Server Errors
def handle_internal_server_error(e):
    print(str(e))
    traceback.print_tb(e.__traceback__)

    status = {
        'status': 'error',
        'message': str(e)
    }
    return jsonify(status), 500
app.register_error_handler(500, handle_internal_server_error)


def get_heroku_app_name(branch):
    return re.sub(r'-*$','', f'joplin-pr-{branch}'[0:30]).lower()


def has_deletion_protection(app):
Exemplo n.º 18
0
#!/usr/bin/env python3
from github_webhook import Webhook
from flask import Flask
import json
import os
import subprocess

# Mounted in by docker
repobase = "/repos/"
secret_file = "/etc/github_webhook_secret"

with open(secret_file, "r") as file:
    secret = file.read().strip()

app = Flask(__name__)  # Standard Flask app
webhook = Webhook(app, secret=secret)  # Defines '/postreceive' endpoint


@webhook.hook()  # Defines a handler for the 'push' event
def on_push(data):
    print(json.dumps(data))
    if data["ref"] == "refs/heads/master":
        repo = data["repository"]["name"]
        url = data["repository"]["ssh_url"]
        if not os.path.isdir(repobase + repo + "/.git"):
            subprocess.run(["/usr/bin/git", "clone", url, repobase + repo])
            print("Cloned " + url + " to " + repobase + repo)
        else:
            subprocess.run(["/usr/bin/git", "pull", "--rebase"],
                           cwd=repobase + repo)
            print("Pulled " + repobase + repo)
Exemplo n.º 19
0
import os
from flask import Flask
from github_webhook import Webhook
from worker import invoke
from github import Github

app = Flask(__name__)
webhook = Webhook(app, secret=os.environ.get('SECRET', 'youvebeenmade'))
g = Github(os.environ.get('GH_ACCESS_TOKEN', ''))
org = g.get_organization(os.environ.get('GH_ORGANIZATION', 'deviavir'))
repo = org.get_repo(os.environ.get('GH_REPO', 'terraform-ci'))


@app.route('/')
def main():
    return 'OK'


@webhook.hook()
def on_push(data):
    print("Got push data: {0}".format(data))
    branch = data['ref'].replace('refs/heads/', '')

    if branch == 'master':
        provider = 'aws'
        tf_commit = False
        upstream = data['repository']['ssh_url']
        modifieds = data['head_commit']['modified']
        for change in modifieds:
            if 'terraform/' in change:
                tf_commit = True
Exemplo n.º 20
0
from flask import redirect
from github_webhook import Webhook

from shared import configuration
from shared_web.flask_app import PDFlask

from . import webhooks

APP = PDFlask(__name__)
WEBHOOK = Webhook(APP, endpoint='/api/github')


@APP.route('/')
def home():
    return 'build-commit-id: ' + APP.config['commit-id']


@WEBHOOK.hook()
def on_push(data):
    ref = data['ref']
    print(f'Got push on {ref}')
    if ref == 'refs/heads/master':
        webhooks.update_prs(data['repository']['full_name'])
    return data


@WEBHOOK.hook(event_type='status')
def on_status(data):
    sha = data.get('sha')
    context = data.get('context')
    state = data.get('state')
import pytest
from flask import Flask
from github_webhook import Webhook

from communication import communication
from compilation import compilation
from downloader import downloader
from notification import notification
from testing import testing

# ----------------------------------------------------------------------------#
# App Config.
# ----------------------------------------------------------------------------#

app = Flask(__name__)
webhook = Webhook(app)

# ----------------------------------------------------------------------------#
# Controllers.
# ----------------------------------------------------------------------------#


@app.route('/')
def home():
    return "Hello world!"


@webhook.hook()
def on_push(data):
    result = communication.Result()
    downloader.push_event(data, result)
Exemplo n.º 22
0
        sha_name, signature = header_signature.split('=')
        if sha_name != 'sha1':
            return False

        mac = hmac.new(SECRET_KEY, msg=request.data, digestmod='sha1')

        if not str(mac.hexdigest()) == str(signature):
            return False

        return True


jenkins = GitKeeper(sys.argv[1])

app = Flask(__name__)
webhook = Webhook(app)  # /postreceive endpoint


@webhook.hook()
def on_push(data):
    if jenkins.validate_header():
        name = data[u'repository'][u'name']
        branch = data[u'ref'].split('/')[-1]
        app.logger.info('Push event received for {}'.format(name))
        try:
            jenkins.pull(name, branch)
            app.logger.info('Pull success!')
        except Exception as e:
            app.logger.error('Pull failed with {}'.format(e))
        return '200 OK!'
    app.logger.warning(' 403 - Unverified request received!')
Exemplo n.º 23
0
from github_webhook import Webhook
from flask import Flask
import os

app = Flask(__name__)
webhook = Webhook(app, "/")

REPOS = [
    'jpush-api-java-client', 'jpush-api-csharp-client', 'jpush-api-php-client',
    'jpush-api-python-client', 'jpush-api-nodejs-client',
    'jpush-api-ruby-client', 'jmessage-api-java-client',
    'jmessage-api-csharp-client', 'jmessage-api-python-client',
    'jmessage-api-php-client', 'jsms-api-java-client', 'jsms-api-php-client',
    'jsms-api-csharp-client'
]
current = os.path.split(os.path.realpath(__file__))[0]
separator = "\n========================================================================\n"
log_file = "{0}/hooks.log".format(current)


def log_it(str):
    f = open(log_file, 'a')
    f.write(str)
    f.close()


@app.route("/")  # Standard Flask endpoint
def hello_world():
    return "Hello, World!"

Exemplo n.º 24
0
import subprocess
import os
import shutil

from github_webhook import Webhook
from flask import Flask
from make_readme import generate_READMEs

app = Flask(__name__)

github_webhook_secret = open("github_webhook_secret", "r").read().strip()
webhook = Webhook(app, endpoint="/github", secret=github_webhook_secret)

login = open("login").read().strip()
token = open("token").read().strip()

my_env = os.environ.copy()
my_env["GIT_TERMINAL_PROMPT"] = "0"
my_env["GIT_AUTHOR_NAME"] = "Yunohost-Bot"
my_env["GIT_AUTHOR_EMAIL"] = "*****@*****.**"
my_env["GIT_COMMITTER_NAME"] = "Yunohost-Bot"
my_env["GIT_COMMITTER_EMAIL"] = "*****@*****.**"


def git(cmd, in_folder=None):

    if not isinstance(cmd, list):
        cmd = cmd.split()
    if in_folder:
        cmd = ["-C", in_folder] + cmd
    cmd = ["git"] + cmd
Exemplo n.º 25
0
 def __init__(self, app):
     url = app.config.get('GITHUB_WEBHOOK_URL', '/api/webhook')
     secret = app.config.get('GITHUB_WEBHOOK_SECRET')
     Webhook.__init__(self, app, url, secret)
Exemplo n.º 26
0
from app import app
from github_webhook import Webhook
from utils.cron.interfaceTestCron import Cron
from models.cronTab import CronTab
from app import cron_manager
from utils import common
import datetime

webhook = Webhook(app, endpoint='/api/webhook')


@webhook.hook(event_type='ExecTest'
              )  # Defines a handler for the 'ExecTest' event
def on_exec_test(data):
    try:
        data['testCaseSuiteIdList'] = data['testCaseSuiteIdList'].strip(
        ).split(';')
    except BaseException:
        raise TypeError('参数 「testCaseSuiteIdList」 不合法')

    try:
        data['testDomain'] = data['testDomain'].strip()
    except BaseException:
        raise TypeError('参数 「testDomain」 不合法')

    try:
        data['dingdingAccessToken'] = data['dingdingAccessToken'].strip()
    except BaseException:
        raise TypeError('参数 「dingdingAccessToken」 不合法')

    data['isExecuteForbiddenedCase'] = True if common.can_convert_to_str(data.get('isExecuteForbiddenedCase'))\
Exemplo n.º 27
0
from pprint import pprint

from flask import Flask
from github_webhook import Webhook

from qmk_commands import discord_msg
from update_kb_redis import update_needed

# Setup
app = Flask(__name__)
app.config.from_object(__name__)
github_secret = None
webhook = Webhook(app, '/postreceive', github_secret)


# Views
@app.route("/")
def index():
    return "Hello, World!"


@app.route("/healthcheck")
def healthcheck():
    return "GOOD"


@webhook.hook('push')
def on_push(data):
    """Handle a webhook from github.
    """
    print('Got webhook request:')
Exemplo n.º 28
0
import subprocess
import os

from flask import Blueprint, request
from github_webhook import Webhook

webhook_blueprint = Blueprint('webhooks', __name__)
webhook = Webhook(
    webhook_blueprint
)  # register GitHub webhook and define '/postreceive' endpoint

# Constants
GITHUB_WEBHOOK_BASH_SCRIPTS_PATH = './github_webhook_bash_scripts'


@webhook.hook()  # defines a handler for the 'push' event.
def on_portfolio_website_push(data):
    """
    This route is called when GitHub's webhook makes a request with a JSON payload. It executes a bash script depending
    on the :code:`full_name` key's value in the JSON payload.

    :param data: GitHub JSON payload.
    :type data: JSON
    :return: None
    :rtype: None
    """
    full_name = data['repository']['full_name']
    print(f'Received push from: {full_name}')
    if full_name == 'edmondchuc/portfolio-website':
        subprocess.call(
            os.path.join(GITHUB_WEBHOOK_BASH_SCRIPTS_PATH,