source: emailtotracscript/trunk/email2trac.py.in @ 149

Last change on this file since 149 was 149, checked in by jouvin, 17 years ago

EmailToTracScript?
EmailtoTracScript?:

Blacklist (don't register as ticket ) mail from MAILER-DAEMON

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 23.2 KB
Line 
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# For vi/emacs or other use tabstop=4 (vi: set ts=4)
21#
22"""
23email2trac.py -- Email tickets to Trac.
24
25A simple MTA filter to create Trac tickets from inbound emails.
26
27Copyright 2005, Daniel Lundin <daniel@edgewall.com>
28Copyright 2005, Edgewall Software
29
30Changed By: Bas van der Vlies <basv@sara.nl>
31Date      : 13 September 2005
32Descr.    : Added config file and command line options, spam level
33            detection, reply address and mailto option. Unicode support
34
35Changed By: Walter de Jong <walter@sara.nl>
36Descr.    : multipart-message code and trac attachments
37
38
39The scripts reads emails from stdin and inserts directly into a Trac database.
40MIME headers are mapped as follows:
41
42        * From:      => Reporter
43                     => CC (Optional via reply_address option)
44        * Subject:   => Summary
45        * Body       => Description
46        * Component  => Can be set to SPAM via spam_level option
47
48How to use
49----------
50 * Create an config file:
51        [DEFAULT]                      # REQUIRED
52        project      : /data/trac/test # REQUIRED
53        debug        : 1               # OPTIONAL, if set print some DEBUG info
54        spam_level   : 4               # OPTIONAL, if set check for SPAM mail
55        reply_address: 1               # OPTIONAL, if set then fill in ticket CC field
56        umask        : 022             # OPTIONAL, if set then use this umask for creation of the attachments
57        mailto_link  : 1               # OPTIONAL, if set then [mailto:<>] in description
58        mailto_cc    : basv@sara.nl    # OPTIONAL, use this address as CC in mailto line
59        ticket_update: 1               # OPTIONAL, if set then check if this is an update for a ticket
60        trac_version : 0.8             # OPTIONAL, default is 0.10
61
62        [jouvin]                       # OPTIONAL project declaration, if set both fields necessary
63        project      : /data/trac/jouvin # use -p|--project jouvin. 
64       
65 * default config file is : /etc/email2trac.conf
66
67 * Commandline opions:
68                -h | --help
69                -c <value> | --component=<value>
70                -f <config file> | --file=<config file>
71                -p <project name> | --project=<project name>
72
73SVN Info:
74        $Id: email2trac.py.in 149 2007-03-08 21:53:07Z jouvin $
75"""
76import os
77import sys
78import string
79import getopt
80import stat
81import time
82import email
83import email.Iterators
84import email.Header
85import re
86import urllib
87import unicodedata
88import ConfigParser
89from stat import *
90import mimetypes
91import syslog
92import traceback
93
94
95# Some global variables
96#
97trac_default_version = 0.10
98m = None
99
100
101class TicketEmailParser(object):
102        env = None
103        comment = '> '
104   
105        def __init__(self, env, parameters, version):
106                self.env = env
107
108                # Database connection
109                #
110                self.db = None
111
112                # Some useful mail constants
113                #
114                self.author = None
115                self.email_addr = None
116                self.email_field = None
117
118                self.VERSION = version
119                if self.VERSION == 0.8:
120                        self.get_config = self.env.get_config
121                else:
122                        self.get_config = self.env.config.get
123
124                if parameters.has_key('umask'):
125                        os.umask(int(parameters['umask'], 8))
126
127                if parameters.has_key('debug'):
128                        self.DEBUG = int(parameters['debug'])
129                else:
130                        self.DEBUG = 0
131
132                if parameters.has_key('mailto_link'):
133                        self.MAILTO = int(parameters['mailto_link'])
134                        if parameters.has_key('mailto_cc'):
135                                self.MAILTO_CC = parameters['mailto_cc']
136                        else:
137                                self.MAILTO_CC = ''
138                else:
139                        self.MAILTO = 0
140
141                if parameters.has_key('spam_level'):
142                        self.SPAM_LEVEL = int(parameters['spam_level'])
143                else:
144                        self.SPAM_LEVEL = 0
145
146                if parameters.has_key('email_comment'):
147                        self.comment = str(parameters['email_comment'])
148
149                if parameters.has_key('email_header'):
150                        self.EMAIL_HEADER = int(parameters['email_header'])
151                else:
152                        self.EMAIL_HEADER = 0
153
154                if parameters.has_key('alternate_notify_template'):
155                        self.notify_template = str(parameters['alternate_notify_template'])
156                else:
157                        self.notify_template = None
158
159                if parameters.has_key('reply_all'):
160                        self.REPLY_ALL = int(parameters['reply_all'])
161                else:
162                        self.REPLY_ALL = 0
163
164                if parameters.has_key('ticket_update'):
165                        self.TICKET_UPDATE = int(parameters['ticket_update'])
166                else:
167                        self.TICKET_UPDATE = 0
168
169                if parameters.has_key('drop_spam'):
170                        self.DROP_SPAM = int(parameters['drop_spam'])
171                else:
172                        self.DROP_SPAM = 0
173
174                if parameters.has_key('verbatim_format'):
175                        self.VERBATIM_FORMAT = int(parameters['verbatim_format'])
176                else:
177                        self.VERBATIM_FORMAT = 1
178
179                if parameters.has_key('strip_signature'):
180                        self.STRIP_SIGNATURE = int(parameters['strip_signature'])
181                else:
182                        self.STRIP_SIGNATURE = 0
183
184                if parameters.has_key('use_textwrap'):
185                        self.USE_TEXTWRAP = int(parameters['use_textwrap'])
186                else:
187                        self.USE_TEXTWRAP = 0
188
189        # X-Spam-Score: *** (3.255) BAYES_50,DNS_FROM_AHBL_RHSBL,HTML_
190        # Note if Spam_level then '*' are included
191        def spam(self, message):
192                if message.has_key('X-Spam-Score'):
193                        spam_l = string.split(message['X-Spam-Score'])
194                        number = spam_l[0].count('*')
195
196                        if number >= self.SPAM_LEVEL:
197                                return 'Spam'
198
199                elif message.has_key('X-Virus-found'):                  # treat virus mails as spam
200                        return 'Spam'
201
202                return self.get_config('ticket', 'default_component')
203
204        def blacklisted_from(self):
205                FROM_RE = re.compile(r"""
206                    MAILER-DAEMON@
207                    """, re.VERBOSE)
208                result =  FROM_RE.search(self.email_addr)
209                if result:
210                        return True
211                else:
212                        return False
213
214        def email_to_unicode(self, message_str):
215                """
216                Email has 7 bit ASCII code, convert it to unicode with the charset
217        that is encoded in 7-bit ASCII code and encode it as utf-8 so Trac
218                understands it.
219                """
220                results =  email.Header.decode_header(message_str)
221                str = None
222                for text,format in results:
223                        if format:
224                                try:
225                                        temp = unicode(text, format)
226                                except UnicodeError, detail:
227                                        # This always works
228                                        #
229                                        temp = unicode(text, 'iso-8859-15')
230                                except LookupError, detail:
231                                        #text = 'ERROR: Could not find charset: %s, please install' %format
232                                        #temp = unicode(text, 'iso-8859-15')
233                                        temp = message_str
234                                       
235                        else:
236                                temp = string.strip(text)
237                                temp = unicode(text, 'iso-8859-15')
238
239                        if str:
240                                str = '%s %s' %(str, temp)
241                        else:
242                                str = '%s' %temp
243
244                #str = str.encode('utf-8')
245                return str
246
247        def debug_attachments(self, message):
248                n = 0
249                for part in message.walk():
250                        if part.get_content_maintype() == 'multipart':      # multipart/* is just a container
251                                print 'TD: multipart container'
252                                continue
253
254                        n = n + 1
255                        print 'TD: part%d: Content-Type: %s' % (n, part.get_content_type())
256                        print 'TD: part%d: filename: %s' % (n, part.get_filename())
257
258                        if part.is_multipart():
259                                print 'TD: this part is multipart'
260                                payload = part.get_payload(decode=1)
261                                print 'TD: payload:', payload
262                        else:
263                                print 'TD: this part is not multipart'
264
265                        part_file = '/var/tmp/part%d' % n
266                        print 'TD: writing part%d (%s)' % (n,part_file)
267                        fx = open(part_file, 'wb')
268                        text = part.get_payload(decode=1)
269                        if not text:
270                                text = '(None)'
271                        fx.write(text)
272                        fx.close()
273                        try:
274                                os.chmod(part_file,S_IRWXU|S_IRWXG|S_IRWXO)
275                        except OSError:
276                                pass
277
278        def email_header_txt(self, m):
279                """
280                Display To and CC addresses in description field
281                """
282                str = ''
283                if m['To'] and len(m['To']) > 0 and m['To'] != 'hic@sara.nl':
284                        str = "'''To:''' %s [[BR]]" %(m['To'])
285                if m['Cc'] and len(m['Cc']) > 0:
286                        str = "%s'''Cc:''' %s [[BR]]" % (str, m['Cc'])
287
288                return  self.email_to_unicode(str)
289
290
291        def set_owner(self, ticket):
292                """
293                Select default owner for ticket component
294                """
295                cursor = self.db.cursor()
296                sql = "SELECT owner FROM component WHERE name='%s'" % ticket['component']
297                cursor.execute(sql)
298                try:
299                        ticket['owner'] = cursor.fetchone()[0]
300                except TypeError, detail:
301                        ticket['owner'] = "UNKNOWN"
302
303        def get_author_emailaddrs(self, message):
304                """
305                Get the default author name and email address from the message
306                """
307                temp = self.email_to_unicode(message['from'])
308                #print temp.encode('utf-8')
309
310                self.author, self.email_addr  = email.Utils.parseaddr(temp)
311                #print self.author.encode('utf-8', 'replace')
312
313                # Look for email address in registered trac users
314                #
315                if self.VERSION == 0.8:
316                        users = []
317                else:
318                        users = [ u for (u, n, e) in self.env.get_known_users(self.db)
319                                if e == self.email_addr ]
320
321                if len(users) == 1:
322                        self.email_field = users[0]
323                else:
324                        self.email_field =  self.email_to_unicode(message['from'])
325
326        def set_reply_fields(self, ticket, message):
327                """
328                Set all the right fields for a new ticket
329                """
330                ticket['reporter'] = self.email_field
331
332                # Put all CC-addresses in ticket CC field
333                #
334                if self.REPLY_ALL:
335                        #tos = message.get_all('to', [])
336                        ccs = message.get_all('cc', [])
337
338                        addrs = email.Utils.getaddresses(ccs)
339                        if not addrs:
340                                return
341
342                        # Remove reporter email address if notification is
343                        # on
344                        #
345                        if self.notification:
346                                try:
347                                        addrs.remove((self.author, self.email_addr))
348                                except ValueError, detail:
349                                        pass
350
351                        for name,mail in addrs:
352                                try:
353                                        mail_list = '%s, %s' %(mail_list, mail)
354                                except:
355                                        mail_list = mail
356
357                        if mail_list:
358                                ticket['cc'] = self.email_to_unicode(mail_list)
359
360        def save_email_for_debug(self, message, tempfile=False):
361                if tempfile:
362                        import tempfile
363                        msg_file = tempfile.mktemp('.email2trac')
364                else:
365                        msg_file = '/var/tmp/msg.txt'
366                print 'TD: saving email to %s' % msg_file
367                fx = open(msg_file, 'wb')
368                fx.write('%s' % message)
369                fx.close()
370                try:
371                        os.chmod(msg_file,S_IRWXU|S_IRWXG|S_IRWXO)
372                except OSError:
373                        pass
374
375        def ticket_update(self, m):
376                """
377                If the current email is a reply to an existing ticket, this function
378                will append the contents of this email to that ticket, instead of
379                creating a new one.
380                """
381                if not m['Subject']:
382                        return False
383                else:
384                        subject  = self.email_to_unicode(m['Subject'])
385
386                TICKET_RE = re.compile(r"""
387                                        (?P<ticketnr>[#][0-9]+:)
388                                        """, re.VERBOSE)
389
390                result =  TICKET_RE.search(subject)
391                if not result:
392                        return False
393
394                body_text = self.get_body_text(m)
395
396                # Strip '#' and ':' from ticket_id
397                #
398                ticket_id = result.group('ticketnr')
399                ticket_id = int(ticket_id[1:-1])
400
401                # Get current time
402                #
403                when = int(time.time())
404
405                if self.VERSION  == 0.8:
406                        tkt = Ticket(self.db, ticket_id)
407                        tkt.save_changes(self.db, self.author, body_text, when)
408                else:
409                        try:
410                                tkt = Ticket(self.env, ticket_id, self.db)
411                        except util.TracError, detail:
412                                return False
413
414                        tkt.save_changes(self.author, body_text, when)
415                        tkt['id'] = ticket_id
416
417                if self.VERSION  == 0.9:
418                        self.attachments(m, tkt, True)
419                else:
420                        self.attachments(m, tkt)
421
422                if self.notification:
423                        self.notify(tkt, False, when)
424
425                return True
426
427        def new_ticket(self, msg):
428                """
429                Create a new ticket
430                """
431                tkt = Ticket(self.env)
432                tkt['status'] = 'new'
433
434                # Some defaults
435                #
436                tkt['milestone'] = self.get_config('ticket', 'default_milestone')
437                tkt['priority'] = self.get_config('ticket', 'default_priority')
438                tkt['severity'] = self.get_config('ticket', 'default_severity')
439                tkt['version'] = self.get_config('ticket', 'default_version')
440
441                if not msg['Subject']:
442                        tkt['summary'] = u'(geen subject)'
443                else:
444                        tkt['summary'] = self.email_to_unicode(msg['Subject'])
445
446
447                if settings.has_key('component'):
448                        tkt['component'] = settings['component']
449                else:
450                        tkt['component'] = self.spam(msg)
451
452                # Discard SPAM messages.
453                #
454                if self.DROP_SPAM and (tkt['component'] == 'Spam'):
455                        if self.DROP_SPAM > 2 :
456                          print 'This message is a SPAM. Automatic ticket insertion refused (SPAM level > %d' % self.SPAM_LEVEL
457                        return False   
458
459                # Set default owner for component
460                #
461                self.set_owner(tkt)
462                self.set_reply_fields(tkt, msg)
463
464                # produce e-mail like header
465                #
466                head = ''
467                if self.EMAIL_HEADER > 0:
468                        head = self.email_header_txt(msg)
469                       
470                body_text = self.get_body_text(msg)
471
472                tkt['description'] = '\r\n%s\r\n%s' \
473                        %(head, body_text)
474
475                when = int(time.time())
476                if self.VERSION == 0.8:
477                        ticket_id = tkt.insert(self.db)
478                else:
479                        ticket_id = tkt.insert()
480                        tkt['id'] = ticket_id
481
482                changed = False
483                comment = ''
484
485                # Rewrite the description if we have mailto enabled
486                #
487                if self.MAILTO:
488                        changed = True
489                        comment = u'\nadded mailto line\n'
490                        mailto = self.html_mailto_link(tkt['summary'], ticket_id, body_text)
491                        tkt['description'] = u'\r\n%s\r\n%s%s\r\n' \
492                                %(head, mailto, body_text)
493
494                n =  self.attachments(msg, tkt)
495                if n:
496                        changed = True
497                        comment = '%s\nThis message has %d attachment(s)\n' %(comment, n)
498
499                if changed:
500                        if self.VERSION  == 0.8:
501                                tkt.save_changes(self.db, self.author, comment)
502                        else:
503                                tkt.save_changes(self.author, comment)
504
505                #print tkt.get_changelog(self.db, when)
506
507                if self.notification:
508                        self.notify(tkt, True)
509                        #self.notify(tkt, False)
510
511        def parse(self, fp):
512                global m
513
514                m = email.message_from_file(fp)
515                if not m:
516                        return
517
518                if self.DEBUG > 1:        # save the entire e-mail message text
519                        self.save_email_for_debug(m)
520                        self.debug_attachments(m)
521
522                self.db = self.env.get_db_cnx()
523                self.get_author_emailaddrs(m)
524                if self.blacklisted_from():
525                        if self.DEBUG > 1 :
526                                print 'Message rejected : From: in blacklist'
527                        return False
528
529                if self.get_config('notification', 'smtp_enabled') in ['true']:
530                        self.notification = 1
531                else:
532                        self.notification = 0
533
534                # Must we update existing tickets
535                #
536                if self.TICKET_UPDATE > 0:
537                        if self.ticket_update(m):
538                                return True
539
540                self.new_ticket(m)
541
542        def strip_signature(self, text):
543                """
544                Strip signature from message, inspired by Mailman software
545                """
546                body = []
547                for line in text.splitlines():
548                        if line == '-- ':
549                                break
550                        body.append(line)
551
552                return ('\n'.join(body))
553
554        def get_body_text(self, msg):
555                """
556                put the message text in the ticket description or in the changes field.
557                message text can be plain text or html or something else
558                """
559                has_description = 0
560                encoding = True
561                ubody_text = u'No plain text message'
562                for part in msg.walk():
563
564                        # 'multipart/*' is a container for multipart messages
565                        #
566                        if part.get_content_maintype() == 'multipart':
567                                continue
568
569                        if part.get_content_type() == 'text/plain':
570                                # Try to decode, if fails then do not decode
571                                #
572                                body_text = part.get_payload(decode=1)
573                                if not body_text:                       
574                                        body_text = part.get_payload(decode=0)
575               
576                                if self.STRIP_SIGNATURE:
577                                        body_text = self.strip_signature(body_text)
578
579
580                                if self.USE_TEXTWRAP:
581                                        import textwrap
582                                        body_text = textwrap.fill( body_text,
583                                                                                           width = self.USE_TEXTWRAP,
584                                                                                           replace_whitespace = False )
585
586                                # Get contents charset (iso-8859-15 if not defined in mail headers)
587                                #
588                                charset = part.get_content_charset()
589                                if not charset:
590                                        charset = 'iso-8859-15'
591
592                                try:
593                                        ubody_text = unicode(body_text, charset)
594
595                                except UnicodeError, detail:
596                                        ubody_text = unicode(body_text, 'iso-8859-15')
597
598                                except LookupError, detail:
599                                        ubody_text = 'ERROR: Could not find charset: %s, please install' %(charset)
600
601                        elif part.get_content_type() == 'text/html':
602                                ubody_text = '(see attachment for HTML mail message)'
603
604                        else:
605                                ubody_text = '(see attachment for message)'
606
607                        has_description = 1
608                        break           # we have the description, so break
609
610                if not has_description:
611                        ubody_text = '(see attachment for message)'
612
613                # A patch so that the web-interface will not update the description
614                # field of a ticket
615                #
616                ubody_text = ('\r\n'.join(ubody_text.splitlines()))
617
618                #  If we can unicode it try to encode it for trac
619                #  else we a lot of garbage
620                #
621                #if encoding:
622                #       ubody_text = ubody_text.encode('utf-8')
623
624                if self.VERBATIM_FORMAT:
625                        ubody_text = '{{{\r\n%s\r\n}}}' %ubody_text
626                else:
627                        ubody_text = '%s' %ubody_text
628
629                return ubody_text
630
631        def notify(self, tkt , new=True, modtime=0):
632                """
633                A wrapper for the TRAC notify function. So we can use templates
634                """
635                if tkt['component'] == 'Spam':
636                        return 
637
638                try:
639                        # create false {abs_}href properties, to trick Notify()
640                        #
641                        self.env.abs_href = Href(self.get_config('project', 'url'))
642                        self.env.href = Href(self.get_config('project', 'url'))
643
644                        tn = TicketNotifyEmail(self.env)
645                        if self.notify_template:
646                                tn.template_name = self.notify_template;
647
648                        tn.notify(tkt, new, modtime)
649
650                except Exception, e:
651                        print 'TD: Failure sending notification on creation of ticket #%s: %s' %(tkt['id'], e)
652
653        def mail_line(self, str):
654                return '%s %s' % (self.comment, str)
655
656
657        def html_mailto_link(self, subject, id, body):
658                if not self.author:
659                        author = self.email_addr
660                else:   
661                        author = self.author
662
663                # Must find a fix
664                #
665                #arr = string.split(body, '\n')
666                #arr = map(self.mail_line, arr)
667                #body = string.join(arr, '\n')
668                #body = '%s wrote:\n%s' %(author, body)
669
670                # Temporary fix
671                #
672                str = 'mailto:%s?Subject=%s&Cc=%s' %(
673                       urllib.quote(self.email_addr),
674                           urllib.quote('Re: #%s: %s' %(id, subject)),
675                           urllib.quote(self.MAILTO_CC)
676                           )
677
678                str = '\r\n{{{\r\n#!html\r\n<a href="%s">Reply to: %s</a>\r\n}}}\r\n' %(str, author)
679                return str
680
681        def attachments(self, message, ticket, update=False):
682                '''
683                save any attachments as files in the ticket's directory
684                '''
685                count = 0
686                first = 0
687                number = 0
688                for part in message.walk():
689                        if part.get_content_maintype() == 'multipart':          # multipart/* is just a container
690                                continue
691
692                        if not first:                                                                           # first content is the message
693                                first = 1
694                                if part.get_content_type() == 'text/plain':             # if first is text, is was already put in the description
695                                        continue
696
697                        filename = part.get_filename()
698                        count = count + 1
699                        if not filename:
700                                number = number + 1
701                                filename = 'part%04d' % number
702
703                                ext = mimetypes.guess_extension(part.get_content_type())
704                                if not ext:
705                                        ext = '.bin'
706
707                                filename = '%s%s' % (filename, ext)
708                        else:
709                                filename = self.email_to_unicode(filename)
710
711                        # From the trac code
712                        #
713                        filename = filename.replace('\\', '/').replace(':', '/')
714                        filename = os.path.basename(filename)
715
716                        # We try to normalize the filename to utf-8 NFC if we can.
717                        # Files uploaded from OS X might be in NFD.
718                        # Check python version and then try it
719                        #
720                        if sys.version_info[0] > 2 or (sys.version_info[0] == 2 and sys.version_info[1] >= 3):
721                                try:
722                                        filename = unicodedata.normalize('NFC', unicode(filename, 'utf-8')).encode('utf-8') 
723                                except TypeError:
724                                        pass
725
726                        url_filename = urllib.quote(filename)
727                        if self.VERSION == 0.8:
728                                dir = os.path.join(self.env.get_attachments_dir(), 'ticket',
729                                                        urllib.quote(str(ticket['id'])))
730                                if not os.path.exists(dir):
731                                        mkdir_p(dir, 0755)
732                        else:
733                                dir = '/tmp'
734
735                        path, fd =  util.create_unique_file(os.path.join(dir, url_filename))
736                        text = part.get_payload(decode=1)
737                        if not text:
738                                text = '(None)'
739                        fd.write(text)
740                        fd.close()
741
742                        # get the filesize
743                        #
744                        stats = os.lstat(path)
745                        filesize = stats[stat.ST_SIZE]
746
747                        # Insert the attachment it differs for the different TRAC versions
748                        #
749                        if self.VERSION == 0.8:
750                                cursor = self.db.cursor()
751                                try:
752                                        cursor.execute('INSERT INTO attachment VALUES("%s","%s","%s",%d,%d,"%s","%s","%s")'
753                                                %('ticket', urllib.quote(str(ticket['id'])), filename + '?format=raw', filesize,
754                                                int(time.time()),'', self.author, 'e-mail') )
755
756                                # Attachment is already known
757                                #
758                                except sqlite.IntegrityError:   
759                                        #self.db.close()
760                                        return count
761
762                                self.db.commit()
763
764                        else:
765                                fd = open(path)
766                                att = attachment.Attachment(self.env, 'ticket', ticket['id'])
767
768                                # This will break the ticket_update system, the body_text is vaporized
769                                # ;-(
770                                #
771                                if not update:
772                                        att.author = self.author
773                                        att.description = self.email_to_unicode('Added by email2trac')
774
775                                att.insert(url_filename, fd, filesize)
776                                fd.close()
777
778                        # Remove the created temporary filename
779                        #
780                        os.unlink(path)
781
782                # Return how many attachments
783                #
784                return count
785
786
787def mkdir_p(dir, mode):
788        '''do a mkdir -p'''
789
790        arr = string.split(dir, '/')
791        path = ''
792        for part in arr:
793                path = '%s/%s' % (path, part)
794                try:
795                        stats = os.stat(path)
796                except OSError:
797                        os.mkdir(path, mode)
798
799
800def ReadConfig(file, name):
801        """
802        Parse the config file
803        """
804
805        if not os.path.isfile(file):
806                print 'File %s does not exist' %file
807                sys.exit(1)
808
809        config = ConfigParser.ConfigParser()
810        try:
811                config.read(file)
812        except ConfigParser.MissingSectionHeaderError,detail:
813                print detail
814                sys.exit(1)
815
816
817        # Use given project name else use defaults
818        #
819        if name:
820                if not config.has_section(name):
821                        print "Not a valid project name: %s" %name
822                        print "Valid names: %s" %config.sections()
823                        sys.exit(1)
824
825                project =  dict()
826                for option in  config.options(name):
827                        project[option] = config.get(name, option)
828
829        else:
830                project = config.defaults()
831
832        return project
833
834
835if __name__ == '__main__':
836        # Default config file
837        #
838        configfile = '@email2trac_conf@'
839        project = ''
840        component = ''
841        ENABLE_SYSLOG = 0
842               
843        try:
844                opts, args = getopt.getopt(sys.argv[1:], 'chf:p:', ['component=','help', 'file=', 'project='])
845        except getopt.error,detail:
846                print __doc__
847                print detail
848                sys.exit(1)
849       
850        project_name = None
851        for opt,value in opts:
852                if opt in [ '-h', '--help']:
853                        print __doc__
854                        sys.exit(0)
855                elif opt in ['-c', '--component']:
856                        component = value
857                elif opt in ['-f', '--file']:
858                        configfile = value
859                elif opt in ['-p', '--project']:
860                        project_name = value
861       
862        settings = ReadConfig(configfile, project_name)
863        if not settings.has_key('project'):
864                print __doc__
865                print 'No Trac project is defined in the email2trac config file.'
866                sys.exit(1)
867       
868        if component:
869                settings['component'] = component
870       
871        if settings.has_key('trac_version'):
872                version = float(settings['trac_version'])
873        else:
874                version = trac_default_version
875
876        if settings.has_key('enable_syslog'):
877                ENABLE_SYSLOG =  float(settings['enable_syslog'])
878                       
879        #debug HvB
880        #print settings
881       
882        try:
883                if version == 0.8:
884                        from trac.Environment import Environment
885                        from trac.Ticket import Ticket
886                        from trac.Notify import TicketNotifyEmail
887                        from trac.Href import Href
888                        from trac import util
889                        import sqlite
890                elif version == 0.9:
891                        from trac import attachment
892                        from trac.env import Environment
893                        from trac.ticket import Ticket
894                        from trac.web.href import Href
895                        from trac import util
896                        from trac.Notify import TicketNotifyEmail
897                elif version == 0.10:
898                        from trac import attachment
899                        from trac.env import Environment
900                        from trac.ticket import Ticket
901                        from trac.web.href import Href
902                        from trac import util
903                        #
904                        # return  util.text.to_unicode(str)
905                        #
906                        # see http://projects.edgewall.com/trac/changeset/2799
907                        from trac.ticket.notification import TicketNotifyEmail
908       
909                env = Environment(settings['project'], create=0)
910                tktparser = TicketEmailParser(env, settings, version)
911                tktparser.parse(sys.stdin)
912
913        # Catch all errors ans log to SYSLOG if we have enabled this
914        # else stdout
915        #
916        except Exception, error:
917                if ENABLE_SYSLOG:
918                        syslog.openlog('email2trac', syslog.LOG_NOWAIT)
919                        etype, evalue, etb = sys.exc_info()
920                        for e in traceback.format_exception(etype, evalue, etb):
921                                syslog.syslog(e)
922                        syslog.closelog()
923                else:
924                        traceback.print_exc()
925
926                if m:
927                        tktparser.save_email_for_debug(m, True)
928
929# EOB
Note: See TracBrowser for help on using the repository browser.