webkit_qt.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. CHECK_AUTH_JS = """
  2. var code = document.getElementById("code");
  3. var access_denied = document.getElementById("access_denied");
  4. var result;
  5. if (code) {
  6. result = {authorized: true, code: code.value};
  7. } else if (access_denied) {
  8. result = {authorized: false, message: access_denied.innerText};
  9. } else {
  10. result = {};
  11. }
  12. result;
  13. """
  14. def _on_qt_page_load_finished(dialog, webview):
  15. to_s = lambda x: (str(x.toUtf8()) if hasattr(x,'toUtf8') else x)
  16. frame = webview.page().currentFrame()
  17. try: #PySide does not QStrings
  18. from QtCore import QString
  19. jscode = QString(CHECK_AUTH_JS)
  20. except ImportError:
  21. jscode = CHECK_AUTH_JS
  22. res = frame.evaluateJavaScript(jscode)
  23. try:
  24. authorization = dict((to_s(k), to_s(v)) for (k, v) in res.toPyObject().items())
  25. except AttributeError: #PySide returns the result in pure Python
  26. authorization = dict((to_s(k), to_s(v)) for (k, v) in res.items())
  27. if "authorized" in authorization:
  28. dialog.authorization_code = authorization.get("code")
  29. dialog.close()
  30. def get_code(url, size=(640, 480), title="Google authentication"):
  31. """Open a QT webkit window and return the access code."""
  32. try:
  33. from PyQt4 import QtCore, QtGui, QtWebKit
  34. except ImportError:
  35. from PySide import QtCore, QtGui, QtWebKit
  36. app = QtGui.QApplication([])
  37. dialog = QtGui.QDialog()
  38. dialog.setWindowTitle(title)
  39. dialog.resize(*size)
  40. webview = QtWebKit.QWebView()
  41. webpage = QtWebKit.QWebPage()
  42. webview.setPage(webpage)
  43. webpage.loadFinished.connect(lambda: _on_qt_page_load_finished(dialog, webview))
  44. webview.setUrl(QtCore.QUrl.fromEncoded(url))
  45. layout = QtGui.QGridLayout()
  46. layout.addWidget(webview)
  47. dialog.setLayout(layout)
  48. dialog.authorization_code = None
  49. dialog.show()
  50. app.exec_()
  51. return dialog.authorization_code