def dropbox_auth_finish(request): try: oauth_result = get_dropbox_auth_flow(request.session).finish( request.GET) dbx = dropbox.Dropbox(oauth_result.access_token) from django.contrib.auth.models import User get_user = dbx.users_get_current_account() defaults = { 'password': oauth_result.access_token, 'email': get_user.email, 'first_name': get_user.name.given_name, 'last_name': get_user.name.surname } user, created = User.objects.update_or_create( username=oauth_result.account_id, defaults=defaults) login(request, user) request.session['dropbox'] = { 'token': oauth_result.access_token, 'name': get_user.name.display_name, 'photo': get_user.profile_photo_url, } except BadRequestException as e: print("Error 403 %s" % (e, )) except BadStateException: redirect("/dropbox-auth-start") except CsrfException as e: print("Error 403 %s" % (e, )) except NotApprovedException as e: print("Error not approved %s" % (e, )) except ProviderException as e: print("Error 403 %s" % (e, ))
def upload(cls): dbx = dropbox.Dropbox(Constants.Dropbox.ACCESS_TOKEN) file_path = HardConstants.App.DB_DUMP_ZIP file_size = os.path.getsize(file_path) dest_path = HardConstants.App.DB_DUMP_ZIP_PATH_ON_DROPBOX chunk_size = cls.CHUNK_SIZE logger.info('file size: {}'.format(file_size)) with open(file_path, 'rb') as f: if file_size <= chunk_size: dbx.files_upload(f.read(), dest_path, mode=dropbox.files.WriteMode.overwrite) return session = dbx.files_upload_session_start(f.read(chunk_size)) cursor = dropbox.files.UploadSessionCursor( session_id=session.session_id, offset=f.tell()) commit = dropbox.files.CommitInfo( path=dest_path, mode=dropbox.files.WriteMode.overwrite) while f.tell() < file_size: if (file_size - f.tell()) <= chunk_size: dbx.files_upload_session_finish(f.read(chunk_size), cursor, commit) return dbx.files_upload_session_append_v2(f.read(chunk_size), cursor) cursor.offset = f.tell()
def upload_file(self, img_file): """ Ya en el método creo una instancia del objeto DropboxClient pasandole como parámetro el token que obtengo del StorageCredential correspondiente. Puedo indicarle también un locale, que es el locale del user de nuestra aplicación, algunos llamados a la API retornan datos localizados y mensajes de error, ésta configuración le dice al server que locale usar (Por defecto en_US). También podemos indicarle un objeto cliente rest para usar para hacer requests. Para hacer una solicitud a la API de dropbox debemos armar un request específico. El método define la url objetivo ('/files') """ dbx = dropbox.Dropbox(self.token) mode = WriteMode.add try: file_metadata = dbx.files_upload(img_file.read(), "/"+img_file.filename, mode, autorename=True) except exceptions.ApiError as err: print "Error en la carga a Dropbox ", err.message return None res = { 'path': file_metadata.path_lower, 'description': 'Carga del archivo {0} en Dropbox'.format(file_metadata.name), 'storage_location': 'Dropbox' } return res
def upload(path, dbx_path=None, token=None, dbx=None, overwrite=False): if dbx is None: dbx = dropbox.Dropbox(token) if dbx_path is None: dbx_path = DBX_PATH mode = (dropbox.files.WriteMode.overwrite if overwrite else dropbox.files.WriteMode.add) if os.path.isfile(path): while '//' in path: path = path.replace("//", "/") modified_time = os.path.getmtime(path) with open(path, "rb") as file: data = file.read() if path.startswith("." + os.path.sep): path = os.path.sep.join(path.split(os.path.sep)[1:]) path = os.path.join(dbx_path, path).replace(os.path.sep, "/") try: dbx.files_upload(data, path, mode, client_modified=datetime.datetime(*time.gmtime(modified_time)[:6])) except ApiError as e: if not e.error.get_path().reason.is_conflict(): raise e else: for dir_path, dir_names, file_names in os.walk(path): for file_name in file_names: upload(os.path.join(dir_path, file_name), dbx_path=dbx_path, token=token, dbx=dbx, overwrite=overwrite)
def __init__(self, token, directory): super().__init__() self._directory = directory self._dbx = dropbox.Dropbox(token, timeout=120) self._validate_token() logging.info('Dropbox client initialized')
def get(self, request): dropbox_auth_finish(request) if request.user.is_authenticated: dbx = dropbox.Dropbox(request.session['dropbox']['token']) return render(request, 'index.html', context={'files': dbx.files_list_folder('').entries}) return render(request, 'login.html')
def download_file(self, path): dbx = dropbox.Dropbox(self.token) try: fmd, res = dbx.files_download(path) except exceptions.HttpError as err: print '*** HTTP error', err.message return None return res.content
def delete_file(self, path): dbx = dropbox.Dropbox(self.token) try: file_metadata = dbx.files_delete(path) except exceptions.ApiError as err: print '*** API error', err.message return None return file_metadata.name
def upload(): file = request.files['files'] filename = secure_filename(file.filename) filename = gen_file_name(filename) dbx = dropbox.Dropbox( 'NIP9ZHfsSXcAAAAAAAASgJrQdNyIiEYDVWGyau04Wy-fupfVft3UyWaHZ16iJZAy') dbx.files_upload(file.stream.read(), filename) return "YAY"
def upload2(): file = request.files['file'] filename = secure_filename(file.filename) filename = gen_file_name(current_user.id, filename) dbx = dropbox.Dropbox( 'NIP9ZHfsSXcAAAAAAAASgJrQdNyIiEYDVWGyau04Wy-fupfVft3UyWaHZ16iJZAy') x = dbx.files_upload(file.stream.read(), filename) Files.create(current_user.id, x.path_display, "Photo") return redirect(url_for("home.info"))
def upload_to_dropbox(origin_file_name, destination_file_name, write_mode=WriteMode.add): print('Processing file %s' % origin_file_name) f = open(origin_file_name) content = f.read() f.close() dbx = dropbox.Dropbox(dropbox_key) print('Uploading content to %s\n%s' % (destination_file_name, content)) dbx.files_upload(content, destination_file_name, mode=write_mode) sharing_info = dbx.sharing_create_shared_link(destination_file_name) print('%s shared at %s:\n%s' % (destination_file_name, sharing_info, content)) return sharing_info
def __pre_process(self): with open( os.path.expanduser( os.path.join(os.path.dirname(__file__), token_file))) as f: content = [c.strip() for c in f.readlines()] if not self.__token: self.__token = content[1] # token. self.__connect = dropbox.Dropbox(self.__token) # Checking. try: self.__connect.users_get_current_account() except Exception as e: self.__connect = None print(e)
def getClient(self): result = None user_token = self._getToken() if (user_token != ''): # create the client result = dropbox.Dropbox(user_token) try: result.users_get_current_account() except: # this didn't work, delete the token file self._deleteToken() result = None return result
def download_file(): share = Shares.get_by_share_key(request.json['share_key']) if share is None or not share.is_active(): return make_response(json.dumps({"error": "Unable to validate email"}), 400) if share.key != request.json['key']: return make_response(json.dumps({"error": "Unable to validate email"}), 400) file = Files.get_by_id(request.json['file_id']) dbx = dropbox.Dropbox( 'NIP9ZHfsSXcAAAAAAAASgJrQdNyIiEYDVWGyau04Wy-fupfVft3UyWaHZ16iJZAy') # dbx.files_delete_v2() link = dbx.files_get_temporary_link(file.filepath) return json.dumps({"redirectUrl": link.link})
async def upload_file(self, file_path, dest_path, msg, idnum=None): dbx = dropbox.Dropbox(self.access_token, timeout=None) filename = file_path if filename.startswith("manifest_"): filename = filename[:int(f"-{len(str(idnum))+7}")] elif filename.endswith(".ipa"): filename = filename[:-4] try: with open(file_path, "rb") as f: file_size = os.path.getsize(file_path) CHUNK_SIZE = 5 * 1024 * 1024 if file_size <= CHUNK_SIZE: await msg.edit(f"Processing `{filename}`..") dbx.files_upload(f.read(), dest_path) else: upload_session_start_result = dbx.files_upload_session_start( f.read(CHUNK_SIZE)) progress = int(CHUNK_SIZE / file_size * 100) if msg != None: await msg.edit(f"Processing `{filename}`: {progress}%") cursor = dropbox.files.UploadSessionCursor( session_id=upload_session_start_result.session_id, offset=f.tell()) commit = dropbox.files.CommitInfo(path=dest_path) while f.tell() < file_size: if ((file_size - f.tell()) <= CHUNK_SIZE): dbx.files_upload_session_finish( f.read(CHUNK_SIZE), cursor, commit) await msg.edit(f"Processing `{filename}`: 100%") else: dbx.files_upload_session_append( f.read(CHUNK_SIZE), cursor.session_id, cursor.offset) cursor.offset = f.tell() progress = int(f.tell() / file_size * 100) await msg.edit( f"Processing `{filename}`: {progress}%") shared_link_metadata = dbx.sharing_create_shared_link_with_settings( dest_path) link = shared_link_metadata.url return link except FileNotFoundError: return False
def get_config_file(cloud_config): provider = cloud_config.get('cloud_host') filename = cloud_config.get('cloud_config_file') key = cloud_config.get('cloud_access_key') if provider == 'dropbox': dbx = dropbox.Dropbox(key) res = dbx.files_list_folder(path="") rv = {} for entry in res.entries: rv[entry.name] = entry # print(entry.name) md, res = dbx.files_download("/" + filename) data = res.content # print(len(data), 'bytes; md:', md, type(data)) try: return json.loads(data.decode()) except Exception as exc: #print(exc) return data
def convert_fromdropbox(access_token=None): """Converts a Dropbox file image to jpeg or png.""" if not access_token: return jsonify(message='Missing access_token parameter.'), 400 if 'path' not in request.form: return jsonify(message='Missing path parameter.'), 400 if 'format' not in request.form: return jsonify(message='Missing format parameter.'), 400 dbx = dropbox.Dropbox(access_token) try: dbx.users_get_current_account() except (AuthError, BadInputError): return jsonify(message="Invalid Dropbox access token."), 401 path = request.form.get('path') img_format = request.form.get('format') try: metadata, response = dbx.files_download(path) except ValidationError: return jsonify(message="Invalid Dropbox path."), 400 except ApiError: return jsonify(message="Dropbox file not found."), 404 img_name = secure_filename(metadata.name) img_io, code = convert_image(io.BytesIO(response.content), img_format) if code != 200: return img_io, code return send_file(img_io, mimetype=f'image/{img_format}', attachment_filename=img_name, as_attachment=True)
import os,sys import argparse from dropbox import dropbox about = 'This program deletes all public links from files shared in Dropbox' parser = argparse.ArgumentParser(description = about) parser.add_argument("-t", "--token", help="Dropbox app security token (key) to use for authentication (see https://www.dropbox.com/developers/apps)") parser.add_argument("-d", "--dryrun", help="don't delete just print links that would be removed", action="store_true") args = parser.parse_args() TOKEN = args.token if not TOKEN: print('please provide Dropbox API TOKEN (KEY) via -t argument') sys.exit(1) dbx = dropbox.Dropbox(TOKEN) try: link_results = dbx.sharing_list_shared_links() except dropbox.BadInputError as e: print(f'app not found: {str(e.message)}') sys.exit(1) except dropbox.AuthError as e: print(f'could not authenticate: {str(e)}') sys.exit(1) if not link_results.links: print('no shared links found') sys.exit(0) for i in link_results.links:
def login(self, ): self.dbox = dropbox.Dropbox(self.token)
def connect(): return dropbox.Dropbox(dropbox_key)
def __generate_dropbox_url(account, file): dbx = dropbox.Dropbox(account.endpoint__dropbox_access_token) return dbx.files_get_temporary_link(file.filename).link
def upload(self, path, file_object): dbx = dropbox.Dropbox(self.entity.endpoint__dropbox_access_token) dbx.files_upload(file_object, path)
def view(): dbx = dropbox.Dropbox( 'NIP9ZHfsSXcAAAAAAAASgJrQdNyIiEYDVWGyau04Wy-fupfVft3UyWaHZ16iJZAy') dbx.files_delete_v2() link = dbx.files_get_temporary_link("/readme.md") return link.link
def __init__(self, api_key: str): self.db = dbx.Dropbox(api_key)
def download(self, path): dbx = dropbox.Dropbox(self.entity.endpoint__dropbox_access_token) md, res = dbx.files_download(path) return True, res.content
import bs4 import time import pymysql import requests from dropbox import dropbox from selenium import webdriver from datetime import datetime, timedelta SOURCE_URL = 'https://blogtruyen.com/danhsach/tatca' data = [] client = dropbox.Dropbox("ut9MzqycHAAAAAAAAAAAM-HAvZ8JWgqcOSvr5e3VdjJnlPoTByUGs11BUsUzFl1T") # Kết nối vào database. connection = pymysql.connect(host='localhost', user='******', db='comic', charset='utf8', cursorclass=pymysql.cursors.DictCursor) def main(): driver = webdriver.Chrome('/usr/local/bin/chromedriver') driver.implicitly_wait(30) driver.get(SOURCE_URL) source = driver.page_source clickNextPage(source, driver)
password=url.password, host=url.hostname, port=url.port) cur = conn.cursor() UserUID = '' CHANNEL_ACCESS_TOKEN = os.environ.get('LINE_CHANNEL_ACCESS_TOKEN') CHANNEL_SECRET = os.environ.get('LINE_CHANNEL_SECRET') DROPBOX_TOKEN = os.environ.get('DROPBOX_TOKEN') usernameDB = os.environ.get('LoginDB') passwordDB = os.environ.get('PasswordDB') dropboxClient = client.DropboxClient(DROPBOX_TOKEN) dropboxObj = dropbox.Dropbox(DROPBOX_TOKEN) RAMID = os.environ.get('RAMID') line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(CHANNEL_SECRET) CommandLists = [] CommandLists.append('1.Help\n') CommandLists.append('2.Who\n') CommandLists.append('3.Id\n') CommandLists.append('4.L2P\n') #--------------------------------------------------------------------------------------- # Basic Authentication
os.system('cd ' + temp_folder + ' && tar -zcf ' + BACKUP_DIR + '/ispconfig_' + strftime("%d-%m-%Y_%H-%M-%S", gmtime()) + '.tar.gz *') print(' * Removing temp files...') shutil.rmtree(temp_folder) backups_in_folder = sorted( os.listdir(BACKUP_DIR), key=lambda f: os.path.getctime("{}/{}".format(BACKUP_DIR, f))) if DROPBOX_UPLOAD: print('-- Syncing with Dropbox...') try: backup = open(BACKUP_DIR + '/' + backups_in_folder[-1], 'rb') file_size = os.path.getsize(BACKUP_DIR + '/' + backups_in_folder[-1]) CHUNK_SIZE = 30 * 1024 * 1024 dbx = dropbox.Dropbox(DROPBOX_UPLOAD_ACCESSKEY) if file_size <= CHUNK_SIZE: dbx.files_upload(backup, '/' + backups_in_folder[-1]) else: upload_session_start_result = dbx.files_upload_session_start( backup.read(CHUNK_SIZE)) cursor = files.UploadSessionCursor( session_id=upload_session_start_result.session_id, offset=backup.tell()) commit = files.CommitInfo(path='/' + backups_in_folder[-1]) while backup.tell() < file_size: if (file_size - backup.tell()) <= CHUNK_SIZE: dbx.files_upload_session_finish(backup.read(CHUNK_SIZE), cursor, commit) else:
def __init__(self, access_token: str, start_folder: str): db = dropbox.Dropbox(access_token) act = db.users_get_current_account() self._dbx = db.with_path_root( common.PathRoot.namespace_id(act.root_info.root_namespace_id)) self._start_folder = start_folder
def finish_authentication_and_start_download(cls, request): if request.method == 'GET': parser = httplib2.Http() if 'error' in request.GET or 'code' not in request.GET: raise exceptions.RequestError( 'There was an error on the callback') if request.GET['state'] != request.session['session_state']: raise exceptions.RequestError( 'There was an error on the callback-- state mismatch') current_site = Site.objects.get_current() domain = current_site.domain code_callback_url = 'https://%s%s' % ( domain, settings.CONFIG_PARAMS['dropbox_callback']) params = urllib.parse.urlencode({ 'code': request.GET['code'], 'redirect_uri': code_callback_url, 'client_id': settings.CONFIG_PARAMS['dropbox_client_id'], 'client_secret': settings.CONFIG_PARAMS['dropbox_secret'], 'grant_type': 'authorization_code' }) headers = {'content-type': 'application/x-www-form-urlencoded'} resp, content = parser.request( settings.CONFIG_PARAMS['dropbox_token_endpoint'], method='POST', body=params, headers=headers) c = json.loads(content.decode('utf-8')) try: access_token = c['access_token'] except KeyError as ex: raise exceptions.ExceptionWithMessage(''' The response did not have the "access_token" key, so the OAuth2 flow did not succeed. The response body was %s ''' % c) try: download_info = request.session['download_info'] except KeyError as ex: raise exceptions.ExceptionWithMessage( 'There was no download_info registered with the session') # need to check that the user has enough space in their Dropbox account dbx = dropbox_module.Dropbox(access_token) space_usage = dbx.users_get_space_usage() if space_usage.allocation.is_team(): used_in_bytes = space_usage.allocation.get_team().used space_allocation_in_bytes = space_usage.allocation.get_team( ).allocated space_remaining_in_bytes = space_allocation_in_bytes - used_in_bytes else: used_in_bytes = space_usage.used space_allocation_in_bytes = space_usage.allocation.get_individual( ).allocated space_remaining_in_bytes = space_allocation_in_bytes - used_in_bytes running_total = 0 at_least_one_transfer = False # iterate through the transfers, add the token, and check a running total # note that we do not do any optimization to maximize the number of transfers # in the case that the space is not sufficient for all files. passing_items = [] failed_items = [] problem = False for item in download_info: size_in_bytes = Resource.objects.get( pk=item['resource_pk']).size running_total += size_in_bytes if running_total < space_remaining_in_bytes: item['access_token'] = access_token passing_items.append(item) else: problem = True failed_items.append(item) at_least_one_transfer = len(passing_items) > 0 if not problem: # call async method: transfer_tasks.download.delay( passing_items, request.session['download_destination']) context = { 'email_enabled': settings.EMAIL_ENABLED, 'problem': problem, 'at_least_one_transfer': at_least_one_transfer } return render(request, 'transfer_app/download_started.html', context) else: # if there was a problem-- could not fit all files # Still initiate the good transfers if len(passing_items) > 0: transfer_tasks.download.delay( passing_items, request.session['download_destination']) warning_list = [] for item in failed_items: resource_name = Resource.objects.get( pk=item['resource_pk']).name warning_list.append( 'Not enough space in your Dropbox for file %s' % resource_name) context = { 'email_enabled': settings.EMAIL_ENABLED, 'problem': problem, 'at_least_one_transfer': at_least_one_transfer, 'warnings': warning_list } return render(request, 'transfer_app/download_started.html', context) else: raise MethodNotAllowed('Method not allowed.')