def MeguzDeleteVideo(request, meguz_id): from django.core.urlresolvers import reverse from django.contrib import messages from django_youtube.api import Api, AccessControl, ApiError from main.models import User user = User.objects.get(token=request.COOKIES.get('fbmgz_234778956683382')) if user is None: HttpResponseRedirect("/") else: # Check meguz existence meguz = Meguz.objects.get(pk=meguz_id) if meguz is None: HttpResponseRedirect("/") else: # Check is user's meguz if meguz.user.token != user.token: HttpResponseRedirect("/") else: try: api = Api() api.authenticate() if meguz.video_id != '': if api.delete_video(meguz.video_id) is True: meguz.video_id = ''; meguz.video_thumb = ''; meguz.save() HttpResponseRedirect("/usuario/mis-meguz") except: messages.add_message(request, messages.ERROR, _('Ha ocurrido un error, por favor intenta de nuevo')) return HttpResponseRedirect("/") return render_to_response('meguz/delete.html', {}, context_instance=RequestContext(request))
def _upload_to_youtube(self, name, path): """ Uploads the file from the given path to youtube Parameter --------- name : str Name of the file (short caption) path : str Path to tempory file Return ------ str, str Youtube video id, Youtube SWF url """ youtube = Youtube() youtube.authenticate() video_entry = youtube.upload_direct( path, name, access_control=AccessControl.Unlisted ) return video_entry.id.text.split('/')[-1], video_entry.GetSwfUrl()
def entry(self): """ Connects to Youtube Api and retrieves the video entry object Return: gdata.youtube.YouTubeVideoEntry """ api = Api() api.authenticate() return api.fetch_video(self.video_id)
def MeguzUpdateMultimedia(request, prize_id, user_token): from django.core.urlresolvers import reverse from django.contrib import messages from django_youtube.api import Api, AccessControl, ApiError from main.models import User prize = Offer.objects.get(pk=prize_id) user = User.objects.get(token=user_token) meguz = Meguz.objects.get(prize=prize, user=user) if meguz is None: return HttpResponseRedirect("/") else: # If request.GET isset from Youtube, update media_url with video ID if request.method == "GET": if "status" in request.GET: if request.GET["status"] == "200": if "id" in request.GET: # Update database info meguz.video_id = request.GET["id"] meguz.video_thumb = "http://img.youtube.com/vi/%s/1.jpg" % request.GET["id"] meguz.save() # Update youtube metadata try: api = Api() api.authenticate() title = meguz.title + " | Meguz.com" description = meguz.description + "... Visita www.meguz.com para mas informacion" keywords = ( meguz.prize.category.name + "," + meguz.prize.prize_name + "," + meguz.prize.company.name ) api.update_video(meguz.video_id, title, description, keywords) # Api error happend except ApiError as e: messages.add_message(request, messages.ERROR, e.message) return HttpResponseRedirect("/") # Other error except: messages.add_message( request, messages.ERROR, _("Ha ocurrido un error, por favor intenta de nuevo") ) return HttpResponseRedirect("/") return HttpResponseRedirect("/usuario/mis-meguz") # /meguz/{id}/{slug}
def upload(request): """ Displays an upload form Creates upload url and token from facebook api and uses them on the form """ # Get the optional parameters title = request.GET.get( "title", "%s's video on %s" % (request.user.username, request.get_host())) description = request.GET.get("description", "") keywords = request.GET.get("keywords", "") # Try to create post_url and token to create an upload form try: api = Api() # upload method needs authentication api.authenticate() # Customize following line to your needs, you can add description, keywords or developer_keys # I prefer to update video information after upload finishes data = api.upload(title, description=description, keywords=keywords, access_control=AccessControl.Unlisted) except ApiError as e: # An api error happened, redirect to homepage messages.add_message(request, messages.ERROR, e.message) return HttpResponseRedirect("/") except: # An error happened, redirect to homepage messages.add_message( request, messages.ERROR, _('An error occurred during the upload, Please try again.')) return HttpResponseRedirect("/") # Create the form instance form = YoutubeUploadForm(initial={"token": data["youtube_token"]}) protocol = 'https' if request.is_secure() else 'http' import os next_url = "".join([ protocol, ":", os.sep, os.sep, request.get_host(), reverse("django_youtube.views.upload_return"), os.sep ]) return render_to_response("django_youtube/upload.html", { "form": form, "post_url": data["post_url"], "next_url": next_url }, context_instance=RequestContext(request))
def _upload_to_youtube(self, name, path): """ Uploads the file from the given path to youtube """ youtube = Youtube() youtube.authenticate() video_entry = youtube.upload_direct( path, name, access_control=AccessControl.Unlisted ) return video_entry.id.text.split('/')[-1], video_entry.GetSwfUrl()
def MeguzEdit(request,meguz_id): from django.core.urlresolvers import reverse from django.contrib import messages from django_youtube.api import Api, AccessControl, ApiError from main.models import User user = User.objects.get(token=request.COOKIES.get('fbmgz_234778956683382')) if user is None: HttpResponseRedirect("/") else: # Check meguz existence meguz = Meguz.objects.get(pk=meguz_id) if meguz is None: HttpResponseRedirect("/") else: # Check is user's meguz if meguz.user.token != user.token: HttpResponseRedirect("/") else: # Load MeguzForm, MeguzMultimediaForm formData = MeguzForm(initial={"title":meguz.title, "description":meguz.description}) # Check video status title = meguz.title + " | Meguz.com" keywords = meguz.prize.category.name + "," + meguz.prize.prize_name + "," + meguz.prize.company.name description = meguz.description + "... Visita www.meguz.com para mas informacion" try: api = Api() api.authenticate() #if meguz.video_id is not None: # status = api.check_upload_status(meguz.video_id) data = api.upload(title, description=description, keywords=keywords, access_control=AccessControl.Unlisted) except: messages.add_message(request, messages.ERROR, _('Ha ocurrido un error, por favor intenta de nuevo')) return HttpResponseRedirect("/") formVideo = MeguzMultimediaForm(initial={"token": data["youtube_token"]}) import os protocol = 'https' if request.is_secure() else 'http' next_url = "".join([protocol, ":", os.sep, os.sep, request.get_host(), "/meguz/update/multimedia/{0}/{1}".format(meguz.prize.id,request.COOKIES.get('fbmgz_234778956683382')), os.sep]) context = {'meguz':meguz,'form_data':formData, 'form_video':formVideo, 'post_url': data['post_url'], 'next_url': next_url } return render_to_response('meguz/edit.html', context, context_instance=RequestContext(request))
def delete(self, *args, **kwargs): """ Deletes the video from youtube Raises: OperationError """ api = Api() # Authentication is required for deletion api.authenticate() # Send API request, raises OperationError on unsuccessful deletion api.delete_video(self.video_id) # Call the super method return super(Video, self).delete(*args, **kwargs)
def save(self, *args, **kwargs): """ Syncronize the video information on db with the video on Youtube The reason that I didn't use signals is to avoid saving the video instance twice. """ # if this is a new instance add details from api if not self.id: # Connect to api and get the details entry = self.entry() # Set the details self.title = entry.media.title.text self.description = entry.media.description.text self.keywords = entry.media.keywords.text self.youtube_url = entry.media.player.url self.swf_url = entry.GetSwfUrl() if entry.media.private: self.access_control = AccessControl.Private else: self.access_control = AccessControl.Public # Save the instance super(Video, self).save(*args, **kwargs) # show thumbnails for thumbnail in entry.media.thumbnail: t = Thumbnail() t.url = thumbnail.url t.video = self t.save() else: # updating the video instance # Connect to API and update video on youtube api = Api() # update method needs authentication api.authenticate() # Update the info on youtube, raise error on failure api.update_video(self.video_id, self.title, self.description, self.keywords, self.access_control) # Save the model return super(Video, self).save(*args, **kwargs)
def upload(request,ret_view = True): """ Displays an upload form Creates upload url and token from youtube api and uses them on the form """ # Get the optional parameters title = request.GET.get("title", "%s's video on %s" % ( request.user.username, request.get_host())) description = request.GET.get("description", "") keywords = request.GET.get("keywords", "") # Try to create post_url and token to create an upload form try: api = Api() # upload method needs authentication api.authenticate() # Customize following line to your needs, you can add description, keywords or developer_keys # I prefer to update video information after upload finishes data = api.upload(title, description=description, keywords=keywords, access_control=AccessControl.Unlisted) except ApiError as e: # An api error happened, redirect to homepage messages.add_message(request, messages.ERROR, e.message) return HttpResponseRedirect("/") except: # An error happened, redirect to homepage messages.add_message(request, messages.ERROR, _( 'An error occurred during the upload, Please try again.')) return HttpResponseRedirect("/") # Create the form instance form = YoutubeUploadForm(initial={"token": data["youtube_token"]}) protocol = 'https' if request.is_secure() else 'http' next_url = '%s://%s%s/' % (protocol, request.get_host(), reverse("django_youtube.views.upload_return")) if not ret_view: return form,data["post_url"],next_url return render_to_response( "django_youtube/upload.html", {"form": form, "post_url": data["post_url"], "next_url": next_url}, context_instance=RequestContext(request) )
def check_video_availability(request, video_id): """ Controls the availability of the video. Newly uploaded videos are in processing stage. And others might be rejected. Returns: json response """ # Check video availability # Available states are: processing api = Api() api.authenticate() availability = api.check_upload_status(video_id) if availability is not True: data = {'success': False} else: data = {'success': True} return HttpResponse(json.dumps(data), content_type="application/json")
def upload(request): """ Displays an upload form Creates upload url and token from youtube api and uses them on the form """ # Get the optional parameters title = request.GET.get("title", "%s's video on %s" % ( request.user.name, request.get_host())) description = request.GET.get("description", "") keywords = request.GET.get("keywords", "") # Try to create post_url and token to create an upload form try: api = Api() # upload method needs authentication api.authenticate() # Customize following line to your needs, you can add description, keywords or developer_keys # I prefer to update video information after upload finishes data = api.upload(title, description=description, keywords=keywords, access_control=AccessControl.Public) except ApiError as e: # An api error happened, redirect to homepage messages.add_message(request, messages.ERROR, e.message) return HttpResponseRedirect("/") except: # An error happened, redirect to homepage messages.add_message(request, messages.ERROR, _( 'An error occurred during the upload, Please try again.')) return HttpResponseRedirect("/") # Create the form instance form = YoutubeUploadForm(initial={"token": data["youtube_token"]}) protocol = 'https' if request.is_secure() else 'http' import os next_url = "".join([protocol, ":", os.sep, os.sep, request.get_host( ), reverse("django_youtube.views.upload_return"), os.sep]) return dict(form=form, post_url=data["post_url"], next_url=next_url)
def video(request, video_id): """ Displays a video in an embed player """ # Check video availability # Available states are: processing api = Api() api.authenticate() availability = api.check_upload_status(video_id) if availability is not True: # Video is not available video = Video.objects.filter(video_id=video_id).get() state = availability["upload_state"] # Add additional states here. I'm not sure what states are available if state == "failed" or state == "rejected": return render_to_response("django_youtube/video_failed.html", { "video": video, "video_id": video_id, "message": _("Invalid video."), "availability": availability }, context_instance=RequestContext(request)) else: return render_to_response( "django_youtube/video_unavailable.html", { "video": video, "video_id": video_id, "message": _("This video is currently being processed"), "availability": availability }, context_instance=RequestContext(request)) video_params = _video_params(request, video_id) return render_to_response("django_youtube/video.html", video_params, context_instance=RequestContext(request))
def MeguzDelete(request, meguz_id): from django.core.urlresolvers import reverse from django.contrib import messages from django_youtube.api import Api, AccessControl, ApiError from main.models import User user = User.objects.get(token=request.COOKIES.get("fbmgz_234778956683382")) if user is None: HttpResponseRedirect("/") else: # Check meguz existence meguz = Meguz.objects.get(pk=meguz_id) if meguz is None: HttpResponseRedirect("/") else: # Check is user's meguz if meguz.user.token != user.token: HttpResponseRedirect("/") else: try: api = Api() api.authenticate() if api.delete_video(meguz.video_id) is True: if meguz.status == "C": try: es = ES("127.0.0.1:9200") es.delete("meguz", "meguz", meguz.id) except: messages.add_message(request, messages.ERROR, _("Aviso no se encuentra en es")) meguz.delete() HttpResponseRedirect("/usuario/mis-meguz") except: messages.add_message(request, messages.ERROR, _("Ha ocurrido un error, por favor intenta de nuevo")) return HttpResponseRedirect("/") return render_to_response("meguz/delete.html", {}, context_instance=RequestContext(request))
def video(request, video_id): """ Displays a video in an embed player """ # Check video availability # Available states are: processing api = Api() api.authenticate() availability = api.check_upload_status(video_id) if availability is not True: # Video is not available video = Video.objects.filter(video_id=video_id).get() state = availability["upload_state"] # Add additional states here. I'm not sure what states are available if state == "failed" or state == "rejected": return render_to_response( "django_youtube/video_failed.html", {"video": video, "video_id": video_id, "message": _("Invalid video."), "availability": availability}, context_instance=RequestContext(request) ) else: return render_to_response( "django_youtube/video_unavailable.html", {"video": video, "video_id": video_id, "message": _("This video is currently being processed"), "availability": availability}, context_instance=RequestContext(request) ) video_params = _video_params(request, video_id) return render_to_response( "django_youtube/video.html", video_params, context_instance=RequestContext(request) )
def PrizeMultimedia(request, offer_id): if not request.user.is_authenticated(): return HttpResponseRedirect("/epanel") else: from django.core.urlresolvers import reverse from django.contrib import messages from django_youtube.api import Api, AccessControl, ApiError offer = Offer.objects.get(id=offer_id) show_media = False # Offer doesnt exists if offer is None: return HttpResponseRedirect("/epanel") # Offer exists else: # If request.POST isset then an Image its been uploaded if request.method == 'POST': #form = OfferMultimediaForm(request.POST, request.FILES) offer.media_type = request.POST['media_type'] offer.media_image = request.FILES['media_image'] offer.save() offer.media_thumb = offer.media_image.url offer.save() # update elasticsearch if(offer.status == 'C'): es = ES("localhost:9200") prizeES = es.get("prize","prize",offer.id) prizeES.thumbnail = offer.media_thumb prizeES.save() # If request.GET isset from Youtube, update media_url with video ID if request.method == 'GET': if 'status' in request.GET: if request.GET['status'] == "200": if 'id' in request.GET: offer.media_url = request.GET['id'] offer.media_thumb = "http://img.youtube.com/vi/%s/mqdefault.jpg" % request.GET['id'] offer.media_type = 'Y' offer.save() # update elasticsearch if(offer.status == 'C'): es = ES("localhost:9200") prizeES = es.get("prize","prize",offer.id) prizeES.thumbnail = offer.media_thumb prizeES.save() return HttpResponseRedirect("/epanel/premios/multimedia/%s" % offer_id) # video metadata title = offer.title + " | Meguz.com" keywords = offer.category.name + "," + offer.prize_name + "," + offer.company.name description = offer.description + "... Visita www.meguz.com para mas informacion" # Try to create post_url and token try: api = Api() api.authenticate() data = api.upload(title, description=description, keywords=keywords, access_control=AccessControl.Unlisted) # Api error happend except ApiError as e: messages.add_message(request, messages.ERROR, e.message) return HttpResponseRedirect("/epanel") # Other error except: messages.add_message(request, messages.ERROR, _('Ha ocurrido un error, por favor intenta de nuevo')) return HttpResponseRedirect("/epanel") form = OfferMultimediaForm(initial={'media_type':offer.media_type,"token": data["youtube_token"]}) import os from django.contrib.sites.models import Site current_site = Site.objects.get_current() domain = current_site.domain protocol = 'https' if request.is_secure() else 'http' next_url = "".join([protocol, ":", os.sep, os.sep, domain, "/epanel/premios/multimedia/%d" % offer.id, os.sep]) if offer.media_url != '' or offer.media_image != '': show_media = True context = {'form':form, 'offer':offer, 'show_media':show_media, 'post_url': data['post_url'], 'next_url': next_url} return render_to_response('epanel/offer/multimedia.html', context, context_instance=RequestContext(request))
def MeguzCreateBase(request): if request.method == "POST": # Imports for django_youtube from django.core.urlresolvers import reverse from django.contrib import messages from django_youtube.api import Api, AccessControl, ApiError # Get POST params title = request.POST["title"] description = request.POST["description"] offer_id = request.POST["offer_id"] # Get and validate Offer offer = Offer.objects.get(pk=offer_id) if offer is None: response = "Premio no existe" else: # Offer is OK # Get and validate User from main.models import User user = User.objects.get(token=request.COOKIES.get("fbmgz_234778956683382")) if user is None: response = "Usuario no existe" else: # User is OK # Save Meguz meguz = Meguz() meguz.title = title meguz.description = description meguz.slug = slugify(title) meguz.status = "B" meguz.prize_id = offer_id meguz.vote_count = 0 meguz.user_id = user.id meguz.save() # Generate video metadata title = title + " | Meguz.com" keywords = offer.category.name + "," + offer.prize_name + "," + offer.company.name + ", Meguz, Premios" description = description + "... Visita www.meguz.com para mas informacion" # Try to create post_url and token try: api = Api() api.authenticate() data = api.upload( title, description=description, keywords=keywords, access_control=AccessControl.Unlisted ) # Api error happend except ApiError as e: response = e.message # Other error except Error as e: response = e.message response = data["youtube_token"] + "[GLUE]" + data["post_url"] + "[GLUE]" + str(meguz.id) else: response = "Forbidden" context = {"response": response} return render_to_response("meguz/create_base.html", context, context_instance=RequestContext(request))
def MeguzEdit(request, meguz_id): from django.core.urlresolvers import reverse from django.contrib import messages from django_youtube.api import Api, AccessControl, ApiError from main.models import User user = User.objects.get(token=request.COOKIES.get("fbmgz_234778956683382")) if user is None: HttpResponseRedirect("/") else: # Check meguz existence meguz = Meguz.objects.get(pk=meguz_id) if meguz is None: HttpResponseRedirect("/") else: # Check is user's meguz if meguz.user.token != user.token: HttpResponseRedirect("/") else: # Load MeguzForm, MeguzMultimediaForm formData = MeguzForm(initial={"title": meguz.title, "description": meguz.description}) # Check video status title = meguz.title + " | Meguz.com" keywords = meguz.prize.category.name + "," + meguz.prize.prize_name + "," + meguz.prize.company.name description = meguz.description + "... Visita www.meguz.com para mas informacion" try: api = Api() api.authenticate() # if meguz.video_id is not None: # status = api.check_upload_status(meguz.video_id) # Get actual video status availability = api.check_upload_status(meguz.video_id) if availability is not True: video_state = availability["upload_state"] video_msg = availability["detailed_message"] else: video_state = False video_msg = "" # Generate video data for new upload data = api.upload( title, description=description, keywords=keywords, access_control=AccessControl.Unlisted ) except: messages.add_message(request, messages.ERROR, _("Ha ocurrido un error, por favor intenta de nuevo")) return HttpResponseRedirect("/") formVideo = MeguzMultimediaForm(initial={"token": data["youtube_token"]}) import os from django.contrib.sites.models import Site current_site = Site.objects.get_current() domain = current_site.domain protocol = "https" if request.is_secure() else "http" next_url = "".join( [ protocol, ":", os.sep, os.sep, domain, "/meguz/update/multimedia/{0}/{1}".format( meguz.prize.id, request.COOKIES.get("fbmgz_234778956683382") ), os.sep, ] ) context = { "meguz": meguz, "form_data": formData, "form_video": formVideo, "post_url": data["post_url"], "next_url": next_url, "video_state": video_state, "video_msg": video_msg, } return render_to_response("meguz/edit.html", context, context_instance=RequestContext(request))
def direct_upload(request): """ direct upload method starts with uploading video to our server then sends the video file to youtube param: (optional) `only_data`: if set, a json response is returns i.e. {'video_id':'124weg'} return: if `only_data` set, a json object. otherwise redirects to the video display page """ if request.method == "POST": try: form = YoutubeDirectUploadForm(request.POST, request.FILES) # upload the file to our server if form.is_valid(): uploaded_video = form.save() # send this file to youtube api = Api() api.authenticate() video_entry = api.upload_direct( uploaded_video.file_on_server.path, "Uploaded video from zuqqa") # get data from video entry swf_url = video_entry.GetSwfUrl() youtube_url = video_entry.id.text # getting video_id is tricky, I can only reach the url which # contains the video_id. # so the only option is to parse the id element # https://groups.google.com/forum/?fromgroups=#!topic/youtube-api-gdata/RRl_h4zuKDQ url_parts = youtube_url.split("/") url_parts.reverse() video_id = url_parts[0] # save video_id to video instance video = Video() video.user = request.user video.video_id = video_id video.title = 'tmp video' video.youtube_url = youtube_url video.swf_url = swf_url video.save() # delete the uploaded video instance uploaded_video.delete() # return the response return_only_data = request.GET.get('only_data') if return_only_data: return HttpResponse(json.dumps({"video_id": video_id})) else: # Redirect to the video page or the specified page try: next_url = settings.YOUTUBE_UPLOAD_REDIRECT_URL except AttributeError: next_url = reverse("django_youtube.views.video", kwargs={"video_id": video_id}) return HttpResponseRedirect(next_url) except: import sys logger.error("Unexpected error: %s - %s" % (sys.exc_info()[0], sys.exc_info()[1])) # @todo: proper error management return HttpResponse("error happened") form = YoutubeDirectUploadForm() return render_to_response("django_youtube/direct-upload.html", {"form": form}, context_instance=RequestContext(request))
def direct_upload(request): """ direct upload method starts with uploading video to our server then sends the video file to youtube param: (optional) `only_data`: if set, a json response is returns i.e. {'video_id':'124weg'} return: if `only_data` set, a json object. otherwise redirects to the video display page """ if request.method == "POST": try: form = YoutubeDirectUploadForm(request.POST, request.FILES) # upload the file to our server if form.is_valid(): uploaded_video = form.save() # send this file to youtube api = Api() api.authenticate() video_entry = api.upload_direct(uploaded_video.file_on_server.path, "Uploaded video from zuqqa") # get data from video entry swf_url = video_entry.GetSwfUrl() youtube_url = video_entry.id.text # getting video_id is tricky, I can only reach the url which # contains the video_id. # so the only option is to parse the id element # https://groups.google.com/forum/?fromgroups=#!topic/youtube-api-gdata/RRl_h4zuKDQ url_parts = youtube_url.split("/") url_parts.reverse() video_id = url_parts[0] # save video_id to video instance video = Video() video.user = request.user video.video_id = video_id video.title = 'tmp video' video.youtube_url = youtube_url video.swf_url = swf_url video.save() # send a signal video_created.send(sender=video, video=video) # delete the uploaded video instance uploaded_video.delete() # return the response return_only_data = request.GET.get('only_data') if return_only_data: return HttpResponse(json.dumps({"video_id": video_id}), content_type="application/json") else: # Redirect to the video page or the specified page try: next_url = settings.YOUTUBE_UPLOAD_REDIRECT_URL except AttributeError: next_url = reverse( "django_youtube.views.video", kwargs={"video_id": video_id}) return HttpResponseRedirect(next_url) except: import sys logger.error("Unexpected error: %s - %s" % (sys.exc_info()[ 0], sys.exc_info()[1])) # @todo: proper error management return HttpResponse("error happened") form = YoutubeDirectUploadForm() if return_only_data: return HttpResponse(json.dumps({"error": 500}), content_type="application/json") else: return render_to_response( "django_youtube/direct-upload.html", {"form": form}, context_instance=RequestContext(request) )
def PrizeParticipate(request, offer_id): from django.core.urlresolvers import reverse from django.contrib import messages from django_youtube.api import Api, AccessControl, ApiError prize = Offer.objects.get(pk=offer_id) if prize is None: messages.add_message(request, messages.ERROR, _('Prize is None')) return HttpResponseRedirect("/") else: # Prize exists from main.models import User user = User.objects.get(token=request.COOKIES.get('fbmgz_234778956683382')) if user is None: messages.add_message(request, messages.ERROR, _('User is none')) return HttpResponseRedirect("/") else: # User exists prize = Offer.objects.get(pk=offer_id) meguz = Meguz.objects.filter(user=user,prize=prize) if meguz.count() == 0: # User is not participating company = Company.objects.get(pk=prize.company.id) formData = MeguzForm() # video metadata title = prize.title + " | Meguz.com" keywords = prize.category.name + "," + prize.prize_name + "," + prize.company.name description = prize.description + "... Visita www.meguz.com para mas informacion" # Try to create post_url and token try: api = Api() api.authenticate() data = api.upload(title, description=description, keywords=keywords, access_control=AccessControl.Unlisted) # Api error happend except ApiError as e: messages.add_message(request, messages.ERROR, _('Api error happend')) messages.add_message(request, messages.ERROR, e.message) return HttpResponseRedirect("/") # Other error except Error as e: messages.add_message(request, messages.ERROR, _('Ha ocurrido un error, por favor intenta de nuevo')) return HttpResponseRedirect("/") formVideo = MeguzMultimediaForm(initial={"token": data["youtube_token"]}) import os from django.contrib.sites.models import Site current_site = Site.objects.get_current() domain = current_site.domain protocol = 'https' if request.is_secure() else 'http' next_url = "".join([protocol, ":", os.sep, os.sep, domain, "/meguz/update/multimedia/{0}/{1}".format(prize.id,request.COOKIES.get('fbmgz_234778956683382')), os.sep]) context = { 'offer': prize, 'company': company, 'form_data': formData, 'form_video': formVideo, 'post_url': data['post_url'], 'next_url': next_url } return render_to_response('meguz/new.html', context, context_instance=RequestContext(request)) else: # User is already participating context = { 'offer': prize } return render_to_response('meguz/new_forbidden.html', context, context_instance=RequestContext(request))
def MeguzEditForm(request, meguz_id, user_token): from django.core.urlresolvers import reverse from django.contrib import messages from django_youtube.api import Api, AccessControl, ApiError if request.method == 'POST': meguzForm = MeguzForm(request.POST) if(meguzForm.is_valid()): # Load model with form meguz = Meguz.objects.get(pk=meguz_id) meguz.title = request.POST['title'] meguz.description = request.POST['description'] meguz.id = meguz_id # Load user id from main.models import User user = User.objects.get(token=user_token) if user is None: context = {'response':'Forbidden'} else: meguz.save() if meguz.status == 'C': es = ES("localhost:9200") meguzES = es.get("meguz","meguz",meguz.id) meguzES.title = meguz.title meguzES.description = meguz.description meguzES.save() # Update youtube data try: api = Api() api.authenticate() title = meguz.title + " | Meguz.com" description = meguz.description + "... Visita www.meguz.com para mas informacion" keywords = meguz.prize.category.name + "," + meguz.prize.prize_name + "," + meguz.prize.company.name if meguz.video_id != '': api.update_video(meguz.video_id, title, description, keywords) # Api error happend except ApiError as e: messages.add_message(request, messages.ERROR, e.message) return HttpResponseRedirect("/") # Other error except: messages.add_message(request, messages.ERROR, _('Ha ocurrido un error, por favor intenta de nuevo')) return HttpResponseRedirect("/") context = {'response':meguz.id} else: context = {'response':'fail'} else: context = {'response': 'invalid'} return render_to_response('meguz/edit_form.html', context, context_instance=RequestContext(request))