Skip to content
Browse files

Desktop App using Dropbox Api. There is oAuth authentication with Dro…

…pbox as the provider. Basic operations like get user account info, read file and write to file can be done to dropbox cloud using the Api
  • Loading branch information...
1 parent 39dfccb commit 2545a919e198e6b0be632a9f7243001c92a077f1 @Bhagyashree-Mandora committed
View
0 Dropbox_Api_Check_Dsktp/dropbox/__init__.py
No changes.
View
BIN Dropbox_Api_Check_Dsktp/dropbox/__init__.pyc
Binary file not shown.
View
222 Dropbox_Api_Check_Dsktp/dropbox/auth.py
@@ -0,0 +1,222 @@
+"""
+The dropbox.auth module is responsible for making OAuth work for the Dropbox
+Client API. It glues together all the separate parts of the Python OAuth
+reference implementation and gives a nicer API to it. You'll pass a
+configure dropbox.auth.Authenticator object to dropbox.client.DropboxClient
+in order to work with the API.
+"""
+
+import httplib
+import urllib
+import simplejson as json
+from oauth import oauth
+from ConfigParser import SafeConfigParser
+
+REALM="No Realm"
+HTTP_DEBUG_LEVEL=0
+
+class SimpleOAuthClient(oauth.OAuthClient):
+ """
+ An implementation of the oauth.OAuthClient class providing OAuth services
+ for the Dropbox Client API. You shouldn't have to use this, but if you need
+ to implement your own OAuth, then this is where to look.
+
+ One setting of interest is the HTTP_DEBUG_LEVEL, which you can set to a
+ larger number to get detailed HTTP output.
+ """
+ def __init__(self, server, port=httplib.HTTP_PORT, request_token_url='', access_token_url='', authorization_url=''):
+ self.server = server
+ self.port = port
+ self.request_token_url = request_token_url
+ self.access_token_url = access_token_url
+ self.authorization_url = authorization_url
+ self.connection = httplib.HTTPConnection(self.server, int(self.port))
+ self.connection.set_debuglevel(HTTP_DEBUG_LEVEL)
+
+ def fetch_request_token(self, oauth_request):
+ """Called by oauth to fetch the request token from Dropbox. Returns an OAuthToken."""
+ self.connection.request(oauth_request.http_method,
+ self.request_token_url,
+ headers=oauth_request.to_header())
+ response = self.connection.getresponse()
+ data = response.read()
+ assert response.status == 200, "Invalid response code %d : %r" % (response.status, data)
+ return oauth.OAuthToken.from_string(data)
+
+ def fetch_access_token(self, oauth_request, trusted_url=None):
+ """Used to get a access token from Drobpox using the headers. Returns an OauthToken."""
+ url = trusted_url if trusted_url else self.access_token_url
+
+ self.connection.request(oauth_request.http_method, url,
+ headers=oauth_request.to_header())
+
+ response = self.connection.getresponse()
+ assert response.status == 200, "Invalid response code %d" % response.status
+ if trusted_url:
+ token = json.loads(response.read())
+ token['token'] = str(token['token'])
+ token['secret'] = str(token['secret'])
+ return oauth.OAuthToken(token['token'], token['secret'])
+ else:
+ return oauth.OAuthToken.from_string(response.read())
+
+ def authorize_token(self, oauth_request):
+ """
+ This is not used in the Drobpox API.
+ """
+ raise NotImplementedError("authorize_token is not implemented via OAuth.")
+
+ def access_resource(self, oauth_request):
+ """
+ Not used by the Dropbox API.
+ """
+ raise NotImplementedError("access_resource is not implemented via OAuth.")
+
+
+
+
+class Authenticator(object):
+ """
+ The Authenticator puts a thin gloss over the oauth.oauth Python library
+ so that the dropbox.client.DropboxClient doesn't need to know much about
+ your configuration and OAuth operations.
+
+ It uses a configuration file in the standard .ini format that ConfigParser
+ understands. A sample configuration is included in config/testing.ini
+ which you should copy and put in your own consumer keys and secrets.
+
+ Because different installations may want to store these configurations
+ differently, you aren't required to configure an Authenticator via
+ the .ini method. As long as you configure it with a dict with the
+ same keys you'll be fine.
+ """
+
+ def __init__(self, config):
+ """
+ Configures the Authenticator with all the required settings in config.
+ Typically you'll use Authenticator.load_config() to load these from
+ a .ini file and then pass the returned dict to here.
+ """
+ self.client = SimpleOAuthClient(config['server'],
+ config['port'],
+ config['request_token_url'],
+ config['access_token_url'],
+ config['authorization_url'])
+
+ self.trusted_access_token_url = config.get('trusted_access_token_url', None)
+
+ self.consumer = oauth.OAuthConsumer(config['consumer_key'],
+ config['consumer_secret'])
+
+ self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
+
+ self.config = config
+
+
+ @classmethod
+ def load_config(self, filename):
+ """
+ Loads a configuration .ini file, and then pulls out the 'auth' key
+ to make a dict you can pass to Authenticator().
+ """
+ config = SafeConfigParser()
+ config_file = open(filename, "r")
+ config.readfp(config_file)
+ return dict(config.items('auth'))
+
+ def build_authorize_url(self, req_token, callback=None):
+ """
+ When you send a user to authorize a request token you created, you need
+ to make the URL correctly. This is the method you use. It will
+ return a URL that you can then redirect a user at so they can login to
+ Dropbox and approve this request key.
+ """
+ if callback:
+ oauth_callback = "&%s" % urllib.urlencode({'oauth_callback': callback})
+ else:
+ oauth_callback = ""
+
+ return "%s?oauth_token=%s%s" % (self.config['authorization_url'], req_token.key, oauth_callback)
+
+
+ def obtain_request_token(self):
+ """
+ This is your first step in the OAuth process. You call this to get a
+ request_token from the Dropbox server that you can then use with
+ Authenticator.build_authorize_url() to get the user to authorize it.
+ After it's authorized you use this token with
+ Authenticator.obtain_access_token() to get an access token.
+
+ NOTE: You should only need to do this once for each user, and then you
+ store the access token for that user for later operations.
+ """
+ self.oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
+ http_url=self.client.request_token_url)
+
+ self.oauth_request.sign_request(self.signature_method_hmac_sha1, self.consumer, None)
+
+ token = self.client.fetch_request_token(self.oauth_request)
+
+ return token
+
+
+ def obtain_access_token(self, token, verifier):
+ """
+ After you get a request token, and then send the user to the authorize
+ URL, you can use the authorized access token with this method to get the
+ access token to use for future operations. Store this access token with
+ the user so that you can reuse it on future operations.
+
+ The verifier parameter is not currently used, but will be enforced in
+ the future to follow the 1.0a version of OAuth. Make it blank for now.
+ """
+ self.oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
+ token=token,
+ http_url=self.client.access_token_url,
+ verifier=verifier)
+ self.oauth_request.sign_request(self.signature_method_hmac_sha1, self.consumer, token)
+
+ token = self.client.fetch_access_token(self.oauth_request)
+
+ return token
+
+ def obtain_trusted_access_token(self, user_name, user_password):
+ """
+ This is for trusted partners using a constrained device such as a mobile
+ or other embedded system. It allows them to use the user's password
+ directly to obtain an access token, rather than going through all the
+ usual OAuth steps.
+ """
+ assert user_name, "The user name is required."
+ assert user_password, "The user password is required."
+ assert self.trusted_access_token_url, "You must set trusted_access_token_url in your config file."
+ parameters = {'email': user_name, 'password': user_password}
+ params = urllib.urlencode(parameters)
+ assert params, "Didn't get a valid params."
+
+ url = self.trusted_access_token_url + "?" + params
+ self.oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, http_url=url, parameters=parameters)
+ self.oauth_request.sign_request(self.signature_method_hmac_sha1,
+ self.consumer, None)
+ token = self.client.fetch_access_token(self.oauth_request, url)
+ return token
+
+ def build_access_headers(self, method, token, resource_url, parameters, callback=None):
+ """
+ This is used internally to build all the required OAuth parameters and
+ signatures to make an OAuth request. It's provided for debugging
+ purposes.
+ """
+ params = parameters.copy()
+
+ if callback:
+ params['oauth_callback'] = callback
+
+ self.oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
+ token=token, http_method=method,
+ http_url=resource_url,
+ parameters=parameters)
+
+ self.oauth_request.sign_request(self.signature_method_hmac_sha1, self.consumer, token)
+ return self.oauth_request.to_header(), params
+
View
BIN Dropbox_Api_Check_Dsktp/dropbox/auth.pyc
Binary file not shown.
View
277 Dropbox_Api_Check_Dsktp/dropbox/client.py
@@ -0,0 +1,277 @@
+"""
+The main client API you'll be working with most often. You'll need to
+configure a dropbox.client.Authenticator for this to work, but otherwise
+it's fairly self-explanatory.
+"""
+
+from dropbox import rest
+import urllib
+import urllib2
+import poster
+import httplib
+
+API_VERSION=0
+HASH_BLOCK_SIZE=10*1024
+
+class DropboxClient(object):
+ """
+ The main access point of doing REST calls on Dropbox. You use it
+ by first creating and configuring a dropbox.auth.Authenticator,
+ and then configuring a DropboxClient to talk to the service. The
+ DropboxClient then does all the work of properly calling each API
+ with the correct OAuth authentication.
+ """
+
+
+ def __init__(self, api_host, content_host, port, auth, token):
+ """
+ The api_host and content_host are normally 'api.dropbox.com' and
+ 'api-content.dropbox.com' and will use the same port.
+ The auth is a dropbox.client.Authenticator that is properly configured.
+ The token is a valid OAuth `access token` that you got using
+ dropbox.client.Authenticator.obtain_access_token.
+ """
+ self.api_rest = rest.RESTClient(api_host, port)
+ self.content_rest = rest.RESTClient(content_host, port)
+ self.auth = auth
+ self.token = token
+ self.api_host = api_host
+ self.content_host = content_host
+ self.api_host = api_host
+ self.port = int(port)
+
+
+ def request(self, host, method, target, params, callback):
+ """
+ This is an internal method used to properly craft the url, headers, and
+ params for a Dropbox API request. It is exposed for you in case you
+ need craft other API calls not in this library or you want to debug it.
+
+ It is only expected to work for GET or POST parameters.
+ """
+ assert method in ['GET','POST'], "Only 'GET' and 'POST' are allowed for method."
+
+ base = self.build_full_url(host, target)
+ headers, params = self.auth.build_access_headers(method, self.token, base, params, callback)
+
+ if method == "GET":
+ url = self.build_url(target, params)
+ else:
+ url = self.build_url(target)
+
+ return url, headers, params
+
+
+ def account_info(self, status_in_response=False, callback=None):
+ """
+ Retrieve information about the user's account.
+
+ * callback. Optional. The server will wrap its response of format inside a call to the argument specified by callback. Value must contains only alphanumeric characters and underscores.
+ * status_in_response. Optional. Some clients (e.g., Flash) cannot handle HTTP status codes well. If this parameter is set to true, the service will always return a 200 status and report the relevant status code via additional information in the response body. Default is false.
+ """
+
+ params = {'status_in_response': status_in_response}
+
+ url, headers, params = self.request(self.api_host, "GET", "/account/info", params, callback)
+
+ return self.api_rest.GET(url, headers)
+
+
+ def put_file(self, root, to_path, file_obj):
+ """
+ Retrieve or upload file contents relative to the user's Dropbox root or
+ the application's sandbox directory within the user's Dropbox.
+
+ * root is one of "dropbox" or "sandbox", most clients will use "sandbox".
+ * to_path is the `directory` path to put the file (NOT the full path).
+ * file_obj is an open and ready to read file object that will be uploaded.
+
+ The filename is taken from the file_obj name currently, so you can't
+ have the local file named differently than it's target name. This may
+ change in future versions.
+
+ Finally, this function is not terribly efficient due to Python's
+ HTTPConnection requiring all of the file be read into ram for the POST.
+ Future versions will avoid this problem.
+ """
+ assert root in ["dropbox", "sandbox"]
+
+ path = "/files/%s%s" % (root, to_path)
+
+ params = { "file" : file_obj.name, }
+
+ url, headers, params = self.request(self.content_host, "POST", path, params, None)
+
+ params['file'] = file_obj
+ data, mp_headers = poster.encode.multipart_encode(params)
+ if 'Content-Length' in mp_headers:
+ mp_headers['Content-Length'] = str(mp_headers['Content-Length'])
+ headers.update(mp_headers)
+
+ conn = httplib.HTTPConnection(self.content_host, self.port)
+ conn.request("POST", url, "".join(data), headers)
+
+ resp = rest.RESTResponse(conn.getresponse())
+ conn.close()
+ file_obj.close()
+
+ return resp
+
+
+ def get_file(self, root, from_path):
+ """
+ Retrieves a file from the given root ("dropbox" or "sandbox") based on
+ from_path as the `full path` to the file. Unlike the other calls, this
+ one returns a raw HTTPResponse with the connection open. You should
+ do your read and any processing you need and then close it.
+ """
+ assert root in ["dropbox", "sandbox"]
+
+ path = "/files/%s%s" % (root, from_path)
+
+ url, headers, params = self.request(self.content_host, "GET", path, {}, None)
+ return self.content_rest.request("GET", url, headers=headers, raw_response=True)
+
+
+ def file_copy(self, root, from_path, to_path, callback=None):
+ """
+ Copy a file or folder to a new location.
+
+ * callback. Optional. The server will wrap its response of format inside a call to the argument specified by callback. Value must contains only alphanumeric characters and underscores.
+ * from_path. Required. from_path specifies either a file or folder to be copied to the location specified by to_path. This path is interpreted relative to the location specified by root.
+ * root. Required. Specify the root relative to which from_path and to_path are specified. Valid values are dropbox and sandbox.
+ * to_path. Required. to_path specifies the destination path including the new name for file or folder. This path is interpreted relative to the location specified by root.
+ """
+ assert root in ["dropbox", "sandbox"]
+
+ params = {'root': root, 'from_path': from_path, 'to_path': to_path}
+
+ url, headers, params = self.request(self.api_host, "POST", "/fileops/copy", params, callback)
+
+ return self.api_rest.POST(url, params, headers)
+
+
+ def file_create_folder(self, root, path, callback=None):
+ """
+ Create a folder relative to the user's Dropbox root or the user's application sandbox folder.
+
+ * callback. Optional. The server will wrap its response of format inside a call to the argument specified by callback. Value must contains only alphanumeric characters and underscores.
+ * path. Required. The path to the new folder to create, relative to root.
+ * root. Required. Specify the root relative to which path is specified. Valid values are dropbox and sandbox.
+ """
+ assert root in ["dropbox", "sandbox"]
+ params = {'root': root, 'path': path}
+
+ url, headers, params = self.request(self.api_host, "POST", "/fileops/create_folder", params, callback)
+
+ return self.api_rest.POST(url, params, headers)
+
+
+ def file_delete(self, root, path, callback=None):
+ """
+ Delete a file or folder.
+
+ * callback. Optional. The server will wrap its response of format inside a call to the argument specified by callback. Value must contains only alphanumeric characters and underscores.
+ * path. Required. path specifies either a file or folder to be deleted. This path is interpreted relative to the location specified by root.
+ * root. Required. Specify the root relative to which path is specified. Valid values are dropbox and sandbox.
+ """
+ assert root in ["dropbox", "sandbox"]
+
+ params = {'root': root, 'path': path}
+
+ url, headers, params = self.request(self.api_host, "POST", "/fileops/delete", params,
+ callback)
+
+ return self.api_rest.POST(url, params, headers)
+
+
+ def file_move(self, root, from_path, to_path, callback=None):
+ """
+ Move a file or folder to a new location.
+
+ * callback. Optional. The server will wrap its response of format inside a call to the argument specified by callback. Value must contains only alphanumeric characters and underscores.
+ * from_path. Required. from_path specifies either a file or folder to be copied to the location specified by to_path. This path is interpreted relative to the location specified by root.
+ * root. Required. Specify the root relative to which from_path and to_path are specified. Valid values are dropbox and sandbox.
+ * to_path. Required. to_path specifies the destination path including the new name for file or folder. This path is interpreted relative to the location specified by root.
+ """
+ assert root in ["dropbox", "sandbox"]
+
+ params = {'root': root, 'from_path': from_path, 'to_path': to_path}
+
+ url, headers, params = self.request(self.api_host, "POST", "/fileops/move", params, callback)
+
+ return self.api_rest.POST(url, params, headers)
+
+
+ def metadata(self, root, path, file_limit=10000, hash=None, list=True, status_in_response=False, callback=None):
+ """
+ The metadata API location provides the ability to retrieve file and
+ folder metadata and manipulate the directory structure by moving or
+ deleting files and folders.
+
+ * callback. Optional. The server will wrap its response of format inside a call to the argument specified by callback. Value must contains only alphanumeric characters and underscores.
+ * file_limit. Optional. Default is 10000. When listing a directory, the service will not report listings containing more than file_limit files and will instead respond with a 406 (Not Acceptable) status response.
+ * hash. Optional. Listing return values include a hash representing the state of the directory's contents. If you provide this argument to the metadata call, you give the service an opportunity to respond with a "304 Not Modified" status code instead of a full (potentially very large) directory listing. This argument is ignored if the specified path is associated with a file or if list=false.
+ * list. Optional. The strings true and false are valid values. true is the default. If true, this call returns a list of metadata representations for the contents of the directory. If false, this call returns the metadata for the directory itself.
+ * status_in_response. Optional. Some clients (e.g., Flash) cannot handle HTTP status codes well. If this parameter is set to true, the service will always return a 200 status and report the relevant status code via additional information in the response body. Default is false.
+ """
+
+ assert root in ["dropbox", "sandbox"]
+
+ path = "/metadata/%s%s" % (root, path)
+
+ params = {'file_limit': file_limit,
+ 'list': "true" if list else "false",
+ 'status_in_response': status_in_response}
+ if hash is not None:
+ params['hash'] = hash
+
+ url, headers, params = self.request(self.api_host, "GET", path, params, callback)
+
+ return self.api_rest.GET(url, headers)
+
+ def links(self, root, path):
+ assert root in ["dropbox", "sandbox"]
+ path = "/links/%s%s" % (root, path)
+ return self.build_full_url(self.api_host, path)
+
+
+ def build_url(self, url, params=None):
+ """Used internally to build the proper URL from parameters and the API_VERSION."""
+ if type(url) == unicode:
+ url = url.encode("utf8")
+ target_path = urllib2.quote(url)
+
+ if params:
+ return "/%d%s?%s" % (API_VERSION, target_path, urllib.urlencode(params))
+ else:
+ return "/%d%s" % (API_VERSION, target_path)
+
+
+ def build_full_url(self, host, target):
+ """Used internally to construct the complete URL to the service."""
+ port = "" if self.port == 80 else ":%d" % self.port
+ base_full_url = "http://%s%s" % (host, port)
+ return base_full_url + self.build_url(target)
+
+
+ def account(self, email='', password='', first_name='', last_name='', source=None):
+ params = {'email': email, 'password': password,
+ 'first_name': first_name, 'last_name': last_name}
+
+ url, headers, params = self.request(self.api_host, "POST", "/account",
+ params, None)
+
+ return self.api_rest.POST(url, params, headers)
+
+
+ def thumbnail(self, root, from_path, size='small'):
+ assert root in ["dropbox", "sandbox"]
+ assert size in ['small','medium','large']
+
+ path = "/thumbnails/%s%s" % (root, from_path)
+
+ url, headers, params = self.request(self.content_host, "GET", path,
+ {'size': size}, None)
+ return self.content_rest.request("GET", url, headers=headers, raw_response=True)
+
View
BIN Dropbox_Api_Check_Dsktp/dropbox/client.pyc
Binary file not shown.
View
93 Dropbox_Api_Check_Dsktp/dropbox/rest.py
@@ -0,0 +1,93 @@
+"""
+A simple JSON REST request abstraction that is used by the
+dropbox.client module. You shouldn't need to use this directly
+unless you're implementing unsupport methods.
+"""
+
+
+import httplib
+import simplejson as json
+import urllib
+
+
+class RESTClient(object):
+ """
+ An abstraction on performing JSON REST requests that is used internally
+ by the Dropbox Client API. It provides just enough gear to make requests
+ and get responses as JSON data.
+
+ It is not designed well for file uploads.
+ """
+
+ def __init__(self, host, port):
+ self.host = host
+ self.port = port
+
+ def request(self, method, url, post_params=None, headers=None, raw_response=False):
+ """
+ Given the method and url this will make a JSON REST request to the
+ configured self.host:self.port and returns a RESTResponse for you.
+ If you pass in a dict for post_params then it will urlencode them
+ into the body. If you give in a headers dict then it will add
+ those to the request headers.
+
+ The raw_response parameter determines if you get a RESTResponse or a
+ raw HTTPResponse object. In some cases, like getting a file, you
+ don't want any JSON decoding or extra processing. In that case set
+ this to True and you'll get a plain HTTPResponse.
+ """
+ params = post_params or {}
+ headers = headers or {}
+
+ if params:
+ body = urllib.urlencode(params)
+ else:
+ body = None
+
+ if body:
+ headers["Content-type"] = "application/x-www-form-urlencoded"
+
+ conn = httplib.HTTPConnection(self.host, self.port)
+ conn.request(method, url, body, headers)
+
+ if raw_response:
+ return conn.getresponse()
+ else:
+ resp = RESTResponse(conn.getresponse())
+ conn.close()
+
+ return resp
+
+ def GET(self, url, headers=None):
+ """Convenience method that just does a GET request."""
+ return self.request("GET", url, headers=headers)
+
+ def POST(self, url, params, headers=None):
+ """Convenience method that just does a POST request."""
+ return self.request("POST", url, post_params=params, headers=headers)
+
+
+class RESTResponse(object):
+ """
+ Returned by dropbox.rest.RESTClient wrapping the base http response
+ object to make it more convenient. It contains the attributes
+ http_response, status, reason, body, headers. If the body can
+ be parsed into json, then you get a data attribute too, otherwise
+ it's set to None.
+ """
+
+ def __init__(self, http_resp):
+ self.http_response = http_resp
+ self.status = http_resp.status
+ self.reason = http_resp.reason
+ self.body = http_resp.read()
+ self.headers = dict(http_resp.getheaders())
+
+ try:
+ self.data = json.loads(self.body)
+ except ValueError:
+ # looks like this isn't json, data is None
+ self.data = None
+
+
+
View
BIN Dropbox_Api_Check_Dsktp/dropbox/rest.pyc
Binary file not shown.
View
168 Dropbox_Api_Check_Dsktp/dsktp_api_check.py
@@ -0,0 +1,168 @@
+#!/usr/bin/env python
+
+import pygtk
+pygtk.require('2.0')
+import gtk
+from nose.tools import *
+from dropbox import auth, client, rest
+from helpers import login_and_authorize
+import httplib2
+from httplib2 import socks
+from oauth import oauth
+
+
+
+class ApiCheck:
+
+
+ # This function writes the data entered in the text box to
+ # the file used for writing data
+ def put_file(self,widget,data):
+
+
+ #An object of the Authenticator class from oAuth authentication of our App
+ config = auth.Authenticator.load_config("testing.ini")
+
+ dba = auth.Authenticator(config)
+ access_token=oauth.OAuthToken('r3ie1kzqr0ipxil', 'dbcqrsddgihp3w6')
+
+ print access_token
+
+ #An object of Client is created
+ db_client = client.DropboxClient(config['server'], config['content_server'], config['port'], dba, access_token)
+ root = config['root']
+
+
+ # Writes the data entered in the text box to the file
+ print "Send button is clicked..."
+ text = self.entry.get_text()
+
+ # This location of file is to be taken from the user's laptop
+ # A script which finds the location of the Dropbox folder
+ # needs to be run
+ myfile = open('ourfile.txt','w')
+
+ myfile.truncate()
+ myfile.write(text)
+ myfile.close()
+
+
+ f = open("ourfile.txt")
+ resp = db_client.put_file(root, "/", f)
+ #assert resp
+
+
+ assert_equal(resp.status, 200)
+
+
+ # gets the account information of the user
+ def account_info(self,widget,data):
+
+
+ # An object of the Authenticator class from oAuth authentication of our App
+ config = auth.Authenticator.load_config("testing.ini")
+
+ dba = auth.Authenticator(config)
+ access_token=oauth.OAuthToken('r3ie1kzqr0ipxil', 'dbcqrsddgihp3w6')
+
+ print access_token
+
+ # An object of Client is created
+ db_client = client.DropboxClient(config['server'], config['content_server'], config['port'], dba, access_token)
+ root = config['root']
+
+
+ # Gets the account info of user
+ db_client.file_delete(root, "/tohere")
+ resp = db_client.account_info()
+ assert resp
+ print resp.data
+ # assert_equal(resp.status, 200)
+ # assert_all_in(resp.data.keys(), [u'country', u'display_name', u'uid', u'quota_info'])
+
+
+ # reads data from the file
+ def get_file(self,widget,data):
+
+ # An object of the Authenticator class from oAuth authentication of our App
+ config = auth.Authenticator.load_config("testing.ini")
+
+ dba = auth.Authenticator(config)
+ access_token=oauth.OAuthToken('r3ie1kzqr0ipxil', 'dbcqrsddgihp3w6')
+
+ print access_token
+
+ # An object of Client is created
+ db_client = client.DropboxClient(config['server'], config['content_server'], config['port'], dba, access_token)
+ root = config['root']
+
+
+ # Prints the retrieved file
+ resp = db_client.get_file(root, "/ourfile.txt")
+ assert_equal(resp.status, 200)
+ print resp.read()
+ #assert len(resp.read()) > 100
+
+ return db_client
+
+
+
+
+ # Causing the close button to close the window
+ def delete_event(self, widget, event, data=None):
+ gtk.main_quit
+ return False
+
+
+ # The GUI Description of the Window
+ def __init__(self):
+
+ # Create a new window
+ self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
+ self.window.set_title("Our App")
+ self.window.connect("delete_event", self.delete_event)
+ self.window.set_border_width(10)
+ self.window.set_position(gtk.WIN_POS_CENTER)
+
+ # Horizontal box to pack widgets
+ self.box1 = gtk.HBox(False, 0)
+ self.window.add(self.box1)
+
+ # Text Box for text input
+ self.entry = gtk.Entry()
+ self.box1.pack_start(self.entry, True, True, 0)
+ self.entry.show()
+
+ # Account Info button to get info of users account.
+ self.button4 = gtk.Button("Acc Info")
+ self.button4.connect("clicked", self.account_info, "button 4")
+ self.box1.pack_start(self.button4, True, True, 0)
+
+ # Send button to write to file.
+ self.button2 = gtk.Button("Send")
+ self.button2.connect("clicked", self.put_file, "button 2")
+ self.box1.pack_start(self.button2, True, True, 0)
+
+ # Get button to read a file.
+ self.button3 = gtk.Button("Get")
+ self.button3.connect("clicked", self.get_file, "button 3")
+ self.box1.pack_start(self.button3, True, True, 0)
+
+ # Show Widgets
+ self.button2.show()
+ self.button3.show()
+ self.button4.show()
+ self.box1.show()
+ self.window.show()
+
+
+
+
+def main():
+ gtk.mainloop()
+
+
+if __name__ == "__main__":
+ check = ApiCheck()
+ main()
+
View
106 Dropbox_Api_Check_Dsktp/dsktp_authorisation.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python
+
+import pygtk
+pygtk.require('2.0')
+import gtk
+from nose.tools import *
+from dropbox import auth
+from helpers import login_and_authorize
+import httplib2
+from httplib2 import socks
+
+
+
+CALLBACK_URL = 'http://printer.example.com/request_token_ready'
+RESOURCE_URL = 'http://www.dropbox.com/0/oauth/echo'
+
+
+class oAuthProcess:
+
+ def authorisation(self, widget, data):
+
+ print "Send button is clicked..."
+
+ # creates a dict which stores key and secret
+ config = auth.Authenticator.load_config("testing.ini")
+
+ for key in ['server', 'port', 'consumer_key', 'consumer_secret', 'verifier']:
+ print config[key]
+
+ dba = auth.Authenticator(config)
+
+ # gets temporary token
+ req_token = dba.obtain_request_token()
+ print req_token
+
+ # directs user to get user permission
+ authorize_url = dba.build_authorize_url(req_token, callback="http://localhost/")
+ assert "localhost" in authorize_url, "Should have the return address in it."
+
+ # authorize_url = dba.build_authorize_url(req_token)
+ # login_and_authorize(authorize_url, config)
+
+ print "Goto this Url: ", authorize_url
+
+ # Request token obtained after permission is used to get access token
+ req_token.key = raw_input("Enter the token you got:")
+ access_token = dba.obtain_access_token(req_token, config['verifier'])
+
+ assert access_token
+ assert dba.oauth_request
+ assert access_token.key != req_token.key
+
+ print access_token
+
+
+ def test_build_access_headers():
+ token, dba = test_obtain_access_token()
+ assert token
+ headers, params = dba.build_access_headers("GET", token, RESOURCE_URL, {'image': 'test.png'}, CALLBACK_URL)
+ assert headers
+ assert params
+
+
+
+ # Causing the close button to close the window
+ def delete_event(self, widget, event, data=None):
+ gtk.main_quit
+ return False
+
+
+ # The GUI Description of the Window
+ def __init__(self):
+
+ # Create a new window
+ self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
+ self.window.set_title("Our App")
+ self.window.connect("delete_event", self.delete_event)
+ self.window.set_border_width(10)
+
+ # Horizontal box to pack widgets
+ self.box1 = gtk.HBox(False, 0)
+ self.window.add(self.box1)
+
+ # Text Box for text input
+ self.entry = gtk.Entry()
+ self.box1.pack_start(self.entry, True, True, 0)
+ self.entry.show()
+
+ # Send button. Works on Click event
+ self.button2 = gtk.Button("Get")
+ self.button2.connect("clicked", self.authorisation, "button 2")
+ self.box1.pack_start(self.button2, True, True, 0)
+
+ # Show Widgets
+ self.button2.show()
+ self.box1.show()
+ self.window.show()
+
+
+def main():
+ gtk.mainloop()
+
+
+if __name__ == "__main__":
+ authobj = oAuthProcess()
+ main()
View
28 Dropbox_Api_Check_Dsktp/helpers.py
@@ -0,0 +1,28 @@
+from mechanize import Browser, FormNotFoundError
+
+def login_and_authorize(authorize_url, config):
+ print "AUTHORIZING", authorize_url
+
+ br = Browser()
+ br.set_debug_redirects(True)
+ br.open(authorize_url)
+ print "FIRST PAGE", br.title(), br.geturl()
+ br.select_form(nr=1)
+ br['login_email'] = config['testing_user']
+ br['login_password'] = config['testing_password']
+
+ resp = br.submit()
+ print "RESULT PAGE TITLE", br.title()
+ print "RESULT URL", resp.geturl()
+
+ assert br.viewing_html(), "Looks like it busted."
+
+ try:
+ br.select_form(nr=1)
+ br.submit()
+ assert br.viewing_html(), "Looks like it busted."
+ assert "API Request Authorized" in br.title(), "Title Is Wrong (bad email/password?): %r at %r" % (br.title(), br.geturl())
+ except FormNotFoundError:
+ print "Looks like we're blessed."
+
+
View
26 Dropbox_Api_Check_Dsktp/testing.ini
@@ -0,0 +1,26 @@
+[auth]
+server = api.dropbox.com
+content_server = api-content.dropbox.com
+port = 80
+
+request_token_url = https://api.dropbox.com/0/oauth/request_token
+access_token_url = https://api.dropbox.com/0/oauth/access_token
+authorization_url = https://www.dropbox.com/0/oauth/authorize
+trusted_access_token_url = https://api.dropbox.com/0/token
+
+# the root of Dropbox operations. should be either dropbox or sandbox, depending on your app's setup
+root = dropbox
+
+# key and secret granted by the service provider for this consumer application - same as the mockoauthdatastore
+consumer_key = 9xok2ki1zjn2r1p
+consumer_secret = szsiqick0cqrcu8
+
+# leave the verifier blank for now
+verifier =
+
+# these two configurations aren't needed in normal operation,
+# they're only used during the unit tests to make sure that
+# everything is working.
+testing_user = bhagyashree.mandora@yahoo.co.in
+testing_password =
+
View
222 auth.py
@@ -0,0 +1,222 @@
+"""
+The dropbox.auth module is responsible for making OAuth work for the Dropbox
+Client API. It glues together all the separate parts of the Python OAuth
+reference implementation and gives a nicer API to it. You'll pass a
+configure dropbox.auth.Authenticator object to dropbox.client.DropboxClient
+in order to work with the API.
+"""
+
+import httplib
+import urllib
+import simplejson as json
+from oauth import oauth
+from ConfigParser import SafeConfigParser
+
+REALM="No Realm"
+HTTP_DEBUG_LEVEL=0
+
+class SimpleOAuthClient(oauth.OAuthClient):
+ """
+ An implementation of the oauth.OAuthClient class providing OAuth services
+ for the Dropbox Client API. You shouldn't have to use this, but if you need
+ to implement your own OAuth, then this is where to look.
+
+ One setting of interest is the HTTP_DEBUG_LEVEL, which you can set to a
+ larger number to get detailed HTTP output.
+ """
+ def __init__(self, server, port=httplib.HTTP_PORT, request_token_url='', access_token_url='', authorization_url=''):
+ self.server = server
+ self.port = port
+ self.request_token_url = request_token_url
+ self.access_token_url = access_token_url
+ self.authorization_url = authorization_url
+ self.connection = httplib.HTTPConnection(self.server, int(self.port))
+ self.connection.set_debuglevel(HTTP_DEBUG_LEVEL)
+
+ def fetch_request_token(self, oauth_request):
+ """Called by oauth to fetch the request token from Dropbox. Returns an OAuthToken."""
+ self.connection.request(oauth_request.http_method,
+ self.request_token_url,
+ headers=oauth_request.to_header())
+ response = self.connection.getresponse()
+ data = response.read()
+ assert response.status == 200, "Invalid response code %d : %r" % (response.status, data)
+ return oauth.OAuthToken.from_string(data)
+
+ def fetch_access_token(self, oauth_request, trusted_url=None):
+ """Used to get a access token from Drobpox using the headers. Returns an OauthToken."""
+ url = trusted_url if trusted_url else self.access_token_url
+
+ self.connection.request(oauth_request.http_method, url,
+ headers=oauth_request.to_header())
+
+ response = self.connection.getresponse()
+ assert response.status == 200, "Invalid response code %d" % response.status
+ if trusted_url:
+ token = json.loads(response.read())
+ token['token'] = str(token['token'])
+ token['secret'] = str(token['secret'])
+ return oauth.OAuthToken(token['token'], token['secret'])
+ else:
+ return oauth.OAuthToken.from_string(response.read())
+
+ def authorize_token(self, oauth_request):
+ """
+ This is not used in the Drobpox API.
+ """
+ raise NotImplementedError("authorize_token is not implemented via OAuth.")
+
+ def access_resource(self, oauth_request):
+ """
+ Not used by the Dropbox API.
+ """
+ raise NotImplementedError("access_resource is not implemented via OAuth.")
+
+
+
+
+class Authenticator(object):
+ """
+ The Authenticator puts a thin gloss over the oauth.oauth Python library
+ so that the dropbox.client.DropboxClient doesn't need to know much about
+ your configuration and OAuth operations.
+
+ It uses a configuration file in the standard .ini format that ConfigParser
+ understands. A sample configuration is included in config/testing.ini
+ which you should copy and put in your own consumer keys and secrets.
+
+ Because different installations may want to store these configurations
+ differently, you aren't required to configure an Authenticator via
+ the .ini method. As long as you configure it with a dict with the
+ same keys you'll be fine.
+ """
+
+ def __init__(self, config):
+ """
+ Configures the Authenticator with all the required settings in config.
+ Typically you'll use Authenticator.load_config() to load these from
+ a .ini file and then pass the returned dict to here.
+ """
+ self.client = SimpleOAuthClient(config['server'],
+ config['port'],
+ config['request_token_url'],
+ config['access_token_url'],
+ config['authorization_url'])
+
+ self.trusted_access_token_url = config.get('trusted_access_token_url', None)
+
+ self.consumer = oauth.OAuthConsumer(config['consumer_key'],
+ config['consumer_secret'])
+
+ self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
+
+ self.config = config
+
+
+ @classmethod
+ def load_config(self, filename):
+ """
+ Loads a configuration .ini file, and then pulls out the 'auth' key
+ to make a dict you can pass to Authenticator().
+ """
+ config = SafeConfigParser()
+ config_file = open(filename, "r")
+ config.readfp(config_file)
+ return dict(config.items('auth'))
+
+ def build_authorize_url(self, req_token, callback=None):
+ """
+ When you send a user to authorize a request token you created, you need
+ to make the URL correctly. This is the method you use. It will
+ return a URL that you can then redirect a user at so they can login to
+ Dropbox and approve this request key.
+ """
+ if callback:
+ oauth_callback = "&%s" % urllib.urlencode({'oauth_callback': callback})
+ else:
+ oauth_callback = ""
+
+ return "%s?oauth_token=%s%s" % (self.config['authorization_url'], req_token.key, oauth_callback)
+
+
+ def obtain_request_token(self):
+ """
+ This is your first step in the OAuth process. You call this to get a
+ request_token from the Dropbox server that you can then use with
+ Authenticator.build_authorize_url() to get the user to authorize it.
+ After it's authorized you use this token with
+ Authenticator.obtain_access_token() to get an access token.
+
+ NOTE: You should only need to do this once for each user, and then you
+ store the access token for that user for later operations.
+ """
+ self.oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
+ http_url=self.client.request_token_url)
+
+ self.oauth_request.sign_request(self.signature_method_hmac_sha1, self.consumer, None)
+
+ token = self.client.fetch_request_token(self.oauth_request)
+
+ return token
+
+
+ def obtain_access_token(self, token, verifier):
+ """
+ After you get a request token, and then send the user to the authorize
+ URL, you can use the authorized access token with this method to get the
+ access token to use for future operations. Store this access token with
+ the user so that you can reuse it on future operations.
+
+ The verifier parameter is not currently used, but will be enforced in
+ the future to follow the 1.0a version of OAuth. Make it blank for now.
+ """
+ self.oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
+ token=token,
+ http_url=self.client.access_token_url,
+ verifier=verifier)
+ self.oauth_request.sign_request(self.signature_method_hmac_sha1, self.consumer, token)
+
+ token = self.client.fetch_access_token(self.oauth_request)
+
+ return token
+
+ def obtain_trusted_access_token(self, user_name, user_password):
+ """
+ This is for trusted partners using a constrained device such as a mobile
+ or other embedded system. It allows them to use the user's password
+ directly to obtain an access token, rather than going through all the
+ usual OAuth steps.
+ """
+ assert user_name, "The user name is required."
+ assert user_password, "The user password is required."
+ assert self.trusted_access_token_url, "You must set trusted_access_token_url in your config file."
+ parameters = {'email': user_name, 'password': user_password}
+ params = urllib.urlencode(parameters)
+ assert params, "Didn't get a valid params."
+
+ url = self.trusted_access_token_url + "?" + params
+ self.oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, http_url=url, parameters=parameters)
+ self.oauth_request.sign_request(self.signature_method_hmac_sha1,
+ self.consumer, None)
+ token = self.client.fetch_access_token(self.oauth_request, url)
+ return token
+
+ def build_access_headers(self, method, token, resource_url, parameters, callback=None):
+ """
+ This is used internally to build all the required OAuth parameters and
+ signatures to make an OAuth request. It's provided for debugging
+ purposes.
+ """
+ params = parameters.copy()
+
+ if callback:
+ params['oauth_callback'] = callback
+
+ self.oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
+ token=token, http_method=method,
+ http_url=resource_url,
+ parameters=parameters)
+
+ self.oauth_request.sign_request(self.signature_method_hmac_sha1, self.consumer, token)
+ return self.oauth_request.to_header(), params
+
View
BIN auth.pyc
Binary file not shown.
View
BIN helpers.pyc
Binary file not shown.

0 comments on commit 2545a91

Please sign in to comment.
Something went wrong with that request. Please try again.