Advertisement
Guest User

Untitled

a guest
Aug 2nd, 2015
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. import os
  2. import sys
  3. import urllib
  4. from base64 import b64decode
  5. from zipfile import ZipFile
  6. from cStringIO import StringIO
  7. from uuid import uuid4 as uuid
  8.  
  9. import editor
  10. import console
  11. import keychain
  12. import webbrowser
  13.  
  14. # Set to true and run script to force entry of a new URL key
  15. RENEW_WC_CALLBACK_KEY = False
  16.  
  17. def path_after_docs_dir(pth):
  18. return pth.split("Documents/", 1)[-1]
  19.  
  20. def last_dir_in_path(pth):
  21. return os.path.basename(os.path.normpath(os.path.dirname(pth)))
  22.  
  23. def WC_callback_key(overwrite_key=False):
  24. service = "Working Copy"
  25. # UUID appended to avoid collision with another script
  26. # (generated on original dev machine)
  27. account = "x_callback_url_6653ee08-4c43-4453-a400-c5de315b0725"
  28. key = keychain.get_password(service, account)
  29. if overwrite_key or not key:
  30. key = console.input_alert("Enter Working Copy URL key:")
  31. keychain.set_password(service, account, key)
  32. return key
  33.  
  34. # Arriving here as callback
  35. if len(sys.argv) > 1:
  36. action = sys.argv[1]
  37. # Success
  38. if action == "unpack":
  39. dest_dir = sys.argv[2]
  40. data = sys.argv[3]
  41. # Receive zipped repo, unpack
  42. archive = ZipFile(StringIO(b64decode(data)))
  43. # Overwrite directory (asking?)
  44. archive.extractall(dest_dir)
  45. # Refresh editor after unpacking
  46. editor.reload_files()
  47. editor.open_file(editor.get_path())
  48. # Run as action
  49. else:
  50. # Get path to directory of script from which action was run; this will be
  51. # the install directory, passed to the script when it's called back
  52. dest_dir = os.path.dirname(editor.get_path())
  53. # The name of the repo in WC is assumed to be the same as the closest
  54. # enclosing directory from the activating script
  55. repo_name = os.path.basename(dest_dir)
  56. # Path of this retrieval script starting from Pythonista's Documents
  57. # directory, for the pythonista://<script-name> URL
  58. self_pth = path_after_docs_dir(__file__)
  59.  
  60. success_action = "pythonista://{}?action=run&argv=unpack&argv={}&argv="
  61. success_action = success_action.format(self_pth, dest_dir)
  62. command = "zip"
  63. URL_key = WC_callback_key(RENEW_WC_CALLBACK_KEY)
  64. url_args = urllib.urlencode({ "x-success" : success_action,
  65. "key" : URL_key,
  66. "repo" : repo_name})
  67. x_callback_url = "working-copy://x-callback-url/{command}/?{url_args}"
  68. x_callback_url = x_callback_url.format(command=command, url_args=url_args)
  69. webbrowser.open(x_callback_url)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement