File: downloadmanager.py

package info (click to toggle)
sugar-browse-activity 203-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 2,516 kB
  • sloc: python: 4,284; makefile: 11; xml: 10; sh: 6
file content (441 lines) | stat: -rw-r--r-- 15,685 bytes parent folder | download | duplicates (2)
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# Copyright (C) 2007, One Laptop Per Child
# Copyright (C) 2009, Tomeu Vizoso, Lucian Branescu
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import os
import logging
from gettext import gettext as _
import dbus
import cairo
import StringIO
import tempfile

from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import GObject
from gi.repository import Gio

from sugar3.datastore import datastore
from sugar3 import profile
from sugar3.graphics.alert import Alert, TimeoutAlert
from sugar3.graphics.icon import Icon
from sugar3.activity import activity

try:
    from sugar3.activity.activity import launch_bundle, get_bundle
    _HAS_BUNDLE_LAUNCHER = True
except ImportError:
    _HAS_BUNDLE_LAUNCHER = False


DS_DBUS_SERVICE = 'org.laptop.sugar.DataStore'
DS_DBUS_INTERFACE = 'org.laptop.sugar.DataStore'
DS_DBUS_PATH = '/org/laptop/sugar/DataStore'

_active_downloads = []
_dest_to_window = {}

PROGRESS_TIMEOUT = 3000
SPACE_THRESHOLD = 52428800  # 50 Mb


def format_float(f):
    return "%0.2f" % f


def can_quit():
    return len(_active_downloads) == 0


def num_downloads():
    return len(_active_downloads)


def remove_all_downloads():
    for download in _active_downloads:
        download.cancel()
        if download.dl_jobject is not None:
            datastore.delete(download.dl_jobject.object_id)
        download.cleanup()


def overall_downloads_progress():
    '''
    Returns the average progress of "all" the concurrent
    downloads running in background
    '''
    if len(_active_downloads) != 0:
        total_progress = 0.0
        for download in _active_downloads:
            total_progress += (download._progress / 100.0)
        return (total_progress / num_downloads())
    else:
        return 0.0


class Download(object):

    def __init__(self, webkit_download, activity):
        self._download = webkit_download
        self._activity = activity

        self._source = self._download.get_request().get_uri()
        logging.debug('START Download %s', self._source)

        self.datastore_deleted_handler = None

        self.dl_jobject = None
        self._object_id = None
        self._stop_alert = None

        self._dest_path = ''
        self._progress = 0
        self._last_update_progress = 0
        self._progress_sid = None

        self.temp_path = os.path.join(
            self._activity.get_activity_root(), 'instance')
        if not os.path.exists(self.temp_path):
            os.makedirs(self.temp_path)

        self._download.connect('failed', self.__download_failed_cb)
        self._download.connect('finished', self.__download_finished_cb)
        self._download.connect('received-data',
                               self.__download_received_data_cb)

        # Notify response is called before decide destination
        self._download.connect('notify::response', self.__notify_response_cb)
        self._download.connect('decide-destination',
                               self.__decide_destination_cb)
        self._download.connect('created-destination',
                               self.__created_destination_cb)

    def __notify_response_cb(self, download, pspec):
        logging.debug('__notify_response_cb')
        response = download.get_response()

        # Check free space and cancel the download if there is not enough.
        total_size = response.get_content_length()
        logging.debug('Total size of the file: %s', total_size)
        enough_space = self.enough_space(
            total_size, path=self.temp_path)
        if not enough_space:
            logging.debug('Download canceled because of Disk Space')
            self.cancel()

            self._canceled_alert = Alert()
            self._canceled_alert.props.title = _('Not enough space '
                                                 'to download')

            total_size_mb = total_size / 1024.0 ** 2
            free_space_mb = (self._free_available_space(
                path=self.temp_path) - SPACE_THRESHOLD) \
                / 1024.0 ** 2
            filename = response.get_suggested_filename()
            self._canceled_alert.props.msg = \
                _('Download "%{filename}" requires %{total_size_in_mb}'
                  ' MB of free space, only %{free_space_in_mb} MB'
                  ' is available' %
                  {'filename': filename,
                   'total_size_in_mb': format_float(total_size_mb),
                   'free_space_in_mb': format_float(free_space_mb)})
            ok_icon = Icon(icon_name='dialog-ok')
            self._canceled_alert.add_button(Gtk.ResponseType.OK,
                                            _('Ok'), ok_icon)
            ok_icon.show()
            self._canceled_alert.connect('response',
                                         self.__canceled_response_cb)
            self._activity.add_alert(self._canceled_alert)

    def __canceled_response_cb(self, alert, response_id):
        self._activity.remove_alert(alert)

    def __decide_destination_cb(self, download, suggested_filename):
        logging.debug('__decide_desintation_cb suggests %s',
                      suggested_filename)
        alert = TimeoutAlert(9)
        alert.props.title = _('Download started')
        alert.props.msg = suggested_filename
        self._activity.add_alert(alert)
        alert.connect('response', self.__start_response_cb)
        alert.show()

        self._suggested_filename = suggested_filename
        # figure out download URI
        self._dest_path = tempfile.mktemp(
            dir=self.temp_path, suffix=suggested_filename,
            prefix='tmp')
        logging.debug('Download destination path: %s' % self._dest_path)
        self._download.set_destination('file://' + self._dest_path)
        logging.error(self._download.get_destination)
        return True

    def __created_destination_cb(self, download, dest):
        logging.debug('__created_destination_cb at %s', dest)
        self._create_journal_object()
        self._object_id = self.dl_jobject.object_id

    def _update_progress(self):
        if self._progress > self._last_update_progress:
            self._last_update_progress = self._progress
            self.dl_jobject.metadata['progress'] = str(self._progress)
            datastore.write(self.dl_jobject)

        self._progress_sid = None
        return False

    def __download_received_data_cb(self, download, data_size):
        self._progress = int(self._download.get_estimated_progress() * 100)

        if self._progress_sid is None:
            self._progress_sid = GObject.timeout_add(
                PROGRESS_TIMEOUT, self._update_progress)

    def __download_finished_cb(self, download):
        if hasattr(self._activity, 'busy'):
            self._activity.unbusy()

        if self._progress_sid is not None:
            GObject.source_remove(self._progress_sid)

        if self.dl_jobject is None:
            return  # the "failed" signal was observed

        self.dl_jobject.metadata['title'] = self._suggested_filename
        self.dl_jobject.metadata['description'] = _('From: %s') \
            % self._source
        self.dl_jobject.metadata['progress'] = '100'
        self.dl_jobject.file_path = self._dest_path

        mime_type = Gio.content_type_guess(self._dest_path)[0]
        if mime_type != 'application/vnd.olpc-sugar':
            mime_type = download.get_response().get_mime_type()

        self.dl_jobject.metadata['mime_type'] = mime_type

        if mime_type in ('image/bmp', 'image/gif', 'image/jpeg',
                         'image/png', 'image/tiff'):
            preview = self._get_preview()
            if preview is not None:
                self.dl_jobject.metadata['preview'] = \
                    dbus.ByteArray(preview)

        datastore.write(self.dl_jobject,
                        transfer_ownership=True,
                        reply_handler=self.__internal_save_cb,
                        error_handler=self.__internal_error_cb,
                        timeout=360)

        self._stop_alert = Alert()
        self._stop_alert.props.title = _('Download completed')
        self._stop_alert.props.msg = self._suggested_filename

        bundle = None
        if _HAS_BUNDLE_LAUNCHER:
            bundle = get_bundle(object_id=self._object_id)

        if bundle is not None:
            icon = Icon(file=bundle.get_icon())
            label = _('Open with %s') % bundle.get_name()
            response_id = Gtk.ResponseType.APPLY
        else:
            icon = Icon(icon_name='zoom-activity')
            label = _('Show in Journal')
            response_id = Gtk.ResponseType.ACCEPT

        self._stop_alert.add_button(response_id, label, icon)
        icon.show()

        ok_icon = Icon(icon_name='dialog-ok')
        self._stop_alert.add_button(Gtk.ResponseType.OK, _('Ok'), ok_icon)
        ok_icon.show()

        self._activity.add_alert(self._stop_alert)
        self._stop_alert.connect('response', self.__stop_response_cb)
        self._stop_alert.show()

    def __download_failed_cb(self, download, error):
        logging.error('Error downloading URI due to %s'
                      % error)
        self.cleanup()

    def __internal_save_cb(self):
        logging.debug('Object saved succesfully to the datastore.')
        self.cleanup()

    def __internal_error_cb(self, err):
        logging.debug('Error saving activity object to datastore: %s' % err)
        self.cleanup()

    def __start_response_cb(self, alert, response_id):
        if response_id is Gtk.ResponseType.CANCEL:
            logging.debug('Download Canceled')
            self.cancel()
            try:
                datastore.delete(self._object_id)
            except Exception, e:
                logging.warning('Object has been deleted already %s' % e)

            self.cleanup()
            if self._stop_alert is not None:
                self._activity.remove_alert(self._stop_alert)

        self._activity.remove_alert(alert)

    def __stop_response_cb(self, alert, response_id):
        if response_id == Gtk.ResponseType.APPLY:
            launch_bundle(object_id=self._object_id)
        if response_id == Gtk.ResponseType.ACCEPT:
            activity.show_object_in_journal(self._object_id)
        self._activity.remove_alert(alert)

    def cleanup(self):
        global _active_downloads
        if self in _active_downloads:
            _active_downloads.remove(self)

        if self.datastore_deleted_handler is not None:
            self.datastore_deleted_handler.remove()
            self.datastore_deleted_handler = None

        if os.path.isfile(self._dest_path):
            os.remove(self._dest_path)

        if self.dl_jobject is not None:
            self.dl_jobject.destroy()
            self.dl_jobject = None

    def cancel(self):
        self._download.cancel()

    def enough_space(self, size, path='/'):
        """Check if there is enough (size) free space on path

        size -- free space requested in Bytes

        path -- device where the check will be done. For example: '/tmp'

        This method is useful to check the free space, for example,
        before starting a download from internet, creating a big map
        in some game or whatever action that needs some space in the
        Hard Disk.
        """

        free_space = self._free_available_space(path=path)
        return free_space - size > SPACE_THRESHOLD

    def _free_available_space(self, path='/'):
        """Return available space in Bytes

        This method returns the available free space in the 'path' and
        returns this amount in Bytes.
        """

        s = os.statvfs(path)
        return s.f_bavail * s.f_frsize

    def _create_journal_object(self):
        logging.debug('_create_journal_object')
        self.dl_jobject = datastore.create()
        filename = self._download.get_response().get_suggested_filename()
        self.dl_jobject.metadata['title'] = \
            _('Downloading %(filename)s from \n%(source)s.') % \
            {'filename': filename, 'source': self._source}

        self.dl_jobject.metadata['progress'] = '0'
        self.dl_jobject.metadata['keep'] = '0'
        self.dl_jobject.metadata['buddies'] = ''
        self.dl_jobject.metadata['preview'] = ''
        self.dl_jobject.metadata['icon-color'] = \
            profile.get_color().to_string()
        self.dl_jobject.metadata['mime_type'] = ''
        self.dl_jobject.file_path = self._dest_path
        datastore.write(self.dl_jobject)

        bus = dbus.SessionBus()
        obj = bus.get_object(DS_DBUS_SERVICE, DS_DBUS_PATH)
        datastore_dbus = dbus.Interface(obj, DS_DBUS_INTERFACE)
        self.datastore_deleted_handler = datastore_dbus.connect_to_signal(
            'Deleted', self.__datastore_deleted_cb,
            arg0=self.dl_jobject.object_id)

    def _get_preview(self):
        # This code borrows from sugar3.activity.Activity.get_preview
        # to make the preview with cairo, and also uses GdkPixbuf to
        # load any GdkPixbuf supported format.
        pixbuf = GdkPixbuf.Pixbuf.new_from_file(self._dest_path)
        image_width = pixbuf.get_width()
        image_height = pixbuf.get_height()

        preview_width, preview_height = activity.PREVIEW_SIZE
        preview_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                             preview_width, preview_height)
        cr = cairo.Context(preview_surface)

        scale_w = preview_width * 1.0 / image_width
        scale_h = preview_height * 1.0 / image_height
        scale = min(scale_w, scale_h)

        translate_x = int((preview_width - (image_width * scale)) / 2)
        translate_y = int((preview_height - (image_height * scale)) / 2)

        cr.translate(translate_x, translate_y)
        cr.scale(scale, scale)

        cr.set_source_rgba(1, 1, 1, 0)
        cr.set_operator(cairo.OPERATOR_SOURCE)
        cr.paint()
        Gdk.cairo_set_source_pixbuf(cr, pixbuf, 0, 0)
        cr.paint()

        preview_str = StringIO.StringIO()
        preview_surface.write_to_png(preview_str)
        return preview_str.getvalue()

    def __datastore_deleted_cb(self, uid):
        logging.debug('Downloaded entry has been deleted'
                      ' from the datastore: %r', uid)
        global _active_downloads
        if self in _active_downloads:
            self.cancel()
            self.cleanup()


_ignore_pdf_uris = []
_started_callbacks = []


def ignore_pdf(uri):
    _ignore_pdf_uris.append(uri)


def connect_download_started(callback):
    _started_callbacks.append(callback)


def add_download(webkit_download, activity):
    uri = webkit_download.get_request().get_uri()
    if uri in _ignore_pdf_uris:
        # The pdf viewer will handle this download`
        _ignore_pdf_uris.remove(uri)
        return

    download = Download(webkit_download, activity)
    _active_downloads.append(download)

    for cb in _started_callbacks:
        cb()