tarina

git clone https://git.tarina.org/tarina
Log | Files | Refs | README | LICENSE

webkit_gtk.py (1616B)


      1 import json
      2 
      3 CHECK_AUTH_JS = """
      4     var code = document.getElementById("code");
      5     var access_denied = document.getElementById("access_denied");
      6     var result;
      7     
      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 
     18 def _on_webview_status_bar_changed(webview, status, dialog):
     19     if status:
     20         authorization = json.loads(status)
     21         if authorization.has_key("authorized"):
     22             dialog.set_data("authorization_code", authorization["code"])
     23             dialog.response(0)
     24 
     25 def get_code(url, size=(640, 480), title="Google authentication"):
     26     """Open a GTK webkit window and return the access code."""
     27     import gtk
     28     import webkit
     29     dialog = gtk.Dialog(title=title)
     30     webview = webkit.WebView()
     31     scrolled = gtk.ScrolledWindow()
     32     scrolled.add(webview)
     33     dialog.get_children()[0].add(scrolled)
     34     webview.load_uri(url)    
     35     dialog.resize(*size)
     36     dialog.show_all()
     37     dialog.connect("delete-event", 
     38         lambda event, data: dialog.response(1))
     39     webview.connect("load-finished", 
     40         lambda view, frame: view.execute_script(CHECK_AUTH_JS))       
     41     webview.connect("status-bar-text-changed", 
     42         _on_webview_status_bar_changed, dialog)
     43     dialog.set_data("authorization_code", None)
     44     status = dialog.run()
     45     dialog.destroy()
     46     while gtk.events_pending():
     47         gtk.main_iteration(False)
     48     return dialog.get_data("authorization_code")