first step for mashup json.
authorcavaliet
Mon, 30 Jul 2012 18:23:34 +0200
changeset 713 202fb1255d8b
parent 712 8956317d331c
child 714 a25d344cb446
first step for mashup json.
.settings/org.eclipse.core.resources.prefs
src/ldt/ldt/ldt_utils/projectserializer.py
src/ldt/ldt/ldt_utils/urls.py
src/ldt/ldt/ldt_utils/utils.py
src/ldt/ldt/ldt_utils/views/json.py
src/ldt/ldt/ldt_utils/views/lignesdetemps.py
--- a/.settings/org.eclipse.core.resources.prefs	Wed Jul 25 17:43:35 2012 +0200
+++ b/.settings/org.eclipse.core.resources.prefs	Mon Jul 30 18:23:34 2012 +0200
@@ -1,3 +1,4 @@
+#Fri Jul 27 18:53:06 CEST 2012
 eclipse.preferences.version=1
 encoding//src/ldt/ldt/core/migrations/0001_initial.py=utf-8
 encoding//src/ldt/ldt/core/migrations/0002_auto__del_owner.py=utf-8
@@ -12,6 +13,7 @@
 encoding//src/ldt/ldt/ldt_utils/migrations/0011_gen_stat_annotation.py=utf-8
 encoding//src/ldt/ldt/ldt_utils/migrations/0015_auto__add_contentstat__del_field_content_last_annotated__del_field_con.py=utf-8
 encoding//src/ldt/ldt/ldt_utils/migrations/0017_correct_image_path.py=utf-8
+encoding//src/ldt/ldt/ldt_utils/views/json.py=utf-8
 encoding//src/ldt/ldt/management/utils.py=utf-8
 encoding//src/ldt/ldt/text/migrations/0001_initial.py=utf-8
 encoding//src/ldt/ldt/user/migrations/0001_initial.py=utf-8
--- a/src/ldt/ldt/ldt_utils/projectserializer.py	Wed Jul 25 17:43:35 2012 +0200
+++ b/src/ldt/ldt/ldt_utils/projectserializer.py	Mon Jul 30 18:23:34 2012 +0200
@@ -303,8 +303,7 @@
             
         res = self.ldt_doc.xpath("/iri/annotations/content")
         for content_node in res:
-            content_id = content_node.attrib[u"id"]               
-            
+            content_id = content_node.attrib[u"id"]
             if self.from_display and content_id not in self.display_contents_list:
                 continue
             content = Content.objects.get(iri_id=content_id) #@UndefinedVariable
@@ -317,14 +316,11 @@
                 self.__parse_ensemble(ensemble_node, content)
                 
         if self.first_cutting and self.first_cutting not in self.display_cuttings_list:
-            
             cutting_node= self.ldt_doc.xpath('/iri/annotations/content/ensemble/decoupage[@id=\'%s\']' % self.first_cutting)[0]
             ensemble_node = cutting_node.xpath('..')[0]
-            content_node = ensemble_node.xpath('..')[0]            
-            
+            content_node = ensemble_node.xpath('..')[0]
             iri_id = content_node.get("id")
-            content = Content.objects.get(iri_id=iri_id)
-            
+            content = Content.objects.get(iri_id=iri_id)            
             self.__parse_ensemble(ensemble_node, content, cutting_only=[cutting_node])
             
         
--- a/src/ldt/ldt/ldt_utils/urls.py	Wed Jul 25 17:43:35 2012 +0200
+++ b/src/ldt/ldt/ldt_utils/urls.py	Mon Jul 30 18:23:34 2012 +0200
@@ -46,6 +46,7 @@
     url(r'^front/player/(?P<content_iri_id>.*)/(?P<project_id>.*)/(?P<cutting_id>.*)$', 'views.front.annot_content'),
     url(r'^front/search/$', 'views.front.search_index'),
     url(r'^front/medias', 'views.front.all_contents'),
+    url(r'^mashupbytag/$', 'views.json.mashup_by_tag'),
 )
 
 urlpatterns += patterns('',
--- a/src/ldt/ldt/ldt_utils/utils.py	Wed Jul 25 17:43:35 2012 +0200
+++ b/src/ldt/ldt/ldt_utils/utils.py	Mon Jul 30 18:23:34 2012 +0200
@@ -56,7 +56,7 @@
 
 class LdtUtils(object):
     
-    def generate_ldt(self, contentList, title=u"", author=u"IRI Web", web_url=u"", startSegment=None, projects=None):
+    def generate_ldt(self, contentList, title=u"", author=u"IRI Web", web_url=u"", startSegment=None, projects=None, types_id_list=None):
 
         iri = lxml.etree.Element(u'iri')
         doc = lxml.etree.ElementTree(iri)
@@ -132,6 +132,19 @@
                     decoupage = lxml.etree.SubElement(contentd, "decoupage")
                     decoupage.set(u"id", decoupage_id)
                     decoupage.set(u"idens", ensemble_id)
+                # We add the project's decoupages in the generated project
+                if len(annotations_nodes) > 0:
+                    if content.iri_id in annotations_nodes:
+                        contentnode = annotations_nodes[content.iri_id]
+                        if contentnode is not None:
+                            for ens in contentnode["ensembles"]:
+                                for decoupagenode in ens:
+                                    type_id = decoupagenode.get(u"id")
+                                    if type_id in types_id_list:
+                                        decoupage = lxml.etree.SubElement(contentd, "decoupage")
+                                        decoupage.set(u"id", decoupagenode.get(u"id"))
+                                        decoupage.set(u"idens", ens.get(u"id"))
+            
             if startSegment is not None:
                 activeSegment = lxml.etree.SubElement(display, "activeSegment")
                 idas = lxml.etree.SubElement(activeSegment, "id")
--- a/src/ldt/ldt/ldt_utils/views/json.py	Wed Jul 25 17:43:35 2012 +0200
+++ b/src/ldt/ldt/ldt_utils/views/json.py	Mon Jul 30 18:23:34 2012 +0200
@@ -1,12 +1,17 @@
+# -*- 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): 
@@ -72,3 +77,74 @@
     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
--- a/src/ldt/ldt/ldt_utils/views/lignesdetemps.py	Wed Jul 25 17:43:35 2012 +0200
+++ b/src/ldt/ldt/ldt_utils/views/lignesdetemps.py	Mon Jul 30 18:23:34 2012 +0200
@@ -30,24 +30,30 @@
     resp.write(lxml.etree.tostring(doc, pretty_print=True, encoding="utf-8")) 
     return resp
 
-def search_ldt(request, field, query, edition=None): 
+def search_ldt(request, field, query, edition=None, return_project=False, query_encoded=True): 
     
     contentList = []
     resp = HttpResponse(mimetype="text/xml")
     queryStr = ""
 
-    if query and len(query) > 0:        
-        queryStr = base64.urlsafe_b64decode(query.encode("ascii")).decode("utf8")
+    if query and len(query) > 0: 
+        if query_encoded:
+            queryStr = base64.urlsafe_b64decode(query.encode("ascii")).decode("utf8")
+        else:
+            queryStr = query
         searcher = LdtSearch()
         ids = {}
         projIds = {}
+        typesIds = {}
         
         for result in searcher.query(field, queryStr):
             ids[result["iri_id"]] = ""
             projIds[result["project_id"]] = ""
+            typesIds[result["decoupage_id"]] = ""
 
         id_list = ids.keys()
         projId_list = projIds.keys()
+        typesId_list = typesIds.keys()
         
         #if edition is not None:
         #    ids_editions = map(lambda t:t[0], filter(lambda id: id[0] is not None, Speak.objects.filter(session__day__edition=edition).order_by("session__start_ts", "order").values_list("content__iri_id")))            
@@ -58,8 +64,10 @@
           
     ldtgen = LdtUtils()
     #            generate_ldt(contentList, title=u"", author=u"IRI Web", web_url=u"", startSegment=None, projects=None):
-    doc = ldtgen.generate_ldt(contentList, title=u"Recherche : " + queryStr, projects=projectList)
-    doc = set_forbidden_stream(doc, request.user)   
+    doc = ldtgen.generate_ldt(contentList, title=u"Recherche : " + queryStr, projects=projectList, types_id_list=typesId_list)
+    doc = set_forbidden_stream(doc, request.user)
+    if return_project:
+        return doc   
     doc.write(resp, pretty_print=True)
     
     return resp