def auth_finish(request): try: access_token, user_id, url_state = get_auth(request.session).finish(request.GET) client = DropboxClient(access_token) user = request.user client_email = client.account_info()["email"] uid = client.account_info()["uid"] name = client.account_info()["display_name"] try: formerAccount = DropboxAccount.objects.get(uid=uid) formerAccount.token = access_token formerAccount.display_name = name formerAccount.email = client_email formerAccount.save() new_account = False except ObjectDoesNotExist: new_account = True account = user.dropboxaccount_set.create(uid=uid, token=access_token, email=client_email, display_name=name) response = HttpResponseRedirect("/services") response.set_cookie("service_added", "dropbox", path="/") response.set_cookie("new_account", new_account, path="/") response.set_cookie("account_uid", uid, path="/") return response except DropboxOAuth2Flow.BadRequestException, e: http_status(400) info = "error404" return render(request, "dropbox.html", {"info": info})
def get_dropbox_client(self): """ Connect and return a Dropbox client object. """ self.read_token_file() sess = session.DropboxSession(self.DBBACKUP_DROPBOX_APP_KEY, self.DBBACKUP_DROPBOX_APP_SECRET, self.DBBACKUP_DROPBOX_ACCESS_TYPE) # Get existing or new access token and use it for this session access_token = self.get_access_token(sess) sess.set_token(access_token.key, access_token.secret) dropbox = DropboxClient(sess) # Test the connection by making call to get account_info dropbox.account_info() return dropbox
def get_dropbox_client(self): """ Connect and return a Dropbox client object. """ self.read_token_file() sess = session.DropboxSession(self.DBBACKUP_DROPBOX_APP_KEY, self.DBBACKUP_DROPBOX_APP_SECRET, self.DBBACKUP_DROPBOX_ACCESS_TYPE) # Get existing or new access token and use it for this session access_token = self.get_access_token(sess) sess.set_token(access_token.key, access_token.secret) dropbox = DropboxClient(sess) # Test the connection by making call to get account_info dropbox.account_info() return dropbox
def home(): if 'user' not in session: return redirect(url_for('login')) access_token = get_access_token() real_name = None quota = None app.logger.info('access token = %r', access_token) if access_token is not None: client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info["display_name"] quota_info = client.account_info()['quota_info'] quota = "Normal: " + str(filesize_readable(quota_info['normal'])) + " | Shared: " + str(filesize_readable(quota_info['shared'])) return render_template('index.html', real_name=real_name, quota=quota)
class Webcam: def __init__(self, plantId): self.plantId = plantId def takePicture(self): self.client = DropboxClient(ACCES_TOKEN) print self.client.account_info() name = datetime.datetime.now().strftime("%y-%m-%d-%H-%M") + '.jpg' command = PICTURE_CMD + name process = subprocess.Popen(command.split(), stdout=subprocess.PIPE) process.wait() response = self.client.put_file(self.plantId + '/' + name, open(name, 'r')) os.remove(name)
def home(): if 'user' not in session: return redirect(url_for('login')) access_token = get_access_token() real_name = None quota = None app.logger.info('access token = %r', access_token) if access_token is not None: client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info["display_name"] quota_info = client.account_info()['quota_info'] quota = "Normal: " + str(filesize_readable( quota_info['normal'])) + " | Shared: " + str( filesize_readable(quota_info['shared'])) return render_template('index.html', real_name=real_name, quota=quota)
def get_dropbox_client(): client = DropboxClient(session['access_token'], locale='en_UK') user_info = client.account_info() session['user_id'] = user_info['uid'] session['display_name'] = user_info['display_name'] return client
def setup_user(cls, request_key): from dropbox.client import DropboxClient request_token = OAuthRequestToken.get(request_key) session = cls.get_session() session.obtain_access_token(request_token) client = DropboxClient(session) account_info = client.account_info() uid = str(account_info['uid']) q = DropboxUser.all().filter('uid = ', uid) if q.count() == 0: user = DropboxUser(uid=uid, email=account_info['email'], display_name=account_info['display_name'], access_key=session.token.key, access_secret=session.token.secret, country=account_info['country']) else: user = q.get() user.email = account_info['email'] user.display_name = account_info['display_name'] user.access_key = session.token.key user.access_secret = session.token.secret user.put_pending_away(_save=False) user.country = account_info['country'] user.put() OAuthRequestToken.delete(request_key) return user
def salvage_broken_user_settings_document(document): if not document['access_token'] or not document['dropbox_id']: return False if not document['owner'] or not User.load(document['owner']).is_active: return False if document['deleted']: return False if not document.get('dropbox_info') or not document['dropbox_info']['display_name']: logger.info( "Attempting dropbox_info population for document (id:{0})".format(document['_id']) ) client = DropboxClient(document['access_token']) document['dropbox_info'] = {} try: database['dropboxusersettings'].find_and_modify( {'_id': document['_id']}, { '$set': { 'dropbox_info': client.account_info() } } ) except Exception: # Invalid token probably # Still want Dropbox to be enabled to show error message # to user on node settings, pass return True else: return True return False
def main(): global client global datastore global geoData access_token = connect() client = DropboxClient(access_token) print 'linked account: ', client.account_info()["display_name"] manager = DatastoreManager(client) datastore = manager.open_default_datastore() # manager.delete_datastore("default") geoData = datastore.get_table('GeoData') app = MyApp(0) app.MainLoop() # folder_metadata = client.metadata('/GeoDrive') # # print 'metadata: ', folder_metadata["contents"] # for geoFile in folder_metadata["contents"]: # # print file # print geoFile["path"] + "\n\tclient_mtime:" + geoFile["client_mtime"] + "\n\tmodified:" + geoFile["modified"] # entry = geoData.query(path=geoFile["path"]) # print entry # print "Distance: " + str(distance_on_earth(33.644277, -117.842026, 33.645147, -117.831879)) # geoData.insert(path='/GeoDrive/Work.txt', lat=33.644277, long=-117.842026, lastLoc=Date()) # geoData.insert(path='/GeoDrive/Home.txt', lat=33.645147, long=-117.831879, lastLoc=Date()) datastore.commit()
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
def get_path(self, path): client = DropboxClient(self.token) files_list = client.metadata(path)['contents'] quota_info = client.account_info()['quota_info'] if path != '/': path = '/' + path.replace("%20", " ") path_regex = re.compile(path, re.IGNORECASE) for item in files_list: item['name'] = path_regex.split(item['path'], 1)[-1][1:] item['path'] = '/' + item['name'] else: for item in files_list: item['path'] = item['path'][1:] item['name'] = item['path'] parent_url = (SITE_URL + 'api/path/dropbox/%i' + path) %self.uid upload_url = (SITE_URL + 'api/upload/dropbox/%i' + path) %self.uid data = { 'bytes_total': quota_info['quota'], 'bytes_used': quota_info['normal'] + quota_info['shared'], 'contents': files_list, 'display_name': self.display_name, 'parent_path': parent_url, 'service_class': 'dropbox', 'service_name': 'dropbox', 'uid': self.uid, 'upload_path': upload_url, 'username': self.email } return data
def salvage_broken_user_settings_document(document): if not document['access_token'] or not document['dropbox_id']: return False if not document['owner'] or not User.load(document['owner']).is_active: return False if document['deleted']: return False if not document.get( 'dropbox_info') or not document['dropbox_info']['display_name']: logger.info( "Attempting dropbox_info population for document (id:{0})".format( document['_id'])) client = DropboxClient(document['access_token']) document['dropbox_info'] = {} try: database['dropboxusersettings'].find_and_modify( {'_id': document['_id']}, {'$set': { 'dropbox_info': client.account_info() }}) except Exception: # Invalid token probably # Still want Dropbox to be enabled to show error message # to user on node settings, pass return True else: return True return False
def oauth_callback(): '''Callback function for when the user returns from OAuth.''' access_token, uid, extras = get_flow().finish(request.args) client = DropboxClient(access_token) return render_template('done.html', display_name=client.account_info()['display_name'])
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
class DropboxBackupClient(object): def __init__(self, key,secret,type, token_path): self.TOKENS_FILEPATH = token_path self.session = session.DropboxSession(key, secret, type) def check_for_authorization(self): try: if os.path.exists(self.TOKENS_FILEPATH): with open(self.TOKENS_FILEPATH, 'rb') as tokenhandle: tokendata = pickle.load(tokenhandle) self.request_token = tokendata.get('request_token') self.access_token = tokendata.get('access_token') self.session.set_token(self.access_token.key, self.access_token.secret) self.client = DropboxClient(self.session) self.client.account_info() return True else: self.get_authorization() except Exception: return False return True def prompt_for_authorization(self): print "Dropbox not authorized, visit the following URL to authorize %s and press Enter to continue" % self.session.build_authorize_url(self.request_token) raw_input() self.access_token = self.session.obtain_access_token(self.request_token) self.tokendata = dict(request_token=self.request_token, access_token=self.access_token) with open(self.TOKENS_FILEPATH, 'wb') as tokenhandle: pickle.dump(self.tokendata, tokenhandle, -1) def get_authorization(self): self.request_token = self.session.obtain_request_token() self.authorize_url = self.session.build_authorize_url(self.request_token) self.prompt_for_authorization() self.client = DropboxClient(self.session) self.client.account_info() def upload_file(self, file_object, upload_target): if self.check_for_authorization(): self.client.put_file(upload_target, file_object)
class DropboxProvider(ExternalProvider): name = 'DropBox' short_name = 'dropbox' client_id = settings.DROPBOX_KEY client_secret = settings.DROPBOX_SECRET # Explicitly override auth_url_base as None -- DropboxOAuth2Flow handles this for us auth_url_base = None callback_url = None handle_callback = None @property def oauth_flow(self): if 'oauth_states' not in session.data: session.data['oauth_states'] = {} if self.short_name not in session.data['oauth_states']: session.data['oauth_states'][self.short_name] = {'state': None} return DropboxOAuth2Flow( self.client_id, self.client_secret, redirect_uri=web_url_for('oauth_callback', service_name=self.short_name, _absolute=True), session=session.data['oauth_states'][self.short_name], csrf_token_session_key='state') @property def auth_url(self): return self.oauth_flow.start('force_reapprove=true') # Overrides ExternalProvider def auth_callback(self, user): # TODO: consider not using client library during auth flow try: access_token, dropbox_user_id, url_state = self.oauth_flow.finish( request.values) except (DropboxOAuth2Flow.NotApprovedException, DropboxOAuth2Flow.BadStateException): # 1) user cancelled and client library raised exc., or # 2) the state was manipulated, possibly due to time. # Either way, return and display info about how to properly connect. return except (DropboxOAuth2Flow.ProviderException, DropboxOAuth2Flow.CsrfException): raise HTTPError(http.FORBIDDEN) except DropboxOAuth2Flow.BadRequestException: raise HTTPError(http.BAD_REQUEST) self.client = DropboxClient(access_token) info = self.client.account_info() return self._set_external_account( user, { 'key': access_token, 'provider_id': info['uid'], 'display_name': info['display_name'], })
def get_dropbox_profile(self): dropbox_profile = None if self.dropbox_token is not None: client = DropboxClient(self.dropbox_token) try: dropbox_profile = client.account_info() except Exception, e: pass
def get_dropbox_profile(self): dropbox_profile = None if self.dropbox_token is not None: client = DropboxClient(self.dropbox_token) try: dropbox_profile = client.account_info() except Exception, e: pass
def home(): real_name = None if 'access_token' in session and session['access_token'] is not None: access_token = session['access_token'] client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info['display_name'] return render_template('index.html', real_name=real_name)
def _dropbox_auth(self): access_token = None dataManager = LocalDataManager() #A KeyError will be raised if there is no token. access_token = dataManager.get_credentials('Dropbox') dropboxClient = DropboxClient(access_token) try: dropboxClient.account_info() except rest.ErrorResponse as e: if e.status == 401: raise faults.InvalidAuth('Dropbox-Auth') except rest.RESTSocketError as e: raise faults.NetworkError('No internet-Auth') return dropboxClient
def spaceUsage(): client = DropboxClient(session['accessToken']) accountInfo = client.account_info() quotaInfo = accountInfo["quota_info"] total = quotaInfo["quota"] normal = quotaInfo["normal"] shared = quotaInfo["shared"] used = normal + shared return toMB(used), toMB(total - used)
def _dropbox_auth(self): access_token = None dataManager = LocalDataManager() #A KeyError will be raised if there is no token. access_token = dataManager.get_credentials('Dropbox') dropboxClient = DropboxClient(access_token) try: dropboxClient.account_info() except rest.ErrorResponse as e: if e.status == 401: raise faults.InvalidAuth('Dropbox-Auth') except rest.RESTSocketError as e: raise faults.NetworkError('No internet-Auth') return dropboxClient
def get_user_info(self, access_token): client = DropboxClient(access_token) info = client.account_info() return { "email": info["email"], "verified": info["email_verified"], "first_name": info["name_details"]["given_name"], "last_name": info["name_details"]["surname"], "country": info["country"] }
def get_user_info(self, access_token): client = DropboxClient(access_token) info = client.account_info() return { "email": info["email"], "verified": info["email_verified"], "first_name": info["name_details"]["given_name"], "last_name": info["name_details"]["surname"], "country": info["country"] }
def main(): logging.info('BEGIN') access_token = get_access_token() if access_token is not None: client = DropboxClient(access_token) account_info = client.account_info() if os.path.exists(SERIES_FILE): os.remove(SERIES_FILE) out = open(SERIES_FILE, 'a+') out.write(client.get_file('/series.csv').read()) out.close() reader = csv.reader(open(SERIES_FILE, 'r'), delimiter=',') reader.next() for row in reader: sid = row[0] pid = row[1] active = row[4] if(active == 0): continue if(sid == "" and pid != ""): logging.info("pid %s (no sid)", pid) response = client.search('', pid) if len(response) == 0: logging.info("pid %s not found in Dropbox", pid) download(pid, client) else: logging.info("pid %s already in Dropbox", pid) continue logging.info("sid %s", sid) r = requests.get("http://www.bbc.co.uk/programmes/" + sid + "/episodes/player.json") if(r.status_code == 404): logging.info("404 Not Found") continue for episode in r.json()["episodes"]: tpid = episode["programme"]["pid"] if(pid != "" and tpid != pid): continue; logging.info("pid %s START", tpid) response = client.search('', tpid) if len(response) == 0: logging.info("pid %s not found in Dropbox", tpid) download(tpid, client) continue else: logging.info("pid %s already in Dropbox", tpid) continue logging.info("sid %s END", sid) os.remove(SERIES_FILE) logging.info('END')
def home(): if 'user' not in session: return redirect(url_for('login')) access_token = get_access_token() real_name = None print(access_token) if access_token is not None: client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info["display_name"] return render_template('index.html', real_name=real_name)
def home(): if 'user' not in session: return redirect(url_for('login')) access_token = get_access_token() real_name = None print(access_token) if access_token is not None: client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info["display_name"] return render_template('index.html', real_name=real_name)
def dropbox_user(token): "creates a user from a dropbox token" client = DropboxClient(token) info = client.account_info() try: user = (str(info["uid"]) + "-" + info["display_name"]).replace(" ", "_") # user = str(info["uid"]) + "-" + info["display_name"] logging.info("got user ID %s" % user) except KeyError: logging.error("Could not find uid in %s" % info) raise return user
def dropbox_auth_finish(self, request): from dropbox.client import DropboxOAuth2Flow, DropboxClient access_token = None try: auth_flow = self.get_dropbox_auth_flow(request) access_token, user_id, url_state = auth_flow.finish(request.DATA) except DropboxOAuth2Flow.BadRequestException as e: # http_status(400) pass except DropboxOAuth2Flow.BadStateException as e: return HttpResponseRedirect("/api/dropbox/auth-start") except DropboxOAuth2Flow.CsrfException as e: # http_status(403) pass except DropboxOAuth2Flow.NotApprovedException as e: return HttpResponseRedirect("/") except DropboxOAuth2Flow.ProviderException as e: # http_status(403) pass client = DropboxClient(oauth2_access_token=access_token) message = "Your account has been successfully added." try: account_info = client.account_info() temporary_flow = models.TemporaryFlowModel.objects.get( email=account_info["email"], type="DROPBOX", user=request.user ) try: account_check = models.AccountModel.objects.get(type="DROPBOX", email=account_info["email"]) account_check.is_active = 1 account_check.status = 1 account_check.save() message = "This account has already been linked. We have re-activated it for you." except models.AccountModel.DoesNotExist: account = models.AccountModel() account.owner = request.user account.email = account_info["email"] account.access_token = access_token account.description = account_info["display_name"] + "(" + account_info["email"] + ")" account.type = "DROPBOX" account.quota = account_info["quota_info"]["quota"] account.used_space = account_info["quota_info"]["normal"] account.is_active = 1 account.name = "Dropbox" account.status = 1 account.assigned_space = account_info["quota_info"]["quota"] account.save() temporary_flow.delete() except models.TemporaryFlowModel.DoesNotExist: message = "The provided email does not match with the actual Dropbox email." return HttpResponseRedirect("/accounts")
def run(self): users = User.query.all() for user in users: if user.email is not None: continue client = DropboxClient(user.access_token) try: info = client.account_info() except: continue user.email = info.get('email') print user.id, user.email db.session.commit()
def home(): if 'user' not in session: return redirect(url_for('login')) access_token = get_access_token() real_name = None app.logger.info('access token = %r', access_token) if access_token is not None: client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info["display_name"] verz_files = get_verz_files(client) app.logger.info(verz_files) return render_template('index.html', real_name=real_name, verz_files=verz_files)
def startDrop(): if 'user' not in session: return redirect(url_for('login')) access_token = get_access_token() real_name = None app.logger.info('access token = %r', access_token) if access_token is not None: print("Creating Client start drop") client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info["display_name"] return render_template('index1.html')
def startDrop(): if 'user' not in session: return redirect(url_for('login')) access_token = get_access_token() real_name = None app.logger.info('access token = %r', access_token) if access_token is not None: print("Creating Client start drop") client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info["display_name"] return render_template('index1.html')
def run(self): users = User.query.all() for user in users: if user.email is not None: continue client = DropboxClient(user.access_token) try: info = client.account_info() except: continue user.email = info.get('email') print user.id, user.email db.session.commit()
def dropbox_auth_finish(self, request): from dropbox.client import DropboxOAuth2Flow, DropboxClient access_token = None try: auth_flow = self.get_dropbox_auth_flow(request) access_token, user_id, url_state = auth_flow.finish(request.DATA) except DropboxOAuth2Flow.BadRequestException: # http_status(400) pass except DropboxOAuth2Flow.BadStateException: return HttpResponseRedirect("/api/dropbox/auth-start") except DropboxOAuth2Flow.CsrfException: # http_status(403) pass except DropboxOAuth2Flow.NotApprovedException: return HttpResponseRedirect("/") except DropboxOAuth2Flow.ProviderException: # http_status(403) pass client = DropboxClient(oauth2_access_token=access_token) try: account_info = client.account_info() temporary_flow = models.TemporaryFlowModel.objects.get( email=account_info["email"], type="DROPBOX", user=request.user ) try: account_check = models.AccountModel.objects.get(type="DROPBOX", email=account_info["email"]) account_check.is_active = 1 account_check.status = 1 account_check.save() except models.AccountModel.DoesNotExist: account = models.AccountModel() account.owner = request.user account.email = account_info["email"] account.access_token = access_token account.description = account_info["display_name"] + "(" + account_info["email"] + ")" account.type = "DROPBOX" account.quota = account_info["quota_info"]["quota"] account.used_space = account_info["quota_info"]["normal"] account.is_active = 1 account.name = "Dropbox" account.status = 1 account.assigned_space = account_info["quota_info"]["quota"] account.save() temporary_flow.delete() except models.TemporaryFlowModel.DoesNotExist: pass return HttpResponseRedirect("/accounts")
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
def dropbox_auth_finish(self, request): from dropbox.client import DropboxOAuth2Flow,DropboxClient access_token = None try: auth_flow = self.get_dropbox_auth_flow(request) access_token, user_id, url_state = auth_flow.finish(request.DATA) except DropboxOAuth2Flow.BadRequestException as e: #http_status(400) pass except DropboxOAuth2Flow.BadStateException as e: return HttpResponseRedirect("/api/dropbox/auth-start") except DropboxOAuth2Flow.CsrfException as e: #http_status(403) pass except DropboxOAuth2Flow.NotApprovedException as e: return HttpResponseRedirect("/") except DropboxOAuth2Flow.ProviderException as e: #http_status(403) pass client = DropboxClient(oauth2_access_token=access_token) message = 'Your account has been successfully added.' try: account_info=client.account_info() temporary_flow = models.TemporaryFlowModel.objects.get(email=account_info['email'], type='DROPBOX', user= request.user) try: account_check = models.AccountModel.objects.get(type='DROPBOX', email=account_info['email']) account_check.is_active = 1 account_check.status = 1 account_check.save() message = 'This account has already been linked. We have re-activated it for you.' except models.AccountModel.DoesNotExist: account = models.AccountModel() account.owner = request.user account.email = account_info['email'] account.access_token = access_token account.description = account_info['display_name'] + '(' + account_info['email']+')' account.type = 'DROPBOX' account.quota = account_info['quota_info']['quota'] account.used_space = account_info['quota_info']['normal'] account.is_active = 1 account.name = 'Dropbox' account.status = 1 account.assigned_space = account_info['quota_info']['quota'] account.save() temporary_flow.delete() except models.TemporaryFlowModel.DoesNotExist: message= 'The provided email does not match with the actual Dropbox email.' return HttpResponseRedirect('/accounts')
def dropbox_auth_finish(self, request): from dropbox.client import DropboxOAuth2Flow, DropboxClient access_token = None try: auth_flow = self.get_dropbox_auth_flow(request) access_token, user_id, url_state = auth_flow.finish(request.DATA) except DropboxOAuth2Flow.BadRequestException: # http_status(400) pass except DropboxOAuth2Flow.BadStateException: return HttpResponseRedirect("/api/dropbox/auth-start") except DropboxOAuth2Flow.CsrfException: # http_status(403) pass except DropboxOAuth2Flow.NotApprovedException: return HttpResponseRedirect("/") except DropboxOAuth2Flow.ProviderException: # http_status(403) pass client = DropboxClient(oauth2_access_token=access_token) try: account_info = client.account_info() temporary_flow = models.TemporaryFlowModel.objects.get( email=account_info['email'], type='DROPBOX', user=request.user) try: account_check = models.AccountModel.objects.get( type='DROPBOX', email=account_info['email']) account_check.is_active = 1 account_check.status = 1 account_check.save() except models.AccountModel.DoesNotExist: account = models.AccountModel() account.owner = request.user account.email = account_info['email'] account.access_token = access_token account.description = account_info[ 'display_name'] + '(' + account_info['email'] + ')' account.type = 'DROPBOX' account.quota = account_info['quota_info']['quota'] account.used_space = account_info['quota_info']['normal'] account.is_active = 1 account.name = 'Dropbox' account.status = 1 account.assigned_space = account_info['quota_info']['quota'] account.save() temporary_flow.delete() except models.TemporaryFlowModel.DoesNotExist: pass return HttpResponseRedirect('/accounts')
def dashboard(): if 'user' not in session: return redirect('/') access_token = get_access_token() real_name = '' if access_token is not None: client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info["display_name"] return render_template('admin/dashboard.html', real_name=real_name)
def index(request): if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('myapp:login')) else: # get the user from db dbx_user = DbxUser.objects.get(user=request.user) dbx_client = DropboxClient(dbx_user.dbx_access_token) # get the user dropbox account info account_info = dbx_client.account_info() context = { 'dbx_user' : dbx_user, 'dbx_account_info' : account_info, } return render(request, 'myapp/index.html', context)
def home( self ): user = None try: user = cherrypy.session['user'] except: pass if not user: raise cherrypy.HTTPRedirect( cherrypy.url('login') ) access_token = cherrypy.session.get("access_token") real_name = None if access_token is not None: client = DropboxClient( access_token ) account_info = client.account_info() real_name = account_info["display_name"] return self.render_template( 'index.html', real_name=real_name, user=user )
def home(): if 'db_uid' not in session: return redirect(url_for('login')) access_token = get_access_token() real_name = None uid = None if access_token is not None: client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info["display_name"] uid = str(session['db_uid']) if real_name is None: return render_template('index.html', real_name=real_name) else: url = url_for('get_route_root', uid=uid) return redirect("%s?refresh=1" % url)
def connect(): global access_token # load the required configurations app_key = 'f0biclwqhiz4ctt' app_secret = 'wc0p641zbl3hfiv' access_token = config.get('Auth', 'access_token') # if access_token doesn't exist authenticate if access_token == '': # start the flow with app_key and app_secret from config file auth_flow = DropboxOAuth2FlowNoRedirect(app_key, app_secret) try: authorize_url = auth_flow.start() except Exception as e: logger.error(e) try_again() # ask the user to do their part in the process print('1. Go to: ' + authorize_url) print('2. Click \'Allow\' (you might have to log in first).') print('3. Copy the authorization code.') auth_code = input('Enter the authorization code here: ').strip() # use the auth code to get the access_token try: access_token, user_id = auth_flow.finish(auth_code) except dbrest.ErrorResponse as e: logger.error(e) try_again() finally: save_token() else: # if access token exists then try to get the account info to test if its still valid try: dc = DropboxClient(access_token) account = dc.account_info() logger.info('User %s successfully authorized.' % account['display_name']) except dbrest.ErrorResponse as e: logger.error(e) access_token = '' save_token() try_again() except KeyboardInterrupt as e: logger.error(e) except Exception as e: logger.error(e) try_again()
class DropboxDataProvider(): """ read and write files in a remote dropbox uing the dropbox API """ def __init__(self, app_key, app_secret, access_type, access_token, access_token_secret, location='',): session = DropboxSession(app_key, app_secret, access_type) 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 read(self, filename): return self.client.get_file(filename).read()
class DropboxSyncClient: def __init__(self, oauth2_access_token): self.access_token = oauth2_access_token self._client = DropboxClient(oauth2_access_token) def upload_file(self, dropbox_file_path, local_file_path, replace=False): f = open(local_file_path, 'rb') response = self._client.put_file(dropbox_file_path, f, replace) return 1, response['path'] def generate_public_url(self, dropbox_file_path): return self._client.share(dropbox_file_path)['url'] def delete_file(self, dropbox_file_path): self._client.file_delete(dropbox_file_path) return 1, None def update_local_to_cloud(self, dropbox_file_path, local_file_path): return 1, self.upload_file(dropbox_file_path, local_file_path, replace=True) def update_cloud_to_local(self, dropbox_file_path, local_file_path): try: try: os.makedirs(os.path.dirname(local_file_path)) except Exception as e: pass open(local_file_path, 'wb').write(self._client.get_file(dropbox_file_path).read()) return 1, None except Exception as e: print e return 1, None def get_file_list(self, dropbox_folder_path): folder_metadata = self._client.metadata(dropbox_folder_path) return [content['path'] for content in folder_metadata['contents']] def set_access_token(self, access_token): self._client = DropboxClient(access_token) def get_remaining_space(self): quota_info = self._client.account_info()['quota_info'] return quota_info['total'] - (quota_info['shared'] + quota_info['normal'])
def home(request): """ Render personalized welcome page if user has already linked their dropbox. Otherwise, page provides option to link. """ user = request.user try: access_token = user.profile.access_token except Profile.DoesNotExist: access_token = None real_name = None if access_token: client = DropboxClient(access_token) account_info = client.account_info() real_name = account_info["display_name"] return render(request, 'dropbox/index.html', {'real_name':real_name})
def user_detail(uid): # NOTE: no login here, just sets the current user upon visiting the # user page. user = User.load(uid) if not user: abort(403) session['user_id'] = user._primary_key settings = get_dropbox_settings(user) if settings: dropbox_client = DropboxClient(settings.access_token) account_info = dropbox_client.account_info() metadata = dropbox_client.metadata('/') else: account_info = None metadata = None return render_template('user.html', user=user, settings=settings, account_info=account_info, metadata=metadata )
def connect_dropbox(conf): # If dropbox_key is not set, stop program and give informative print to # user if conf["dropbox_key"] != "APP_KEY" or conf["dropbox_secret"] != "SECRET": # connect to dropbox and start the session authorization process print "[INFO] Start authorizing application from Dropbox..." flow = DropboxOAuth2FlowNoRedirect(conf["dropbox_key"], conf["dropbox_secret"]) print "[INFO] Authorizing application using link below:\n{}\n".format( flow.start()) authCode = raw_input("Enter auth code here: ").strip() # # finish the authorization and grab the Dropbox client (accessToken, userID) = flow.finish(authCode) client = DropboxClient(accessToken) print "[SUCCESS] dropbox account linked" print '[INFO] Linked account: ', client.account_info()["display_name"] return client else: print "[ERROR] Add your dropbox information to conf.json!" return None
def account(): # Logout if request.args.get('logout') is not None: session.clear() return redirect(url_for('index')) # Save the token in session if 'accessToken' not in session: session['accessToken'] = request.form["accessToken"] # Get the account metadata try: accessToken = session['accessToken'] client = DropboxClient(accessToken) accountInfo = client.account_info() session["userID"] = accountInfo["uid"] return render_template("account.html", accountInfo=accountInfo) except: session.clear() if not accessToken: session["errorLabel"] = "0" else: session["errorLabel"] = "1" return redirect(url_for('index'))
class DropboxStorage(Storage): """ A storage class providing access to resources in a Dropbox Public folder. """ 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 _get_abs_path(self, name): return os.path.realpath(os.path.join(self.location, name)) def _open(self, name, mode='rb'): name = self._get_abs_path(name) remote_file = DropboxFile(name, self, mode=mode) return remote_file def _save(self, name, content): name = self._get_abs_path(name) directory = os.path.dirname(name) if not self.exists(directory) and directory: self.client.file_create_folder(directory) response = self.client.metadata(directory) if not response['is_dir']: raise IOError("%s exists and is not a directory." % directory) abs_name = os.path.realpath(os.path.join(self.location, name)) self.client.put_file(abs_name, content) return name def delete(self, name): name = self._get_abs_path(name) self.client.file_delete(name) def exists(self, name): name = self._get_abs_path(name) try: metadata = self.client.metadata(name) if metadata.get('is_deleted'): return False except ErrorResponse as e: if e.status == 404: # not found return False raise e return True def listdir(self, path): path = self._get_abs_path(path) response = self.client.metadata(path) directories = [] files = [] for entry in response.get('contents', []): if entry['is_dir']: directories.append(os.path.basename(entry['path'])) else: files.append(os.path.basename(entry['path'])) return directories, files def size(self, name): cache_key = 'django-dropbox-size:%s' % filepath_to_uri(name) size = cache.get(cache_key) if not size: size = self.client.metadata(filepath_to_uri(name))['bytes'] cache.set(cache_key, size, CACHE_TIMEOUT) return size def url(self, name): cache_key = 'django-dropbox-url:%s' % filepath_to_uri(name) url = cache.get(cache_key) if not url: url = self.client.share(filepath_to_uri(name), short_url=False)['url'] + '?dl=1' cache.set(cache_key, url, CACHE_TIMEOUT) return url def get_available_name(self, name): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ name = self._get_abs_path(name) dir_name, file_name = os.path.split(name) file_root, file_ext = os.path.splitext(file_name) # If the filename already exists, add an underscore and a number (before # the file extension, if one exists) to the filename until the generated # filename doesn't exist. count = itertools.count(1) while self.exists(name): # file_ext includes the dot. name = os.path.join( dir_name, "%s_%s%s" % (file_root, count.next(), file_ext)) return name
class DropBox(clouddrive.CloudDrive): name = "DropBox" def __init__(self, access_token): self.client = DropboxClient(access_token) self.access_token = access_token clouddrive.CloudDrive.__init__(self, access_token) @staticmethod def auth(): #app_key = 'knbyx2adg14kkn5' #app_secret = 'kh3ulgqry8jffqp' app_key = 'eif0l7bgnpb06di' app_secret = 'qa02jhdo4jrwaid' global Auth_DROPMytoken global Auth_Drop_Running_true def keep_running(): global Auth_Drop_Running_true return Auth_Drop_Running_true class AuthHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_HEAD(s): s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() def do_GET(s): s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() if s.path.find("code=") != -1: global Auth_DROPMytoken global Auth_Drop_Running_true Auth_DROPMytoken = s.path Auth_Drop_Running_true = False s.wfile.write("ok see command line") return class MYrequest: def __init__(self, url): self.url = url def get(self, mystring): if self.url.find(mystring) == -1: return item = self.url.split(mystring + "=")[1] if item.find("&") != -1: item = item.split("&")[0] return urllib.unquote(item).decode() redirect_url = "http://localhost:8787" my_session = {} Auth_Drop_Running_true = True flow = DropboxOAuth2Flow(app_key, app_secret, redirect_url, my_session, "dropbox-auth-csrf-token") authorize_url = flow.start() webbrowser.open(authorize_url) try: httpd = BaseHTTPServer.HTTPServer(("", 8787), AuthHandler) while keep_running(): httpd.handle_request() except KeyboardInterrupt: pass httpd.server_close() token, user_id, url_state = flow.finish(MYrequest(Auth_DROPMytoken)) clouddrive.CloudDrive.access_token = token return token def read(self, filename): try: data = [] with self.client.get_file(filename) as f: data += f.read() except: return -1 return ''.join(data) def write(self, filename, data): try: response = self.client.put_file(filename, data, True) except: return -1 return 1 def mkdir(self, dirname): try: self.client.file_create_folder(dirname) except: return -1 return 1 def delete(self, filename): try: self.client.file_delete(filename) except: return -1 return 1 def capacity(self): try: a = self.client.account_info()["quota_info"] except: return -1 return a["quota"] - a["shared"] - a["normal"] def listing(self, path="/"): lists = self.client.metadata(path) filelist = [] for x in lists["contents"]: filelist.append((x['path'], x['is_dir'])) return filelist
def get_dropbox_name_email(access_token): client = DropboxClient(access_token) meta = client.account_info() return (meta.get('display_name', '').split(' ')[0], meta.get('email'))
class DBoxClient(object): def __init__(self): self._logger = logging.getLogger(config.dpbox['logger']['name']) self.cache_file = config.dpbox['cachefile'] self._token = None self._load() key, secret = decode_dropbox_key(config.dpbox['app']['encoded']) self.session = DBoxSession(config.dpbox['app']['key'], config.dpbox['app']['secret'], access_type=config.dpbox['app']['access']) if (self._token): self.session.set_token(self._token[0], self._token[1]) else: self._token = self.session.link() self._save() self.client = DropboxClient(self.session) def reset(self): self._logger.debug('[dpbox v%s] resetting local state' % (VERSION)) self._save() def download(self, source, directory=''): if len(directory) > 0 and directory[len(directory) - 1] != '/': directory += '/' self._logger.info(u'[dpbox v%s] FETCH %s -> %s' % (VERSION, unicode(source), unicode(directory))) self._download(source, directory) def _download(self, source, directory): try: metadata = self.client.metadata(source) self._logger.debug(u'metadata for %s' % source) self._logger.debug(metadata) except Exception as e: self._logger.error('[dpbox v%s] error fetching file' % (VERSION)) self._logger.exception(e) return # Will check later if we've got everything. segs = metadata['path'].split('/') directory += segs[len(segs) - 1] if metadata['is_dir']: try: os.stat(directory) except: os.mkdir(directory) for item in metadata['contents']: self._download(item['path'], directory + '/') else: f = self.client.get_file(source) print 'writing file to disc...' destination = open(os.path.expanduser(directory.encode('utf-8')), 'wb') destination.write(f.read()) destination.close() print u"[rev %s] %s - '%s' downloaded" % ( metadata['revision'], metadata['size'], directory) def upload(self, source, directory): if len(directory) > 0 and directory[len(directory) - 1] != '/': directory += '/' segs = source.split('/') directory += segs[len(segs) - 1] f = open(source, 'rb') print u'uploading file %s -> %s' % (source, directory) response = self.client.put_file(directory.encode('utf-8'), f) print "[rev %s] %s - '%s' uploaded" % ( response['revision'], response['size'], response['path']) self._logger.debug('[dpbox v%s] upload response: %s' % (VERSION, response)) def list(self, directory): path = unicode(directory).encode('utf-8') metadata = self.client.metadata(path) self._logger.debug('[dpbox v%s] metadata: %s' % (VERSION, metadata)) print 'display content of ', metadata['path'], ', ', metadata['size'] for item in metadata['contents']: if item['is_dir']: print 'd ', item['path'] else: print 'f ', item['path'] def infos(self, item, filename=''): path = unicode(item).encode('utf-8') metadata = self.client.metadata(path) if len(filename) > 0: with open(filename, 'w') as outfile: json.dump(metadata, outfile) else: print metadata def user(self, item=''): infos = self.client.account_info() self._logger.debug(u'[dpbox v%s] %s' % (VERSION, infos)) if len(item) > 0: print item, ' = ', infos[item] return for name in infos: space = ' ' * (20 - len(name)) if isinstance(infos[name], types.DictType): print name, ':' for key in infos[name]: print ' -> ', key, ': ', infos[name][key] else: print name, space, infos[name] def disconnect(self): cachefile = os.path.expanduser(self.cache_file) if os.path.exists(cachefile): os.unlink(cachefile) self.session.unlink() print 'disconnected from service' def _save(self): with open(os.path.expanduser(self.cache_file), 'w') as f: f.write(''.join([json.dumps(self._token), '\n'])) # f.write(''.join([json.dumps(self.remote_dir), '\n'])) def _load(self): cachefile = os.path.expanduser(self.cache_file) if not os.path.exists(cachefile): self._logger.warn('[dpbox v%s] Cache file not found: %s' % (VERSION, cachefile)) self.reset() return try: with open(cachefile, 'r') as f: dir_changed = False try: line = f.readline() # Token. self._token = json.loads(line) self._logger.debug('[dpbox v%s] loaded token' % (VERSION)) except Exception as e: self._logger.warn('[dpbox v%s] can\'t load cache state' % (VERSION)) self._logger.exception(e) # try: # line = f.readline() # Dropbox directory. # directory = json.loads(line) # if directory != self.remote_dir: # Don't use state. # self._logger.info(u'remote dir changed "%s" -> "%s"' % # (directory, self.remote_dir)) # dir_changed = True # except Exception as e: # self._logger.warn('can\'t load cache state') # self._logger.exception(e) if dir_changed: return except Exception as e: self._logger.error('[dpbox v%s] error opening cache file' % (VERSION)) self._logger.exception(e)
# Include the Dropbox SDK from dropbox.client import DropboxClient, DropboxOAuth2Flow, DropboxOAuth2FlowNoRedirect from dropbox.rest import ErrorResponse, RESTSocketError #from dropbox.datastore import DatastoreError, DatastoreManager, Date, Bytes import dropbox.datastore from pprint import pprint import time access_token = 'yd0PQdjPz0sAAAAAAAAAAWoWEA1yPLVJ5BfBy4I9NKta-yJrb-UJPPtXeh4Emkgt' client = DropboxClient(access_token) print 'linked account: ', client.account_info() manager = dropbox.datastore.DatastoreManager(client) ds = manager.list_datastores() print "ds = ", ds #datastore = manager.open_default_datastore() #manager.delete_datastore('cbr-7') manager.delete_datastore('cbrtest')