Example #1
0
def _get_vimeo_client(settings):
    v = vimeo.VimeoClient(key=settings.VIMEO_CLIENT_ID,
                          secret=settings.VIMEO_SECRET_CLIENT_ID)

    token = v.load_client_credentials()

    authenticated_client = vimeo.VimeoClient(
        token=token,
        key=settings.VIMEO_CLIENT_ID,
        secret=settings.VIMEO_SECRET_CLIENT_ID)

    return authenticated_client
Example #2
0
    def initializeVimeoClient(self):
        import vimeo

        if len(sys.modules["__main__"].settings.getSetting(
                "oauth_token_secret")) > 0 and len(
                    sys.modules["__main__"].settings.getSetting(
                        "oauth_token")) > 0:
            sys.modules["__main__"].client = vimeo.VimeoClient(
                token=sys.modules["__main__"].settings.getSetting(
                    "oauth_token").encode('ascii'),
                token_secret=sys.modules["__main__"].settings.getSetting(
                    "oauth_token_secret").encode('ascii'))
        else:
            sys.modules["__main__"].client = vimeo.VimeoClient()
Example #3
0
def upload_baptism_to_vimeo(config, video_path, metadata):
    """ uploads the video to vimeo using the credentials stored in config """
    import vimeo

    vimeo_handle = vimeo.VimeoClient(token=config["vimeo"]["token"],
                                     key=config["vimeo"]["key"],
                                     secret=config["vimeo"]["secret"])

    video_uri = vimeo_handle.upload(video_path)

    vimeo_handle.patch(video_uri,
                       data={
                           'name':
                           "Zur Erinnerung " + "an die Taufe am " +
                           metadata["date"].strftime("%d.%m.%Y"),
                           'description':
                           '',
                           'privacy': {
                               'view': 'password'
                           },
                           'password':
                           create_baptism_video_password(metadata)
                       })
    video_uri = video_uri.replace("s", "")

    return video_uri
Example #4
0
def updateVimeoVideoDetails(video_id, title, description):
    if video_id:
        v = vimeo.VimeoClient(token=settings.VIMEO_TOKEN, )
        postdata = {'name': title, 'description': description}
        vimeoUrl = '/videos/%s' % int(video_id)
        json_data = v.patch(vimeoUrl, data=postdata)
        return 'Updated Successfully'
Example #5
0
def get_vimeo_videos(request):
    subscription = Subscription.objects.get(user=request.user)
    if not subscription:
        return Response({"message": "Invalid subscription"},
                        status=status.HTTP_401_UNAUTHORIZED)
    v = vimeo.VimeoClient(token=subscription.vimeo_token,
                          key=settings.VIMEO_CLIENT_IDENTIFIED,
                          secret=settings.VIMEO_CLIENT_SECRET)

    try:
        video_list = v.get(
            '/me/videos?per_page=100&fields=uri,name,pictures.sizes')
        if video_list.status_code == 200:
            return Response(video_list.json().get('data'),
                            status=status.HTTP_200_OK)
        elif video_list.status_code == 401:
            return Response({'message': video_list.json().get('error')},
                            status=status.HTTP_401_UNAUTHORIZED)
        else:
            logger.exception(
                "error getting Videos from Vimeo. Error Code: {0}, Error Message: {1}"
                .format(video_list.status_code,
                        video_list.json().get('error')))
            return Response({"message": "Failed to load video list"},
                            status=status.HTTP_400_BAD_REQUEST)
    except Exception as ex:
        logger.exception(ex)
        return Response({"message": ex.message},
                        status=status.HTTP_400_BAD_REQUEST)
Example #6
0
def post_file():
    if request.method == 'POST':
        # construct request
        client = vimeo.VimeoClient(
            token=access_token,
            key=client_id,
            secret=client_secret
        )

        try:
            # unpack payload
            data = json.loads(request.form.get('data'))
            name = data.get('name')
            description = data.get('description')
            filename = data.get('filename')
            projection = data.get('projection')
            stereo_format = data.get('stereo_format')

            file = request.files.get('file')
            if file and filename:
                file.save(filename)

                uri = client.upload(filename, data={
                    'name': name,
                    'description': description,
                    'spatial.projection': projection,
                    'spatial.stereo_format': stereo_format
                })

                os.remove(filename)
                return jsonify({'res': {'uri': uri}})
            else:
                return jsonify({'err': 'No file provided'})
        except Exception as err:
            return jsonify({'err': str(err)})
Example #7
0
def authorize_vimeo_success(request):
    subscription = Subscription.objects.get(user=request.user)
    if not subscription:
        return HttpResponse('Unauthorized', status=401)

    if not request.GET.get('error') and request.GET.get('state') == 'xyz':
        v = vimeo.VimeoClient(
            key=settings.VIMEO_CLIENT_IDENTIFIED,
            secret=settings.VIMEO_CLIENT_SECRET)
        token, user, scope = v.exchange_code(request.GET.get('code'),
                                             settings.BASE_URL + '/auth/vimeo/success')
        subscription.vimeo_token = token
        subscription.vimeo_scope = scope
        subscription.save()

        # try and populate feed titles and images
        feeds_without_titles = Feed.objects.filter(owner=request.user, provider__name='vimeo', video_thumbnail='')
        for feed in feeds_without_titles:
            title, image = get_vimeo_title_and_thumbnail_with_subscription(feed.video_id, subscription)
            if title:
                feed.video_title = title
                feed.video_thumbnail = image
                feed.save()

    return redirect('/app/dashboard')
Example #8
0
def course_detail(request ):
	v = vimeo.VimeoClient(
		    token=settings.VIMEO_ACCESS_TOKEN,
		    key=settings.VIMEO_CLIENT_ID,
		    secret=settings.VIMEO_CLIENT_SECRET
		)

	# course_obj = vimeo_project.objects.all()
	course_obj = sorted(vimeo_project.objects.all(), key=lambda n: (n.name.split('Module ')[1]))
	# about_me = v.get('/me/projects?sort=date&direction=desc', params={"fields": "uri, name"})

	# for i in about_me.json()['data']:
	# 	about_me2 = v.get(str(i['uri'])+str('/videos'), params={"fields": "name, link, embed.html, duration, description, pictures.sizes", "per_page":100, "page": 2 })

	# 	try:
	# 		if not vimeo_project.objects.filter(name=i['name']).exists():
	# 			q_2 = vimeo_project(name=i['name'], url=i['uri'])
	# 			q_2.save()
	# 		else:
	# 			q_2 = vimeo_project.objects.get(name=i['name'])


	# 		for x  in about_me2.json()['data']:				 
	# 			if vimeo_videos.objects.filter(project=vimeo_project.objects.get(name=i['name']), url=x['link']).exists():
	# 				q_1 = vimeo_videos.objects.filter(project=vimeo_project.objects.get(name=i['name']), url=x['link']).update(name=x['name'])


	# 				# q_1 = vimeo_videos(project=vimeo_project.objects.get(name=i['name']), url=x['link'], html=x['embed']['html'], duration=x['duration'], thub_url=x['pictures']['sizes'][2])
	# 				# q_1.save()
	# 	except:
	# 		pass
		 
	return render(request, 'course_learning/coursedetails.html', { 'course_obj':course_obj})
Example #9
0
def upload(path):
    config_file = os.path.dirname(os.path.realpath(__file__)) + '/config.json'
    config = json.load(open(config_file))

    if 'client_id' not in config or 'client_secret' not in config:
        raise Exception(
            'We could not locate your client id or client secret ' + 'in `' +
            config_file + '`. Please create one, and ' +
            'reference `config.json.example`.')

    # Instantiate the library with your client id, secret and access token
    # (pulled from dev site)
    client = vimeo.VimeoClient(token=config['access_token'],
                               key=config['client_id'],
                               secret=config['client_secret'])

    # Create a variable with a hard coded path to your file system
    # TODO: accept via argparse
    file_name = '<full path to a video on the filesystem>'

    print('Uploading: %s' % file_name)

    try:
        # Upload the file and include the video title and description.
        uri = client.upload(
            file_name,
            data={
                'name':
                'Vimeo API SDK test upload',
                'description':
                "This video was uploaded through the Vimeo API's " +
                "Python SDK."
            })

        # Get the metadata response from the upload and log out the Vimeo.com url
        video_data = client.get(uri + '?fields=link').json()
        print('"%s" has been uploaded to %s' % (file_name, video_data['link']))

        # Make an API call to edit the title and description of the video.
        client.patch(uri,
                     data={
                         'name':
                         'Vimeo API SDK test edit',
                         'description':
                         "This video was edited through the Vimeo API's " +
                         "Python SDK."
                     })

        print('The title and description for %s has been edited.' % uri)

        # Make an API call to see if the video is finished transcoding.
        video_data = client.get(uri + '?fields=transcode.status').json()
        print('The transcode status for %s is: %s' %
              (uri, video_data['transcode']['status']))
    except vimeo.exceptions.VideoUploadFailure as e:
        # We may have had an error. We can't resolve it here necessarily, so
        # report it to the user.
        print('Error uploading %s' % file_name)
        print('Server reported: %s' % e.message)
Example #10
0
def upload(filename):
    ident, secret, token = auth('vimeo',
                                ['client_id', 'client_secret', 'token'])
    api = vimeo.VimeoClient(token=token, key=ident, secret=secret)

    print 'Uploading...'
    api.upload(filename)
    print 'Done!'
Example #11
0
 def __init__(self, video_amount: int = None):
     self.default_params = {
         'per_page':
         video_amount if video_amount else settings.SEARCH_VIMEO_AMOUNT
     }
     self.client = vimeo.VimeoClient(token=settings.VIMEO_ACCESS_TOKEN,
                                     key=settings.VIMEO_CLIENT_ID,
                                     secret=settings.VIMEO_CLIENT_SECRET)
Example #12
0
def Vimeo_Upload(video):
    v = vimeo.VimeoClient(token=config.TOKEN,
                          key=config.CLIENT_ID,
                          secret=config.CLIENT_SECRET)
    about_me = v.get('/me')
    assert about_me.status_code == 200
    video_uri = v.upload(video.file)
    video_uri = (video_uri.split('s')[0] + video_uri.split('s')[1])
    return video_uri
Example #13
0
    def auth(self, creds):

        client = vimeo.VimeoClient(
                  key=creds['client_id'],
                  secret=creds["client_secret"],
                  token=creds["access"],
                  token_secret=creds["access_secret"],
                  format="json")
        return client
Example #14
0
def authorize_vimeo(request):
    if not request.user.get_subscription():
        return HttpResponse('Unauthorized', status=401)
    v = vimeo.VimeoClient(
        key=settings.VIMEO_CLIENT_IDENTIFIED,
        secret=settings.VIMEO_CLIENT_SECRET)
    vimeo_authorization_url = v.auth_url(['public', 'private'],
                                         settings.BASE_URL + '/auth/vimeo/success', 'xyz')
    return redirect(vimeo_authorization_url)
Example #15
0
def getVideo(id):
    client = vimeo.VimeoClient(
        token='1a028b267f6e92a4f90389b031d33b60',
        key='a591a007d8a09bc7fd57c50d325180224bdffa25',
        secret=
        '4IWycSdPpr9m73k/5TTQF+WBUV631kUtK4EQETBVhzmweZXTiOZp7jYYSP3cEXrzSLfS2IrQh1lnVPevXvZPbyRJV3UKWYwfhzHr68nUHSHg+Srm3BvqOiPvc8gAjWH3'
    )
    res = client.get('/videos/' + id[18:])
    jsonData = res.json()
    return jsonData
Example #16
0
def add_vimeo(url, uri):
    personal_token: str = os.getenv("PAT")
    client_id: str = os.getenv("CID")
    secret_key: str = os.getenv("SAT")
    video = f"https://api.vimeo.com/videos{url[uri:]}"
    client = vimeo.VimeoClient(token=personal_token,
                               key=client_id,
                               secret=secret_key)
    response = client.get(video)
    return vimeo_to_db(
        response.json()) if response.status_code == 200 else "Invalid URL"
    def get_video(self):
        if self.vimeo_id:
            v = vimeo.VimeoClient(token=VIMEO_ACCESS_TOKEN,
                                  key=VIMEO_CLIENT_KEY,
                                  secret=VIMEO_CLIENT_SECRET)

            response = v.get("/videos/%s" % (self.vimeo_id, ), params={})
            data = response.json()
        else:
            data = None
        return data
Example #18
0
def requestOAuth():
    oauth2Server.callback = processResoponse

    t = threading.Thread(target=oauth2Server.run, args=())
    t.start()

    v = vimeo.VimeoClient(key=KEY, secret=SECRET)

    vimeo_authorization_url = v.auth_url(['public', 'private', 'upload'],
                                         'http://localhost:8081', '')
    webbrowser.open(vimeo_authorization_url)
Example #19
0
def conectarVimeo(tokenF, keyF, secretF):
    v = vimeo.VimeoClient(token=tokenF, key=keyF, secret=secretF)
    print(tokenF)
    # Make the request to the server for the "/me" endpoint.
    about_me = v.get('/me')
    # Make sure we got back a successful response.
    #assert about_me.status_code == 200

    # Load the body's JSON data.
    respostaStatus = about_me.json()
    print(respostaStatus)
    return respostaStatus
Example #20
0
def upload(vimeoObj, VidLocation, titleVid, description, tag, count=1):
    if count == 5:
        print "Retring in upload failed"
        return

    v = vimeo.VimeoClient(token=vimeoObj, key=KEY, secret=SECRET)
    try:
        video_uri = v.upload(VidLocation)
        v.patch(video_uri, data={'name': titleVid, 'description': description})
        print "upload complete"
    except:
        print "Upload failed. Retrying..."
        upload(vimeoObj, VidLocation, titleVid, description, tag, count + 1)
Example #21
0
def sync():
    personal_token: str = os.getenv("PAT")
    client_id: str = os.getenv("CID")
    secret_key: str = os.getenv("SAT")
    uri = '/me/videos'
    client = vimeo.VimeoClient(token=personal_token,
                               key=client_id,
                               secret=secret_key)
    response = client.get(uri)

    if response.status_code == 200:
        data = response.json()
        return (add_items(data['data']))
    def list(self, request, *args, **kwargs):
        endpoint = kwargs.get('endpoint', None)
        if endpoint == '' or endpoint == None:
            return Response(False)

        v = vimeo.VimeoClient(token=VIMEO_ACCESS_TOKEN,
                              key=VIMEO_CLIENT_KEY,
                              secret=VIMEO_CLIENT_SECRET)

        response = v.get("/%s" % (endpoint, ), params=dict(request.GET))
        data = response.json()

        return Response(data, status=response.status_code)
Example #23
0
def processResoponse(CODE_FROM_URL):
    """This section completes the authentication for the user."""
    v = vimeo.VimeoClient(key=KEY, secret=SECRET)
    # You should retrieve the "code" from the URL string Vimeo redirected to.  Here that's named CODE_FROM_URL
    try:
        token, user, scope = v.exchange_code(CODE_FROM_URL,
                                             'http://localhost:8081')
        print token
        print scope
    except vimeo.auth.GrantFailed:
        print "tokening failed"

    print caller
    caller.vimeoObj = token
Example #24
0
def get_client(config):

    if 'client_id' not in config or 'client_secret' not in config:
        raise Exception(
            'We could not locate your client id or client secret ' + 'in `' +
            config_file + '`. Please create one, and ' +
            'reference `config.json.example`.')

    # Instantiate the library with your client id, secret and access token
    # (pulled from dev site)
    client = vimeo.VimeoClient(token=config['access_token'],
                               key=config['client_id'],
                               secret=config['client_secret'])

    return client
Example #25
0
def get_vimeo_title_and_thumbnail_with_subscription(video_id, subscription):
    if not subscription.vimeo_token:
        return

    v = vimeo.VimeoClient(token=subscription.vimeo_token,
                          key=settings.VIMEO_CLIENT_IDENTIFIED,
                          secret=settings.VIMEO_CLIENT_SECRET)
    video = v.get(
        '/me/videos/{0}?fields=uri,name,pictures.sizes'.format(video_id))
    if video.status_code == 200:
        try:
            video_json = video.json()
            return video_json.get('name'), video_json.get('pictures').get(
                'sizes')[3].get('link')
        except:
            pass
    return "", ""
def getVideos():
    v = vimeo.VimeoClient(
        token="81e7f05a8bdd4aeca46f464705c877a3",
        key="4ae71a994fd01243ec81198daba42fe517832820",
        secret=
        "8UbigGyYMe1/EfEecJxL/n5QneEeSPoBm2uKN+mTZnSyn9oMWeIIuBZ6eEGV6jJnAWQOfcL4L6GPwcAVDrU7/MWso4rhJgz585I+DwQdSRLOlp+/BZ8QDk0SNDUt64Kw"
    )

    about_me = v.get(
        '/me/videos?per_page=100&filter=playable&query=Menni&sort=date&weak_search=true',
        params={"fields": "link, name, pictures"})
    assert about_me.status_code == 200
    jsonData = about_me.json()
    strData = json.dumps(jsonData)

    dataLoc = strData.find("data") + 7
    strData = strData[dataLoc:len(strData)]
    return strData
Example #27
0
 def post(self, request):
     key = getattr(settings, 'VIMEO_CLIENT_ID', '')
     secret = getattr(settings, 'VIMEO_CLIENT_SECRET_ID', '')
     token = getattr(settings, 'VIMEO_TOKEN', '')
     v = vimeo.VimeoClient(key=key, secret=secret, token=token)
     file_path = self.handle_uploaded_file(request.data['video'])
     try:
         video_uri = v.upload(file_path)
         if video_uri:
             a = video_uri.split('/')
             dt.sleep(5)
             return Response('https://vimeo.com/{}'.format(a[-1]))
         else:
             return Response(False)
     except OSError:
         pass
     finally:
         os.remove(file_path)
Example #28
0
def demo(request):
	v = vimeo.VimeoClient(
		    token=settings.VIMEO_ACCESS_TOKEN,
		    key=settings.VIMEO_CLIENT_ID,
		    secret=settings.VIMEO_CLIENT_SECRET
		)
	  
	about_me = v.get('/me/projects/828255/videos?sort=date&direction=desc')
	# about_me = v.get('/me/projects', params={ "per_page":100, "page": 1 })
	# 	lst = ""

	# for i in vimeo_videos.objects.all():
	# 	try:
	# 		i.name.split('Slide')[1].strip()
	# 	except:
	# 		lst += str(i.id) + "<br>"
	 
	return JsonResponse(about_me.json(), safe=False)
Example #29
0
def connect_to_vimeo(config_file):
    config = json.load(open(config_file))

    if 'client_id' not in config or 'client_secret' not in config:
        raise ConnectionError(
            'No client_id or client_secret found in {}'.format(config_file))

    vimeo_client = vimeo.VimeoClient(token=config['access_token'],
                                     key=config['client_id'],
                                     secret=config['client_secret'])

    about_me = vimeo_client.get(
        '/me')  # Make the request to the server for the "/me" endpoint.

    if about_me.status_code != 200:
        raise ValueError('Cannot get /me, status is {}'.format(
            about_me.status_code))

    return vimeo_client
Example #30
0
def refresh_view_count(_id=None):
    from velo.gallery.models import Video
    videos = Video.objects.filter(status=1).order_by('-id')

    if _id:
        videos = videos.filter(id=_id)

    if not datetime.date.today().day == 1:
        videos = videos[:20]  # Daily we update only last 20 video counters, but once in month we update all.

    YOUTUBE_API_SERVICE_NAME = "youtube"
    YOUTUBE_API_VERSION = "v3"

    storage = Storage("gallery/youtube-oauth2.json")
    credentials = storage.get()

    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
      http=credentials.authorize(httplib2.Http()))

    v = vimeo.VimeoClient(token=settings.VIMEO_TOKEN, key=settings.VIMEO_KEY, secret=settings.VIMEO_SECRET)

    for video in videos:
        if video.kind == 1: # youtube
            video_response = youtube.videos().list(
                id=video.video_id,
                part='statistics'
              ).execute()
            item = video_response.get('items')[0]
            video.view_count = int(item.get('statistics').get('viewCount'))

            # TODO: Add YOUTUBE VIDEO Availability checker

        elif video.kind == 2: # vimeo
            video_response = v.get('/videos/%s' % video.video_id)
            if video_response.status_code == 200:
                item = video_response.json()
                video.view_count = int(item.get('stats').get('plays'))
                if item.get('status') != 'available':
                    video.status = 0
            elif video_response.status_code == 404:
                video.status = 0
        video.save()