# Path: src/app/models.py
# class Build(models.Model):
# 
#     class Meta:
#         db_table = 'builds'
# 
#     number = models.IntegerField()
#     job = models.ForeignKey(Job, related_name="builds")
#     created = models.DateTimeField(auto_now_add=True)
#     result = models.TextField(default="")
# 
#     def __str__(self):
#         return "{0}:{1}".format(self.job.name, self.number)
# 
# class Job(models.Model):
# 
#     class Meta:
#         db_table = 'jobs'
# 
#     name = models.CharField(unique=True, max_length=250)
#     description = models.TextField(blank=True, default='')
#     svn_url = models.TextField()
#     svn_username = models.TextField(blank=True, default='')
#     svn_password = models.TextField(blank=True, default='')
# 
#     recipient = models.TextField()
#     violation_threshold_num = models.IntegerField(default=888)
# 
#     def __str__(self):
#         return self.name
# 
# Path: src/app/serializers.py
# class BuildSerializer(serializers.ModelSerializer):
#     links = serializers.SerializerMethodField()
# 
#     class Meta:
#         model = Build
#         fields = ('id', 'number', 'created', 'job', 'result', 'links')
# 
#     def get_links(self, obj):
#         request = self.context['request']
#         links = {
#             'self': reverse('build-detail', kwargs={'pk': obj.pk}, request=request),
#             'job': None,
#         }
#         # 注意: 这里用的是sprint_id, assigned用的是 obj.assigned.
#         if obj.job:
#             links['job'] = reverse(
#                 'job-detail', kwargs={'pk': obj.job_id}, request=request)
# 
#         return links
# 
#     def validate(self, attrs):
#         return attrs
# 
# class JobSerializer(serializers.ModelSerializer):
#     links = serializers.SerializerMethodField()
#     violation_info = serializers.SerializerMethodField()
# 
#     class Meta:
#         model = Job
#         fields = ('id', 'name', 'description',
#                   'svn_url', 'svn_username', 'svn_password',
#                   'recipient', 'violation_threshold_num', 'links', 'violation_info')
# 
#     def get_violation_info(self, obj):
#         last_builds = obj.builds.order_by('-number')[:1]
#         violation_info = {
#             "violation_file_num": -1,
#             'violation_num': -1,
#             'created': '0-0-0 0:0:0',
#             'health_url': '/static/img/rain.png',
#             'report_url': ''
#         }
#         if not last_builds:
#             return violation_info
#         last_build = last_builds[0]
#         build_info = json.loads(last_build.result)
# 
#         violation_info = build_info['violation_info']
#         if violation_info['violation_num'] >= obj.violation_threshold_num:
#             health_url = '/static/img/rain.png'
#         else:
#             health_url = '/static/img/sun.png'
# 
#         violation_info.update({
#             'created': build_info['datetime'],
#             'health_url': health_url,
#             'report_url': settings.JENKINS_URL + '/job/{job_name}/violations/'.format(job_name=obj.name)
#         })
# 
#         return violation_info
# 
#     def get_links(self, obj):
#         request = self.context['request']
#         return {
#             'self': reverse('job-detail', kwargs={'pk': obj.pk}, request=request)
#         }


import json
import logging
from django.conf import settings
from django.shortcuts import get_object_or_404
from rest_framework import authentication, filters, permissions, viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from lintjenkins import LintJenkins
from silk.profiling.profiler import silk_profile
from .models import Build, Job
from .serializers import BuildSerializer, JobSerializer
        job_info = serializer.data
        logger.info(job_info)
        try:
            lint_jenkins.add_job(svn=str(job_info['svn_url']),
                                 username=str(job_info['svn_username']),
                                 password=str(job_info['svn_password']),
                                 job_name=str(job_info['name']))
        except Exception as e:
            logger.exception(e)
            Job.objects.filter(id=job_info['id']).delete()
            raise Exception(e)

        logger.info('create params:%s', serializer.data)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            serializer.data.sort(key=lambda x: x['violation_info']['violation_num'], reverse=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        serializer.data.sort(key=lambda x: x['violation_info']['violation_num'], reverse=True)
        return Response(serializer.data)


class BuildViewSet(DefaultsMixin, viewsets.ModelViewSet):
    queryset = Build.objects.all()

# Path: src/app/models.py
# class Build(models.Model):
# 
#     class Meta:
#         db_table = 'builds'
# 
#     number = models.IntegerField()
#     job = models.ForeignKey(Job, related_name="builds")
#     created = models.DateTimeField(auto_now_add=True)
#     result = models.TextField(default="")
# 
#     def __str__(self):
#         return "{0}:{1}".format(self.job.name, self.number)
# 
# class Job(models.Model):
# 
#     class Meta:
#         db_table = 'jobs'
# 
#     name = models.CharField(unique=True, max_length=250)
#     description = models.TextField(blank=True, default='')
#     svn_url = models.TextField()
#     svn_username = models.TextField(blank=True, default='')
#     svn_password = models.TextField(blank=True, default='')
# 
#     recipient = models.TextField()
#     violation_threshold_num = models.IntegerField(default=888)
# 
#     def __str__(self):
#         return self.name
# 
# Path: src/app/serializers.py
# class BuildSerializer(serializers.ModelSerializer):
#     links = serializers.SerializerMethodField()
# 
#     class Meta:
#         model = Build
#         fields = ('id', 'number', 'created', 'job', 'result', 'links')
# 
#     def get_links(self, obj):
#         request = self.context['request']
#         links = {
#             'self': reverse('build-detail', kwargs={'pk': obj.pk}, request=request),
#             'job': None,
#         }
#         # 注意: 这里用的是sprint_id, assigned用的是 obj.assigned.
#         if obj.job:
#             links['job'] = reverse(
#                 'job-detail', kwargs={'pk': obj.job_id}, request=request)
# 
#         return links
# 
#     def validate(self, attrs):
#         return attrs
# 
# class JobSerializer(serializers.ModelSerializer):
#     links = serializers.SerializerMethodField()
#     violation_info = serializers.SerializerMethodField()
# 
#     class Meta:
#         model = Job
#         fields = ('id', 'name', 'description',
#                   'svn_url', 'svn_username', 'svn_password',
#                   'recipient', 'violation_threshold_num', 'links', 'violation_info')
# 
#     def get_violation_info(self, obj):
#         last_builds = obj.builds.order_by('-number')[:1]
#         violation_info = {
#             "violation_file_num": -1,
#             'violation_num': -1,
#             'created': '0-0-0 0:0:0',
#             'health_url': '/static/img/rain.png',
#             'report_url': ''
#         }
#         if not last_builds:
#             return violation_info
#         last_build = last_builds[0]
#         build_info = json.loads(last_build.result)
# 
#         violation_info = build_info['violation_info']
#         if violation_info['violation_num'] >= obj.violation_threshold_num:
#             health_url = '/static/img/rain.png'
#         else:
#             health_url = '/static/img/sun.png'
# 
#         violation_info.update({
#             'created': build_info['datetime'],
#             'health_url': health_url,
#             'report_url': settings.JENKINS_URL + '/job/{job_name}/violations/'.format(job_name=obj.name)
#         })
# 
#         return violation_info
# 
#     def get_links(self, obj):
#         request = self.context['request']
#         return {
#             'self': reverse('job-detail', kwargs={'pk': obj.pk}, request=request)
#         }


# Path: src/app/views.py
import json
import logging
from django.conf import settings
from django.shortcuts import get_object_or_404
from rest_framework import authentication, filters, permissions, viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from lintjenkins import LintJenkins
from silk.profiling.profiler import silk_profile
from .models import Build, Job
from .serializers import BuildSerializer, JobSerializer

        job_info = serializer.data
        logger.info(job_info)
        try:
            lint_jenkins.add_job(svn=str(job_info['svn_url']),
                                 username=str(job_info['svn_username']),
                                 password=str(job_info['svn_password']),
                                 job_name=str(job_info['name']))
        except Exception as e:
            logger.exception(e)
            Job.objects.filter(id=job_info['id']).delete()
            raise Exception(e)

        logger.info('create params:%s', serializer.data)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            serializer.data.sort(key=lambda x: x['violation_info']['violation_num'], reverse=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        serializer.data.sort(key=lambda x: x['violation_info']['violation_num'], reverse=True)
        return Response(serializer.data)


class BuildViewSet(DefaultsMixin, viewsets.ModelViewSet):
    queryset = Build.objects.all()

    serializer_class = BuildSerializer