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