# Path: app/services/models.py
# class Event(models.Model):
#     """
#     An event object stores the name of an event and the structure of the payload,
#     and types expected in the payload.
#     """
#     name = models.CharField(max_length=90)
#     service = models.CharField(max_length=90)
#     # Stores both the attribute json with sample input
#     # and the attribute json with the expected types
#     payload = jsonfield.JSONField()
#     attributes = jsonfield.JSONField()
# 
# Path: app/services/hooks/github.py
# class GithubHook():
#     """
#     Receiever for the Github Webhooks API.
#     """
#     @classmethod
#     def process_event(cls, event_name, event):
#         """
#         Processes a hook service event from Github.
#         """
#         # Create the Event object as a convenience
#         event = EventData(event_name, **event)
#         unlocked = []
#         if event.user is not None:
#             unlocked = check_for_unlocked_achievements(event_name, event, event.user)
# 
#         return json_response(unlocked)
# 
# Path: app/achievement/hooks.py
# def check_for_unlocked_achievements(event, payload, user=None):
#     """
#     Checks if a user has unlocked any achievements, given the event
#     and event payload as input.
# 
#     @param event: Name of the event
#     @param payload: Dictionary of key-value event data
#     @param user: The User/UserProfile model or name of a user
#     @return: listof Achievement
#     """
#     if isinstance(user, basestring):
#         # There's a guarantee that usernames are unique
#         if User.objects.filter(username=user).count() == 1:
#             user = User.objects.get(username=user).profile
#         elif UserProfile.objects.filter(user__username=user).count() == 1:
#             user = UserProfile.objects.get(user__username=user)
#         else:
#             return []
#     elif isinstance(user, User):
#         user = user.profile
# 
#     unlocked_achievements = []
#     if user:
#         achievements = Achievement.objects.exclude(Q(active=False) | Q(pk__in=
#             map(lambda u: u.pk, user.achievements)))
#     else:
#         achievements = Achievement.objects.exclude(active=False)
# 
#     for achievement in achievements:
#         if achievement.unlocked(event, payload):
#             unlocked_achievements.append(achievement.to_json())
#             if user:
#                 unlocked_achievement = UserAchievement(achievement=achievement, user=user)
#                 unlocked_achievement.save()
# 
#     return unlocked_achievements
# 
# Path: app/services/utils.py
# def json_response(data, success=True):
#     """
#     Creates a HttpResponse for returning json data.
# 
#     @param data: Object
#     @return: HttpResponse
#     """
#     return HttpResponse(json.dumps({
#             'response': data,
#             'success': success
#         }, separators=(',', ':'), indent=4),
#         content_type="application/json", status=200)
# 
# def initialize_webhook_addresses():
#     """
#     Adds the webhook addresses to the settings variable.
#     """
#     if not hasattr(settings, 'GITHUB_IP_ADDRESSES'):
#         blocks = get_api_data('https://api.github.com/meta')
#         blocks = blocks['hooks']
#         addresses = []
#         for block in blocks:
#             addresses += map(lambda ip: str(ip), list(ipaddress.ip_network(block).hosts()))
#         setattr(settings, 'GITHUB_IP_ADDRESSES', addresses)
# 
#     return None
# 
# def get_client_ip(request):
#     """
#     Gets the client's ip address from a request object.
#     """
#     forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', None)
#     real_ip = request.META.get('HTTP_X_REAL_IP', None)
#     if forwarded_for:
#         return forwarded_for.split(',')[0]
#     elif real_ip:
#         return real_ip
#     return request.META.get('REMOTE_ADDR')


import json
import re
from django.conf import settings
from django.http import HttpResponse
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import user_passes_test, login_required
from app.services.models import Event
from app.services.hooks import GithubHook
from app.achievement.hooks import check_for_unlocked_achievements
from app.services.utils import json_response, initialize_webhook_addresses, get_client_ip




@login_required
@require_http_methods(['GET'])
@user_passes_test(lambda u: u.is_superuser)

# Path: app/services/models.py
# class Event(models.Model):
#     """
#     An event object stores the name of an event and the structure of the payload,
#     and types expected in the payload.
#     """
#     name = models.CharField(max_length=90)
#     service = models.CharField(max_length=90)
#     # Stores both the attribute json with sample input
#     # and the attribute json with the expected types
#     payload = jsonfield.JSONField()
#     attributes = jsonfield.JSONField()
# 
# Path: app/services/hooks/github.py
# class GithubHook():
#     """
#     Receiever for the Github Webhooks API.
#     """
#     @classmethod
#     def process_event(cls, event_name, event):
#         """
#         Processes a hook service event from Github.
#         """
#         # Create the Event object as a convenience
#         event = EventData(event_name, **event)
#         unlocked = []
#         if event.user is not None:
#             unlocked = check_for_unlocked_achievements(event_name, event, event.user)
# 
#         return json_response(unlocked)
# 
# Path: app/achievement/hooks.py
# def check_for_unlocked_achievements(event, payload, user=None):
#     """
#     Checks if a user has unlocked any achievements, given the event
#     and event payload as input.
# 
#     @param event: Name of the event
#     @param payload: Dictionary of key-value event data
#     @param user: The User/UserProfile model or name of a user
#     @return: listof Achievement
#     """
#     if isinstance(user, basestring):
#         # There's a guarantee that usernames are unique
#         if User.objects.filter(username=user).count() == 1:
#             user = User.objects.get(username=user).profile
#         elif UserProfile.objects.filter(user__username=user).count() == 1:
#             user = UserProfile.objects.get(user__username=user)
#         else:
#             return []
#     elif isinstance(user, User):
#         user = user.profile
# 
#     unlocked_achievements = []
#     if user:
#         achievements = Achievement.objects.exclude(Q(active=False) | Q(pk__in=
#             map(lambda u: u.pk, user.achievements)))
#     else:
#         achievements = Achievement.objects.exclude(active=False)
# 
#     for achievement in achievements:
#         if achievement.unlocked(event, payload):
#             unlocked_achievements.append(achievement.to_json())
#             if user:
#                 unlocked_achievement = UserAchievement(achievement=achievement, user=user)
#                 unlocked_achievement.save()
# 
#     return unlocked_achievements
# 
# Path: app/services/utils.py
# def json_response(data, success=True):
#     """
#     Creates a HttpResponse for returning json data.
# 
#     @param data: Object
#     @return: HttpResponse
#     """
#     return HttpResponse(json.dumps({
#             'response': data,
#             'success': success
#         }, separators=(',', ':'), indent=4),
#         content_type="application/json", status=200)
# 
# def initialize_webhook_addresses():
#     """
#     Adds the webhook addresses to the settings variable.
#     """
#     if not hasattr(settings, 'GITHUB_IP_ADDRESSES'):
#         blocks = get_api_data('https://api.github.com/meta')
#         blocks = blocks['hooks']
#         addresses = []
#         for block in blocks:
#             addresses += map(lambda ip: str(ip), list(ipaddress.ip_network(block).hosts()))
#         setattr(settings, 'GITHUB_IP_ADDRESSES', addresses)
# 
#     return None
# 
# def get_client_ip(request):
#     """
#     Gets the client's ip address from a request object.
#     """
#     forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', None)
#     real_ip = request.META.get('HTTP_X_REAL_IP', None)
#     if forwarded_for:
#         return forwarded_for.split(',')[0]
#     elif real_ip:
#         return real_ip
#     return request.META.get('REMOTE_ADDR')


# Path: app/services/views.py
import json
import re
from django.conf import settings
from django.http import HttpResponse
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import user_passes_test, login_required
from app.services.models import Event
from app.services.hooks import GithubHook
from app.achievement.hooks import check_for_unlocked_achievements
from app.services.utils import json_response, initialize_webhook_addresses, get_client_ip





@login_required
@require_http_methods(['GET'])
@user_passes_test(lambda u: u.is_superuser)

def service_events(request, service):