def import_dropbox(force = False): ''' Returns list of arrays of cvs lines Lines are preprocessed according to bank's format. ''' db = shelve.open('dropboxfiles') client = get_client() meta = client.metadata('/xpense') files = meta['contents'] res = [] for f in files: if f['is_dir']: continue path = str(f['path']) if path in db: logging.info('Already imported file %s', path) if not force: logging.info('... skipping') continue else: logging.info('... forcing import') db[path] = 'True' file, meta = client.get_file_and_metadata(path) lines = file.read().splitlines() file.close() logging.info('Read file %s with %i bytes', path, len(lines)) # Preprocess del lines[0:4] del lines[-1] res.append(lines) db.close() return res
# coding: utf-8 # https://forum.omz-software.com/topic/1521/dropbox-access-txt-file/5 import contextlib, dropboxlogin filename = '2048.py' dropbox_client = dropboxlogin.get_client() with contextlib.closing(dropbox_client.get_file(filename)) as in_file: data = in_file.read() print data # -------------------- # Here is a 6 liner that simply uploads, then downloads a textfile, which makes use of the generated token to make things easy. You can replace the test string with an open file object import dropbox, contextlib TOKEN = 'YOUR ACCESS TOKEN GOES HERE... GENERATE FROM DROPBOX API PAGE' d = dropbox.Dropbox(TOKEN) d.files_upload('test', '/test.txt') with contextlib.closing(d.files_download('/test.txt')[1]) as response: print response.content # --------------------
def upload(slug, dropbox_draft_path): print '\nUploading ' + slug + '.md' f = open(slug + '.md') db = dropboxlogin.get_client() response = db.put_file(dropbox_draft_path + slug + '.md', f) remove(slug + '.md')
def upload(slug, dropbox_draft_path): print '\nUploading ' + slug +'.md' f = open(slug + '.md') db = dropboxlogin.get_client() response = db.put_file(dropbox_draft_path + slug + '.md', f) remove(slug + '.md')
## This is a wrapper script for sending documents to Docverter ## for conversion from markdown to PDF using Pandoc. Typically ## Docverter calls are made with cURL; this script uses httplib. ## It is intended for use with Pythonista on iOS, so output file ## is uploaded to Dropbox after document conversion. ## For more information, see: http://www.docverter.com/api.html import clipboard import datetime import httplib import mimetypes ## https://gist.github.com/omz/4034526 ## http://omz-software.com/pythonista/forums/discussion/10/using-the-dropbox-module/p1 from dropboxlogin import get_client dropbox_client = get_client() ## Helper functions for posting multipart/form-data request ## using standard libraries. Updated to reflect changes to ## httplib in Python 2.0. ## {{{ http://code.activestate.com/recipes/146306/ (r1) def post_multipart(host, selector, fields, files): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page. """ content_type, body = encode_multipart_formdata(fields, files) h = httplib.HTTPConnection(host)
def main(choose, keepMeta, geoTag, dest_dir, size): minumum_size = True resizePercent = 0 if size == 'fifty': scale = float(50) / 100 elif size == 'custom': msg = 'Enter desired reduction percent for selected photo(s): ' try: scale = float(console.input_alert(msg, 'Numbers only', '35')) / 100 # No minumums here...reduce all photos no matter what their size. minumum_size = False except KeyboardInterrupt: sys.exit('Script cancelled.') elif size == 'none': scale = 1 #john = dialogs.form_dialog(title = 'Photo Options',fields=[{'type':'switch','title':'Geotag'}, {'type':'switch','title':'Keep Metadata'}]) # Disable idle timer to cover working with a large batch of photos console.set_idle_timer_disabled(True) start = time.clock() # Create an instance of Dropbox client drop_client = get_client() ans = '' ''' When metadata is returned with photo the photo is a tuple, with one the image, and the other the media metadata. ''' for count, photo in enumerate(choose): # Raw data string and Metadata img, meta = photo #print meta #sys.exit() print '\nProcessing photo...' # Get date & time photo was taken theYear, theDate, theTime = GetDateTime(meta) # Formulate file name for photo old_filename = str(meta.get('filename')) if theDate: folder_name = '{}/{}'.format(theYear, theDate) new_filename = '{}.{}'.format(theTime, old_filename) else: folder_name = 'NoDates' new_filename = old_filename keepMeta = False new_filename = '{}/{}/{}'.format(dest_dir, folder_name, new_filename) if folder_name == 'NoDates': no_exif.append(new_filename) # Get dimensions for resize based on size of original photo new_w, new_h, w, h, resizeOk = GetDimensions(meta, scale, new_filename, minumum_size) fmt = '\nOriginal Name: {}\nNew Name: {}' print fmt.format(old_filename, new_filename) fmt = '\nOriginal Size: {}x{}\nNew Size: {}x{}' print fmt.format(w, h, new_w, new_h) addToMsg = 'with' if keepMeta else 'without' if resizeOk: msg = '\nCreating resized copy of original photo {} the metadata from original.' else: msg = '\nCreating copy of original photo {} the metadata from original.' print msg.format(addToMsg) # Write string image of original photo to Pythonista script dir with open('with_meta.jpg', 'wb') as out_file: out_file.write(img) # Open image, resize it, and write new image to scripts dir img = Image.open('with_meta.jpg') img = img.resize((new_w, new_h), Image.ANTIALIAS) if geoTag: # Get geo-tagging info theLocation = GetLocation(meta) if theLocation: print '\nGeo-tagging photo...' # Find out if photo is oriented for landscape or portrait orientation = meta.get('Orientation') # ccc: add a default? ''' Get degrees needed to rotate photo for it's proper orientation. See www.impulsesdventue.com/photo exif-orientation.html for more details. ''' degrees, oriented = GetDegreesToRotate(orientation) print '\nThe orientation for photo is {}.'.format(oriented) theTime = theTime.replace('.', ':') theLocation = '{} @ {} in {}'.format(theDate, theTime, theLocation) # Rotate so tag is on bottom of photo regardless of orientation img = img.rotate(degrees).convert('RGBA') # Tuple w, h = img.size draw = ImageDraw.Draw(img) # Font for geo-tag will be 28 pt Helvetica #fontsize = 56 if w > 1300 else 28 fontsize = 28 font = ImageFont.truetype('Helvetica', fontsize) # Determine y axis for geotag #if h < 1000: #y = h - 35 #else: #y = h - 75 y = h - 35 # Put red text @ bottom left of photo draw.text((25, y), theLocation, (255, 0, 0), font=font) # Rotate back to original position img = img.rotate(-degrees) else: print '\nNo gps metadata for photo.' no_gps.append(new_filename) else: print '\nPhoto will not be geotagged. Flag is set to false.' meta = '' #img = img.resize((new_w, new_h),Image.ANTIALIAS) # Save new image img.save('without_meta.jpg') if keepMeta: ''' Copy metadata from 'with_meta.jpg' to 'without_meta.jpg and call this reprocessed image file 'meta_resized.jpg'. ''' CopyMeta('with_meta.jpg', 'without_meta.jpg', new_w, new_h) jpgFile = 'meta_resized.jpg' else: # Use resized photo that has not had metadata added back into it jpgFile = 'without_meta.jpg' print '\nUploading photo to Dropbox...' ''' Upload resized photo with or without original metadata to Dropbox...use with statement to open file so file closes automatically at end of with. ''' with open(jpgFile, 'r') as img: response = drop_client.put_file(new_filename, img) # Give Dropbox server time to process time.sleep(5) response = jpgFile = theLocation = img = theDate = theTime = theYear = new_filename = old_filename = '' print '\nUpload successful.' finish = time.clock() print '{} photos processed in {}'.format(count + 1, Timer(start, finish, count + 1)) if no_exif: print '\nPhotos with no DateTimeOriginal tag in their metadata and will need categorizing manually:' print '\n'.join(no_exif) if no_resize: print '\nPhotos that did not get resized because either you chose not to resize, or they were smaller than the minumum size of 1600x1200:' print '\n'.join(no_resize) if no_gps: print '\nPhotos that did not get geo-tagged because there was no gps info in the photo\'s metadata:' print '\n'.join(no_gps)
# Original script by Federico Viticci: # http://omz-software.com/pythonista/forums/discussion/comment/165#Comment_165 # dropboxlogin must be setup prior to using this script # Script by OMZ located here: https://gist.github.com/4034526 # javascript:window.location='pythonista://MakePDF?action=run&argv='+encodeURIComponent(document.title)+'&argv='+encodeURIComponent(document.location.href); import clipboard import urllib2 import console from dropboxlogin import get_client dropbox_client = get_client() import keychain import time import webbrowser import sys import webbrowser import urllib import bs4 numArgs = len(sys.argv) console.clear() if numArgs < 2: url = clipboard.get() console.show_activity() soup = bs4.BeautifulSoup(urllib.urlopen(url))
# See: http://omz-forums.appspot.com/pythonista/post/5823162193281024 import dropboxlogin import os import tarfile tar_file_name = "my_archive.tar" with tarfile.open(tar_file_name, "w") as out_file: # add this script at the root of the tarball out_file.add(os.path.basename(__file__)) with open(tar_file_name) as in_file: dropboxlogin.get_client().put_file(tar_file_name, in_file, overwrite=True)
return state def savestate(state): fyle = open(STATE_FILE,'w') pickle.dump(state,fyle) fyle.close() if __name__ == '__main__': console.show_activity() print """ **************************************** * Dropbox File Syncronization * ****************************************""" client = dropboxlogin.get_client() print '\nLoading local state' # lets see if we can unpickle try: state = loadstate() except: print '\nCannot find state file. ***Making new local state***' # Aaaah, we have nothing, probably first run state = dropbox_state() print '\nDownloading everything from Dropbox' # no way to check what we have locally is newer, gratuitous dl state.download_all(client) print '\nUpdating state from Dropbox' state.execute_delta(client)
# See: http://omz-forums.appspot.com/pythonista/post/5823162193281024 import dropboxlogin import tarfile tar_file_name = "my_archive.tar" with open(tar_file_name, "w") as out_file: out_file.write(dropboxlogin.get_client().get_file(tar_file_name).read()) with tarfile.open(tar_file_name) as tar_file: tar_file.extractall()
# See: http://omz-forums.appspot.com/pythonista/post/5823162193281024 import dropboxlogin, tarfile tar_file_name = 'my_archive.tar' with open(tar_file_name, 'w') as out_file: out_file.write(dropboxlogin.get_client().get_file(tar_file_name).read()) with tarfile.open(tar_file_name) as tar_file: tar_file.extractall()