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.97 2004-02-11 23:55:08 richard Exp $
20 """Extending hyperdb with types specific to issue-tracking.
21 """
22 __docformat__ = 'restructuredtext'
24 from __future__ import nested_scopes
26 import re, os, smtplib, socket, time, random
27 import cStringIO, base64, quopri, mimetypes
29 from rfc2822 import encode_header
31 from roundup import password, date, hyperdb
33 # MessageSendError is imported for backwards compatibility
34 from roundup.mailer import Mailer, straddr, MessageSendError
36 class Database:
37 def getuid(self):
38 """Return the id of the "user" node associated with the user
39 that owns this connection to the hyperdatabase."""
40 if self.journaltag is None:
41 return None
42 elif self.journaltag == 'admin':
43 # admin user may not exist, but always has ID 1
44 return '1'
45 else:
46 return self.user.lookup(self.journaltag)
48 def getUserTimezone(self):
49 """Return user timezone defined in 'timezone' property of user class.
50 If no such property exists return 0
51 """
52 userid = self.getuid()
53 try:
54 timezone = int(self.user.get(userid, 'timezone'))
55 except (KeyError, ValueError, TypeError):
56 # If there is no class 'user' or current user doesn't have timezone
57 # property or that property is not numeric assume he/she lives in
58 # Greenwich :)
59 timezone = 0
60 return timezone
62 def confirm_registration(self, otk):
63 props = self.otks.getall(otk)
64 for propname, proptype in self.user.getprops().items():
65 value = props.get(propname, None)
66 if value is None:
67 pass
68 elif isinstance(proptype, hyperdb.Date):
69 props[propname] = date.Date(value)
70 elif isinstance(proptype, hyperdb.Interval):
71 props[propname] = date.Interval(value)
72 elif isinstance(proptype, hyperdb.Password):
73 props[propname] = password.Password()
74 props[propname].unpack(value)
76 # tag new user creation with 'admin'
77 self.journaltag = 'admin'
79 # create the new user
80 cl = self.user
82 props['roles'] = self.config.NEW_WEB_USER_ROLES
83 del props['__time']
84 userid = cl.create(**props)
85 # clear the props from the otk database
86 self.otks.destroy(otk)
87 self.commit()
89 return userid
92 class DetectorError(RuntimeError):
93 """ Raised by detectors that want to indicate that something's amiss
94 """
95 pass
97 # deviation from spec - was called IssueClass
98 class IssueClass:
99 """This class is intended to be mixed-in with a hyperdb backend
100 implementation. The backend should provide a mechanism that
101 enforces the title, messages, files, nosy and superseder
102 properties:
104 - title = hyperdb.String(indexme='yes')
105 - messages = hyperdb.Multilink("msg")
106 - files = hyperdb.Multilink("file")
107 - nosy = hyperdb.Multilink("user")
108 - superseder = hyperdb.Multilink(classname)
109 """
111 # New methods:
112 def addmessage(self, nodeid, summary, text):
113 """Add a message to an issue's mail spool.
115 A new "msg" node is constructed using the current date, the user that
116 owns the database connection as the author, and the specified summary
117 text.
119 The "files" and "recipients" fields are left empty.
121 The given text is saved as the body of the message and the node is
122 appended to the "messages" field of the specified issue.
123 """
125 # XXX "bcc" is an optional extra here...
126 def nosymessage(self, nodeid, msgid, oldvalues, whichnosy='nosy',
127 from_address=None, cc=[]): #, bcc=[]):
128 """Send a message to the members of an issue's nosy list.
130 The message is sent only to users on the nosy list who are not
131 already on the "recipients" list for the message.
133 These users are then added to the message's "recipients" list.
135 If 'msgid' is None, the message gets sent only to the nosy
136 list, and it's called a 'System Message'.
137 """
138 authid = self.db.msg.safeget(msgid, 'author')
139 recipients = self.db.msg.safeget(msgid, 'recipients', [])
141 sendto = []
142 seen_message = {}
143 for recipient in recipients:
144 seen_message[recipient] = 1
146 def add_recipient(userid):
147 # make sure they have an address
148 address = self.db.user.get(userid, 'address')
149 if address:
150 sendto.append(address)
151 recipients.append(userid)
153 def good_recipient(userid):
154 # Make sure we don't send mail to either the anonymous
155 # user or a user who has already seen the message.
156 return (userid and
157 (self.db.user.get(userid, 'username') != 'anonymous') and
158 not seen_message.has_key(userid))
160 # possibly send the message to the author, as long as they aren't
161 # anonymous
162 if (good_recipient(authid) and
163 (self.db.config.MESSAGES_TO_AUTHOR == 'yes' or
164 (self.db.config.MESSAGES_TO_AUTHOR == 'new' and not oldvalues))):
165 add_recipient(authid)
167 if authid:
168 seen_message[authid] = 1
170 # now deal with the nosy and cc people who weren't recipients.
171 for userid in cc + self.get(nodeid, whichnosy):
172 if good_recipient(userid):
173 add_recipient(userid)
175 if oldvalues:
176 note = self.generateChangeNote(nodeid, oldvalues)
177 else:
178 note = self.generateCreateNote(nodeid)
180 # If we have new recipients, update the message's recipients
181 # and send the mail.
182 if sendto:
183 if msgid:
184 self.db.msg.set(msgid, recipients=recipients)
185 self.send_message(nodeid, msgid, note, sendto, from_address)
187 # backwards compatibility - don't remove
188 sendmessage = nosymessage
190 def send_message(self, nodeid, msgid, note, sendto, from_address=None):
191 '''Actually send the nominated message from this node to the sendto
192 recipients, with the note appended.
193 '''
194 users = self.db.user
195 messages = self.db.msg
196 files = self.db.file
198 inreplyto = messages.safeget(msgid, 'inreplyto')
199 messageid = messages.safeget(msgid, 'messageid')
201 # make up a messageid if there isn't one (web edit)
202 if not messageid:
203 # this is an old message that didn't get a messageid, so
204 # create one
205 messageid = "<%s.%s.%s%s@%s>"%(time.time(), random.random(),
206 self.classname, nodeid,
207 self.db.config.MAIL_DOMAIN)
208 messages.set(msgid, messageid=messageid)
210 # send an email to the people who missed out
211 cn = self.classname
212 title = self.get(nodeid, 'title') or '%s message copy'%cn
214 authid = messages.safeget(msgid, 'author')
215 authname = users.safeget(authid, 'realname')
216 if not authname:
217 authname = users.safeget(authid, 'username', '')
218 authaddr = users.safeget(authid, 'address', '')
219 if authaddr:
220 authaddr = " <%s>" % straddr( ('',authaddr) )
222 # make the message body
223 m = ['']
225 # put in roundup's signature
226 if self.db.config.EMAIL_SIGNATURE_POSITION == 'top':
227 m.append(self.email_signature(nodeid, msgid))
229 # add author information
230 if authid:
231 if len(self.get(nodeid,'messages')) == 1:
232 m.append("New submission from %s%s:"%(authname, authaddr))
233 else:
234 m.append("%s%s added the comment:"%(authname, authaddr))
235 else:
236 m.append("System message:")
237 m.append('')
239 # add the content
240 m.append(messages.safeget(msgid, 'content', ''))
242 # add the change note
243 if note:
244 m.append(note)
246 # put in roundup's signature
247 if self.db.config.EMAIL_SIGNATURE_POSITION == 'bottom':
248 m.append(self.email_signature(nodeid, msgid))
250 # encode the content as quoted-printable
251 content = cStringIO.StringIO('\n'.join(m))
252 content_encoded = cStringIO.StringIO()
253 quopri.encode(content, content_encoded, 0)
254 content_encoded = content_encoded.getvalue()
256 # get the files for this message
257 message_files = msgid and messages.get(msgid, 'files') or None
259 # make sure the To line is always the same (for testing mostly)
260 sendto.sort()
262 # make sure we have a from address
263 if from_address is None:
264 from_address = self.db.config.TRACKER_EMAIL
266 # additional bit for after the From: "name"
267 from_tag = getattr(self.db.config, 'EMAIL_FROM_TAG', '')
268 if from_tag:
269 from_tag = ' ' + from_tag
271 subject = '[%s%s] %s' % (cn, nodeid, encode_header(title))
272 author = straddr((encode_header(authname) + from_tag, from_address))
274 # create the message
275 mailer = Mailer(self.db.config)
276 message, writer = mailer.get_standard_message(sendto, subject, author)
278 tracker_name = encode_header(self.db.config.TRACKER_NAME)
279 writer.addheader('Reply-To', straddr((tracker_name, from_address)))
280 if messageid:
281 writer.addheader('Message-Id', messageid)
282 if inreplyto:
283 writer.addheader('In-Reply-To', inreplyto)
285 # attach files
286 if message_files:
287 part = writer.startmultipartbody('mixed')
288 part = writer.nextpart()
289 part.addheader('Content-Transfer-Encoding', 'quoted-printable')
290 body = part.startbody('text/plain; charset=utf-8')
291 body.write(content_encoded)
292 for fileid in message_files:
293 name = files.get(fileid, 'name')
294 mime_type = files.get(fileid, 'type')
295 content = files.get(fileid, 'content')
296 part = writer.nextpart()
297 if mime_type == 'text/plain':
298 part.addheader('Content-Disposition',
299 'attachment;\n filename="%s"'%name)
300 part.addheader('Content-Transfer-Encoding', '7bit')
301 body = part.startbody('text/plain')
302 body.write(content)
303 else:
304 # some other type, so encode it
305 if not mime_type:
306 # this should have been done when the file was saved
307 mime_type = mimetypes.guess_type(name)[0]
308 if mime_type is None:
309 mime_type = 'application/octet-stream'
310 part.addheader('Content-Disposition',
311 'attachment;\n filename="%s"'%name)
312 part.addheader('Content-Transfer-Encoding', 'base64')
313 body = part.startbody(mime_type)
314 body.write(base64.encodestring(content))
315 writer.lastpart()
316 else:
317 writer.addheader('Content-Transfer-Encoding', 'quoted-printable')
318 body = writer.startbody('text/plain; charset=utf-8')
319 body.write(content_encoded)
321 mailer.smtp_send(sendto, message)
323 def email_signature(self, nodeid, msgid):
324 ''' Add a signature to the e-mail with some useful information
325 '''
326 # simplistic check to see if the url is valid,
327 # then append a trailing slash if it is missing
328 base = self.db.config.TRACKER_WEB
329 if (not isinstance(base , type('')) or
330 not (base.startswith('http://') or base.startswith('https://'))):
331 base = "Configuration Error: TRACKER_WEB isn't a " \
332 "fully-qualified URL"
333 elif base[-1] != '/' :
334 base += '/'
335 web = base + self.classname + nodeid
337 # ensure the email address is properly quoted
338 email = straddr((self.db.config.TRACKER_NAME,
339 self.db.config.TRACKER_EMAIL))
341 line = '_' * max(len(web)+2, len(email))
342 return '%s\n%s\n<%s>\n%s'%(line, email, web, line)
345 def generateCreateNote(self, nodeid):
346 """Generate a create note that lists initial property values
347 """
348 cn = self.classname
349 cl = self.db.classes[cn]
350 props = cl.getprops(protected=0)
352 # list the values
353 m = []
354 l = props.items()
355 l.sort()
356 for propname, prop in l:
357 value = cl.get(nodeid, propname, None)
358 # skip boring entries
359 if not value:
360 continue
361 if isinstance(prop, hyperdb.Link):
362 link = self.db.classes[prop.classname]
363 if value:
364 key = link.labelprop(default_to_id=1)
365 if key:
366 value = link.get(value, key)
367 else:
368 value = ''
369 elif isinstance(prop, hyperdb.Multilink):
370 if value is None: value = []
371 l = []
372 link = self.db.classes[prop.classname]
373 key = link.labelprop(default_to_id=1)
374 if key:
375 value = [link.get(entry, key) for entry in value]
376 value.sort()
377 value = ', '.join(value)
378 m.append('%s: %s'%(propname, value))
379 m.insert(0, '----------')
380 m.insert(0, '')
381 return '\n'.join(m)
383 def generateChangeNote(self, nodeid, oldvalues):
384 """Generate a change note that lists property changes
385 """
386 if __debug__ :
387 if not isinstance(oldvalues, type({})) :
388 raise TypeError("'oldvalues' must be dict-like, not %s."%
389 type(oldvalues))
391 cn = self.classname
392 cl = self.db.classes[cn]
393 changed = {}
394 props = cl.getprops(protected=0)
396 # determine what changed
397 for key in oldvalues.keys():
398 if key in ['files','messages']:
399 continue
400 if key in ('activity', 'creator', 'creation'):
401 continue
402 # not all keys from oldvalues might be available in database
403 # this happens when property was deleted
404 try:
405 new_value = cl.get(nodeid, key)
406 except KeyError:
407 continue
408 # the old value might be non existent
409 # this happens when property was added
410 try:
411 old_value = oldvalues[key]
412 if type(new_value) is type([]):
413 new_value.sort()
414 old_value.sort()
415 if new_value != old_value:
416 changed[key] = old_value
417 except:
418 changed[key] = new_value
420 # list the changes
421 m = []
422 l = changed.items()
423 l.sort()
424 for propname, oldvalue in l:
425 prop = props[propname]
426 value = cl.get(nodeid, propname, None)
427 if isinstance(prop, hyperdb.Link):
428 link = self.db.classes[prop.classname]
429 key = link.labelprop(default_to_id=1)
430 if key:
431 if value:
432 value = link.get(value, key)
433 else:
434 value = ''
435 if oldvalue:
436 oldvalue = link.get(oldvalue, key)
437 else:
438 oldvalue = ''
439 change = '%s -> %s'%(oldvalue, value)
440 elif isinstance(prop, hyperdb.Multilink):
441 change = ''
442 if value is None: value = []
443 if oldvalue is None: oldvalue = []
444 l = []
445 link = self.db.classes[prop.classname]
446 key = link.labelprop(default_to_id=1)
447 # check for additions
448 for entry in value:
449 if entry in oldvalue: continue
450 if key:
451 l.append(link.get(entry, key))
452 else:
453 l.append(entry)
454 if l:
455 l.sort()
456 change = '+%s'%(', '.join(l))
457 l = []
458 # check for removals
459 for entry in oldvalue:
460 if entry in value: continue
461 if key:
462 l.append(link.get(entry, key))
463 else:
464 l.append(entry)
465 if l:
466 l.sort()
467 change += ' -%s'%(', '.join(l))
468 else:
469 change = '%s -> %s'%(oldvalue, value)
470 m.append('%s: %s'%(propname, change))
471 if m:
472 m.insert(0, '----------')
473 m.insert(0, '')
474 return '\n'.join(m)
476 # vim: set filetype=python ts=4 sw=4 et si