add auto deploy by gogs

pull/342/head
vapao 2021-06-25 14:47:07 +08:00
parent e6cda83c4d
commit e071cc502a
1 changed files with 29 additions and 20 deletions

View File

@ -8,34 +8,43 @@ from apps.repository.models import Repository
from apps.repository.utils import dispatch as build_dispatch from apps.repository.utils import dispatch as build_dispatch
from apps.deploy.utils import dispatch as deploy_dispatch from apps.deploy.utils import dispatch as deploy_dispatch
from threading import Thread from threading import Thread
import hashlib
import hmac
import json import json
def auto_deploy(request, deploy_id, kind): def auto_deploy(request, deploy_id, kind):
token = request.headers.get('X-Gitlab-Token') or request.headers.get('X-Gitee-Token') if not _is_valid_token(request):
if token and _is_valid_token(token): return HttpResponseForbidden()
try: try:
body = json.loads(request.body) body = json.loads(request.body)
if not body['ref'].startswith('refs/'): # Compatible with gogs
body['ref'] = 'refs/tags/' + body['ref']
body = json.loads(request.body)
_, _kind, ref = body['ref'].split('/', 2)
if kind == 'branch' and _kind == 'heads':
commit_id = body['after'] commit_id = body['after']
_, _kind, ref = body['ref'].split('/', 2) if commit_id != '0000000000000000000000000000000000000000' and ref == request.GET.get('name'):
if commit_id != '0000000000000000000000000000000000000000': Thread(target=_dispatch, args=(deploy_id, ref, commit_id)).start()
if kind == 'branch': return HttpResponse(status=202)
if _kind == 'heads' and ref == request.GET.get('name'): elif kind == 'tag' and _kind == 'tags':
Thread(target=_dispatch, args=(deploy_id, ref, commit_id)).start() Thread(target=_dispatch, args=(deploy_id, ref)).start()
return HttpResponse(status=202) return HttpResponse(status=202)
elif kind == 'tag': return HttpResponse(status=204)
if _kind == 'tags': except Exception as e:
Thread(target=_dispatch, args=(deploy_id, ref)).start() return HttpResponseBadRequest(e)
return HttpResponse(status=202)
return HttpResponse(status=204)
except Exception as e:
return HttpResponseBadRequest(e)
return HttpResponseForbidden()
def _is_valid_token(token): def _is_valid_token(request):
api_key = AppSetting.get_default('api_key') api_key = AppSetting.get_default('api_key')
return api_key == token token = request.headers.get('X-Gitlab-Token') or request.headers.get('X-Gitee-Token')
if token:
return token == api_key
token = request.headers.get('X-Gogs-Signature')
if token:
return token == hmac.new(api_key.encode(), request.body, hashlib.sha256).hexdigest()
return False
def _dispatch(deploy_id, ref, commit_id=None): def _dispatch(deploy_id, ref, commit_id=None):