<commit_before># Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
import models
import forms
from mozpackager.MozPackager import MozPackage
from tasks import build_package
from mozpackager.settings import BUILD_DIR
from mozpackager.settings.local import README_PATH
from django.core.servers.basehttp import FileWrapper
import mimetypes
import os
from django.db.models import Q
import operator
import json
from django.views.decorators.csrf import csrf_exempt
import markdown2
import commonware.log
log = commonware.log.getLogger('playdoh')
#import logging
#log = logging.getLogger('mozpackager')

@csrf_exempt
def search(request):
    search = request.POST.get('search', None)
    packages = []
    if search:
        filters = [Q(**{"%s__icontains" % t: search})
                        for t in models.MozillaPackage.search_fields]
        packages = models.MozillaPackage.objects.filter(
                    reduce(operator.or_, filters)).order_by('-created_on')
    return render_to_response('search_results.html',
            { 
                'packages': packages
            },
            RequestContext(request) )

def detail(request, id):
    instance = get_object_or_404(models.MozillaPackage, id=id)
    try:
        dependencies = [n.name for n in instance.mozillapackagedependency_set.all()]
    except:
        dependencies= []
    try:
        system_dependencies = [n.name for n in instance.mozillapackagesystemdependency_set.all()]
    except:
        system_pendencies= []
    return render_to_response('package_detail.html',
            { 
                'dependencies': dependencies,
                'system_dependencies': system_dependencies,
                'package': instance },
            RequestContext(request) )

@csrf_exempt
def build_from_build_source(request, id):
    return_dict = {}
    return_dict['status'] = 'OK'
    return_dict['message'] = 'No Post Received'
    if request.method == 'POST':
        try:
            test = request.POST.get('test', False)
            build_source = models.MozillaBuildSource.objects.get(id=id)
            package_build = models.MozillaPackageBuild()
            package_build.mozilla_package = build_source.mozilla_package
            package_build.arch_type = request.POST.get('arch_type')
            package_build.output_type = request.POST.get('build_type')
            package_build.build_source = build_source
            package_build.save()

            if not test:
                result = build_package.apply_async(args=[],kwargs = { 'package_build_id': package_build.id},
                        queue='rhel-6-x86_64',
                        routing_key='rhel-6-x86_64.build')
            else:
                import random, string
                result = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32))
            package_build.celery_id = result
            package_build.save()
            return_dict['message'] = 'Build Source Created'
        except models.MozillaBuildSource.DoesNotExist:
            return_dict['status'] = 'FAIL'
            return_dict['message'] = 'Could not find Build Source with id: %s' % id


    return HttpResponse(json.dumps(return_dict))

def delete_package_build(request, id):
    return_dict = {}
    return_dict['status'] = 'OK'
    try:
        build_source = models.MozillaPackageBuild.objects.get(id=id)
        build_source.delete()
        return_dict['message'] = 'Build Package Deleted'
    except models.MozillaPackageBuild.DoesNotExist:
        return_dict['status'] = 'FAIL'
        return_dict['message'] = 'Could not find Build Package with id: %s' % id


    return HttpResponse(json.dumps(return_dict))
def delete_build_source(request, id):
    return_dict = {}
    return_dict['status'] = 'OK'
    try:
        build_source = models.MozillaBuildSource.objects.get(id=id)
        build_source.delete()
        return_dict['message'] = 'Build Source Deleted'
    except models.MozillaBuildSource.DoesNotExist:
        return_dict['status'] = 'FAIL'
        return_dict['message'] = 'Could not find Build Source with id: %s' % id


    return HttpResponse(json.dumps(return_dict))

def get_build_sources(request, id):
    return_dict = {}
    try:
        mozilla_package = models.MozillaPackage.objects.get(id=id)
    except models.MozillaPackage.DoesNotExist:
        return_dict['status'] = 'FAIL'
        return_dict['message'] = 'Could not find Mozilla Package with id:%s' % id
        return HttpResponse(json.dumps(return_dict))
    return_dict['status'] = 'OK'
    return_dict['sources'] = []
    for source in mozilla_package.mozillabuildsource_set.all():
        tmp = {}
        tmp['id'] = source.id
        tmp['build_source_type'] = source.build_type
        tmp['build_source'] = source.remote_package_name
        tmp['system_dependencies'] = source.system_dependency_string
        tmp['package_dependencies'] = source.package_dependency_string
        tmp['remote_package_name'] = source.remote_package_name
        tmp['get_build_url'] = source.get_build_url()
        tmp['get_delete_url'] = source.get_delete_url()
        if source.build_source_file:
            tmp['build_source_file_name'] = str(source.build_source_file.source_file).replace("uploads/", "")
        else:
            tmp['build_source_file_name'] = ''
        return_dict['sources'].append(tmp)

    return HttpResponse(json.dumps(return_dict))
def package_build_logs(request, id):
    mozilla_build_package = models.MozillaPackageBuild.objects.get(id=id)
    log_output = ''
    logs = mozilla_build_package.mozillapackagelog_set.all()
    for log in logs:
        log_output += "<div class='log_output_header'>%s</div>" % log.log_type
        log_output += "<div class='log_output_content'>%s</div>" % log.log_message.replace('\n', '<br />')

    return HttpResponse(log_output)

    return HttpResponse('asdfasdfsdf');
def get_package_builds(request, id):
    return_dict = {}
    try:
        mozilla_package = models.MozillaPackage.objects.get(id=id)
    except models.MozillaPackage.DoesNotExist:
        return_dict['status'] = 'FAIL'
        return_dict['message'] = 'Could not find Mozilla Package with id:%s' % id
        return HttpResponse(json.dumps(return_dict))
    return_dict['status'] = 'OK'
    return_dict['package_builds'] = []
    for package in mozilla_package.mozillapackagebuild_set.all().order_by('-id'):
        tmp = {}
        tmp['id'] = package.id
        if package.build_package_name:
            tmp['name'] = package.build_package_name
        else:
            tmp['name'] = ''
        if package.build_source.build_type == 'gem' or package.build_source.build_type == 'python':
            tmp['build_source_type'] = package.build_source.build_type
            tmp['build_source'] = package.build_source.remote_package_name
        else:
            tmp['build_source_type'] = 'Uploaded File'
            tmp['build_source'] = str(package.build_source.build_source_file.source_file).replace("uploads/", "")
            
        tmp['build_status'] = package.build_status
        """tmp['build_source_type'] = source.build_type
        tmp['build_source'] = source.remote_package_name
        tmp['system_dependencies'] = source.system_dependency_string
        tmp['package_dependencies'] = source.package_dependency_string
        tmp['remote_package_name'] = source.remote_package_name
        tmp['get_build_url'] = source.get_build_url()
        tmp['get_delete_url'] = source.get_delete_url()
        if source.build_source_file:<commit_msg>Added is_signed to json output in view<commit_after># Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
import models
import forms
from mozpackager.MozPackager import MozPackage
from tasks import build_package
from mozpackager.settings import BUILD_DIR
from mozpackager.settings.local import README_PATH
from django.core.servers.basehttp import FileWrapper
import mimetypes
import os
from django.db.models import Q
import operator
import json
from django.views.decorators.csrf import csrf_exempt
import markdown2
import commonware.log
log = commonware.log.getLogger('playdoh')
#import logging
#log = logging.getLogger('mozpackager')

@csrf_exempt
def search(request):
    search = request.POST.get('search', None)
    packages = []
    if search:
        filters = [Q(**{"%s__icontains" % t: search})
                        for t in models.MozillaPackage.search_fields]
        packages = models.MozillaPackage.objects.filter(
                    reduce(operator.or_, filters)).order_by('-created_on')
    return render_to_response('search_results.html',
            { 
                'packages': packages
            },
            RequestContext(request) )

def detail(request, id):
    instance = get_object_or_404(models.MozillaPackage, id=id)
    try:
        dependencies = [n.name for n in instance.mozillapackagedependency_set.all()]
    except:
        dependencies= []
    try:
        system_dependencies = [n.name for n in instance.mozillapackagesystemdependency_set.all()]
    except:
        system_pendencies= []
    return render_to_response('package_detail.html',
            { 
                'dependencies': dependencies,
                'system_dependencies': system_dependencies,
                'package': instance },
            RequestContext(request) )

@csrf_exempt
def build_from_build_source(request, id):
    return_dict = {}
    return_dict['status'] = 'OK'
    return_dict['message'] = 'No Post Received'
    if request.method == 'POST':
        try:
            test = request.POST.get('test', False)
            build_source = models.MozillaBuildSource.objects.get(id=id)
            package_build = models.MozillaPackageBuild()
            package_build.mozilla_package = build_source.mozilla_package
            package_build.arch_type = request.POST.get('arch_type')
            package_build.output_type = request.POST.get('build_type')
            package_build.build_source = build_source
            package_build.save()

            if not test:
                result = build_package.apply_async(args=[],kwargs = { 'package_build_id': package_build.id},
                        queue='rhel-6-x86_64',
                        routing_key='rhel-6-x86_64.build')
            else:
                import random, string
                result = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32))
            package_build.celery_id = result
            package_build.save()
            return_dict['message'] = 'Build Source Created'
        except models.MozillaBuildSource.DoesNotExist:
            return_dict['status'] = 'FAIL'
            return_dict['message'] = 'Could not find Build Source with id: %s' % id


    return HttpResponse(json.dumps(return_dict))

def delete_package_build(request, id):
    return_dict = {}
    return_dict['status'] = 'OK'
    try:
        build_source = models.MozillaPackageBuild.objects.get(id=id)
        build_source.delete()
        return_dict['message'] = 'Build Package Deleted'
    except models.MozillaPackageBuild.DoesNotExist:
        return_dict['status'] = 'FAIL'
        return_dict['message'] = 'Could not find Build Package with id: %s' % id


    return HttpResponse(json.dumps(return_dict))
def delete_build_source(request, id):
    return_dict = {}
    return_dict['status'] = 'OK'
    try:
        build_source = models.MozillaBuildSource.objects.get(id=id)
        build_source.delete()
        return_dict['message'] = 'Build Source Deleted'
    except models.MozillaBuildSource.DoesNotExist:
        return_dict['status'] = 'FAIL'
        return_dict['message'] = 'Could not find Build Source with id: %s' % id


    return HttpResponse(json.dumps(return_dict))

def get_build_sources(request, id):
    return_dict = {}
    try:
        mozilla_package = models.MozillaPackage.objects.get(id=id)
    except models.MozillaPackage.DoesNotExist:
        return_dict['status'] = 'FAIL'
        return_dict['message'] = 'Could not find Mozilla Package with id:%s' % id
        return HttpResponse(json.dumps(return_dict))
    return_dict['status'] = 'OK'
    return_dict['sources'] = []
    for source in mozilla_package.mozillabuildsource_set.all():
        tmp = {}
        tmp['id'] = source.id
        tmp['build_source_type'] = source.build_type
        tmp['build_source'] = source.remote_package_name
        tmp['system_dependencies'] = source.system_dependency_string
        tmp['package_dependencies'] = source.package_dependency_string
        tmp['remote_package_name'] = source.remote_package_name
        tmp['get_build_url'] = source.get_build_url()
        tmp['get_delete_url'] = source.get_delete_url()
        if source.build_source_file:
            tmp['build_source_file_name'] = str(source.build_source_file.source_file).replace("uploads/", "")
        else:
            tmp['build_source_file_name'] = ''
        return_dict['sources'].append(tmp)

    return HttpResponse(json.dumps(return_dict))
def package_build_logs(request, id):
    mozilla_build_package = models.MozillaPackageBuild.objects.get(id=id)
    log_output = ''
    logs = mozilla_build_package.mozillapackagelog_set.all()
    for log in logs:
        log_output += "<div class='log_output_header'>%s</div>" % log.log_type
        log_output += "<div class='log_output_content'>%s</div>" % log.log_message.replace('\n', '<br />')

    return HttpResponse(log_output)

    return HttpResponse('asdfasdfsdf');
def get_package_builds(request, id):
    return_dict = {}
    try:
        mozilla_package = models.MozillaPackage.objects.get(id=id)
    except models.MozillaPackage.DoesNotExist:
        return_dict['status'] = 'FAIL'
        return_dict['message'] = 'Could not find Mozilla Package with id:%s' % id
        return HttpResponse(json.dumps(return_dict))
    return_dict['status'] = 'OK'
    return_dict['package_builds'] = []
    for package in mozilla_package.mozillapackagebuild_set.all().order_by('-id'):
        tmp = {}
        tmp['id'] = package.id
        if package.build_package_name:
            tmp['name'] = package.build_package_name
        else:
            tmp['name'] = ''
        if package.build_source.build_type == 'gem' or package.build_source.build_type == 'python':
            tmp['build_source_type'] = package.build_source.build_type
            tmp['build_source'] = package.build_source.remote_package_name
        else:
            tmp['build_source_type'] = 'Uploaded File'
            tmp['build_source'] = str(package.build_source.build_source_file.source_file).replace("uploads/", "")
            
        tmp['build_status'] = package.build_status
        tmp['is_signed'] = package.is_signed
        """tmp['build_source_type'] = source.build_type
        tmp['build_source'] = source.remote_package_name
        tmp['system_dependencies'] = source.system_dependency_string
        tmp['package_dependencies'] = source.package_dependency_string
        tmp['remote_package_name'] = source.remote_package_name
        tmp['get_build_url'] = source.get_build_url()
        tmp['get_delete_url'] = source.get_delete_url()
        if source.build_source_file:
{'fraction_non_alphanumeric': 0.10951045385007649, 'fraction_numerical': 0.002422233554309026, 'mean_word_length': 3.1341238471673254, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '750431', 'n_tokens_mistral': 4673, 'n_tokens_neox': 4554, 'n_words': 853}