<commit_before>from rest_framework import status, viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.response import Response

from .models import Agent, Device, Event
from .serializers import (  # FIXME alphabetic order
    AddSerializer, AgentSerializer, DeviceSerializer, EventSerializer,
    EventWritableSerializer, MigrateSerializer, RegisterSerializer,
    RemoveSerializer, AllocateSerializer, DeallocateSerializer,
    ReceiveSerializer
)


class AgentView(viewsets.ModelViewSet):
    queryset = Agent.objects.all()
    serializer_class = AgentSerializer
    permission_classes = (IsAdminUser,)


class DeviceView(viewsets.ModelViewSet):
    queryset = Device.objects.all()
    serializer_class = DeviceSerializer
    permission_classes= (IsAuthenticated,)
    
    def get_success_event_creation_response(self, request, event):
        serializer = EventSerializer(event, context={'request': request})
        headers = self.get_success_headers(serializer.data)
        
        return Response(serializer.data, status=status.HTTP_201_CREATED,
                        headers=headers)
    
    def create_event(self, serializer, type):
        serializer.is_valid(raise_exception=True)
        
        return serializer.save(
            agent=self.request.user.agent,
            device=self.get_object(),
            type=type
        )
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def add(self, request, pk=None):
        serializer = AddSerializer(data=request.data,
                                   context={'request': request})
        event = self.create_event(serializer, type=Event.ADD)
        
        return self.get_success_event_creation_response(request, event)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def remove(self, request, pk=None):
        serializer = RemoveSerializer(data=request.data,
                                      context={'request': request,
                                               'device': self.get_object()})
        event = self.create_event(serializer, type=Event.REMOVE)
        
        return self.get_success_event_creation_response(request, event)
    
    @detail_route(methods=['get'])
    def events(self, request, pk=None):
        device = self.get_object()
        queryset = Event.objects.related_to_device(device)
        serializer = EventSerializer(queryset, many=True,
                                     context={'request': request})
        return Response(serializer.data)
    
    @list_route(methods=['post'], permission_classes=[IsAuthenticated])
    def register(self, request):
        serializer = RegisterSerializer(data=request.data,
                                        context={'request': request})
        
        serializer.is_valid(raise_exception=True)
        event = serializer.save(agent=request.user.agent)
        
        return self.get_success_event_creation_response(request, event)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def recycle(self, request, pk=None):
        serializer = EventWritableSerializer(data=request.data,
                                             context={'request': request})
        
        event = self.create_event(serializer, type=Event.RECYCLE)
        
        return self.get_success_event_creation_response(request, event)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def migrate(self, request, pk=None):
        serializer = MigrateSerializer(data=request.data,
                                       context={'request': request})
        
        event = self.create_event(serializer, type=Event.MIGRATE)
        
        return self.get_success_event_creation_response(request, event)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def allocate(self, request, pk=None):
        serializer = AllocateSerializer(
            data=request.data,
            context={'request': request, 'device': self.get_object()}
        )
        
        event = self.create_event(serializer, type=Event.ALLOCATE)
        
        return self.get_success_event_creation_response(request, event)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def deallocate(self, request, pk=None):
        serializer = DeallocateSerializer(
            data=request.data,
            context={'request': request, 'device': self.get_object()}
        )
        event = self.create_event(serializer, type=Event.DEALLOCATE)
        
        return self.get_success_event_creation_response(request, event)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def receive(self, request, pk=None):
        serializer = ReceiveSerializer(
            data=request.data,
            context={'request': request, 'device': self.get_object()}
        )
        event = self.create_event(serializer, type=Event.RECEIVE)
        
        return self.get_success_event_creation_response(request, event)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated],
                  url_path='usage-proof')
    def usage_proof(self, request, pk=None):
        serializer = EventWritableSerializer(data=request.data,
                                             context={'request': request})
        
        event = self.create_event(serializer, type=Event.USAGEPROOF)
        
        return self.get_success_event_creation_response(request, event)


class EventView(viewsets.ReadOnlyModelViewSet):
    queryset = Event.objects.all()
    serializer_class = EventSerializer
    permission_classes= (IsAuthenticated,)<commit_msg>Refactor: encapsulate common code for handling event POSTs.<commit_after>from rest_framework import status, viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.response import Response

from .models import Agent, Device, Event
from .serializers import (  # FIXME alphabetic order
    AddSerializer, AgentSerializer, DeviceSerializer, EventSerializer,
    EventWritableSerializer, MigrateSerializer, RegisterSerializer,
    RemoveSerializer, AllocateSerializer, DeallocateSerializer,
    ReceiveSerializer
)


class AgentView(viewsets.ModelViewSet):
    queryset = Agent.objects.all()
    serializer_class = AgentSerializer
    permission_classes = (IsAdminUser,)


class DeviceView(viewsets.ModelViewSet):
    queryset = Device.objects.all()
    serializer_class = DeviceSerializer
    permission_classes= (IsAuthenticated,)
    
    def get_success_event_creation_response(self, request, event):
        serializer = EventSerializer(event, context={'request': request})
        headers = self.get_success_headers(serializer.data)
        
        return Response(serializer.data, status=status.HTTP_201_CREATED,
                        headers=headers)
    
    def create_event(self, serializer, type):
        serializer.is_valid(raise_exception=True)
        
        return serializer.save(
            agent=self.request.user.agent,
            device=self.get_object(),
            type=type
        )
    
    def post_event(self, request, type, serializer_class=None,
                   extra_context=None):
        serializer_class = serializer_class or EventWritableSerializer
        extra_context = extra_context or {}
        
        context = {'request': request}
        context.update(extra_context)
        
        serializer = serializer_class(data=request.data, context=context)
        event = self.create_event(serializer, type=type)
        
        return self.get_success_event_creation_response(request, event)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def add(self, request, pk=None):
        return self.post_event(request, Event.ADD, AddSerializer)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def remove(self, request, pk=None):
        return self.post_event(request, Event.REMOVE, RemoveSerializer,
                               extra_context={'device': self.get_object()})
    
    @detail_route(methods=['get'])
    def events(self, request, pk=None):
        device = self.get_object()
        queryset = Event.objects.related_to_device(device)
        serializer = EventSerializer(queryset, many=True,
                                     context={'request': request})
        return Response(serializer.data)
    
    @list_route(methods=['post'], permission_classes=[IsAuthenticated])
    def register(self, request):
        serializer = RegisterSerializer(data=request.data,
                                        context={'request': request})
        
        serializer.is_valid(raise_exception=True)
        event = serializer.save(agent=request.user.agent)
        
        return self.get_success_event_creation_response(request, event)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def recycle(self, request, pk=None):
        return self.post_event(request, Event.RECYCLE)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def migrate(self, request, pk=None):
        return self.post_event(request, Event.MIGRATE, MigrateSerializer)
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def allocate(self, request, pk=None):
        return self.post_event(request, Event.ALLOCATE, AllocateSerializer,
                               extra_context={'device': self.get_object()})
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def deallocate(self, request, pk=None):
        return self.post_event(request, Event.DEALLOCATE, DeallocateSerializer,
                               extra_context={'device': self.get_object()})
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def receive(self, request, pk=None):
        return self.post_event(request, Event.RECEIVE, ReceiveSerializer,
                               extra_context={'device': self.get_object()})
    
    @detail_route(methods=['post'], permission_classes=[IsAuthenticated],
                  url_path='usage-proof')
    def usage_proof(self, request, pk=None):
        return self.post_event(request, Event.USAGEPROOF)


class EventView(viewsets.ReadOnlyModelViewSet):
    queryset = Event.objects.all()
    serializer_class = EventSerializer
    permission_classes= (IsAuthenticated,)
{'fraction_non_alphanumeric': 0.09719748804948918, 'fraction_numerical': 0.0005623769800356172, 'mean_word_length': 3.0127867619405793, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 13, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2583210', 'n_tokens_mistral': 2859, 'n_tokens_neox': 2828, 'n_words': 501}