2019-07-18 12:45:03 +00:00
|
|
|
import yaml
|
|
|
|
from flask import Flask, request, abort
|
|
|
|
from matrix_client.client import MatrixClient
|
|
|
|
|
2019-07-18 13:09:10 +00:00
|
|
|
application = Flask(__name__)
|
2019-07-18 12:45:03 +00:00
|
|
|
|
2019-07-18 12:47:28 +00:00
|
|
|
"""
|
|
|
|
config.yml Example:
|
|
|
|
|
|
|
|
secret: "..."
|
|
|
|
matrix:
|
2019-07-18 13:46:22 +00:00
|
|
|
server: https://matrix.org
|
2019-07-18 12:47:28 +00:00
|
|
|
username: ...
|
|
|
|
password: "..."
|
|
|
|
"""
|
2019-07-18 12:45:03 +00:00
|
|
|
with open("config.yml", 'r') as ymlfile:
|
|
|
|
cfg = yaml.safe_load(ymlfile)
|
|
|
|
|
|
|
|
|
2019-07-18 13:42:10 +00:00
|
|
|
@application.route('/matrix', methods=['POST'])
|
2019-07-18 12:45:03 +00:00
|
|
|
def notify():
|
|
|
|
channel = request.args.get('channel')
|
|
|
|
if channel is None or len(channel) == 0:
|
|
|
|
abort(401)
|
|
|
|
gitlab_token = request.headers.get('X-Gitlab-Token')
|
|
|
|
if gitlab_token is None or len(gitlab_token) == 0 or gitlab_token != cfg['secret']:
|
|
|
|
abort(403)
|
2019-07-18 14:11:34 +00:00
|
|
|
gitlab_event = request.headers.get("X-Gitlab-Event")
|
|
|
|
|
|
|
|
if gitlab_event == "Push Hook":
|
|
|
|
client = MatrixClient(cfg["matrix"]["server"])
|
|
|
|
client.login(username=cfg["matrix"]["username"], password=cfg["matrix"]["password"])
|
|
|
|
|
|
|
|
room = client.join_room(room_id_or_alias=channel)
|
|
|
|
|
2019-07-18 23:47:11 +00:00
|
|
|
def sort_commits_by_time(commits):
|
|
|
|
return sorted(commits, key=lambda commit: commit["timestamp"])
|
|
|
|
|
|
|
|
def extract_commit_message(commit):
|
2019-07-18 23:54:23 +00:00
|
|
|
return next(iter(commit["message"].splitlines(keepends=False)),
|
|
|
|
"$EMPTY_COMMIT_MESSAGE - impossibruh").strip()
|
2019-07-18 23:47:11 +00:00
|
|
|
|
2019-07-18 14:11:34 +00:00
|
|
|
username = request.json["user_name"]
|
2019-07-18 23:47:11 +00:00
|
|
|
commit_messages = list(map(extract_commit_message, sort_commits_by_time(request.json["commits"])))
|
2019-07-18 14:11:34 +00:00
|
|
|
project_name = request.json["project"]["name"]
|
2019-07-18 23:47:11 +00:00
|
|
|
html_commits = "\n".join((f" <li>{msg}</li>" for msg in commit_messages))
|
|
|
|
text_commits = "\n".join((f"- {msg}" for msg in commit_messages))
|
|
|
|
room.send_html(f"<strong>{username} pushed {len(commit_messages)} commits to {project_name}</strong><br>\n"
|
|
|
|
f"<ul>\n{html_commits}\n</ul>\n",
|
|
|
|
body=f"{username} pushed {len(commit_messages)} commits to {project_name}\n{text_commits}\n",
|
2019-07-18 14:11:34 +00:00
|
|
|
msgtype="m.notice")
|
2019-07-18 12:45:03 +00:00
|
|
|
|
|
|
|
return ""
|