webkit_gtk.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import json
  2. import gtk
  3. import webkit
  4. CHECK_AUTH_JS = """
  5. var code = document.getElementById("code");
  6. var access_denied = document.getElementById("access_denied");
  7. var result;
  8. if (code) {
  9. result = {authorized: true, code: code.value};
  10. } else if (access_denied) {
  11. result = {authorized: false, message: access_denied.innerText};
  12. } else {
  13. result = {};
  14. }
  15. window.status = JSON.stringify(result);
  16. """
  17. def _on_webview_status_bar_changed(webview, status, dialog):
  18. if status:
  19. authorization = json.loads(status)
  20. if authorization.has_key("authorized"):
  21. dialog.set_data("authorization_code", authorization["code"])
  22. dialog.response(0)
  23. def get_code(url, size=(640, 480), title="Google authentication"):
  24. """Open a GTK webkit window and return the access code."""
  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", lambda event, data: dialog.response(1))
  34. webview.connect("load-finished",
  35. lambda view, frame: view.execute_script(CHECK_AUTH_JS))
  36. webview.connect("status-bar-text-changed", _on_webview_status_bar_changed, dialog)
  37. dialog.set_data("authorization_code", None)
  38. status = dialog.run()
  39. dialog.destroy()
  40. while gtk.events_pending():
  41. gtk.main_iteration(False)
  42. return dialog.get_data("authorization_code")