Code

fixed Apply Error that was raised, when property was deleted from class and we are...
[roundup.git] / roundup / roundupdb.py
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.91 2003-09-16 16:12:38 kedder 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
79       
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()
86         
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.
129         
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(', '.join(sendto),
292                                                       subject, author)
294         tracker_name = encode_header(self.db.config.TRACKER_NAME)
295         writer.addheader('Reply-To', straddr((tracker_name, from_address)))
296         if messageid:
297             writer.addheader('Message-Id', messageid)
298         if inreplyto:
299             writer.addheader('In-Reply-To', inreplyto)
301         # attach files
302         if message_files:
303             part = writer.startmultipartbody('mixed')
304             part = writer.nextpart()
305             part.addheader('Content-Transfer-Encoding', 'quoted-printable')
306             body = part.startbody('text/plain; charset=utf-8')
307             body.write(content_encoded)
308             for fileid in message_files:
309                 name = files.get(fileid, 'name')
310                 mime_type = files.get(fileid, 'type')
311                 content = files.get(fileid, 'content')
312                 part = writer.nextpart()
313                 if mime_type == 'text/plain':
314                     part.addheader('Content-Disposition',
315                         'attachment;\n filename="%s"'%name)
316                     part.addheader('Content-Transfer-Encoding', '7bit')
317                     body = part.startbody('text/plain')
318                     body.write(content)
319                 else:
320                     # some other type, so encode it
321                     if not mime_type:
322                         # this should have been done when the file was saved
323                         mime_type = mimetypes.guess_type(name)[0]
324                     if mime_type is None:
325                         mime_type = 'application/octet-stream'
326                     part.addheader('Content-Disposition',
327                         'attachment;\n filename="%s"'%name)
328                     part.addheader('Content-Transfer-Encoding', 'base64')
329                     body = part.startbody(mime_type)
330                     body.write(base64.encodestring(content))
331             writer.lastpart()
332         else:
333             writer.addheader('Content-Transfer-Encoding', 'quoted-printable')
334             body = writer.startbody('text/plain; charset=utf-8')
335             body.write(content_encoded)
337         mailer.smtp_send(sendto, message)
339     def email_signature(self, nodeid, msgid):
340         ''' Add a signature to the e-mail with some useful information
341         '''
342         # simplistic check to see if the url is valid,
343         # then append a trailing slash if it is missing
344         base = self.db.config.TRACKER_WEB 
345         if (not isinstance(base , type('')) or
346             not (base.startswith('http://') or base.startswith('https://'))):
347             base = "Configuration Error: TRACKER_WEB isn't a " \
348                 "fully-qualified URL"
349         elif base[-1] != '/' :
350             base += '/'
351         web = base + self.classname + nodeid
353         # ensure the email address is properly quoted
354         email = straddr((self.db.config.TRACKER_NAME,
355             self.db.config.TRACKER_EMAIL))
357         line = '_' * max(len(web)+2, len(email))
358         return '%s\n%s\n<%s>\n%s'%(line, email, web, line)
361     def generateCreateNote(self, nodeid):
362         """Generate a create note that lists initial property values
363         """
364         cn = self.classname
365         cl = self.db.classes[cn]
366         props = cl.getprops(protected=0)
368         # list the values
369         m = []
370         l = props.items()
371         l.sort()
372         for propname, prop in l:
373             value = cl.get(nodeid, propname, None)
374             # skip boring entries
375             if not value:
376                 continue
377             if isinstance(prop, hyperdb.Link):
378                 link = self.db.classes[prop.classname]
379                 if value:
380                     key = link.labelprop(default_to_id=1)
381                     if key:
382                         value = link.get(value, key)
383                 else:
384                     value = ''
385             elif isinstance(prop, hyperdb.Multilink):
386                 if value is None: value = []
387                 l = []
388                 link = self.db.classes[prop.classname]
389                 key = link.labelprop(default_to_id=1)
390                 if key:
391                     value = [link.get(entry, key) for entry in value]
392                 value.sort()
393                 value = ', '.join(value)
394             m.append('%s: %s'%(propname, value))
395         m.insert(0, '----------')
396         m.insert(0, '')
397         return '\n'.join(m)
399     def generateChangeNote(self, nodeid, oldvalues):
400         """Generate a change note that lists property changes
401         """
402         if __debug__ :
403             if not isinstance(oldvalues, type({})) :
404                 raise TypeError("'oldvalues' must be dict-like, not %s."%
405                     type(oldvalues))
407         cn = self.classname
408         cl = self.db.classes[cn]
409         changed = {}
410         props = cl.getprops(protected=0)
412         # determine what changed
413         for key in oldvalues.keys():
414             if key in ['files','messages']:
415                 continue
416             if key in ('activity', 'creator', 'creation'):
417                 continue
418             # not all keys from oldvalues might be available in database
419             # this happens when property was deleted
420             try:                
421                 new_value = cl.get(nodeid, key)
422             except KeyError:
423                 continue
424             # the old value might be non existent
425             # this happens when property was added
426             try:
427                 old_value = oldvalues[key]
428                 if type(new_value) is type([]):
429                     new_value.sort()
430                     old_value.sort()
431                 if new_value != old_value:
432                     changed[key] = old_value
433             except:
434                 changed[key] = new_value
436         # list the changes
437         m = []
438         l = changed.items()
439         l.sort()
440         for propname, oldvalue in l:
441             prop = props[propname]
442             value = cl.get(nodeid, propname, None)
443             if isinstance(prop, hyperdb.Link):
444                 link = self.db.classes[prop.classname]
445                 key = link.labelprop(default_to_id=1)
446                 if key:
447                     if value:
448                         value = link.get(value, key)
449                     else:
450                         value = ''
451                     if oldvalue:
452                         oldvalue = link.get(oldvalue, key)
453                     else:
454                         oldvalue = ''
455                 change = '%s -> %s'%(oldvalue, value)
456             elif isinstance(prop, hyperdb.Multilink):
457                 change = ''
458                 if value is None: value = []
459                 if oldvalue is None: oldvalue = []
460                 l = []
461                 link = self.db.classes[prop.classname]
462                 key = link.labelprop(default_to_id=1)
463                 # check for additions
464                 for entry in value:
465                     if entry in oldvalue: continue
466                     if key:
467                         l.append(link.get(entry, key))
468                     else:
469                         l.append(entry)
470                 if l:
471                     l.sort()
472                     change = '+%s'%(', '.join(l))
473                     l = []
474                 # check for removals
475                 for entry in oldvalue:
476                     if entry in value: continue
477                     if key:
478                         l.append(link.get(entry, key))
479                     else:
480                         l.append(entry)
481                 if l:
482                     l.sort()
483                     change += ' -%s'%(', '.join(l))
484             else:
485                 change = '%s -> %s'%(oldvalue, value)
486             m.append('%s: %s'%(propname, change))
487         if m:
488             m.insert(0, '----------')
489             m.insert(0, '')
490         return '\n'.join(m)
492 # vim: set filetype=python ts=4 sw=4 et si