Esempio n. 1
0
    def get(self):
        """
        Demonstrates asynchronous use of VimeoClient via tornado.gen

        The caller must be decorated by tornado.gen.coroutine
        The call to an API function must include the async kwarg set to True
        The result must be yielded before assignment
        """
        vimeo = VimeoClient("YOUR ACCESS TOKEN")
        res = yield vimeo.users(query='cats', async=True)
        self.write(res)
        self.finish()
Esempio n. 2
0
def main(argv):
    parser = optparse.OptionParser(
        usage='Usage: %prog [options]',
        description="Simple Vimeo uploader")
    parser.add_option('-k', '--key',
                      help="Consumer key")
    parser.add_option('-s', '--secret',
                      help="Consumer secret")
    parser.add_option('-t', '--access-token',
                      help="Access token")
    parser.add_option('-y', '--access-token-secret',
                      help="Access token secret")


    (options, args) = parser.parse_args(argv[1:])
    
    if None in (options.key, options.secret):
        print "Missing key or secret"
        sys.exit(-1)

    if None in (options.access_token, options.access_token_secret):
        client = VimeoClient(options.key, options.secret)
        client.get_request_token()
        print client.get_authorize_token_url()
        verifier = sys.stdin.readline().strip()
        print "Using ", verifier, " as verifier"
        print "Token is:", client.get_access_token(verifier)
    else:
        client = VimeoClient(options.key, options.secret,
                                   token=options.access_token,
                                   token_secret=options.access_token_secret)
Esempio n. 3
0
    def search_by_keyword(self, query, page=1):
        client = VimeoClient(settings.VIMEO_CONSUMER_KEY,
                             settings.VIMEO_CONSUMER_SECRET)

        videos = client.vimeo_videos_search(query=query)

        data = {'results': []}

        data['index'] = {
            'total_results': len(videos),
            'items_per_page': self.NB_RESULTS_PER_PAGE
        }

        for video in videos.getchildren():
            current_result = {
                'id': video.get('id'),
                'name': video.get('title'),
                'permalink_url': 'http://vimeo.com/%s' % video.get('id'),
                'description': '',
                'embed_url': 'http://player.vimeo.com/video/%s' % video.get('id'),
                'embed_type': '',
                'duration': '',
                'user_name': '',
                'user_url': ''
            }
            response = client.vimeo_videos_getThumbnailUrls(video_id=video.get('id'))
            thumbnails = response.getchildren()
            information = client.vimeo_videos_getInfo(video_id=video.get('id'))

            if len(information):
                current_result.update({
                    'description': information.find('description').text,
                    'duration': information.find('duration').text,
                    'user_name': information.find('owner').get('display_name'),
                    'user_url': information.find('owner').get('profileurl')
                })

            if len(thumbnails) > 1:
                current_result['image_url'] = thumbnails[1].text

            data['results'].append(current_result)
        return data
Esempio n. 4
0
    def initialize(self, form):
        """ Prepare the upload form for this service """

        # test the authentication
        if self.token:
            try:
                self.v = VimeoClient(
                    token=self.token,
                    token_secret=self.token_secret,
                    verifier=self.verifier)
                self.v.cache_timeout = 0
                self.uploader = self.v.get_uploader()
            except:
                # failed to authenticate, erase tokens
                self.token = None
                self.token_secret = None
                self.verifier = None
                self.settings.app_state["vimeo_token"] = ""
                self.settings.app_state["vimeo_token_secret"] = ""
                self.settings.app_state["vimeo_verifier"] = ""

                # Show error message
                messagebox.show(
                    _("Validation Error!"),
                    _("Vimeo authentication has expired."))

        self.form = form
        form.lblUsername.set_property("visible", False)
        form.txtUsername.set_property("visible", False)
        form.lblPassword.set_property("visible", False)
        form.txtPassword.set_property("visible", False)
        if self.token:
            # already authorized
            form.login_divider.set_property("visible", False)
            form.btnAuthorize.set_property("visible", False)
            form.lblVerification.set_property("visible", False)
            form.txtVerification.set_property("visible", False)
        else:
            # user needs to authorize OpenShot
            form.login_divider.set_property("visible", True)
            form.btnAuthorize.set_property("visible", True)
            form.lblVerification.set_property("visible", True)
            form.txtVerification.set_property("visible", True)
        form.lnkForgot.set_label("http://www.vimeo.com")
        form.lnkForgot.set_uri("http://www.vimeo.com")
Esempio n. 5
0
def search():

    """
    Handling of POST requests for autocomplete.js
    """

    if request.method == "POST":

        max_results = 3
        result = []

        debug(("Incoming POST request: {}").format(request.json["search"]))

        yt_search_request = (
            "{}/search?q={}&type=playlist&part=id,snippet"
            + "&fields=items(id/playlistId,snippet(thumbnails/medium/url,title))"
            + "&maxResults={}&key={}").format(
                read_config("YOUTUBE_API_URL"), quote(request.json["search"]),
                max_results, read_config("YOUTUBE_API_KEY"))
        yt_search_response = urllib_request.urlopen(yt_search_request)
        youtube = loads(yt_search_response.read().decode())

        VIMEO = VimeoClient(
            token=read_config("VIMEO_TOKEN"),
            key=read_config("VIMEO_KEY"),
            secret=read_config("VIMEO_SECRET"))

        vim_search_request = VIMEO.get(("/channels?query={}&per_page={}").format(quote(request.json["search"]), max_results), params={"fields": "name, uri, pictures.uri, metadata.connections.videos.total"})

        vimeo = vim_search_request.json()

        for playlist in youtube["items"]:

            req = (
                "{}/playlistItems?playlistId={}"
                + "&part=id&fields=pageInfo/totalResults"
                + "&maxresults=1&key={}").format(
                    read_config("YOUTUBE_API_URL"), playlist["id"]["playlistId"], read_config("YOUTUBE_API_KEY"))
            request_send = urllib_request.urlopen(req)
            videos_in_playlist = loads(request_send.read().decode())

            #TODO: decide what to return in case of missing thumbnail
            thumbnail_url = ""

            if "thumbnails" in playlist["snippet"]:
                # api call needed as playlist thumbnail != thumbnail of first video (or not inevitable)
                thumbnail_url = playlist["snippet"]["thumbnails"]["medium"]["url"]

            result.append({
                "source": "youtube",
                "id": playlist["id"]["playlistId"],
                "title": playlist["snippet"]["title"],
                "thumb": thumbnail_url,
                "amount": videos_in_playlist["pageInfo"]["totalResults"]})

        for video in vimeo["data"]:
            result.append({
                "source": "vimeo",
                "id": video["uri"].split("/")[2],
                "title": video["name"],
                #TODO: check if thumbnail of first video is always thumbnail of channel (or customizable as on YouTube)
                "thumb": ("https://i.vimeocdn.com/video/{}_100x75.jpg").format(video["pictures"]["uri"].split("/")[4]),
                "amount": video["metadata"]["connections"]["videos"]["total"]
            })

        return dumps(result)
Esempio n. 6
0
 def get_authorization_url(self):
     self.v = VimeoClient()
     self.v.cache_timeout = 0
     return self.v.get_authorization_url(permission="write")
Esempio n. 7
0
class VimeoService():
    def __init__(self, project, settings):
        self.project = project
        self.filename = None
        self.settings = settings
        self.token = None
        self.token_secret = None
        self.verifier = None
        self.form = None

        # Add language support
        _ = Language_Init.Translator(project).lang.gettext
        self._ = _

        # get tokens (if already authorized)
        if self.settings.app_state["vimeo_token"]:
            self.token = self.settings.app_state["vimeo_token"]
        if self.settings.app_state["vimeo_token_secret"]:
            self.token_secret = self.settings.app_state["vimeo_token_secret"]
        if self.settings.app_state["vimeo_verifier"]:
            self.verifier = self.settings.app_state["vimeo_verifier"]

    def initialize(self, form):
        """ Prepare the upload form for this service """

        # test the authentication
        if self.token:
            try:
                self.v = VimeoClient(
                    token=self.token,
                    token_secret=self.token_secret,
                    verifier=self.verifier)
                self.v.cache_timeout = 0
                self.uploader = self.v.get_uploader()
            except:
                # failed to authenticate, erase tokens
                self.token = None
                self.token_secret = None
                self.verifier = None
                self.settings.app_state["vimeo_token"] = ""
                self.settings.app_state["vimeo_token_secret"] = ""
                self.settings.app_state["vimeo_verifier"] = ""

                # Show error message
                messagebox.show(
                    _("Validation Error!"),
                    _("Vimeo authentication has expired."))

        self.form = form
        form.lblUsername.set_property("visible", False)
        form.txtUsername.set_property("visible", False)
        form.lblPassword.set_property("visible", False)
        form.txtPassword.set_property("visible", False)
        if self.token:
            # already authorized
            form.login_divider.set_property("visible", False)
            form.btnAuthorize.set_property("visible", False)
            form.lblVerification.set_property("visible", False)
            form.txtVerification.set_property("visible", False)
        else:
            # user needs to authorize OpenShot
            form.login_divider.set_property("visible", True)
            form.btnAuthorize.set_property("visible", True)
            form.lblVerification.set_property("visible", True)
            form.txtVerification.set_property("visible", True)
        form.lnkForgot.set_label("http://www.vimeo.com")
        form.lnkForgot.set_uri("http://www.vimeo.com")

    def get_logo(self):
        logo_path = os.path.join(self.project.BASE_DIR, "openshot", "uploads",
                                 "logos", "vimeo.png")
        return gtk.gdk.pixbuf_new_from_file(logo_path)

    def get_export_presets(self):
        """ Get a tuple of related export presets for this service (if any) """

        # get reference to gettext
        _ = self._

        return (_("Web"), _("Vimeo-HD"))

    def get_authorization_url(self):
        self.v = VimeoClient()
        self.v.cache_timeout = 0
        return self.v.get_authorization_url(permission="write")

    def validate(self, form):
        """ Validate the upload form... check for missing values. """

        # get reference to gettext
        _ = self._

        # get code
        verification_code = form.txtVerification.get_text()
        title = form.txtTitle.get_text()
        start, end = form.txtDescription.get_buffer().get_bounds()
        description = form.txtDescription.get_buffer().get_text(start, end)

        # Validate the the form is valid
        if not os.path.isfile(str(self.filename)):
            # Show error message
            messagebox.show(
                _("Validation Error!"), _("Please choose a valid video file."))
            return False

        if not title:
            # Show error message
            messagebox.show(
                _("Validation Error!"), _("Please enter a valid title."))
            return False

        if not self.token:
            if not description:
                # Show error message
                messagebox.show(
                    _("Validation Error!"),
                    _("Please enter a valid description."))
                return False

            if not verification_code:
                # Show error message
                messagebox.show(
                    _("Validation Error!"),
                    _("Please enter a valid verification code.  Click the 'Authorize' button and login to the website.  Confirm the authorization, and copy the verification code."
                      ))
                return False

        # form is valid
        return True

    def set_file(self, filename):
        self.filename = filename

    def start_upload(self, form):

        # get reference to gettext
        _ = self._

        if not self.token:
            # Not Authorized Yet.
            # get code
            verification_code = form.txtVerification.get_text()

            try:
                # pass code and authorize OpenShot (hopefully)
                self.v.set_verifier(verification_code)
                access_token = self.v.get_access_token()

                # save tokens in settings
                self.verifier = verification_code
                self.settings.app_state["vimeo_verifier"] = self.verifier

                self.token = access_token.key
                self.settings.app_state["vimeo_token"] = self.token

                self.token_secret = access_token.secret
                self.settings.app_state[
                    "vimeo_token_secret"] = self.token_secret

                # Get uploader object
                self.uploader = self.v.get_uploader()

            except:
                # Show error message
                messagebox.show(
                    _("Validation Error!"),
                    _("There was an error authorizing OpenShot.  Please be sure to enter the correct verification code from vimeo.com."
                      ))

        # get settings
        title = form.txtTitle.get_text()
        start, end = form.txtDescription.get_buffer().get_bounds()
        description = form.txtDescription.get_buffer().get_text(start, end)

        try:
            # enable upload button
            form.btnUpload.set_sensitive(False)

            # Upload the file to Vimeo
            output = self.uploader.upload(
                self.filename,
                chunk=True,
                chunk_size=64 * 1024,
                chunk_complete_hook=self.on_chunk_complete)
            upload_ticket_id = output.get("id")
            output = self.v.videos_upload_complete(ticket_id=upload_ticket_id)
            video_id = output.get("video_id")

            # Set the name and description of the video
            self.v.videos_setTitle(title=title, video_id=video_id)
            self.v.videos_setDescription(
                description=description, video_id=video_id)

        except:
            # Show error message
            messagebox.show(
                _("Validation Error!"),
                _("There was an error uploading to Vimeo."))

            # enable upload button
            form.btnUpload.set_sensitive(True)
            return False

        # enable upload button
        form.btnUpload.set_sensitive(True)

        # successful
        return True

    def on_chunk_complete(self, *args):
        #print "on_chunk_complete"

        total_size = args[0]["total_size"]
        chunk_size = args[0]["chunk_size"]
        chunk_id = args[0]["chunk_id"] + 1  # zero based

        # calculate current bytes transferred
        current_bytes = chunk_id * chunk_size

        if current_bytes >= total_size:
            # don't exceed the total bytes
            current_bytes = total_size

        # calculate percentage
        percent = float(current_bytes) / float(total_size)
        gobject.idle_add(self.form.update_progressbar, percent)

        # allow other gtk operations to happen
        while gtk.events_pending():
            gtk.main_iteration()