~ralsina/u1-toys/trunk

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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# -*- coding: utf-8 -*-

import cgi
import json
import sys
from pprint import pprint
from urlparse import urlparse

from oauth import oauth
import dbus
import dbus.mainloop.qt
from PyQt4 import QtCore, QtGui, QtNetwork

from ubuntuone.controlpanel.web_client import WebClient
from ubuntuone.platform.credentials import CredentialsManagementTool

import rc_images

# FIXME: constants from u1cp
FILE_SYNC_DISABLED = u'file-sync-disabled'
FILE_SYNC_DISCONNECTED = u'file-sync-disconnected'
FILE_SYNC_ERROR = u'file-sync-error'
FILE_SYNC_IDLE = u'file-sync-idle'
FILE_SYNC_STARTING = u'file-sync-starting'
FILE_SYNC_STOPPED = u'file-sync-stopped'
FILE_SYNC_SYNCING = u'file-sync-syncing'
FILE_SYNC_UNKNOWN = u'file-sync-unknown'

MSG_KEY = 'message'
STATUS_KEY = 'status'

UBUNTUONE_FROM_OAUTH = u'https://one.ubuntu.com/api/1.0/from_oauth/'
QUOTA_API = u"https://one.ubuntu.com/api/quota/"

STATUS_DISABLED = {MSG_KEY: '', STATUS_KEY: FILE_SYNC_DISABLED}
WARNING_MARKUP = '<font color="red"><b>%%s</b></font>'
DISCONNECTED_ICON = 'disconnected'
ERROR_ICON = 'error'
IDLE_ICON = 'idle'
SYNCING_ICON = 'syncing'

MSG_FILE_SYNC_DISABLED = 'File Sync is disabled.'
MSG_FILE_SYNC_DISCONNECTED = 'File Sync is disconnected.'
MSG_FILE_SYNC_ERROR = 'File Sync error.'
MSG_FILE_SYNC_IDLE = 'File Sync is up-to-date.'
MSG_FILE_SYNC_STARTING = 'File Sync starting.'
MSG_FILE_SYNC_STOPPED = 'File Sync is stopped.'
MSG_FILE_SYNC_SYNCING = 'File Sync in progress.'


FILE_SYNC_STATUS = {
    FILE_SYNC_DISABLED:
        {'msg': MSG_FILE_SYNC_DISABLED,
         'icon': ERROR_ICON,
         },
    FILE_SYNC_DISCONNECTED:
        {'msg': MSG_FILE_SYNC_DISCONNECTED,
         'icon': DISCONNECTED_ICON,
         },
    FILE_SYNC_ERROR:
        {'msg': MSG_FILE_SYNC_ERROR,
         'icon': ERROR_ICON,
         },
    FILE_SYNC_IDLE:
        {'msg': MSG_FILE_SYNC_IDLE,
         'icon': IDLE_ICON,
         },
    FILE_SYNC_STARTING:
        {'msg': MSG_FILE_SYNC_STARTING,
         'icon': SYNCING_ICON,
         },
    FILE_SYNC_STOPPED:
        {'msg': MSG_FILE_SYNC_STOPPED,
         'icon': ERROR_ICON,
         },
    FILE_SYNC_SYNCING:
        {'msg': MSG_FILE_SYNC_SYNCING,
         'icon': SYNCING_ICON,
         },
    FILE_SYNC_UNKNOWN:
        {'msg': MSG_FILE_SYNC_ERROR,
         'icon': ERROR_ICON,
         },
}

# End of FIXME

from httplib2 import iri2uri


class TrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self):
        super(TrayIcon, self).__init__()
        self._quota_info = None
        self._last_status = None
        self.file_sync_disabled = None
        self.icons = {}
        self.icons[SYNCING_ICON] = QtGui.QIcon(':/syncing.png')
        self.icons[ERROR_ICON] = QtGui.QIcon(':/error.png')
        self.icons[IDLE_ICON] = QtGui.QIcon(':/idle.png')
        self.icons[DISCONNECTED_ICON] = QtGui.QIcon(':/disconnected.png')

        self.setup_menu()

        self.nam = QtNetwork.QNetworkAccessManager(self,
            finished=self.reply_finished)

        self.wc = WebClient(self.get_credentials)

        bus = dbus.SessionBus()
        self.sd_proxy = bus.get_object('com.ubuntuone.SyncDaemon', '/')

        self.status_proxy = bus.get_object(
            'com.ubuntuone.SyncDaemon', '/status')
        self.status_iface = dbus.Interface(self.status_proxy,
            dbus_interface='com.ubuntuone.SyncDaemon.Status')
        self.status_iface.connect_to_signal(
            'StatusChanged', self.status_changed)

        self.creds_proxy = bus.get_object("com.ubuntuone.Credentials",
                             "/credentials",
                             follow_name_owner_changes=True)
        self.creds_iface = dbus.Interface(self.creds_proxy,
            "com.ubuntuone.CredentialsManagement")
        self.creds_proxy.connect_to_signal('CredentialsFound',
            self.creds_found)
        self.creds_proxy.connect_to_signal('CredentialsNotFound',
            self.creds_not_found)
        self.creds_proxy.connect_to_signal('CredentialsError',
            self.creds_error)

        self._credentials = None
        self.get_credentials()
        self._last_status = self.process_status(
            self.status_proxy.current_status())

    def setup_menu(self):
        self.menu = QtGui.QMenu()

        self.open_u1_folder_action = QtGui.QAction("Open Ubuntu One Folder",
            self, triggered=self.open_u1_folder)
        self.menu.addAction(self.open_u1_folder_action)

        self.open_u1_web_action = QtGui.QAction("Go to Ubuntu One Web",
            self, triggered=self.open_u1_web)
        self.menu.addAction(self.open_u1_web_action)
        self.menu.addSeparator()

        self.quota_action = QtGui.QAction("", self)
        self.menu.addAction(self.quota_action)

        self.status_action = QtGui.QAction("", self)
        self.menu.addAction(self.status_action)

        self.get_more_storage_action = QtGui.QAction("Get more Storage",
            self, triggered=self.get_more_storage)
        self.menu.addAction(self.get_more_storage_action)
        self.menu.addSeparator()

        self.get_help_action = QtGui.QAction("Go to Ubuntu One Help",
            self, triggered=self.get_help)
        self.menu.addAction(self.get_help_action)

        self.quit_action = QtGui.QAction("Exit",
            self, triggered=self.quit)
        self.menu.addAction(self.quit_action)
        self.update_menu()
        self.setContextMenu(self.menu)

    def update_menu(self):
        if self._last_status:
            self.status_action.setVisible(True)
            status_key = self._last_status[STATUS_KEY]
            self.setIcon(self.icons[FILE_SYNC_STATUS[status_key]['icon']])
            self.status_action.setText(FILE_SYNC_STATUS[status_key]['msg'])
        else:
            self.status_action.setVisible(False)
        if self._quota_info:
            self.quota_action.setText(self.humanize_quota())
            self.quota_action.setVisible(True)
        else:
            self.quota_action.setVisible(False)

    def reply_finished(self, reply):
        if unicode(reply.url().path()) == u'/api/quota/':
            # Handle quota responses
            self._quota_info = json.loads(unicode(reply.readAll()))
            print "Got quota: ", self._quota_info
            self.update_menu()

    def creds_found(self, data):
        # Received credentials, save them.
        print "creds_found", data
        self._credentials = data
        if not self._quota_info:
            self.get_quota()

    def creds_not_found(self, data):
        # No credentials, remove old ones.
        print "creds_not_found", data
        self._credentials = None

    def creds_error(self, data):
        # No credentials, remove old ones.
        print "creds_error", data
        self._credentials = None

    def get_credentials(self):
        # Do we have them already? If not, get'em
        if not self._credentials:
            self.creds_proxy.find_credentials()
        # Return what we've got, could be None
        return self._credentials

    def open_u1_folder(self):
        path = self.sd_proxy.get_rootdir()
        QtGui.QDesktopServices.openUrl(QtCore.QUrl.fromLocalFile(path))

    def open_u1_web(self):
        self.open_uri("https://one.ubuntu.com/")

    def get_more_storage(self):
        self.open_uri("https://one.ubuntu.com/services/")

    def get_help(self):
        self.open_uri("https://one.ubuntu.com/help/")

    def quit(self):
        # FIXME: stop syncdaemon?
        QtGui.QApplication.instance().quit()

    def status_changed(self, status):
        print "New status:", status
        self._last_status = self.process_status(status)
        self.update_menu()

    # FIXME: duplicated from u1cp
    def process_status(self, status):
        """Process raw file sync status into custom format.

        Return a dictionary with two members:
        * STATUS_KEY: the current status of syncdaemon, can be one of:
            FILE_SYNC_DISABLED, FILE_SYNC_STARTING, FILE_SYNC_DISCONNECTED,
            FILE_SYNC_SYNCING, FILE_SYNC_IDLE, FILE_SYNC_ERROR,
            FILE_SYNC_UNKNOWN
        * MSG_KEY: a non translatable but human readable string of the status.

        """
        if not status:
            self.file_sync_disabled = True
            return

        msg = '%s (%s)' % (status['description'], status['name'])
        result = {MSG_KEY: msg}

        # file synch is enabled
        is_error = bool(status['is_error'])
        is_synching = bool(status['is_connected'])
        is_idle = bool(status['is_online']) and status['queues'] == 'IDLE'
        is_disconnected = status['name'] == 'WAITING' or \
                          (status['name'] == 'READY' and \
                           'Not User' in status['connection'])
        is_starting = status['name'] in ('INIT', 'LOCAL_RESCAN', 'READY')
        is_stopped = status['name'] == 'SHUTDOWN'

        if is_error:
            result[STATUS_KEY] = FILE_SYNC_ERROR
        elif is_idle:
            result[STATUS_KEY] = FILE_SYNC_IDLE
        elif is_synching:
            result[STATUS_KEY] = FILE_SYNC_SYNCING
        elif is_disconnected:
            result[STATUS_KEY] = FILE_SYNC_DISCONNECTED
        elif is_starting:
            self.file_sync_disabled = False
            result[STATUS_KEY] = FILE_SYNC_STARTING
        elif is_stopped:
            result[STATUS_KEY] = FILE_SYNC_STOPPED
        else:
            logger.warning('file_sync_status: unknown (got %r)', status)
            result[STATUS_KEY] = FILE_SYNC_UNKNOWN

        if self.file_sync_disabled:
            return STATUS_DISABLED
        else:
            return result

    def open_uri(self, uri):
        if self._credentials:
            parameters = {'next': uri}
            uri = self.sign_uri(UBUNTUONE_FROM_OAUTH, parameters)
        url = QtCore.QUrl()
        url.setEncodedUrl(uri)
        QtGui.QDesktopServices.openUrl(url)

    def sign_uri(self, uri, parameters=None):
        # Without credentials, return unsigned URL
        if not self._credentials:
            return uri
        if isinstance(uri, unicode):
            uri = bytes(iri2uri(uri))
        print "uri:", uri
        method = "GET"
        credentials = self._credentials
        consumer = oauth.OAuthConsumer(credentials["consumer_key"],
                                       credentials["consumer_secret"])
        token = oauth.OAuthToken(credentials["token"],
                                 credentials["token_secret"])
        if not parameters:
            _, _, _, _, query, _ = urlparse(uri)
            parameters = dict(cgi.parse_qsl(query))
        request = oauth.OAuthRequest.from_consumer_and_token(
                                            http_url=uri,
                                            http_method=method,
                                            parameters=parameters,
                                            oauth_consumer=consumer,
                                            token=token)
        sig_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
        request.sign_request(sig_method, consumer, token)
        print "SIGNED:", repr(request.to_url())
        return request.to_url()

    def get_quota(self):
        """Launch quota info request."""
        uri = self.sign_uri(QUOTA_API)
        url = QtCore.QUrl()
        url.setEncodedUrl(uri)
        self.nam.get(QtNetwork.QNetworkRequest(url))

    def humanize_quota(self):
        total = int(self._quota_info['total'])
        used = int(self._quota_info['used'])
        percent = (float(used) / total) * 100
        return "%d%% of %d GiB used" % (percent, total / (2 ** 30))


def main():
    app = QtGui.QApplication(sys.argv)
    mainloop = dbus.mainloop.qt.DBusQtMainLoop(set_as_default=True)
    icon = TrayIcon()
    icon.show()
    dbus.set_default_main_loop(mainloop)
    app.exec_()

if __name__ == "__main__":
    main()