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