def sync(): if 'user' not in session: return redirect(url_for('login')) access_token = get_access_token() print(access_token) real_name = '' if access_token is not None: client = DropboxClient(access_token) gallery_items = client.metadata('/gallery') for idx, item in enumerate(gallery_items['contents']): if item['is_dir']: pass else: name = get_image_name(item['path'], '/gallery/') f, metadata = client.get_file_and_metadata(item['path']) make_dir('%s/%s' % (GAL_PATH, name)) for lang in LANGUAGES: make_dir('%s/%s/%s' % (GAL_PATH, name, lang)) create_file('%s/%s.jpg' % (GAL_PATH, name), f.read()) for lang in LANGUAGES: create_file( '%s/%s/%s/%s' % (GAL_PATH, name, lang, 'title.txt'), '') return redirect(url_for('admin.dashboard'))
def getdropboxfile(request,name): dp = DropboxClient(settings.DROPBOX_ACCESS_TOKEN) f, metadata = dp.get_file_and_metadata(name) response = HttpResponse(f.read(),content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(name) return response
def main(): # ask for the user to enter their token auth_token = raw_input("Please enter your Dropbox auth token: ") client = DropboxClient(auth_token) # see if there are any new .mp3 files # currently the program sleeps for 5 minutes between checks - change it # however you like while True: time.sleep(5 * 60) possible_file = client.metadata('/new') # check for errors contents = possible_file.get('contents') files = len(contents) if files > 0: print 'something here' i = 0 while i < files: path = contents[i].get('path') # print path # get the file file, metadata = client.get_file_and_metadata(path) # transfer the file to local out = open('voice.mp3', 'wb') out.write(file.read()) out.close() # execute a bash command using mpg123 to play the .mp3 subprocess.call("mpg123 ./voice.mp3", shell=True) # move the file to the save folder # old_path = './new/' + path # print old_path # print path new_path = path[4:] # TODO add date to path name new_path = '/save/' + new_path # print new_path print "moving from " + path + " to " + new_path client.file_move(path, new_path) i+=1 else: print 'nothing here'
def download_and_save_images(list_images, year, month): client = DropboxClient(DROPBOX_TOKEN) DESTINATION_FOLDER = 'images/' + year + month + '/' if not os.path.exists(DESTINATION_FOLDER): os.makedirs(DESTINATION_FOLDER) final_images = [] for image in list_images: f, metadata = client.get_file_and_metadata(image) out = open(DESTINATION_FOLDER + image, 'wb') final_images.append(DESTINATION_FOLDER + image) out.write(f.read()) out.close() return final_images
def render_beavlet(request, doc): user = request.user try: access_token = user.profile.access_token except Profile.DoesNotExist: message.add_message(request, messages.ERROR, "Your dropbox account needs to be linked!") return redirect('/dropbox/') client = DropboxClient(access_token) f, meta = client.get_file_and_metadata('/' + doc) s = f.read() from apps.nbviewer.views import render_raw_json_to_response return render_raw_json_to_response(request, s)
def process_user(uid): '''Call /delta for the given user ID and process any changes.''' # OAuth token for the user token = redis_client.hget('tokens', uid) # /delta cursor for the user (None the first time) cursor = redis_client.hget('cursors', uid) client = DropboxClient(token) has_more = True while has_more: result = client.delta(cursor) for path, metadata in result['entries']: # Ignore deleted files, folders, and non-markdown files if (metadata is None or metadata['is_dir'] or not path.endswith('.md')): continue # Convert to Markdown and store as <basename>.html response, metadata = client.get_file_and_metadata(path) md = response.read().decode() html = markdown(md, extensions=['gfm']) html_name = path[:-3] + '.html' client.put_file(html_name, html, overwrite=True) # Include URL to published file in HTML comment at top of Markdown # file if '<!-- Published file url:' != md.split('\n')[0]: share_url = client.share(html_name, short_url=False).get('url') file_key = share_url.split('/')[4] url_name = urllib.parse.quote(html_name) url_comment = ('<!-- Published file url:\n' 'https://dl.dropboxusercontent.com/s/' '{}{}\n-->\n'.format(file_key, url_name)) md = url_comment + md client.put_file(path, md, overwrite=True) # Update cursor cursor = result['cursor'] redis_client.hset('cursors', uid, cursor) # Repeat only if there's more to do has_more = result['has_more']
def view_note(note_title): access_token = get_access_token() if not access_token: return json_response(False, 'You are not currently logged in through Dropbox.') client = DropboxClient(access_token) try: f, metadata = client.get_file_and_metadata('/' + note_title) json_content = f.read().replace('\n', '') except dropbox.rest.ErrorResponse as e: app.logger.exception(e) return json_response(False, 'An error occured while trying to retrieve your note from Dropbox.') real_name = session.get('real_name', None) return json_response(True, '', note=json_content)
class DropboxDataStorage(FileSystemStorage): def __init__(self): self.client = DropboxClient(settings.DROPBOX_ACCESS_TOKEN) def _open(self, name, mode='rb'): f, metadata = self.client.get_file_and_metadata(name) tmp_file = open('test','wb') tmp_file.write(f.read()) return File(tmp_file, mode) def _save(self,name,content): f = content name = str(self.get_available_name(name)).replace('\\', '/') try: response = self.client.put_file(name, f) if 'rev' in response: return name else: raise DropboxDataStorageException("Incorrect Dropbox Response") except dbrest.ErrorResponse,e: raise DropboxDataStorageException("Dropbox Response Error: %s"%str(e))
def get_chunk_data(self, chunk): access_token = "JkT9Fsx17gQAAAAAAAAAs1DAbvAU3sQrP1pJ8WiTdnG7HzQHE70idZ9Ph-GBuA3s" client = DropboxClient(access_token) f, response = client.get_file_and_metadata(chunk.info['dropbox']) chunk.data = base64.b64decode(f.read())
from dropbox.client import DropboxOAuth2FlowNoRedirect, DropboxClient from dropbox import rest as dbrest auth_flow = DropboxOAuth2FlowNoRedirect('pos53ybtbvmf2dc', 'akmlyilnzwmti9b') authorize_url = auth_flow.start() 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 = raw_input("Enter the authorization code here: ").strip() try: access_token, user_id = auth_flow.finish(auth_code) except dbrest.ErrorResponse, e: print('Error: %s' % (e,)) # return client = DropboxClient(access_token) print 'linked account: ', client.account_info() f, metadata = client.get_file_and_metadata('/Work/Othodi/data/cities.txt') # f, metadata = client.get_file_and_metadata('/magnum-opus.txt') out_fname = 'cities_from_dropbox.txt' out = open('cities_from_dropbox.txt', 'wb') out.write(f.read()) out.close() print metadata with open(out_fname,'r'): for line in f: print(line)
class DropboxNoteProvider(RemoteNoteProvider): __DAY_ONE_EXTENSION= ".doentry" def __init__(self, accessToken, folder, proxyHost=None, proxyPort=None, proxyUser=None, proxyPassword=None): self.__token= accessToken self.__notesPath= folder + "/entries" self.__removedNotesPath= self.__notesPath + "/deleted" self.__photosPath= folder + "/photos" self.__removedPhotosPath= self.__photosPath + "/deleted" self.__client= DropboxClient(self.__token, rest_client=_restClient(proxyHost, proxyPort, proxyUser, proxyPassword)) self.__notesCache= {} self.__dayOneFlavor= folder == SyncFolder.DayOne def requiresReverseUpdate(self): return True @online @expires def sync(self): notes= self.__list(self.__notesPath, False) removedNotes= self.__list(self.__removedNotesPath, True) #Clean inconsistent files for uuid in list(notes.keys()): if uuid in removedNotes: if removedNotes[uuid].lastModified >= notes[uuid].lastModified: self.__client.file_delete(self.__notePath(uuid)) if notes[uuid].hasPhoto: self.__client.file_delete(self.__photoPath(uuid)) del notes[uuid] else: self.__client.file_delete(self.__removedNotePath(uuid)) del removedNotes[uuid] notes.update(removedNotes) self.__notesCache= notes return notes @online @expires def get(self, uuid): response, metadata= self.__client.get_file_and_metadata(self.__notePath(uuid)) with response: note= unmarshalNote(response.read(), getLastModified(metadata)) if uuid not in self.__notesCache or self.__notesCache[uuid].hasPhoto: try: with self.__client.get_file(self.__photoPath(uuid)) as response: note.photo= response.read() except ErrorResponse as e: if e.status == 404: #Photo does not exist pass else: raise e return renderHtml(note) @online @expires def add(self, note): """ The note lastModified time is updated from Dropbox when the operations succeeds (unfortunately there's no way to set the modified time in Dropbox). """ uuid= note.uuid result= self.__client.put_file(self.__notePath(uuid), marshalNote(note)) if len(result["path"]) != len(self.__notePath(uuid)): try: self.__client.file_delete(result["path"]) except ErrorResponse: pass raise RuntimeError("Note[uuid=%s] already exists" % uuid) note.lastModified= getLastModified(result) if note.photo: self.__client.put_file(self.__photoPath(uuid), note.photo, overwrite=True) elif uuid in self.__notesCache and self.__notesCache[uuid].hasPhoto: try: self.__client.file_delete(self.__photoPath(uuid)) except ErrorResponse: pass renderHtml(note) #Clean removed note if exists if uuid in self.__notesCache and self.__notesCache[uuid].removed: try: self.__client.file_delete(self.__removedNotePath(uuid)) except ErrorResponse: pass @online @expires def update(self, note): """ The note lastModified time is updated from Dropbox when the operations succeeds (unfortunately there's no way to set the modified time in Dropbox). """ uuid= note.uuid #Check if note exists if self.__notesCache and (uuid not in self.__notesCache or self.__notesCache[uuid].removed): raise RuntimeError("Note[uuid=%s] does not exist" % uuid) result= self.__client.put_file(self.__notePath(uuid), marshalNote(note), overwrite=True) note.lastModified= getLastModified(result) if note.photo: self.__client.put_file(self.__photoPath(uuid), note.photo, overwrite=True) elif uuid not in self.__notesCache or self.__notesCache[uuid].hasPhoto: try: self.__client.file_delete(self.__photoPath(uuid)) except ErrorResponse: pass renderHtml(note) @online @expires def remove(self, note): """ The note lastModified time is updated from Dropbox when the operations succeeds (unfortunately there's no way to set the modified time in Dropbox). """ uuid= note.uuid #Remove note if exists if uuid in self.__notesCache and not self.__notesCache[uuid].removed: try: self.__client.file_delete(self.__notePath(uuid)) except ErrorResponse: pass #Remove photo if exists if uuid in self.__notesCache and self.__notesCache[uuid].hasPhoto: try: self.__client.file_delete(self.__photoPath(uuid)) except ErrorResponse: pass result= self.__client.put_file(self.__removedNotePath(uuid), b"", overwrite=True) note.lastModified= getLastModified(result) def __list(self, path, removed): folder= self.__client.metadata(path) if not folder["is_dir"]: raise RuntimeError("Path is not a folder") notes= {} pos= len(path) + 1 for file in folder["contents"]: if not file["is_dir"]: name= self.__fileUuid(file["path"][pos:]) if isUuid(name): notes[name]= NoteStatus(name, getLastModified(file), removed) if not removed: folder= self.__client.metadata(self.__photosPath) if not folder["is_dir"]: raise RuntimeError("Path is not a folder") pos= len(self.__photosPath) + 1 for file in folder["contents"]: name= file["path"][pos:] if not file["is_dir"] and name.endswith(".jpg"): name= name[:-4] if name in notes: notes[name].hasPhoto= True return notes def __fileUuid(self, filename): if self.__dayOneFlavor and filename.endswith(self.__DAY_ONE_EXTENSION): return filename[:-(len(self.__DAY_ONE_EXTENSION))] return filename def __buildNotePath(self, parentPath, uuid): path= parentPath + "/" + uuid if self.__dayOneFlavor: path+= self.__DAY_ONE_EXTENSION return path def __notePath(self, uuid): return self.__buildNotePath(self.__notesPath, uuid) def __removedNotePath(self, uuid): return self.__buildNotePath(self.__removedNotesPath, uuid) def __photoPath(self, uuid): return self.__photosPath + "/" + uuid + ".jpg"
from dropbox.client import DropboxOAuth2FlowNoRedirect, DropboxClient from dropbox import rest as dbrest auth_flow = DropboxOAuth2FlowNoRedirect('pos53ybtbvmf2dc', 'akmlyilnzwmti9b') authorize_url = auth_flow.start() 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 = raw_input("Enter the authorization code here: ").strip() try: access_token, user_id = auth_flow.finish(auth_code) except dbrest.ErrorResponse, e: print('Error: %s' % (e, )) # return client = DropboxClient(access_token) print 'linked account: ', client.account_info() f, metadata = client.get_file_and_metadata('/Work/Othodi/data/cities.txt') # f, metadata = client.get_file_and_metadata('/magnum-opus.txt') out_fname = 'cities_from_dropbox.txt' out = open('cities_from_dropbox.txt', 'wb') out.write(f.read()) out.close() print metadata with open(out_fname, 'r'): for line in f: print(line)