src/ldt/ldt/ldt_utils/views.py
changeset 71 8a881c9593d0
parent 69 784ebba76424
child 75 655b017251fa
equal deleted inserted replaced
69:784ebba76424 71:8a881c9593d0
    30 import lxml.etree
    30 import lxml.etree
    31 import mimetypes
    31 import mimetypes
    32 import os
    32 import os
    33 import urllib2
    33 import urllib2
    34 
    34 
       
    35 from django.views.decorators.csrf import csrf_exempt
       
    36 
       
    37 
    35 @login_required
    38 @login_required
    36 def workspace(request):
    39 def workspace(request):
    37 
    40 
    38     # list of contents
    41     # list of contents
    39     content_list = Content.objects.all() #@UndefinedVariable
    42     content_list = Content.objects.all() #@UndefinedVariable
   668                     cleaned_data['videopath'] = settings.STREAM_URL
   671                     cleaned_data['videopath'] = settings.STREAM_URL
   669                 # if the source is already http:// or rtmp:// we don't have to add STREAM_URL
   672                 # if the source is already http:// or rtmp:// we don't have to add STREAM_URL
   670                 if cleaned_data['src'].startswith("rtmp://") or cleaned_data['src'].startswith("http://"):
   673                 if cleaned_data['src'].startswith("rtmp://") or cleaned_data['src'].startswith("http://"):
   671                     cleaned_data['videopath'] = ''
   674                     cleaned_data['videopath'] = ''
   672                 media, created = Media.objects.get_or_create(src=cleaned_data['src'], defaults=cleaned_data) #@UndefinedVariable
   675                 media, created = Media.objects.get_or_create(src=cleaned_data['src'], defaults=cleaned_data) #@UndefinedVariable
   673             elif media_input_type == "url" or  media_input_type == "upload" :                
   676             elif media_input_type == "url" or media_input_type == "upload" :                
   674                 # copy file
   677                 # copy file
   675                 #complet src
   678                 #complet src
   676                 destination_file = None
   679                 destination_file = None
   677                 source_file = None
   680                 source_file = None
   678                 try:
   681                 try:
   681                         source_file = urllib2.urlopen(url)
   684                         source_file = urllib2.urlopen(url)
   682                         source_filename = source_file.info().get('Content-Disposition', None)
   685                         source_filename = source_file.info().get('Content-Disposition', None)
   683                         if not source_filename:
   686                         if not source_filename:
   684                             source_filename = urlparse.urlparse(url).path.rstrip("/").split('/')[-1]
   687                             source_filename = urlparse.urlparse(url).path.rstrip("/").split('/')[-1]
   685                     elif media_input_type == "upload":
   688                     elif media_input_type == "upload":
   686                         source_file = request.FILES['media-media_file']
   689                         #source_file = request.FILES['media-media_file']
   687                         source_filename = source_file.name
   690                         # At this point the file has already be uploaded thanks to the upload view, and original file name is sent through a post var
       
   691                         source_filename = request.POST["media-local_file_name"]
   688                     
   692                     
   689                     source_filename = ldt_utils_path.sanitize_filename(source_filename)
   693                     source_filename = ldt_utils_path.sanitize_filename(source_filename)
   690                     destination_filepath = os.path.join(settings.STREAM_PATH, source_filename)
   694                     destination_filepath = os.path.join(settings.STREAM_PATH, source_filename)
   691                     base_source_filename = source_filename
   695                     base_source_filename = source_filename
   692                     extension = base_source_filename.split(".")[-1]
   696                     extension = base_source_filename.split(".")[-1]
   694                         extension = ""
   698                         extension = ""
   695                         base_basename_filename = base_source_filename
   699                         base_basename_filename = base_source_filename
   696                     else:
   700                     else:
   697                         base_basename_filename = base_source_filename[:-1 * (len(extension) + 1)]
   701                         base_basename_filename = base_source_filename[:-1 * (len(extension) + 1)]
   698                     i = 0
   702                     i = 0
       
   703                     init_path = destination_filepath
       
   704                     init_name = source_filename
   699                     while os.path.exists(destination_filepath):
   705                     while os.path.exists(destination_filepath):
   700                         base_source_filename = "%s.%d.%s" % (base_basename_filename, i, extension)
   706                         base_source_filename = "%s.%d.%s" % (base_basename_filename, i, extension)
   701                         destination_filepath = os.path.join(settings.STREAM_PATH, base_source_filename)
   707                         destination_filepath = os.path.join(settings.STREAM_PATH, base_source_filename)
   702                         i += 1
   708                         i += 1
       
   709                     
       
   710                     if media_input_type == "url":
       
   711                         # we upload the file if we are in url case
       
   712                         destination_file = open(destination_filepath, "wb")
       
   713                         chunck = source_file.read(2048)
       
   714                         while chunck:
       
   715                             destination_file.write(chunck)
       
   716                             chunck = source_file.read(2048)
   703                         
   717                         
   704                     destination_file = open(destination_filepath, "w")
   718                     elif media_input_type == "upload":
       
   719                         # Since the file names have been 1 iteration too far, we rebuild the existing file name
       
   720                         if i == 1 :
       
   721                             base_source_filename = init_name
       
   722                             destination_filepath = init_path
       
   723                         else :
       
   724                             i -= 2
       
   725                             base_source_filename = "%s.%d.%s" % (base_basename_filename, i, extension)
       
   726                             destination_filepath = os.path.join(settings.STREAM_PATH, base_source_filename)
       
   727                     
       
   728                     
   705                     src_prefix = settings.STREAM_SRC_PREFIX.rstrip("/")
   729                     src_prefix = settings.STREAM_SRC_PREFIX.rstrip("/")
   706                     if len(src_prefix) > 0:
   730                     if len(src_prefix) > 0:
   707                         cleaned_data["src"] = src_prefix + "/" + base_source_filename
   731                         cleaned_data["src"] = src_prefix + "/" + base_source_filename
   708                     else:
   732                     else:
   709                         cleaned_data["src"] = base_source_filename
   733                         cleaned_data["src"] = base_source_filename
   710                     
   734                     
   711                     chunck = source_file.read(2048)
   735                     
   712                     while chunck:
       
   713                         destination_file.write(chunck)
       
   714                         chunck = source_file.read(2048)
       
   715         
       
   716                 except Exception as inst:
   736                 except Exception as inst:
   717                     logging.debug("write_content_base : POST error when processing file:" + str(inst)) #@UndefinedVariable
   737                     logging.debug("write_content_base : POST error when processing file:" + str(inst)) #@UndefinedVariable
   718                     form_status = "error"
   738                     form_status = "error"
   719                     #set error for form
   739                     #set error for form
   720                     if media_input_type == "url":
   740                     if media_input_type == "url":
   721                         errors = media_form._errors.setdefault("external_src_url", ErrorList())
   741                         errors = media_form._errors.setdefault("external_src_url", ErrorList())
   722                         errors.append(_("Problem when downloading file from url : ") + str(inst))
   742                         errors.append(_("Problem when downloading file from url : ") + url)
   723                     elif media_input_type == "upload":
   743                     elif media_input_type == "upload":
   724                         errors = media_form._errors.setdefault("media_file", ErrorList())
   744                         errors = media_form._errors.setdefault("media_file", ErrorList())
   725                         errors.append(_("Problem when uploading file : ") + str(inst))
   745                         errors.append(_("Problem when uploading file : ") + str(inst))
   726                 finally:
   746                 finally:
   727                     if destination_file:
   747                     if media_input_type == "url":
   728                         destination_file.close()
   748                         if destination_file:
   729                     if source_file:
   749                             destination_file.close()
   730                         source_file.close()
   750                         if source_file:
   731                         
   751                             source_file.close()
       
   752                 
   732                 if form_status != "error":
   753                 if form_status != "error":
   733                     #try:
   754                     #try:
   734                     del cleaned_data["media_file"]
   755                     del cleaned_data["media_file"]
   735                     if not cleaned_data['videopath']:
   756                     if not cleaned_data['videopath']:
   736                         cleaned_data['videopath'] = settings.STREAM_URL
   757                         cleaned_data['videopath'] = settings.STREAM_URL
   739                         mimetype = mimetypes.guess_type(cleaned_data['src'])
   760                         mimetype = mimetypes.guess_type(cleaned_data['src'])
   740                     cleaned_data['mimetype_field'] = mimetype
   761                     cleaned_data['mimetype_field'] = mimetype
   741                     media, created = Media.objects.get_or_create(src=cleaned_data['src'], defaults=cleaned_data) #@UndefinedVariable
   762                     media, created = Media.objects.get_or_create(src=cleaned_data['src'], defaults=cleaned_data) #@UndefinedVariable
   742                 else:
   763                 else:
   743                     media = None
   764                     media = None
       
   765                     
   744 
   766 
   745             if media and not created:
   767             if media and not created:
   746                 for attribute in ('external_id', 'external_permalink', 'external_publication_url', 'external_src_url', 'media_creation_date', 'videopath', 'duration', 'description', 'title'):
   768                 for attribute in ('external_id', 'external_permalink', 'external_publication_url', 'external_src_url', 'media_creation_date', 'videopath', 'duration', 'description', 'title'):
   747                     setattr(media, attribute, cleaned_data.get(attribute))
   769                     setattr(media, attribute, cleaned_data.get(attribute))
   748                 mimetype = cleaned_data.get('mimetype_field', None)
   770                 mimetype = cleaned_data.get('mimetype_field', None)
   807     if iri_id:
   829     if iri_id:
   808         create_content_action = reverse('ldt.ldt_utils.views.write_content', kwargs={'iri_id':iri_id})
   830         create_content_action = reverse('ldt.ldt_utils.views.write_content', kwargs={'iri_id':iri_id})
   809     else:
   831     else:
   810         create_content_action = reverse('ldt.ldt_utils.views.write_content')
   832         create_content_action = reverse('ldt.ldt_utils.views.write_content')
   811     
   833     
   812     return render_to_response('ldt/ldt_utils/create_content.html', {'content_form': content_form, 'media_form': media_form, 'form_status': form_status, 'create_content_action': create_content_action, 'iri_id': iri_id}, context_instance=RequestContext(request))
   834     session_key = request.COOKIES[settings.SESSION_COOKIE_NAME]
       
   835     cookie_name = settings.SESSION_COOKIE_NAME
       
   836     
       
   837     return render_to_response('ldt/ldt_utils/create_content.html', {'content_form': content_form, 'media_form': media_form, 'form_status': form_status, 'create_content_action': create_content_action, 'iri_id': iri_id, 'session_key':session_key, 'cookie_name':cookie_name}, context_instance=RequestContext(request))
   813 
   838 
   814 @login_required
   839 @login_required
   815 def prepare_delete_content(request, iri_id=None):
   840 def prepare_delete_content(request, iri_id=None):
   816     errors = []
   841     errors = []
   817     titles = []
   842     titles = []
   836     if not iri_id:
   861     if not iri_id:
   837         iri_id = request.REQUEST.get("iri_id", None)
   862         iri_id = request.REQUEST.get("iri_id", None)
   838         
   863         
   839     if iri_id:
   864     if iri_id:
   840         Content.objects.filter(iri_id=iri_id).delete() #@UndefinedVariable
   865         Content.objects.filter(iri_id=iri_id).delete() #@UndefinedVariable
   841     
   866 
       
   867 
       
   868 def upload(request):
       
   869     if request.method == 'POST':
       
   870         for field_name in request.FILES:
       
   871             # We get the file name
       
   872             source_file = request.FILES[field_name]
       
   873             source_filename = source_file.name
       
   874             # We sanitize the file name : no space, only lower case.
       
   875             source_filename = ldt_utils_path.sanitize_filename(source_filename)
       
   876             destination_filepath = os.path.join(settings.STREAM_PATH, source_filename)
       
   877             base_source_filename = source_filename
       
   878             extension = base_source_filename.split(".")[-1]
       
   879             if extension == base_source_filename:
       
   880                 extension = ""
       
   881                 base_basename_filename = base_source_filename
       
   882             else:
       
   883                 base_basename_filename = base_source_filename[:-1 * (len(extension) + 1)]
       
   884             i = 0
       
   885             # We search if there is already a file with the same name, and rename the target by name.X.ext
       
   886             while os.path.exists(destination_filepath):
       
   887                 base_source_filename = "%s.%d.%s" % (base_basename_filename, i, extension)
       
   888                 destination_filepath = os.path.join(settings.STREAM_PATH, base_source_filename)
       
   889                 i += 1
       
   890                 
       
   891             destination_file = open(destination_filepath, "wb")
       
   892             
       
   893             for chunk in source_file.chunks():
       
   894                 destination_file.write(chunk)
       
   895             destination_file.close()
       
   896             
       
   897 
       
   898         # indicate that everything is OK for SWFUpload
       
   899         return HttpResponse("ok", mimetype="text/plain")
       
   900     else:
       
   901         return HttpResponse("notok", mimetype="text/plain")
       
   902