コード例 #1
0
    def getfile(self, filename=None, REQUEST=None, asFile=False):
        """
        """
        if not self.isReader():
            raise Unauthorized, "You cannot read this content"

        onOpenDocument_error = self._onOpenDocument()
        if onOpenDocument_error:
            raise Unauthorized, onOpenDocument_error

        fss = self.getParentDatabase().getStorageAttachments()
        if REQUEST is not None:
            filename = REQUEST.get('filename')
        if filename is not None:
            if fss:
                storage = FileSystemStorage()
                file_obj = storage.get(filename, self)
            else:
                #file_obj = getattr(self, filename)
                file_obj = self.get(filename, None)
            if not file_obj:
                return None
            if asFile:
                return file_obj
            if REQUEST:
                REQUEST.RESPONSE.setHeader('content-type',
                                           file_obj.getContentType())
                REQUEST.RESPONSE.setHeader("Content-Disposition",
                                           "inline; filename=" + filename)
            if fss:
                return file_obj.getData()
            else:
                return file_obj.data
        else:
            return None
コード例 #2
0
 def deletefile(self, filename):
     """
     """
     if (self.getParentDatabase().getStorageAttachments()):
         storage = FileSystemStorage()
         storage.unset(filename, self)
     else:
         if filename in self.objectIds():
             self.manage_delObjects(filename)
コード例 #3
0
def main():
    global app

    attr_storage = AttributeStorage()
    fss_storage = FileSystemStorage()
    
    app = makerequest(app)
    
    _policy = PermissiveSecurityPolicy()
    _oldpolicy = setSecurityPolicy(_policy)
    newSecurityManager(None, OmnipotentUser().__of__(app.acl_users))

    global portal, ct
    
    portal = app[ploneid]
    setSite(portal)
    
    # Initialization
    log('Initialized at', datetime.now().isoformat())
    
    ct = getToolByName(portal, 'portal_catalog')
    fssfiles = ct.searchResults({'portal_type':pt})
    
    for fssfile in fssfiles:
        log('Migrating: [%s] %s in %s ... ' %(fssfile.portal_type,fssfile.id, fssfile.getPath()))
    
        obj = portal.restrictedTraverse(fssfile.getPath())
    
        try:
            f_tp = 'image'
            field = obj.Schema()[f_tp]
        except KeyError, e:
            f_tp = 'file'
            field = obj.Schema()[f_tp]
    
    
        fieldstorage = field.storage
    
        try:
            mimetype = field.getContentType(obj)
        except:
            mimetype = obj.getContentType()
    
        content = StringIO(str(fss_storage.get(f_tp, obj)))
    
        # Cleaning the storage 
        fss_storage.unset(f_tp, obj)
    
        field.set(obj, content)
        field.setContentType(obj, mimetype)
        field.setFilename(obj,obj.id)
    
        log('Transaction commit and Data.fs synchronism.')
        transaction.commit()
        app._p_jar.sync()
コード例 #4
0
def main():
    global app

    attr_storage = AttributeStorage()
    fss_storage = FileSystemStorage()

    app = makerequest(app)

    _policy = PermissiveSecurityPolicy()
    _oldpolicy = setSecurityPolicy(_policy)
    newSecurityManager(None, OmnipotentUser().__of__(app.acl_users))

    global portal, ct

    portal = app[ploneid]
    setSite(portal)

    # Initialization
    log('Initialized at', datetime.now().isoformat())

    ct = getToolByName(portal, 'portal_catalog')
    fssfiles = ct.searchResults({'portal_type': pt})

    for fssfile in fssfiles:
        log('Migrating: [%s] %s in %s ... ' %
            (fssfile.portal_type, fssfile.id, fssfile.getPath()))

        obj = portal.restrictedTraverse(fssfile.getPath())

        try:
            f_tp = 'image'
            field = obj.Schema()[f_tp]
        except KeyError, e:
            f_tp = 'file'
            field = obj.Schema()[f_tp]

        fieldstorage = field.storage

        try:
            mimetype = field.getContentType(obj)
        except:
            mimetype = obj.getContentType()

        content = StringIO(str(fss_storage.get(f_tp, obj)))

        # Cleaning the storage
        fss_storage.unset(f_tp, obj)

        field.set(obj, content)
        field.setContentType(obj, mimetype)
        field.setFilename(obj, obj.id)

        log('Transaction commit and Data.fs synchronism.')
        transaction.commit()
        app._p_jar.sync()
コード例 #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, "")
コード例 #6
0
ファイル: FSSItem.py プロジェクト: mikejmets/iw.fss
from Products.Archetypes.public import BaseContent
from Products.Archetypes.public import registerType

from Products.ATContentTypes.content.base import ATCTContent
from Products.ATContentTypes.content.base import ATContentTypeSchema

# Products imports
from iw.fss.config import PROJECTNAME
from iw.fss.FileSystemStorage import FileSystemStorage

BaseItemShema = Schema((
    FileField(
        'file',
        required=False,
        primary=True,
        storage=FileSystemStorage(),
        widget=FileWidget(
            description=
            "Select the file to be added by clicking the 'Browse' button.",
            description_msgid="help_file",
            label="File",
            label_msgid="label_file",
            i18n_domain="plone",
            show_content_type=False,
        )),
    ImageField('image',
               required=False,
               sizes={
                   'mini': (40, 40),
                   'thumb': (80, 80),
               },
コード例 #7
0
ファイル: migrationExample.py プロジェクト: mikejmets/iw.fss
def migrateToFSStorage(self):
    """
    Migrate File and Images FileFields to FSStorage
    
    /!\ Assertion is made that the schema definition has been migrated to define
    FSS as storage for interested fields
    """
    try:
        conf = getUtility(IConf, "globalconf")()
    except AttributeError:
        raise ValueError, "install and configure FileSystemStorage first!"

    out = StringIO.StringIO()
    cat = getToolByName(self, "portal_catalog")
    brains = cat({"portal_type": ["File", "Image"]})

    # this defines are here to avoid instantiating a new one for each file
    # it is known to be harmless with those storages
    attr_storage = AttributeStorage()
    fss_storage = FileSystemStorage()

    for b in brains:
        o = b.getObject()
        print >> out, "/".join(o.getPhysicalPath()), ":",

        # ensure we have an UID
        # it should not happen on a standard plone site, but I've met the case
        # with some weird custom types
        #  the UID code was valid on a Plone 2.1.2 bundle (AT 1.3.7)
        if o.UID() is None:
            o._register()
            o._updateCatalog(o.aq_parent)
            print >> out, "UID was None, set to: ", o.UID(),

        for f in o.Schema().fields():
            # visit only FileFields with FileSystemStorage
            if not isinstance(f, FileField):
                continue
            storage = f.getStorage()
            if not isinstance(storage, FileSystemStorage):
                continue

            name = f.getName()
            print >> out, "'%s'" % name,

            # skip if field has already a content
            if f.get_size(o) != 0:
                print >> out, "already set",
                continue

            # get content from old storage and delete old storage
            try:
                content = attr_storage.get(name, o)
            except AttributeError:
                print >> out, "no old value",
                continue
            attr_storage.unset(name, o)

            fss_storage.initializeField(o, f)  # FIXME: really needed?
            f.set(o, content)

            # unset empty files, this avoid empty files on disk
            if f.get_size(o) == 0:
                print >> out, "unset",
                f.set(o, "DELETE_FILE")

            print >> out, ",",

        # new line for next object
        print >> out, ""

    return out.getvalue()
コード例 #8
0
# only required for migration from iw.fss to plone.app.blob
try:
    from iw.fss.FileSystemStorage import FileSystemStorage
    HAS_FSS = True
except ImportError:
    HAS_FSS = False

from unimr.red5.protectedvod.interface import IRed5Stream
from unimr.red5.protectedvod.permissions import DownloadRed5Stream
from unimr.red5.protectedvod.config import PROJECTNAME

if HAS_FSS:
    Red5StreamSchema = ATFileSchema.copy()
    file_field = Red5StreamSchema['file']
    file_field.read_permission = DownloadRed5Stream
    file_field.storage = FileSystemStorage()
    file_field.registerLayer('storage', file_field.storage)
else:
    Red5StreamSchema = ATBlobSchema.copy()

finalizeATCTSchema(Red5StreamSchema)


class Red5Stream(ATBlob):
    """ video/audio content for streaming by red5 server """

    implements(IRed5Stream)
    portal_type = 'Red5Stream'
    archetype_name = 'Red5Stream'
    inlineMimetypes = tuple()