author | sylvain.thenault@logilab.fr |
Fri, 24 Apr 2009 19:46:40 +0200 | |
branch | tls-sprint |
changeset 1483 | 1367efbcd6a5 |
parent 1477 | b056a49c16dc |
child 1723 | 30c3a713ab61 |
permissions | -rw-r--r-- |
0 | 1 |
"""some hooks and views to handle notification on entity's changes |
2 |
||
3 |
:organization: Logilab |
|
633 | 4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
6 |
""" |
|
7 |
__docformat__ = "restructuredtext en" |
|
8 |
||
9 |
from base64 import b64encode, b64decode |
|
10 |
from itertools import repeat |
|
11 |
from time import time |
|
12 |
try: |
|
13 |
from socket import gethostname |
|
14 |
except ImportError: |
|
15 |
def gethostname(): |
|
16 |
return 'XXX' |
|
17 |
||
18 |
from logilab.common.textutils import normalize_text |
|
738
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
19 |
from logilab.common.deprecation import class_renamed |
0 | 20 |
|
21 |
from cubicweb import RegistryException |
|
781
323656dd85a9
fix import, use non_final_entity instead of implements('Any')
sylvain.thenault@logilab.fr
parents:
761
diff
changeset
|
22 |
from cubicweb.selectors import implements, yes |
803 | 23 |
from cubicweb.view import EntityView, Component |
0 | 24 |
from cubicweb.common.mail import format_mail |
25 |
||
26 |
from cubicweb.server.pool import PreCommitOperation |
|
27 |
from cubicweb.server.hookhelper import SendMailOp |
|
28 |
from cubicweb.server.hooksmanager import Hook |
|
29 |
||
30 |
_ = unicode |
|
31 |
||
32 |
class RecipientsFinder(Component): |
|
33 |
"""this component is responsible to find recipients of a notification |
|
34 |
||
35 |
by default user's with their email set are notified if any, else the default |
|
36 |
email addresses specified in the configuration are used |
|
37 |
""" |
|
38 |
id = 'recipients_finder' |
|
781
323656dd85a9
fix import, use non_final_entity instead of implements('Any')
sylvain.thenault@logilab.fr
parents:
761
diff
changeset
|
39 |
__select__ = yes() |
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
40 |
user_rql = ('Any X,E,A WHERE X is CWUser, X in_state S, S name "activated",' |
0 | 41 |
'X primary_email E, E address A') |
1477 | 42 |
|
0 | 43 |
def recipients(self): |
44 |
mode = self.config['default-recipients-mode'] |
|
45 |
if mode == 'users': |
|
46 |
# use unsafe execute else we may don't have the right to see users |
|
47 |
# to notify... |
|
48 |
execute = self.req.unsafe_execute |
|
49 |
dests = [(u.get_email(), u.property_value('ui.language')) |
|
50 |
for u in execute(self.user_rql, build_descr=True, propagate=True).entities()] |
|
51 |
elif mode == 'default-dest-addrs': |
|
52 |
lang = self.vreg.property_value('ui.language') |
|
53 |
dests = zip(self.config['default-dest-addrs'], repeat(lang)) |
|
54 |
else: # mode == 'none' |
|
55 |
dests = [] |
|
56 |
return dests |
|
57 |
||
1477 | 58 |
|
0 | 59 |
# hooks ####################################################################### |
60 |
||
61 |
class RenderAndSendNotificationView(PreCommitOperation): |
|
62 |
"""delay rendering of notification view until precommit""" |
|
63 |
def precommit_event(self): |
|
64 |
if self.view.rset[0][0] in self.session.query_data('pendingeids', ()): |
|
65 |
return # entity added and deleted in the same transaction |
|
66 |
self.view.render_and_send(**getattr(self, 'viewargs', {})) |
|
1477 | 67 |
|
0 | 68 |
class StatusChangeHook(Hook): |
69 |
"""notify when a workflowable entity has its state modified""" |
|
70 |
events = ('after_add_entity',) |
|
71 |
accepts = ('TrInfo',) |
|
1477 | 72 |
|
0 | 73 |
def call(self, session, entity): |
74 |
if not entity.from_state: # not a transition |
|
75 |
return |
|
76 |
rset = entity.related('wf_info_for') |
|
77 |
try: |
|
78 |
view = session.vreg.select_view('notif_status_change', |
|
79 |
session, rset, row=0) |
|
80 |
except RegistryException: |
|
81 |
return |
|
82 |
comment = entity.printable_value('comment', format='text/plain') |
|
83 |
if comment: |
|
84 |
comment = normalize_text(comment, 80, |
|
85 |
rest=entity.comment_format=='text/rest') |
|
86 |
RenderAndSendNotificationView(session, view=view, viewargs={ |
|
87 |
'comment': comment, 'previous_state': entity.previous_state.name, |
|
88 |
'current_state': entity.new_state.name}) |
|
89 |
||
90 |
||
91 |
class RelationChangeHook(Hook): |
|
92 |
events = ('before_add_relation', 'after_add_relation', |
|
93 |
'before_delete_relation', 'after_delete_relation') |
|
94 |
accepts = ('Any',) |
|
95 |
def call(self, session, fromeid, rtype, toeid): |
|
96 |
"""if a notification view is defined for the event, send notification |
|
97 |
email defined by the view |
|
98 |
""" |
|
99 |
rset = session.eid_rset(fromeid) |
|
100 |
vid = 'notif_%s_%s' % (self.event, rtype) |
|
101 |
try: |
|
102 |
view = session.vreg.select_view(vid, session, rset, row=0) |
|
103 |
except RegistryException: |
|
104 |
return |
|
105 |
RenderAndSendNotificationView(session, view=view) |
|
106 |
||
107 |
||
108 |
class EntityChangeHook(Hook): |
|
109 |
events = ('after_add_entity', |
|
110 |
'after_update_entity') |
|
111 |
accepts = ('Any',) |
|
112 |
def call(self, session, entity): |
|
113 |
"""if a notification view is defined for the event, send notification |
|
114 |
email defined by the view |
|
115 |
""" |
|
116 |
rset = entity.as_rset() |
|
117 |
vid = 'notif_%s' % self.event |
|
118 |
try: |
|
119 |
view = session.vreg.select_view(vid, session, rset, row=0) |
|
120 |
except RegistryException: |
|
121 |
return |
|
122 |
RenderAndSendNotificationView(session, view=view) |
|
123 |
||
124 |
||
125 |
# abstract or deactivated notification views and mixin ######################## |
|
126 |
||
127 |
class NotificationView(EntityView): |
|
128 |
"""abstract view implementing the email API |
|
129 |
||
130 |
all you have to do by default is : |
|
131 |
* set id and accepts attributes to match desired events and entity types |
|
132 |
* set a content attribute to define the content of the email (unless you |
|
133 |
override call) |
|
134 |
""" |
|
135 |
msgid_timestamp = True |
|
1477 | 136 |
|
0 | 137 |
def recipients(self): |
877
decb67772c92
should not use named args for req and rset when selecting
sylvain.thenault@logilab.fr
parents:
803
diff
changeset
|
138 |
finder = self.vreg.select_component('recipients_finder', self.req, self.rset) |
0 | 139 |
return finder.recipients() |
1477 | 140 |
|
0 | 141 |
def subject(self): |
142 |
entity = self.entity(0, 0) |
|
143 |
subject = self.req._(self.message) |
|
144 |
etype = entity.dc_type() |
|
145 |
eid = entity.eid |
|
146 |
login = self.user_login() |
|
147 |
return self.req._('%(subject)s %(etype)s #%(eid)s (%(login)s)') % locals() |
|
148 |
||
149 |
def user_login(self): |
|
150 |
# req is actually a session (we are on the server side), and we have to |
|
151 |
# prevent nested internal session |
|
152 |
return self.req.actual_session().user.login |
|
1477 | 153 |
|
0 | 154 |
def context(self, **kwargs): |
155 |
entity = self.entity(0, 0) |
|
156 |
for key, val in kwargs.iteritems(): |
|
1126 | 157 |
if val and isinstance(val, unicode) and val.strip(): |
158 |
kwargs[key] = self.req._(val) |
|
0 | 159 |
kwargs.update({'user': self.user_login(), |
160 |
'eid': entity.eid, |
|
161 |
'etype': entity.dc_type(), |
|
162 |
'url': entity.absolute_url(), |
|
163 |
'title': entity.dc_long_title(),}) |
|
164 |
return kwargs |
|
1477 | 165 |
|
0 | 166 |
def cell_call(self, row, col=0, **kwargs): |
167 |
self.w(self.req._(self.content) % self.context(**kwargs)) |
|
168 |
||
169 |
def construct_message_id(self, eid): |
|
170 |
return construct_message_id(self.config.appid, eid, self.msgid_timestamp) |
|
171 |
||
172 |
def render_and_send(self, **kwargs): |
|
173 |
"""generate and send an email message for this view""" |
|
174 |
self._kwargs = kwargs |
|
175 |
recipients = self.recipients() |
|
176 |
if not recipients: |
|
877
decb67772c92
should not use named args for req and rset when selecting
sylvain.thenault@logilab.fr
parents:
803
diff
changeset
|
177 |
self.info('skipping %s notification, no recipients', self.id) |
0 | 178 |
return |
179 |
if not isinstance(recipients[0], tuple): |
|
180 |
from warnings import warn |
|
181 |
warn('recipients should now return a list of 2-uple (email, language)', |
|
182 |
DeprecationWarning, stacklevel=1) |
|
183 |
lang = self.vreg.property_value('ui.language') |
|
184 |
recipients = zip(recipients, repeat(lang)) |
|
185 |
entity = self.entity(0, 0) |
|
186 |
# if the view is using timestamp in message ids, no way to reference |
|
187 |
# previous email |
|
188 |
if not self.msgid_timestamp: |
|
189 |
refs = [self.construct_message_id(eid) |
|
190 |
for eid in entity.notification_references(self)] |
|
191 |
else: |
|
192 |
refs = () |
|
193 |
msgid = self.construct_message_id(entity.eid) |
|
194 |
userdata = self.req.user_data() |
|
195 |
origlang = self.req.lang |
|
196 |
for emailaddr, lang in recipients: |
|
197 |
self.req.set_language(lang) |
|
198 |
# since the same view (eg self) may be called multiple time and we |
|
199 |
# need a fresh stream at each iteration, reset it explicitly |
|
200 |
self.w = None |
|
201 |
# call dispatch before subject to set .row/.col attributes on the view :/ |
|
202 |
content = self.dispatch(row=0, col=0, **kwargs) |
|
203 |
subject = self.subject() |
|
204 |
msg = format_mail(userdata, [emailaddr], content, subject, |
|
205 |
config=self.config, msgid=msgid, references=refs) |
|
206 |
self.send([emailaddr], msg) |
|
207 |
# restore language |
|
208 |
self.req.set_language(origlang) |
|
209 |
||
210 |
def send(self, recipients, msg): |
|
211 |
SendMailOp(self.req, recipients=recipients, msg=msg) |
|
212 |
||
213 |
||
214 |
def construct_message_id(appid, eid, withtimestamp=True): |
|
215 |
if withtimestamp: |
|
216 |
addrpart = 'eid=%s×tamp=%.10f' % (eid, time()) |
|
217 |
else: |
|
218 |
addrpart = 'eid=%s' % eid |
|
219 |
# we don't want any equal sign nor trailing newlines |
|
220 |
leftpart = b64encode(addrpart, '.-').rstrip().rstrip('=') |
|
221 |
return '<%s@%s.%s>' % (leftpart, appid, gethostname()) |
|
222 |
||
223 |
||
224 |
def parse_message_id(msgid, appid): |
|
225 |
if msgid[0] == '<': |
|
226 |
msgid = msgid[1:] |
|
227 |
if msgid[-1] == '>': |
|
228 |
msgid = msgid[:-1] |
|
229 |
try: |
|
230 |
values, qualif = msgid.split('@') |
|
231 |
padding = len(values) % 4 |
|
232 |
values = b64decode(str(values + '='*padding), '.-') |
|
233 |
values = dict(v.split('=') for v in values.split('&')) |
|
234 |
fromappid, host = qualif.split('.', 1) |
|
235 |
except: |
|
236 |
return None |
|
237 |
if appid != fromappid or host != gethostname(): |
|
238 |
return None |
|
239 |
return values |
|
1477 | 240 |
|
0 | 241 |
|
242 |
class StatusChangeMixIn(object): |
|
243 |
id = 'notif_status_change' |
|
244 |
msgid_timestamp = True |
|
245 |
message = _('status changed') |
|
246 |
content = _(""" |
|
247 |
%(user)s changed status from <%(previous_state)s> to <%(current_state)s> for entity |
|
248 |
'%(title)s' |
|
249 |
||
250 |
%(comment)s |
|
251 |
||
252 |
url: %(url)s |
|
253 |
""") |
|
254 |
||
255 |
||
738
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
256 |
############################################################################### |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
257 |
# Actual notification views. # |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
258 |
# # |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
259 |
# disable them at the recipients_finder level if you don't want them # |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
260 |
############################################################################### |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
261 |
|
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
262 |
# XXX should be based on dc_title/dc_description, no? |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
263 |
|
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
264 |
class ContentAddedView(NotificationView): |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
265 |
__abstract__ = True |
1477 | 266 |
id = 'notif_after_add_entity' |
0 | 267 |
msgid_timestamp = False |
268 |
message = _('new') |
|
269 |
content = """ |
|
270 |
%(title)s |
|
271 |
||
272 |
%(content)s |
|
273 |
||
274 |
url: %(url)s |
|
275 |
""" |
|
276 |
||
277 |
def context(self, **kwargs): |
|
278 |
entity = self.entity(0, 0) |
|
279 |
content = entity.printable_value(self.content_attr, format='text/plain') |
|
280 |
if content: |
|
281 |
contentformat = getattr(entity, self.content_attr + '_format', 'text/rest') |
|
282 |
content = normalize_text(content, 80, rest=contentformat=='text/rest') |
|
761 | 283 |
return super(ContentAddedView, self).context(content=content, **kwargs) |
1477 | 284 |
|
0 | 285 |
def subject(self): |
286 |
entity = self.entity(0, 0) |
|
287 |
return u'%s #%s (%s)' % (self.req.__('New %s' % entity.e_schema), |
|
288 |
entity.eid, self.user_login()) |
|
289 |
||
738
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
290 |
NormalizedTextView = class_renamed('NormalizedTextView', ContentAddedView) |