def post(self, request, *args, **kwargs): url = request.POST.get("url") if not url: return HttpResponseBadRequest("Missing 'url' parameter.") embed = Embed.get_for_url(url) if not embed: return HttpResponseBadRequest("Can't load embed from given URL.") html = "" if embed.type == "video": html = embed.html document = pq("<div></div>").html(html) for iframe in document.find("iframe[src^='http://www.youtube.com/embed']"): iframe = pq(iframe) iframe.attr("src", iframe.attr("src") + "&wmode=transparent") html = document.html() return JsonResponse(dict( html=html, url=embed.embed_url, ))
def clean(self): url = self.cleaned_data.get("url") file = self.cleaned_data.get("file") if not file and not url: raise forms.ValidationError(self.error_messages["empty_fields"]) elif url and not file: hostname = urlparse.urlparse(url).hostname if hostname in self.tiny_url_services(): url = json.loads(requests.get( "http://untiny.me/api/1.0/extract", params=dict(url=url, format="json") ).text)["org_url"] response = requests.head(url) if response.error or response.status_code != 200 or "content-type" not in response.headers: raise forms.ValidationError(self.error_messages["invalid_url"]) content_type = response.headers.get("content-type") if IMAGE_CONTENT_TYPE_RE.match(content_type): # Download the image self.media_type = "image" content_length = response.headers.get("content-length") if not content_type: raise forms.ValidationError(self.error_messages["invalid_url"]) content_length = int(content_length) if content_length and content_length > MAX_IMAGE_SIZE: raise forms.ValidationError(self.error_messages["large_image"]) response = requests.get(url) path = urlparse.urlparse(url).path filename = path.split("/")[-1] if not IMAGE_FILENAME_RE.match(filename): extension = content_type.split("/")[-1] if extension in ("pjpeg", "jpeg"): extension = "jpg" #noinspection PyUnusedLocal filename = ''.join( random.choice(string.ascii_lowercase + string.digits) for x in xrange(10) ) + extension file = File(response.raw, name=filename) file._size = content_length self.cleaned_data["file"] = file elif AUDIO_CONTENT_TYPE_RE.match(content_type): self.media_type = "audio" else: self.embed = Embed.get_for_url(url) else: content_type = file.content_type size = file._size if IMAGE_CONTENT_TYPE_RE.match(content_type): if size > MAX_IMAGE_SIZE: raise forms.ValidationError(self.error_messages["large_image"]) # Validate if it's an image forms.ImageField( error_messages=dict( invalid_image=u"The uploaded file is not an image." ) ).to_python(file) self.media_type = "image" elif AUDIO_CONTENT_TYPE_RE.match(content_type): if size > MAX_AUDIO_SIZE: raise forms.ValidationError(self.error_messages["large_audio"]) self.media_type = "audio" elif content_type in UploadedVideo.SUPPORTED_CONTENT_TYPES: self.media_type = "video" return self.cleaned_data