cubicweb/sobjects/notification.py
changeset 11057 0b59724cb3f2
parent 10702 f94c812c3669
child 11143 ebb6809659a4
equal deleted inserted replaced
11052:058bb3dc685f 11057:0b59724cb3f2
       
     1 # copyright 2003-2014 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
       
     2 # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
       
     3 #
       
     4 # This file is part of CubicWeb.
       
     5 #
       
     6 # CubicWeb is free software: you can redistribute it and/or modify it under the
       
     7 # terms of the GNU Lesser General Public License as published by the Free
       
     8 # Software Foundation, either version 2.1 of the License, or (at your option)
       
     9 # any later version.
       
    10 #
       
    11 # CubicWeb is distributed in the hope that it will be useful, but WITHOUT
       
    12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
       
    13 # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
       
    14 # details.
       
    15 #
       
    16 # You should have received a copy of the GNU Lesser General Public License along
       
    17 # with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
       
    18 """some views to handle notification on data changes"""
       
    19 
       
    20 __docformat__ = "restructuredtext en"
       
    21 from cubicweb import _
       
    22 
       
    23 from itertools import repeat
       
    24 
       
    25 from six import text_type
       
    26 
       
    27 from logilab.common.textutils import normalize_text
       
    28 from logilab.common.deprecation import class_renamed, class_moved, deprecated
       
    29 from logilab.common.registry import yes
       
    30 
       
    31 from cubicweb.entity import Entity
       
    32 from cubicweb.view import Component, EntityView
       
    33 from cubicweb.server.hook import SendMailOp
       
    34 from cubicweb.mail import construct_message_id, format_mail
       
    35 from cubicweb.server.session import Session, InternalManager
       
    36 
       
    37 
       
    38 class RecipientsFinder(Component):
       
    39     """this component is responsible to find recipients of a notification
       
    40 
       
    41     by default user's with their email set are notified if any, else the default
       
    42     email addresses specified in the configuration are used
       
    43     """
       
    44     __regid__ = 'recipients_finder'
       
    45     __select__ = yes()
       
    46     user_rql = ('Any X,E,A WHERE X is CWUser, X in_state S, S name "activated",'
       
    47                 'X primary_email E, E address A')
       
    48 
       
    49     def recipients(self):
       
    50         mode = self._cw.vreg.config['default-recipients-mode']
       
    51         if mode == 'users':
       
    52             execute = self._cw.execute
       
    53             dests = [(u.cw_adapt_to('IEmailable').get_email(),
       
    54                       u.property_value('ui.language'))
       
    55                      for u in execute(self.user_rql, build_descr=True).entities()]
       
    56         elif mode == 'default-dest-addrs':
       
    57             lang = self._cw.vreg.property_value('ui.language')
       
    58             dests = zip(self._cw.vreg.config['default-dest-addrs'], repeat(lang))
       
    59         else: # mode == 'none'
       
    60             dests = []
       
    61         return dests
       
    62 
       
    63 
       
    64 # abstract or deactivated notification views and mixin ########################
       
    65 
       
    66 
       
    67 class SkipEmail(Exception):
       
    68     """raise this if you decide to skip an email during its generation"""
       
    69 
       
    70 
       
    71 class NotificationView(EntityView):
       
    72     """abstract view implementing the "email" API (eg to simplify sending
       
    73     notification)
       
    74     """
       
    75     # XXX refactor this class to work with len(rset) > 1
       
    76 
       
    77     msgid_timestamp = True
       
    78 
       
    79     # to be defined on concrete sub-classes
       
    80     content = None # body of the mail
       
    81     message = None # action verb of the subject
       
    82 
       
    83     # this is usually the method to call
       
    84     def render_and_send(self, **kwargs):
       
    85         """generate and send email messages for this view"""
       
    86         # render_emails changes self._cw so cache it here so all mails are sent
       
    87         # after we commit our transaction.
       
    88         cnx = self._cw
       
    89         for msg, recipients in self.render_emails(**kwargs):
       
    90             SendMailOp(cnx, recipients=recipients, msg=msg)
       
    91 
       
    92     def cell_call(self, row, col=0, **kwargs):
       
    93         self.w(self._cw._(self.content) % self.context(**kwargs))
       
    94 
       
    95     def render_emails(self, **kwargs):
       
    96         """generate and send emails for this view (one per recipient)"""
       
    97         self._kwargs = kwargs
       
    98         recipients = self.recipients()
       
    99         if not recipients:
       
   100             self.info('skipping %s notification, no recipients', self.__regid__)
       
   101             return
       
   102         if self.cw_rset is not None:
       
   103             entity = self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0)
       
   104             # if the view is using timestamp in message ids, no way to reference
       
   105             # previous email
       
   106             if not self.msgid_timestamp:
       
   107                 refs = [self.construct_message_id(eid)
       
   108                         for eid in entity.cw_adapt_to('INotifiable').notification_references(self)]
       
   109             else:
       
   110                 refs = ()
       
   111             msgid = self.construct_message_id(entity.eid)
       
   112         else:
       
   113             refs = ()
       
   114             msgid = None
       
   115         req = self._cw
       
   116         self.user_data = req.user_data()
       
   117         for something in recipients:
       
   118             if isinstance(something, tuple):
       
   119                 emailaddr, lang = something
       
   120                 user = InternalManager(lang=lang)
       
   121             else:
       
   122                 emailaddr = something.cw_adapt_to('IEmailable').get_email()
       
   123                 user = something
       
   124             # hi-jack self._cw to get a session for the returned user
       
   125             session = Session(user, self._cw.repo)
       
   126             with session.new_cnx() as cnx:
       
   127                 self._cw = cnx
       
   128                 try:
       
   129                     # since the same view (eg self) may be called multiple time and we
       
   130                     # need a fresh stream at each iteration, reset it explicitly
       
   131                     self.w = None
       
   132                     try:
       
   133                         # XXX forcing the row & col here may make the content and
       
   134                         #     subject inconsistent because subject will depend on
       
   135                         #     self.cw_row & self.cw_col if they are set.
       
   136                         content = self.render(row=0, col=0, **kwargs)
       
   137                         subject = self.subject()
       
   138                     except SkipEmail:
       
   139                         continue
       
   140                     except Exception as ex:
       
   141                         # shouldn't make the whole transaction fail because of rendering
       
   142                         # error (unauthorized or such) XXX check it doesn't actually
       
   143                         # occurs due to rollback on such error
       
   144                         self.exception(str(ex))
       
   145                         continue
       
   146                     msg = format_mail(self.user_data, [emailaddr], content, subject,
       
   147                                       config=self._cw.vreg.config, msgid=msgid, references=refs)
       
   148                     yield msg, [emailaddr]
       
   149                 finally:
       
   150                     self._cw = req
       
   151 
       
   152     # recipients handling ######################################################
       
   153 
       
   154     def recipients(self):
       
   155         """return a list of either 2-uple (email, language) or user entity to
       
   156         whom this email should be sent
       
   157         """
       
   158         finder = self._cw.vreg['components'].select(
       
   159             'recipients_finder', self._cw, rset=self.cw_rset,
       
   160             row=self.cw_row or 0, col=self.cw_col or 0)
       
   161         return finder.recipients()
       
   162 
       
   163     # email generation helpers #################################################
       
   164 
       
   165     def construct_message_id(self, eid):
       
   166         return construct_message_id(self._cw.vreg.config.appid, eid,
       
   167                                     self.msgid_timestamp)
       
   168 
       
   169     def format_field(self, attr, value):
       
   170         return ':%(attr)s: %(value)s' % {'attr': attr, 'value': value}
       
   171 
       
   172     def format_section(self, attr, value):
       
   173         return '%(attr)s\n%(ul)s\n%(value)s\n' % {
       
   174             'attr': attr, 'ul': '-'*len(attr), 'value': value}
       
   175 
       
   176     def subject(self):
       
   177         entity = self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0)
       
   178         subject = self._cw._(self.message)
       
   179         etype = entity.dc_type()
       
   180         eid = entity.eid
       
   181         login = self.user_data['login']
       
   182         return self._cw._('%(subject)s %(etype)s #%(eid)s (%(login)s)') % locals()
       
   183 
       
   184     def context(self, **kwargs):
       
   185         entity = self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0)
       
   186         for key, val in kwargs.items():
       
   187             if val and isinstance(val, text_type) and val.strip():
       
   188                kwargs[key] = self._cw._(val)
       
   189         kwargs.update({'user': self.user_data['login'],
       
   190                        'eid': entity.eid,
       
   191                        'etype': entity.dc_type(),
       
   192                        'url': entity.absolute_url(__secure__=True),
       
   193                        'title': entity.dc_long_title(),})
       
   194         return kwargs
       
   195 
       
   196 
       
   197 class StatusChangeMixIn(object):
       
   198     __regid__ = 'notif_status_change'
       
   199     msgid_timestamp = True
       
   200     message = _('status changed')
       
   201     content = _("""
       
   202 %(user)s changed status from <%(previous_state)s> to <%(current_state)s> for entity
       
   203 '%(title)s'
       
   204 
       
   205 %(comment)s
       
   206 
       
   207 url: %(url)s
       
   208 """)
       
   209 
       
   210 
       
   211 ###############################################################################
       
   212 # Actual notification views.                                                  #
       
   213 #                                                                             #
       
   214 # disable them at the recipients_finder level if you don't want them          #
       
   215 ###############################################################################
       
   216 
       
   217 # XXX should be based on dc_title/dc_description, no?
       
   218 
       
   219 class ContentAddedView(NotificationView):
       
   220     """abstract class for notification on entity/relation
       
   221 
       
   222     all you have to do by default is :
       
   223     * set id and __select__ attributes to match desired events and entity types
       
   224     * set a content attribute to define the content of the email (unless you
       
   225       override call)
       
   226     """
       
   227     __abstract__ = True
       
   228     __regid__ = 'notif_after_add_entity'
       
   229     msgid_timestamp = False
       
   230     message = _('new')
       
   231     content = """
       
   232 %(title)s
       
   233 
       
   234 %(content)s
       
   235 
       
   236 url: %(url)s
       
   237 """
       
   238     # to be defined on concrete sub-classes
       
   239     content_attr = None
       
   240 
       
   241     def context(self, **kwargs):
       
   242         entity = self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0)
       
   243         content = entity.printable_value(self.content_attr, format='text/plain')
       
   244         if content:
       
   245             contentformat = getattr(entity, self.content_attr + '_format',
       
   246                                     'text/rest')
       
   247             # XXX don't try to wrap rest until we've a proper transformation (see
       
   248             # #103822)
       
   249             if contentformat != 'text/rest':
       
   250                 content = normalize_text(content, 80)
       
   251         return super(ContentAddedView, self).context(content=content, **kwargs)
       
   252 
       
   253     def subject(self):
       
   254         entity = self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0)
       
   255         return  u'%s #%s (%s)' % (self._cw.__('New %s' % entity.e_schema),
       
   256                                   entity.eid, self.user_data['login'])
       
   257 
       
   258 
       
   259 def format_value(value):
       
   260     if isinstance(value, text_type):
       
   261         return u'"%s"' % value
       
   262     return value
       
   263 
       
   264 
       
   265 class EntityUpdatedNotificationView(NotificationView):
       
   266     """abstract class for notification on entity/relation
       
   267 
       
   268     all you have to do by default is :
       
   269     * set id and __select__ attributes to match desired events and entity types
       
   270     * set a content attribute to define the content of the email (unless you
       
   271       override call)
       
   272     """
       
   273     __abstract__ = True
       
   274     __regid__ = 'notif_entity_updated'
       
   275     msgid_timestamp = True
       
   276     message = _('updated')
       
   277     no_detailed_change_attrs = ()
       
   278     content = """
       
   279 Properties have been updated by %(user)s:
       
   280 
       
   281 %(changes)s
       
   282 
       
   283 url: %(url)s
       
   284 """
       
   285 
       
   286     def context(self, changes=(), **kwargs):
       
   287         context = super(EntityUpdatedNotificationView, self).context(**kwargs)
       
   288         _ = self._cw._
       
   289         formatted_changes = []
       
   290         entity = self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0)
       
   291         for attr, oldvalue, newvalue in sorted(changes):
       
   292             # check current user has permission to see the attribute
       
   293             rschema = self._cw.vreg.schema[attr]
       
   294             if rschema.final:
       
   295                 rdef = entity.e_schema.rdef(rschema)
       
   296                 if not rdef.has_perm(self._cw, 'read', eid=self.cw_rset[0][0]):
       
   297                     continue
       
   298             # XXX suppose it's a subject relation...
       
   299             elif not rschema.has_perm(self._cw, 'read',
       
   300                                       fromeid=self.cw_rset[0][0]):
       
   301                 continue
       
   302             if attr in self.no_detailed_change_attrs:
       
   303                 msg = _('%s updated') % _(attr)
       
   304             elif oldvalue not in (None, ''):
       
   305                 msg = _('%(attr)s updated from %(oldvalue)s to %(newvalue)s') % {
       
   306                     'attr': _(attr),
       
   307                     'oldvalue': format_value(oldvalue),
       
   308                     'newvalue': format_value(newvalue)}
       
   309             else:
       
   310                 msg = _('%(attr)s set to %(newvalue)s') % {
       
   311                     'attr': _(attr), 'newvalue': format_value(newvalue)}
       
   312             formatted_changes.append('* ' + msg)
       
   313         if not formatted_changes:
       
   314             # current user isn't allowed to see changes, skip this notification
       
   315             raise SkipEmail()
       
   316         context['changes'] = '\n'.join(formatted_changes)
       
   317         return context
       
   318 
       
   319     def subject(self):
       
   320         entity = self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0)
       
   321         return  u'%s #%s (%s)' % (self._cw.__('Updated %s' % entity.e_schema),
       
   322                                   entity.eid, self.user_data['login'])