Blame view

product/ERP5/Tool/NotificationTool.py 18.3 KB
Nicolas Delaby committed
1
# -*- coding: utf-8 -*-
Jean-Paul Smets committed
2 3
##############################################################################
#
Łukasz Nowak committed
4
# Copyright (c) 2004-2009 Nexedi SA and Contributors. All Rights Reserved.
Jean-Paul Smets committed
5 6 7
#                    Sebastien Robin <seb@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
Łukasz Nowak committed
8
# programmers who take the whole responsibility of assessing all potential
Jean-Paul Smets committed
9 10
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
Łukasz Nowak committed
11
# guarantees and support are strongly advised to contract a Free Software
Jean-Paul Smets committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################
from AccessControl import ClassSecurityInfo
30
from Products.ERP5Type.Globals import DTMLFile
Jean-Paul Smets committed
31 32 33
from Products.CMFCore.utils import getToolByName
from Products.ERP5Type.Tool.BaseTool import BaseTool
from Products.ERP5Type import Permissions
Nicolas Delaby committed
34
from AccessControl import ModuleSecurityInfo
Jérome Perrin committed
35
from zExceptions import Unauthorized
Jean-Paul Smets committed
36 37
from Products.ERP5 import _dtmldir

Jean-Paul Smets committed
38
from mimetypes import guess_type
Julien Muchembled committed
39 40 41 42 43
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
Jérome Perrin committed
44
from email.utils import formataddr
Julien Muchembled committed
45 46
from email.header import make_header
from email import encoders
Jean-Paul Smets committed
47

Kazuhiko Shiozaki committed
48 49
class ConversionError(Exception): pass
class MimeTypeException(Exception): pass
Jean-Paul Smets committed
50

Nicolas Delaby committed
51 52 53
security = ModuleSecurityInfo('Products.ERP5.Tool.NotificationTool')
security.declarePublic('buildEmailMessage',)

Yusei Tahara committed
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
def buildAttachmentDictList(document_list, document_type_list=()):
  """return a list of dictionary which will be used by buildEmailMessage"""
  attachment_list = []
  for attachment in document_list:
    mime_type = None
    content = None
    name = None
    if not attachment.getPortalType() in document_type_list:
      mime_type = 'application/pdf'
      content = attachment.asPDF() # XXX - Not implemented yet
    else:
      #
      # Document type attachment
      #

      # WARNING - this could fail since getContentType
      # is not (yet) part of Document API
      if getattr(attachment, 'getContentType', None) is not None:
        mime_type = attachment.getContentType()
      else:
        raise ValueError, "Cannot find mimetype of the document."

      if mime_type is not None:
        try:
          mime_type, content = attachment.convert(mime_type)
        except ConversionError:
          mime_type = attachment.getBaseContentType()
          content = attachment.getBaseData()
        except (NotImplementedError, MimeTypeException):
          pass

      if content is None:
        if getattr(attachment, 'getTextContent', None) is not None:
          content = attachment.getTextContent()
        elif getattr(attachment, 'getData', None) is not None:
          content = attachment.getData()
        elif getattr(attachment, 'getBaseData', None) is not None:
          content = attachment.getBaseData()

    if not isinstance(content, str):
      content = str(content)

    attachment_list.append({'mime_type':mime_type,
                            'content':content,
Nicolas Delaby committed
98
                            'name':attachment.getStandardFilename()}
Yusei Tahara committed
99 100 101 102
                           )
  return attachment_list


Jean-Paul Smets committed
103 104
def buildEmailMessage(from_url, to_url, msg=None,
                      subject=None, attachment_list=None,
Yusei Tahara committed
105 106
                      extra_headers=None,
                      additional_headers=None):
Jean-Paul Smets committed
107 108 109 110
  """
    Builds a mail message which is ready to be
    sent by Zope MailHost.

Łukasz Nowak committed
111
    * attachment_list is a list of dictionaries with those keys:
Jean-Paul Smets committed
112 113 114
     - name : name of the attachment,
     - content: data of the attachment
     - mime_type: mime-type corresponding to the attachment
Łukasz Nowak committed
115
    * extra_headers is a dictionary of custom headers to add to the email.
Jean-Paul Smets committed
116
      "X-" prefix is automatically added to those headers.
Yusei Tahara committed
117
    * additional_headers is similar to extra_headers, but no prefix is added.
Jean-Paul Smets committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131
  """

  if attachment_list == None:
    # Create non multi-part MIME message.
    message = MIMEText(msg, _charset='utf-8')
    attachment_list = []
  else:
    # Create multi-part MIME message.
    message = MIMEMultipart()
    message.preamble = "If you can read this, your mailreader\n" \
                        "can not handle multi-part messages!\n"
    message.attach(MIMEText(msg, _charset='utf-8'))

  if extra_headers:
Yusei Tahara committed
132 133 134 135 136 137
    for key, value in extra_headers.items():
      message.add_header('X-%s' % key, value)

  if additional_headers:
    for key, value in additional_headers.items():
      message.add_header(key, value)
Jean-Paul Smets committed
138

Julien Muchembled committed
139 140 141 142 143 144 145
  if subject:
    message.add_header('Subject',
                        make_header([(subject, 'utf-8')]).encode())
  if from_url:
    message.add_header('From', from_url)
  if to_url:
    message.add_header('To', to_url)
Jean-Paul Smets committed
146 147

  for attachment in attachment_list:
Julien Muchembled committed
148 149
    attachment_name = attachment.get('name', '')

Jean-Paul Smets committed
150 151
    # try to guess the mime type
    if not attachment.has_key('mime_type'):
Jérome Perrin committed
152 153 154
      mime_type, encoding = guess_type( attachment_name )
      if mime_type is not None:
        attachment['mime_type'] = mime_type
Jean-Paul Smets committed
155 156 157 158 159 160 161
      else:
        attachment['mime_type'] = 'application/octet-stream'

    # attach it
    if attachment['mime_type'] == 'text/plain':
      part = MIMEText(attachment['content'], _charset='utf-8')
    else:
Yusei Tahara committed
162 163 164 165 166 167 168 169
      major, minor = attachment['mime_type'].split('/', 1)
      if major == 'text':
        part = MIMEText(attachment['content'], _subtype=minor)
      elif major == 'image':
        part = MIMEImage(attachment['content'], _subtype=minor)
      elif major == 'audio':
        part = MIMEAudio(attachment['content'], _subtype=minor)
      else:
Gabriel Monnerat committed
170
        #  encode non-plaintext attachment in base64
Yusei Tahara committed
171 172
        part = MIMEBase(major, minor)
        part.set_payload(attachment['content'])
Julien Muchembled committed
173
        encoders.encode_base64(part)
Jean-Paul Smets committed
174

Julien Muchembled committed
175 176
    part.add_header('Content-Disposition', 'attachment',
                    filename=attachment_name)
Romain Courteaud committed
177 178
    part.add_header('Content-ID', '<%s>' % \
                    ''.join(['%s' % ord(i) for i in attachment_name]))
Jean-Paul Smets committed
179 180 181 182
    message.attach(part)

  return message

Yusei Tahara committed
183

Jean-Paul Smets committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
class NotificationTool(BaseTool):
  """
    This tool manages notifications.

    It is used as a central point to send messages from one
    user to one or many users. The purpose of the tool
    is to provide an API for sending messages which is
    independent on how messages are actually going to be
    sent and when.

    It is also useful to send messages without having to
    write always the same piece of code (eg. lookup the user,
    lookup its mail, etc.).

    This early implementation only provides asynchronous
    email sending.

    Future implementations may be able to lookup user preferences
    to decide how and when to send a message to each user.
  """
  id = 'portal_notifications'
  meta_type = 'ERP5 Notification Tool'
  portal_type = 'Notification Tool'

  # Declarative Security
  security = ClassSecurityInfo()

  security.declareProtected( Permissions.ManagePortal, 'manage_overview' )
  manage_overview = DTMLFile( 'explainNotificationTool', _dtmldir )

Yusei Tahara committed
214
  # low-level interface
Yusei Tahara committed
215
  def _sendEmailMessage(self, from_url, to_url, body=None, subject=None,
Yusei Tahara committed
216 217
                        attachment_list=None, extra_headers=None,
                        additional_headers=None, debug=False):
Yusei Tahara committed
218 219 220 221 222 223 224 225 226 227 228 229 230
    portal = self.getPortalObject()
    mailhost = getattr(portal, 'MailHost', None)
    if mailhost is None:
      raise ValueError, "Can't find MailHost."
    message = buildEmailMessage(from_url, to_url, msg=body, subject=subject,
                                attachment_list=attachment_list, extra_headers=extra_headers,
                                additional_headers=additional_headers)

    if debug:
      return message.as_string()

    mailhost.send(messageText=message.as_string(), mto=to_url, mfrom=from_url)

Yusei Tahara committed
231
  # high-level interface
Jean-Paul Smets committed
232
  security.declareProtected(Permissions.UseMailhostServices, 'sendMessage')
Yusei Tahara committed
233
  def sendMessage(self, sender=None, recipient=None, subject=None,
Yusei Tahara committed
234 235
                  message=None,
                  attachment_list=None, attachment_document_list=None,
Yusei Tahara committed
236 237
                  notifier_list=None, priority_level=None,
                  store_as_event=False,
Jérome Perrin committed
238
                  check_consistency=False,
Yusei Tahara committed
239
                  message_text_format='text/plain',
Nicolas Delaby committed
240
                  event_keyword_argument_dict=None,
Jérome Perrin committed
241 242
                  portal_type_list=None,
                  REQUEST=None):
Jean-Paul Smets committed
243
    """
Yusei Tahara committed
244
      This method provides a common API to send messages to erp5 users
Łukasz Nowak committed
245
      from object actions of workflow scripts.
Jean-Paul Smets committed
246

Yusei Tahara committed
247
      Note that you can't send message to person who don't have his own Person document.
Yusei Tahara committed
248 249
      This method provides only high-level functionality so that you can't use email address
      for sender and recipient, or raw data for attachments.
Jean-Paul Smets committed
250

Vincent Pelletier committed
251
      sender -- a user id or a user document
Yusei Tahara committed
252

Vincent Pelletier committed
253
      recipient -- a user id or a user document, or a list thereof
Jean-Paul Smets committed
254 255 256 257 258

      subject -- the subject of the message

      message -- the text of the message (already translated)

Yusei Tahara committed
259 260 261 262
      attachment_list -- list of dictionary which contains raw data and
                         name and mimetype for attachment.
                         See buildEmailMessage.

Yusei Tahara committed
263 264
      attachment_document_list -- list of document (optional)
                                  which will be attachment.
Jean-Paul Smets committed
265

Jean-Paul Smets committed
266 267 268
      priority_level -- a priority level which is used to
                        lookup user preferences and decide
                        which notifier to use
Yusei Tahara committed
269
                        XXX Not implemented yet!!
Jean-Paul Smets committed
270 271 272 273

      notifier_list -- a list of portal type names to use
                       to send the event

Yusei Tahara committed
274 275 276
      store_as_event -- whenever CRM is available, store
                        notifications as events

Jérome Perrin committed
277 278 279 280 281 282 283
      check_consistency -- Check that the created events match their constraints.
                           If any of the event have an unsatisified constraint, a
                           ValueError is raised.
                           Note that if `store_as_event` is true, some draft
                           events are created anyway, so caller may want to
                           abort transaction.

Yusei Tahara committed
284 285
      event_keyword_argument_dict -- additional keyword arguments which is used for
                                     constructor of event document.
Jean-Paul Smets committed
286

Jean-Paul Smets committed
287
    TODO: support default notification email
Jean-Paul Smets committed
288
    """
Jérome Perrin committed
289 290
    if REQUEST is not None:
      raise Unauthorized()
Yusei Tahara committed
291
    portal = self.getPortalObject()
Vincent Pelletier committed
292 293
    searchUsers = self.acl_users.searchUsers
    def getUserValueByUserId(user_id):
Sebastien Robin committed
294 295
      user, = [x for x in searchUsers(id=user_id, exact_match=True,
               login_portal_type=portal.getPortalLoginTypeList()) if 'path' in x]
Jérome Perrin committed
296
      return portal.unrestrictedTraverse(user['path'])
Jérome Perrin committed
297 298 299 300 301 302 303 304

    if notifier_list is None:
      # XXX TODO: Use priority_level. Need to implement default notifier query system.
      # XXX       For now, we use 'Mail Message'.
      notifier_list = ['Mail Message']
    if not isinstance(notifier_list, (tuple, list)):
      raise TypeError("Notifier list must be a list of portal types")

Jérome Perrin committed
305 306 307
    if not subject:
      raise TypeError("subject is required")

Yusei Tahara committed
308 309
    # Find "From" Person
    from_person = None
Jean-Paul Smets committed
310
    if isinstance(sender, basestring):
Vincent Pelletier committed
311
      sender = getUserValueByUserId(sender)
Jean-Paul Smets committed
312 313
    if sender is not None:
      email_value = sender.getDefaultEmailValue()
Yusei Tahara committed
314 315 316 317 318
      if email_value is not None and email_value.asText():
        from_person = sender

    # Find "To" Person list
    to_person_list = []
Vincent Pelletier committed
319 320 321
    # XXX: evaluating a document as boolean is bad, as __bool__ may be
    # overloaded to (for example) return False if there are no children (which
    # would have unintended effects here).
Yusei Tahara committed
322
    if recipient:
Yusei Tahara committed
323
      if not isinstance(recipient, (list, tuple)):
Vincent Pelletier committed
324
        recipient = (recipient, )
Nicolas Delaby committed
325 326
      for person in recipient:
        if isinstance(person, basestring):
Vincent Pelletier committed
327
          person_value = getUserValueByUserId(person)
Nicolas Delaby committed
328
          if person_value is None:
Vincent Pelletier committed
329
            raise ValueError("Can't find user with id %r" % (person, ))
Jérome Perrin committed
330
          person = person_value
Yusei Tahara committed
331 332
        to_person_list.append(person)

Yusei Tahara committed
333 334 335 336 337
    # prepare low-level arguments if needed.
    low_level_kw = {}
    default_from_email = portal.email_from_address
    default_to_email = getattr(portal, 'email_to_address',
                               default_from_email)
Łukasz Nowak committed
338 339
    default_from_name = portal.title
    default_from_name = getattr(portal, 'email_from_name', default_from_name)
Yusei Tahara committed
340
    if from_person is None:
Łukasz Nowak committed
341
      # when sending without sender defined compose identifiable From header
Jérome Perrin committed
342
      low_level_kw['from_url'] = formataddr((default_from_name, default_from_email))
Yusei Tahara committed
343
    if not to_person_list:
Yusei Tahara committed
344
      low_level_kw['to_url'] = default_to_email
Yusei Tahara committed
345 346
    if attachment_list is not None:
      low_level_kw['attachment_list'] = attachment_list
Yusei Tahara committed
347 348 349 350 351 352 353

    # Make event
    available_notifier_list = self.getNotifierList()
    event_list = []
    if event_keyword_argument_dict is None:
      event_keyword_argument_dict = {}
    for notifier in notifier_list:
Jérome Perrin committed
354
      if notifier in available_notifier_list:
Jérome Perrin committed
355
        event = portal.getDefaultModule(notifier).newContent(portal_type=notifier,
Jérome Perrin committed
356
                                                           temp_object=not store_as_event,
Yusei Tahara committed
357 358
                                                           **event_keyword_argument_dict)
      else:
Jérome Perrin committed
359 360 361 362 363 364 365
        # portal type does not exist, likely erp5_crm is not installed. Try to
        # import the class with the same name.
        from Products.ERP5Type import Document as document_module
        constructor = getattr(document_module,
          'newTemp%s' % notifier.replace(' ', ''))
        event = constructor(self, '_', **event_keyword_argument_dict)

Yusei Tahara committed
366 367 368
      event.setSourceValue(from_person)
      event.setDestinationValueList(to_person_list)
      event.setTitle(subject)
Nicolas Delaby committed
369
      event.setContentType(message_text_format)
Yusei Tahara committed
370 371 372
      event.setTextContent(message)
      event.setAggregateValueList(attachment_document_list)
      event_list.append(event)
Yusei Tahara committed
373

Jérome Perrin committed
374 375 376 377 378 379
    if check_consistency:
      for event in event_list:
        constraint_message_list = event.checkConsistency()
        if constraint_message_list:
          raise ValueError(constraint_message_list)

Yusei Tahara committed
380
    for event in event_list:
Romain Courteaud committed
381
      if event.isTempObject() or (not portal.portal_workflow.isTransitionPossible(event, 'start')):
Jérome Perrin committed
382 383 384
        event.send(**low_level_kw)
      else:
        event.start(**low_level_kw)
Yusei Tahara committed
385

Jean-Paul Smets committed
386
    return
Łukasz Nowak committed
387
    # Future implementation could consist in implementing
Jean-Paul Smets committed
388 389
    # policies such as grouped notification (per hour, per day,
    # per week, etc.) depending on user preferences. It
Jean-Paul Smets committed
390
    # also add some priority and selection of notification
Ivan Tyagov committed
391
    # tool (ex SMS vs. email)
Jean-Paul Smets committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409

    # Here is a sample code of how this implementation could look like
    # (pseudo code)
    # NOTE: this implementation should also make sure that the current
    # buildEmailMessage method defined here and the Event.send method
    # are merged once for all

    if self.getNotifierList():
      # CRM is installed - so we can lookup notification preferences
      if notifier_list is None:
        # Find which notifier to use on preferences
        if priority_level not in ('low', 'medium', 'high'): # XXX Better naming required here
          priority_level = 'high'
        notifier_list = self.preferences.getPreference(
              'preferred_%s_priority_nofitier_list' % priority_level)
      event_list = []
      for notifier in notifier_list:
        event_module = self.getDefaultModule(notifier)
Yusei Tahara committed
410
        new_event = event_module.newContent(portal_type=notifier, temp_object=store_as_event)
Jean-Paul Smets committed
411 412 413 414 415
        event_list.append(new_event)
    else:
      # CRM is not installed - only notification by email is possible
      # So create a temp object directly
      from Products.ERP5Type.Document import newTempEvent
Jérome Perrin committed
416
      new_event = newTempEvent(self, '_')
Jean-Paul Smets committed
417 418 419 420 421 422 423 424 425 426 427
      event_list = [new_event]

    if event in event_list:
      # We try to build events using the same parameters as the one
      # we were provided for notification.
      # The handling of attachment is still an open question:
      # either use relation (to prevent duplication) or keep
      # a copy inside. It is probably a good idea to
      # make attachment_list polymorphic in order to be able
      # to provide different kinds of attachments can be provided
      # Either document references or binary data.
Gabriel Monnerat committed
428
      event.build(sender=sender, recipient=recipient, subject=subject,
Jean-Paul Smets committed
429 430 431 432 433 434
                  message=message, attachment_list=attachment_list,) # Rename here and add whatever
                                                                     # parameter makes sense such
                                                                     # as text format
      event.send() # Make sure workflow transition is invoked if this is
                   # a persistent notification

Jean-Paul Smets committed
435 436 437 438 439 440 441
      # Aggregation could be handled by appending the notification
      # to an existing message rather than creating a new one.
      # Sending the message should be handled by the alarm based
      # on a date value stored on the event. This probably required
      # a new workflow state to represent events which are waiting
      # for being sent automatically. (ie. scheduled sending)

Jean-Paul Smets committed
442 443 444 445 446 447 448
  security.declareProtected(Permissions.AccessContentsInformation, 'getNotifierList')
  def getNotifierList(self):
    """
      Returns the list of available notifiers. For now
      we consider that any event is a potential notifier.
      This could change though.
    """
Yusei Tahara committed
449
    return self.getPortalEventTypeList()
Nicolas Delaby committed
450

Nicolas Delaby committed
451
  security.declareProtected(Permissions.AccessContentsInformation, 'getDocumentValue')
Nicolas Delaby committed
452 453 454 455 456 457 458 459 460
  def getDocumentValue(self, **kw):
    """
      Returns the last version of a Notification Document in selected Language.
    """
    method = self._getTypeBasedMethod('getDocumentValue')
    return method(**kw)

  def __call__(self, *args, **kw):
    return self.sendMessage(*args, **kw)