split of write_content_base function : media management put in media_management() function
authorrougeronj
Thu, 08 Nov 2012 17:57:31 +0100
changeset 917 9251909ce0f2
parent 916 7a614efbaadb
child 918 c5d890348839
split of write_content_base function : media management put in media_management() function
src/ldt/ldt/ldt_utils/views/content.py
--- a/src/ldt/ldt/ldt_utils/views/content.py	Thu Nov 08 16:25:01 2012 +0100
+++ b/src/ldt/ldt/ldt_utils/views/content.py	Thu Nov 08 17:57:31 2012 +0100
@@ -34,6 +34,123 @@
 import urlparse
 #from django.core.files.temp import NamedTemporaryFile
 
+def media_management(request, media_input_type, cleaned_data, content_form, media_form, form_status):
+    if media_input_type == "none":
+                    media = None
+    elif media_input_type == "link":
+        media = content_form.cleaned_data["media_obj"]
+        created = False
+    elif media_input_type == "create":
+        del cleaned_data["media_file"]
+        if not cleaned_data['videopath']:
+            cleaned_data['videopath'] = settings.STREAM_URL
+        # if the source is already http:// or rtmp:// we don't have to add STREAM_URL
+        if cleaned_data['src'].startswith("rtmp://") or cleaned_data['src'].startswith("http://"):
+            cleaned_data['videopath'] = ''
+            
+            media, created = Media.objects.get_or_create(src=cleaned_data['src'], defaults=cleaned_data) #@UndefinedVariable
+    
+    elif media_input_type == "url" or media_input_type == "upload" :
+        # copy file
+        #complet src
+        destination_file = None
+        source_file = None
+        try:
+            if media_input_type == "url":
+                url = cleaned_data["external_src_url"]
+                source_file = urllib2.urlopen(url)
+                source_filename = source_file.info().get('Content-Disposition', None)
+                if not source_filename:
+                    source_filename = urlparse.urlparse(url).path.rstrip("/").split('/')[-1]
+            elif media_input_type == "upload":
+                #source_file = request.FILES['media-media_file']
+                # At this point the file has already be uploaded thanks to the upload view, and original file name is sent through a post var
+                source_filename = request.POST["media-local_file_name"]
+            
+            source_filename = ldt_utils_path.sanitize_filename(source_filename)
+            destination_filepath = os.path.join(settings.STREAM_PATH, source_filename)
+            base_source_filename = source_filename
+            extension = base_source_filename.split(".")[-1]
+            if extension == base_source_filename:
+                extension = ""
+                base_basename_filename = base_source_filename
+            else:
+                base_basename_filename = base_source_filename[:-1 * (len(extension) + 1)]
+            i = 0
+            
+            while os.path.exists(destination_filepath):
+                base_source_filename = "%s.%d.%s" % (base_basename_filename, i, extension)
+                destination_filepath = os.path.join(settings.STREAM_PATH, base_source_filename)
+                i += 1
+            
+            if media_input_type == "url":
+                # we upload the file if we are in url case
+                destination_file = open(destination_filepath, "wb")
+                chunck = source_file.read(2048)
+                while chunck:
+                    destination_file.write(chunck)
+                    chunck = source_file.read(2048)
+                
+            elif media_input_type == "upload":
+                # The media file has been uploaded in the session temp folder 
+                # so we just have to move to the regular folder and rename it.
+                if os.path.exists(os.path.join(settings.STREAM_PATH, "tmp/" + request.COOKIES[settings.SESSION_COOKIE_NAME] + "/", source_filename)):
+                    os.rename(os.path.join(settings.STREAM_PATH, "tmp/" + request.COOKIES[settings.SESSION_COOKIE_NAME] + "/", source_filename), os.path.join(settings.STREAM_PATH, base_source_filename))
+            
+            
+            src_prefix = settings.STREAM_SRC_PREFIX.rstrip("/")
+            if len(src_prefix) > 0:
+                cleaned_data["src"] = src_prefix + "/" + base_source_filename
+            else:
+                cleaned_data["src"] = base_source_filename
+            
+            
+        except Exception as inst:
+            logging.debug("write_content_base : POST error when processing file:" + str(inst)) #@UndefinedVariable
+            form_status = "error"
+            #set error for form
+            if media_input_type == "url":
+                errors = media_form._errors.setdefault("external_src_url", ErrorList())
+                errors.append(_("Problem when downloading file from url : ") + url)
+            elif media_input_type == "upload":
+                errors = media_form._errors.setdefault("media_file", ErrorList())
+                errors.append(_("Problem when uploading file : ") + str(inst))
+        finally:
+            if media_input_type == "url":
+                if destination_file:
+                    destination_file.close()
+                if source_file:
+                    source_file.close()
+        
+        
+        if form_status != "error":
+            del cleaned_data["media_file"]
+            if not cleaned_data['videopath']:
+                cleaned_data['videopath'] = settings.STREAM_URL
+            mimetype = cleaned_data.get('mimetype_field', None)
+            if not mimetype:
+                mimetype = mimetypes.guess_type(cleaned_data['src'])
+            cleaned_data['mimetype_field'] = mimetype
+            media, created = Media.safe_objects.get_or_create(src=cleaned_data['src'], defaults=cleaned_data) #@UndefinedVariable
+            cached_assign('view_media', request.user, media)
+        else:
+            media = None
+            
+
+    if media and not created:
+        for attribute in ('external_id', 'external_permalink', 'external_publication_url', 'external_src_url', 'media_creation_date', 'videopath', 'duration', 'description', 'title', 'front_project'):
+            setattr(media, attribute, cleaned_data.get(attribute))
+        mimetype = cleaned_data.get('mimetype_field', None)
+        if not mimetype:
+            mimetype = mimetypes.guess_type(media.src)
+        media.mimetype_field = mimetype
+        cached_assign('view_media', request.user, media)
+        cached_assign('change_media', request.user, media)
+        media.save()
+        
+    return media, form_status
+    
+    
 @transaction.commit_manually
 def write_content_base(request, iri_id=None):
     if iri_id:
@@ -88,6 +205,7 @@
             media_valid = media_form.is_valid()
             content_valid = content_form.is_valid()
             picture_valid = picture_form.is_valid()
+            
             if 'image' in request.POST.keys():
                 image_link = request.POST.get('url_image')
                 if picture_valid and image_link!='' :
@@ -111,118 +229,13 @@
                 
                 media_input_type = content_form.cleaned_data["media_input_type"]
                 
-                if media_input_type == "none":
-                    media = None
-                elif media_input_type == "link":
-                    media = content_form.cleaned_data["media_obj"]
-                    created = False
-                elif media_input_type == "create":
-                    del cleaned_data["media_file"]
-                    if not cleaned_data['videopath']:
-                        cleaned_data['videopath'] = settings.STREAM_URL
-                    # if the source is already http:// or rtmp:// we don't have to add STREAM_URL
-                    if cleaned_data['src'].startswith("rtmp://") or cleaned_data['src'].startswith("http://"):
-                        cleaned_data['videopath'] = ''
-                        
-                        media, created = Media.objects.get_or_create(src=cleaned_data['src'], defaults=cleaned_data) #@UndefinedVariable
+                
+                
                 
-                elif media_input_type == "url" or media_input_type == "upload" :
-                    # copy file
-                    #complet src
-                    destination_file = None
-                    source_file = None
-                    try:
-                        if media_input_type == "url":
-                            url = cleaned_data["external_src_url"]
-                            source_file = urllib2.urlopen(url)
-                            source_filename = source_file.info().get('Content-Disposition', None)
-                            if not source_filename:
-                                source_filename = urlparse.urlparse(url).path.rstrip("/").split('/')[-1]
-                        elif media_input_type == "upload":
-                            #source_file = request.FILES['media-media_file']
-                            # At this point the file has already be uploaded thanks to the upload view, and original file name is sent through a post var
-                            source_filename = request.POST["media-local_file_name"]
-                        
-                        source_filename = ldt_utils_path.sanitize_filename(source_filename)
-                        destination_filepath = os.path.join(settings.STREAM_PATH, source_filename)
-                        base_source_filename = source_filename
-                        extension = base_source_filename.split(".")[-1]
-                        if extension == base_source_filename:
-                            extension = ""
-                            base_basename_filename = base_source_filename
-                        else:
-                            base_basename_filename = base_source_filename[:-1 * (len(extension) + 1)]
-                        i = 0
-                        
-                        while os.path.exists(destination_filepath):
-                            base_source_filename = "%s.%d.%s" % (base_basename_filename, i, extension)
-                            destination_filepath = os.path.join(settings.STREAM_PATH, base_source_filename)
-                            i += 1
-                        
-                        if media_input_type == "url":
-                            # we upload the file if we are in url case
-                            destination_file = open(destination_filepath, "wb")
-                            chunck = source_file.read(2048)
-                            while chunck:
-                                destination_file.write(chunck)
-                                chunck = source_file.read(2048)
-                            
-                        elif media_input_type == "upload":
-                            # The media file has been uploaded in the session temp folder 
-                            # so we just have to move to the regular folder and rename it.
-                            if os.path.exists(os.path.join(settings.STREAM_PATH, "tmp/" + request.COOKIES[settings.SESSION_COOKIE_NAME] + "/", source_filename)):
-                                os.rename(os.path.join(settings.STREAM_PATH, "tmp/" + request.COOKIES[settings.SESSION_COOKIE_NAME] + "/", source_filename), os.path.join(settings.STREAM_PATH, base_source_filename))
-                        
-                        
-                        src_prefix = settings.STREAM_SRC_PREFIX.rstrip("/")
-                        if len(src_prefix) > 0:
-                            cleaned_data["src"] = src_prefix + "/" + base_source_filename
-                        else:
-                            cleaned_data["src"] = base_source_filename
-                        
-                        
-                    except Exception as inst:
-                        logging.debug("write_content_base : POST error when processing file:" + str(inst)) #@UndefinedVariable
-                        form_status = "error"
-                        #set error for form
-                        if media_input_type == "url":
-                            errors = media_form._errors.setdefault("external_src_url", ErrorList())
-                            errors.append(_("Problem when downloading file from url : ") + url)
-                        elif media_input_type == "upload":
-                            errors = media_form._errors.setdefault("media_file", ErrorList())
-                            errors.append(_("Problem when uploading file : ") + str(inst))
-                    finally:
-                        if media_input_type == "url":
-                            if destination_file:
-                                destination_file.close()
-                            if source_file:
-                                source_file.close()
-                    
-                    
-                    if form_status != "error":
-                        del cleaned_data["media_file"]
-                        if not cleaned_data['videopath']:
-                            cleaned_data['videopath'] = settings.STREAM_URL
-                        mimetype = cleaned_data.get('mimetype_field', None)
-                        if not mimetype:
-                            mimetype = mimetypes.guess_type(cleaned_data['src'])
-                        cleaned_data['mimetype_field'] = mimetype
-                        media, created = Media.safe_objects.get_or_create(src=cleaned_data['src'], defaults=cleaned_data) #@UndefinedVariable
-                        cached_assign('view_media', request.user, media)
-                    else:
-                        media = None
-                        
-    
-                if media and not created:
-                    for attribute in ('external_id', 'external_permalink', 'external_publication_url', 'external_src_url', 'media_creation_date', 'videopath', 'duration', 'description', 'title', 'front_project'):
-                        setattr(media, attribute, cleaned_data.get(attribute))
-                    mimetype = cleaned_data.get('mimetype_field', None)
-                    if not mimetype:
-                        mimetype = mimetypes.guess_type(media.src)
-                    media.mimetype_field = mimetype
-                    cached_assign('view_media', request.user, media)
-                    cached_assign('change_media', request.user, media)
-                    media.save()
+                media, form_status = media_management(request, media_input_type, cleaned_data, content_form, media_form, form_status)
+                
+                
+                
                 
                 if form_status != "error": 
                     content_defaults = {}