Example #1
0
    def setfile(
        self,
        submittedValue,
        filename='',
        overwrite=False,
        contenttype=''
    ):
        """ Store `submittedValue` (assumed to be a file) as a blob (or FSS).

        The name is normalized before storing. Return the normalized name and
        the guessed content type. (The `contenttype` parameter is ignored.)
        """
        # TODO: does the `contenttype` parameter exist for BBB?
        # If so, mention it. If not, can it go?
        if filename == '':
            filename = submittedValue.filename
        if filename:
            if """\\""" in filename:
                filename = filename.split("\\")[-1]
            filename = '.'.join(
                [normalizeString(s, encoding='utf-8')
                    for s in filename.split('.')])
            if overwrite and filename in self.objectIds():
                self.deletefile(filename)
            try:
                self._checkId(filename)
            except BadRequest:
                #
                # If filename is a reserved id, we rename it
                #
                # Rather than risk dates going back in time when timezone is
                # changed, always use UTC. I.e. here we care more about
                # ordering and uniqueness than about the time (which can be
                # found elsewhere on the object).
                #
                filename = '%s_%s' % (
                    DateTime().toZone('UTC').strftime("%Y%m%d%H%M%S"),
                    filename)

            if (isinstance(submittedValue, FileUpload) or
                    type(submittedValue) == file):
                submittedValue.seek(0)
                contenttype = guessMimetype(submittedValue, filename)
                submittedValue = submittedValue.read()
            elif submittedValue.__class__.__name__ == '_fileobject':
                submittedValue = submittedValue.read()
            blob = BlobWrapper(contenttype)
            file_obj = blob.getBlob().open('w')
            file_obj.write(submittedValue)
            file_obj.close()
            blob.setFilename(filename)
            blob.setContentType(contenttype)
            self._setObject(filename, blob)
            return (filename, contenttype)
        else:
            return (None, "")
def _get_blob_from_fs_file(file_path):
    """get blob file from fs file. remove tmp prefix separated by --
    """
    file_obj = open(file_path)
    file_name = os.path.split(file_path)[-1].split('--')[-1]
    file_mimetype = guessMimetype(file_obj, filename=file_name)
    file_blob = NamedBlobFile(data=file_obj.read(),
                              contentType=file_mimetype,
                              filename=unicode(file_name))
    return file_blob
def _get_blob_from_fs_file(file_path):
    """get blob file from fs file. remove tmp prefix separated by --
    """
    file_obj = open(file_path)
    file_name = os.path.split(file_path)[-1].split('--')[-1]
    file_mimetype = guessMimetype(file_obj, filename=file_name)
    file_blob = NamedBlobFile(data=file_obj.read(),
                              contentType=file_mimetype,
                              filename=unicode(file_name))
    return file_blob
Example #4
0
    def setfile(self,
                submittedValue,
                filename='',
                overwrite=False,
                contenttype=''):
        """ Store `submittedValue` (assumed to be a file) as a blob (or FSS).

        The name is normalized before storing. Return the normalized name and
        the guessed content type. (The `contenttype` parameter is ignored.)
        """
        # TODO: does the `contenttype` parameter exist for BBB?
        # If so, mention it. If not, can it go?
        if filename == '':
            filename = submittedValue.filename
        if filename:
            if """\\""" in filename:
                filename = filename.split("\\")[-1]
            filename = '.'.join([
                normalizeString(s, encoding='utf-8')
                for s in filename.split('.')
            ])
            if overwrite and filename in self.objectIds():
                self.deletefile(filename)
            try:
                self._checkId(filename)
            except BadRequest:
                # if filename is a reserved id, we rename it
                filename = '%s_%s' % (DateTime().toZone('UTC').strftime(
                    "%Y%m%d%H%M%S"), filename)

            if HAS_BLOB:
                if (isinstance(submittedValue, FileUpload)
                        or type(submittedValue) == file):
                    submittedValue.seek(0)
                    contenttype = guessMimetype(submittedValue, filename)
                    submittedValue = submittedValue.read()
                elif submittedValue.__class__.__name__ == '_fileobject':
                    submittedValue = submittedValue.read()
                try:
                    blob = BlobWrapper(contenttype)
                except:  # XXX Except what?
                    # BEFORE PLONE 4.0.1
                    blob = BlobWrapper()
                file_obj = blob.getBlob().open('w')
                file_obj.write(submittedValue)
                file_obj.close()
                blob.setFilename(filename)
                blob.setContentType(contenttype)
                self._setObject(filename, blob)
            else:
                self.manage_addFile(filename, submittedValue)
                contenttype = self[filename].getContentType()
            return (filename, contenttype)
        else:
            return (None, "")
Example #5
0
    def setfile(self,
                submittedValue,
                filename='',
                overwrite=False,
                contenttype=''):
        """
        """
        if filename == '':
            filename = submittedValue.filename
        if filename != '':
            if """\\""" in filename:
                filename = filename.split("\\")[-1]
            filename = ".".join([
                normalizeString(s, encoding='utf-8')
                for s in filename.split('.')
            ])
            if overwrite and filename in self.objectIds():
                self.deletefile(filename)
            try:
                self._checkId(filename)
            except BadRequest:
                # if filename is a reserved id, we rename it
                filename = DateTime().toZone('UTC').strftime(
                    "%Y%m%d%H%M%S") + "_" + filename

            if (self.getParentDatabase().getStorageAttachments() == True):
                tmpfile = File(filename, filename, submittedValue)
                storage = FileSystemStorage()
                storage.set(filename, self, tmpfile)
                contenttype = storage.get(filename, self).getContentType()
            elif HAS_BLOB:
                if isinstance(submittedValue,
                              FileUpload) or type(submittedValue) == file:
                    submittedValue.seek(0)
                    contenttype = guessMimetype(submittedValue, filename)
                    submittedValue = submittedValue.read()
                try:
                    blob = BlobWrapper(contenttype)
                except:
                    # BEFORE PLONE 4.0.1
                    blob = BlobWrapper()
                file_obj = blob.getBlob().open('w')
                file_obj.write(submittedValue)
                file_obj.close()
                blob.setFilename(filename)
                blob.setContentType(contenttype)
                self._setObject(filename, blob)
            else:
                self.manage_addFile(filename, submittedValue)
                contenttype = self[filename].getContentType()
            return (filename, contenttype)
        else:
            return (None, "")
Example #6
0
def getRarMimeTypes(blobfile):
    """ Get mime-types from RAR archive
    """
    filename = getattr(blobfile, 'filename', '')
    if hasattr(blobfile, 'getIterator'):
        blobfile = blobfile.getIterator()
    with NamedTemporaryFile(suffix=filename) as tmpfile:
        for chunk in blobfile:
            tmpfile.write(chunk)
        tmpfile.flush()
        zfile = RarFile(tmpfile.name)
        for zchild in zfile.infolist():
            data = StringIO(zchild.header_data)
            filename = getattr(zchild, 'filename', None)
            mimetype = guessMimetype(data, filename)
            if not mimetype:
                continue
            yield mimetype
Example #7
0
def attachThis(plominoDocument, submittedValue, itemname, filename='', overwrite=True):
    '''
    Funcion with the aim to simplify the setting of a file as an attachment of a plominoDocument
    Usage sample:
    submittedValue = plominoPrint(plominoDocument, 'stampa_autorizzazione')
    attachThis(plominoDocument, submittedValue, 'autorizzazione', filename='stampa_autorizzazione.pdf')
    #### TO DO ####
    a batter reciper proposed by Eric B. could be found here:
    https://github.com/plomino/Plomino/issues/172#issuecomment-9494835
    ###############
    '''
    new_file = None
    try:
        os.path.isfile(submittedValue)
    except:
        pass
    else:
        if os.path.isfile(submittedValue):
            with open(submittedValue, 'r') as ff:
                (new_file, contenttype) = plominoDocument.setfile(ff,
                    filename=filename, overwrite=overwrite)
    if not new_file:
        (new_file, contenttype) = plominoDocument.setfile(submittedValue,
            filename=filename, overwrite=overwrite)


    if not contenttype:
        # then try a guess
        try:
            import cStringIO
            from plone.app.blob.utils import guessMimetype
            tmpFile = cStringIO.StringIO()
            tmpFile.write(submittedValue)
            contenttype = guessMimetype(tmpFile, filename)
            tmpFile.close()
        except:
            pass

    current_files = plominoDocument.getItem(itemname, {}) or {}
    current_files[new_file] = contenttype or 'unknown filetype'
    plominoDocument.setItem(itemname, current_files)
    return new_file
Example #8
0
 def __init__(self, context):
     self.context = context
     self.__mimetype = guessMimetype(self.context, self.filename())
Example #9
0
 def mimetype(self):
     """ see interface ... """
     return guessMimetype(self.context, self.filename())
Example #10
0
 def __init__(self, context):
     self.context = context
     self.__mimetype = guessMimetype(self.context, self.filename())
Example #11
0
 def mimetype(self):
     """ see interface ... """
     return guessMimetype(StringIO(self.context.data), None)
 def testMimetypeGuessing(self):
     gif = StringIO(getImage())
     self.assertEqual(guessMimetype(gif), 'image/gif')
     self.assertEqual(guessMimetype(gif, 'image.jpg'), 'image/jpeg')
     self.assertEqual(guessMimetype(StringIO(), 'image.jpg'), 'image/jpeg')
     self.assertEqual(guessMimetype(StringIO('foo')), 'text/plain')
Example #13
0
 def mimetype(self):
     """ see interface ... """
     mimetype = self.context.mimetype
     if mimetype is None:
         mimetype = guessMimetype(self.context.file, self.filename())
     return mimetype
Example #14
0
 def testMimetypeGuessing(self):
     gif = StringIO(getImage())
     self.assertEqual(guessMimetype(gif), 'image/gif')
     self.assertEqual(guessMimetype(gif, 'image.jpg'), 'image/jpeg')
     self.assertEqual(guessMimetype(StringIO(), 'image.jpg'), 'image/jpeg')
     self.assertEqual(guessMimetype(StringIO('foo')), 'text/plain')
Example #15
0
    
    try:
        import cStringIO
        from plone.app.blob.utils import guessMimetype
    except ImportError, err:
        out.update(dict(
            contenttype = None,
            success = 0,
            err_msg = '%s' % err
        ))
        out['contenttype'] = None
    else:
        tmpFile = cStringIO.StringIO()
        tmpFile.write(submittedValue)
        out.update(dict(
            contenttype = guessMimetype(tmpFile, filename),
            success = 1,
        ))
        tmpFile.close()
        
    return out

def attachThis(plominoDocument, submittedValue, itemname, filename='', overwrite=True):
    '''
    Funcion with the aim to simplify the setting of a file as an attachment of a plominoDocument
    Usage sample:
    submittedValue = plominoPrint(plominoDocument, 'stampa_autorizzazione')
    attachThis(plominoDocument, submittedValue, 'autorizzazione', filename='stampa_autorizzazione.pdf')
    #### TO DO ####
    a batter reciper proposed by Eric B. could be found here:
    https://github.com/plomino/Plomino/issues/172#issuecomment-9494835