This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
pfwbged.basecontent/src/pfwbged/basecontent/browser/adddmsfile.py

157 lines
5.5 KiB
Python

import json
import os
from five import grok
from zope.interface import implements
from zope.component import getUtility, createObject
from Acquisition import aq_inner, aq_base
from Acquisition.interfaces import IAcquirer
from zope.annotation.interfaces import IAnnotations
from zope import schema
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from zope.schema.interfaces import IContextSourceBinder
from zope.schema.interfaces import RequiredMissing
from plone.supermodel import model
from z3c.form import field, form, button
from Products.CMFCore.utils import getToolByName
from plone.dexterity.interfaces import IDexterityFTI
from plone.dexterity.browser.add import DefaultAddView, DefaultAddForm
from plone.namedfile.field import NamedBlobFile as NamedBlobFileField
from plone.namedfile.file import NamedBlobFile
from plone.directives.form import default_value
from App.config import getConfiguration
from collective.dms.basecontent.dmsfile import IDmsFile, DmsFile
from collective.dms.basecontent.dmsdocument import IDmsDocument
from pfwbged.basecontent import _
def make_terms(items):
""" Create zope.schema terms for vocab from tuples """
terms = [SimpleTerm(value=pair[0], token=pair[0], title=pair[1]) for pair in items]
return terms
@grok.provider(IContextSourceBinder)
def file_source(context):
items = [('upload', _('Uploaded File'))]
# add an entry for previous version only if there's one
portal_catalog = getToolByName(context , 'portal_catalog')
folder_path = '/'.join(context.getPhysicalPath())
results = portal_catalog.searchResults({'path': {'query': folder_path}, 'portal_type': 'dmsmainfile'})
if results:
items.append(('previous', _('Previous Version')))
config = getConfiguration()
version_templates = os.path.join(config.zopehome, 'etc',
'version_templates', 'list.json')
if os.path.exists(version_templates):
templates = json.load(file(version_templates))
for entry in templates:
if entry.get('portal_types') and context.portal_type not in entry.get('portal_types'):
continue
items.append(('template-%s' % entry.get('filename'), entry.get('label')))
return SimpleVocabulary(make_terms(items))
class IAddVersion(model.Schema):
model.primary('file')
file = NamedBlobFileField(
title=_(u"File"),
required=False,
)
create_from = schema.Choice(
title=_(u'Create File From'),
required=True,
source=file_source)
label = schema.TextLine(
title=_(u'Label'),
required=False,
)
signed = schema.Bool(
title=_(u"Signed version"),
default=False)
class AddVersion(DefaultAddForm, form.AddForm):
grok.name('adddmsmainfile')
grok.context(IDmsDocument)
label = _(u'New version')
description = u''
schema = IAddVersion
portal_type = 'dmsmainfile'
def extractData(self):
data, errors = super(AddVersion, self).extractData()
if not errors:
if data.get('create_from') == 'upload' and not data.get('file'):
errors = (RequiredMissing('file'),)
return (data, errors)
def create(self, data):
fti = getUtility(IDexterityFTI, name=self.portal_type)
container = aq_inner(self.context)
content = createObject(fti.factory)
# Note: The factory may have done this already, but we want to be sure
# that the created type has the right portal type. It is possible
# to re-define a type through the web that uses the factory from an
# existing type, but wants a unique portal_type!
if hasattr(content, '_setPortalTypeName'):
content._setPortalTypeName(fti.getId())
# Acquisition wrap temporarily to satisfy things like vocabularies
# depending on tools
if IAcquirer.providedBy(content):
content = content.__of__(container)
content.signed = data.get('signed')
content.label = data.get('label')
if data.get('create_from') in (None, 'upload'):
content.file = data.get('file')
elif data.get('create_from') == 'previous':
portal_catalog = getToolByName(self.context , 'portal_catalog')
folder_path = '/'.join(self.context.getPhysicalPath())
results = portal_catalog.searchResults({'path': {'query': folder_path},
'portal_type': 'dmsmainfile',
'sort_on': 'getObjPositionInParent',
'sort_order': 'descending'})
previous_file = results[0].getObject().file
content.file = NamedBlobFile(previous_file.data,
filename=previous_file.filename)
elif data.get('create_from').startswith('template-'):
config = getConfiguration()
base_path = os.path.join(config.zopehome, 'etc', 'version_templates')
filename = os.path.realpath(os.path.join(base_path,
data.get('create_from')[9:]))
if not filename.startswith(base_path):
raise Exception('wrong template')
content.file = NamedBlobFile(file(filename).read(),
filename=data.get('create_from')[9:])
annotations = IAnnotations(container)
if 'higher_version' not in annotations:
content.title = u'1'
else:
content.title = unicode(annotations['higher_version'].value + 1)
for group in self.groups:
form.applyChanges(group, content, data)
return aq_base(content)