webkit_gtk.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import json
  2. CHECK_AUTH_JS = """
  3. var code = document.getElementById("code");
  4. var access_denied = document.getElementById("access_denied");
  5. var result;
  6. if (code) {
  7. result = {authorized: true, code: code.value};
  8. } else if (access_denied) {
  9. result = {authorized: false, message: access_denied.innerText};
  10. } else {
  11. result = {};
  12. }
  13. window.status = JSON.stringify(result);
  14. """
  15. def _on_webview_status_bar_changed(webview, status, dialog):
  16. if status:
  17. authorization = json.loads(status)
  18. if authorization.has_key("authorized"):
  19. dialog.set_data("authorization_code", authorization["code"])
  20. dialog.response(0)
  21. def get_code(url, size=(640, 480), title="Google authentication"):
  22. """Open a GTK webkit window and return the access code."""
  23. import gtk
  24. import webkit
  25. dialog = gtk.Dialog(title=title)
  26. webview = webkit.WebView()
  27. scrolled = gtk.ScrolledWindow()
  28. scrolled.add(webview)
  29. dialog.get_children()[0].add(scrolled)
  30. webview.load_uri(url)
  31. dialog.resize(*size)
  32. dialog.show_all()
  33. dialog.connect("delete-event",
  34. lambda event, data: dialog.response(1))
  35. webview.connect("load-finished",
  36. lambda view, frame: view.execute_script(CHECK_AUTH_JS))
  37. webview.connect("status-bar-text-changed",
  38. _on_webview_status_bar_changed, dialog)
  39. dialog.set_data("authorization_code", None)
  40. status = dialog.run()
  41. dialog.destroy()
  42. while gtk.events_pending():
  43. gtk.main_iteration(False)
  44. return dialog.get_data("authorization_code")