1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17 #
18 # $Id: roundupdb.py,v 1.92 2003-10-04 11:21:47 jlgijsbers Exp $
20 __doc__ = """
21 Extending hyperdb with types specific to issue-tracking.
22 """
24 import re, os, smtplib, socket, time, random
25 import cStringIO, base64, quopri, mimetypes
27 from rfc2822 import encode_header
29 from roundup import password, date, hyperdb
31 # MessageSendError is imported for backwards compatibility
32 from roundup.mailer import Mailer, straddr, MessageSendError
34 class Database:
35 def getuid(self):
36 """Return the id of the "user" node associated with the user
37 that owns this connection to the hyperdatabase."""
38 if self.journaltag is None:
39 return None
40 elif self.journaltag == 'admin':
41 # admin user may not exist, but always has ID 1
42 return '1'
43 else:
44 return self.user.lookup(self.journaltag)
46 def getUserTimezone(self):
47 """Return user timezone defined in 'timezone' property of user class.
48 If no such property exists return 0
49 """
50 userid = self.getuid()
51 try:
52 timezone = int(self.user.get(userid, 'timezone'))
53 except (KeyError, ValueError, TypeError):
54 # If there is no class 'user' or current user doesn't have timezone
55 # property or that property is not numeric assume he/she lives in
56 # Greenwich :)
57 timezone = 0
58 return timezone
60 def confirm_registration(self, otk):
61 props = self.otks.getall(otk)
62 for propname, proptype in self.user.getprops().items():
63 value = props.get(propname, None)
64 if value is None:
65 pass
66 elif isinstance(proptype, hyperdb.Date):
67 props[propname] = date.Date(value)
68 elif isinstance(proptype, hyperdb.Interval):
69 props[propname] = date.Interval(value)
70 elif isinstance(proptype, hyperdb.Password):
71 props[propname] = password.Password()
72 props[propname].unpack(value)
74 # tag new user creation with 'admin'
75 self.journaltag = 'admin'
77 # create the new user
78 cl = self.user
80 props['roles'] = self.config.NEW_WEB_USER_ROLES
81 del props['__time']
82 userid = cl.create(**props)
83 # clear the props from the otk database
84 self.otks.destroy(otk)
85 self.commit()
87 return userid
90 class DetectorError(RuntimeError):
91 """ Raised by detectors that want to indicate that something's amiss
92 """
93 pass
95 # deviation from spec - was called IssueClass
96 class IssueClass:
97 """ This class is intended to be mixed-in with a hyperdb backend
98 implementation. The backend should provide a mechanism that
99 enforces the title, messages, files, nosy and superseder
100 properties:
101 properties['title'] = hyperdb.String(indexme='yes')
102 properties['messages'] = hyperdb.Multilink("msg")
103 properties['files'] = hyperdb.Multilink("file")
104 properties['nosy'] = hyperdb.Multilink("user")
105 properties['superseder'] = hyperdb.Multilink(classname)
106 """
108 # New methods:
109 def addmessage(self, nodeid, summary, text):
110 """Add a message to an issue's mail spool.
112 A new "msg" node is constructed using the current date, the user that
113 owns the database connection as the author, and the specified summary
114 text.
116 The "files" and "recipients" fields are left empty.
118 The given text is saved as the body of the message and the node is
119 appended to the "messages" field of the specified issue.
120 """
122 # XXX "bcc" is an optional extra here...
123 def nosymessage(self, nodeid, msgid, oldvalues, whichnosy='nosy',
124 from_address=None, cc=[]): #, bcc=[]):
125 """Send a message to the members of an issue's nosy list.
127 The message is sent only to users on the nosy list who are not
128 already on the "recipients" list for the message.
130 These users are then added to the message's "recipients" list.
132 """
133 users = self.db.user
134 messages = self.db.msg
136 # figure the recipient ids
137 sendto = []
138 r = {}
139 recipients = messages.get(msgid, 'recipients')
140 for recipid in messages.get(msgid, 'recipients'):
141 r[recipid] = 1
143 # figure the author's id, and indicate they've received the message
144 authid = messages.get(msgid, 'author')
146 # possibly send the message to the author, as long as they aren't
147 # anonymous
148 if (users.get(authid, 'username') != 'anonymous' and
149 not r.has_key(authid)):
150 if (self.db.config.MESSAGES_TO_AUTHOR == 'yes' or
151 (self.db.config.MESSAGES_TO_AUTHOR == 'new' and not oldvalues)):
152 # make sure they have an address
153 add = users.get(authid, 'address')
154 if add:
155 # send it to them
156 sendto.append(add)
157 recipients.append(authid)
159 r[authid] = 1
161 # now deal with cc people.
162 for cc_userid in cc :
163 if r.has_key(cc_userid):
164 continue
165 # make sure they have an address
166 add = users.get(cc_userid, 'address')
167 if add:
168 # send it to them
169 sendto.append(add)
170 recipients.append(cc_userid)
172 # now figure the nosy people who weren't recipients
173 nosy = self.get(nodeid, whichnosy)
174 for nosyid in nosy:
175 # Don't send nosy mail to the anonymous user (that user
176 # shouldn't appear in the nosy list, but just in case they
177 # do...)
178 if users.get(nosyid, 'username') == 'anonymous':
179 continue
180 # make sure they haven't seen the message already
181 if not r.has_key(nosyid):
182 # make sure they have an address
183 add = users.get(nosyid, 'address')
184 if add:
185 # send it to them
186 sendto.append(add)
187 recipients.append(nosyid)
189 # generate a change note
190 if oldvalues:
191 note = self.generateChangeNote(nodeid, oldvalues)
192 else:
193 note = self.generateCreateNote(nodeid)
195 # we have new recipients
196 if sendto:
197 # update the message's recipients list
198 messages.set(msgid, recipients=recipients)
200 # send the message
201 self.send_message(nodeid, msgid, note, sendto, from_address)
203 # backwards compatibility - don't remove
204 sendmessage = nosymessage
206 def send_message(self, nodeid, msgid, note, sendto, from_address=None):
207 '''Actually send the nominated message from this node to the sendto
208 recipients, with the note appended.
209 '''
210 users = self.db.user
211 messages = self.db.msg
212 files = self.db.file
214 # determine the messageid and inreplyto of the message
215 inreplyto = messages.get(msgid, 'inreplyto')
216 messageid = messages.get(msgid, 'messageid')
218 # make up a messageid if there isn't one (web edit)
219 if not messageid:
220 # this is an old message that didn't get a messageid, so
221 # create one
222 messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
223 self.classname, nodeid, self.db.config.MAIL_DOMAIN)
224 messages.set(msgid, messageid=messageid)
226 # send an email to the people who missed out
227 cn = self.classname
228 title = self.get(nodeid, 'title') or '%s message copy'%cn
229 # figure author information
230 authid = messages.get(msgid, 'author')
231 authname = users.get(authid, 'realname')
232 if not authname:
233 authname = users.get(authid, 'username')
234 authaddr = users.get(authid, 'address')
235 if authaddr:
236 authaddr = " <%s>" % straddr( ('',authaddr) )
237 else:
238 authaddr = ''
240 # make the message body
241 m = ['']
243 # put in roundup's signature
244 if self.db.config.EMAIL_SIGNATURE_POSITION == 'top':
245 m.append(self.email_signature(nodeid, msgid))
247 # add author information
248 if len(self.get(nodeid,'messages')) == 1:
249 m.append("New submission from %s%s:"%(authname, authaddr))
250 else:
251 m.append("%s%s added the comment:"%(authname, authaddr))
252 m.append('')
254 # add the content
255 m.append(messages.get(msgid, 'content'))
257 # add the change note
258 if note:
259 m.append(note)
261 # put in roundup's signature
262 if self.db.config.EMAIL_SIGNATURE_POSITION == 'bottom':
263 m.append(self.email_signature(nodeid, msgid))
265 # encode the content as quoted-printable
266 content = cStringIO.StringIO('\n'.join(m))
267 content_encoded = cStringIO.StringIO()
268 quopri.encode(content, content_encoded, 0)
269 content_encoded = content_encoded.getvalue()
271 # get the files for this message
272 message_files = messages.get(msgid, 'files')
274 # make sure the To line is always the same (for testing mostly)
275 sendto.sort()
277 # make sure we have a from address
278 if from_address is None:
279 from_address = self.db.config.TRACKER_EMAIL
281 # additional bit for after the From: "name"
282 from_tag = getattr(self.db.config, 'EMAIL_FROM_TAG', '')
283 if from_tag:
284 from_tag = ' ' + from_tag
286 subject = '[%s%s] %s' % (cn, nodeid, encode_header(title))
287 author = straddr((encode_header(authname) + from_tag, from_address))
289 # create the message
290 mailer = Mailer(self.db.config)
291 message, writer = mailer.get_standard_message(sendto, subject, author)
293 tracker_name = encode_header(self.db.config.TRACKER_NAME)
294 writer.addheader('Reply-To', straddr((tracker_name, from_address)))
295 if messageid:
296 writer.addheader('Message-Id', messageid)
297 if inreplyto:
298 writer.addheader('In-Reply-To', inreplyto)
300 # attach files
301 if message_files:
302 part = writer.startmultipartbody('mixed')
303 part = writer.nextpart()
304 part.addheader('Content-Transfer-Encoding', 'quoted-printable')
305 body = part.startbody('text/plain; charset=utf-8')
306 body.write(content_encoded)
307 for fileid in message_files:
308 name = files.get(fileid, 'name')
309 mime_type = files.get(fileid, 'type')
310 content = files.get(fileid, 'content')
311 part = writer.nextpart()
312 if mime_type == 'text/plain':
313 part.addheader('Content-Disposition',
314 'attachment;\n filename="%s"'%name)
315 part.addheader('Content-Transfer-Encoding', '7bit')
316 body = part.startbody('text/plain')
317 body.write(content)
318 else:
319 # some other type, so encode it
320 if not mime_type:
321 # this should have been done when the file was saved
322 mime_type = mimetypes.guess_type(name)[0]
323 if mime_type is None:
324 mime_type = 'application/octet-stream'
325 part.addheader('Content-Disposition',
326 'attachment;\n filename="%s"'%name)
327 part.addheader('Content-Transfer-Encoding', 'base64')
328 body = part.startbody(mime_type)
329 body.write(base64.encodestring(content))
330 writer.lastpart()
331 else:
332 writer.addheader('Content-Transfer-Encoding', 'quoted-printable')
333 body = writer.startbody('text/plain; charset=utf-8')
334 body.write(content_encoded)
336 mailer.smtp_send(sendto, message)
338 def email_signature(self, nodeid, msgid):
339 ''' Add a signature to the e-mail with some useful information
340 '''
341 # simplistic check to see if the url is valid,
342 # then append a trailing slash if it is missing
343 base = self.db.config.TRACKER_WEB
344 if (not isinstance(base , type('')) or
345 not (base.startswith('http://') or base.startswith('https://'))):
346 base = "Configuration Error: TRACKER_WEB isn't a " \
347 "fully-qualified URL"
348 elif base[-1] != '/' :
349 base += '/'
350 web = base + self.classname + nodeid
352 # ensure the email address is properly quoted
353 email = straddr((self.db.config.TRACKER_NAME,
354 self.db.config.TRACKER_EMAIL))
356 line = '_' * max(len(web)+2, len(email))
357 return '%s\n%s\n<%s>\n%s'%(line, email, web, line)
360 def generateCreateNote(self, nodeid):
361 """Generate a create note that lists initial property values
362 """
363 cn = self.classname
364 cl = self.db.classes[cn]
365 props = cl.getprops(protected=0)
367 # list the values
368 m = []
369 l = props.items()
370 l.sort()
371 for propname, prop in l:
372 value = cl.get(nodeid, propname, None)
373 # skip boring entries
374 if not value:
375 continue
376 if isinstance(prop, hyperdb.Link):
377 link = self.db.classes[prop.classname]
378 if value:
379 key = link.labelprop(default_to_id=1)
380 if key:
381 value = link.get(value, key)
382 else:
383 value = ''
384 elif isinstance(prop, hyperdb.Multilink):
385 if value is None: value = []
386 l = []
387 link = self.db.classes[prop.classname]
388 key = link.labelprop(default_to_id=1)
389 if key:
390 value = [link.get(entry, key) for entry in value]
391 value.sort()
392 value = ', '.join(value)
393 m.append('%s: %s'%(propname, value))
394 m.insert(0, '----------')
395 m.insert(0, '')
396 return '\n'.join(m)
398 def generateChangeNote(self, nodeid, oldvalues):
399 """Generate a change note that lists property changes
400 """
401 if __debug__ :
402 if not isinstance(oldvalues, type({})) :
403 raise TypeError("'oldvalues' must be dict-like, not %s."%
404 type(oldvalues))
406 cn = self.classname
407 cl = self.db.classes[cn]
408 changed = {}
409 props = cl.getprops(protected=0)
411 # determine what changed
412 for key in oldvalues.keys():
413 if key in ['files','messages']:
414 continue
415 if key in ('activity', 'creator', 'creation'):
416 continue
417 # not all keys from oldvalues might be available in database
418 # this happens when property was deleted
419 try:
420 new_value = cl.get(nodeid, key)
421 except KeyError:
422 continue
423 # the old value might be non existent
424 # this happens when property was added
425 try:
426 old_value = oldvalues[key]
427 if type(new_value) is type([]):
428 new_value.sort()
429 old_value.sort()
430 if new_value != old_value:
431 changed[key] = old_value
432 except:
433 changed[key] = new_value
435 # list the changes
436 m = []
437 l = changed.items()
438 l.sort()
439 for propname, oldvalue in l:
440 prop = props[propname]
441 value = cl.get(nodeid, propname, None)
442 if isinstance(prop, hyperdb.Link):
443 link = self.db.classes[prop.classname]
444 key = link.labelprop(default_to_id=1)
445 if key:
446 if value:
447 value = link.get(value, key)
448 else:
449 value = ''
450 if oldvalue:
451 oldvalue = link.get(oldvalue, key)
452 else:
453 oldvalue = ''
454 change = '%s -> %s'%(oldvalue, value)
455 elif isinstance(prop, hyperdb.Multilink):
456 change = ''
457 if value is None: value = []
458 if oldvalue is None: oldvalue = []
459 l = []
460 link = self.db.classes[prop.classname]
461 key = link.labelprop(default_to_id=1)
462 # check for additions
463 for entry in value:
464 if entry in oldvalue: continue
465 if key:
466 l.append(link.get(entry, key))
467 else:
468 l.append(entry)
469 if l:
470 l.sort()
471 change = '+%s'%(', '.join(l))
472 l = []
473 # check for removals
474 for entry in oldvalue:
475 if entry in value: continue
476 if key:
477 l.append(link.get(entry, key))
478 else:
479 l.append(entry)
480 if l:
481 l.sort()
482 change += ' -%s'%(', '.join(l))
483 else:
484 change = '%s -> %s'%(oldvalue, value)
485 m.append('%s: %s'%(propname, change))
486 if m:
487 m.insert(0, '----------')
488 m.insert(0, '')
489 return '\n'.join(m)
491 # vim: set filetype=python ts=4 sw=4 et si