Example #1
0
    def on_ok_clicked(self):
        """
        Method that is run when you click the OK button.
        """
        downloaded = {}

        # Get a directory to put the media files in. If the media path in
        # preferences is not just the user's home, then we will use that. If it
        # is the user's home, we create a new directory below that, so we don't
        # splatter files into home.
        media_path = self.db.get_mediapath()
        if media_path == USER_HOME or media_path == "" or media_path == None:
            media_path = os.path.join(USER_HOME, "mediadir")
        if not os.path.isdir(media_path):
            os.makedirs(media_path)

        # Many thanks to 'sirex' from whom I have taken the code he submitted as
        # part of bug 0003553: Import media files from GEDCOM
        file_pattern = re.compile(r'.*\.(png|jpg|jpeg|gif)$')

        def fetch_file(url, filename):
            LOG.debug("Downloading url %s to file %s" % (url, filename))
            fr = urlopen(url)
            fw = open(filename, 'wb')
            for block in fr:
                fw.write(block)
            fw.close()
            fr.close()

        self.progress = ProgressMeter(
            _('Downloading files'), '')
        self.progress.set_pass(_('Downloading files'),
                               self.db.get_number_of_media_objects())

        self.db.disable_signals()
        with DbTxn('Download files', self.db) as trans:
            for media_handle in self.db.media_map.keys():
                media = self.db.get_object_from_handle(media_handle)
                url = media.get_path()
                res = urlparse(url)
                LOG.debug(res)
                if res.scheme == "http" or res.scheme == "https":
                    if file_pattern.match(url):
                        if url in downloaded:
                            full_path = downloaded[url]
                        else:
                            filename = url.split('/')[-1]
                            full_path = os.path.join(media_path, filename)
                            fetch_file(url, full_path)
                            downloaded[url] = full_path
                            self.num_downloads += 1
                        media.set_path(full_path)
                        media.set_mime_type(get_type(full_path))
                        self.db.commit_media_object(media, trans)

                self.progress.step()

        self.db.enable_signals()
        self.db.request_rebuild()
        self.progress.close()
Example #2
0
    def on_name_changed(self, *obj):
        """
        Called anytime the filename text window changes. Checks to
        see if the file exists. If it does, the image is loaded into
        the preview window.
        """
        fname = self.file_text.get_filename()
        if not fname:
            return
        filename = fname
        basename = os.path.basename(filename)
        (root, ext) = os.path.splitext(basename)
        old_title = self.description.get_text()

        if old_title == "" or old_title == self.temp_name:
            self.description.set_text(root)
        self.temp_name = root

        filename = find_file(filename)
        if filename:
            mtype = get_type(filename)
            if mtype and mtype.startswith("image"):
                image = scale_image(filename, THUMBSCALE)
            else:
                image = find_mime_type_pixbuf(mtype)
            self.image.set_from_pixbuf(image)
Example #3
0
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data,
        and decide if this is a move or a reorder.
        The only data we accept on mediaview is dropping a file, so URI_LIST.
        We assume this is what we obtain
        """
        if not sel_data:
            return
        files = sel_data.get_uris()
        for file in files:
            protocol, site, mfile, j, k, l = urlparse(file)
            if protocol == "file":
                name = url2pathname(mfile)
                mime = get_type(name)
                if not is_valid_type(mime):
                    return
                photo = Media()
                self.uistate.set_busy_cursor(True)
                photo.set_checksum(create_checksum(name))
                self.uistate.set_busy_cursor(False)
                base_dir = str(media_path(self.dbstate.db))
                if os.path.exists(base_dir):
                    name = relative_path(name, base_dir)
                photo.set_path(name)
                photo.set_mime_type(mime)
                basename = os.path.basename(name)
                (root, ext) = os.path.splitext(basename)
                photo.set_description(root)
                with DbTxn(_("Drag Media Object"), self.dbstate.db) as trans:
                    self.dbstate.db.add_media(photo, trans)
        widget.emit_stop_by_name('drag_data_received')
Example #4
0
 def _run(self):
     """
     Go through directories that are mentioned in the database via
     media files, and include all images that are not all ready
     included.
     """
     if not self.prepared:
         self.prepare()
     self.set_total(len(self.dir_list))
     for directory in self.dir_list:
         for (dirpath, dirnames, filenames) in os.walk(directory):
             if ".git" in dirnames:
                 dirnames.remove('.git')  # don't visit .git directories
             for filename in filenames:
                 media_full_path = os.path.join(dirpath, filename)
                 if media_full_path not in self.path_list:
                     self.path_list.append(media_full_path)
                     mime_type = get_type(media_full_path)
                     if is_image_type(mime_type):
                         obj = Media()
                         obj.set_path(media_full_path)
                         obj.set_mime_type(mime_type)
                         (root, ext) = os.path.splitext(filename)
                         obj.set_description(root)
                         self.db.add_media(obj, self.trans)
         self.update()
     return True
Example #5
0
 def save(self, commit=True):
     from gramps.webapp.utils import dp
     from gramps.webapp.libdjango import DjangoInterface
     dji = DjangoInterface()
     model = super(MediaForm, self).save(commit=False)
     model.mime = get_type(model.path)
     dobj = dp(self.cleaned_data['text'])
     dji.add_date(model, dobj.serialize())
     if commit:
         model.save()
     return model
Example #6
0
    def save(self, *obj):
        """
        Callback function called when the save button is pressed.
        The media object is updated, and callback called.
        """
        description = str(self.description.get_text())

        if self.file_text.get_filename() is None:
            msgstr = _("Import failed")
            msgstr2 = _("The filename supplied could not be found.")
            ErrorDialog(msgstr, msgstr2, parent=self.window)
            return

        filename = self.file_text.get_filename()
        full_file = filename

        if self.relpath.get_active():
            pname = str(media_path(self.dbase))
            if not os.path.exists(pname):
                msgstr = _("Cannot import %s")
                msgstr2 = _("Directory specified in preferences: "
                            "Base path for relative media paths: "
                            "%s does not exist. Change preferences "
                            "or do not use relative path when importing")
                ErrorDialog(msgstr % filename, msgstr2 % pname,
                            parent=self.window)
                return
            filename = relative_path(filename, pname)


        mtype = get_type(full_file)
        description = description or os.path.basename(filename)

        self.obj.set_description(description)
        self.obj.set_mime_type(mtype)
        name = filename
        self.obj.set_path(name)

        self.last_directory = os.path.dirname(full_file)
        self.relative_path = self.relpath.get_active()

        self._cleanup_on_exit()
        if self.callback:
            self.callback(self.obj)
        self.close()
Example #7
0
    def save(self, *obj):
        """
        Callback function called when the save button is pressed.
        The media object is updated, and callback called.
        """
        description = str(self.description.get_text())

        if self.file_text.get_filename() is None:
            msgstr = _("Import failed")
            msgstr2 = _("The filename supplied could not be found.")
            ErrorDialog(msgstr, msgstr2, parent=self.window) # parent-OK
            return

        filename = self.file_text.get_filename()
        full_file = filename

        if self.relpath.get_active():
            pname = str(media_path(self.dbase))
            if not os.path.exists(pname):
                msgstr = _("Cannot import %s")
                msgstr2 = _("Directory specified in preferences: "
                            "Base path for relative media paths: "
                            "%s does not exist. Change preferences "
                            "or do not use relative path when importing")
                ErrorDialog(msgstr % filename, msgstr2 % pname, # parent-OK
                            parent=self.window)
                return
            filename = relative_path(filename, pname)


        mtype = get_type(full_file)
        description = description or os.path.basename(filename)

        self.obj.set_description(description)
        self.obj.set_mime_type(mtype)
        name = filename
        self.obj.set_path(name)

        self.last_directory = os.path.dirname(full_file)
        self.relative_path = self.relpath.get_active()

        self._cleanup_on_exit()
        if self.callback:
            self.callback(self.obj)
Example #8
0
    def determine_mime(self):
        descr = get_description(self.obj.get_mime_type())
        if descr:
            self.mimetext.set_text(descr)

        path = self.file_path.get_text()
        path_full = media_path_full(self.db, path)
        if path != self.obj.get_path() and path_full != self.obj.get_path():
            #redetermine mime
            mime = get_type(find_file(path_full))
            self.obj.set_mime_type(mime)
            descr = get_description(mime)
            if descr:
                self.mimetext.set_text(descr)
            else:
                self.mimetext.set_text(_('Unknown'))
        #if mime type not set, is note
        if not self.obj.get_mime_type():
            self.mimetext.set_text(_('Note'))
Example #9
0
    def determine_mime(self):
        descr = get_description(self.obj.get_mime_type())
        if descr:
            self.mimetext.set_text(descr)

        path = self.file_path.get_text()
        path_full = media_path_full(self.db, path)
        if path != self.obj.get_path() and path_full != self.obj.get_path():
            # redetermine mime
            mime = get_type(find_file(path_full))
            self.obj.set_mime_type(mime)
            descr = get_description(mime)
            if descr:
                self.mimetext.set_text(descr)
            else:
                self.mimetext.set_text(_("Unknown"))
        # if mime type not set, is note
        if not self.obj.get_mime_type():
            self.mimetext.set_text(_("Note"))
Example #10
0
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data,
        and decide if this is a move or a reorder.
        The only data we accept on mediaview is dropping a file, so URI_LIST.
        We assume this is what we obtain
        """
        if not sel_data:
            return

        files = sel_data.get_uris()
        photo = None

        for file in files:
            protocol, site, mfile, j, k, l = urlparse(file)
            if protocol == "file":
                name = url2pathname(mfile)
                mime = get_type(name)
                if not is_valid_type(mime):
                    return
                photo = Media()
                self.uistate.set_busy_cursor(True)
                photo.set_checksum(create_checksum(name))
                self.uistate.set_busy_cursor(False)
                base_dir = str(media_path(self.dbstate.db))
                if os.path.exists(base_dir):
                    name = relative_path(name, base_dir)
                photo.set_path(name)
                photo.set_mime_type(mime)
                basename = os.path.basename(name)
                (root, ext) = os.path.splitext(basename)
                photo.set_description(root)
                with DbTxn(_("Drag Media Object"), self.dbstate.db) as trans:
                    self.dbstate.db.add_media(photo, trans)

        if photo:
            self.uistate.set_active(photo.handle, "Media")

        widget.emit_stop_by_name('drag_data_received')
Example #11
0
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data, 
        and decide if this is a move or a reorder.
        The only data we accept on mediaview is dropping a file, so URI_LIST. 
        We assume this is what we obtain
        """
        if not sel_data:
            return
        #modern file managers provide URI_LIST. For Windows split sel_data.data
        files = sel_data.get_uris()
        for file in files:
            if win():
                clean_string = conv_to_unicode(
                    file.replace('\0', ' ').replace("\r", " ").strip(), None)
            else:
                clean_string = file
            protocol, site, mfile, j, k, l = urlparse(clean_string)
            if protocol == "file":
                name = url2pathname(mfile)
                mime = get_type(name)
                if not is_valid_type(mime):
                    return
                photo = MediaObject()
                self.uistate.set_busy_cursor(True)
                photo.set_checksum(create_checksum(name))
                self.uistate.set_busy_cursor(False)
                base_dir = str(media_path(self.dbstate.db))
                if os.path.exists(base_dir):
                    name = relative_path(name, base_dir)
                photo.set_path(name)
                photo.set_mime_type(mime)
                basename = os.path.basename(name)
                (root, ext) = os.path.splitext(basename)
                photo.set_description(root)
                with DbTxn(_("Drag Media Object"), self.dbstate.db) as trans:
                    self.dbstate.db.add_object(photo, trans)
        widget.emit_stop_by_name('drag_data_received')
Example #12
0
def __create_thumbnail_image(src_file,
                             mtype=None,
                             rectangle=None,
                             size=SIZE_NORMAL):
    """
    Generates the thumbnail image for a file. If the mime type is specified,
    and is not an 'image', then we attempt to find and run a thumbnailer
    utility to create a thumbnail. For images, we simply create a smaller
    image, scaled to thumbnail size.

    :param src_file: filename of the source file
    :type src_file: unicode
    :param mtype: mime type of the specified file (optional)
    :type mtype: unicode
    :param rectangle: subsection rectangle
    :type rectangle: tuple
    :rtype: bool
    :returns: True is the thumbnailwas successfully generated
    """
    if mtype is None:
        mtype = get_type(src_file)
    filename = __build_thumb_path(src_file, rectangle, size)
    return run_thumbnailer(mtype, src_file, filename, size, rectangle)
Example #13
0
    def on_name_changed(self, *obj):
        """
        Called anytime the filename text window changes. Checks to
        see if the file exists. If it does, the image is loaded into
        the preview window.
        """
        fname = self.file_text.get_filename()
        if not fname:
            return
        filename = fname
        basename = os.path.basename(filename)
        (root, ext) = os.path.splitext(basename)
        old_title = self.description.get_text()

        if old_title == '' or old_title == self.temp_name:
            self.description.set_text(root)
        self.temp_name = root

        filename = find_file(filename)
        if filename:
            mtype = get_type(filename)
            image = get_thumbnail_image(filename, mtype)
            self.image.set_from_pixbuf(image)
Example #14
0
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data,
        and decide if this is a move or a reorder.
        """
        if sel_data and sel_data.get_data():
            try:
                (mytype, selfid, obj, row_from) = pickle.loads(sel_data.get_data())

                # make sure this is the correct DND type for this object
                if mytype == self._DND_TYPE.drag_type:
                    
                    # determine the destination row
                    data = self.iconlist.get_dest_item_at_pos(x, y)
                    if data:
                        (path, pos) = data
                        row = path.get_indices()[0]
                        if pos ==  Gtk.IconViewDropPosition.DROP_LEFT:
                            row = max(row, 0)
                        elif pos == Gtk.IconViewDropPosition.DROP_RIGHT:
                            row = min(row, len(self.get_data()))
                        elif pos == Gtk.IconViewDropPosition.DROP_INTO:
                            row = min(row+1, len(self.get_data()))
                    else:
                        row = len(self.get_data())
                    
                    # if the is same object, we have a move, otherwise,
                    # it is a standard drag-n-drop
                    
                    if id(self) == selfid:
                        self._move(row_from, row, obj)
                    else:
                        self._handle_drag(row, obj)
                    self.rebuild()
                elif mytype == DdTargets.MEDIAOBJ.drag_type:
                    oref = MediaRef()
                    oref.set_reference_handle(obj)
                    self.get_data().append(oref)
                    self.changed = True
                    self.rebuild()
                elif self._DND_EXTRA and mytype == self._DND_EXTRA.drag_type:
                    self.handle_extra_type(mytype, obj)
            except pickle.UnpicklingError:
                files =  sel_data.get_uris()
                for file in files:
                    protocol, site, mfile, j, k, l = urlparse(file)
                    if protocol == "file":
                        name = url2pathname(mfile)
                        mime = get_type(name)
                        if not is_valid_type(mime):
                            return
                        photo = MediaObject()
                        self.uistate.set_busy_cursor(True)
                        photo.set_checksum(create_checksum(name))
                        self.uistate.set_busy_cursor(False)
                        base_dir = str(media_path(self.dbstate.db))
                        if os.path.exists(base_dir):
                            name = relative_path(name, base_dir)
                        photo.set_path(name)
                        photo.set_mime_type(mime)
                        basename = os.path.basename(name)
                        (root, ext) = os.path.splitext(basename)
                        photo.set_description(root)
                        with DbTxn(_("Drag Media Object"),
                                   self.dbstate.db) as trans:
                            self.dbstate.db.add_object(photo, trans)
                            oref = MediaRef()
                            oref.set_reference_handle(photo.get_handle())
                            self.get_data().append(oref)
                            self.changed = True
                    self.rebuild()
Example #15
0
    def on_ok_clicked(self):
        """
        Method that is run when you click the OK button.
        """
        downloaded = {}

        # Get a directory to put the media files in. If the media path in
        # preferences is not just the user's home, then we will use that. If it
        # is the user's home, we create a new directory below that, so we don't
        # splatter files into home.
        media_path = self.db.get_mediapath()
        if media_path == USER_HOME or media_path == "" or media_path == None:
            media_path = os.path.join(USER_HOME, "mediadir")
        if not os.path.isdir(media_path):
            os.makedirs(media_path)

        # Many thanks to 'sirex' from whom I have taken the code he submitted as
        # part of bug 0003553: Import media files from GEDCOM
        file_pattern = re.compile(r'.*\.(png|jpg|jpeg|gif)$')

        def fetch_file(url, filename):
            LOG.debug("Downloading url %s to file %s" % (url, filename))
            try:
                fr = urlopen(url)
            except HTTPError:
                return False
            try:
                fw = open(filename, 'wb')
            except:
                fr.close()
                return False
            for block in fr:
                fw.write(block)
            fw.close()
            fr.close()
            return True

        self.progress = ProgressMeter(_('Downloading files'), '')
        self.progress.set_pass(_('Downloading files'),
                               self.db.get_number_of_media())

        self.db.disable_signals()
        errors = ''
        with DbTxn('Download files', self.db) as trans:
            for media_handle in self.db.get_media_handles():
                media = self.db.get_media_from_handle(media_handle)
                url = media.get_path()
                res = urlparse(url)
                LOG.debug(res)
                if res.scheme == "http" or res.scheme == "https":
                    if file_pattern.match(url):
                        if url in downloaded:
                            full_path = downloaded[url]
                        else:
                            filename = url.split('/')[-1]
                            full_path = os.path.join(media_path, filename)
                            if not fetch_file(url, full_path):
                                errors += url + '\n'
                                continue
                            downloaded[url] = full_path
                            self.num_downloads += 1
                        media.set_path(full_path)
                        media.set_mime_type(get_type(full_path))
                        self.db.commit_media(media, trans)
                    else:
                        errors += url + '\n'

                self.progress.step()

        self.db.enable_signals()
        self.db.request_rebuild()
        self.progress.close()
        if errors:
            message = _("Media download errors detected")
            if hasattr(self.user.uistate, 'window'):
                parent_window = self.user.uistate.window
            else:
                parent_window = None
            self.user.info(message,
                           errors,
                           parent=parent_window,
                           monospaced=True)
Example #16
0
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data,
        and decide if this is a move or a reorder.
        """
        if sel_data and sel_data.get_data():
            try:
                (mytype, selfid, obj,
                 row_from) = pickle.loads(sel_data.get_data())

                # make sure this is the correct DND type for this object
                if mytype == self._DND_TYPE.drag_type:

                    # determine the destination row
                    data = self.iconlist.get_dest_item_at_pos(x, y)
                    if data:
                        (path, pos) = data
                        row = path.get_indices()[0]
                        if pos == Gtk.IconViewDropPosition.DROP_LEFT:
                            row = max(row, 0)
                        elif pos == Gtk.IconViewDropPosition.DROP_RIGHT:
                            row = min(row, len(self.get_data()))
                        elif pos == Gtk.IconViewDropPosition.DROP_INTO:
                            row = min(row + 1, len(self.get_data()))
                    else:
                        row = len(self.get_data())

                    # if the is same object, we have a move, otherwise,
                    # it is a standard drag-n-drop

                    if id(self) == selfid:
                        self._move(row_from, row, obj)
                    else:
                        self._handle_drag(row, obj)
                    self.rebuild()
                elif mytype == DdTargets.MEDIAOBJ.drag_type:
                    oref = MediaRef()
                    oref.set_reference_handle(obj)
                    self.get_data().append(oref)
                    self.changed = True
                    self.rebuild()
                elif self._DND_EXTRA and mytype == self._DND_EXTRA.drag_type:
                    self.handle_extra_type(mytype, obj)
            except pickle.UnpicklingError:
                files = sel_data.get_uris()
                for file in files:
                    protocol, site, mfile, j, k, l = urlparse(file)
                    if protocol == "file":
                        name = url2pathname(mfile)
                        mime = get_type(name)
                        if not is_valid_type(mime):
                            return
                        photo = MediaObject()
                        self.uistate.set_busy_cursor(True)
                        photo.set_checksum(create_checksum(name))
                        self.uistate.set_busy_cursor(False)
                        base_dir = str(media_path(self.dbstate.db))
                        if os.path.exists(base_dir):
                            name = relative_path(name, base_dir)
                        photo.set_path(name)
                        photo.set_mime_type(mime)
                        basename = os.path.basename(name)
                        (root, ext) = os.path.splitext(basename)
                        photo.set_description(root)
                        with DbTxn(_("Drag Media Object"),
                                   self.dbstate.db) as trans:
                            self.dbstate.db.add_object(photo, trans)
                            oref = MediaRef()
                            oref.set_reference_handle(photo.get_handle())
                            self.get_data().append(oref)
                            self.changed = True
                    self.rebuild()