webkit_qt.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. try:
  2. from PyQt4 import QtCore, QtGui, QtWebKit
  3. except ImportError:
  4. from PySide import QtCore, QtGui, QtWebKit
  5. CHECK_AUTH_JS = """
  6. var code = document.getElementById("code");
  7. var access_denied = document.getElementById("access_denied");
  8. var result;
  9. if (code) {
  10. result = {authorized: true, code: code.value};
  11. } else if (access_denied) {
  12. result = {authorized: false, message: access_denied.innerText};
  13. } else {
  14. result = {};
  15. }
  16. result;
  17. """
  18. def _on_qt_page_load_finished(dialog, webview):
  19. to_s = lambda x: (str(x.toUtf8()) if hasattr(x,'toUtf8') else x)
  20. frame = webview.page().currentFrame()
  21. try: #PySide does not QStrings
  22. from QtCore import QString
  23. jscode = QString(CHECK_AUTH_JS)
  24. except ImportError:
  25. jscode = CHECK_AUTH_JS
  26. res = frame.evaluateJavaScript(jscode)
  27. try:
  28. authorization = dict((to_s(k), to_s(v)) for (k, v) in res.toPyObject().items())
  29. except AttributeError: #PySide returns the result in pure Python
  30. authorization = dict((to_s(k), to_s(v)) for (k, v) in res.items())
  31. if "authorized" in authorization:
  32. dialog.authorization_code = authorization.get("code")
  33. dialog.close()
  34. def get_code(url, size=(640, 480), title="Google authentication"):
  35. """Open a QT webkit window and return the access code."""
  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