~chipaca/+junk/watgui

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import sys
import dbus
from BeautifulSoup import BeautifulSoup
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import Soup, SoupGNOME
import gtk
import gtksourceview2
import json
from oauth import oauth
import ubuntu_sso

MAGIC_COUCH_URI = "magic:couch"
ACCOUNT_URI = "https://one.ubuntu.com/api/account/"
KNOWN_URIS = [ACCOUNT_URI,
              "https://one.ubuntu.com/api/1.0/devices/",
              "https://one.ubuntu.com/api/quota/",
              "https://one.ubuntu.com/api/storage",
              "https://one.ubuntu.com/files/api/public_files",
              "https://one.ubuntu.com/notes/api/1.0/",
              "https://one.ubuntu.com/notes/api/1.0/user/",
              MAGIC_COUCH_URI,
              ]

class WebApiToolGui(gtk.Window):
    def __init__(self):
        super(WebApiToolGui, self).__init__()
        self.set_default_size(800, 600)
        self.connect("delete-event", gtk.main_quit)
        self.set_border_width(4)
        self.set_icon_name("gnome-web-browser")
        self.set_title("WATGUI: Web API Tool GUI")

        vbox = gtk.VBox(spacing=4)
        self.add(vbox)

        hbox = gtk.HBox(spacing=4)
        vbox.pack_start(hbox, False, False, 0)

        self.uri_entry = gtk.combo_box_entry_new_text()
        hbox.pack_start(self.uri_entry, True, True, 0)
        for uri in sys.argv[1:]:
            self.uri_entry.append_text(uri)
        for uri in KNOWN_URIS:
            self.uri_entry.append_text(uri)
        self.uri_entry.set_active(0)
        self.uri_entry.child.set_activates_default(True)
        self.uri_entry.set_tooltip_text("The URI to GET")

        self.app_entry = gtk.Entry()
        hbox.pack_start(self.app_entry, False, False, 0)
        self.app_entry.set_text("Ubuntu One")
        self.app_entry.set_activates_default(True)
        self.app_entry.set_tooltip_text("The SSO App Name")

        self.hmac_chk = gtk.CheckButton("HMAC")
        hbox.pack_start(self.hmac_chk, False, False, 0)
        self.hmac_chk.set_active(True)

        button = gtk.Button()
        button.add(gtk.image_new_from_icon_name("forward",
                                                gtk.ICON_SIZE_BUTTON))
        button.connect("clicked", self._clicked_cb)
        hbox.pack_start(button, False, False, 0)
        button.set_can_default(True)
        button.grab_default()

        self.sw = gtk.ScrolledWindow()
        self.sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.sw.set_shadow_type(gtk.SHADOW_IN)
        vbox.pack_start(self.sw, True, True, 0)

        self.buffer = gtksourceview2.Buffer()

        self.view = gtksourceview2.View(self.buffer)
        self.view.set_editable(False)
        self.sw.add(self.view)

        self.spinner_vp = gtk.Viewport()
        self.spinner_vp.set_shadow_type(gtk.SHADOW_IN)
        vbox.pack_start(self.spinner_vp, True, True, 0)

        vbox2 = gtk.VBox()
        self.spinner_vp.add(vbox2)

        self.spinner = gtk.Spinner()
        vbox2.pack_start(self.spinner, True, False, 0)

        self.langmgr = gtksourceview2.LanguageManager()

        self.session = Soup.SessionAsync()
        self.session.add_feature_by_type(SoupGNOME.ProxyResolverGNOME)
        self.bus = dbus.SessionBus()

    def show_all(self):
        super(WebApiToolGui, self).show_all()
        self._stop_spinner()

    def _start_spinner(self):
        self.sw.hide()
        self.spinner_vp.show_all()
        self.spinner.start()

    def _stop_spinner(self):
        self.sw.show_all()
        self.spinner_vp.hide()
        self.spinner.stop()

    def _clicked_cb(self, button):
        self._start_spinner()
        proxy = self.bus.get_object(ubuntu_sso.DBUS_BUS_NAME,
                                    ubuntu_sso.DBUS_CRED_PATH,
                                    follow_name_owner_changes=True)
        proxy.find_credentials(self._get_app_name(),
                               dbus_interface=ubuntu_sso.DBUS_IFACE_CRED_NAME,
                               reply_handler=self._dbus_reply_handler,
                               error_handler=self._dbus_error_handler)

    def _get_app_name(self):
        return self.app_entry.get_text().strip()

    def _dbus_reply_handler(self, credentials):
        do_request = bool(credentials)
        request = None
        uri = orig_uri = self.uri_entry.get_active_text().strip()
        if orig_uri == MAGIC_COUCH_URI:
            uri = ACCOUNT_URI
        method = "GET"
        if not credentials:
            app_name = self._get_app_name()
            dialog = gtk.MessageDialog(parent=self, type=gtk.MESSAGE_QUESTION,
                                       buttons=gtk.BUTTONS_YES_NO,
                                       message_format="Continue with no OAuth?")
            fmt = u"I was unable to find OAuth tokens for app \u201c%s\u201d"
            dialog.format_secondary_text(fmt % app_name)
            do_request = dialog.run() == gtk.RESPONSE_YES
            dialog.hide()
            dialog.destroy()
        else:
            if 0 and uri.startswith('https://couchdb.one.ubuntu.com/'):
                consumer = oauth.OAuthConsumer("ubuntuone",
                                               "hammertime")
            else:
                consumer = oauth.OAuthConsumer(credentials["consumer_key"],
                                               credentials["consumer_secret"])
            token = oauth.OAuthToken(credentials["token"],
                                     credentials["token_secret"])
            request = oauth.OAuthRequest.from_consumer_and_token(
                http_url=uri,
                http_method=method,
                oauth_consumer=consumer,
                token=token)
            if self.hmac_chk.get_active():
                sig_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
            else:
                sig_method = oauth.OAuthSignatureMethod_PLAINTEXT()
            request.sign_request(sig_method,
                                 consumer, token)

        if do_request:
            try:
                msg = Soup.Message.new(method, uri)
            except StandardError:
                return self._error("Bad URI")
            if request is not None:
                for k, v in request.to_header().items():
                    msg.request_headers.append(k, v)
            self.session.queue_message(msg, self._callback, orig_uri)
        else:
            self._stop_spinner()

    def _debug(self, header, value, _):
        print '%-20s: %s' % (header, value)

    def _handle_magic_uri_result(self, msg):
        data = json.loads(msg.response_body.data)
        host = data['couchdb']['host']
        path = data['couchdb']['dbpath']
        self.uri_entry.remove_text(KNOWN_URIS.index(MAGIC_COUCH_URI))
        self.uri_entry.append_text("%s/%s/" % (host, path.replace('/', '%2f')))
        self.uri_entry.set_active(len(KNOWN_URIS)-1)
        self._set_buffer("couchdb URL ready")
        self._stop_spinner()

    def _callback(self, session, msg, uri):
        if uri == MAGIC_COUCH_URI and msg.status_code == 200:
            return self._handle_magic_uri_result(msg)

        self.set_title("WATGUI: %s" % (uri,))

        msg.response_headers.foreach(self._debug, None)
        data = msg.response_body.data
        content_type = msg.response_headers.get_one("content-type")
        if content_type:
            content_type = content_type.split(';')[0]
            munger = getattr(self, '_munge_' + content_type.replace('/', '_'),
                             lambda s: (s, None))
            data, lang_id = munger(data)
        if data is not None:
            self._set_buffer(data, lang_id)
            print
            print data
        elif msg.status_code != 200:
            self._set_buffer("%s: %s" % (msg.status_code, msg.reason_phrase))
        self._stop_spinner()

    def _error(self, msg):
        self._set_buffer(msg)
        self._stop_spinner()

    def _set_buffer(self, data, lang_id=None):
        if lang_id is not None:
            lang = self.langmgr.get_language(lang_id)
            self.buffer.set_language(lang)
            self.buffer.set_highlight_syntax(True)
        else:
            self.buffer.set_highlight_syntax(False)
        self.buffer.begin_not_undoable_action()
        self.buffer.set_text(data)
        self.buffer.end_not_undoable_action()

    def _munge_application_json(self, data):
        return json.dumps(json.loads(data), indent=4), 'js'

    def _munge_text_html(self, data):
        # beautifulsoup does a good job at guessing the encoding
        return str(BeautifulSoup(data)), 'html'

    def _dbus_error_handler(self, *a):
        print 'dbus error:', a
        self._error(str(a))



if __name__ == '__main__':
    DBusGMainLoop(set_as_default=True)
    tool = WebApiToolGui()
    tool.show_all()
    gtk.main()