author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Wed, 27 May 2009 11:18:46 +0200 | |
branch | stable |
changeset 1950 | ab7a41b2cd26 |
parent 1723 | 30c3a713ab61 |
child 1977 | 606923dff11b |
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 |
|
1723 | 201 |
# XXX call render before subject to set .row/.col attributes on the |
202 |
# view |
|
203 |
content = self.render(row=0, col=0, **kwargs) |
|
0 | 204 |
subject = self.subject() |
205 |
msg = format_mail(userdata, [emailaddr], content, subject, |
|
206 |
config=self.config, msgid=msgid, references=refs) |
|
207 |
self.send([emailaddr], msg) |
|
208 |
# restore language |
|
209 |
self.req.set_language(origlang) |
|
210 |
||
211 |
def send(self, recipients, msg): |
|
212 |
SendMailOp(self.req, recipients=recipients, msg=msg) |
|
213 |
||
214 |
||
215 |
def construct_message_id(appid, eid, withtimestamp=True): |
|
216 |
if withtimestamp: |
|
217 |
addrpart = 'eid=%s×tamp=%.10f' % (eid, time()) |
|
218 |
else: |
|
219 |
addrpart = 'eid=%s' % eid |
|
220 |
# we don't want any equal sign nor trailing newlines |
|
221 |
leftpart = b64encode(addrpart, '.-').rstrip().rstrip('=') |
|
222 |
return '<%s@%s.%s>' % (leftpart, appid, gethostname()) |
|
223 |
||
224 |
||
225 |
def parse_message_id(msgid, appid): |
|
226 |
if msgid[0] == '<': |
|
227 |
msgid = msgid[1:] |
|
228 |
if msgid[-1] == '>': |
|
229 |
msgid = msgid[:-1] |
|
230 |
try: |
|
231 |
values, qualif = msgid.split('@') |
|
232 |
padding = len(values) % 4 |
|
233 |
values = b64decode(str(values + '='*padding), '.-') |
|
234 |
values = dict(v.split('=') for v in values.split('&')) |
|
235 |
fromappid, host = qualif.split('.', 1) |
|
236 |
except: |
|
237 |
return None |
|
238 |
if appid != fromappid or host != gethostname(): |
|
239 |
return None |
|
240 |
return values |
|
1477 | 241 |
|
0 | 242 |
|
243 |
class StatusChangeMixIn(object): |
|
244 |
id = 'notif_status_change' |
|
245 |
msgid_timestamp = True |
|
246 |
message = _('status changed') |
|
247 |
content = _(""" |
|
248 |
%(user)s changed status from <%(previous_state)s> to <%(current_state)s> for entity |
|
249 |
'%(title)s' |
|
250 |
||
251 |
%(comment)s |
|
252 |
||
253 |
url: %(url)s |
|
254 |
""") |
|
255 |
||
256 |
||
738
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
257 |
############################################################################### |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
258 |
# Actual notification views. # |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
259 |
# # |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
260 |
# 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
|
261 |
############################################################################### |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
262 |
|
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
263 |
# 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
|
264 |
|
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
265 |
class ContentAddedView(NotificationView): |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
266 |
__abstract__ = True |
1477 | 267 |
id = 'notif_after_add_entity' |
0 | 268 |
msgid_timestamp = False |
269 |
message = _('new') |
|
270 |
content = """ |
|
271 |
%(title)s |
|
272 |
||
273 |
%(content)s |
|
274 |
||
275 |
url: %(url)s |
|
276 |
""" |
|
277 |
||
278 |
def context(self, **kwargs): |
|
279 |
entity = self.entity(0, 0) |
|
280 |
content = entity.printable_value(self.content_attr, format='text/plain') |
|
281 |
if content: |
|
282 |
contentformat = getattr(entity, self.content_attr + '_format', 'text/rest') |
|
283 |
content = normalize_text(content, 80, rest=contentformat=='text/rest') |
|
761 | 284 |
return super(ContentAddedView, self).context(content=content, **kwargs) |
1477 | 285 |
|
0 | 286 |
def subject(self): |
287 |
entity = self.entity(0, 0) |
|
288 |
return u'%s #%s (%s)' % (self.req.__('New %s' % entity.e_schema), |
|
289 |
entity.eid, self.user_login()) |
|
290 |
||
738
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
291 |
NormalizedTextView = class_renamed('NormalizedTextView', ContentAddedView) |