[22] | 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 | # |
---|
[80] | 20 | # For vi/emacs or other use tabstop=4 (vi: set ts=4) |
---|
| 21 | # |
---|
[22] | 22 | """ |
---|
[54] | 23 | email2trac.py -- Email tickets to Trac. |
---|
[22] | 24 | |
---|
| 25 | A simple MTA filter to create Trac tickets from inbound emails. |
---|
| 26 | |
---|
| 27 | Copyright 2005, Daniel Lundin <daniel@edgewall.com> |
---|
| 28 | Copyright 2005, Edgewall Software |
---|
| 29 | |
---|
[282] | 30 | Authors: |
---|
| 31 | Bas van der Vlies <basv@sara.nl> |
---|
| 32 | Walter de Jong <walter@sara.nl> |
---|
[22] | 33 | |
---|
| 34 | The scripts reads emails from stdin and inserts directly into a Trac database. |
---|
| 35 | |
---|
| 36 | How to use |
---|
| 37 | ---------- |
---|
[282] | 38 | * See https://subtrac.sara.nl/oss/email2trac/ |
---|
| 39 | |
---|
[22] | 40 | * Create an config file: |
---|
[282] | 41 | [DEFAULT] # REQUIRED |
---|
| 42 | project : /data/trac/test # REQUIRED |
---|
| 43 | debug : 1 # OPTIONAL, if set print some DEBUG info |
---|
[297] | 44 | trac_version : 0.10 # OPTIONAL, default is 0.11 |
---|
[22] | 45 | |
---|
[282] | 46 | [jouvin] # OPTIONAL project declaration, if set both fields necessary |
---|
| 47 | project : /data/trac/jouvin # use -p|--project jouvin. |
---|
[22] | 48 | |
---|
| 49 | * default config file is : /etc/email2trac.conf |
---|
| 50 | |
---|
| 51 | * Commandline opions: |
---|
[205] | 52 | -h,--help |
---|
| 53 | -f,--file <configuration file> |
---|
| 54 | -n,--dry-run |
---|
| 55 | -p, --project <project name> |
---|
| 56 | -t, --ticket_prefix <name> |
---|
[22] | 57 | |
---|
| 58 | SVN Info: |
---|
| 59 | $Id: email2trac.py.in 356 2010-04-15 13:18:09Z bas $ |
---|
| 60 | """ |
---|
| 61 | import os |
---|
| 62 | import sys |
---|
| 63 | import string |
---|
| 64 | import getopt |
---|
| 65 | import stat |
---|
| 66 | import time |
---|
| 67 | import email |
---|
[136] | 68 | import email.Iterators |
---|
| 69 | import email.Header |
---|
[22] | 70 | import re |
---|
| 71 | import urllib |
---|
| 72 | import unicodedata |
---|
| 73 | from stat import * |
---|
| 74 | import mimetypes |
---|
[96] | 75 | import traceback |
---|
[22] | 76 | |
---|
[190] | 77 | |
---|
| 78 | # Will fail where unavailable, e.g. Windows |
---|
| 79 | # |
---|
| 80 | try: |
---|
| 81 | import syslog |
---|
| 82 | SYSLOG_AVAILABLE = True |
---|
| 83 | except ImportError: |
---|
| 84 | SYSLOG_AVAILABLE = False |
---|
| 85 | |
---|
[182] | 86 | from datetime import tzinfo, timedelta, datetime |
---|
[199] | 87 | from trac import config as trac_config |
---|
[91] | 88 | |
---|
[96] | 89 | # Some global variables |
---|
| 90 | # |
---|
[276] | 91 | trac_default_version = '0.11' |
---|
[96] | 92 | m = None |
---|
[22] | 93 | |
---|
[182] | 94 | # A UTC class needed for trac version 0.11, added by |
---|
| 95 | # tbaschak at ktc dot mb dot ca |
---|
| 96 | # |
---|
| 97 | class UTC(tzinfo): |
---|
| 98 | """UTC""" |
---|
| 99 | ZERO = timedelta(0) |
---|
| 100 | HOUR = timedelta(hours=1) |
---|
| 101 | |
---|
| 102 | def utcoffset(self, dt): |
---|
| 103 | return self.ZERO |
---|
| 104 | |
---|
| 105 | def tzname(self, dt): |
---|
| 106 | return "UTC" |
---|
| 107 | |
---|
| 108 | def dst(self, dt): |
---|
| 109 | return self.ZERO |
---|
| 110 | |
---|
| 111 | |
---|
[22] | 112 | class TicketEmailParser(object): |
---|
| 113 | env = None |
---|
| 114 | comment = '> ' |
---|
| 115 | |
---|
[206] | 116 | def __init__(self, env, parameters, version): |
---|
[22] | 117 | self.env = env |
---|
| 118 | |
---|
| 119 | # Database connection |
---|
| 120 | # |
---|
| 121 | self.db = None |
---|
| 122 | |
---|
[206] | 123 | # Save parameters |
---|
| 124 | # |
---|
| 125 | self.parameters = parameters |
---|
| 126 | |
---|
[72] | 127 | # Some useful mail constants |
---|
| 128 | # |
---|
[287] | 129 | self.email_name = None |
---|
[72] | 130 | self.email_addr = None |
---|
[183] | 131 | self.email_from = None |
---|
[288] | 132 | self.author = None |
---|
[287] | 133 | self.id = None |
---|
[294] | 134 | |
---|
| 135 | self.STRIP_CONTENT_TYPES = list() |
---|
[72] | 136 | |
---|
[22] | 137 | self.VERSION = version |
---|
[206] | 138 | self.DRY_RUN = parameters['dry_run'] |
---|
[317] | 139 | self.VERBOSE = parameters['verbose'] |
---|
[204] | 140 | |
---|
[172] | 141 | self.get_config = self.env.config.get |
---|
[22] | 142 | |
---|
| 143 | if parameters.has_key('umask'): |
---|
| 144 | os.umask(int(parameters['umask'], 8)) |
---|
| 145 | |
---|
| 146 | if parameters.has_key('debug'): |
---|
| 147 | self.DEBUG = int(parameters['debug']) |
---|
| 148 | else: |
---|
| 149 | self.DEBUG = 0 |
---|
| 150 | |
---|
| 151 | if parameters.has_key('mailto_link'): |
---|
| 152 | self.MAILTO = int(parameters['mailto_link']) |
---|
[74] | 153 | if parameters.has_key('mailto_cc'): |
---|
| 154 | self.MAILTO_CC = parameters['mailto_cc'] |
---|
| 155 | else: |
---|
| 156 | self.MAILTO_CC = '' |
---|
[22] | 157 | else: |
---|
| 158 | self.MAILTO = 0 |
---|
| 159 | |
---|
| 160 | if parameters.has_key('spam_level'): |
---|
| 161 | self.SPAM_LEVEL = int(parameters['spam_level']) |
---|
| 162 | else: |
---|
| 163 | self.SPAM_LEVEL = 0 |
---|
| 164 | |
---|
[207] | 165 | if parameters.has_key('spam_header'): |
---|
| 166 | self.SPAM_HEADER = parameters['spam_header'] |
---|
| 167 | else: |
---|
| 168 | self.SPAM_HEADER = 'X-Spam-Score' |
---|
| 169 | |
---|
[191] | 170 | if parameters.has_key('email_quote'): |
---|
| 171 | self.EMAIL_QUOTE = str(parameters['email_quote']) |
---|
| 172 | else: |
---|
| 173 | self.EMAIL_QUOTE = '> ' |
---|
[22] | 174 | |
---|
| 175 | if parameters.has_key('email_header'): |
---|
| 176 | self.EMAIL_HEADER = int(parameters['email_header']) |
---|
| 177 | else: |
---|
| 178 | self.EMAIL_HEADER = 0 |
---|
| 179 | |
---|
[42] | 180 | if parameters.has_key('alternate_notify_template'): |
---|
| 181 | self.notify_template = str(parameters['alternate_notify_template']) |
---|
| 182 | else: |
---|
| 183 | self.notify_template = None |
---|
[22] | 184 | |
---|
[222] | 185 | if parameters.has_key('alternate_notify_template_update'): |
---|
| 186 | self.notify_template_update = str(parameters['alternate_notify_template_update']) |
---|
| 187 | else: |
---|
| 188 | self.notify_template_update = None |
---|
| 189 | |
---|
[43] | 190 | if parameters.has_key('reply_all'): |
---|
| 191 | self.REPLY_ALL = int(parameters['reply_all']) |
---|
| 192 | else: |
---|
| 193 | self.REPLY_ALL = 0 |
---|
[42] | 194 | |
---|
[74] | 195 | if parameters.has_key('ticket_update'): |
---|
| 196 | self.TICKET_UPDATE = int(parameters['ticket_update']) |
---|
| 197 | else: |
---|
| 198 | self.TICKET_UPDATE = 0 |
---|
[43] | 199 | |
---|
[353] | 200 | if parameters.has_key('ticket_update_by_subject'): |
---|
| 201 | self.TICKET_UPDATE_BY_SUBJECT = int(parameters['ticket_update_by_subject']) |
---|
| 202 | else: |
---|
| 203 | self.TICKET_UPDATE_BY_SUBJECT = 0 |
---|
| 204 | |
---|
[118] | 205 | if parameters.has_key('drop_spam'): |
---|
| 206 | self.DROP_SPAM = int(parameters['drop_spam']) |
---|
| 207 | else: |
---|
| 208 | self.DROP_SPAM = 0 |
---|
[74] | 209 | |
---|
[134] | 210 | if parameters.has_key('verbatim_format'): |
---|
| 211 | self.VERBATIM_FORMAT = int(parameters['verbatim_format']) |
---|
| 212 | else: |
---|
| 213 | self.VERBATIM_FORMAT = 1 |
---|
[118] | 214 | |
---|
[231] | 215 | if parameters.has_key('reflow'): |
---|
[256] | 216 | self.REFLOW = int(parameters['reflow']) |
---|
[231] | 217 | else: |
---|
| 218 | self.REFLOW = 1 |
---|
| 219 | |
---|
[278] | 220 | if parameters.has_key('drop_alternative_html_version'): |
---|
| 221 | self.DROP_ALTERNATIVE_HTML_VERSION = int(parameters['drop_alternative_html_version']) |
---|
| 222 | else: |
---|
| 223 | self.DROP_ALTERNATIVE_HTML_VERSION = 0 |
---|
| 224 | |
---|
[136] | 225 | if parameters.has_key('strip_signature'): |
---|
| 226 | self.STRIP_SIGNATURE = int(parameters['strip_signature']) |
---|
| 227 | else: |
---|
| 228 | self.STRIP_SIGNATURE = 0 |
---|
[134] | 229 | |
---|
[191] | 230 | if parameters.has_key('strip_quotes'): |
---|
| 231 | self.STRIP_QUOTES = int(parameters['strip_quotes']) |
---|
| 232 | else: |
---|
| 233 | self.STRIP_QUOTES = 0 |
---|
| 234 | |
---|
[309] | 235 | self.properties = dict() |
---|
| 236 | if parameters.has_key('inline_properties'): |
---|
| 237 | self.INLINE_PROPERTIES = int(parameters['inline_properties']) |
---|
| 238 | else: |
---|
| 239 | self.INLINE_PROPERTIES = 0 |
---|
| 240 | |
---|
[148] | 241 | if parameters.has_key('use_textwrap'): |
---|
| 242 | self.USE_TEXTWRAP = int(parameters['use_textwrap']) |
---|
| 243 | else: |
---|
| 244 | self.USE_TEXTWRAP = 0 |
---|
| 245 | |
---|
[238] | 246 | if parameters.has_key('binhex'): |
---|
[294] | 247 | self.STRIP_CONTENT_TYPES.append('application/mac-binhex40') |
---|
[238] | 248 | |
---|
| 249 | if parameters.has_key('applesingle'): |
---|
[294] | 250 | self.STRIP_CONTENT_TYPES.append('application/applefile') |
---|
[238] | 251 | |
---|
| 252 | if parameters.has_key('appledouble'): |
---|
[294] | 253 | self.STRIP_CONTENT_TYPES.append('application/applefile') |
---|
[238] | 254 | |
---|
[294] | 255 | if parameters.has_key('strip_content_types'): |
---|
| 256 | items = parameters['strip_content_types'].split(',') |
---|
| 257 | for item in items: |
---|
| 258 | self.STRIP_CONTENT_TYPES.append(item.strip()) |
---|
| 259 | |
---|
[257] | 260 | self.WORKFLOW = None |
---|
| 261 | if parameters.has_key('workflow'): |
---|
| 262 | self.WORKFLOW = parameters['workflow'] |
---|
| 263 | |
---|
[173] | 264 | # Use OS independend functions |
---|
| 265 | # |
---|
| 266 | self.TMPDIR = os.path.normcase('/tmp') |
---|
| 267 | if parameters.has_key('tmpdir'): |
---|
| 268 | self.TMPDIR = os.path.normcase(str(parameters['tmpdir'])) |
---|
| 269 | |
---|
[194] | 270 | if parameters.has_key('ignore_trac_user_settings'): |
---|
| 271 | self.IGNORE_TRAC_USER_SETTINGS = int(parameters['ignore_trac_user_settings']) |
---|
| 272 | else: |
---|
| 273 | self.IGNORE_TRAC_USER_SETTINGS = 0 |
---|
[191] | 274 | |
---|
[320] | 275 | if parameters.has_key('email_triggers_workflow'): |
---|
| 276 | self.EMAIL_TRIGGERS_WORKFLOW = int(parameters['email_triggers_workflow']) |
---|
| 277 | else: |
---|
| 278 | self.EMAIL_TRIGGERS_WORKFLOW = 1 |
---|
| 279 | |
---|
[297] | 280 | if parameters.has_key('subject_field_separator'): |
---|
| 281 | self.SUBJECT_FIELD_SEPARATOR = parameters['subject_field_separator'].strip() |
---|
| 282 | else: |
---|
| 283 | self.SUBJECT_FIELD_SEPARATOR = '&' |
---|
| 284 | |
---|
[305] | 285 | self.trac_smtp_from = self.get_config('notification', 'smtp_from') |
---|
| 286 | |
---|
[341] | 287 | ########## Email Header Functions ########################################################### |
---|
[339] | 288 | |
---|
[22] | 289 | def spam(self, message): |
---|
[191] | 290 | """ |
---|
| 291 | # X-Spam-Score: *** (3.255) BAYES_50,DNS_FROM_AHBL_RHSBL,HTML_ |
---|
| 292 | # Note if Spam_level then '*' are included |
---|
| 293 | """ |
---|
[194] | 294 | spam = False |
---|
[207] | 295 | if message.has_key(self.SPAM_HEADER): |
---|
| 296 | spam_l = string.split(message[self.SPAM_HEADER]) |
---|
[22] | 297 | |
---|
[207] | 298 | try: |
---|
| 299 | number = spam_l[0].count('*') |
---|
| 300 | except IndexError, detail: |
---|
| 301 | number = 0 |
---|
| 302 | |
---|
[22] | 303 | if number >= self.SPAM_LEVEL: |
---|
[194] | 304 | spam = True |
---|
| 305 | |
---|
[191] | 306 | # treat virus mails as spam |
---|
| 307 | # |
---|
| 308 | elif message.has_key('X-Virus-found'): |
---|
[194] | 309 | spam = True |
---|
| 310 | |
---|
| 311 | # How to handle SPAM messages |
---|
| 312 | # |
---|
| 313 | if self.DROP_SPAM and spam: |
---|
| 314 | if self.DEBUG > 2 : |
---|
| 315 | print 'This message is a SPAM. Automatic ticket insertion refused (SPAM level > %d' % self.SPAM_LEVEL |
---|
| 316 | |
---|
[204] | 317 | return 'drop' |
---|
[194] | 318 | |
---|
| 319 | elif spam: |
---|
| 320 | |
---|
[204] | 321 | return 'Spam' |
---|
[67] | 322 | |
---|
[194] | 323 | else: |
---|
[22] | 324 | |
---|
[204] | 325 | return False |
---|
[191] | 326 | |
---|
[221] | 327 | def email_header_acl(self, keyword, header_field, default): |
---|
[206] | 328 | """ |
---|
[221] | 329 | This function wil check if the email address is allowed or denied |
---|
| 330 | to send mail to the ticket list |
---|
| 331 | """ |
---|
[206] | 332 | try: |
---|
[221] | 333 | mail_addresses = self.parameters[keyword] |
---|
| 334 | |
---|
| 335 | # Check if we have an empty string |
---|
| 336 | # |
---|
| 337 | if not mail_addresses: |
---|
| 338 | return default |
---|
| 339 | |
---|
[206] | 340 | except KeyError, detail: |
---|
[221] | 341 | if self.DEBUG > 2 : |
---|
[250] | 342 | print 'TD: %s not defined, all messages are allowed.' %(keyword) |
---|
[206] | 343 | |
---|
[221] | 344 | return default |
---|
[206] | 345 | |
---|
[221] | 346 | mail_addresses = string.split(mail_addresses, ',') |
---|
| 347 | |
---|
| 348 | for entry in mail_addresses: |
---|
[209] | 349 | entry = entry.strip() |
---|
[221] | 350 | TO_RE = re.compile(entry, re.VERBOSE|re.IGNORECASE) |
---|
| 351 | result = TO_RE.search(header_field) |
---|
[208] | 352 | if result: |
---|
| 353 | return True |
---|
[149] | 354 | |
---|
[208] | 355 | return False |
---|
| 356 | |
---|
[22] | 357 | def email_header_txt(self, m): |
---|
[72] | 358 | """ |
---|
| 359 | Display To and CC addresses in description field |
---|
| 360 | """ |
---|
[288] | 361 | s = '' |
---|
[334] | 362 | |
---|
[213] | 363 | if m['To'] and len(m['To']) > 0: |
---|
[288] | 364 | s = "'''To:''' %s\r\n" %(m['To']) |
---|
[22] | 365 | if m['Cc'] and len(m['Cc']) > 0: |
---|
[288] | 366 | s = "%s'''Cc:''' %s\r\n" % (s, m['Cc']) |
---|
[22] | 367 | |
---|
[288] | 368 | return self.email_to_unicode(s) |
---|
[22] | 369 | |
---|
[138] | 370 | |
---|
[194] | 371 | def get_sender_info(self, message): |
---|
[45] | 372 | """ |
---|
[72] | 373 | Get the default author name and email address from the message |
---|
[226] | 374 | """ |
---|
[43] | 375 | |
---|
[226] | 376 | self.email_to = self.email_to_unicode(message['to']) |
---|
| 377 | self.to_name, self.to_email_addr = email.Utils.parseaddr (self.email_to) |
---|
| 378 | |
---|
[194] | 379 | self.email_from = self.email_to_unicode(message['from']) |
---|
[287] | 380 | self.email_name, self.email_addr = email.Utils.parseaddr(self.email_from) |
---|
[142] | 381 | |
---|
[304] | 382 | ## Trac can not handle author's name that contains spaces |
---|
| 383 | # and forbid the ticket email address as author field |
---|
[194] | 384 | |
---|
[305] | 385 | if self.email_addr == self.trac_smtp_from: |
---|
[304] | 386 | self.author = "email2trac" |
---|
| 387 | else: |
---|
| 388 | self.author = self.email_addr |
---|
| 389 | |
---|
[194] | 390 | if self.IGNORE_TRAC_USER_SETTINGS: |
---|
| 391 | return |
---|
| 392 | |
---|
| 393 | # Is this a registered user, use email address as search key: |
---|
| 394 | # result: |
---|
| 395 | # u : login name |
---|
| 396 | # n : Name that the user has set in the settings tab |
---|
| 397 | # e : email address that the user has set in the settings tab |
---|
[45] | 398 | # |
---|
[194] | 399 | users = [ (u,n,e) for (u, n, e) in self.env.get_known_users(self.db) |
---|
[250] | 400 | if e and (e.lower() == self.email_addr.lower()) ] |
---|
[43] | 401 | |
---|
[45] | 402 | if len(users) == 1: |
---|
[194] | 403 | self.email_from = users[0][0] |
---|
[250] | 404 | self.author = users[0][0] |
---|
[45] | 405 | |
---|
[72] | 406 | def set_reply_fields(self, ticket, message): |
---|
| 407 | """ |
---|
| 408 | Set all the right fields for a new ticket |
---|
| 409 | """ |
---|
[299] | 410 | if self.DEBUG: |
---|
| 411 | print 'TD: set_reply_fields' |
---|
[72] | 412 | |
---|
[270] | 413 | ## Only use name or email adress |
---|
| 414 | #ticket['reporter'] = self.email_from |
---|
| 415 | ticket['reporter'] = self.author |
---|
| 416 | |
---|
| 417 | |
---|
[45] | 418 | # Put all CC-addresses in ticket CC field |
---|
[43] | 419 | # |
---|
| 420 | if self.REPLY_ALL: |
---|
| 421 | |
---|
[299] | 422 | email_cc = '' |
---|
| 423 | |
---|
| 424 | cc_addrs = email.Utils.getaddresses( message.get_all('cc', []) ) |
---|
| 425 | |
---|
| 426 | if not cc_addrs: |
---|
[105] | 427 | return |
---|
[43] | 428 | |
---|
[299] | 429 | ## Build a list of forbidden CC addresses |
---|
| 430 | # |
---|
[300] | 431 | #to_addrs = email.Utils.getaddresses( message.get_all('to', []) ) |
---|
| 432 | #to_list = list() |
---|
| 433 | #for n,e in to_addrs: |
---|
| 434 | # to_list.append(e) |
---|
[299] | 435 | |
---|
[43] | 436 | # Remove reporter email address if notification is |
---|
| 437 | # on |
---|
| 438 | # |
---|
| 439 | if self.notification: |
---|
| 440 | try: |
---|
[299] | 441 | cc_addrs.remove((self.author, self.email_addr)) |
---|
[43] | 442 | except ValueError, detail: |
---|
| 443 | pass |
---|
| 444 | |
---|
[299] | 445 | for name,addr in cc_addrs: |
---|
| 446 | |
---|
| 447 | ## Prevent mail loop |
---|
| 448 | # |
---|
[300] | 449 | #if addr in to_list: |
---|
[304] | 450 | |
---|
| 451 | if addr == self.trac_smtp_from: |
---|
[299] | 452 | if self.DEBUG: |
---|
| 453 | print "Skipping %s mail address for CC-field" %(addr) |
---|
| 454 | continue |
---|
[43] | 455 | |
---|
[299] | 456 | if email_cc: |
---|
| 457 | email_cc = '%s, %s' %(email_cc, addr) |
---|
| 458 | else: |
---|
| 459 | email_cc = addr |
---|
[96] | 460 | |
---|
[299] | 461 | if email_cc: |
---|
| 462 | if self.DEBUG: |
---|
| 463 | print 'TD: set_reply_fields: %s' %email_cc |
---|
| 464 | |
---|
| 465 | ticket['cc'] = self.email_to_unicode(email_cc) |
---|
| 466 | |
---|
[339] | 467 | |
---|
| 468 | ########## DEBUG functions ########################################################### |
---|
| 469 | |
---|
[310] | 470 | def debug_body(self, message_body, tempfile=False): |
---|
| 471 | if tempfile: |
---|
| 472 | import tempfile |
---|
| 473 | body_file = tempfile.mktemp('.email2trac') |
---|
| 474 | else: |
---|
| 475 | body_file = os.path.join(self.TMPDIR, 'body.txt') |
---|
| 476 | |
---|
[331] | 477 | if self.DRY_RUN: |
---|
| 478 | print 'DRY-RUN: not saving body to %s' %(body_file) |
---|
| 479 | return |
---|
| 480 | |
---|
| 481 | print 'TD: writing body to %s' %(body_file) |
---|
| 482 | fx = open(body_file, 'wb') |
---|
[310] | 483 | if not message_body: |
---|
[331] | 484 | message_body = '(None)' |
---|
[310] | 485 | |
---|
| 486 | message_body = message_body.encode('utf-8') |
---|
| 487 | #message_body = unicode(message_body, 'iso-8859-15') |
---|
| 488 | |
---|
| 489 | fx.write(message_body) |
---|
| 490 | fx.close() |
---|
| 491 | try: |
---|
| 492 | os.chmod(body_file,S_IRWXU|S_IRWXG|S_IRWXO) |
---|
| 493 | except OSError: |
---|
| 494 | pass |
---|
| 495 | |
---|
| 496 | def debug_attachments(self, message_parts): |
---|
[317] | 497 | """ |
---|
| 498 | """ |
---|
| 499 | if self.VERBOSE: |
---|
| 500 | print "VB: debug_attachments" |
---|
| 501 | |
---|
[310] | 502 | n = 0 |
---|
[331] | 503 | for item in message_parts: |
---|
[310] | 504 | # Skip inline text parts |
---|
[331] | 505 | if not isinstance(item, tuple): |
---|
[310] | 506 | continue |
---|
| 507 | |
---|
[331] | 508 | (original, filename, part) = item |
---|
[310] | 509 | |
---|
| 510 | n = n + 1 |
---|
| 511 | print 'TD: part%d: Content-Type: %s' % (n, part.get_content_type()) |
---|
[348] | 512 | print 'TD: part%d: filename: %s' % (n, filename) |
---|
[310] | 513 | |
---|
[348] | 514 | ## Forbidden chars |
---|
| 515 | # |
---|
| 516 | filename = filename.replace('\\', '_') |
---|
| 517 | filename = filename.replace('/', '_') |
---|
| 518 | |
---|
| 519 | |
---|
| 520 | part_file = os.path.join(self.TMPDIR, filename) |
---|
[310] | 521 | print 'TD: writing part%d (%s)' % (n,part_file) |
---|
[331] | 522 | |
---|
| 523 | if self.DRY_RUN: |
---|
| 524 | print 'DRY_RUN: NOT saving attachments' |
---|
| 525 | continue |
---|
| 526 | |
---|
[310] | 527 | fx = open(part_file, 'wb') |
---|
| 528 | text = part.get_payload(decode=1) |
---|
[331] | 529 | |
---|
[310] | 530 | if not text: |
---|
| 531 | text = '(None)' |
---|
[331] | 532 | |
---|
[310] | 533 | fx.write(text) |
---|
| 534 | fx.close() |
---|
[331] | 535 | |
---|
[310] | 536 | try: |
---|
| 537 | os.chmod(part_file,S_IRWXU|S_IRWXG|S_IRWXO) |
---|
| 538 | except OSError: |
---|
| 539 | pass |
---|
| 540 | |
---|
[96] | 541 | def save_email_for_debug(self, message, tempfile=False): |
---|
[309] | 542 | |
---|
[96] | 543 | if tempfile: |
---|
| 544 | import tempfile |
---|
| 545 | msg_file = tempfile.mktemp('.email2trac') |
---|
| 546 | else: |
---|
[173] | 547 | #msg_file = '/var/tmp/msg.txt' |
---|
| 548 | msg_file = os.path.join(self.TMPDIR, 'msg.txt') |
---|
| 549 | |
---|
[331] | 550 | if self.DRY_RUN: |
---|
| 551 | print 'DRY_RUN: NOT saving email message to %s' %(msg_file) |
---|
| 552 | else: |
---|
| 553 | print 'TD: saving email to %s' %(msg_file) |
---|
[44] | 554 | |
---|
[331] | 555 | fx = open(msg_file, 'wb') |
---|
| 556 | fx.write('%s' % message) |
---|
| 557 | fx.close() |
---|
| 558 | |
---|
| 559 | try: |
---|
| 560 | os.chmod(msg_file,S_IRWXU|S_IRWXG|S_IRWXO) |
---|
| 561 | except OSError: |
---|
| 562 | pass |
---|
| 563 | |
---|
[309] | 564 | message_parts = self.get_message_parts(message) |
---|
| 565 | message_parts = self.unique_attachment_names(message_parts) |
---|
| 566 | body_text = self.body_text(message_parts) |
---|
| 567 | self.debug_body(body_text, True) |
---|
| 568 | self.debug_attachments(message_parts) |
---|
| 569 | |
---|
[339] | 570 | ########## Conversion functions ########################################################### |
---|
| 571 | |
---|
[341] | 572 | def email_to_unicode(self, message_str): |
---|
| 573 | """ |
---|
| 574 | Email has 7 bit ASCII code, convert it to unicode with the charset |
---|
| 575 | that is encoded in 7-bit ASCII code and encode it as utf-8 so Trac |
---|
| 576 | understands it. |
---|
| 577 | """ |
---|
| 578 | if self.VERBOSE: |
---|
| 579 | print "VB: email_to_unicode" |
---|
| 580 | |
---|
| 581 | results = email.Header.decode_header(message_str) |
---|
| 582 | |
---|
| 583 | s = None |
---|
| 584 | for text,format in results: |
---|
| 585 | if format: |
---|
| 586 | try: |
---|
| 587 | temp = unicode(text, format) |
---|
| 588 | except UnicodeError, detail: |
---|
| 589 | # This always works |
---|
| 590 | # |
---|
| 591 | temp = unicode(text, 'iso-8859-15') |
---|
| 592 | except LookupError, detail: |
---|
| 593 | #text = 'ERROR: Could not find charset: %s, please install' %format |
---|
| 594 | #temp = unicode(text, 'iso-8859-15') |
---|
| 595 | temp = message_str |
---|
| 596 | |
---|
| 597 | else: |
---|
| 598 | temp = string.strip(text) |
---|
| 599 | temp = unicode(text, 'iso-8859-15') |
---|
| 600 | |
---|
| 601 | if s: |
---|
| 602 | s = '%s %s' %(s, temp) |
---|
| 603 | else: |
---|
| 604 | s = '%s' %temp |
---|
| 605 | |
---|
| 606 | #s = s.encode('utf-8') |
---|
| 607 | return s |
---|
| 608 | |
---|
[288] | 609 | def str_to_dict(self, s): |
---|
[164] | 610 | """ |
---|
[288] | 611 | Transfrom a string of the form [<key>=<value>]+ to dict[<key>] = <value> |
---|
[164] | 612 | """ |
---|
| 613 | |
---|
[297] | 614 | fields = string.split(s, self.SUBJECT_FIELD_SEPARATOR) |
---|
[262] | 615 | |
---|
[164] | 616 | result = dict() |
---|
| 617 | for field in fields: |
---|
| 618 | try: |
---|
[262] | 619 | index, value = string.split(field, '=') |
---|
[169] | 620 | |
---|
| 621 | # We can not change the description of a ticket via the subject |
---|
| 622 | # line. The description is the body of the email |
---|
| 623 | # |
---|
| 624 | if index.lower() in ['description']: |
---|
| 625 | continue |
---|
| 626 | |
---|
[164] | 627 | if value: |
---|
[165] | 628 | result[index.lower()] = value |
---|
[169] | 629 | |
---|
[164] | 630 | except ValueError: |
---|
| 631 | pass |
---|
[165] | 632 | return result |
---|
[167] | 633 | |
---|
[339] | 634 | ########## TRAC ticket functions ########################################################### |
---|
| 635 | |
---|
[202] | 636 | def update_ticket_fields(self, ticket, user_dict, use_default=None): |
---|
| 637 | """ |
---|
| 638 | This will update the ticket fields. It will check if the |
---|
| 639 | given fields are known and if the right values are specified |
---|
| 640 | It will only update the ticket field value: |
---|
[169] | 641 | - If the field is known |
---|
[202] | 642 | - If the value supplied is valid for the ticket field. |
---|
| 643 | If not then there are two options: |
---|
| 644 | 1) Skip the value (use_default=None) |
---|
| 645 | 2) Set default value for field (use_default=1) |
---|
[169] | 646 | """ |
---|
[334] | 647 | if self.VERBOSE: |
---|
| 648 | print "VB: update_ticket_fields" |
---|
[169] | 649 | |
---|
| 650 | # Build a system dictionary from the ticket fields |
---|
| 651 | # with field as index and option as value |
---|
| 652 | # |
---|
| 653 | sys_dict = dict() |
---|
| 654 | for field in ticket.fields: |
---|
[167] | 655 | try: |
---|
[169] | 656 | sys_dict[field['name']] = field['options'] |
---|
| 657 | |
---|
[167] | 658 | except KeyError: |
---|
[169] | 659 | sys_dict[field['name']] = None |
---|
[167] | 660 | pass |
---|
[169] | 661 | |
---|
[301] | 662 | ## Check user supplied fields an compare them with the |
---|
[169] | 663 | # system one's |
---|
| 664 | # |
---|
| 665 | for field,value in user_dict.items(): |
---|
[202] | 666 | if self.DEBUG >= 10: |
---|
| 667 | print 'user_field\t %s = %s' %(field,value) |
---|
[169] | 668 | |
---|
[301] | 669 | ## To prevent mail loop |
---|
| 670 | # |
---|
| 671 | if field == 'cc': |
---|
| 672 | |
---|
| 673 | cc_list = user_dict['cc'].split(',') |
---|
| 674 | |
---|
[304] | 675 | if self.trac_smtp_from in cc_list: |
---|
[301] | 676 | if self.DEBUG > 10: |
---|
[304] | 677 | print 'TD: MAIL LOOP: %s is not allowed as CC address' %(self.trac_smtp_from) |
---|
| 678 | cc_list.remove(self.trac_smtp_from) |
---|
[301] | 679 | |
---|
| 680 | value = ','.join(cc_list) |
---|
| 681 | |
---|
| 682 | |
---|
[169] | 683 | if sys_dict.has_key(field): |
---|
| 684 | |
---|
| 685 | # Check if value is an allowed system option, if TypeError then |
---|
| 686 | # every value is allowed |
---|
| 687 | # |
---|
| 688 | try: |
---|
| 689 | if value in sys_dict[field]: |
---|
| 690 | ticket[field] = value |
---|
[202] | 691 | else: |
---|
| 692 | # Must we set a default if value is not allowed |
---|
| 693 | # |
---|
| 694 | if use_default: |
---|
| 695 | value = self.get_config('ticket', 'default_%s' %(field) ) |
---|
[169] | 696 | |
---|
| 697 | except TypeError: |
---|
[345] | 698 | pass |
---|
| 699 | |
---|
| 700 | ## Only set if we have a value |
---|
| 701 | # |
---|
| 702 | if value: |
---|
[169] | 703 | ticket[field] = value |
---|
[202] | 704 | |
---|
| 705 | if self.DEBUG >= 10: |
---|
| 706 | print 'ticket_field\t %s = %s' %(field, ticket[field]) |
---|
[345] | 707 | |
---|
[260] | 708 | def ticket_update(self, m, id, spam): |
---|
[78] | 709 | """ |
---|
[79] | 710 | If the current email is a reply to an existing ticket, this function |
---|
| 711 | will append the contents of this email to that ticket, instead of |
---|
| 712 | creating a new one. |
---|
[78] | 713 | """ |
---|
[334] | 714 | if self.VERBOSE: |
---|
| 715 | print "VB: ticket_update: %s" %id |
---|
[202] | 716 | |
---|
[164] | 717 | # Must we update ticket fields |
---|
| 718 | # |
---|
[220] | 719 | update_fields = dict() |
---|
[165] | 720 | try: |
---|
[260] | 721 | id, keywords = string.split(id, '?') |
---|
[262] | 722 | |
---|
| 723 | # Skip the last ':' character |
---|
| 724 | # |
---|
| 725 | keywords = keywords[:-1] |
---|
[220] | 726 | update_fields = self.str_to_dict(keywords) |
---|
[165] | 727 | |
---|
| 728 | # Strip '#' |
---|
| 729 | # |
---|
[260] | 730 | self.id = int(id[1:]) |
---|
[165] | 731 | |
---|
[260] | 732 | except ValueError: |
---|
[165] | 733 | # Strip '#' and ':' |
---|
| 734 | # |
---|
[260] | 735 | self.id = int(id[1:-1]) |
---|
[164] | 736 | |
---|
[71] | 737 | |
---|
[194] | 738 | # When is the change committed |
---|
| 739 | # |
---|
| 740 | if self.VERSION == 0.11: |
---|
| 741 | utc = UTC() |
---|
| 742 | when = datetime.now(utc) |
---|
| 743 | else: |
---|
| 744 | when = int(time.time()) |
---|
[77] | 745 | |
---|
[172] | 746 | try: |
---|
[253] | 747 | tkt = Ticket(self.env, self.id, self.db) |
---|
[172] | 748 | except util.TracError, detail: |
---|
[253] | 749 | # Not a valid ticket |
---|
| 750 | self.id = None |
---|
[172] | 751 | return False |
---|
[126] | 752 | |
---|
[288] | 753 | # How many changes has this ticket |
---|
| 754 | cnum = len(tkt.get_changelog()) |
---|
| 755 | |
---|
| 756 | |
---|
[220] | 757 | # reopen the ticket if it is was closed |
---|
| 758 | # We must use the ticket workflow framework |
---|
| 759 | # |
---|
[320] | 760 | if tkt['status'] in ['closed'] and self.EMAIL_TRIGGERS_WORKFLOW: |
---|
[220] | 761 | |
---|
[257] | 762 | #print controller.actions['reopen'] |
---|
| 763 | # |
---|
| 764 | # As reference |
---|
| 765 | # req = Mock(href=Href('/'), abs_href=Href('http://www.example.com/'), authname='anonymous', perm=MockPerm(), args={}) |
---|
| 766 | # |
---|
| 767 | #a = controller.render_ticket_action_control(req, tkt, 'reopen') |
---|
| 768 | #print 'controller : ', a |
---|
| 769 | # |
---|
| 770 | #b = controller.get_all_status() |
---|
| 771 | #print 'get all status: ', b |
---|
| 772 | # |
---|
| 773 | #b = controller.get_ticket_changes(req, tkt, 'reopen') |
---|
| 774 | #print 'get_ticket_changes :', b |
---|
| 775 | |
---|
[288] | 776 | if self.WORKFLOW and (self.VERSION in [0.11]) : |
---|
[257] | 777 | from trac.ticket.default_workflow import ConfigurableTicketWorkflow |
---|
| 778 | from trac.test import Mock, MockPerm |
---|
| 779 | |
---|
| 780 | req = Mock(authname='anonymous', perm=MockPerm(), args={}) |
---|
| 781 | |
---|
| 782 | controller = ConfigurableTicketWorkflow(self.env) |
---|
| 783 | fields = controller.get_ticket_changes(req, tkt, self.WORKFLOW) |
---|
| 784 | |
---|
| 785 | if self.DEBUG: |
---|
| 786 | print 'TD: Workflow ticket update fields: ', fields |
---|
| 787 | |
---|
| 788 | for key in fields.keys(): |
---|
| 789 | tkt[key] = fields[key] |
---|
| 790 | |
---|
| 791 | else: |
---|
| 792 | tkt['status'] = 'reopened' |
---|
| 793 | tkt['resolution'] = '' |
---|
| 794 | |
---|
[309] | 795 | # Must we update some ticket fields properties via subjectline |
---|
[172] | 796 | # |
---|
[220] | 797 | if update_fields: |
---|
| 798 | self.update_ticket_fields(tkt, update_fields) |
---|
[166] | 799 | |
---|
[236] | 800 | message_parts = self.get_message_parts(m) |
---|
[253] | 801 | message_parts = self.unique_attachment_names(message_parts) |
---|
[210] | 802 | |
---|
[309] | 803 | # Must we update some ticket fields properties via body_text |
---|
| 804 | # |
---|
| 805 | if self.properties: |
---|
| 806 | self.update_ticket_fields(tkt, self.properties) |
---|
| 807 | |
---|
[177] | 808 | if self.EMAIL_HEADER: |
---|
[236] | 809 | message_parts.insert(0, self.email_header_txt(m)) |
---|
[76] | 810 | |
---|
[236] | 811 | body_text = self.body_text(message_parts) |
---|
| 812 | |
---|
[348] | 813 | if self.VERSION == 0.9: |
---|
| 814 | error_with_attachments = self.attach_attachments(message_parts, True) |
---|
| 815 | else: |
---|
| 816 | error_with_attachments = self.attach_attachments(message_parts) |
---|
| 817 | |
---|
[309] | 818 | if body_text.strip() or update_fields or self.properties: |
---|
[250] | 819 | if self.DRY_RUN: |
---|
[288] | 820 | print 'DRY_RUN: tkt.save_changes(self.author, body_text, ticket_change_number) ', self.author, cnum |
---|
[250] | 821 | else: |
---|
[348] | 822 | if error_with_attachments: |
---|
| 823 | body_text = '%s\\%s' %(error_with_attachments, body_text) |
---|
| 824 | |
---|
[288] | 825 | tkt.save_changes(self.author, body_text, when, None, str(cnum)) |
---|
| 826 | |
---|
[219] | 827 | |
---|
[348] | 828 | #if self.VERSION == 0.9: |
---|
| 829 | # error_with_attachments = self.attach_attachments(message_parts, True) |
---|
| 830 | #else: |
---|
| 831 | # error_with_attachments = self.attach_attachments(message_parts) |
---|
[76] | 832 | |
---|
[204] | 833 | if self.notification and not spam: |
---|
[253] | 834 | self.notify(tkt, False, when) |
---|
[72] | 835 | |
---|
[71] | 836 | return True |
---|
| 837 | |
---|
[202] | 838 | def set_ticket_fields(self, ticket): |
---|
[77] | 839 | """ |
---|
[202] | 840 | set the ticket fields to value specified |
---|
| 841 | - /etc/email2trac.conf with <prefix>_<field> |
---|
| 842 | - trac default values, trac.ini |
---|
| 843 | """ |
---|
| 844 | user_dict = dict() |
---|
| 845 | |
---|
| 846 | for field in ticket.fields: |
---|
| 847 | |
---|
| 848 | name = field['name'] |
---|
| 849 | |
---|
[335] | 850 | ## default trac value |
---|
[202] | 851 | # |
---|
[233] | 852 | if not field.get('custom'): |
---|
| 853 | value = self.get_config('ticket', 'default_%s' %(name) ) |
---|
| 854 | else: |
---|
[345] | 855 | ## Else we get the default value for reporter |
---|
| 856 | # |
---|
[233] | 857 | value = field.get('value') |
---|
| 858 | options = field.get('options') |
---|
[345] | 859 | |
---|
[335] | 860 | if value and options and (value not in options): |
---|
[345] | 861 | value = options[int(value)] |
---|
| 862 | |
---|
[202] | 863 | if self.DEBUG > 10: |
---|
| 864 | print 'trac.ini name %s = %s' %(name, value) |
---|
| 865 | |
---|
[335] | 866 | ## email2trac.conf settings |
---|
| 867 | # |
---|
[206] | 868 | prefix = self.parameters['ticket_prefix'] |
---|
[202] | 869 | try: |
---|
[206] | 870 | value = self.parameters['%s_%s' %(prefix, name)] |
---|
[202] | 871 | if self.DEBUG > 10: |
---|
| 872 | print 'email2trac.conf %s = %s ' %(name, value) |
---|
| 873 | |
---|
| 874 | except KeyError, detail: |
---|
| 875 | pass |
---|
| 876 | |
---|
| 877 | if self.DEBUG: |
---|
| 878 | print 'user_dict[%s] = %s' %(name, value) |
---|
| 879 | |
---|
[345] | 880 | if value: |
---|
| 881 | user_dict[name] = value |
---|
[202] | 882 | |
---|
| 883 | self.update_ticket_fields(ticket, user_dict, use_default=1) |
---|
| 884 | |
---|
[352] | 885 | if 'status' not in user_dict.keys(): |
---|
| 886 | ticket['status'] = 'new' |
---|
[202] | 887 | |
---|
| 888 | |
---|
[356] | 889 | def ticket_update_by_subject(self, subject): |
---|
| 890 | """ |
---|
| 891 | This list of Re: prefixes is probably incomplete. Taken from |
---|
| 892 | wikipedia. Here is how the subject is matched |
---|
| 893 | - Re: <subject> |
---|
| 894 | - Re: (<Mail list label>:)+ <subject> |
---|
[202] | 895 | |
---|
[356] | 896 | So we must have the last column |
---|
| 897 | """ |
---|
| 898 | if self.VERBOSE: |
---|
| 899 | print "VB: ticket_update_by_subject()" |
---|
| 900 | |
---|
| 901 | matched_id = None |
---|
| 902 | if self.TICKET_UPDATE and self.TICKET_UPDATE_BY_SUBJECT: |
---|
| 903 | |
---|
| 904 | SUBJECT_RE = re.compile(r'^(RE|AW|VS|SV):(.*:)*\s*(.*)', re.IGNORECASE) |
---|
| 905 | result = SUBJECT_RE.search(subject) |
---|
| 906 | |
---|
| 907 | if result: |
---|
| 908 | # This is a reply |
---|
| 909 | orig_subject = result.group(3) |
---|
| 910 | |
---|
| 911 | if self.DEBUG: |
---|
| 912 | print 'TD: subject search string: %s' %(orig_subject) |
---|
| 913 | |
---|
| 914 | cursor = self.db.cursor() |
---|
| 915 | summaries = [orig_subject, '%%: %s' % orig_subject] |
---|
| 916 | |
---|
| 917 | # hard-code the time to 30 days for now. Can easily be |
---|
| 918 | # made configurable |
---|
| 919 | lookback = int(time.mktime(time.gmtime())) - 2592000 |
---|
| 920 | |
---|
| 921 | for summary in summaries: |
---|
| 922 | if self.DEBUG: |
---|
| 923 | print 'TD: Looking for summary matching: "%s"' % summary |
---|
| 924 | sql = """SELECT id FROM ticket |
---|
| 925 | WHERE changetime >= %s AND summary LIKE %s |
---|
| 926 | ORDER BY changetime DESC""" |
---|
| 927 | cursor.execute(sql, [lookback, summary.strip()]) |
---|
| 928 | |
---|
| 929 | for row in cursor: |
---|
| 930 | (matched_id,) = row |
---|
| 931 | if self.DEBUG: |
---|
| 932 | print 'TD: Found matching ticket id: %d' % matched_id |
---|
| 933 | break |
---|
| 934 | |
---|
| 935 | if matched_id: |
---|
| 936 | matched_id = '#%d:' % matched_id |
---|
| 937 | return matched_id |
---|
| 938 | |
---|
| 939 | return matched_id |
---|
| 940 | |
---|
| 941 | |
---|
[262] | 942 | def new_ticket(self, msg, subject, spam, set_fields = None): |
---|
[202] | 943 | """ |
---|
[77] | 944 | Create a new ticket |
---|
| 945 | """ |
---|
[356] | 946 | if self.VERBOSE: |
---|
| 947 | print "VB: function new_ticket()" |
---|
[250] | 948 | |
---|
[41] | 949 | tkt = Ticket(self.env) |
---|
[326] | 950 | |
---|
| 951 | self.set_reply_fields(tkt, msg) |
---|
| 952 | |
---|
[202] | 953 | self.set_ticket_fields(tkt) |
---|
| 954 | |
---|
| 955 | # Old style setting for component, will be removed |
---|
| 956 | # |
---|
[204] | 957 | if spam: |
---|
| 958 | tkt['component'] = 'Spam' |
---|
| 959 | |
---|
[206] | 960 | elif self.parameters.has_key('component'): |
---|
| 961 | tkt['component'] = self.parameters['component'] |
---|
[201] | 962 | |
---|
[22] | 963 | if not msg['Subject']: |
---|
[151] | 964 | tkt['summary'] = u'(No subject)' |
---|
[22] | 965 | else: |
---|
[264] | 966 | tkt['summary'] = subject |
---|
[22] | 967 | |
---|
| 968 | |
---|
[262] | 969 | if set_fields: |
---|
| 970 | rest, keywords = string.split(set_fields, '?') |
---|
| 971 | |
---|
| 972 | if keywords: |
---|
| 973 | update_fields = self.str_to_dict(keywords) |
---|
| 974 | self.update_ticket_fields(tkt, update_fields) |
---|
| 975 | |
---|
[45] | 976 | # produce e-mail like header |
---|
| 977 | # |
---|
[22] | 978 | head = '' |
---|
| 979 | if self.EMAIL_HEADER > 0: |
---|
| 980 | head = self.email_header_txt(msg) |
---|
[296] | 981 | |
---|
[236] | 982 | message_parts = self.get_message_parts(msg) |
---|
[309] | 983 | |
---|
| 984 | # Must we update some ticket fields properties via body_text |
---|
| 985 | # |
---|
| 986 | if self.properties: |
---|
| 987 | self.update_ticket_fields(tkt, self.properties) |
---|
| 988 | |
---|
[296] | 989 | if self.DEBUG: |
---|
| 990 | print 'TD: self.get_message_parts ', |
---|
| 991 | print message_parts |
---|
| 992 | |
---|
[236] | 993 | message_parts = self.unique_attachment_names(message_parts) |
---|
[296] | 994 | if self.DEBUG: |
---|
| 995 | print 'TD: self.unique_attachment_names', |
---|
| 996 | print message_parts |
---|
[236] | 997 | |
---|
| 998 | if self.EMAIL_HEADER > 0: |
---|
| 999 | message_parts.insert(0, self.email_header_txt(msg)) |
---|
| 1000 | |
---|
| 1001 | body_text = self.body_text(message_parts) |
---|
[45] | 1002 | |
---|
[236] | 1003 | tkt['description'] = body_text |
---|
[90] | 1004 | |
---|
[182] | 1005 | #when = int(time.time()) |
---|
[192] | 1006 | # |
---|
[182] | 1007 | utc = UTC() |
---|
| 1008 | when = datetime.now(utc) |
---|
[45] | 1009 | |
---|
[253] | 1010 | if not self.DRY_RUN: |
---|
| 1011 | self.id = tkt.insert() |
---|
[273] | 1012 | |
---|
[90] | 1013 | changed = False |
---|
| 1014 | comment = '' |
---|
[77] | 1015 | |
---|
[273] | 1016 | # some routines in trac are dependend on ticket id |
---|
| 1017 | # like alternate notify template |
---|
| 1018 | # |
---|
| 1019 | if self.notify_template: |
---|
[274] | 1020 | tkt['id'] = self.id |
---|
[273] | 1021 | changed = True |
---|
| 1022 | |
---|
[295] | 1023 | ## Rewrite the description if we have mailto enabled |
---|
[45] | 1024 | # |
---|
[72] | 1025 | if self.MAILTO: |
---|
[100] | 1026 | changed = True |
---|
[142] | 1027 | comment = u'\nadded mailto line\n' |
---|
[343] | 1028 | mailto = self.html_mailto_link( m['Subject']) |
---|
[253] | 1029 | |
---|
[213] | 1030 | tkt['description'] = u'%s\r\n%s%s\r\n' \ |
---|
[142] | 1031 | %(head, mailto, body_text) |
---|
[295] | 1032 | |
---|
| 1033 | ## Save the attachments to the ticket |
---|
| 1034 | # |
---|
[340] | 1035 | error_with_attachments = self.attach_attachments(message_parts) |
---|
[295] | 1036 | |
---|
[319] | 1037 | if error_with_attachments: |
---|
| 1038 | changed = True |
---|
| 1039 | comment = '%s\n%s\n' %(comment, error_with_attachments) |
---|
[45] | 1040 | |
---|
[90] | 1041 | if changed: |
---|
[204] | 1042 | if self.DRY_RUN: |
---|
[344] | 1043 | print 'DRY_RUN: tkt.save_changes(%s, comment) real reporter = %s' %( tkt['reporter'], self.author) |
---|
[201] | 1044 | else: |
---|
[344] | 1045 | tkt.save_changes(tkt['reporter'], comment) |
---|
[201] | 1046 | #print tkt.get_changelog(self.db, when) |
---|
[90] | 1047 | |
---|
[250] | 1048 | if self.notification and not spam: |
---|
[253] | 1049 | self.notify(tkt, True) |
---|
[45] | 1050 | |
---|
[260] | 1051 | |
---|
[342] | 1052 | def attach_attachments(self, message_parts, update=False): |
---|
| 1053 | ''' |
---|
| 1054 | save any attachments as files in the ticket's directory |
---|
| 1055 | ''' |
---|
| 1056 | if self.VERBOSE: |
---|
| 1057 | print "VB: attach_attachments()" |
---|
| 1058 | |
---|
| 1059 | if self.DRY_RUN: |
---|
| 1060 | print "DRY_RUN: no attachments attached to tickets" |
---|
| 1061 | return '' |
---|
| 1062 | |
---|
| 1063 | count = 0 |
---|
| 1064 | |
---|
| 1065 | # Get Maxium attachment size |
---|
| 1066 | # |
---|
| 1067 | max_size = int(self.get_config('attachment', 'max_size')) |
---|
| 1068 | status = None |
---|
| 1069 | |
---|
| 1070 | for item in message_parts: |
---|
| 1071 | # Skip body parts |
---|
| 1072 | if not isinstance(item, tuple): |
---|
| 1073 | continue |
---|
| 1074 | |
---|
| 1075 | (original, filename, part) = item |
---|
| 1076 | # |
---|
| 1077 | # Must be tuneables HvB |
---|
| 1078 | # |
---|
| 1079 | path, fd = util.create_unique_file(os.path.join(self.TMPDIR, filename)) |
---|
| 1080 | text = part.get_payload(decode=1) |
---|
| 1081 | if not text: |
---|
| 1082 | text = '(None)' |
---|
| 1083 | fd.write(text) |
---|
| 1084 | fd.close() |
---|
| 1085 | |
---|
| 1086 | # get the file_size |
---|
| 1087 | # |
---|
| 1088 | stats = os.lstat(path) |
---|
| 1089 | file_size = stats[stat.ST_SIZE] |
---|
| 1090 | |
---|
| 1091 | # Check if the attachment size is allowed |
---|
| 1092 | # |
---|
| 1093 | if (max_size != -1) and (file_size > max_size): |
---|
| 1094 | status = '%s\nFile %s is larger then allowed attachment size (%d > %d)\n\n' \ |
---|
| 1095 | %(status, original, file_size, max_size) |
---|
| 1096 | |
---|
| 1097 | os.unlink(path) |
---|
| 1098 | continue |
---|
| 1099 | else: |
---|
| 1100 | count = count + 1 |
---|
| 1101 | |
---|
| 1102 | # Insert the attachment |
---|
| 1103 | # |
---|
| 1104 | fd = open(path, 'rb') |
---|
| 1105 | att = attachment.Attachment(self.env, 'ticket', self.id) |
---|
| 1106 | |
---|
| 1107 | # This will break the ticket_update system, the body_text is vaporized |
---|
| 1108 | # ;-( |
---|
| 1109 | # |
---|
| 1110 | if not update: |
---|
| 1111 | att.author = self.author |
---|
| 1112 | att.description = self.email_to_unicode('Added by email2trac') |
---|
| 1113 | |
---|
[348] | 1114 | try: |
---|
| 1115 | att.insert(filename, fd, file_size) |
---|
| 1116 | except OSError, detail: |
---|
| 1117 | status = '%s\nFilename %s could not be saved, problem: %s' %(status, filename, detail) |
---|
[342] | 1118 | |
---|
| 1119 | # Remove the created temporary filename |
---|
| 1120 | # |
---|
| 1121 | fd.close() |
---|
| 1122 | os.unlink(path) |
---|
| 1123 | |
---|
| 1124 | ## return error |
---|
| 1125 | # |
---|
| 1126 | return status |
---|
| 1127 | |
---|
[339] | 1128 | ########## Fullblog functions ########################################################### |
---|
| 1129 | |
---|
[260] | 1130 | def blog(self, id): |
---|
| 1131 | """ |
---|
| 1132 | The blog create/update function |
---|
| 1133 | """ |
---|
| 1134 | # import the modules |
---|
| 1135 | # |
---|
| 1136 | from tracfullblog.core import FullBlogCore |
---|
[312] | 1137 | from tracfullblog.model import BlogPost, BlogComment |
---|
| 1138 | from trac.test import Mock, MockPerm |
---|
[260] | 1139 | |
---|
| 1140 | # instantiate blog core |
---|
| 1141 | blog = FullBlogCore(self.env) |
---|
[312] | 1142 | req = Mock(authname='anonymous', perm=MockPerm(), args={}) |
---|
| 1143 | |
---|
[260] | 1144 | if id: |
---|
| 1145 | |
---|
| 1146 | # update blog |
---|
| 1147 | # |
---|
[268] | 1148 | comment = BlogComment(self.env, id) |
---|
[260] | 1149 | comment.author = self.author |
---|
[312] | 1150 | |
---|
| 1151 | message_parts = self.get_message_parts(m) |
---|
| 1152 | comment.comment = self.body_text(message_parts) |
---|
| 1153 | |
---|
[260] | 1154 | blog.create_comment(req, comment) |
---|
| 1155 | |
---|
| 1156 | else: |
---|
| 1157 | # create blog |
---|
| 1158 | # |
---|
| 1159 | import time |
---|
| 1160 | post = BlogPost(self.env, 'blog_'+time.strftime("%Y%m%d%H%M%S", time.gmtime())) |
---|
| 1161 | |
---|
| 1162 | #post = BlogPost(self.env, blog._get_default_postname(self.env)) |
---|
| 1163 | |
---|
| 1164 | post.author = self.author |
---|
| 1165 | post.title = self.email_to_unicode(m['Subject']) |
---|
[312] | 1166 | |
---|
| 1167 | message_parts = self.get_message_parts(m) |
---|
| 1168 | post.body = self.body_text(message_parts) |
---|
[260] | 1169 | |
---|
| 1170 | blog.create_post(req, post, self.author, u'Created by email2trac', False) |
---|
| 1171 | |
---|
| 1172 | |
---|
[342] | 1173 | |
---|
| 1174 | ########## MAIN function ########################################################### |
---|
| 1175 | |
---|
[77] | 1176 | def parse(self, fp): |
---|
[356] | 1177 | """ |
---|
| 1178 | """ |
---|
| 1179 | if self.VERBOSE: |
---|
| 1180 | print "VB: main function parse()" |
---|
[96] | 1181 | global m |
---|
| 1182 | |
---|
[77] | 1183 | m = email.message_from_file(fp) |
---|
[239] | 1184 | |
---|
[77] | 1185 | if not m: |
---|
[221] | 1186 | if self.DEBUG: |
---|
[250] | 1187 | print "TD: This is not a valid email message format" |
---|
[77] | 1188 | return |
---|
[239] | 1189 | |
---|
| 1190 | # Work around lack of header folding in Python; see http://bugs.python.org/issue4696 |
---|
[316] | 1191 | try: |
---|
| 1192 | m.replace_header('Subject', m['Subject'].replace('\r', '').replace('\n', '')) |
---|
| 1193 | except AttributeError, detail: |
---|
| 1194 | pass |
---|
[239] | 1195 | |
---|
[77] | 1196 | if self.DEBUG > 1: # save the entire e-mail message text |
---|
[219] | 1197 | self.save_email_for_debug(m, True) |
---|
[77] | 1198 | |
---|
| 1199 | self.db = self.env.get_db_cnx() |
---|
[194] | 1200 | self.get_sender_info(m) |
---|
[152] | 1201 | |
---|
[221] | 1202 | if not self.email_header_acl('white_list', self.email_addr, True): |
---|
| 1203 | if self.DEBUG > 1 : |
---|
| 1204 | print 'Message rejected : %s not in white list' %(self.email_addr) |
---|
| 1205 | return False |
---|
[77] | 1206 | |
---|
[221] | 1207 | if self.email_header_acl('black_list', self.email_addr, False): |
---|
| 1208 | if self.DEBUG > 1 : |
---|
| 1209 | print 'Message rejected : %s in black list' %(self.email_addr) |
---|
| 1210 | return False |
---|
| 1211 | |
---|
[227] | 1212 | if not self.email_header_acl('recipient_list', self.to_email_addr, True): |
---|
[226] | 1213 | if self.DEBUG > 1 : |
---|
| 1214 | print 'Message rejected : %s not in recipient list' %(self.to_email_addr) |
---|
| 1215 | return False |
---|
| 1216 | |
---|
[204] | 1217 | # If drop the message |
---|
[194] | 1218 | # |
---|
[204] | 1219 | if self.spam(m) == 'drop': |
---|
[194] | 1220 | return False |
---|
| 1221 | |
---|
[204] | 1222 | elif self.spam(m) == 'spam': |
---|
| 1223 | spam_msg = True |
---|
| 1224 | else: |
---|
| 1225 | spam_msg = False |
---|
| 1226 | |
---|
[77] | 1227 | if self.get_config('notification', 'smtp_enabled') in ['true']: |
---|
| 1228 | self.notification = 1 |
---|
| 1229 | else: |
---|
| 1230 | self.notification = 0 |
---|
| 1231 | |
---|
[304] | 1232 | |
---|
[260] | 1233 | # Check if FullBlogPlugin is installed |
---|
[77] | 1234 | # |
---|
[260] | 1235 | blog_enabled = None |
---|
| 1236 | if self.get_config('components', 'tracfullblog.*') in ['enabled']: |
---|
| 1237 | blog_enabled = True |
---|
[329] | 1238 | |
---|
[260] | 1239 | if not m['Subject']: |
---|
[329] | 1240 | subject = 'No Subject' |
---|
[260] | 1241 | else: |
---|
| 1242 | subject = self.email_to_unicode(m['Subject']) |
---|
[77] | 1243 | |
---|
[260] | 1244 | # |
---|
| 1245 | # [hic] #1529: Re: LRZ |
---|
| 1246 | # [hic] #1529?owner=bas,priority=medium: Re: LRZ |
---|
| 1247 | # |
---|
| 1248 | TICKET_RE = re.compile(r""" |
---|
| 1249 | (?P<blog>blog:(?P<blog_id>\w*)) |
---|
[262] | 1250 | |(?P<new_fields>[#][?].*) |
---|
| 1251 | |(?P<reply>[#][\d]+:) |
---|
| 1252 | |(?P<reply_fields>[#][\d]+\?.*?:) |
---|
[260] | 1253 | """, re.VERBOSE) |
---|
[77] | 1254 | |
---|
[265] | 1255 | # Find out if this is a ticket or a blog |
---|
| 1256 | # |
---|
[260] | 1257 | result = TICKET_RE.search(subject) |
---|
| 1258 | |
---|
| 1259 | if result: |
---|
[309] | 1260 | if result.group('blog'): |
---|
| 1261 | if blog_enabled: |
---|
| 1262 | self.blog(result.group('blog_id')) |
---|
| 1263 | else: |
---|
| 1264 | if self.DEBUG: |
---|
| 1265 | print "Fullblog plugin is not installed" |
---|
| 1266 | return |
---|
[260] | 1267 | |
---|
| 1268 | # update ticket + fields |
---|
| 1269 | # |
---|
[262] | 1270 | if result.group('reply_fields') and self.TICKET_UPDATE: |
---|
| 1271 | self.ticket_update(m, result.group('reply_fields'), spam_msg) |
---|
[260] | 1272 | |
---|
| 1273 | # Update ticket |
---|
| 1274 | # |
---|
[262] | 1275 | elif result.group('reply') and self.TICKET_UPDATE: |
---|
| 1276 | self.ticket_update(m, result.group('reply'), spam_msg) |
---|
[260] | 1277 | |
---|
[262] | 1278 | # New ticket + fields |
---|
| 1279 | # |
---|
| 1280 | elif result.group('new_fields'): |
---|
| 1281 | self.new_ticket(m, subject[:result.start('new_fields')], spam_msg, result.group('new_fields')) |
---|
| 1282 | |
---|
[260] | 1283 | else: |
---|
[356] | 1284 | result = self.ticket_update_by_subject(subject) |
---|
| 1285 | if result: |
---|
| 1286 | self.ticket_update(m, result, spam_msg) |
---|
[353] | 1287 | else: |
---|
| 1288 | # No update by subject, so just create a new ticket |
---|
| 1289 | self.new_ticket(m, subject, spam_msg) |
---|
| 1290 | |
---|
[356] | 1291 | |
---|
[343] | 1292 | ########## BODY TEXT functions ########################################################### |
---|
| 1293 | |
---|
[136] | 1294 | def strip_signature(self, text): |
---|
| 1295 | """ |
---|
| 1296 | Strip signature from message, inspired by Mailman software |
---|
| 1297 | """ |
---|
| 1298 | body = [] |
---|
| 1299 | for line in text.splitlines(): |
---|
| 1300 | if line == '-- ': |
---|
| 1301 | break |
---|
| 1302 | body.append(line) |
---|
| 1303 | |
---|
| 1304 | return ('\n'.join(body)) |
---|
| 1305 | |
---|
[231] | 1306 | def reflow(self, text, delsp = 0): |
---|
| 1307 | """ |
---|
| 1308 | Reflow the message based on the format="flowed" specification (RFC 3676) |
---|
| 1309 | """ |
---|
| 1310 | flowedlines = [] |
---|
| 1311 | quotelevel = 0 |
---|
| 1312 | prevflowed = 0 |
---|
| 1313 | |
---|
| 1314 | for line in text.splitlines(): |
---|
| 1315 | from re import match |
---|
| 1316 | |
---|
| 1317 | # Figure out the quote level and the content of the current line |
---|
| 1318 | m = match('(>*)( ?)(.*)', line) |
---|
| 1319 | linequotelevel = len(m.group(1)) |
---|
| 1320 | line = m.group(3) |
---|
| 1321 | |
---|
| 1322 | # Determine whether this line is flowed |
---|
| 1323 | if line and line != '-- ' and line[-1] == ' ': |
---|
| 1324 | flowed = 1 |
---|
| 1325 | else: |
---|
| 1326 | flowed = 0 |
---|
| 1327 | |
---|
| 1328 | if flowed and delsp and line and line[-1] == ' ': |
---|
| 1329 | line = line[:-1] |
---|
| 1330 | |
---|
| 1331 | # If the previous line is flowed, append this line to it |
---|
| 1332 | if prevflowed and line != '-- ' and linequotelevel == quotelevel: |
---|
| 1333 | flowedlines[-1] += line |
---|
| 1334 | # Otherwise, start a new line |
---|
| 1335 | else: |
---|
| 1336 | flowedlines.append('>' * linequotelevel + line) |
---|
| 1337 | |
---|
| 1338 | prevflowed = flowed |
---|
| 1339 | |
---|
| 1340 | |
---|
| 1341 | return '\n'.join(flowedlines) |
---|
| 1342 | |
---|
[191] | 1343 | def strip_quotes(self, text): |
---|
[193] | 1344 | """ |
---|
| 1345 | Strip quotes from message by Nicolas Mendoza |
---|
| 1346 | """ |
---|
| 1347 | body = [] |
---|
| 1348 | for line in text.splitlines(): |
---|
| 1349 | if line.startswith(self.EMAIL_QUOTE): |
---|
| 1350 | continue |
---|
| 1351 | body.append(line) |
---|
[151] | 1352 | |
---|
[193] | 1353 | return ('\n'.join(body)) |
---|
[191] | 1354 | |
---|
[309] | 1355 | def inline_properties(self, text): |
---|
| 1356 | """ |
---|
| 1357 | Parse text if we use inline keywords to set ticket fields |
---|
| 1358 | """ |
---|
| 1359 | if self.DEBUG: |
---|
| 1360 | print 'TD: inline_properties function' |
---|
| 1361 | |
---|
| 1362 | properties = dict() |
---|
| 1363 | body = list() |
---|
| 1364 | |
---|
| 1365 | INLINE_EXP = re.compile('\s*[@]\s*([a-zA-Z]+)\s*:(.*)$') |
---|
| 1366 | |
---|
| 1367 | for line in text.splitlines(): |
---|
| 1368 | match = INLINE_EXP.match(line) |
---|
| 1369 | if match: |
---|
| 1370 | keyword, value = match.groups() |
---|
| 1371 | self.properties[keyword] = value.strip() |
---|
[311] | 1372 | if self.DEBUG: |
---|
| 1373 | print "TD: inline properties: %s : %s" %(keyword,value) |
---|
[309] | 1374 | else: |
---|
| 1375 | body.append(line) |
---|
| 1376 | |
---|
| 1377 | return '\n'.join(body) |
---|
| 1378 | |
---|
| 1379 | |
---|
[154] | 1380 | def wrap_text(self, text, replace_whitespace = False): |
---|
[151] | 1381 | """ |
---|
[191] | 1382 | Will break a lines longer then given length into several small |
---|
| 1383 | lines of size given length |
---|
[151] | 1384 | """ |
---|
| 1385 | import textwrap |
---|
[154] | 1386 | |
---|
[151] | 1387 | LINESEPARATOR = '\n' |
---|
[153] | 1388 | reformat = '' |
---|
[151] | 1389 | |
---|
[154] | 1390 | for s in text.split(LINESEPARATOR): |
---|
| 1391 | tmp = textwrap.fill(s,self.USE_TEXTWRAP) |
---|
| 1392 | if tmp: |
---|
| 1393 | reformat = '%s\n%s' %(reformat,tmp) |
---|
| 1394 | else: |
---|
| 1395 | reformat = '%s\n' %reformat |
---|
[153] | 1396 | |
---|
| 1397 | return reformat |
---|
| 1398 | |
---|
[154] | 1399 | # Python2.4 and higher |
---|
| 1400 | # |
---|
| 1401 | #return LINESEPARATOR.join(textwrap.fill(s,width) for s in str.split(LINESEPARATOR)) |
---|
| 1402 | # |
---|
| 1403 | |
---|
[343] | 1404 | ########## EMAIL attachements functions ########################################################### |
---|
| 1405 | |
---|
[340] | 1406 | def inline_part(self, part): |
---|
| 1407 | """ |
---|
| 1408 | """ |
---|
| 1409 | if self.VERBOSE: |
---|
| 1410 | print "VB: inline_part()" |
---|
[154] | 1411 | |
---|
[340] | 1412 | return part.get_param('inline', None, 'Content-Disposition') == '' or not part.has_key('Content-Disposition') |
---|
| 1413 | |
---|
[236] | 1414 | def get_message_parts(self, msg): |
---|
[45] | 1415 | """ |
---|
[236] | 1416 | parses the email message and returns a list of body parts and attachments |
---|
| 1417 | body parts are returned as strings, attachments are returned as tuples of (filename, Message object) |
---|
[45] | 1418 | """ |
---|
[317] | 1419 | if self.VERBOSE: |
---|
| 1420 | print "VB: get_message_parts()" |
---|
| 1421 | |
---|
[309] | 1422 | message_parts = list() |
---|
[294] | 1423 | |
---|
[278] | 1424 | ALTERNATIVE_MULTIPART = False |
---|
| 1425 | |
---|
[22] | 1426 | for part in msg.walk(): |
---|
[236] | 1427 | if self.DEBUG: |
---|
[278] | 1428 | print 'TD: Message part: Main-Type: %s' % part.get_content_maintype() |
---|
[236] | 1429 | print 'TD: Message part: Content-Type: %s' % part.get_content_type() |
---|
[278] | 1430 | |
---|
| 1431 | ## Check content type |
---|
[294] | 1432 | # |
---|
| 1433 | if part.get_content_type() in self.STRIP_CONTENT_TYPES: |
---|
[238] | 1434 | |
---|
[294] | 1435 | if self.DEBUG: |
---|
| 1436 | print "TD: A %s attachment named '%s' was skipped" %(part.get_content_type(), part.get_filename()) |
---|
[238] | 1437 | |
---|
| 1438 | continue |
---|
| 1439 | |
---|
[294] | 1440 | ## Catch some mulitpart execptions |
---|
| 1441 | # |
---|
| 1442 | if part.get_content_type() == 'multipart/alternative': |
---|
[278] | 1443 | ALTERNATIVE_MULTIPART = True |
---|
| 1444 | continue |
---|
| 1445 | |
---|
[294] | 1446 | ## Skip multipart containers |
---|
[278] | 1447 | # |
---|
[45] | 1448 | if part.get_content_maintype() == 'multipart': |
---|
[278] | 1449 | if self.DEBUG: |
---|
| 1450 | print "TD: Skipping multipart container" |
---|
[22] | 1451 | continue |
---|
[278] | 1452 | |
---|
[294] | 1453 | ## Check if this is an inline part. It's inline if there is co Cont-Disp header, or if there is one and it says "inline" |
---|
| 1454 | # |
---|
[236] | 1455 | inline = self.inline_part(part) |
---|
| 1456 | |
---|
[294] | 1457 | ## Drop HTML message |
---|
| 1458 | # |
---|
[278] | 1459 | if ALTERNATIVE_MULTIPART and self.DROP_ALTERNATIVE_HTML_VERSION: |
---|
| 1460 | if part.get_content_type() == 'text/html': |
---|
| 1461 | if self.DEBUG: |
---|
| 1462 | print "TD: Skipping alternative HTML message" |
---|
| 1463 | |
---|
| 1464 | ALTERNATIVE_MULTIPART = False |
---|
| 1465 | continue |
---|
| 1466 | |
---|
[294] | 1467 | ## Inline text parts are where the body is |
---|
| 1468 | # |
---|
[236] | 1469 | if part.get_content_type() == 'text/plain' and inline: |
---|
| 1470 | if self.DEBUG: |
---|
| 1471 | print 'TD: Inline body part' |
---|
| 1472 | |
---|
[45] | 1473 | # Try to decode, if fails then do not decode |
---|
| 1474 | # |
---|
[90] | 1475 | body_text = part.get_payload(decode=1) |
---|
[45] | 1476 | if not body_text: |
---|
[90] | 1477 | body_text = part.get_payload(decode=0) |
---|
[231] | 1478 | |
---|
[232] | 1479 | format = email.Utils.collapse_rfc2231_value(part.get_param('Format', 'fixed')).lower() |
---|
| 1480 | delsp = email.Utils.collapse_rfc2231_value(part.get_param('DelSp', 'no')).lower() |
---|
[231] | 1481 | |
---|
| 1482 | if self.REFLOW and not self.VERBATIM_FORMAT and format == 'flowed': |
---|
| 1483 | body_text = self.reflow(body_text, delsp == 'yes') |
---|
[154] | 1484 | |
---|
[136] | 1485 | if self.STRIP_SIGNATURE: |
---|
| 1486 | body_text = self.strip_signature(body_text) |
---|
[22] | 1487 | |
---|
[191] | 1488 | if self.STRIP_QUOTES: |
---|
| 1489 | body_text = self.strip_quotes(body_text) |
---|
| 1490 | |
---|
[309] | 1491 | if self.INLINE_PROPERTIES: |
---|
| 1492 | body_text = self.inline_properties(body_text) |
---|
| 1493 | |
---|
[148] | 1494 | if self.USE_TEXTWRAP: |
---|
[151] | 1495 | body_text = self.wrap_text(body_text) |
---|
[148] | 1496 | |
---|
[294] | 1497 | ## Get contents charset (iso-8859-15 if not defined in mail headers) |
---|
[45] | 1498 | # |
---|
[100] | 1499 | charset = part.get_content_charset() |
---|
[102] | 1500 | if not charset: |
---|
| 1501 | charset = 'iso-8859-15' |
---|
| 1502 | |
---|
[89] | 1503 | try: |
---|
[96] | 1504 | ubody_text = unicode(body_text, charset) |
---|
[100] | 1505 | |
---|
| 1506 | except UnicodeError, detail: |
---|
[96] | 1507 | ubody_text = unicode(body_text, 'iso-8859-15') |
---|
[89] | 1508 | |
---|
[100] | 1509 | except LookupError, detail: |
---|
[139] | 1510 | ubody_text = 'ERROR: Could not find charset: %s, please install' %(charset) |
---|
[100] | 1511 | |
---|
[236] | 1512 | if self.VERBATIM_FORMAT: |
---|
| 1513 | message_parts.append('{{{\r\n%s\r\n}}}' %ubody_text) |
---|
| 1514 | else: |
---|
| 1515 | message_parts.append('%s' %ubody_text) |
---|
| 1516 | else: |
---|
| 1517 | if self.DEBUG: |
---|
[315] | 1518 | try: |
---|
| 1519 | print 'TD: Filename: %s' % part.get_filename() |
---|
| 1520 | except UnicodeEncodeError, detail: |
---|
[331] | 1521 | print 'TD: Filename: Can not be printed due to non-ascii characters' |
---|
[22] | 1522 | |
---|
[317] | 1523 | ## Convert 7-bit filename to 8 bits value |
---|
| 1524 | # |
---|
| 1525 | filename = self.email_to_unicode(part.get_filename()) |
---|
| 1526 | message_parts.append((filename, part)) |
---|
[236] | 1527 | |
---|
| 1528 | return message_parts |
---|
| 1529 | |
---|
[253] | 1530 | def unique_attachment_names(self, message_parts): |
---|
[296] | 1531 | """ |
---|
| 1532 | """ |
---|
[236] | 1533 | renamed_parts = [] |
---|
| 1534 | attachment_names = set() |
---|
[296] | 1535 | |
---|
[331] | 1536 | for item in message_parts: |
---|
[236] | 1537 | |
---|
[296] | 1538 | ## If not an attachment, leave it alone |
---|
| 1539 | # |
---|
[331] | 1540 | if not isinstance(item, tuple): |
---|
| 1541 | renamed_parts.append(item) |
---|
[236] | 1542 | continue |
---|
| 1543 | |
---|
[331] | 1544 | (filename, part) = item |
---|
[295] | 1545 | |
---|
[296] | 1546 | ## If no filename, use a default one |
---|
| 1547 | # |
---|
| 1548 | if not filename: |
---|
[236] | 1549 | filename = 'untitled-part' |
---|
[22] | 1550 | |
---|
[242] | 1551 | # Guess the extension from the content type, use non strict mode |
---|
| 1552 | # some additional non-standard but commonly used MIME types |
---|
| 1553 | # are also recognized |
---|
| 1554 | # |
---|
| 1555 | ext = mimetypes.guess_extension(part.get_content_type(), False) |
---|
[236] | 1556 | if not ext: |
---|
| 1557 | ext = '.bin' |
---|
[22] | 1558 | |
---|
[236] | 1559 | filename = '%s%s' % (filename, ext) |
---|
[22] | 1560 | |
---|
[348] | 1561 | ## Discard relative paths for windows/unix in attachment names |
---|
[296] | 1562 | # |
---|
[348] | 1563 | #filename = filename.replace('\\', '/').replace(':', '/') |
---|
| 1564 | filename = filename.replace('\\', '_') |
---|
| 1565 | filename = filename.replace('/', '_') |
---|
[347] | 1566 | |
---|
[296] | 1567 | # |
---|
[236] | 1568 | # We try to normalize the filename to utf-8 NFC if we can. |
---|
| 1569 | # Files uploaded from OS X might be in NFD. |
---|
| 1570 | # Check python version and then try it |
---|
| 1571 | # |
---|
[348] | 1572 | #if sys.version_info[0] > 2 or (sys.version_info[0] == 2 and sys.version_info[1] >= 3): |
---|
| 1573 | # try: |
---|
| 1574 | # filename = unicodedata.normalize('NFC', unicode(filename, 'utf-8')).encode('utf-8') |
---|
| 1575 | # except TypeError: |
---|
| 1576 | # pass |
---|
[100] | 1577 | |
---|
[236] | 1578 | # Make the filename unique for this ticket |
---|
| 1579 | num = 0 |
---|
| 1580 | unique_filename = filename |
---|
[296] | 1581 | dummy_filename, ext = os.path.splitext(filename) |
---|
[134] | 1582 | |
---|
[339] | 1583 | while (unique_filename in attachment_names) or self.attachment_exists(unique_filename): |
---|
[236] | 1584 | num += 1 |
---|
[296] | 1585 | unique_filename = "%s-%s%s" % (dummy_filename, num, ext) |
---|
[236] | 1586 | |
---|
| 1587 | if self.DEBUG: |
---|
[331] | 1588 | try: |
---|
| 1589 | print 'TD: Attachment with filename %s will be saved as %s' % (filename, unique_filename) |
---|
| 1590 | except UnicodeEncodeError, detail: |
---|
| 1591 | print 'Filename can not be printed due to non-ascii characters' |
---|
[100] | 1592 | |
---|
[236] | 1593 | attachment_names.add(unique_filename) |
---|
| 1594 | |
---|
| 1595 | renamed_parts.append((filename, unique_filename, part)) |
---|
[296] | 1596 | |
---|
[236] | 1597 | return renamed_parts |
---|
| 1598 | |
---|
| 1599 | |
---|
[253] | 1600 | def attachment_exists(self, filename): |
---|
[250] | 1601 | |
---|
| 1602 | if self.DEBUG: |
---|
[331] | 1603 | s = 'TD: attachment already exists: Ticket id : ' |
---|
| 1604 | try: |
---|
| 1605 | print "%s%s, Filename : %s" %(s, self.id, filename) |
---|
| 1606 | except UnicodeEncodeError, detail: |
---|
| 1607 | print "%s%s, Filename : Can not be printed due to non-ascii characters" %(s, self.id) |
---|
[250] | 1608 | |
---|
| 1609 | # We have no valid ticket id |
---|
| 1610 | # |
---|
[253] | 1611 | if not self.id: |
---|
[236] | 1612 | return False |
---|
[250] | 1613 | |
---|
[236] | 1614 | try: |
---|
[253] | 1615 | att = attachment.Attachment(self.env, 'ticket', self.id, filename) |
---|
[236] | 1616 | return True |
---|
[250] | 1617 | except attachment.ResourceNotFound: |
---|
[236] | 1618 | return False |
---|
[343] | 1619 | |
---|
| 1620 | ########## TRAC Ticket Text ########################################################### |
---|
[236] | 1621 | |
---|
| 1622 | def body_text(self, message_parts): |
---|
| 1623 | body_text = [] |
---|
| 1624 | |
---|
| 1625 | for part in message_parts: |
---|
| 1626 | # Plain text part, append it |
---|
| 1627 | if not isinstance(part, tuple): |
---|
| 1628 | body_text.extend(part.strip().splitlines()) |
---|
| 1629 | body_text.append("") |
---|
| 1630 | continue |
---|
| 1631 | |
---|
| 1632 | (original, filename, part) = part |
---|
| 1633 | inline = self.inline_part(part) |
---|
| 1634 | |
---|
| 1635 | if part.get_content_maintype() == 'image' and inline: |
---|
| 1636 | body_text.append('[[Image(%s)]]' % filename) |
---|
| 1637 | body_text.append("") |
---|
| 1638 | else: |
---|
| 1639 | body_text.append('[attachment:"%s"]' % filename) |
---|
| 1640 | body_text.append("") |
---|
| 1641 | |
---|
| 1642 | body_text = '\r\n'.join(body_text) |
---|
| 1643 | return body_text |
---|
| 1644 | |
---|
[343] | 1645 | def html_mailto_link(self, subject): |
---|
| 1646 | """ |
---|
| 1647 | This function returns a HTML mailto tag with the ticket id and author email address |
---|
| 1648 | """ |
---|
| 1649 | if not self.author: |
---|
| 1650 | author = self.email_addr |
---|
| 1651 | else: |
---|
| 1652 | author = self.author |
---|
| 1653 | |
---|
| 1654 | # use urllib to escape the chars |
---|
| 1655 | # |
---|
| 1656 | s = 'mailto:%s?Subject=%s&Cc=%s' %( |
---|
| 1657 | urllib.quote(self.email_addr), |
---|
| 1658 | urllib.quote('Re: #%s: %s' %(self.id, subject)), |
---|
| 1659 | urllib.quote(self.MAILTO_CC) |
---|
| 1660 | ) |
---|
| 1661 | |
---|
| 1662 | s = '\r\n{{{\r\n#!html\r\n<a\r\n href="%s">Reply to: %s\r\n</a>\r\n}}}\r\n' %(s, author) |
---|
| 1663 | return s |
---|
| 1664 | |
---|
| 1665 | ########## TRAC notify section ########################################################### |
---|
| 1666 | |
---|
[253] | 1667 | def notify(self, tkt, new=True, modtime=0): |
---|
[79] | 1668 | """ |
---|
| 1669 | A wrapper for the TRAC notify function. So we can use templates |
---|
| 1670 | """ |
---|
[250] | 1671 | if self.DRY_RUN: |
---|
[344] | 1672 | print 'DRY_RUN: self.notify(tkt, True) reporter = %s' %tkt['reporter'] |
---|
[250] | 1673 | return |
---|
[41] | 1674 | try: |
---|
| 1675 | # create false {abs_}href properties, to trick Notify() |
---|
| 1676 | # |
---|
[193] | 1677 | if not self.VERSION == 0.11: |
---|
[192] | 1678 | self.env.abs_href = Href(self.get_config('project', 'url')) |
---|
| 1679 | self.env.href = Href(self.get_config('project', 'url')) |
---|
[22] | 1680 | |
---|
[41] | 1681 | tn = TicketNotifyEmail(self.env) |
---|
[213] | 1682 | |
---|
[42] | 1683 | if self.notify_template: |
---|
[222] | 1684 | |
---|
[221] | 1685 | if self.VERSION == 0.11: |
---|
[222] | 1686 | |
---|
[221] | 1687 | from trac.web.chrome import Chrome |
---|
[222] | 1688 | |
---|
| 1689 | if self.notify_template_update and not new: |
---|
| 1690 | tn.template_name = self.notify_template_update |
---|
| 1691 | else: |
---|
| 1692 | tn.template_name = self.notify_template |
---|
| 1693 | |
---|
[221] | 1694 | tn.template = Chrome(tn.env).load_template(tn.template_name, method='text') |
---|
| 1695 | |
---|
| 1696 | else: |
---|
[222] | 1697 | |
---|
[221] | 1698 | tn.template_name = self.notify_template; |
---|
[42] | 1699 | |
---|
[77] | 1700 | tn.notify(tkt, new, modtime) |
---|
[41] | 1701 | |
---|
| 1702 | except Exception, e: |
---|
[253] | 1703 | print 'TD: Failure sending notification on creation of ticket #%s: %s' %(self.id, e) |
---|
[41] | 1704 | |
---|
[22] | 1705 | |
---|
[74] | 1706 | |
---|
[343] | 1707 | ########## Parse Config File ########################################################### |
---|
[22] | 1708 | |
---|
| 1709 | def ReadConfig(file, name): |
---|
| 1710 | """ |
---|
| 1711 | Parse the config file |
---|
| 1712 | """ |
---|
| 1713 | if not os.path.isfile(file): |
---|
[79] | 1714 | print 'File %s does not exist' %file |
---|
[22] | 1715 | sys.exit(1) |
---|
| 1716 | |
---|
[199] | 1717 | config = trac_config.Configuration(file) |
---|
[22] | 1718 | |
---|
| 1719 | # Use given project name else use defaults |
---|
| 1720 | # |
---|
| 1721 | if name: |
---|
[199] | 1722 | sections = config.sections() |
---|
| 1723 | if not name in sections: |
---|
[79] | 1724 | print "Not a valid project name: %s" %name |
---|
[199] | 1725 | print "Valid names: %s" %sections |
---|
[22] | 1726 | sys.exit(1) |
---|
| 1727 | |
---|
| 1728 | project = dict() |
---|
[199] | 1729 | for option, value in config.options(name): |
---|
| 1730 | project[option] = value |
---|
[22] | 1731 | |
---|
| 1732 | else: |
---|
[270] | 1733 | # use some trac internals to get the defaults |
---|
[217] | 1734 | # |
---|
| 1735 | project = config.parser.defaults() |
---|
[22] | 1736 | |
---|
| 1737 | return project |
---|
| 1738 | |
---|
[87] | 1739 | |
---|
[22] | 1740 | if __name__ == '__main__': |
---|
| 1741 | # Default config file |
---|
| 1742 | # |
---|
[24] | 1743 | configfile = '@email2trac_conf@' |
---|
[22] | 1744 | project = '' |
---|
| 1745 | component = '' |
---|
[202] | 1746 | ticket_prefix = 'default' |
---|
[204] | 1747 | dry_run = None |
---|
[317] | 1748 | verbose = None |
---|
[202] | 1749 | |
---|
[87] | 1750 | ENABLE_SYSLOG = 0 |
---|
[201] | 1751 | |
---|
[204] | 1752 | |
---|
[317] | 1753 | SHORT_OPT = 'chf:np:t:v' |
---|
| 1754 | LONG_OPT = ['component=', 'dry-run', 'help', 'file=', 'project=', 'ticket_prefix=', 'verbose'] |
---|
[201] | 1755 | |
---|
[22] | 1756 | try: |
---|
[201] | 1757 | opts, args = getopt.getopt(sys.argv[1:], SHORT_OPT, LONG_OPT) |
---|
[22] | 1758 | except getopt.error,detail: |
---|
| 1759 | print __doc__ |
---|
| 1760 | print detail |
---|
| 1761 | sys.exit(1) |
---|
[87] | 1762 | |
---|
[22] | 1763 | project_name = None |
---|
| 1764 | for opt,value in opts: |
---|
| 1765 | if opt in [ '-h', '--help']: |
---|
| 1766 | print __doc__ |
---|
| 1767 | sys.exit(0) |
---|
| 1768 | elif opt in ['-c', '--component']: |
---|
| 1769 | component = value |
---|
| 1770 | elif opt in ['-f', '--file']: |
---|
| 1771 | configfile = value |
---|
[201] | 1772 | elif opt in ['-n', '--dry-run']: |
---|
[204] | 1773 | dry_run = True |
---|
[22] | 1774 | elif opt in ['-p', '--project']: |
---|
| 1775 | project_name = value |
---|
[202] | 1776 | elif opt in ['-t', '--ticket_prefix']: |
---|
| 1777 | ticket_prefix = value |
---|
[317] | 1778 | elif opt in ['-v', '--version']: |
---|
| 1779 | verbose = True |
---|
[87] | 1780 | |
---|
[22] | 1781 | settings = ReadConfig(configfile, project_name) |
---|
| 1782 | if not settings.has_key('project'): |
---|
| 1783 | print __doc__ |
---|
[79] | 1784 | print 'No Trac project is defined in the email2trac config file.' |
---|
[22] | 1785 | sys.exit(1) |
---|
[87] | 1786 | |
---|
[22] | 1787 | if component: |
---|
| 1788 | settings['component'] = component |
---|
[202] | 1789 | |
---|
| 1790 | # The default prefix for ticket values in email2trac.conf |
---|
| 1791 | # |
---|
| 1792 | settings['ticket_prefix'] = ticket_prefix |
---|
[206] | 1793 | settings['dry_run'] = dry_run |
---|
[317] | 1794 | settings['verbose'] = verbose |
---|
[87] | 1795 | |
---|
[22] | 1796 | if settings.has_key('trac_version'): |
---|
[189] | 1797 | version = settings['trac_version'] |
---|
[22] | 1798 | else: |
---|
| 1799 | version = trac_default_version |
---|
| 1800 | |
---|
[189] | 1801 | |
---|
[22] | 1802 | #debug HvB |
---|
| 1803 | #print settings |
---|
[189] | 1804 | |
---|
[87] | 1805 | try: |
---|
[189] | 1806 | if version == '0.9': |
---|
[87] | 1807 | from trac import attachment |
---|
| 1808 | from trac.env import Environment |
---|
| 1809 | from trac.ticket import Ticket |
---|
| 1810 | from trac.web.href import Href |
---|
| 1811 | from trac import util |
---|
| 1812 | from trac.Notify import TicketNotifyEmail |
---|
[189] | 1813 | elif version == '0.10': |
---|
[87] | 1814 | from trac import attachment |
---|
| 1815 | from trac.env import Environment |
---|
| 1816 | from trac.ticket import Ticket |
---|
| 1817 | from trac.web.href import Href |
---|
| 1818 | from trac import util |
---|
[139] | 1819 | # |
---|
| 1820 | # return util.text.to_unicode(str) |
---|
| 1821 | # |
---|
[87] | 1822 | # see http://projects.edgewall.com/trac/changeset/2799 |
---|
| 1823 | from trac.ticket.notification import TicketNotifyEmail |
---|
[199] | 1824 | from trac import config as trac_config |
---|
[189] | 1825 | elif version == '0.11': |
---|
[182] | 1826 | from trac import attachment |
---|
| 1827 | from trac.env import Environment |
---|
| 1828 | from trac.ticket import Ticket |
---|
| 1829 | from trac.web.href import Href |
---|
[199] | 1830 | from trac import config as trac_config |
---|
[182] | 1831 | from trac import util |
---|
[260] | 1832 | |
---|
| 1833 | |
---|
[182] | 1834 | # |
---|
| 1835 | # return util.text.to_unicode(str) |
---|
| 1836 | # |
---|
| 1837 | # see http://projects.edgewall.com/trac/changeset/2799 |
---|
| 1838 | from trac.ticket.notification import TicketNotifyEmail |
---|
[189] | 1839 | else: |
---|
| 1840 | print 'TRAC version %s is not supported' %version |
---|
| 1841 | sys.exit(1) |
---|
| 1842 | |
---|
| 1843 | if settings.has_key('enable_syslog'): |
---|
[190] | 1844 | if SYSLOG_AVAILABLE: |
---|
| 1845 | ENABLE_SYSLOG = float(settings['enable_syslog']) |
---|
[182] | 1846 | |
---|
[291] | 1847 | |
---|
| 1848 | # Must be set before environment is created |
---|
| 1849 | # |
---|
| 1850 | if settings.has_key('python_egg_cache'): |
---|
| 1851 | python_egg_cache = str(settings['python_egg_cache']) |
---|
| 1852 | os.environ['PYTHON_EGG_CACHE'] = python_egg_cache |
---|
| 1853 | |
---|
[87] | 1854 | env = Environment(settings['project'], create=0) |
---|
[333] | 1855 | |
---|
[206] | 1856 | tktparser = TicketEmailParser(env, settings, float(version)) |
---|
[87] | 1857 | tktparser.parse(sys.stdin) |
---|
[22] | 1858 | |
---|
[87] | 1859 | # Catch all errors ans log to SYSLOG if we have enabled this |
---|
| 1860 | # else stdout |
---|
| 1861 | # |
---|
| 1862 | except Exception, error: |
---|
| 1863 | if ENABLE_SYSLOG: |
---|
| 1864 | syslog.openlog('email2trac', syslog.LOG_NOWAIT) |
---|
[187] | 1865 | |
---|
[87] | 1866 | etype, evalue, etb = sys.exc_info() |
---|
| 1867 | for e in traceback.format_exception(etype, evalue, etb): |
---|
| 1868 | syslog.syslog(e) |
---|
[187] | 1869 | |
---|
[87] | 1870 | syslog.closelog() |
---|
| 1871 | else: |
---|
| 1872 | traceback.print_exc() |
---|
[22] | 1873 | |
---|
[97] | 1874 | if m: |
---|
[98] | 1875 | tktparser.save_email_for_debug(m, True) |
---|
[97] | 1876 | |
---|
[356] | 1877 | |
---|
[249] | 1878 | sys.exit(1) |
---|
[22] | 1879 | # EOB |
---|