def create_journal_entry(self,  widget,  data=None):
     filename = self._filechooser.get_filename()
     journal_entry = datastore.create()
     journal_entry.metadata['title'] = self.make_new_filename(filename)
     journal_entry.metadata['title_set_by_user'] = '******'
     journal_entry.metadata['keep'] = '0'
     file_mimetype = mime.get_for_file(filename)
     if not file_mimetype is None:
         journal_entry.metadata['mime_type'] = file_mimetype
     journal_entry.metadata['buddies'] = ''
     if file_mimetype.startswith('image/')  and file_mimetype != 'image/vnd.djvu':
         preview = self.create_preview_metadata(filename)
     elif file_mimetype  == 'application/x-cbz':
         fname = self.extract_image(filename)
         preview = self.create_preview_metadata(fname)
         os.remove(fname)
     else:
         preview = ''
     if not preview  == '':
         journal_entry.metadata['preview'] =  dbus.ByteArray(preview)
     else:
         journal_entry.metadata['preview'] =  ''
         
     journal_entry.file_path = filename
     datastore.write(journal_entry)
     self.update_log_entries += '\n' + _('File %s copied to the Journal.') % filename
     self.alert(_('Success'),  _('%s added to Journal.') 
                 % self.make_new_filename(filename))
Esempio n. 2
0
    def __add_cover_response_cb(self, alert, response_id, operation_function):
        if response_id == Gtk.ResponseType.YES:
            try:
                chooser = ObjectChooser(self,
                                        what_filter='Image',
                                        filter_type=FILTER_TYPE_GENERIC_MIME,
                                        show_preview=True)
            except:
                # for compatibility with older versions
                chooser = ObjectChooser(self, what_filter='Image')

            try:
                result = chooser.run()
                if result == Gtk.ResponseType.ACCEPT:
                    logging.error('ObjectChooser: %r' %
                                  chooser.get_selected_object())
                    jobject = chooser.get_selected_object()
                    if jobject and jobject.file_path:
                        logging.error("imagen seleccionada: %s",
                                      jobject.file_path)
                        mime_type = mime.get_for_file(jobject.file_path)
                        extension = mime.get_primary_extension(mime_type)
                        tempfile_name = \
                            os.path.join(
                                self.get_activity_root(), 'instance',
                                'tmp%i.%s' % (time.time(), extension))
                        os.link(jobject.file_path, tempfile_name)
                        operation_function(tempfile_name)
            finally:
                chooser.destroy()
                del chooser

        elif response_id == Gtk.ResponseType.NO:
            self._save_epub()
        self.remove_alert(alert)
Esempio n. 3
0
    def create_journal_entry(self, widget, data=None):
        filename = self._filechooser.get_filename()
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = self.make_new_filename(filename)
        journal_entry.metadata['title_set_by_user'] = '******'
        journal_entry.metadata['keep'] = '0'
        file_mimetype = mime.get_for_file(filename)
        if not file_mimetype is None:
            journal_entry.metadata['mime_type'] = file_mimetype
        journal_entry.metadata['buddies'] = ''
        if file_mimetype.startswith(
                'image/') and file_mimetype != 'image/vnd.djvu':
            preview = self.create_preview_metadata(filename)
        elif file_mimetype == 'application/x-cbz':
            fname = self.extract_image(filename)
            preview = self.create_preview_metadata(fname)
            os.remove(fname)
        else:
            preview = ''
        if not preview == '':
            journal_entry.metadata['preview'] = dbus.ByteArray(preview)
        else:
            journal_entry.metadata['preview'] = ''

        journal_entry.file_path = filename
        datastore.write(journal_entry)
        self.update_log_entries += '\n' + _(
            'File %s copied to the Journal.') % filename
        self.alert(
            _('Success'),
            _('%s added to Journal.') % self.make_new_filename(filename))
Esempio n. 4
0
def is_file_encrypted(filepath):
    if DISABLE_SECURITY is True:
        return False

    filepath = filepath.replace('file://', '')
    mimebook = mime.get_for_file(filepath)
    return (mimebook == 'application/x-ceibal')
    def load_file(self, jobject, title=None):
        if isinstance(jobject, datastore.RawObject):
            logging.debug('Loading a datastore.RawObject')
            file_path = mime_path = jobject.file_path
            title = jobject.metadata['title']
        elif isinstance(jobject, datastore.DSObject):
            # This file is stored in the Journal (datastore)
            logging.debug('Loading a datastore.DSObject')
            file_path = 'journal://' + jobject.object_id
            mime_path = datastore.get(jobject.object_id).file_path
            title = jobject.metadata['title']
        else:
            logging.debug('Loading a %s', type(jobject))
            file_path = mime_path = jobject

        mimetype = mime.get_for_file('file://' + mime_path)
        logging.info('read_file mime %s', mimetype)
        if mimetype == 'audio/x-mpegurl':
            # is a M3U playlist:
            self._load_m3u_playlist(file_path)
        else:
            # is not a M3U playlist
            self._load_stream(file_path, title)

        missing_tracks = self._get_missing_tracks()
        if len(missing_tracks) > 0:
            logging.info('%s tracks not found', len(missing_tracks))
            self.emit('missing-tracks', missing_tracks)

        # set the focus in the first row
        self._set_cursor(0)
Esempio n. 6
0
    def load_file(self, jobject, title=None):
        if isinstance(jobject, datastore.RawObject):
            logging.debug('Loading a datastore.RawObject')
            file_path = mime_path = jobject.file_path
            title = jobject.metadata['title']
        elif isinstance(jobject, datastore.DSObject):
            # This file is stored in the Journal (datastore)
            logging.debug('Loading a datastore.DSObject')
            file_path = 'journal://' + jobject.object_id
            mime_path = datastore.get(jobject.object_id).file_path
            title = jobject.metadata['title']
        else:
            logging.debug('Loading a %s', type(jobject))
            file_path = mime_path = jobject

        mimetype = mime.get_for_file('file://' + mime_path)
        logging.info('read_file mime %s', mimetype)
        if mimetype == 'audio/x-mpegurl':
            # is a M3U playlist:
            self._load_m3u_playlist(file_path)
        else:
            # is not a M3U playlist
            self._load_stream(file_path, title)

        missing_tracks = self._get_missing_tracks()
        if len(missing_tracks) > 0:
            logging.info('%s tracks not found', len(missing_tracks))
            self.emit('missing-tracks', missing_tracks)

        # set the focus in the first row
        self._set_cursor(0)
Esempio n. 7
0
    def __add_cover_response_cb(self, alert, response_id, operation_function):
        if response_id == Gtk.ResponseType.YES:
            try:
                chooser = ObjectChooser(self, what_filter='Image',
                                        filter_type=FILTER_TYPE_GENERIC_MIME,
                                        show_preview=True)
            except:
                # for compatibility with older versions
                chooser = ObjectChooser(self, what_filter='Image')

            try:
                result = chooser.run()
                if result == Gtk.ResponseType.ACCEPT:
                    logging.error('ObjectChooser: %r' %
                                  chooser.get_selected_object())
                    jobject = chooser.get_selected_object()
                    if jobject and jobject.file_path:
                        logging.error("imagen seleccionada: %s",
                                      jobject.file_path)
                        mime_type = mime.get_for_file(jobject.file_path)
                        extension = mime.get_primary_extension(mime_type)
                        tempfile_name = \
                            os.path.join(
                                self.get_activity_root(), 'instance',
                                'tmp%i.%s' % (time.time(), extension))
                        os.link(jobject.file_path, tempfile_name)
                        operation_function(tempfile_name)
            finally:
                chooser.destroy()
                del chooser

        elif response_id == Gtk.ResponseType.NO:
            self._save_epub()
        self.remove_alert(alert)
Esempio n. 8
0
    def _copy_to_journal(self):
        formats = list(self._cb_object.get_formats().keys())
        most_significant_mime_type = mime.choose_most_significant(formats)
        format_ = self._cb_object.get_formats()[most_significant_mime_type]

        transfer_ownership = False
        if most_significant_mime_type == 'text/uri-list':
            uri = format_.get_data()
            if uri.startswith('file://'):
                parsed_url = urllib.parse.urlparse(uri)
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                mime_type = 'text/uri-list'
        else:
            if format_.is_on_disk():
                parsed_url = urllib.parse.urlparse(format_.get_data())
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                sniffed_mime_type = mime.get_for_file(file_path)
                if sniffed_mime_type == 'application/octet-stream':
                    mime_type = most_significant_mime_type
                else:
                    mime_type = sniffed_mime_type

        jobject = datastore.create()
        jobject.metadata['title'] = self._cb_object.get_name()
        jobject.metadata['keep'] = '0'
        jobject.metadata['buddies'] = ''
        jobject.metadata['preview'] = ''
        settings = Gio.Settings.new('org.sugarlabs.user')
        color = settings.get_string('color')
        jobject.metadata['icon-color'] = color
        jobject.metadata['mime_type'] = mime_type
        jobject.file_path = file_path

        datastore.write(jobject, transfer_ownership=transfer_ownership)

        return jobject
Esempio n. 9
0
    def _copy_to_journal(self):
        formats = self._cb_object.get_formats().keys()
        most_significant_mime_type = mime.choose_most_significant(formats)
        format_ = self._cb_object.get_formats()[most_significant_mime_type]

        transfer_ownership = False
        if most_significant_mime_type == 'text/uri-list':
            uris = mime.split_uri_list(format_.get_data())
            if len(uris) == 1 and uris[0].startswith('file://'):
                parsed_url = urlparse.urlparse(uris[0])
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                mime_type = 'text/uri-list'
        else:
            if format_.is_on_disk():
                parsed_url = urlparse.urlparse(format_.get_data())
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                sniffed_mime_type = mime.get_for_file(file_path)
                if sniffed_mime_type == 'application/octet-stream':
                    mime_type = most_significant_mime_type
                else:
                    mime_type = sniffed_mime_type

        jobject = datastore.create()
        jobject.metadata['title'] = self._cb_object.get_name()
        jobject.metadata['keep'] = '0'
        jobject.metadata['buddies'] = ''
        jobject.metadata['preview'] = ''
        client = GConf.Client.get_default()
        color = client.get_string('/desktop/sugar/user/color')
        jobject.metadata['icon-color'] = color
        jobject.metadata['mime_type'] = mime_type
        jobject.file_path = file_path

        datastore.write(jobject, transfer_ownership=transfer_ownership)

        return jobject
Esempio n. 10
0
    def _copy_to_journal(self):
        formats = self._cb_object.get_formats().keys()
        most_significant_mime_type = mime.choose_most_significant(formats)
        format_ = self._cb_object.get_formats()[most_significant_mime_type]

        transfer_ownership = False
        if most_significant_mime_type == 'text/uri-list':
            uris = mime.split_uri_list(format_.get_data())
            if len(uris) == 1 and uris[0].startswith('file://'):
                parsed_url = urlparse.urlparse(uris[0])
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                mime_type = 'text/uri-list'
        else:
            if format_.is_on_disk():
                parsed_url = urlparse.urlparse(format_.get_data())
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                sniffed_mime_type = mime.get_for_file(file_path)
                if sniffed_mime_type == 'application/octet-stream':
                    mime_type = most_significant_mime_type
                else:
                    mime_type = sniffed_mime_type

        jobject = datastore.create()
        jobject.metadata['title'] = self._cb_object.get_name()
        jobject.metadata['keep'] = '0'
        jobject.metadata['buddies'] = ''
        jobject.metadata['preview'] = ''
        client = GConf.Client.get_default()
        color = client.get_string('/desktop/sugar/user/color')
        jobject.metadata['icon-color'] = color
        jobject.metadata['mime_type'] = mime_type
        jobject.file_path = file_path

        datastore.write(jobject, transfer_ownership=transfer_ownership)

        return jobject
Esempio n. 11
0
    def _copy_to_journal(self):
        formats = self._cb_object.get_formats().keys()
        most_significant_mime_type = mime.choose_most_significant(formats)
        format_ = self._cb_object.get_formats()[most_significant_mime_type]

        transfer_ownership = False
        if most_significant_mime_type == 'text/uri-list':
            uri = format_.get_data()
            if uri.startswith('file://'):
                parsed_url = urlparse.urlparse(uri)
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                mime_type = 'text/uri-list'
        else:
            if format_.is_on_disk():
                parsed_url = urlparse.urlparse(format_.get_data())
                file_path = parsed_url.path  # pylint: disable=E1101
                transfer_ownership = False
                mime_type = mime.get_for_file(file_path)
            else:
                file_path = self._write_to_temp_file(format_.get_data())
                transfer_ownership = True
                sniffed_mime_type = mime.get_for_file(file_path)
                if sniffed_mime_type == 'application/octet-stream':
                    mime_type = most_significant_mime_type
                else:
                    mime_type = sniffed_mime_type

        jobject = datastore.create()
        jobject.metadata['title'] = self._cb_object.get_name()
        jobject.metadata['keep'] = '0'
        jobject.metadata['buddies'] = ''
        jobject.metadata['preview'] = ''
        settings = Gio.Settings('org.sugarlabs.user')
        color = settings.get_string('color')
        jobject.metadata['icon-color'] = color
        jobject.metadata['mime_type'] = mime_type
        jobject.file_path = file_path

        datastore.write(jobject, transfer_ownership=transfer_ownership)

        return jobject
    def load_files(self, dir, col):

        for path, dirnames, filenames in os.walk(dir, True):

            if dir == '/home/olpc':
                f = open('olpc.files', 'r')
                for line in f:
                    line = line.strip()
                    if line in dirnames:
                        dirnames.remove(line)
                f.close()

            else:
                f = open('media.files', 'r')
                for line in f:
                    line = line.strip()
                    if line in dirnames:
                        dirnames.remove(line)
                f.close()

            for filename in filenames:
                file_name = os.path.join(path, filename)
                #remove hidden file_nameexcept for readonly
                pos = str.find(file_name, '/.')
                if col == 3: pos = -1
                name = str.find(file_name, 'Cache')

                if ((pos == -1)
                        or name > 0) and not (os.path.islink(file_name)):
                    if self.num > max_file: return
                    try:
                        file_mimetype = mime.get_for_file(
                            os.path.join(path, filename))
                        if (file_mimetype.startswith('image/')):
                            #or (file_mimetype.startswith('video/')):
                            #check for new files
                            self.num += 1
                            mtime = os.path.getmtime(file_name)
                            iter = self.ls_journal[col].append()
                            jobject_wrapper = JobjectWrapper()
                            jobject_wrapper.set_file_path(
                                os.path.join(path, filename))
                            jobject_wrapper.set_object_id(file_name)
                            jobject_wrapper.set_title(filename)
                            jobject_wrapper.set_mime_type(file_mimetype)
                            jobject_wrapper.set_timestamp(mtime)
                            jobject_wrapper.set_description(file_name)
                            self.ls_journal[col].set(iter, COLUMN_TITLE,
                                                     filename)
                            self.ls_journal[col].set(iter, COLUMN_MTIME,
                                                     str(mtime))
                            self.ls_journal[col].set(iter, COLUMN_JOBJECT,
                                                     jobject_wrapper)
                    except IOError:
                        print 'No mimetype for : %s' % (file_name)
Esempio n. 13
0
    def create_preview_metadata(self,  filename):

        file_mimetype = mime.get_for_file(filename)
        if not file_mimetype.startswith('image/'):
            return ''
            
        scaled_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(filename,
                                                              style.zoom(320), style.zoom(240))
        preview_data = []

        succes, preview_data = scaled_pixbuf.save_to_bufferv('png', [], [])
        preview_data = ''.join(preview_data)

        return preview_data
    def __state_change_cb(self, download, gparamspec):
        state = self._download.get_status()
        if state == WebKit.DownloadStatus.STARTED:
            self._create_journal_object()
            self._object_id = self.dl_jobject.object_id

            alert = TimeoutAlert(9)
            alert.props.title = _('Download started')
            alert.props.msg = _('%s' % self._download.get_suggested_filename())
            self._activity.add_alert(alert)
            alert.connect('response', self.__start_response_cb)
            alert.show()
            global _active_downloads
            _active_downloads.append(self)

        elif state == WebKit.DownloadStatus.FINISHED:
            self._stop_alert = Alert()
            self._stop_alert.props.title = _('Download completed')
            self._stop_alert.props.msg = \
                _('%s' % self._download.get_suggested_filename())
            open_icon = Icon(icon_name='zoom-activity')
            self._stop_alert.add_button(Gtk.ResponseType.APPLY,
                                        _('Show in Journal'), open_icon)
            open_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()

            self.dl_jobject.metadata['title'] = \
                self._download.get_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

            # sniff for a mime type, no way to get headers from WebKit
            sniffed_mime_type = mime.get_for_file(self._dest_path)
            self.dl_jobject.metadata['mime_type'] = sniffed_mime_type

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

        elif state == WebKit.DownloadStatus.CANCELLED:
            self.cleanup()
Esempio n. 15
0
    def create_preview_metadata(self, filename):

        file_mimetype = mime.get_for_file(filename)
        if not file_mimetype.startswith('image/'):
            return ''

        scaled_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            filename, style.zoom(320), style.zoom(240))
        preview_data = []

        succes, preview_data = scaled_pixbuf.save_to_bufferv('png', [], [])
        preview_data = ''.join(preview_data)

        return preview_data
    def __player_error_cb(self, widget, message, detail):
        self.player.stop()
        self.control.set_disabled()

        logging.error('ERROR MESSAGE: %s', message)
        logging.error('ERROR DETAIL: %s', detail)

        file_path = self.playlist_widget._items[
            self.playlist_widget.get_current_playing()]['path']
        mimetype = mime.get_for_file(file_path)

        title = _('Error')
        msg = _('This "%s" file can\'t be played') % mimetype
        self._switch_canvas(False)
        self._show_error_alert(title, msg)
Esempio n. 17
0
    def __player_error_cb(self, widget, message, detail):
        self.player.stop()
        self.control.set_disabled()

        logging.error('ERROR MESSAGE: %s', message)
        logging.error('ERROR DETAIL: %s', detail)

        file_path = self.playlist_widget._items[
            self.playlist_widget.get_current_playing()]['path']
        mimetype = mime.get_for_file(file_path)

        title = _('Error')
        msg = _('This "%s" file can\'t be played') % mimetype
        self._switch_canvas(False)
        self._show_error_alert(title, msg)
Esempio n. 18
0
    def _copy_file(original_uri):
        uri = urllib.parse.urlparse(original_uri)
        path = uri.path  # pylint: disable=E1101
        directory_, file_name = os.path.split(path)

        root, ext = os.path.splitext(file_name)
        if not ext or ext == '.':
            mime_type = mime.get_for_file(path)
            ext = '.' + mime.get_primary_extension(mime_type)

        f_, new_file_path = tempfile.mkstemp(ext, root)
        del f_
        shutil.copyfile(path, new_file_path)
        os.chmod(new_file_path, 0o644)

        return 'file://' + new_file_path
Esempio n. 19
0
 def _guess_mime(self, file_name):
     logging.error('_guess_mime %s', file_name)
     mime_type = None
     if file_name.endswith('.html') or file_name.endswith('.htm'):
         mime_type = 'application/xhtml+xml'
     elif file_name.endswith('.css'):
         mime_type = 'text/css'
     elif file_name.endswith('.png'):
         mime_type = 'image/png'
     elif file_name.endswith('.jpg') or file_name.endswith('.jpeg'):
         mime_type = 'image/jpeg'
     elif file_name.endswith('.gif'):
         mime_type = 'image/gif'
     if mime is None:
         mime_type = mime.get_for_file(file_name)
     return mime_type
Esempio n. 20
0
    def _copy_file(self, original_uri):
        uri = urlparse.urlparse(original_uri)
        path = uri.path  # pylint: disable=E1101
        directory_, file_name = os.path.split(path)

        root, ext = os.path.splitext(file_name)
        if not ext or ext == '.':
            mime_type = mime.get_for_file(path)
            ext = '.' + mime.get_primary_extension(mime_type)

        f_, new_file_path = tempfile.mkstemp(ext, root)
        del f_
        shutil.copyfile(path, new_file_path)
        os.chmod(new_file_path, 0644)

        return 'file://' + new_file_path
 def _guess_mime(self, file_name):
     logging.error('_guess_mime %s', file_name)
     mime_type = None
     if file_name.endswith('.html') or file_name.endswith('.htm'):
         mime_type = 'application/xhtml+xml'
     elif file_name.endswith('.css'):
         mime_type = 'text/css'
     elif file_name.endswith('.png'):
         mime_type = 'image/png'
     elif file_name.endswith('.jpg') or file_name.endswith('.jpeg'):
         mime_type = 'image/jpeg'
     elif file_name.endswith('.gif'):
         mime_type = 'image/gif'
     if mime is None:
         mime_type = mime.get_for_file(file_name)
     return mime_type
Esempio n. 22
0
 def update_preview_cb(self, file_chooser, preview):
     filename = file_chooser.get_preview_filename()
     try:
         file_mimetype = mime.get_for_file(filename)
         if file_mimetype  == 'application/x-cbz' or file_mimetype == 'application/zip':
             fname = self.extract_image(filename)
             pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(fname, 
                 style.zoom(320), style.zoom(240))
             preview.set_from_pixbuf(pixbuf)
             have_preview = True
             os.remove(fname)
         else:
             have_preview = False
     except:
         have_preview = False
     file_chooser.set_preview_widget_active(have_preview)
     return
Esempio n. 23
0
    def __friend_selected_cb(self, menu_item, buddy):
        logging.debug("__friend_selected_cb")
        file_name = model.get_file(self._metadata["uid"])

        if not file_name or not os.path.exists(file_name):
            logging.warn("Entries without a file cannot be sent.")
            self.emit("volume-error", _("Entries without a file cannot be sent."), _("Warning"))
            return

        title = str(self._metadata["title"])
        description = str(self._metadata.get("description", ""))
        mime_type = str(self._metadata["mime_type"])

        if not mime_type:
            mime_type = mime.get_for_file(file_name)

        filetransfer.start_transfer(buddy, file_name, title, description, mime_type)
Esempio n. 24
0
    def __keep_in_journal_cb(self, menu_item):
        mime_type = mime.get_from_file_name(self._document_path)
        if mime_type == 'application/octet-stream':
            mime_type = mime.get_for_file(self._document_path)

        self._jobject = datastore.create()
        title = _('Source') + ': ' + self._title
        self._jobject.metadata['title'] = title
        self._jobject.metadata['keep'] = '0'
        self._jobject.metadata['buddies'] = ''
        self._jobject.metadata['preview'] = ''
        self._jobject.metadata['icon-color'] = self._color
        self._jobject.metadata['mime_type'] = mime_type
        self._jobject.metadata['source'] = '1'
        self._jobject.file_path = self._document_path
        datastore.write(self._jobject, transfer_ownership=True,
                        reply_handler=self.__internal_save_cb,
                        error_handler=self.__internal_save_error_cb)
Esempio n. 25
0
    def get_mime_type(self):
        if not self._formats:
            return ''

        format_ = mime.choose_most_significant(self._formats.keys())
        if format_ == 'text/uri-list':
            uri_data = self._formats[format_].get_data()
            uri = urlparse.urlparse(uri_data, 'file')
            scheme = uri.scheme  # pylint: disable=E1101
            if scheme == 'file':
                path = uri.path  # pylint: disable=E1101
                if os.path.exists(path):
                    format_ = mime.get_for_file(path)
                else:
                    format_ = mime.get_from_file_name(path)
                logging.debug('Chose %r!', format_)

        return format_
Esempio n. 26
0
    def __keep_in_journal_cb(self, menu_item):
        mime_type = mime.get_from_file_name(self._document_path)
        if mime_type == 'application/octet-stream':
            mime_type = mime.get_for_file(self._document_path)

        self._jobject = datastore.create()
        title = _('Source') + ': ' + self._title
        self._jobject.metadata['title'] = title
        self._jobject.metadata['keep'] = '0'
        self._jobject.metadata['buddies'] = ''
        self._jobject.metadata['preview'] = ''
        self._jobject.metadata['icon-color'] = self._color
        self._jobject.metadata['mime_type'] = mime_type
        self._jobject.metadata['source'] = '1'
        self._jobject.file_path = self._document_path
        datastore.write(self._jobject, transfer_ownership=True,
                        reply_handler=self.__internal_save_cb,
                        error_handler=self.__internal_save_error_cb)
Esempio n. 27
0
    def _set_file_path(self, file_path):
        self._file_path = file_path

        if self._file_path is None:
            self._show_no_file()
            return

        mime_type = mime.get_for_file(self._file_path)
        if 'image/' in mime_type:
            self._show_image_viewer(image=True)
        elif 'audio/' in mime_type:
            self._show_image_viewer(icon='audio-x-generic')
        elif 'video/' in mime_type:
            self._show_image_viewer(icon='video-x-generic')
        else:
            response = self._show_text_viewer()
            if not response:
                self._show_image_viewer(icon='application-x-generic')
Esempio n. 28
0
    def _set_file_path(self, file_path):
        self._file_path = file_path

        if self._file_path is None:
            self._show_no_file()
            return

        mime_type = mime.get_for_file(self._file_path)
        if 'image/' in mime_type:
            self._show_image_viewer(image=True)
        elif 'audio/' in mime_type:
            self._show_image_viewer(icon='audio-x-generic')
        elif 'video/' in mime_type:
            self._show_image_viewer(icon='video-x-generic')
        else:
            response = self._show_text_viewer()
            if not response:
                self._show_image_viewer(icon='application-x-generic')
Esempio n. 29
0
    def get_mime_type(self):
        if not self._formats:
            return ''

        format_ = mime.choose_most_significant(self._formats.keys())
        if format_ == 'text/uri-list':
            data = self._formats['text/uri-list'].get_data()
            uri = urlparse.urlparse(mime.split_uri_list(data)[0], 'file')
            scheme = uri.scheme  # pylint: disable=E1101
            if scheme == 'file':
                path = uri.path  # pylint: disable=E1101
                if os.path.exists(path):
                    format_ = mime.get_for_file(path)
                else:
                    format_ = mime.get_from_file_name(path)
                logging.debug('Chose %r!', format_)

        return format_
Esempio n. 30
0
    def __friend_selected_cb(self, menu_item, buddy):
        logging.debug('__friend_selected_cb')
        file_name = model.get_file(self._metadata['uid'])

        if not file_name or not os.path.exists(file_name):
            logging.warn('Entries without a file cannot be sent.')
            self.emit('volume-error',
                      _('Entries without a file cannot be sent.'),
                      _('Warning'))
            return

        title = str(self._metadata['title'])
        description = str(self._metadata.get('description', ''))
        mime_type = str(self._metadata['mime_type'])

        if not mime_type:
            mime_type = mime.get_for_file(file_name)

        filetransfer.start_transfer(buddy, file_name, title, description,
                                    mime_type)
Esempio n. 31
0
    def __friend_selected_cb(self, menu_item, buddy):
        logging.debug('__friend_selected_cb')
        file_name = model.get_file(self._metadata['uid'])

        if not file_name or not os.path.exists(file_name):
            logging.warn('Entries without a file cannot be sent.')
            self.emit('volume-error',
                      _('Entries without a file cannot be sent.'),
                      _('Warning'))
            return

        title = str(self._metadata['title'])
        description = str(self._metadata.get('description', ''))
        mime_type = str(self._metadata['mime_type'])

        if not mime_type:
            mime_type = mime.get_for_file(file_name)

        filetransfer.start_transfer(buddy, file_name, title, description,
                                    mime_type)
Esempio n. 32
0
    def _show_text_viewer(self):
        source_buffer = GtkSource.Buffer()
        source_buffer.set_highlight_syntax(True)

        source_view = GtkSource.View(buffer=source_buffer)
        source_view.set_editable(False)
        source_view.set_cursor_visible(True)
        source_view.set_show_line_numbers(True)
        source_view.set_show_right_margin(True)
        source_view.set_right_margin_position(80)
        source_view.modify_font(_SOURCE_FONT)
        # source_view.set_highlight_current_line(True) #FIXME: Ugly color

        mime_type = mime.get_for_file(self._file_path)

        _logger.debug('Detected mime type: %r', mime_type)

        language_manager = GtkSource.LanguageManager.get_default()
        detected_language = None
        for language_id in language_manager.get_language_ids():
            language = language_manager.get_language(language_id)
            if mime_type in language.get_mime_types():
                detected_language = language
                break

        if detected_language is not None:
            _logger.debug('Detected language: %r',
                          detected_language.get_name())

        source_buffer.set_language(detected_language)
        text = open(self._file_path, 'r').read()
        try:
            text.encode()
            source_buffer.set_text(text)
        except UnicodeDecodeError:
            return False

        source_view.show()
        self._replace(source_view)

        return True
Esempio n. 33
0
    def _show_text_viewer(self):
        source_buffer = GtkSource.Buffer()
        source_buffer.set_highlight_syntax(True)

        source_view = GtkSource.View(buffer=source_buffer)
        source_view.set_editable(False)
        source_view.set_cursor_visible(True)
        source_view.set_show_line_numbers(True)
        source_view.set_show_right_margin(True)
        source_view.set_right_margin_position(80)
        source_view.modify_font(_SOURCE_FONT)
        # source_view.set_highlight_current_line(True) #FIXME: Ugly color

        mime_type = mime.get_for_file(self._file_path)

        _logger.debug('Detected mime type: %r', mime_type)

        language_manager = GtkSource.LanguageManager.get_default()
        detected_language = None
        for language_id in language_manager.get_language_ids():
            language = language_manager.get_language(language_id)
            if mime_type in language.get_mime_types():
                detected_language = language
                break

        if detected_language is not None:
            _logger.debug('Detected language: %r',
                          detected_language.get_name())

        source_buffer.set_language(detected_language)
        text = open(self._file_path, 'r').read()
        works = True
        try:
            text.encode()
            source_buffer.set_text(text)
            self._box.pack_start(source_view, True, True, 0)
            self._box.show_all()
        except UnicodeDecodeError:
            works = False

        return works
Esempio n. 34
0
    def __keep_in_journal_cb(self, menu_item):
        mime_type = mime.get_from_file_name(self._document_path)
        if mime_type == "application/octet-stream":
            mime_type = mime.get_for_file(self._document_path)

        self._jobject = datastore.create()
        title = _("Source") + ": " + self._title
        self._jobject.metadata["title"] = title
        self._jobject.metadata["keep"] = "0"
        self._jobject.metadata["buddies"] = ""
        self._jobject.metadata["preview"] = ""
        self._jobject.metadata["icon-color"] = self._color
        self._jobject.metadata["mime_type"] = mime_type
        self._jobject.metadata["source"] = "1"
        self._jobject.file_path = self._document_path
        datastore.write(
            self._jobject,
            transfer_ownership=True,
            reply_handler=self.__internal_save_cb,
            error_handler=self.__internal_save_error_cb,
        )
Esempio n. 35
0
    def load_document(self, file_path):

        file_name = file_path.replace('file://', '')
        mimetype = mime.get_for_file(file_path)
        if mimetype == 'application/zip':
            logging.error('opening zip file')
            self.zf = zipfile.ZipFile(file_path.replace('file://', ''), 'r')
            self.book_files = self.zf.namelist()
            extract_path = os.path.join(self._activity.get_activity_root(),
                                        'instance')
            for book_file in self.book_files:
                if (book_file != 'annotations.pkl'):
                    self.zf.extract(book_file, extract_path)
                    file_name = os.path.join(extract_path, book_file)

        logging.error('opening file_name %s' % file_name)
        self._etext_file = open(file_name, 'r')

        self.page_index = [0]
        pagecount = 0
        linecount = 0
        while self._etext_file:
            line = self._etext_file.readline()
            if not line:
                break
            line_increment = (len(line) / 80) + 1
            linecount = linecount + line_increment
            if linecount >= PAGE_SIZE:
                position = self._etext_file.tell()
                self.page_index.append(position)
                linecount = 0
                pagecount = pagecount + 1
        self._pagecount = pagecount + 1
        self.set_current_page(0)
        self._scrollbar.set_range(1.0, self._pagecount - 1.0)
        self._scrollbar.set_increments(1.0, 1.0)

        speech.highlight_cb = self.highlight_next_word
        speech.reset_cb = self.reset_text_to_speech
Esempio n. 36
0
    def load_document(self, file_path):

        file_name = file_path.replace('file://', '')
        mimetype = mime.get_for_file(file_path)
        if mimetype == 'application/zip':
            logging.error('opening zip file')
            self.zf = zipfile.ZipFile(file_path.replace('file://', ''), 'r')
            self.book_files = self.zf.namelist()
            extract_path = os.path.join(self._activity.get_activity_root(),
                                        'instance')
            for book_file in self.book_files:
                if (book_file != 'annotations.pkl'):
                    self.zf.extract(book_file, extract_path)
                    file_name = os.path.join(extract_path, book_file)

        logging.error('opening file_name %s' % file_name)
        self._etext_file = open(file_name, 'r')

        self.page_index = [0]
        pagecount = 0
        linecount = 0
        while self._etext_file:
            line = self._etext_file.readline()
            if not line:
                break
            line_increment = (len(line) / 80) + 1
            linecount = linecount + line_increment
            if linecount >= PAGE_SIZE:
                position = self._etext_file.tell()
                self.page_index.append(position)
                linecount = 0
                pagecount = pagecount + 1
        self._pagecount = pagecount + 1
        self.set_current_page(0)
        self._scrollbar.set_range(1.0, self._pagecount - 1.0)
        self._scrollbar.set_increments(1.0, 1.0)

        speech.highlight_cb = self.highlight_next_word
        speech.reset_cb = self.reset_text_to_speech
Esempio n. 37
0
    def _set_file_path(self, file_path):
        self._file_path = file_path

        if self._file_path is None:
            self._buffer.set_text("")
            return

        mime_type = mime.get_for_file(self._file_path)
        _logger.debug("Detected mime type: %r", mime_type)

        language_manager = GtkSource.LanguageManager.get_default()
        detected_language = None
        for language_id in language_manager.get_language_ids():
            language = language_manager.get_language(language_id)
            if mime_type in language.get_mime_types():
                detected_language = language
                break

        if detected_language is not None:
            _logger.debug("Detected language: %r", detected_language.get_name())

        self._buffer.set_language(detected_language)
        self._buffer.set_text(open(self._file_path, "r").read())
Esempio n. 38
0
    def _add_selection(self, object_id, selection):
        if not selection.get_data():
            return

        selection_data = selection.get_data()

        selection_type_atom = selection.get_data_type()
        selection_type = selection_type_atom.name()

        logging.debug('ClipboardTray: adding type %r', selection_type)

        cb_service = clipboard.get_instance()
        if selection_type == 'text/uri-list':
            uris = selection.get_uris()
            if len(uris) > 1:
                raise NotImplementedError('Multiple uris in text/uri-list'
                                          ' still not supported.')
            file_name = uris[0]
            buddies = neighborhood.get_model().get_buddies()
            mime_type = mime.get_for_file(file_name)
            title = os.path.basename(file_name)
            dialog = Gtk.MessageDialog(None, Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO, Gtk.ButtonsType.YES_NO, "Do you want to start file transfer ?")
            response = dialog.run()
            dialog.destroy()
            if response == Gtk.ResponseType.YES:
                for buddy in buddies:
                    if buddy != get_owner_instance():
                        filetransfer.start_transfer(buddy, file_name, title, "dummy", mime_type)
            cb_service.add_object_format(object_id,
                                         selection_type,
                                         uris[0],
                                         on_disk=True)
        else:
            cb_service.add_object_format(object_id,
                                         selection_type,
                                         selection_data,
                                         on_disk=False)
Esempio n. 39
0
    def _set_file_path(self, file_path):
        self._file_path = file_path

        if self._file_path is None:
            self._buffer.set_text('')
            return

        mime_type = mime.get_for_file(self._file_path)
        _logger.debug('Detected mime type: %r', mime_type)

        language_manager = GtkSource.LanguageManager.get_default()
        detected_language = None
        for language_id in language_manager.get_language_ids():
            language = language_manager.get_language(language_id)
            if mime_type in language.get_mime_types():
                detected_language = language
                break

        if detected_language is not None:
            _logger.debug('Detected language: %r',
                          detected_language.get_name())

        self._buffer.set_language(detected_language)
        self._buffer.set_text(open(self._file_path, 'r').read())
Esempio n. 40
0
    def __state_change_cb(self, download, gparamspec):
        state = self._download.get_status()
        if state == WebKit.DownloadStatus.STARTED:
            # Check free space and cancel the download if there is not enough.
            total_size = self._download.get_total_size()
            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 = self._download.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.__stop_response_cb)
                self._activity.add_alert(self._canceled_alert)
            else:
                # FIXME: workaround for SL #4385
                # self._download.connect('notify::progress',
                #                        self.__progress_change_cb)
                self._download.connect('notify::current-size',
                                       self.__current_size_changed_cb)

                self._create_journal_object()
                self._object_id = self.dl_jobject.object_id

                alert = TimeoutAlert(9)
                alert.props.title = _('Download started')
                alert.props.msg = _('%s' %
                                    self._download.get_suggested_filename())
                self._activity.add_alert(alert)
                alert.connect('response', self.__start_response_cb)
                alert.show()
                global _active_downloads
                _active_downloads.append(self)

        elif state == WebKit.DownloadStatus.FINISHED:
            self._stop_alert = Alert()
            self._stop_alert.props.title = _('Download completed')
            self._stop_alert.props.msg = \
                _('%s' % self._download.get_suggested_filename())
            open_icon = Icon(icon_name='zoom-activity')
            self._stop_alert.add_button(Gtk.ResponseType.APPLY,
                                        _('Show in Journal'), open_icon)
            open_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()

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

            self.dl_jobject.metadata['title'] = \
                self._download.get_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

            # sniff for a mime type, no way to get headers from WebKit
            sniffed_mime_type = mime.get_for_file(self._dest_path)
            self.dl_jobject.metadata['mime_type'] = sniffed_mime_type

            if sniffed_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)

        elif state == WebKit.DownloadStatus.CANCELLED:
            self.cleanup()
    def __state_change_cb(self, download, gparamspec):
        state = self._download.get_status()
        if state == WebKit.DownloadStatus.STARTED:
            # Check free space and cancel the download if there is not enough.
            total_size = self._download.get_total_size()
            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 = self._download.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.__stop_response_cb)
                self._activity.add_alert(self._canceled_alert)
            else:
                self._download.connect('notify::progress',
                                       self.__progress_change_cb)
                self._create_journal_object()
                self._object_id = self.dl_jobject.object_id

                alert = TimeoutAlert(9)
                alert.props.title = _('Download started')
                alert.props.msg = _('%s' %
                                    self._download.get_suggested_filename())
                self._activity.add_alert(alert)
                alert.connect('response', self.__start_response_cb)
                alert.show()
                global _active_downloads
                _active_downloads.append(self)

        elif state == WebKit.DownloadStatus.FINISHED:
            self._stop_alert = Alert()
            self._stop_alert.props.title = _('Download completed')
            self._stop_alert.props.msg = \
                _('%s' % self._download.get_suggested_filename())
            open_icon = Icon(icon_name='zoom-activity')
            self._stop_alert.add_button(Gtk.ResponseType.APPLY,
                                        _('Show in Journal'), open_icon)
            open_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()

            if self._dest_path.endswith('.journal'):

                metadata, preview_data, file_path = \
                    utils.unpackage_ds_object(self._dest_path)
                original_object_id = metadata['original_object_id']
                for key in metadata.keys():
                    self.dl_jobject.metadata[key] = metadata[key]

                self.dl_jobject.metadata['preview'] = dbus.ByteArray(
                    preview_data)

                self.dl_jobject.file_path = file_path

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

                # notify to the server, the object was successfully downloaded
                url = 'ws://%s:%d/websocket' % (self._activity.ip,
                                                self._activity.port)
                messanger = utils.Messanger(url)
                data = utils.get_user_data()
                data['object_id'] = original_object_id
                messanger.send_message('DOWNLOADED', data)

            else:
                self.dl_jobject.metadata['title'] = \
                    self._download.get_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

                # sniff for a mime type, no way to get headers from WebKit
                sniffed_mime_type = mime.get_for_file(self._dest_path)
                self.dl_jobject.metadata['mime_type'] = sniffed_mime_type

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

        elif state == WebKit.DownloadStatus.CANCELLED:
            self.cleanup()
    def __state_change_cb(self, download, gparamspec):
        state = self._download.get_status()
        if state == WebKit.DownloadStatus.STARTED:
            # Check free space and cancel the download if there is not enough.
            total_size = self._download.get_total_size()
            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 = self._download.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.__stop_response_cb)
                self._activity.add_alert(self._canceled_alert)
            else:
                # FIXME: workaround for SL #4385
                # self._download.connect('notify::progress',
                #                        self.__progress_change_cb)
                self._download.connect('notify::current-size',
                                       self.__current_size_changed_cb)

                self._create_journal_object()
                self._object_id = self.dl_jobject.object_id

                alert = TimeoutAlert(9)
                alert.props.title = _('Download started')
                alert.props.msg = _('%s' %
                                    self._download.get_suggested_filename())
                self._activity.add_alert(alert)
                alert.connect('response', self.__start_response_cb)
                alert.show()
                global _active_downloads
                _active_downloads.append(self)

        elif state == WebKit.DownloadStatus.FINISHED:
            self._stop_alert = Alert()
            self._stop_alert.props.title = _('Download completed')
            self._stop_alert.props.msg = \
                _('%s' % self._download.get_suggested_filename())

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

            self.dl_jobject.metadata['title'] = \
                self._download.get_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

            # sniff for a mime type, no way to get headers from WebKit
            sniffed_mime_type = mime.get_for_file(self._dest_path)
            self.dl_jobject.metadata['mime_type'] = sniffed_mime_type

            if sniffed_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)

            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_type = Gtk.ResponseType.APPLY
            else:
                icon = Icon(icon_name='zoom-activity')
                label = _('Show in Journal')
                response_type = Gtk.ResponseType.ACCEPT

            self._stop_alert.add_button(response_type, 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()

        elif state == WebKit.DownloadStatus.CANCELLED:
            self.cleanup()
Esempio n. 43
0
 def test_get_for_file(self):
     self.assertEqual(mime.get_for_file(os.path.join(data_dir, "mime.svg")),
                      'image/svg+xml')
    def __state_change_cb(self, download, gparamspec):
        state = self._download.get_status()
        if state == WebKit.DownloadStatus.STARTED:
            # Check free space and cancel the download if there is not enough.
            total_size = self._download.get_total_size()
            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 = self._download.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.__stop_response_cb)
                self._activity.add_alert(self._canceled_alert)
            else:
                self._download.connect('notify::progress',
                                       self.__progress_change_cb)
                self._create_journal_object()
                self._object_id = self.dl_jobject.object_id

                alert = TimeoutAlert(9)
                alert.props.title = _('Download started')
                alert.props.msg = _('%s' %
                                    self._download.get_suggested_filename())
                self._activity.add_alert(alert)
                alert.connect('response', self.__start_response_cb)
                alert.show()
                global _active_downloads
                _active_downloads.append(self)

        elif state == WebKit.DownloadStatus.FINISHED:
            self._stop_alert = Alert()
            self._stop_alert.props.title = _('Download completed')
            self._stop_alert.props.msg = \
                _('%s' % self._download.get_suggested_filename())
            open_icon = Icon(icon_name='zoom-activity')
            self._stop_alert.add_button(Gtk.ResponseType.APPLY,
                                        _('Show in Journal'), open_icon)
            open_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()

            if self._dest_path.endswith('.journal'):

                metadata, preview_data, file_path = \
                    utils.unpackage_ds_object(self._dest_path)
                original_object_id = metadata['original_object_id']
                for key in metadata.keys():
                    self.dl_jobject.metadata[key] = metadata[key]

                self.dl_jobject.metadata['preview'] = dbus.ByteArray(
                    preview_data)

                self.dl_jobject.file_path = file_path

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

                # notify to the server, the object was successfully downloaded
                url = 'ws://%s:%d/websocket' % (self._activity.ip,
                                                self._activity.port)
                messanger = utils.Messanger(url)
                data = utils.get_user_data()
                data['object_id'] = original_object_id
                messanger.send_message('DOWNLOADED', data)

            else:
                self.dl_jobject.metadata['title'] = \
                    self._download.get_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

                # sniff for a mime type, no way to get headers from WebKit
                sniffed_mime_type = mime.get_for_file(self._dest_path)
                self.dl_jobject.metadata['mime_type'] = sniffed_mime_type

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

        elif state == WebKit.DownloadStatus.CANCELLED:
            self.cleanup()