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