NotificationTool.py 17.3 KB
Newer Older
1 2
##############################################################################
#
Łukasz Nowak's avatar
Łukasz Nowak committed
3
# Copyright (c) 2004-2009 Nexedi SA and Contributors. All Rights Reserved.
4 5 6
#                    Sebastien Robin <seb@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
Łukasz Nowak's avatar
Łukasz Nowak committed
7
# programmers who take the whole responsibility of assessing all potential
8 9
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
Łukasz Nowak's avatar
Łukasz Nowak committed
10
# guarantees and support are strongly advised to contract a Free Software
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 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
29
from Products.ERP5Type.Globals import DTMLFile
30 31 32
from Products.CMFCore.utils import getToolByName
from Products.ERP5Type.Tool.BaseTool import BaseTool
from Products.ERP5Type import Permissions
33
from AccessControl import ModuleSecurityInfo
34 35
from Products.ERP5 import _dtmldir

36 37 38 39
from mimetypes import guess_type
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
40 41
from email.MIMEAudio import MIMEAudio
from email.MIMEImage import MIMEImage
42 43 44
from email.Header import make_header
from email import Encoders

45 46
class ConversionError(Exception): pass
class MimeTypeException(Exception): pass
47

48 49 50
security = ModuleSecurityInfo('Products.ERP5.Tool.NotificationTool')
security.declarePublic('buildEmailMessage',)

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
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()
      elif getattr(attachment, 'getTextFormat', None) is not None:
        mime_type = attachment.getTextFormat()
      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,
                            'name':attachment.getReference()}
                           )
  return attachment_list


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

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

  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:
131 132 133 134 135 136
    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)
137 138 139 140 141 142 143

  message.add_header('Subject',
                      make_header([(subject, 'utf-8')]).encode())
  message.add_header('From', from_url)
  message.add_header('To', to_url)

  for attachment in attachment_list:
144 145
    attachment_name = attachment.get('name', '')

146 147 148 149 150 151 152 153 154 155 156 157
    # try to guess the mime type
    if not attachment.has_key('mime_type'):
      type, encoding = guess_type( attachment_name )
      if type != None:
        attachment['mime_type'] = type
      else:
        attachment['mime_type'] = 'application/octet-stream'

    # attach it
    if attachment['mime_type'] == 'text/plain':
      part = MIMEText(attachment['content'], _charset='utf-8')
    else:
158 159 160 161 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:
        #  encode non-plaintext attachment in base64      
        part = MIMEBase(major, minor)
        part.set_payload(attachment['content'])
        Encoders.encode_base64(part)
170

171 172
    part.add_header('Content-Disposition', 'attachment',
                    filename=attachment_name)
173 174
    part.add_header('Content-ID', '<%s>' % \
                    ''.join(['%s' % ord(i) for i in attachment_name]))
175 176 177 178
    message.attach(part)

  return message

179

180 181 182 183 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
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 )

210
  # low-level interface
211
  def _sendEmailMessage(self, from_url, to_url, body=None, subject=None,
212 213
                        attachment_list=None, extra_headers=None,
                        additional_headers=None, debug=False):
214 215 216 217 218 219 220 221 222 223 224 225 226
    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)

227
  # high-level interface
228
  security.declareProtected(Permissions.UseMailhostServices, 'sendMessage')
229
  def sendMessage(self, sender=None, recipient=None, subject=None,
Yusei Tahara's avatar
Yusei Tahara committed
230 231
                  message=None,
                  attachment_list=None, attachment_document_list=None,
232 233 234
                  notifier_list=None, priority_level=None,
                  store_as_event=False,
                  message_text_format='text/plain',
Nicolas Delaby's avatar
Nicolas Delaby committed
235 236
                  event_keyword_argument_dict=None,
                  portal_type_list=None):
237
    """
Yusei Tahara's avatar
Yusei Tahara committed
238
      This method provides a common API to send messages to erp5 users
Łukasz Nowak's avatar
Łukasz Nowak committed
239
      from object actions of workflow scripts.
240

Yusei Tahara's avatar
Yusei Tahara committed
241
      Note that you can't send message to person who don't have his own Person document.
242 243
      This method provides only high-level functionality so that you can't use email address
      for sender and recipient, or raw data for attachments.
244

Yusei Tahara's avatar
Yusei Tahara committed
245 246 247
      sender -- a login name(reference of Person document) or a Person document

      recipient -- a login name(reference of Person document) or a Person document,
248 249 250 251 252 253
                   a list of thereof

      subject -- the subject of the message

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

Yusei Tahara's avatar
Yusei Tahara committed
254 255 256 257
      attachment_list -- list of dictionary which contains raw data and
                         name and mimetype for attachment.
                         See buildEmailMessage.

258 259
      attachment_document_list -- list of document (optional)
                                  which will be attachment.
260

261 262 263
      priority_level -- a priority level which is used to
                        lookup user preferences and decide
                        which notifier to use
264
                        XXX Not implemented yet!!
265 266 267 268

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

269 270 271 272 273
      store_as_event -- whenever CRM is available, store
                        notifications as events

      event_keyword_argument_dict -- additional keyword arguments which is used for
                                     constructor of event document.
274

Nicolas Delaby's avatar
Nicolas Delaby committed
275 276
      portal_type_list -- Portal Type of Users

277
    TODO: support default notification email
278
    """
Yusei Tahara's avatar
Yusei Tahara committed
279
    portal = self.getPortalObject()
280
    catalog_tool = getToolByName(self, 'portal_catalog')
Nicolas Delaby's avatar
Nicolas Delaby committed
281 282
    if portal_type_list is None:
      portal_type_list = ('Person',)
283 284
    # Find "From" Person
    from_person = None
285
    if isinstance(sender, basestring):
Nicolas Delaby's avatar
Nicolas Delaby committed
286 287
      sender = catalog_tool.getResultValue(portal_type=portal_type_list,
                                           reference=sender)
288 289
    if sender is not None:
      email_value = sender.getDefaultEmailValue()
290 291 292 293 294 295
      if email_value is not None and email_value.asText():
        from_person = sender

    # Find "To" Person list
    to_person_list = []
    if recipient:
Yusei Tahara's avatar
Yusei Tahara committed
296 297
      if not isinstance(recipient, (list, tuple)):
        recipient = (recipient,)
298 299 300 301 302
      for person in recipient:
        if isinstance(person, basestring):
          person_value = catalog_tool.getResultValue(portal_type=portal_type_list,
                                                     reference=person)
          if person_value is None:
Yusei Tahara's avatar
Yusei Tahara committed
303
            # For backward compatibility. I recommend to use ValueError.(yusei)
304 305 306
            raise IndexError, "Can't find person document which reference is '%s'" % person
          else:
            person = person_value
Yusei Tahara's avatar
Yusei Tahara committed
307 308 309 310
        email_value = person.getDefaultEmailValue()
        if email_value is None:
          # For backward compatibility. I recommend to use ValueError.(yusei)
          raise AttributeError, "Can't find default email address of %s" % person.getRelativeUrl()
311 312 313 314
        if not email_value.asText():
          raise AttributeError, "Default email address of %s is empty" % person.getRelativeUrl()
        to_person_list.append(person)

315 316 317 318 319
    # 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)
320 321
    default_from_name = portal.title
    default_from_name = getattr(portal, 'email_from_name', default_from_name)
322
    if from_person is None:
323 324 325
      # when sending without sender defined compose identifiable From header
      low_level_kw['from_url'] = '%s <%s>' % (default_from_name,
          default_from_email)
326
    if not to_person_list:
327
      low_level_kw['to_url'] = default_to_email
Yusei Tahara's avatar
Yusei Tahara committed
328 329
    if attachment_list is not None:
      low_level_kw['attachment_list'] = attachment_list
330 331 332 333 334 335

    # Make event
    available_notifier_list = self.getNotifierList()
    event_list = []
    if notifier_list is None:
      # XXX TODO: Use priority_level. Need to implement default notifier query system.
Łukasz Nowak's avatar
Łukasz Nowak committed
336
      # XXX       For now, we use 'Mail Message'.
337 338 339 340 341 342 343 344 345
      notifier_list = ['Mail Message']
    if event_keyword_argument_dict is None:
      event_keyword_argument_dict = {}
    for notifier in notifier_list:
      if notifier in available_notifier_list and store_as_event:
        event = self.getDefaultModule(notifier).newContent(portal_type=notifier,
                                                           **event_keyword_argument_dict)
      else:
        from Products.ERP5Type.Document import newTempEvent
346
        event = newTempEvent(self, '_',
347 348 349 350 351 352 353 354
                             **event_keyword_argument_dict)
      event.setSourceValue(from_person)
      event.setDestinationValueList(to_person_list)
      event.setTitle(subject)
      event.setTextFormat(message_text_format)
      event.setTextContent(message)
      event.setAggregateValueList(attachment_document_list)
      event_list.append(event)
355 356

    portal_workflow = getToolByName(self, 'portal_workflow')
357
    for event in event_list:
358
      event.send(**low_level_kw)
359

360
    return
Łukasz Nowak's avatar
Łukasz Nowak committed
361
    # Future implementation could consist in implementing
362 363
    # policies such as grouped notification (per hour, per day,
    # per week, etc.) depending on user preferences. It
364
    # also add some priority and selection of notification
365
    # tool (ex SMS vs. email)
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

    # 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)
384
        new_event = event_module.newContent(portal_type=notifier, temp_object=store_as_event)
385 386 387 388 389
        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's avatar
Jérome Perrin committed
390
      new_event = newTempEvent(self, '_')
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
      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.
      event.build(sender=sender, recipient=recipient, subject=subject, 
                  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's avatar
Jean-Paul Smets committed
409 410 411 412 413 414 415
      # 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)

416 417 418 419 420 421 422
  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's avatar
Yusei Tahara committed
423
    return self.getPortalEventTypeList()
424 425 426 427 428 429 430 431 432 433

  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)