Beispiel #1
0
    def attach_file(self, file_path, file_name, parent, **kwargs):
        i = kwargs.get('number', None)
        i = str(i) if i else ""
        source = kwargs.get('source', None)

        new_name = "{0}_{1}_{2}.{3}".format(NameNormalizer.sanitize_name(parent.title.strip()),
                                            NameNormalizer.sanitize_name(parent.composer.name.strip()),
                                            "file" + str(i),
                                            file_name.rsplit('.')[-1])
        #replace unicode in string with normalized chars
        new_name = self.normalize_name(new_name)

        old_path = os.path.join(file_path, file_name)
        new_path = os.path.join(file_path, new_name)
        os.rename(old_path, new_path)

        if source:
            self.source = source

        with open(new_path, 'rb+') as dest:
            file_content = File(dest)
            self.attachment.save(new_name, file_content)

        splt = self.attachment.name.split('attachments')
        self.attachment.name = "attachments" + splt[-1]

        self.title = self.file_name
        self.save()
Beispiel #2
0
    def auto_rename(self, **kwargs):
        """Determine the correct name for the file, then rename it if necessary"""
        parent = None
        if self.pieces.all():
            parent = self.pieces.first()
            parent_str = parent.title.strip()
        elif self.movements.all():
            parent = self.movements.first()
            mov = parent
            if mov.piece:
                piece_str = mov.piece.title.strip()
                parent_str = piece_str + "_" + mov.title.strip()
            else:
                parent_str = mov.title.strip()
        else:
            print("{0} is an orphan and will be deleted".format(self.title))
            self.delete()
            return

        # Find position in parent attachments for an index in the name.
        i = 1
        for a in parent.attachments.all():
            if a == self:
                break
            else:
                i += 1

        # Find current file extension.
        old_path = os.path.join(settings.MEDIA_ROOT, self.attachment.name)
        (path, current_name) = os.path.split(old_path)
        (current_file_name, current_extension) = os.path.splitext(current_name)

        new_name = "{0}_{1}_{2}{3}".format(NameNormalizer.sanitize_name(parent_str),
                                           NameNormalizer.sanitize_name(parent.composer.name.strip()),
                                           "file" + str(i),
                                           current_extension)
        new_name = self.normalize_name(new_name)
        new_path = os.path.join(path, new_name)

        # Return now if there's no work to do.
        if self.file_name == new_name:
            return

        shutil.move(old_path, new_path)

        # Point the attachment to the new file
        old_rel_path, old_name = os.path.split(self.attachment.name)
        self.attachment.name = os.path.join(old_rel_path, new_name)
        self.save(**kwargs)
        return
    def compute_correct_file_name(self, position=None, extension=None):
        """Generate the name the file should take on disk, given metadata.

        Note 1: If a new Attachment is being created you must provide the position
        and extension arguments. Otherwise, this function expects this information
        is already available in the Attachment instance.

        Note 2: This function COMPUTES its result. It is not based on the ACTUAL properties
        of some file. That is, you should use this function to compute the properties of
        a file you need to place/name, NOT to get information about the actual file linked
        to by this Attachment. It is a prescriptive, not descriptive result. Examine the
        properties of the Attachment.attachment object for the actual properties of the
        real file.

        Args:
            position (int): The index of this Attachment's in its parent's list of files.
            extension (str): The file extension with dot included (e.g. '.midi, '.exe')

        Returns: A string with the file name the file should be saved with on disk.
        """
        # Generate a parent_str which contains piece and movement names.
        if self.pieces.all():
            parent = self.pieces.first()
            parent_str = parent.title.strip()
        elif self.movements.all():
            parent = self.movements.first()
            mov = parent
            if mov.piece:
                piece_str = mov.piece.title.strip()
                parent_str = piece_str + "_" + mov.title.strip()
            else:
                parent_str = mov.title.strip()
        else:
            msg = 'Attachment "{0}" is an orphan and should be deleted'
            raise ParentResolveError(msg.format(self.title))

        # Generate file name.
        position = str(position) if position else self.get_index_from_parent()
        extension = extension if extension else self.extension
        new_name = "{0}_{1}_{2}{3}".format(NameNormalizer.sanitize_name(parent_str),
                                           NameNormalizer.sanitize_name(parent.composer.name.strip()),
                                           "file" + str(position), extension)
        return NameNormalizer.normalize_name(new_name)