Exemplo n.º 1
0
 def connect(self, query):
     sess = DropboxSession(self.app_key, self.app_secret, "app_folder")
     # Access token is saved to memcache and the filesystem
     s_token = self.cache.get("s_token") or read_file(".s_token")
     s_secret = self.cache.get("s_secret") or read_file(".s_secret")
     if s_token and s_secret:
         sess.set_token(s_token, s_secret)
     elif "oauth_token" in query:  # callback from Dropbox
         s_token = sess.obtain_access_token(dropbox.session.OAuthToken(
             self.cache.get("r_token"), self.cache.get("r_token_secret")))
         self.cache.set("s_token", s_token.key)
         self.cache.set("s_secret", s_token.secret)
         with open(".s_token", "w") as f:
             f.write(s_token.key)
         with open(".s_secret", "w") as f:
             f.write(s_token.secret)
         self.cache.delete("r_token")
         self.cache.delete("r_token_secret")
     else:  # start of Dropbox auth
         req_token = sess.obtain_request_token()
         self.cache.set("r_token", req_token.key)
         self.cache.set("r_token_secret", req_token.secret)
         url = sess.build_authorize_url(req_token, cherrypy.url())
         raise cherrypy.HTTPRedirect(url)
     self.client = DropboxClient(sess)
Exemplo n.º 2
0
class DropboxAPIFacade(object):
	is_setup = False

	"""Easy to use facade for the Dropbox API and database

	Provides full functionality to use the Dropbox API. It saves and retrieves
	access/request tokens automatically from the database. The API session gets
	fed with the right data from the database when it needs it. 

	"""

	def __init__(self, autostart):
		"""Creates the instance and sets up all data and session if autostart"""
		if autostart: self.setup()

	def setup(self):
		"""Retrieves all startup data and creates a new DropboxClient with it"""

		(access_key, access_secret) = dropbox_access.get_access_token()
		self.session = DropboxSession(DROPBOX_APP_KEY, DROPBOX_APP_SECRET, DROPBOX_ACCESS_TYPE)
		self.session.obtain_request_token()
		self.session.set_token(access_key, access_secret)
		self.client = DropboxClient(self.session)
		self.is_setup = True

	def get_account(self):
		"""Retrieves the account information from the Dropbox API"""

		try:
			return self.client.account_info()
		except ErrorResponse, e:
			return None
Exemplo n.º 3
0
 def connect(self, query):
     sess = DropboxSession(self.app_key, self.app_secret, "app_folder")
     # Access token is saved to memcache and the filesystem
     s_token = self.cache.get("s_token") or read_file(".s_token")
     s_secret = self.cache.get("s_secret") or read_file(".s_secret")
     if s_token and s_secret:
         sess.set_token(s_token, s_secret)
     elif "oauth_token" in query:  # callback from Dropbox
         s_token = sess.obtain_access_token(
             dropbox.session.OAuthToken(self.cache.get("r_token"),
                                        self.cache.get("r_token_secret")))
         self.cache.set("s_token", s_token.key)
         self.cache.set("s_secret", s_token.secret)
         with open(".s_token", "w") as f:
             f.write(s_token.key)
         with open(".s_secret", "w") as f:
             f.write(s_token.secret)
         self.cache.delete("r_token")
         self.cache.delete("r_token_secret")
     else:  # start of Dropbox auth
         req_token = sess.obtain_request_token()
         self.cache.set("r_token", req_token.key)
         self.cache.set("r_token_secret", req_token.secret)
         url = sess.build_authorize_url(req_token, cherrypy.url())
         raise cherrypy.HTTPRedirect(url)
     self.client = DropboxClient(sess)
Exemplo n.º 4
0
 def __init__(self, location='/Public'):
     session = DropboxSession(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TYPE, locale=None)
     session.set_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
     self.client = DropboxClient(session)
     self.account_info = self.client.account_info()
     self.location = location
     self.base_url = 'http://dl.dropbox.com/u/{uid}/'.format(**self.account_info)
Exemplo n.º 5
0
def connectDropbox():
    sess = DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)

    if os.path.exists(TOKENS):
        token_file = open(TOKENS)
        token_key, token_secret = token_file.read().split('|')
        token_file.close()
        sess.set_token(token_key, token_secret)
    else:
        request_token = sess.obtain_request_token()

        url = sess.build_authorize_url(request_token)

        # Make the user sign in and authorize this token
        print "url:", url
        print "Please visit this website and press the 'Allow' button, then hit 'Enter' here."

        raw_input()

        # This will fail if the user didn't visit the above URL and hit 'Allow'
        access_token = sess.obtain_access_token(request_token)

        # Save the key to the file so we don't need to do this again
        token_file = open(TOKENS, 'w')

        token_key = access_token.key
        token_secret = access_token.secret
        token_file.write("%s|%s" % (token_key, token_secret))

        token_file.close()

    client = DropboxClient(sess)
    print "Linked account: %s" % client.account_info()
    return client
Exemplo n.º 6
0
 def __init__(self):
     session = DropboxSession(settings.DROPBOX_CONSUMER_KEY,
                              settings.DROPBOX_CONSUMER_SECRET,
                              settings.DROPBOX_ACCESS_TYPE, locale=None)
     session.set_token(settings.DROPBOX_ACCESS_TOKEN,
                       settings.DROPBOX_ACCESS_TOKEN_SECRET)
     self.client = DropboxClient(session)
Exemplo n.º 7
0
 def __init__(self):
     session = DropboxSession(settings.DROPBOX_CONSUMER_KEY,
                              settings.DROPBOX_CONSUMER_SECRET,
                              settings.DROPBOX_ACCESS_TYPE,
                              locale=None)
     session.set_token(settings.DROPBOX_ACCESS_TOKEN,
                       settings.DROPBOX_ACCESS_TOKEN_SECRET)
     self.client = DropboxClient(session)
Exemplo n.º 8
0
    def post(self, request):
        try:
            result = {}
            path = request.POST["source_path"]
            session_id = request.POST["session_id"]
            user_id = get_user_from_session(session_id).id
            dest_path = request.POST["dest_path"]
            dest_path = dest_path.split("/")
            dest_path.append(str(user_id))
            dest_path[-1], dest_path[-2] = dest_path[-2], dest_path[-1]
            dest_path = "/".join(dest_path)
            print "dest_path at starting is ", dest_path
            try:
                # Increment the name of new directory by one
                directories = map(int, os.listdir(dest_path))
                dest_path += str(max(directories) + 1)
            except:
                # If no directory exists then give it name 1
                dest_path += "/" + "1"

            if dest_path[-1] != "/":
                # Append forward slash to given url if not exists
                dest_path += "/"
            if not os.path.isdir(dest_path):
                os.makedirs(dest_path)
            if path.split(":")[0].lower() == "s3":
                print "[DOWNLOAD API FOR S3]"
                bucket = path.split(":")[1][2:]
                source_path = str(path.split(":")[2])
                result = get_data_from_s3(request, source_path, dest_path, bucket, user_id)

            elif path.split(":")[0].lower() == "dropbox":
                print "[DOWNLOAD API FOR DROPBOX]"
                source_path = path.split(":")[1][1:]
                access_token = SocialToken.objects.get(account__user__id=user_id, app__name="Dropbox")
                session = DropboxSession(settings.DROPBOX_APP_KEY, settings.DROPBOX_APP_SECRET)
                access_key, access_secret = (
                    access_token.token,
                    access_token.token_secret,
                )  # Previously obtained OAuth 1 credentials
                session.set_token(access_key, access_secret)
                client = DropboxClient(session)
                token = client.create_oauth2_access_token()
                print "########### ok ###########"
                result = get_data_from_dropbox(request, source_path, dest_path, token, user_id)
            elif path.split(":")[0].lower() == "gdrive":
                # NON FUNCTIONAL
                get_data_from_google(request, path, access_token)
            else:
                shutil.rmtree(dest_path[:-1])
                result = {
                    "error": "Check if you have attached the type of cloud storage with your account or enter valid path"
                }
        except:
            shutil.rmtree(dest_path[:-1])
            result = {"error": "Invalid Input Provided"}
        print result
        return HttpResponse(json.dumps(result))
Exemplo n.º 9
0
 def obj_create(self, bundle, request=None, **kwargs):
     response =  super(ProjectResource, self).obj_create(bundle, request, **kwargs)
     user_profile = UserProfile.objects.get(user=request.user)
     if user_profile.is_dropbox_synced:
         sess = DropboxSession(settings.DROPBOX_AUTH_KEY, settings.DROPBOX_AUTH_SECRET, access_type=settings.DROPBOX_ACCESS_TYPE)
         sess.set_token(user_profile.dropbox_profile.access_token['key'], user_profile.dropbox_profile.access_token['secret'])
         api_client = client.DropboxClient(sess)
         api_client.file_create_folder(response.obj.title)
     return response
Exemplo n.º 10
0
 def __init__(self, location='/Public'):
     session = DropboxSession(CONSUMER_KEY,
                              CONSUMER_SECRET,
                              ACCESS_TYPE,
                              locale=None)
     session.set_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
     self.client = DropboxClient(session)
     self.account_info = self.client.account_info()
     self.location = location
     self.base_url = 'http://dl.dropbox.com/u/{uid}/'.format(
         **self.account_info)
 def __init__(self, token, rootPath):
     BaseDrive.__init__(self, token, rootPath)
     APP_KEY = '5a91csqjtsujuw7'
     APP_SECRET = 'x5wbkk2o273jqz7'
     session = DropboxSession(APP_KEY, APP_SECRET)
     print token
     access_key, access_secret = token.split(',')
     session.set_token(access_key, access_secret)
     first_client = DropboxClient(session)
     token1 = first_client.create_oauth2_access_token()
     self.client = DropboxClient(token1)
Exemplo n.º 12
0
 def __init__(self, file, name=None):
     self.dropbox_metadata = file
     name = name or os.path.basename(self.dropbox_metadata["path"])
     super(DropboxFile, self).__init__(file, name=name)
     self._size = self.dropbox_metadata["size"]
     access_type = getattr(settings, "DROPBOX_ACCESS_TYPE", "app_folder")
     dropbox_session = DropboxSession(settings.DROPBOX_APP_KEY,
                                      settings.DROPBOX_APP_SECRET_KEY,
                                      access_type)
     dropbox_session.set_token(settings.DROPBOX_APP_ACCESS_TOKEN,
                               settings.DROPBOX_APP_ACCESS_TOKEN_SECRET)
     self.dropbox_client = DropboxClient(dropbox_session)
Exemplo n.º 13
0
    def post(self, request):
        source_path = request.POST["source_path"]
        path = request.POST["dest_path"]
        session_id = request.POST["session_id"]
        user_id = get_user_from_session(session_id).id
        try:
            if path.split(":")[0].lower() == "s3":
                print "[UPLOAD API FOR S3]"
                bucket = path.split(":")[1][2:]
                dest_path = str(path.split(":")[2])
                result = post_data_on_s3(request, source_path, dest_path, bucket, user_id)

            elif path.split(":")[0].lower() == "dropbox":
                print "[UPLOAD API FOR DROPBOX]"
                dest_path = path.split(":")[1][1:]
                access_token = SocialToken.objects.get(account__user__id=user_id, app__name="Dropbox")
                session = DropboxSession(settings.DROPBOX_APP_KEY, settings.DROPBOX_APP_SECRET)
                access_key, access_secret = (
                    access_token.token,
                    access_token.token_secret,
                )  # Previously obtained OAuth 1 credentials
                session.set_token(access_key, access_secret)
                client = DropboxClient(session)
                token = client.create_oauth2_access_token()
                result = post_data_on_dropbox(request, source_path, dest_path, token, user_id)

            elif path.split(":")[0].lower() == "gdrive":
                """*** NOT WORKING ***"""
                print "[UPLOAD API FOR GOOGLE DRIVE]"
                storage = Storage(SocialToken, "id", user_id, "token")
                credential = storage.get()
                # credentials = SocialToken.objects.get(account__user__id = request.user.id, app__name = storage)
                # credentials = credentials.token
                http = credential.authorize(httplib2.Http())
                service = discovery.build("drive", "v2", http=http)
                results = service.files().list(maxResults=10).execute()
                items = results.get("items", [])
                if not items:
                    # print 'No files found.'
                    pass
                else:
                    # print 'Files:'
                    for item in items:
                        print "{0} ({1})".format(item["title"], item["id"])
                result = put_data_on_google_drive(request, path, access_token.token)

            else:
                result = {
                    "error": "Check if you have attached the type of cloud storage with your account or enter valid path"
                }
        except:
            result = {"error": "Incorrect Input"}
        return HttpResponse(json.dumps(result))
Exemplo n.º 14
0
 def __init__(self, *args, **kwargs):
     super(DropboxFileUploadHandler, self).__init__(*args, **kwargs)
     fallback_dropbox_folder = getattr(settings,
                                       "DROPBOX_FILE_UPLOAD_FOLDER", "/")
     self.dropbox_folder = kwargs.get("dropbox_folder",
                                      fallback_dropbox_folder)
     access_type = getattr(settings, "DROPBOX_ACCESS_TYPE", "app_folder")
     dropbox_session = DropboxSession(settings.DROPBOX_APP_KEY,
                                      settings.DROPBOX_APP_SECRET_KEY,
                                      access_type)
     dropbox_session.set_token(settings.DROPBOX_APP_ACCESS_TOKEN,
                               settings.DROPBOX_APP_ACCESS_TOKEN_SECRET)
     self.dropbox_client = DropboxClient(dropbox_session)
Exemplo n.º 15
0
    def get_userinfo(self):
        """
        {u'referral_link': u'https://db.tt/LbG4aSx1', u'display_name': u'waiting easilydo', u'uid': 330936854, u'country': u'HK', u'email': u'*****@*****.**', u'team': None, u'quota_info': {u'datastores': 0, u'shared': 0, u'quota': 2147483648, u'normal': 363213}}
        """
        sess = DropboxSession(self.client_id, self.client_secret, self.ACCESS_TYPE)
        sess.set_token(self.token['oauth_token'], self.token['oauth_token_secret'])

        api = DropboxClient(sess)
        try:
            res = api.account_info()
            return res
        except Exception, e:
            logging.warning("dropbox query info fail %s", e, exc_info=True)
            return None
Exemplo n.º 16
0
    def __init__(self, in_user_mode=True):
        """Connect to the Dropbox servers so that files can be uploaded"""

        self.m = Message(in_user_mode=in_user_mode)

        session = DropboxSession(API_KEY, API_SECRET, self.ACCESS_TYPE)

        token_file = PyJson(TOKEN_PATH)
        token = token_file.doc

        # If there is a token saved, that can be used to connect with Dropbox
        if 'key' in token and 'secret' in token:
            # Read the token and authenticate the session with it
            session.set_token(token['key'], token['secret'])

        # Otherwise it is necessary to authenticate for the first time
        else:
            # Request an access token
            request_token = session.obtain_request_token()
            url = session.build_authorize_url(request_token)

            # Open the authentication page in the user's browser and wait for them to accept
            webbrowser.open(url, new=2)

            print("Press enter once you have authorised the app in your browser")
            input()

            # Get a new access token from the authenticated session
            # This will fail if the user didn't visit the above URL and press 'Allow'
            try:
                access_token = session.obtain_access_token(request_token)

            except Exception as error:
                if DEBUG:
                    print(error)
                print("You didn't authorise the app, or something else went wrong")
                exit(1)

            # Save the access token to a file so that authentication is not needed next time the app is run
            token_file.add('key', access_token.key)
            token_file.add('secret', access_token.secret)
            token_file.save()

        # Create a Dropbox client from the session
        client = DropboxClient(session)

        self.client = client
Exemplo n.º 17
0
    def __init__(self, in_user_mode=True):
        """Connect to the Dropbox servers so that files can be uploaded"""

        self.m = Message(in_user_mode=in_user_mode)

        session = DropboxSession(API_KEY, API_SECRET, self.ACCESS_TYPE)

        token_file = PyJson(TOKEN_PATH)
        token = token_file.doc

        # If there is a token saved, that can be used to connect with Dropbox
        if 'key' in token and 'secret' in token:
            # Read the token and authenticate the session with it
            session.set_token(token['key'], token['secret'])

        # Otherwise it is necessary to authenticate for the first time
        else:
            # Request an access token
            request_token = session.obtain_request_token()
            url = session.build_authorize_url(request_token)

            # Open the authentication page in the user's browser and wait for them to accept
            webbrowser.open(url, new=2)

            print "Press enter once you have authorised the app in your browser"
            raw_input()

            # Get a new access token from the authenticated session
            # This will fail if the user didn't visit the above URL and press 'Allow'
            try:
                access_token = session.obtain_access_token(request_token)

            except Exception as error:
                if DEBUG:
                    print error
                print "You didn't authorise the app, or something else went wrong"
                exit(1)

            # Save the access token to a file so that authentication is not needed next time the app is run
            token_file.add('key', access_token.key)
            token_file.add('secret', access_token.secret)
            token_file.save()

        # Create a Dropbox client from the session
        client = DropboxClient(session)

        self.client = client
Exemplo n.º 18
0
    def __init__(self, connection_name='default', location='/Public'):
        connection = settings.DROPBOXES.get(connection_name, None)
        if not connection:
            raise ImproperlyConfigured("Could not load Dropbox Config '%s'" % connection_name)

        CONSUMER_KEY = connection.get('CONSUMER_KEY', None)
        CONSUMER_SECRET = connection.get('CONSUMER_SECRET', None)

        ACCESS_TOKEN = connection.get('ACCESS_TOKEN', None)
        ACCESS_TOKEN_SECRET = connection.get('ACCESS_TOKEN_SECRET', None)
        ACCESS_TYPE = connection.get('ACCESS_TYPE', None)

        session = DropboxSession(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TYPE, locale=None)
        session.set_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
        self.client = DropboxClient(session)
        self.account_info = self.client.account_info()
        self.location = location
        self.base_url = 'http://dl.dropbox.com/u/{uid}/'.format(**self.account_info)
Exemplo n.º 19
0
 def __init__(self, location=None):
   session = DropboxSession(DROPBOX.app_key, DROPBOX.app_secret, DROPBOX.access_type, locale=None)
   session.set_token(DROPBOX.access_key, DROPBOX.access_secret)
   self.client = DropboxClient(session)
   self.overwrite_mode = DROPBOX.overwrite_mode
   self._location = location