~ubuntu-branches/ubuntu/natty/ubuntuone-control-panel/natty

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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# -*- coding: utf-8 -*-

# Authors: Alejandro J. Cura <alecu@canonical.com>
# Authors: Natalia B. Bidart <nataliabidart@canonical.com>
#
# Copyright 2010 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Client to use other DBus services."""

import dbus.service
import ubuntu_sso

from twisted.internet import defer

from ubuntuone.clientdefs import APP_NAME
from ubuntuone.platform.linux import dbus_interface as sd_dbus_iface
from ubuntuone.platform.linux.tools import SyncDaemonTool

from ubuntuone.controlpanel.logger import setup_logging


logger = setup_logging('dbus_client')


class CredentialsError(Exception):
    """No credentials could be retrieved."""


class VolumesError(Exception):
    """An operation over a volume failed."""


def no_op(*a):
    """Do nothing"""


def get_sso_proxy():
    """Get a DBus proxy for credentials management."""
    bus = dbus.SessionBus()
    obj = bus.get_object(bus_name=ubuntu_sso.DBUS_BUS_NAME,
                         object_path=ubuntu_sso.DBUS_CREDENTIALS_PATH,
                         follow_name_owner_changes=True)
    proxy = dbus.Interface(object=obj,
                           dbus_interface=ubuntu_sso.DBUS_CREDENTIALS_IFACE)
    return proxy


def get_credentials():
    """Get the credentials from the ubuntu-sso-client."""
    d = defer.Deferred()
    proxy = get_sso_proxy()

    def found_credentials(app_name, creds):
        """Credentials have been found."""
        if app_name == APP_NAME:
            logger.info('credentials were found! (%r).', APP_NAME)
            d.callback(creds)

    def credentials_error(app_name, error_dict=None):
        """No credentials could be retrieved."""
        if app_name == APP_NAME:
            if error_dict is None:
                error_dict = {'error_message': 'Credentials were not found.',
                              'detailed_error': ''}

            logger.error('credentials error (%r, %r).', app_name, error_dict)
            error = CredentialsError(app_name, error_dict)
            d.errback(error)

    foundsig = proxy.connect_to_signal("CredentialsFound", found_credentials)
    notfoundsig = proxy.connect_to_signal("CredentialsNotFound",
                                          credentials_error)
    errorsig = proxy.connect_to_signal("CredentialsError", credentials_error)
    logger.debug('calling get_credentials.')
    proxy.find_credentials(APP_NAME, {'': ''},
                           reply_handler=no_op, error_handler=d.errback)

    def cleanup_signals(result):
        """Remove signals after use."""
        foundsig.remove()
        notfoundsig.remove()
        errorsig.remove()
        return result

    d.addBoth(cleanup_signals)
    return d


def clear_credentials():
    """Clear the credentials using the ubuntu-sso-client."""
    d = defer.Deferred()
    proxy = get_sso_proxy()

    def credentials_cleared(app_name):
        """Credentials have been cleared."""
        logger.debug('credentials were cleared for app_name %r.', app_name)
        if app_name == APP_NAME:
            logger.info('credentials were cleared! (%r).', APP_NAME)
            d.callback(app_name)

    def credentials_error(app_name, error_dict=None):
        """No credentials could be retrieved."""
        if app_name == APP_NAME:
            logger.error('credentials error (%r, %r).', app_name, error_dict)
            error = CredentialsError(app_name, error_dict)
            d.errback(error)

    clearedsig = proxy.connect_to_signal("CredentialsCleared",
                                         credentials_cleared)
    errorsig = proxy.connect_to_signal("CredentialsError", credentials_error)
    logger.warning('calling clear_credentials.')
    proxy.clear_credentials(APP_NAME, {'': ''},
                            reply_handler=no_op, error_handler=d.errback)

    def cleanup_signals(result):
        """Remove signals after use."""
        clearedsig.remove()
        errorsig.remove()
        return result

    d.addBoth(cleanup_signals)
    return d


def get_syncdaemon_proxy(object_path, dbus_interface):
    """Get a DBus proxy for syncdaemon at 'object_path':'dbus_interface'."""
    logger.debug('get_syncdaemon_proxy: object_path %r, dbus_interface %r',
                 object_path, dbus_interface)
    bus = dbus.SessionBus()
    obj = bus.get_object(bus_name=sd_dbus_iface.DBUS_IFACE_NAME,
                         object_path=object_path,
                         follow_name_owner_changes=True)
    proxy = dbus.Interface(object=obj, dbus_interface=dbus_interface)
    return proxy


def get_config_syncdaemon_proxy():
    """Get a DBus proxy for syncdaemon config calls."""
    return get_syncdaemon_proxy("/config",
                                sd_dbus_iface.DBUS_IFACE_CONFIG_NAME)


def get_folders_syncdaemon_proxy():
    """Get a DBus proxy for syncdaemon folders calls."""
    return get_syncdaemon_proxy("/folders",
                                sd_dbus_iface.DBUS_IFACE_FOLDERS_NAME)


def get_status_syncdaemon_proxy():
    """Get a DBus proxy for syncdaemon status calls."""
    return get_syncdaemon_proxy("/status",
                                sd_dbus_iface.DBUS_IFACE_STATUS_NAME)


def get_throttling_limits():
    """Get the speed limits from the syncdaemon."""
    d = defer.Deferred()
    proxy = get_config_syncdaemon_proxy()
    proxy.get_throttling_limits(reply_handler=d.callback,
                                error_handler=d.errback)
    return d


def set_throttling_limits(limits):
    """Set the speed limits on the syncdaemon."""
    d = defer.Deferred()
    proxy = get_config_syncdaemon_proxy()
    download = int(limits["download"])
    upload = int(limits["upload"])
    proxy.set_throttling_limits(download, upload,
                                reply_handler=lambda: d.callback("ok"),
                                error_handler=d.errback)
    return d


def bandwidth_throttling_enabled():
    """Get the state of throttling in the syncdaemon."""
    d = defer.Deferred()
    proxy = get_config_syncdaemon_proxy()
    proxy.bandwidth_throttling_enabled(reply_handler=d.callback,
                                       error_handler=d.errback)
    return d


def enable_bandwidth_throttling():
    """Enable the speed limits in the syncdaemon."""
    d = defer.Deferred()
    proxy = get_config_syncdaemon_proxy()
    proxy.enable_bandwidth_throttling(reply_handler=lambda: d.callback("ok"),
                                      error_handler=d.errback)
    return d


def disable_bandwidth_throttling():
    """Disable the speed limits in the syncdaemon."""
    d = defer.Deferred()
    proxy = get_config_syncdaemon_proxy()
    proxy.disable_bandwidth_throttling(reply_handler=lambda: d.callback("ok"),
                                       error_handler=d.errback)
    return d


def show_all_notifications_enabled():
    """Get the state of show_all_notifications in the syncdaemon."""
    d = defer.Deferred()
    proxy = get_config_syncdaemon_proxy()
    proxy.show_all_notifications_enabled(reply_handler=d.callback,
                                         error_handler=d.errback)
    return d


def enable_show_all_notifications():
    """Enable show_all_notifications in the syncdaemon."""
    d = defer.Deferred()
    proxy = get_config_syncdaemon_proxy()
    proxy.enable_show_all_notifications(reply_handler=lambda: d.callback("ok"),
                                        error_handler=d.errback)
    return d


def disable_show_all_notifications():
    """Disable show_all_notifications in the syncdaemon."""
    d = defer.Deferred()
    proxy = get_config_syncdaemon_proxy()
    handler = lambda: d.callback("ok")
    proxy.disable_show_all_notifications(reply_handler=handler,
                                         error_handler=d.errback)
    return d


def get_root_dir():
    """Retrieve the root information from syncdaemon."""
    d = defer.Deferred()
    proxy = get_syncdaemon_proxy("/", sd_dbus_iface.DBUS_IFACE_SYNC_NAME)
    proxy.get_rootdir(reply_handler=d.callback, error_handler=d.errback)
    return d


def get_shares_dir():
    """Retrieve the shares information from syncdaemon."""
    d = defer.Deferred()
    proxy = get_syncdaemon_proxy("/", sd_dbus_iface.DBUS_IFACE_SYNC_NAME)
    proxy.get_sharesdir(reply_handler=d.callback, error_handler=d.errback)
    return d


def get_shares_dir_link():
    """Retrieve the shares information from syncdaemon."""
    d = defer.Deferred()
    proxy = get_syncdaemon_proxy("/", sd_dbus_iface.DBUS_IFACE_SYNC_NAME)
    proxy.get_sharesdir_link(reply_handler=d.callback, error_handler=d.errback)
    return d


def get_folders():
    """Retrieve the folders information from syncdaemon."""
    d = defer.Deferred()
    proxy = get_folders_syncdaemon_proxy()
    proxy.get_folders(reply_handler=d.callback, error_handler=d.errback)
    return d


def create_folder(path):
    """Create a new folder through syncdaemon."""
    d = defer.Deferred()
    proxy = get_folders_syncdaemon_proxy()

    sig = proxy.connect_to_signal('FolderCreated', d.callback)
    cb = lambda path, error: d.errback(VolumesError(path, error))
    esig = proxy.connect_to_signal('FolderCreateError', cb)

    proxy.create(path, reply_handler=no_op, error_handler=d.errback)

    def cleanup_signals(result):
        """Remove signals after use."""
        sig.remove()
        esig.remove()
        return result

    d.addBoth(cleanup_signals)
    return d


def subscribe_folder(folder_id):
    """Subscribe to 'folder_id'."""
    d = defer.Deferred()
    proxy = get_folders_syncdaemon_proxy()

    sig = proxy.connect_to_signal('FolderSubscribed', d.callback)
    cb = lambda info, error: d.errback(VolumesError(info['id'], error))
    esig = proxy.connect_to_signal('FolderSubscribeError', cb)

    proxy.subscribe(folder_id, reply_handler=no_op, error_handler=no_op)

    def cleanup_signals(result):
        """Remove signals after use."""
        sig.remove()
        esig.remove()
        return result

    d.addBoth(cleanup_signals)
    return d


def unsubscribe_folder(folder_id):
    """Unsubscribe 'folder_id'."""
    d = defer.Deferred()
    proxy = get_folders_syncdaemon_proxy()

    sig = proxy.connect_to_signal('FolderUnSubscribed', d.callback)
    cb = lambda info, error: d.errback(VolumesError(info['id'], error))
    esig = proxy.connect_to_signal('FolderUnSubscribeError', cb)

    proxy.unsubscribe(folder_id, reply_handler=no_op, error_handler=no_op)

    def cleanup_signals(result):
        """Remove signals after use."""
        sig.remove()
        esig.remove()
        return result

    d.addBoth(cleanup_signals)
    return d


@defer.inlineCallbacks
def get_shares():
    """Retrieve the shares information from syncdaemon."""
    result = yield SyncDaemonTool(bus=dbus.SessionBus()).get_shares()
    defer.returnValue(result)


@defer.inlineCallbacks
def subscribe_share(share_id):
    """Subscribe to 'share_id'."""
    try:
        yield SyncDaemonTool(bus=dbus.SessionBus()).subscribe_share(share_id)
    except Exception, e:
        raise VolumesError(share_id, e)


@defer.inlineCallbacks
def unsubscribe_share(share_id):
    """Unsubscribe 'share_id'."""
    try:
        yield SyncDaemonTool(bus=dbus.SessionBus()).unsubscribe_share(share_id)
    except Exception, e:
        raise VolumesError(share_id, e)


def get_current_status():
    """Retrieve the current status from syncdaemon."""
    d = defer.Deferred()
    proxy = get_status_syncdaemon_proxy()
    proxy.current_status(reply_handler=d.callback, error_handler=d.errback)
    return d


def set_status_changed_handler(handler):
    """Connect 'handler' with syncdaemon's StatusChanged signal."""
    proxy = get_status_syncdaemon_proxy()
    sig = proxy.connect_to_signal('StatusChanged', handler)
    return proxy, sig


def files_sync_enabled():
    """Get if file sync service is enabled."""
    enabled = SyncDaemonTool(bus=None).is_files_sync_enabled()
    return defer.succeed(enabled)


@defer.inlineCallbacks
def set_files_sync_enabled(enabled):
    """Set the file sync service to be 'enabled'."""
    yield SyncDaemonTool(bus=dbus.SessionBus()).enable_files_sync(enabled)


@defer.inlineCallbacks
def connect_file_sync():
    """Connect the file sync service."""
    yield SyncDaemonTool(bus=dbus.SessionBus()).connect()


@defer.inlineCallbacks
def disconnect_file_sync():
    """Disconnect the file sync service."""
    yield SyncDaemonTool(bus=dbus.SessionBus()).disconnect()


@defer.inlineCallbacks
def start_file_sync():
    """Start the file sync service."""
    yield SyncDaemonTool(bus=dbus.SessionBus()).start()


@defer.inlineCallbacks
def stop_file_sync():
    """Stop the file sync service."""
    yield SyncDaemonTool(bus=dbus.SessionBus()).quit()