Beispiel #1
0
    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)
Beispiel #2
0
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))
Beispiel #3
0
    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)
Beispiel #4
0
    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)
Beispiel #5
0
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")
Beispiel #6
0
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))
Beispiel #7
0
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))