# -*- coding: utf8 -*-
import json

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from frigg.builds.models import Project
from frigg.helpers import github


@csrf_exempt
def github_webhook(request):
    try:
        event = request.META['HTTP_X_GITHUB_EVENT']
    except KeyError:
        return HttpResponse("Missing HTTP_X_GITHUB_EVENT")

    data = json.loads(request.body)
    if event == "issue_comment":
        data = github.parse_comment_payload(data)

        # if this comment is on a pull request, build it
        if data and data['pull_request_url'] != "":
            data = github.parse_pull_request_payload(github.api_request(
                data['pull_request_url'],
                Project.token_for_url(data['repo_url'])
            ))

    elif event == "pull_request":
        data = github.parse_pull_request_payload(data)

    elif event == "push":
        data = github.parse_push_payload(data)

    else:
        return HttpResponse("Unknown event: %s" % event)

    if data:
        project = Project.objects.get_or_create_from_url(data['repo_url'])
        project.private = data['private']
        project.save()
        build = project.start_build(data)
        return HttpResponse('Handled "%s" event.\nMore info at %s' % (
            event,
            build.get_absolute_url()
        ))
    else:
        return HttpResponse('Handled "%s" event.' % event)

@@ -27,16 +27,63 @@
 ort json
+%0Afrom django.contrib.auth import get_user_model
 %0A%0Afrom d
@@ -394,17 +394,17 @@
 esponse(
-%22
+'
 Missing 
@@ -422,17 +422,17 @@
 UB_EVENT
-%22
+'
 )%0A%0A    d
@@ -478,17 +478,17 @@
 vent == 
-%22
+'
 issue_co
@@ -492,17 +492,17 @@
 _comment
-%22
+'
 :%0A      
@@ -655,10 +655,10 @@
  != 
-%22%22
+''
 :%0A  
@@ -860,17 +860,17 @@
 vent == 
-%22
+'
 pull_req
@@ -873,17 +873,17 @@
 _request
-%22
+'
 :%0A      
@@ -954,14 +954,14 @@
  == 
-%22
+'
 push
-%22
+'
 :%0A  
@@ -1016,41 +1016,747 @@
   el
-se:%0A        return HttpResponse(%22
+if event == 'member':%0A        if data%5B'action'%5D != 'added':%0A            # no other action is supported so we don't know how the payload will be%0A            return HttpResponse('Unknown action')%0A%0A        username = data%5B'member'%5D%5B'login'%5D%0A        if get_user_model().objects.filter(username=username).exists():%0A            project = Project.objects.get(%0A                name=data%5B'repository'%5D%5B'name'%5D,%0A                owner=data%5B'repository'%5D%5B'owner'%5D%5B'login'%5D%0A            )%0A            project.members.add(get_user_model().objects.get(username=username))%0A            return HttpResponse('Added %25s to the project' %25 data%5B'member'%5D%5B'login'%5D)%0A        return HttpResponse('Unknown user %25s' %25 username)%0A%0A    else:%0A        return HttpResponse('
 Unkn
@@ -1768,17 +1768,17 @@
 vent: %25s
-%22
+'
  %25 event

Add webhook handling of member action