author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Thu, 23 Jul 2009 15:28:41 +0200 | |
changeset 2456 | aa25d6b244c8 |
parent 2304 | 8381cc99daa8 |
child 2565 | df34d3720ff5 |
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): |
|
2102
268659907769
finish to update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2101
diff
changeset
|
65 |
if 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: |
|
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
|
79 |
view = session.vreg.select('views', 'notif_status_change', |
2304
8381cc99daa8
name rset argument
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2144
diff
changeset
|
80 |
session, 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: |
|
2304
8381cc99daa8
name rset argument
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2144
diff
changeset
|
103 |
view = session.vreg.select('views', 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: |
|
2304
8381cc99daa8
name rset argument
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2144
diff
changeset
|
120 |
view = session.vreg.select('views', 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 |
""" |
|
136 |
msgid_timestamp = True |
|
1477 | 137 |
|
0 | 138 |
def recipients(self): |
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
|
139 |
finder = self.vreg.select('components', 'recipients_finder', self.req, |
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
|
140 |
rset=self.rset) |
0 | 141 |
return finder.recipients() |
1477 | 142 |
|
0 | 143 |
def subject(self): |
144 |
entity = self.entity(0, 0) |
|
145 |
subject = self.req._(self.message) |
|
146 |
etype = entity.dc_type() |
|
147 |
eid = entity.eid |
|
148 |
login = self.user_login() |
|
149 |
return self.req._('%(subject)s %(etype)s #%(eid)s (%(login)s)') % locals() |
|
150 |
||
151 |
def user_login(self): |
|
152 |
# req is actually a session (we are on the server side), and we have to |
|
153 |
# prevent nested internal session |
|
154 |
return self.req.actual_session().user.login |
|
1477 | 155 |
|
0 | 156 |
def context(self, **kwargs): |
157 |
entity = self.entity(0, 0) |
|
158 |
for key, val in kwargs.iteritems(): |
|
1126 | 159 |
if val and isinstance(val, unicode) and val.strip(): |
160 |
kwargs[key] = self.req._(val) |
|
0 | 161 |
kwargs.update({'user': self.user_login(), |
162 |
'eid': entity.eid, |
|
163 |
'etype': entity.dc_type(), |
|
164 |
'url': entity.absolute_url(), |
|
165 |
'title': entity.dc_long_title(),}) |
|
166 |
return kwargs |
|
1477 | 167 |
|
0 | 168 |
def cell_call(self, row, col=0, **kwargs): |
169 |
self.w(self.req._(self.content) % self.context(**kwargs)) |
|
170 |
||
171 |
def construct_message_id(self, eid): |
|
172 |
return construct_message_id(self.config.appid, eid, self.msgid_timestamp) |
|
173 |
||
174 |
def render_and_send(self, **kwargs): |
|
175 |
"""generate and send an email message for this view""" |
|
176 |
self._kwargs = kwargs |
|
177 |
recipients = self.recipients() |
|
178 |
if not recipients: |
|
877
decb67772c92
should not use named args for req and rset when selecting
sylvain.thenault@logilab.fr
parents:
803
diff
changeset
|
179 |
self.info('skipping %s notification, no recipients', self.id) |
0 | 180 |
return |
181 |
if not isinstance(recipients[0], tuple): |
|
182 |
from warnings import warn |
|
183 |
warn('recipients should now return a list of 2-uple (email, language)', |
|
184 |
DeprecationWarning, stacklevel=1) |
|
185 |
lang = self.vreg.property_value('ui.language') |
|
186 |
recipients = zip(recipients, repeat(lang)) |
|
187 |
entity = self.entity(0, 0) |
|
188 |
# if the view is using timestamp in message ids, no way to reference |
|
189 |
# previous email |
|
190 |
if not self.msgid_timestamp: |
|
191 |
refs = [self.construct_message_id(eid) |
|
192 |
for eid in entity.notification_references(self)] |
|
193 |
else: |
|
194 |
refs = () |
|
195 |
msgid = self.construct_message_id(entity.eid) |
|
196 |
userdata = self.req.user_data() |
|
197 |
origlang = self.req.lang |
|
198 |
for emailaddr, lang in recipients: |
|
199 |
self.req.set_language(lang) |
|
200 |
# since the same view (eg self) may be called multiple time and we |
|
201 |
# need a fresh stream at each iteration, reset it explicitly |
|
202 |
self.w = None |
|
1723 | 203 |
# XXX call render before subject to set .row/.col attributes on the |
204 |
# view |
|
205 |
content = self.render(row=0, col=0, **kwargs) |
|
0 | 206 |
subject = self.subject() |
207 |
msg = format_mail(userdata, [emailaddr], content, subject, |
|
208 |
config=self.config, msgid=msgid, references=refs) |
|
209 |
self.send([emailaddr], msg) |
|
210 |
# restore language |
|
211 |
self.req.set_language(origlang) |
|
212 |
||
213 |
def send(self, recipients, msg): |
|
214 |
SendMailOp(self.req, recipients=recipients, msg=msg) |
|
215 |
||
216 |
||
217 |
def construct_message_id(appid, eid, withtimestamp=True): |
|
218 |
if withtimestamp: |
|
219 |
addrpart = 'eid=%s×tamp=%.10f' % (eid, time()) |
|
220 |
else: |
|
221 |
addrpart = 'eid=%s' % eid |
|
222 |
# we don't want any equal sign nor trailing newlines |
|
223 |
leftpart = b64encode(addrpart, '.-').rstrip().rstrip('=') |
|
224 |
return '<%s@%s.%s>' % (leftpart, appid, gethostname()) |
|
225 |
||
226 |
||
227 |
def parse_message_id(msgid, appid): |
|
228 |
if msgid[0] == '<': |
|
229 |
msgid = msgid[1:] |
|
230 |
if msgid[-1] == '>': |
|
231 |
msgid = msgid[:-1] |
|
232 |
try: |
|
233 |
values, qualif = msgid.split('@') |
|
234 |
padding = len(values) % 4 |
|
235 |
values = b64decode(str(values + '='*padding), '.-') |
|
236 |
values = dict(v.split('=') for v in values.split('&')) |
|
237 |
fromappid, host = qualif.split('.', 1) |
|
238 |
except: |
|
239 |
return None |
|
240 |
if appid != fromappid or host != gethostname(): |
|
241 |
return None |
|
242 |
return values |
|
1477 | 243 |
|
0 | 244 |
|
245 |
class StatusChangeMixIn(object): |
|
246 |
id = 'notif_status_change' |
|
247 |
msgid_timestamp = True |
|
248 |
message = _('status changed') |
|
249 |
content = _(""" |
|
250 |
%(user)s changed status from <%(previous_state)s> to <%(current_state)s> for entity |
|
251 |
'%(title)s' |
|
252 |
||
253 |
%(comment)s |
|
254 |
||
255 |
url: %(url)s |
|
256 |
""") |
|
257 |
||
258 |
||
738
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 |
# Actual notification views. # |
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 |
# 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
|
263 |
############################################################################### |
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 |
# 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
|
266 |
|
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
267 |
class ContentAddedView(NotificationView): |
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
268 |
__abstract__ = True |
1477 | 269 |
id = 'notif_after_add_entity' |
0 | 270 |
msgid_timestamp = False |
271 |
message = _('new') |
|
272 |
content = """ |
|
273 |
%(title)s |
|
274 |
||
275 |
%(content)s |
|
276 |
||
277 |
url: %(url)s |
|
278 |
""" |
|
279 |
||
280 |
def context(self, **kwargs): |
|
281 |
entity = self.entity(0, 0) |
|
282 |
content = entity.printable_value(self.content_attr, format='text/plain') |
|
283 |
if content: |
|
284 |
contentformat = getattr(entity, self.content_attr + '_format', 'text/rest') |
|
285 |
content = normalize_text(content, 80, rest=contentformat=='text/rest') |
|
761 | 286 |
return super(ContentAddedView, self).context(content=content, **kwargs) |
1477 | 287 |
|
0 | 288 |
def subject(self): |
289 |
entity = self.entity(0, 0) |
|
290 |
return u'%s #%s (%s)' % (self.req.__('New %s' % entity.e_schema), |
|
291 |
entity.eid, self.user_login()) |
|
292 |
||
738
9b8cb1976992
better name for NormalizedTextView, drop ContentAddedMixIn
sylvain.thenault@logilab.fr
parents:
730
diff
changeset
|
293 |
NormalizedTextView = class_renamed('NormalizedTextView', ContentAddedView) |