Advertisement
Guest User

pyDropboxPath.py for Python 2.x

a guest
Jan 18th, 2011
1,605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.18 KB | None | 0 0
  1.  
  2. #!/usr/bin/env python
  3. # Python code to read/write/backup/delete dropbox config values for both 0.7.x and 0.8.x/1.0.x on all platforms
  4. # Code blatantly 'stolen' from pyDropboxPath.py 0.8.3  :-)
  5. # This file written by Andrew Scheller, 2010-10-14
  6. # Updated by Andrew Scheller, 2010-11-09
  7. # Updated by Andrew Scheller, 2011-01-01
  8. # Updated by Andrew Scheller, 2011-01-12
  9. #
  10. # http://wiki.dropbox.com/DropboxAddons/PyDropboxValues
  11.  
  12. usage_txt = '''Usage:
  13. pyDropboxValues.py
  14. or
  15. pyDropboxValues.py --help
  16. or
  17. pyDropboxValues.py [_printkeys|_linkurl|_raw|_backup|_dropbox]
  18. '''
  19.  
  20. import os
  21. import sys
  22. try:
  23.         import sqlite3
  24. except:
  25.     from pysqlite2 import dbapi2 as sqlite3
  26. import base64
  27. import pickle
  28. import shutil
  29.  
  30. pickled_keys = set(('ns_p2p_key_map', 'recently_changed3', 'sandboxes', 'shadowed_proxy_password', 'last_update'))
  31.  
  32.  
  33. def GetConfigDbDirectory():
  34.         if sys.platform == 'win32':
  35.                 assert os.environ.has_key('APPDATA'), Exception('APPDATA env variable not found')
  36.                 dbpath = os.path.join(os.environ['APPDATA'],'Dropbox')
  37.         elif sys.platform in ('linux2','darwin'):
  38.                 assert os.environ.has_key('HOME'), Exception('HOME env variable not found')
  39.                 dbpath = os.path.join(os.environ['HOME'],'.dropbox')
  40.         else: # FIXME other archs?
  41.                 raise Exception('platform %s not known, please report' % sys.platform)
  42.         return dbpath
  43.  
  44.  
  45. def GetConfigDbFilename():
  46.         dbpath = GetConfigDbDirectory()
  47.         if os.path.isfile(os.path.join(dbpath,'config.db')):
  48.                 dbfn, dbfnver = os.path.join(dbpath,'config.db'), 1
  49.         elif os.path.isfile(os.path.join(dbpath, 'dropbox.db')):
  50.                 dbfn, dbfnver = os.path.join(dbpath,'dropbox.db'), 0
  51.         else:
  52.                 raise Exception('Dropbox database not found, is dropbox installed?')
  53.         return (dbfn, dbfnver)
  54.  
  55.  
  56. def GetDbConnection(dbfile):
  57.         lastdir = os.getcwd()
  58.         os.chdir(os.path.dirname(dbfile))
  59.         connection = sqlite3.connect(os.path.basename(dbfile), isolation_level=None)
  60.         os.chdir(lastdir)
  61.         return connection
  62.  
  63.  
  64. def GetDbVersion(dbfnver, connection):
  65.         if dbfnver == 0: # dropbox.db, old-style
  66.                 dbver = 0
  67.         elif dbfnver == 1: # config.db, can be upgraded, lets check schema
  68.                 cursor = connection.cursor()
  69.                 cursor.execute('SELECT value FROM config WHERE key="config_schema_version"')
  70.                 row = cursor.fetchone()
  71.                 cursor.close()
  72.                 dbver = row[0]
  73.         return dbver
  74.  
  75.  
  76. def GetDbKeys(connection):
  77.         cursor = connection.cursor()
  78.         cursor.execute('SELECT key FROM config')
  79.         allkeys = set()
  80.         for row in cursor:
  81.                 allkeys.add(row[0])
  82.         cursor.close()
  83.         return allkeys
  84.  
  85.  
  86. # ReadDbValue can be called while dropbox is running
  87. def ReadDbValue(connection, dbver, dbkey, decode_value=True):
  88.         cursor = connection.cursor()
  89.         # dup code now, but maybe someday it will be different
  90.         if dbver == 0:
  91.                 cursor.execute('SELECT value FROM config WHERE key=?', (dbkey,))
  92.         elif dbver == 1:
  93.                 cursor.execute('SELECT value FROM config WHERE key=?', (dbkey,))
  94.         else:
  95.                 raise Exception('Unhandled DB schema version %d' % dbver)
  96.  
  97.         row = cursor.fetchone()
  98.         cursor.close()
  99.         if row is None:
  100.                 raise Exception('key %s not found in dropbox config database' % dbkey)
  101.         else:
  102.                 dbvalue = row[0]
  103.                 if dbvalue and decode_value:
  104.                         if dbver == 0: # always pickled then b64encoded
  105.                                 value = pickle.loads(base64.b64decode(dbvalue))
  106.                         elif dbver == 1: # some (non-string) values are still pickled
  107.                                 if dbkey in pickled_keys:
  108.                                         value = pickle.loads(dbvalue)
  109.                                 else:
  110.                                         value = dbvalue
  111.                         else:
  112.                                 raise Exception('Unhandled DB schema version %d' % dbver)
  113.                 else:
  114.                         value = dbvalue
  115.         return value
  116.  
  117.  
  118. # WriteDbValue should only be called when dropbox is stopped
  119. def WriteDbValue(connection, dbver, dbkey, value, encode_value=True):
  120.         if encode_value:
  121.                 if dbver == 0: # always pickled then b64encoded
  122.                         dbvalue = base64.b64encode(pickle.dumps(value))
  123.                 elif dbver == 1: # some (non-string) values are still pickled
  124.                         if dbkey in pickled_keys:
  125.                                 dbvalue = pickle.dumps(value)
  126.                         else:
  127.                                 dbvalue = value
  128.                 else:
  129.                         raise Exception('Unhandled DB schema version %d' % dbver)
  130.         else:
  131.                 dbvalue = value
  132.         cursor = connection.cursor()
  133.         cursor.execute('REPLACE INTO config (key,value) VALUES (?,?)', (dbkey,dbvalue))
  134.         cursor.close()
  135.  
  136.  
  137. # DeleteDbValue should only be called when dropbox is stopped
  138. def DeleteDbValue(connection, dbver, dbkey):
  139.         cursor = connection.cursor()
  140.         cursor.execute('DELETE FROM config WHERE key=?', (dbkey,))
  141.         cursor.close()
  142.  
  143.  
  144. # Utility function - locate the user's "Dropbox" folder
  145. def GetDropboxLocation(connection=None, dbver=None):
  146.         if connection is None:
  147.                 dbfile, dbfnver = GetConfigDbFilename()
  148.                 connection = GetDbConnection(dbfile)
  149.                 dbver = GetDbVersion(dbfnver, connection)
  150.         try:
  151.                 # first try to get path from config database
  152.                 dbfolder = ReadDbValue(connection, dbver, 'dropbox_path')
  153.         except Exception, e:
  154.                 if str(e) == 'key %s not found in dropbox config database' % 'dropbox_path':
  155.                         # second try to get path from host.db
  156.                         dbpath = GetConfigDbDirectory()
  157.                         if os.path.isfile(os.path.join(dbpath,'host.db')):
  158.                                 dbfolder = base64.b64decode(open(os.path.join(dbpath,'host.db')).readlines()[1])
  159.                         else:
  160.                                 # finally just guess default path
  161.                                 if sys.platform == 'win32':
  162.                                         import ctypes
  163.                                         dll = ctypes.windll.shell32
  164.                                         buf = ctypes.create_string_buffer(300)
  165.                                         dll.SHGetSpecialFolderPathA(None, buf, 0x0005, False)
  166.                                         if dbver == 0:
  167.                                                 dbfolder = os.path.join(buf.value,'My Dropbox')
  168.                                         else:
  169.                                                 dbfolder = os.path.join(buf.value,'Dropbox')
  170.                                 elif sys.platform in ('linux2','darwin'):
  171.                                         dbfolder = os.path.join(os.environ['HOME'],'Dropbox')
  172.                                 else:
  173.                                         raise Exception('platform %s not known, please report' % sys.platform)
  174.                 else:
  175.                         raise e
  176.         return dbfolder
  177.  
  178.  
  179. if __name__ == '__main__':
  180.         dbfile, dbfnver = GetConfigDbFilename()
  181.         connection = GetDbConnection(dbfile)
  182.         dbver = GetDbVersion(dbfnver, connection)
  183.         try:
  184.                 try:
  185.                         if len(sys.argv) == 1:
  186.                                 for key in sorted(GetDbKeys(connection)):
  187.                                         value = ReadDbValue(connection, dbver, key)
  188.                                         print key, '=', value
  189.                         elif len(sys.argv) == 2:
  190.                                 # hopefully there's never config values called _printkeys, _linkurl, _raw, _backup or _dropbox !
  191.                                 if sys.argv[1] == '-h' or sys.argv[1] == '--help':
  192.                                         print usage_txt
  193.                                 elif sys.argv[1] == '_printkeys':
  194.                                         print sorted(GetDbKeys(connection))
  195.                                 elif sys.argv[1] == '_linkurl':
  196.                                         value = ReadDbValue(connection, dbver, 'host_id')
  197.                                         print "https://www.dropbox.com/cli_link?host_id=%s" % value
  198.                                 elif sys.argv[1] == '_raw':
  199.                                         for key in sorted(GetDbKeys(connection)):
  200.                                                 value = ReadDbValue(connection, dbver, key, False)
  201.                                                 print key, '=', value
  202.                                 elif sys.argv[1] == '_backup':
  203.                                         (basedir, basefile) = os.path.split(dbfile)
  204.                                         backup_num = 1
  205.                                         backup_filename = os.path.join(basedir, "backup_%d_%s" % (backup_num, basefile))
  206.                                         while os.path.exists(backup_filename):
  207.                                                 backup_num += 1
  208.                                                 backup_filename = os.path.join(basedir, "backup_%d_%s" % (backup_num, basefile))
  209.                                         shutil.copy2(dbfile, backup_filename)
  210.                                         print "Backed up '%s' to '%s'" % (basefile, backup_filename)
  211.                                 elif sys.argv[1] == '_dropbox':
  212.                                         print GetDropboxLocation(connection, dbver)
  213.                                 else:
  214.                                         value = ReadDbValue(connection, dbver, sys.argv[1])
  215.                                         print value
  216.                         else:
  217.                                 print usage_txt
  218.                 except Exception , detail:
  219.                         print "An error occured: %s" % detail
  220.         finally:
  221.                 connection.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement