src/ldt/ldt/ldt_utils/views/json.py
author cavaliet
Mon, 30 Jul 2012 18:23:34 +0200
changeset 713 202fb1255d8b
parent 691 ff0b66633807
child 714 a25d344cb446
permissions -rw-r--r--
first step for mashup json.

# -*- coding: utf-8 -*-
from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404, get_list_or_404
from django.utils import simplejson
from django.utils.html import escape
from django.utils.translation import ugettext as _
from ldt.indexation import get_results_with_context
from ldt.ldt_utils.models import Project
from ldt.ldt_utils.projectserializer import ProjectSerializer
from ldt.ldt_utils.views.lignesdetemps import search_ldt
from datetime import datetime
import ldt.auth as ldt_auth
import lxml.etree


def project_json_id(request, id): 
    
    project = get_object_or_404(Project.safe_objects, ldt_id=id)

    return project_json(request, project, False)

def project_json_cutting_id(request, id, cutting_id):

    project = get_object_or_404(Project.safe_objects, ldt_id=id)

    return project_json(request, project, first_cutting=cutting_id)

def project_json_externalid(request, id): 
        
    res_proj = get_list_or_404(Project.safe_objects.order_by('-modification_date'), contents__external_id=id) #@UndefinedVariable
    
    return project_json(request, res_proj[0], False)



def project_json(request, project, serialize_contents=True, first_cutting=None):
    
    if not ldt_auth.check_access(request.user, project):
        return HttpResponseForbidden(_("You can not access this project"))
        
    mimetype = request.REQUEST.get("mimetype")
    if mimetype is None:
        mimetype = "application/json; charset=utf-8"
    else:
        mimetype = mimetype.encode("utf-8")
    if "charset" not in mimetype:
        mimetype += "; charset=utf-8" 
    resp = HttpResponse(mimetype=mimetype)
    resp['Cache-Control'] = 'no-cache, must-revalidate'
    resp['Pragma'] = 'no-cache'
    
    indent = request.REQUEST.get("indent")
    if indent is None:
        indent = settings.LDT_JSON_DEFAULT_INDENT
    else:
        indent = int(indent)
    
    callback = request.REQUEST.get("callback")
    escape_str = request.REQUEST.get("escape")
    escape_bool = False
    if escape_str:
        escape_bool = {'true': True, 'false': False, "0": False, "1": True}.get(escape_str.lower())
        
        
    ps = ProjectSerializer(project, serialize_contents, first_cutting=first_cutting)
    project_dict = ps.serialize_to_cinelab()
    
    json_str = simplejson.dumps(project_dict, ensure_ascii=False, indent=indent)
    
    if callback is not None:
        json_str = "%s(%s)" % (callback, json_str)
    
    if escape_bool:
        json_str = escape(json_str)
    
    resp.write(json_str)

    return resp



def mashup_by_tag(request):
    mashup_dict = {
        "id": u"display_ïd",
        "contents": u"contenté_list",
        "annotation_types": u"çùttings_list",
    }
    
    # do we indent ?
    indent = request.REQUEST.get("indent")
    if indent is None:
        indent = settings.LDT_JSON_DEFAULT_INDENT
    else:
        indent = int(indent)
    # do we escape ?
    escape_str = request.REQUEST.get("escape")
    escape_bool = False
    if escape_str:
        escape_bool = {'true': True, 'false': False, "0": False, "1": True}.get(escape_str.lower())
    
    mashup_dict["escape_bool"] = escape_bool
    mashup_dict["indent"] = indent
    
    # We search
    s = request.REQUEST.get("tag")
    if s:
        #results = get_results_with_context("tags", s)
        
        # We get the projects with all the segments
        project_xml = search_ldt(request, "tags", s, None, True, False)
        project = Project()
        project.ldt = lxml.etree.tostring(project_xml, pretty_print=True)
        # Useful datas
        project.modification_date = project.creation_date = datetime.now()
        #return HttpResponse(lxml.etree.tostring(project_xml, pretty_print=True), mimetype="text/xml;charset=utf-8")
        ps = ProjectSerializer(project, from_contents=False)
        #project_dict = ps.serialize_to_cinelab()
        mashup_dict = ps.serialize_to_cinelab()
        
        
        
#        tc_in = 0
#        if request.REQUEST.get("in") :
#            tc_in = float(request.REQUEST.get("in"))
#        tc_out = float('inf')
#        if request.REQUEST.get("out") :
#            tc_out = float(request.REQUEST.get("out"))
#        # Since the timecodes are saved as strings, we filter after calculating float in and out. Timecodes have to be in milliseconds
#        filtered_results = []
#        for res in results:
#            cur_in = float(res["begin"])
#            cur_out = cur_in + float(res["duration"])
#            if tc_in<=cur_in and cur_out<=tc_out:
#                 filtered_results.append(res)
#        mashup_dict["results"] = filtered_results
    
    
    
    json_str = simplejson.dumps(mashup_dict, ensure_ascii=False, indent=indent)
    if escape_bool:
        json_str = escape(json_str)
    
    
    resp = HttpResponse(mimetype="application/json; charset=utf-8")
    resp['Cache-Control'] = 'no-cache, must-revalidate'
    resp['Pragma'] = 'no-cache'
    resp.write(json_str)
    
    return resp