1 | #!@PYTHON@ |
---|
2 | # Copyright (C) 2002 |
---|
3 | # |
---|
4 | # This file is part of the email2trac utils |
---|
5 | # |
---|
6 | # This program is free software; you can redistribute it and/or modify it |
---|
7 | # under the terms of the GNU General Public License as published by the |
---|
8 | # Free Software Foundation; either version 2, or (at your option) any |
---|
9 | # later version. |
---|
10 | # |
---|
11 | # This program is distributed in the hope that it will be useful, |
---|
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
14 | # GNU General Public License for more details. |
---|
15 | # |
---|
16 | # You should have received a copy of the GNU General Public License |
---|
17 | # along with this program; if not, write to the Free Software |
---|
18 | # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA |
---|
19 | # |
---|
20 | """ |
---|
21 | emailfilter.py -- Email tickets to Trac. |
---|
22 | |
---|
23 | A simple MTA filter to create Trac tickets from inbound emails. |
---|
24 | |
---|
25 | Copyright 2005, Daniel Lundin <daniel@edgewall.com> |
---|
26 | Copyright 2005, Edgewall Software |
---|
27 | |
---|
28 | Changed By: Bas van der Vlies <basv@sara.nl> |
---|
29 | Date : 13 September 2005 |
---|
30 | Descr. : Added config file and command line options, spam level |
---|
31 | detection, reply address and mailto option. Unicode support |
---|
32 | |
---|
33 | Changed By: Walter de Jong <walter@sara.nl> |
---|
34 | Descr. : multipart-message code and trac attachments |
---|
35 | |
---|
36 | |
---|
37 | The scripts reads emails from stdin and inserts directly into a Trac database. |
---|
38 | MIME headers are mapped as follows: |
---|
39 | |
---|
40 | * From: => Reporter |
---|
41 | => CC (Optional via reply_address option) |
---|
42 | * Subject: => Summary |
---|
43 | * Body => Description |
---|
44 | * Component => Can be set to SPAM via spam_level option |
---|
45 | |
---|
46 | How to use |
---|
47 | ---------- |
---|
48 | * Create an config file: |
---|
49 | [DEFAULT] # REQUIRED |
---|
50 | project : /data/trac/test # REQUIRED |
---|
51 | debug : 1 # OPTIONAL, if set print some DEBUG info |
---|
52 | spam_level : 4 # OPTIONAL, if set check for SPAM mail |
---|
53 | reply_address: 1 # OPTIONAL, if set then fill in ticket CC field |
---|
54 | umask : 022 # OPTIONAL, if set then use this umask for creation of the attachments |
---|
55 | mailto_link : 1 # OPTIONAL, if set then [mailto:<CC>] in description |
---|
56 | trac_version : 0.8 # OPTIONAL, default is 0.9 |
---|
57 | |
---|
58 | [jouvin] # OPTIONAL project declaration, if set both fields necessary |
---|
59 | project : /data/trac/jouvin # use -p|--project jouvin. |
---|
60 | |
---|
61 | * default config file is : /etc/email2trac.conf |
---|
62 | |
---|
63 | * Commandline opions: |
---|
64 | -h | --help |
---|
65 | -c <value> | --component=<value> |
---|
66 | -f <config file> | --file=<config file> |
---|
67 | -p <project name> | --project=<project name> |
---|
68 | |
---|
69 | SVN Info: |
---|
70 | $Id: email2trac.py.in 22 2006-01-15 10:53:48Z bas $ |
---|
71 | """ |
---|
72 | |
---|
73 | import os |
---|
74 | import sys |
---|
75 | import string |
---|
76 | import getopt |
---|
77 | import stat |
---|
78 | import time |
---|
79 | import email |
---|
80 | import re |
---|
81 | import urllib |
---|
82 | import unicodedata |
---|
83 | import ConfigParser |
---|
84 | from email import Header |
---|
85 | from stat import * |
---|
86 | import mimetypes |
---|
87 | |
---|
88 | trac_default_version = 0.9 |
---|
89 | |
---|
90 | class TicketEmailParser(object): |
---|
91 | env = None |
---|
92 | comment = '> ' |
---|
93 | |
---|
94 | def __init__(self, env, parameters, version): |
---|
95 | self.env = env |
---|
96 | |
---|
97 | # Database connection |
---|
98 | # |
---|
99 | self.db = None |
---|
100 | |
---|
101 | self.VERSION = version |
---|
102 | if self.VERSION > 0.8: |
---|
103 | self.new_ticket = ticket.Ticket |
---|
104 | self.get_config = self.env.config.get |
---|
105 | else: |
---|
106 | self.new_ticket = Ticket.Ticket |
---|
107 | self.get_config = self.env.get_config |
---|
108 | |
---|
109 | if parameters.has_key('umask'): |
---|
110 | os.umask(int(parameters['umask'], 8)) |
---|
111 | |
---|
112 | if parameters.has_key('debug'): |
---|
113 | self.DEBUG = int(parameters['debug']) |
---|
114 | else: |
---|
115 | self.DEBUG = 0 |
---|
116 | |
---|
117 | if parameters.has_key('reply_address'): |
---|
118 | self.CC = int(parameters['reply_address']) |
---|
119 | else: |
---|
120 | self.CC = 0 |
---|
121 | |
---|
122 | if parameters.has_key('mailto_link'): |
---|
123 | self.MAILTO = int(parameters['mailto_link']) |
---|
124 | else: |
---|
125 | self.MAILTO = 0 |
---|
126 | |
---|
127 | if parameters.has_key('spam_level'): |
---|
128 | self.SPAM_LEVEL = int(parameters['spam_level']) |
---|
129 | else: |
---|
130 | self.SPAM_LEVEL = 0 |
---|
131 | |
---|
132 | if parameters.has_key('email_comment'): |
---|
133 | self.comment = str(parameters['email_comment']) |
---|
134 | |
---|
135 | if parameters.has_key('email_header'): |
---|
136 | self.EMAIL_HEADER = int(parameters['email_header']) |
---|
137 | else: |
---|
138 | self.EMAIL_HEADER = 0 |
---|
139 | |
---|
140 | |
---|
141 | # X-Spam-Score: *** (3.255) BAYES_50,DNS_FROM_AHBL_RHSBL,HTML_ |
---|
142 | # Note if Spam_level then '*' are included |
---|
143 | def spam(self, message): |
---|
144 | if message.has_key('X-Spam-Score'): |
---|
145 | spam_l = string.split(message['X-Spam-Score']) |
---|
146 | number = spam_l[0].count('*') |
---|
147 | |
---|
148 | if number >= self.SPAM_LEVEL: |
---|
149 | return number |
---|
150 | |
---|
151 | return 0 |
---|
152 | |
---|
153 | def to_unicode(self, str): |
---|
154 | """ |
---|
155 | Email has 7 bit ASCII code, convert it to unicode with the charset |
---|
156 | that is encoded in 7-bit ASCII code and encode it as utf-8 so TRAC |
---|
157 | understands it. |
---|
158 | """ |
---|
159 | results = Header.decode_header(str) |
---|
160 | str = None |
---|
161 | for text,format in results: |
---|
162 | if format: |
---|
163 | try: |
---|
164 | temp = unicode(text, format) |
---|
165 | except UnicodeError: |
---|
166 | # This always works |
---|
167 | # |
---|
168 | temp = unicode(text, 'iso-8859-15') |
---|
169 | temp = temp.encode('utf-8') |
---|
170 | else: |
---|
171 | temp = string.strip(text) |
---|
172 | |
---|
173 | if str: |
---|
174 | str = '%s %s' %(str, temp) |
---|
175 | else: |
---|
176 | str = temp |
---|
177 | |
---|
178 | return str |
---|
179 | |
---|
180 | def debug_attachments(self, message): |
---|
181 | n = 0 |
---|
182 | for part in message.walk(): |
---|
183 | if part.get_content_maintype() == 'multipart': # multipart/* is just a container |
---|
184 | print 'TD: multipart container' |
---|
185 | continue |
---|
186 | |
---|
187 | n = n + 1 |
---|
188 | print 'TD: part%d: Content-Type: %s' % (n, part.get_content_type()) |
---|
189 | print 'TD: part%d: filename: %s' % (n, part.get_filename()) |
---|
190 | |
---|
191 | if part.is_multipart(): |
---|
192 | print 'TD: this part is multipart' |
---|
193 | payload = part.get_payload(decode=1) |
---|
194 | print 'TD: payload:', payload |
---|
195 | else: |
---|
196 | print 'TD: this part is not multipart' |
---|
197 | |
---|
198 | part_file = '/var/tmp/part%d' % n |
---|
199 | print 'TD: writing part%d (%s)' % (n,part_file) |
---|
200 | fx = open(part_file, 'wb') |
---|
201 | text = part.get_payload(decode=1) |
---|
202 | if not text: |
---|
203 | text = '(None)' |
---|
204 | fx.write(text) |
---|
205 | fx.close() |
---|
206 | try: |
---|
207 | os.chmod(part_file,S_IRWXU|S_IRWXG|S_IRWXO) |
---|
208 | except OSError: |
---|
209 | pass |
---|
210 | |
---|
211 | def email_header_txt(self, m): |
---|
212 | # if not m['Subject']: |
---|
213 | # subject = '(geen subject)' |
---|
214 | # else: |
---|
215 | # subject = self.to_unicode(m['Subject']) |
---|
216 | # |
---|
217 | # head = "'''Subject:''' %s [[BR]]" % subject |
---|
218 | # if m['From'] and len(m['From']) > 0: |
---|
219 | # head = "%s'''From:''' %s [[BR]]" % (head, m['From']) |
---|
220 | # if m['Date'] and len(m['Date']) > 0: |
---|
221 | # head = "%s'''Date:''' %s [[BR]]" %(head, m['Date']) |
---|
222 | |
---|
223 | str = '' |
---|
224 | if m['To'] and len(m['To']) > 0 and m['To'] != 'hic@sara.nl': |
---|
225 | str = "'''To:''' %s [[BR]]" %(m['To']) |
---|
226 | if m['Cc'] and len(m['Cc']) > 0: |
---|
227 | str = "%s'''Cc:''' %s [[BR]]" % (str, m['Cc']) |
---|
228 | |
---|
229 | return str |
---|
230 | |
---|
231 | def parse(self, fp): |
---|
232 | msg = email.message_from_file(fp) |
---|
233 | if not msg: |
---|
234 | return |
---|
235 | |
---|
236 | if self.DEBUG > 1: # save the entire e-mail message text |
---|
237 | msg_file = '/var/tmp/msg.txt' |
---|
238 | print 'TD: saving email to %s' % msg_file |
---|
239 | fx = open(msg_file, 'wb') |
---|
240 | fx.write('%s' % msg) |
---|
241 | fx.close() |
---|
242 | try: |
---|
243 | os.chmod(msg_file,S_IRWXU|S_IRWXG|S_IRWXO) |
---|
244 | except OSError: |
---|
245 | pass |
---|
246 | |
---|
247 | self.db = self.env.get_db_cnx() |
---|
248 | tkt = self.new_ticket(self.env) |
---|
249 | tkt['status'] = 'new' |
---|
250 | |
---|
251 | # Some defaults |
---|
252 | # |
---|
253 | tkt['milestone'] = self.get_config('ticket', 'default_milestone') |
---|
254 | tkt['priority'] = self.get_config('ticket', 'default_priority') |
---|
255 | tkt['severity'] = self.get_config('ticket', 'default_severity') |
---|
256 | tkt['version'] = self.get_config('ticket', 'default_version') |
---|
257 | |
---|
258 | if not msg['Subject']: |
---|
259 | tkt['summary'] = '(geen subject)' |
---|
260 | else: |
---|
261 | tkt['summary'] = self.to_unicode(msg['Subject']) |
---|
262 | |
---|
263 | if self.SPAM_LEVEL and self.spam(msg): |
---|
264 | print 'This message is a SPAM. Automatic ticket insertion refused (SPAM level > %d' % self.SPAM_LEVEL |
---|
265 | sys.exit(1) |
---|
266 | |
---|
267 | if settings.has_key('component'): |
---|
268 | tkt['component'] = settings['component'] |
---|
269 | else: |
---|
270 | tkt['component'] = self.get_config('ticket', 'default_component') |
---|
271 | |
---|
272 | # Get default owner for component |
---|
273 | # |
---|
274 | cursor = self.db.cursor() |
---|
275 | sql = 'SELECT owner FROM component WHERE name=\'%s\'' % tkt['component'] |
---|
276 | cursor.execute(sql) |
---|
277 | tkt['owner'] = cursor.fetchone()[0] |
---|
278 | |
---|
279 | from_str = self.to_unicode(msg['from']) |
---|
280 | tkt['reporter'] = from_str |
---|
281 | if self.CC: |
---|
282 | tkt['cc'] = from_str |
---|
283 | |
---|
284 | # produce e-mail like header |
---|
285 | head = '' |
---|
286 | if self.EMAIL_HEADER > 0: |
---|
287 | head = self.email_header_txt(msg) |
---|
288 | |
---|
289 | if self.DEBUG > 0: |
---|
290 | self.debug_attachments(msg) |
---|
291 | |
---|
292 | # |
---|
293 | # put the message text in the ticket description |
---|
294 | # message text can be plain text or html or something else |
---|
295 | # |
---|
296 | has_description = 0 |
---|
297 | for part in msg.walk(): |
---|
298 | if part.get_content_maintype() == 'multipart': # 'multipart/*' is a container for multipart messages |
---|
299 | continue |
---|
300 | |
---|
301 | if part.get_content_type() == 'text/plain': |
---|
302 | body_text = part.get_payload(decode=1) # try to decode |
---|
303 | if not body_text: # decode failed |
---|
304 | body_text = part.get_payload(decode=0) # do not decode |
---|
305 | |
---|
306 | tkt['description'] = '\n{{{\n\n%s\n}}}\n' % body_text |
---|
307 | |
---|
308 | elif part.get_content_type() == 'text/html': |
---|
309 | tkt['description'] = '%s\n\n(see attachment for HTML mail message)\n' % head |
---|
310 | body_text = tkt['description'] |
---|
311 | |
---|
312 | else: |
---|
313 | tkt['description'] = '%s\n\n(see attachment for message)\n' % head |
---|
314 | body_text = tkt['description'] |
---|
315 | |
---|
316 | has_description = 1 |
---|
317 | break # we have the description, so break |
---|
318 | |
---|
319 | if not has_description: |
---|
320 | tkt['description'] = '%s\n\n(no plain text message, see attachments)' % head |
---|
321 | has_description = 1 |
---|
322 | |
---|
323 | author, email_addr = email.Utils.parseaddr(msg['from']) |
---|
324 | if self.MAILTO: |
---|
325 | mailto = self.html_mailto_link(author, email_addr, self.to_unicode(msg['subject']), body_text) |
---|
326 | tkt['description'] = '%s\n%s %s' %(head, mailto, tkt['description']) |
---|
327 | |
---|
328 | if self.VERSION > 0.8: |
---|
329 | tkt['id'] = tkt.insert() |
---|
330 | else: |
---|
331 | tkt['id'] = tkt.insert(self.db) |
---|
332 | |
---|
333 | # |
---|
334 | # Just how to show to update description |
---|
335 | # |
---|
336 | #tkt['description'] = '\n{{{\n\n Bas is op nieuw bezig\n\n }}}\n' |
---|
337 | #tkt.save_changes(self.db, author, "Lekker bezig") |
---|
338 | # |
---|
339 | self.attachments(msg, tkt, author) |
---|
340 | |
---|
341 | |
---|
342 | def mail_line(self, str): |
---|
343 | return '%s %s' % (self.comment, str) |
---|
344 | |
---|
345 | |
---|
346 | def html_mailto_link(self, author, mail_addr, subject, body): |
---|
347 | if not author: |
---|
348 | author = mail_addr |
---|
349 | else: |
---|
350 | author = self.to_unicode(author) |
---|
351 | |
---|
352 | # Must find a fix |
---|
353 | # |
---|
354 | #arr = string.split(body, '\n') |
---|
355 | #arr = map(self.mail_line, arr) |
---|
356 | |
---|
357 | #body = string.join(arr, '\n') |
---|
358 | #body = '%s wrote:\n%s' %(author, body) |
---|
359 | |
---|
360 | # Obsolete for reference |
---|
361 | # |
---|
362 | #body = self.to_unicode(body) |
---|
363 | #body = urllib.quote(body) |
---|
364 | #body = Header.encode(body) |
---|
365 | # |
---|
366 | |
---|
367 | # Temporary fix |
---|
368 | body = '> Type your reply' |
---|
369 | str = 'mailto:%s?subject=%s&body=%s' % (urllib.quote(mail_addr), urllib.quote('Re: %s' % subject), urllib.quote(body)) |
---|
370 | str = '\n{{{\n#!html\n<a href="%s">Reply to: %s</a>\n}}}\n' %(str, author) |
---|
371 | |
---|
372 | return str |
---|
373 | |
---|
374 | def attachments(self, message, ticket, user): |
---|
375 | '''save any attachments as file in the ticket's directory''' |
---|
376 | |
---|
377 | count = 0 |
---|
378 | first = 0 |
---|
379 | for part in message.walk(): |
---|
380 | if part.get_content_maintype() == 'multipart': # multipart/* is just a container |
---|
381 | continue |
---|
382 | |
---|
383 | if not first: # first content is the message |
---|
384 | first = 1 |
---|
385 | if part.get_content_type() == 'text/plain': # if first is text, is was already put in the description |
---|
386 | continue |
---|
387 | |
---|
388 | filename = part.get_filename() |
---|
389 | if not filename: |
---|
390 | count = count + 1 |
---|
391 | filename = 'part%04d' % count |
---|
392 | |
---|
393 | ext = mimetypes.guess_extension(part.get_type()) |
---|
394 | if not ext: |
---|
395 | ext = '.bin' |
---|
396 | |
---|
397 | filename = '%s%s' % (filename, ext) |
---|
398 | else: |
---|
399 | filename = self.to_unicode(filename) |
---|
400 | |
---|
401 | if '/' in filename: |
---|
402 | filename = os.path.basename(filename) |
---|
403 | |
---|
404 | url_filename = urllib.quote(filename) |
---|
405 | |
---|
406 | if self.VERSION > 0.8: |
---|
407 | tmpfile = '/tmp/email2trac-ticket%sattachment' % str(ticket['id']) |
---|
408 | else: |
---|
409 | dir = os.path.join(self.env.get_attachments_dir(), 'ticket', |
---|
410 | urllib.quote(str(ticket['id']))) |
---|
411 | if not os.path.exists(dir): |
---|
412 | mkdir_p(dir, 0755) |
---|
413 | |
---|
414 | tmpfile = os.path.join(dir, url_filename) |
---|
415 | |
---|
416 | f = open(tmpfile, 'wb') |
---|
417 | text = part.get_payload(decode=1) |
---|
418 | if not text: |
---|
419 | text = '(None)' |
---|
420 | f.write(text) |
---|
421 | |
---|
422 | # get the filesize |
---|
423 | # |
---|
424 | stats = os.lstat(tmpfile) |
---|
425 | filesize = stats[stat.ST_SIZE] |
---|
426 | |
---|
427 | # Insert the attachment it differs for the different TRAC versions |
---|
428 | # |
---|
429 | if self.VERSION > 0.8: |
---|
430 | att = attachment.Attachment(self.env,'ticket',ticket['id']) |
---|
431 | att.insert(url_filename,f,filesize) |
---|
432 | f.close() |
---|
433 | else: |
---|
434 | cursor = self.db.cursor() |
---|
435 | cursor.execute('INSERT INTO attachment VALUES("%s","%s","%s",%d,%d,"%s","%s","%s")' |
---|
436 | %('ticket', urllib.quote(str(ticket['id'])), filename + '?format=raw', filesize, |
---|
437 | int(time.time()),'', user, 'e-mail') ) |
---|
438 | self.db.commit() |
---|
439 | |
---|
440 | |
---|
441 | def mkdir_p(dir, mode): |
---|
442 | '''do a mkdir -p''' |
---|
443 | |
---|
444 | arr = string.split(dir, '/') |
---|
445 | path = '' |
---|
446 | for part in arr: |
---|
447 | path = '%s/%s' % (path, part) |
---|
448 | try: |
---|
449 | stats = os.stat(path) |
---|
450 | except OSError: |
---|
451 | os.mkdir(path, mode) |
---|
452 | |
---|
453 | |
---|
454 | def ReadConfig(file, name): |
---|
455 | """ |
---|
456 | Parse the config file |
---|
457 | """ |
---|
458 | |
---|
459 | if not os.path.isfile(file): |
---|
460 | print 'File %s does not exists' %file |
---|
461 | sys.exit(1) |
---|
462 | |
---|
463 | config = ConfigParser.ConfigParser() |
---|
464 | try: |
---|
465 | config.read(file) |
---|
466 | except ConfigParser.MissingSectionHeaderError,detail: |
---|
467 | print detail |
---|
468 | sys.exit(1) |
---|
469 | |
---|
470 | |
---|
471 | # Use given project name else use defaults |
---|
472 | # |
---|
473 | if name: |
---|
474 | if not config.has_section(name): |
---|
475 | print "Not an valid project name: %s" %name |
---|
476 | print "Valid names: %s" %config.sections() |
---|
477 | sys.exit(1) |
---|
478 | |
---|
479 | project = dict() |
---|
480 | for option in config.options(name): |
---|
481 | project[option] = config.get(name, option) |
---|
482 | |
---|
483 | else: |
---|
484 | project = config.defaults() |
---|
485 | |
---|
486 | return project |
---|
487 | |
---|
488 | if __name__ == '__main__': |
---|
489 | # Default config file |
---|
490 | # |
---|
491 | configfile = '/etc/email2trac.conf' |
---|
492 | # configfile = './email2trac.conf' |
---|
493 | project = '' |
---|
494 | component = '' |
---|
495 | |
---|
496 | try: |
---|
497 | opts, args = getopt.getopt(sys.argv[1:], 'chf:p:', ['component=','help', 'file=', 'project=']) |
---|
498 | except getopt.error,detail: |
---|
499 | print __doc__ |
---|
500 | print detail |
---|
501 | sys.exit(1) |
---|
502 | |
---|
503 | project_name = None |
---|
504 | for opt,value in opts: |
---|
505 | if opt in [ '-h', '--help']: |
---|
506 | print __doc__ |
---|
507 | sys.exit(0) |
---|
508 | elif opt in ['-c', '--component']: |
---|
509 | component = value |
---|
510 | elif opt in ['-f', '--file']: |
---|
511 | configfile = value |
---|
512 | elif opt in ['-p', '--project']: |
---|
513 | project_name = value |
---|
514 | |
---|
515 | settings = ReadConfig(configfile, project_name) |
---|
516 | if not settings.has_key('project'): |
---|
517 | print __doc__ |
---|
518 | print 'No project defined in config file, eg:\n\t project: /data/trac/bas' |
---|
519 | sys.exit(1) |
---|
520 | |
---|
521 | if component: |
---|
522 | settings['component'] = component |
---|
523 | |
---|
524 | if settings.has_key('trac_version'): |
---|
525 | version = float(settings['trac_version']) |
---|
526 | else: |
---|
527 | version = trac_default_version |
---|
528 | |
---|
529 | #debug HvB |
---|
530 | #print settings |
---|
531 | |
---|
532 | if version > 0.8: |
---|
533 | from trac import attachment, config, env, ticket |
---|
534 | env = env.Environment(settings['project'], create=0) |
---|
535 | ticket_mod = ticket |
---|
536 | else: |
---|
537 | from trac import Environment, Ticket |
---|
538 | env = Environment.Environment(settings['project'], create=0) |
---|
539 | ticket_mod = Ticket |
---|
540 | |
---|
541 | tktparser = TicketEmailParser(env, settings, version) |
---|
542 | tktparser.parse(sys.stdin) |
---|
543 | |
---|
544 | # EOB |
---|