summaryrefslogtreecommitdiffstats
path: root/src/collective/dms/batchimport/fileimporter.py
blob: 3af748b3982b6f474bdb0d8d557111c0126a5b60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# -*- coding: utf8 -*-

import logging
import os
import os.path

from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from zope import schema

from zope.component import queryUtility
from five import grok
from Products.CMFPlone.interfaces import IPloneSiteRoot
from Products.CMFCore.utils import getToolByName

import z3c.form.button
from plone import api
from plone.directives import form
from plone.i18n.normalizer.interfaces import IIDNormalizer

from plone.namedfile.field import NamedFile, NamedBlobFile

from . import _
from . import utils

log = logging.getLogger('collective.dms.batchimport')

class IImportFileFormSchema(form.Schema):
    file = NamedBlobFile(title=_(u"File"))

    title = schema.Text(required=False)
    portal_type = schema.Text(required=False)
    location = schema.Text(required=False)
    owner = schema.Text(required=False)
    treating_groups = schema.Text(required=False)  # new, comme separated identifiers
    recipient_groups = schema.Text(required=False)  # new, comme separated identifiers
    keywords = schema.Text(required=False)  # comma separated identifiers

    notification_recipients = schema.Text(required=False)  # comma separated emails

    # legacy
    treating_group = schema.Text(required=False)


class ImportFileForm(form.SchemaForm):
    schema = IImportFileFormSchema

    # Permission required to
    grok.require("cmf.ManagePortal")

    ignoreContext = True

    grok.context(IPloneSiteRoot)

    # appear as @@fileimport view
    grok.name("fileimport")

    def get_folder(self, foldername):
        folder = getToolByName(self.context, 'portal_url').getPortalObject()
        for part in foldername.split('/'):
            if not part:
                continue
            folder = getattr(folder, part)
        return folder

    def convertTitleToId(self, title):
        """Plug into plone's id-from-title machinery.
        """
        #title = title.decode('utf-8')
        newid = queryUtility(IIDNormalizer).normalize(title)
        return newid

    @z3c.form.button.buttonAndHandler(_('Import'), name='import')
    def import_file(self, action):
        # Extract form field values and errors from HTTP request
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        portal_type = data['portal_type']
        filename = data['file'].filename
        owner = data['owner']
        if data['treating_group']:  # legacy
            treating_groups = set([data['treating_group']])
        else:
            treating_groups = set([x.strip() for x in (data['treating_groups'] or '').split(',')])

        recipient_groups = set([x.strip() for x in (data['recipient_groups'] or '').split(',')])

        folder = self.get_folder(data['location'])
        keywords = set([x.strip() for x in (data['keywords'] or '').split(',')])

        document_id = self.convertTitleToId(data.get('title') or os.path.splitext(filename)[0])

        utils.createDocument(self, folder, portal_type, document_id,
                filename, data['file'], owner,
                treating_groups=treating_groups,
                recipient_groups=recipient_groups,
                metadata={
                    'title': data.get('title'),
                    'keywords': keywords,
                    })

        if data.get('notification_recipients'):
            document_location = self.request.response.headers['location']
            subject = 'Nouveau document, %s' % data.get('title')
            message = 'Ouvrir dans la GED :\n  %s\n' % document_location
            recipients = data.get('notification_recipients').split(',')
            self.send_message(subject, message, recipients)

    def send_message(self, subject, message, recipients):
        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['To'] = ', '.join(recipients)
        msg['From'] = api.portal.get().getProperty('email_from_address') or 'admin@localhost'

        msg.attach(MIMEText(message, _charset='utf-8'))
        self.context.MailHost.send(msg.as_string())