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 | """ |
---|
23 | email2trac.py -- Email tickets to Trac. |
---|
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 | |
---|
30 | Authors: |
---|
31 | Bas van der Vlies <basv@sara.nl> |
---|
32 | Walter de Jong <walter@sara.nl> |
---|
33 | |
---|
34 | The scripts reads emails from stdin and inserts directly into a Trac database. |
---|
35 | |
---|
36 | How to use |
---|
37 | ---------- |
---|
38 | * See https://subtrac.sara.nl/oss/email2trac/ |
---|
39 | |
---|
40 | * Create an config file: |
---|
41 | [DEFAULT] # REQUIRED |
---|
42 | project : /data/trac/test # REQUIRED |
---|
43 | debug : 1 # OPTIONAL, if set print some DEBUG info |
---|
44 | |
---|
45 | [jouvin] # OPTIONAL project declaration, if set both fields necessary |
---|
46 | project : /data/trac/jouvin # use -p|--project jouvin. |
---|
47 | |
---|
48 | * default config file is : /etc/email2trac.conf |
---|
49 | |
---|
50 | * Commandline opions: |
---|
51 | -h,--help |
---|
52 | -d, --debug |
---|
53 | -f,--file <configuration file> |
---|
54 | -n,--dry-run |
---|
55 | -p, --project <project name> |
---|
56 | -t, --ticket_prefix <name> |
---|
57 | |
---|
58 | SVN Info: |
---|
59 | $Id: email2trac.py.in 498 2010-12-28 17:17:50Z bas $ |
---|
60 | """ |
---|
61 | import os |
---|
62 | import sys |
---|
63 | import string |
---|
64 | import getopt |
---|
65 | import time |
---|
66 | import email |
---|
67 | import email.Iterators |
---|
68 | import email.Header |
---|
69 | import re |
---|
70 | import urllib |
---|
71 | import unicodedata |
---|
72 | import mimetypes |
---|
73 | import traceback |
---|
74 | import logging |
---|
75 | import logging.handlers |
---|
76 | import UserDict |
---|
77 | import tempfile |
---|
78 | |
---|
79 | from datetime import tzinfo, timedelta, datetime |
---|
80 | from stat import * |
---|
81 | |
---|
82 | |
---|
83 | from trac import __version__ as trac_version |
---|
84 | from trac import config as trac_config |
---|
85 | |
---|
86 | # Some global variables |
---|
87 | # |
---|
88 | m = None |
---|
89 | |
---|
90 | class SaraDict(UserDict.UserDict): |
---|
91 | def __init__(self, dictin = None): |
---|
92 | UserDict.UserDict.__init__(self) |
---|
93 | self.name = None |
---|
94 | |
---|
95 | if dictin: |
---|
96 | if dictin.has_key('name'): |
---|
97 | self.name = dictin['name'] |
---|
98 | del dictin['name'] |
---|
99 | self.data = dictin |
---|
100 | |
---|
101 | def get_value(self, name): |
---|
102 | if self.has_key(name): |
---|
103 | return self[name] |
---|
104 | else: |
---|
105 | return None |
---|
106 | |
---|
107 | def __repr__(self): |
---|
108 | return repr(self.data) |
---|
109 | |
---|
110 | def __str__(self): |
---|
111 | return str(self.data) |
---|
112 | |
---|
113 | def __getattr__(self, name): |
---|
114 | """ |
---|
115 | override the class attribute get method. Return the value |
---|
116 | from the dictionary |
---|
117 | """ |
---|
118 | if self.data.has_key(name): |
---|
119 | return self.data[name] |
---|
120 | else: |
---|
121 | return None |
---|
122 | |
---|
123 | def __setattr__(self, name, value): |
---|
124 | """ |
---|
125 | override the class attribute set method only when the UserDict |
---|
126 | has set its class attribute |
---|
127 | """ |
---|
128 | if self.__dict__.has_key('data'): |
---|
129 | self.data[name] = value |
---|
130 | else: |
---|
131 | self.__dict__[name] = value |
---|
132 | |
---|
133 | def __iter__(self): |
---|
134 | return iter(self.data.keys()) |
---|
135 | |
---|
136 | class TicketEmailParser(object): |
---|
137 | env = None |
---|
138 | comment = '> ' |
---|
139 | |
---|
140 | def __init__(self, env, parameters, logger, version): |
---|
141 | self.env = env |
---|
142 | |
---|
143 | # Database connection |
---|
144 | # |
---|
145 | self.db = None |
---|
146 | |
---|
147 | # Save parameters |
---|
148 | # |
---|
149 | self.parameters = parameters |
---|
150 | self.logger = logger |
---|
151 | |
---|
152 | # Some useful mail constants |
---|
153 | # |
---|
154 | self.email_name = None |
---|
155 | self.email_addr = None |
---|
156 | self.email_from = None |
---|
157 | self.author = None |
---|
158 | self.id = None |
---|
159 | |
---|
160 | self.STRIP_CONTENT_TYPES = list() |
---|
161 | |
---|
162 | ## fields properties via body_text |
---|
163 | # |
---|
164 | self.properties = dict() |
---|
165 | |
---|
166 | self.VERSION = version |
---|
167 | |
---|
168 | self.get_config = self.env.config.get |
---|
169 | |
---|
170 | ## init function ## |
---|
171 | # |
---|
172 | self.setup_parameters() |
---|
173 | |
---|
174 | def setup_parameters(self): |
---|
175 | if self.parameters.umask: |
---|
176 | os.umask(self.parameters.umask) |
---|
177 | |
---|
178 | if not self.parameters.spam_level: |
---|
179 | self.parameters.spam_level = 0 |
---|
180 | |
---|
181 | if not self.parameters.spam_header: |
---|
182 | self.parameters.spam_header = 'X-Spam-Score' |
---|
183 | |
---|
184 | if not self.parameters.email_quote: |
---|
185 | self.parameters.email_quote = '> ' |
---|
186 | |
---|
187 | if not self.parameters.ticket_update_by_subject_lookback: |
---|
188 | self.parameters.ticket_update_by_subject_lookback = 30 |
---|
189 | |
---|
190 | if self.parameters.verbatim_format == None: |
---|
191 | self.parameters.verbatim_format = 1 |
---|
192 | |
---|
193 | if self.parameters.reflow == None: |
---|
194 | self.parameters.reflow = 1 |
---|
195 | |
---|
196 | if self.parameters.binhex: |
---|
197 | self.STRIP_CONTENT_TYPES.append('application/mac-binhex40') |
---|
198 | |
---|
199 | if self.parameters.applesingle: |
---|
200 | self.STRIP_CONTENT_TYPES.append('application/applefile') |
---|
201 | |
---|
202 | if self.parameters.appledouble: |
---|
203 | self.STRIP_CONTENT_TYPES.append('application/applefile') |
---|
204 | |
---|
205 | if self.parameters.strip_content_types: |
---|
206 | items = self.parameters.strip_content_types.split(',') |
---|
207 | for item in items: |
---|
208 | self.STRIP_CONTENT_TYPES.append(item.strip()) |
---|
209 | |
---|
210 | if self.parameters.tmpdir: |
---|
211 | self.parameters.tmpdir = os.path.normcase(str(self.parameters['tmpdir'])) |
---|
212 | else: |
---|
213 | self.parameters.tmpdir = os.path.normcase('/tmp') |
---|
214 | |
---|
215 | if self.parameters.email_triggers_workflow == None: |
---|
216 | self.parameters.email_triggers_workflow = 1 |
---|
217 | |
---|
218 | if not self.parameters.subject_field_separator: |
---|
219 | self.parameters.subject_field_separator = '&' |
---|
220 | else: |
---|
221 | self.parameters.subject_field_separator = self.parameters.subject_field_separator.strip() |
---|
222 | |
---|
223 | self.trac_smtp_from = self.get_config('notification', 'smtp_from') |
---|
224 | self.smtp_default_domain = self.get_config('notification', 'smtp_default_domain') |
---|
225 | |
---|
226 | |
---|
227 | self.system = None |
---|
228 | |
---|
229 | ########## Email Header Functions ########################################################### |
---|
230 | |
---|
231 | def spam(self, message): |
---|
232 | """ |
---|
233 | # X-Spam-Score: *** (3.255) BAYES_50,DNS_FROM_AHBL_RHSBL,HTML_ |
---|
234 | # Note if Spam_level then '*' are included |
---|
235 | """ |
---|
236 | spam = False |
---|
237 | if message.has_key(self.parameters.spam_header): |
---|
238 | spam_l = string.split(message[self.parameters.spam_header]) |
---|
239 | |
---|
240 | try: |
---|
241 | number = spam_l[0].count('*') |
---|
242 | except IndexError, detail: |
---|
243 | number = 0 |
---|
244 | |
---|
245 | if number >= self.parameters.spam_level: |
---|
246 | spam = True |
---|
247 | |
---|
248 | # treat virus mails as spam |
---|
249 | # |
---|
250 | elif message.has_key('X-Virus-found'): |
---|
251 | spam = True |
---|
252 | |
---|
253 | # How to handle SPAM messages |
---|
254 | # |
---|
255 | if self.parameters.drop_spam and spam: |
---|
256 | |
---|
257 | self.logger.info('Message is a SPAM. Automatic ticket insertion refused (SPAM level > %d)' %self.parameters.spam_level) |
---|
258 | return 'drop' |
---|
259 | |
---|
260 | elif spam: |
---|
261 | |
---|
262 | return 'Spam' |
---|
263 | else: |
---|
264 | |
---|
265 | return False |
---|
266 | |
---|
267 | def email_header_acl(self, keyword, header_field, default): |
---|
268 | """ |
---|
269 | This function wil check if the email address is allowed or denied |
---|
270 | to send mail to the ticket list |
---|
271 | """ |
---|
272 | self.logger.debug('function email_header_acl: %s' %keyword) |
---|
273 | |
---|
274 | try: |
---|
275 | mail_addresses = self.parameters[keyword] |
---|
276 | |
---|
277 | # Check if we have an empty string |
---|
278 | # |
---|
279 | if not mail_addresses: |
---|
280 | return default |
---|
281 | |
---|
282 | except KeyError, detail: |
---|
283 | self.logger.debug('%s not defined, all messages are allowed.' %(keyword)) |
---|
284 | |
---|
285 | return default |
---|
286 | |
---|
287 | mail_addresses = string.split(mail_addresses, ',') |
---|
288 | |
---|
289 | for entry in mail_addresses: |
---|
290 | entry = entry.strip() |
---|
291 | TO_RE = re.compile(entry, re.VERBOSE|re.IGNORECASE) |
---|
292 | result = TO_RE.search(header_field) |
---|
293 | if result: |
---|
294 | return True |
---|
295 | |
---|
296 | return False |
---|
297 | |
---|
298 | def email_header_txt(self, m): |
---|
299 | """ |
---|
300 | Display To and CC addresses in description field |
---|
301 | """ |
---|
302 | s = '' |
---|
303 | |
---|
304 | if m['To'] and len(m['To']) > 0: |
---|
305 | s = "'''To:''' %s\r\n" %(m['To']) |
---|
306 | if m['Cc'] and len(m['Cc']) > 0: |
---|
307 | s = "%s'''Cc:''' %s\r\n" % (s, m['Cc']) |
---|
308 | |
---|
309 | return self.email_to_unicode(s) |
---|
310 | |
---|
311 | |
---|
312 | def get_sender_info(self, message): |
---|
313 | """ |
---|
314 | Get the default author name and email address from the message |
---|
315 | """ |
---|
316 | |
---|
317 | self.email_to = self.email_to_unicode(message['to']) |
---|
318 | self.to_name, self.to_email_addr = email.Utils.parseaddr (self.email_to) |
---|
319 | |
---|
320 | self.email_from = self.email_to_unicode(message['from']) |
---|
321 | self.email_name, self.email_addr = email.Utils.parseaddr(self.email_from) |
---|
322 | |
---|
323 | ## Trac can not handle author's name that contains spaces |
---|
324 | # |
---|
325 | if self.email_addr == self.trac_smtp_from: |
---|
326 | if self.email_name: |
---|
327 | self.author = self.email_name |
---|
328 | else: |
---|
329 | self.author = "email2trac" |
---|
330 | else: |
---|
331 | self.author = self.email_addr |
---|
332 | |
---|
333 | if self.parameters.ignore_trac_user_settings: |
---|
334 | return |
---|
335 | |
---|
336 | # Is this a registered user, use email address as search key: |
---|
337 | # result: |
---|
338 | # u : login name |
---|
339 | # n : Name that the user has set in the settings tab |
---|
340 | # e : email address that the user has set in the settings tab |
---|
341 | # |
---|
342 | users = [ (u,n,e) for (u, n, e) in self.env.get_known_users(self.db) |
---|
343 | if ( |
---|
344 | (e and (e.lower() == self.email_addr.lower())) or |
---|
345 | (u + '@' + self.smtp_default_domain.lower() == self.email_addr.lower()) |
---|
346 | ) |
---|
347 | ] |
---|
348 | |
---|
349 | if len(users) >= 1: |
---|
350 | self.email_from = users[0][0] |
---|
351 | self.author = users[0][0] |
---|
352 | |
---|
353 | def set_reply_fields(self, ticket, message): |
---|
354 | """ |
---|
355 | Set all the right fields for a new ticket |
---|
356 | """ |
---|
357 | self.logger.debug('function set_reply_fields') |
---|
358 | |
---|
359 | ## Only use name or email adress |
---|
360 | #ticket['reporter'] = self.email_from |
---|
361 | ticket['reporter'] = self.author |
---|
362 | |
---|
363 | |
---|
364 | # Put all CC-addresses in ticket CC field |
---|
365 | # |
---|
366 | if self.parameters.reply_all: |
---|
367 | |
---|
368 | email_cc = '' |
---|
369 | |
---|
370 | cc_addrs = email.Utils.getaddresses( message.get_all('cc', []) ) |
---|
371 | |
---|
372 | if not cc_addrs: |
---|
373 | return |
---|
374 | |
---|
375 | ## Build a list of forbidden CC addresses |
---|
376 | # |
---|
377 | #to_addrs = email.Utils.getaddresses( message.get_all('to', []) ) |
---|
378 | #to_list = list() |
---|
379 | #for n,e in to_addrs: |
---|
380 | # to_list.append(e) |
---|
381 | |
---|
382 | # Always Remove reporter email address from cc-list |
---|
383 | # |
---|
384 | try: |
---|
385 | cc_addrs.remove((self.author, self.email_addr)) |
---|
386 | except ValueError, detail: |
---|
387 | pass |
---|
388 | |
---|
389 | for name,addr in cc_addrs: |
---|
390 | |
---|
391 | ## Prevent mail loop |
---|
392 | # |
---|
393 | #if addr in to_list: |
---|
394 | |
---|
395 | if addr == self.trac_smtp_from: |
---|
396 | self.logger.debug("Skipping %s mail address for CC-field" %(addr)) |
---|
397 | continue |
---|
398 | |
---|
399 | if email_cc: |
---|
400 | email_cc = '%s, %s' %(email_cc, addr) |
---|
401 | else: |
---|
402 | email_cc = addr |
---|
403 | |
---|
404 | if email_cc: |
---|
405 | self.logger.debug('set_reply_fields: %s' %email_cc) |
---|
406 | |
---|
407 | ticket['cc'] = self.email_to_unicode(email_cc) |
---|
408 | |
---|
409 | |
---|
410 | ########## DEBUG functions ########################################################### |
---|
411 | |
---|
412 | def debug_body(self, message_body, temporary_file=False): |
---|
413 | if temporary_file: |
---|
414 | body_file = tempfile.mktemp('.email2trac') |
---|
415 | else: |
---|
416 | body_file = os.path.join(self.parameters.tmpdir, 'body.txt') |
---|
417 | |
---|
418 | if self.parameters.dry_run: |
---|
419 | print 'DRY-RUN: not saving body to %s' %(body_file) |
---|
420 | return |
---|
421 | |
---|
422 | print 'writing body to %s' %(body_file) |
---|
423 | fx = open(body_file, 'wb') |
---|
424 | if not message_body: |
---|
425 | message_body = '(None)' |
---|
426 | |
---|
427 | message_body = message_body.encode('utf-8') |
---|
428 | #message_body = unicode(message_body, 'iso-8859-15') |
---|
429 | |
---|
430 | fx.write(message_body) |
---|
431 | fx.close() |
---|
432 | try: |
---|
433 | os.chmod(body_file,S_IRWXU|S_IRWXG|S_IRWXO) |
---|
434 | except OSError: |
---|
435 | pass |
---|
436 | |
---|
437 | def debug_attachments(self, message_parts): |
---|
438 | """ |
---|
439 | """ |
---|
440 | self.logger.debug('function debug_attachments') |
---|
441 | |
---|
442 | n = 0 |
---|
443 | for item in message_parts: |
---|
444 | # Skip inline text parts |
---|
445 | if not isinstance(item, tuple): |
---|
446 | continue |
---|
447 | |
---|
448 | (original, filename, part) = item |
---|
449 | |
---|
450 | n = n + 1 |
---|
451 | print 'part%d: Content-Type: %s' % (n, part.get_content_type()) |
---|
452 | |
---|
453 | s = 'part%d: filename: %s' %(n, filename) |
---|
454 | self.print_unicode(s) |
---|
455 | |
---|
456 | ## Forbidden chars |
---|
457 | # |
---|
458 | filename = filename.replace('\\', '_') |
---|
459 | filename = filename.replace('/', '_') |
---|
460 | |
---|
461 | |
---|
462 | part_file = os.path.join(self.parameters.tmpdir, filename) |
---|
463 | s = 'writing part%d (%s)' % (n,part_file) |
---|
464 | self.print_unicode(s) |
---|
465 | |
---|
466 | if self.parameters.dry_run: |
---|
467 | print 'DRY_RUN: NOT saving attachments' |
---|
468 | continue |
---|
469 | |
---|
470 | part_file = util.text.unicode_quote(part_file) |
---|
471 | |
---|
472 | fx = open(part_file, 'wb') |
---|
473 | text = part.get_payload(decode=1) |
---|
474 | |
---|
475 | if not text: |
---|
476 | text = '(None)' |
---|
477 | |
---|
478 | fx.write(text) |
---|
479 | fx.close() |
---|
480 | |
---|
481 | try: |
---|
482 | os.chmod(part_file,S_IRWXU|S_IRWXG|S_IRWXO) |
---|
483 | except OSError: |
---|
484 | pass |
---|
485 | |
---|
486 | def save_email_for_debug(self, message, create_tempfile=False): |
---|
487 | |
---|
488 | if create_tempfile: |
---|
489 | msg_file = tempfile.mktemp('.email2trac') |
---|
490 | else: |
---|
491 | #msg_file = '/var/tmp/msg.txt' |
---|
492 | msg_file = os.path.join(self.parameters.tmpdir, 'msg.txt') |
---|
493 | |
---|
494 | if self.parameters.dry_run: |
---|
495 | print 'DRY_RUN: NOT saving email message to %s' %(msg_file) |
---|
496 | else: |
---|
497 | print 'saving email to %s' %(msg_file) |
---|
498 | |
---|
499 | fx = open(msg_file, 'wb') |
---|
500 | fx.write('%s' % message) |
---|
501 | fx.close() |
---|
502 | |
---|
503 | try: |
---|
504 | os.chmod(msg_file,S_IRWXU|S_IRWXG|S_IRWXO) |
---|
505 | except OSError: |
---|
506 | pass |
---|
507 | |
---|
508 | message_parts = self.get_message_parts(message) |
---|
509 | message_parts = self.unique_attachment_names(message_parts) |
---|
510 | body_text = self.get_body_text(message_parts) |
---|
511 | self.debug_body(body_text, True) |
---|
512 | self.debug_attachments(message_parts) |
---|
513 | |
---|
514 | ########## Conversion functions ########################################################### |
---|
515 | |
---|
516 | def email_to_unicode(self, message_str): |
---|
517 | """ |
---|
518 | Email has 7 bit ASCII code, convert it to unicode with the charset |
---|
519 | that is encoded in 7-bit ASCII code and encode it as utf-8 so Trac |
---|
520 | understands it. |
---|
521 | """ |
---|
522 | self.logger.debug("function email_to_unicode") |
---|
523 | |
---|
524 | results = email.Header.decode_header(message_str) |
---|
525 | |
---|
526 | s = None |
---|
527 | for text,format in results: |
---|
528 | if format: |
---|
529 | try: |
---|
530 | temp = unicode(text, format) |
---|
531 | except UnicodeError, detail: |
---|
532 | # This always works |
---|
533 | # |
---|
534 | temp = unicode(text, 'iso-8859-15') |
---|
535 | except LookupError, detail: |
---|
536 | #text = 'ERROR: Could not find charset: %s, please install' %format |
---|
537 | #temp = unicode(text, 'iso-8859-15') |
---|
538 | temp = message_str |
---|
539 | |
---|
540 | else: |
---|
541 | temp = string.strip(text) |
---|
542 | temp = unicode(text, 'iso-8859-15') |
---|
543 | |
---|
544 | if s: |
---|
545 | s = '%s %s' %(s, temp) |
---|
546 | else: |
---|
547 | s = '%s' %temp |
---|
548 | |
---|
549 | #s = s.encode('utf-8') |
---|
550 | return s |
---|
551 | |
---|
552 | def str_to_dict(self, s): |
---|
553 | """ |
---|
554 | Transfrom a string of the form [<key>=<value>]+ to dict[<key>] = <value> |
---|
555 | """ |
---|
556 | self.logger.debug("function str_to_dict") |
---|
557 | |
---|
558 | fields = string.split(s, self.parameters.subject_field_separator) |
---|
559 | |
---|
560 | result = dict() |
---|
561 | for field in fields: |
---|
562 | try: |
---|
563 | index, value = string.split(field, '=') |
---|
564 | |
---|
565 | # We can not change the description of a ticket via the subject |
---|
566 | # line. The description is the body of the email |
---|
567 | # |
---|
568 | if index.lower() in ['description']: |
---|
569 | continue |
---|
570 | |
---|
571 | if value: |
---|
572 | result[index.lower()] = value |
---|
573 | |
---|
574 | except ValueError: |
---|
575 | pass |
---|
576 | return result |
---|
577 | |
---|
578 | def print_unicode(self,s): |
---|
579 | """ |
---|
580 | This function prints unicode strings if possible else it will quote it |
---|
581 | """ |
---|
582 | try: |
---|
583 | self.logger.debug(s) |
---|
584 | except UnicodeEncodeError, detail: |
---|
585 | self.logger.debug(util.text.unicode_quote(s)) |
---|
586 | |
---|
587 | ########## TRAC ticket functions ########################################################### |
---|
588 | |
---|
589 | def check_permission_participants(self, tkt, action): |
---|
590 | """ |
---|
591 | Check if the mailer is allowed to update the ticket |
---|
592 | """ |
---|
593 | self.logger.debug('function check_permission_participants') |
---|
594 | |
---|
595 | if tkt['reporter'].lower() in [self.author, self.email_addr]: |
---|
596 | self.logger.debug('ALLOW, %s is the ticket reporter' %(self.email_addr)) |
---|
597 | |
---|
598 | return True |
---|
599 | |
---|
600 | perm = PermissionSystem(self.env) |
---|
601 | if perm.check_permission(action, self.author): |
---|
602 | self.logger.debug('ALLOW, %s has trac permission to update the ticket' %(self.author)) |
---|
603 | |
---|
604 | return True |
---|
605 | |
---|
606 | # Is the updater in the CC? |
---|
607 | try: |
---|
608 | cc_list = tkt['cc'].split(',') |
---|
609 | for cc in cc_list: |
---|
610 | if self.email_addr.lower() in cc.strip(): |
---|
611 | self.logger.debug('ALLOW, %s is in the CC' %(self.email_addr)) |
---|
612 | |
---|
613 | return True |
---|
614 | |
---|
615 | except KeyError: |
---|
616 | pass |
---|
617 | |
---|
618 | return False |
---|
619 | |
---|
620 | def check_permission(self, tkt, action): |
---|
621 | """ |
---|
622 | check if the reporter has the right permission for the action: |
---|
623 | - TICKET_CREATE |
---|
624 | - TICKET_MODIFY |
---|
625 | - TICKET_APPEND |
---|
626 | - TICKET_CHGPROP |
---|
627 | |
---|
628 | There are three models: |
---|
629 | - None : no checking at all |
---|
630 | - trac : check the permission via trac permission model |
---|
631 | - email2trac: .... |
---|
632 | """ |
---|
633 | self.logger.debug("function check_permission") |
---|
634 | |
---|
635 | if self.parameters.ticket_permission_system in ['trac']: |
---|
636 | |
---|
637 | perm = PermissionSystem(self.env) |
---|
638 | if perm.check_permission(action, self.author): |
---|
639 | return True |
---|
640 | else: |
---|
641 | return False |
---|
642 | |
---|
643 | elif self.parameters.ticket_permission_system in ['update_restricted_to_participants']: |
---|
644 | return (self.check_permission_participants(tkt, action)) |
---|
645 | |
---|
646 | ## Default is to allow everybody ticket updates and ticket creation |
---|
647 | # |
---|
648 | else: |
---|
649 | return True |
---|
650 | |
---|
651 | |
---|
652 | def update_ticket_fields(self, ticket, user_dict, new=None): |
---|
653 | """ |
---|
654 | This will update the ticket fields. It will check if the |
---|
655 | given fields are known and if the right values are specified |
---|
656 | It will only update the ticket field value: |
---|
657 | - If the field is known |
---|
658 | - If the value supplied is valid for the ticket field. |
---|
659 | If not then there are two options: |
---|
660 | 1) Skip the value (new=None) |
---|
661 | 2) Set default value for field (new=1) |
---|
662 | """ |
---|
663 | self.logger.debug("function update_ticket_fields") |
---|
664 | |
---|
665 | ## Check only permission model on ticket updates |
---|
666 | # |
---|
667 | if not new: |
---|
668 | if self.parameters.ticket_permission_system: |
---|
669 | if not self.check_permission(ticket, 'TICKET_CHGPROP'): |
---|
670 | self.logger.info('Reporter: %s has no permission to change ticket properties' %self.author) |
---|
671 | return False |
---|
672 | |
---|
673 | ## Build a system dictionary from the ticket fields |
---|
674 | # with field as index and option as value |
---|
675 | # |
---|
676 | sys_dict = dict() |
---|
677 | for field in ticket.fields: |
---|
678 | try: |
---|
679 | sys_dict[field['name']] = field['options'] |
---|
680 | |
---|
681 | except KeyError: |
---|
682 | #sys_dict[field['name']] = None |
---|
683 | pass |
---|
684 | |
---|
685 | ## Check user supplied fields an compare them with the |
---|
686 | # system one's |
---|
687 | # |
---|
688 | for field,value in user_dict.items(): |
---|
689 | if self.parameters.debug: |
---|
690 | s = 'user_field\t %s = %s' %(field,value) |
---|
691 | self.print_unicode(s) |
---|
692 | |
---|
693 | ## To prevent mail loop |
---|
694 | # |
---|
695 | if field == 'cc': |
---|
696 | |
---|
697 | cc_list = user_dict['cc'].split(',') |
---|
698 | |
---|
699 | if self.trac_smtp_from in cc_list: |
---|
700 | self.logger.debug('MAIL LOOP: %s is not allowed as CC address' %(self.trac_smtp_from)) |
---|
701 | |
---|
702 | cc_list.remove(self.trac_smtp_from) |
---|
703 | |
---|
704 | value = ','.join(cc_list) |
---|
705 | |
---|
706 | |
---|
707 | ## Check if every value is allowed for this field |
---|
708 | # |
---|
709 | if sys_dict.has_key(field): |
---|
710 | |
---|
711 | if value in sys_dict[field]: |
---|
712 | ticket[field] = value |
---|
713 | else: |
---|
714 | ## Must we set a default if value is not allowed |
---|
715 | # |
---|
716 | if new: |
---|
717 | value = self.get_config('ticket', 'default_%s' %(field) ) |
---|
718 | |
---|
719 | else: |
---|
720 | ## Only set if we have a value |
---|
721 | # |
---|
722 | #if value: |
---|
723 | # ticket[field] = value |
---|
724 | ticket[field] = value |
---|
725 | |
---|
726 | if self.parameters.debug: |
---|
727 | s = 'ticket_field\t %s = %s' %(field, ticket[field]) |
---|
728 | self.print_unicode(s) |
---|
729 | |
---|
730 | def ticket_update(self, m, id, spam): |
---|
731 | """ |
---|
732 | If the current email is a reply to an existing ticket, this function |
---|
733 | will append the contents of this email to that ticket, instead of |
---|
734 | creating a new one. |
---|
735 | """ |
---|
736 | self.logger.debug("function ticket_update") |
---|
737 | |
---|
738 | if not self.parameters.ticket_update: |
---|
739 | self.logger.debug("ticket_update disabled") |
---|
740 | return False |
---|
741 | |
---|
742 | ## Must we update ticket fields |
---|
743 | # |
---|
744 | update_fields = dict() |
---|
745 | try: |
---|
746 | id, keywords = string.split(id, '?') |
---|
747 | |
---|
748 | update_fields = self.str_to_dict(keywords) |
---|
749 | |
---|
750 | ## Strip '#' |
---|
751 | # |
---|
752 | self.id = int(id[1:]) |
---|
753 | |
---|
754 | except ValueError: |
---|
755 | |
---|
756 | ## Strip '#' |
---|
757 | # |
---|
758 | self.id = int(id[1:]) |
---|
759 | |
---|
760 | self.logger.debug("ticket_update id %s" %id) |
---|
761 | |
---|
762 | ## When is the change committed |
---|
763 | # |
---|
764 | if self.VERSION < 0.11: |
---|
765 | when = int(time.time()) |
---|
766 | else: |
---|
767 | when = datetime.now(util.datefmt.utc) |
---|
768 | |
---|
769 | try: |
---|
770 | tkt = Ticket(self.env, self.id, self.db) |
---|
771 | |
---|
772 | except util.TracError, detail: |
---|
773 | |
---|
774 | ## Not a valid ticket |
---|
775 | # |
---|
776 | self.id = None |
---|
777 | return False |
---|
778 | |
---|
779 | ## Check the permission of the reporter |
---|
780 | # |
---|
781 | if self.parameters.ticket_permission_system: |
---|
782 | if not self.check_permission(tkt, 'TICKET_APPEND'): |
---|
783 | self.logger.info('Reporter: %s has no permission to add comments or attachments to tickets' %self.author) |
---|
784 | return False |
---|
785 | |
---|
786 | ## How many changes has this ticket |
---|
787 | # |
---|
788 | # cnum = len(tkt.get_changelog()) |
---|
789 | grouped = TicketModule(self.env).grouped_changelog_entries(tkt, self.db) |
---|
790 | cnum = sum(1 for e in grouped) + 1 |
---|
791 | |
---|
792 | |
---|
793 | ## reopen the ticket if it is was closed |
---|
794 | # We must use the ticket workflow framework |
---|
795 | # |
---|
796 | if self.parameters.email_triggers_workflow and (self.VERSION >= 0.11): |
---|
797 | |
---|
798 | self.logger.debug('Workflow ticket update fields: ') |
---|
799 | |
---|
800 | from trac.ticket.default_workflow import ConfigurableTicketWorkflow |
---|
801 | from trac.test import Mock, MockPerm |
---|
802 | |
---|
803 | req = Mock(authname=self.author, perm=MockPerm(), args={}) |
---|
804 | try: |
---|
805 | workflow = self.parameters['workflow_%s' %tkt['status']] |
---|
806 | except KeyError: |
---|
807 | ## fallback for compability (Will be deprecated) |
---|
808 | # |
---|
809 | if tkt['status'] in ['closed']: |
---|
810 | workflow = self.parameters.workflow |
---|
811 | else: |
---|
812 | workflow = None |
---|
813 | |
---|
814 | controller = ConfigurableTicketWorkflow(self.env) |
---|
815 | #print controller.actions |
---|
816 | #print controller.actions.keys() |
---|
817 | #print controller.get_ticket_actions(req, tkt) |
---|
818 | #print controller.actions[workflow] |
---|
819 | #print controller.actions[workflow]['permissions'] is a list |
---|
820 | |
---|
821 | if workflow: |
---|
822 | |
---|
823 | if self.parameters.ticket_permission_system: |
---|
824 | |
---|
825 | if self.check_permission(tkt, controller.actions[workflow]['permissions'][0]): |
---|
826 | fields = controller.get_ticket_changes(req, tkt, workflow) |
---|
827 | else: |
---|
828 | fields = dict() |
---|
829 | self.logger.info('Reporter: %s has no permission to trigger workflow' %self.author) |
---|
830 | |
---|
831 | else: |
---|
832 | fields = controller.get_ticket_changes(req, tkt, workflow) |
---|
833 | |
---|
834 | for key in fields.keys(): |
---|
835 | self.logger.debug('\t %s : %s' %(key, fields[key])) |
---|
836 | tkt[key] = fields[key] |
---|
837 | |
---|
838 | ## Old pre 0.11 situation |
---|
839 | # |
---|
840 | elif self.parameters.email_triggers_workflow: |
---|
841 | |
---|
842 | self.logger.debug('email triggers workflow pre trac 0.11') |
---|
843 | |
---|
844 | if tkt['status'] in ['closed']: |
---|
845 | tkt['status'] = 'reopened' |
---|
846 | tkt['resolution'] = '' |
---|
847 | |
---|
848 | else: |
---|
849 | self.logger.debug('email triggers workflow disabled') |
---|
850 | |
---|
851 | ## Must we update some ticket fields properties via subject line |
---|
852 | # |
---|
853 | if update_fields: |
---|
854 | self.update_ticket_fields(tkt, update_fields) |
---|
855 | |
---|
856 | message_parts = self.get_message_parts(m) |
---|
857 | message_parts = self.unique_attachment_names(message_parts) |
---|
858 | |
---|
859 | ## Must we update some ticket fields properties via body_text |
---|
860 | # |
---|
861 | if self.properties: |
---|
862 | self.update_ticket_fields(tkt, self.properties) |
---|
863 | |
---|
864 | if self.parameters.email_header: |
---|
865 | message_parts.insert(0, self.email_header_txt(m)) |
---|
866 | |
---|
867 | body_text = self.get_body_text(message_parts) |
---|
868 | |
---|
869 | error_with_attachments = self.attach_attachments(message_parts) |
---|
870 | |
---|
871 | if body_text.strip() or update_fields or self.properties: |
---|
872 | if self.parameters.dry_run: |
---|
873 | print 'DRY_RUN: tkt.save_changes(self.author, body_text, ticket_change_number) ', self.author, cnum |
---|
874 | else: |
---|
875 | if error_with_attachments: |
---|
876 | body_text = '%s\\%s' %(error_with_attachments, body_text) |
---|
877 | self.logger.debug('tkt.save_changes(%s, %d)' %(self.author, cnum)) |
---|
878 | tkt.save_changes(self.author, body_text, when, None, str(cnum)) |
---|
879 | |
---|
880 | |
---|
881 | if not spam: |
---|
882 | self.notify(tkt, False, when) |
---|
883 | |
---|
884 | return True |
---|
885 | |
---|
886 | def set_ticket_fields(self, ticket): |
---|
887 | """ |
---|
888 | set the ticket fields to value specified |
---|
889 | - /etc/email2trac.conf with <prefix>_<field> |
---|
890 | - trac default values, trac.ini |
---|
891 | """ |
---|
892 | self.logger.debug('function set_ticket_fields') |
---|
893 | |
---|
894 | user_dict = dict() |
---|
895 | |
---|
896 | for field in ticket.fields: |
---|
897 | |
---|
898 | name = field['name'] |
---|
899 | |
---|
900 | ## default trac value |
---|
901 | # |
---|
902 | if not field.get('custom'): |
---|
903 | value = self.get_config('ticket', 'default_%s' %(name) ) |
---|
904 | if (name in ['resolution']) and (value in ['fixed']): |
---|
905 | value = None |
---|
906 | else: |
---|
907 | ## Else get the default value for reporter |
---|
908 | # |
---|
909 | value = field.get('value') |
---|
910 | options = field.get('options') |
---|
911 | |
---|
912 | if value and options and (value not in options): |
---|
913 | value = options[int(value)] |
---|
914 | |
---|
915 | if self.parameters.debug: |
---|
916 | s = 'trac[%s] = %s' %(name, value) |
---|
917 | self.print_unicode(s) |
---|
918 | |
---|
919 | ## email2trac.conf settings |
---|
920 | # |
---|
921 | prefix = self.parameters.ticket_prefix |
---|
922 | try: |
---|
923 | value = self.parameters['%s_%s' %(prefix, name)] |
---|
924 | if self.parameters.debug: |
---|
925 | s = 'email2trac[%s] = %s ' %(name, value) |
---|
926 | self.print_unicode(s) |
---|
927 | |
---|
928 | except KeyError, detail: |
---|
929 | pass |
---|
930 | |
---|
931 | if value: |
---|
932 | user_dict[name] = value |
---|
933 | if self.parameters.debug: |
---|
934 | s = 'used %s = %s' %(name, value) |
---|
935 | self.print_unicode(s) |
---|
936 | |
---|
937 | self.update_ticket_fields(ticket, user_dict, new=1) |
---|
938 | |
---|
939 | if 'status' not in user_dict.keys(): |
---|
940 | ticket['status'] = 'new' |
---|
941 | |
---|
942 | |
---|
943 | def ticket_update_by_subject(self, subject): |
---|
944 | """ |
---|
945 | This list of Re: prefixes is probably incomplete. Taken from |
---|
946 | wikipedia. Here is how the subject is matched |
---|
947 | - Re: <subject> |
---|
948 | - Re: (<Mail list label>:)+ <subject> |
---|
949 | |
---|
950 | So we must have the last column |
---|
951 | """ |
---|
952 | self.logger.debug('function ticket_update_by_subject') |
---|
953 | |
---|
954 | matched_id = None |
---|
955 | if self.parameters.ticket_update and self.parameters.ticket_update_by_subject: |
---|
956 | |
---|
957 | SUBJECT_RE = re.compile(r'^(?:(?:RE|AW|VS|SV|FW|FWD):\s*)+(.*)', re.IGNORECASE) |
---|
958 | result = SUBJECT_RE.search(subject) |
---|
959 | |
---|
960 | if result: |
---|
961 | ## This is a reply |
---|
962 | # |
---|
963 | orig_subject = result.group(1) |
---|
964 | |
---|
965 | self.logger.debug('subject search string: %s' %(orig_subject)) |
---|
966 | |
---|
967 | cursor = self.db.cursor() |
---|
968 | summaries = [orig_subject, '%%: %s' % orig_subject] |
---|
969 | |
---|
970 | ## Convert days to seconds |
---|
971 | # |
---|
972 | lookback = int(time.mktime(time.gmtime())) - \ |
---|
973 | self.parameters.ticket_update_by_subject_lookback * 24 * 3600 |
---|
974 | |
---|
975 | |
---|
976 | for summary in summaries: |
---|
977 | self.logger.debug('Looking for summary matching: "%s"' % summary) |
---|
978 | |
---|
979 | sql = """SELECT id FROM ticket |
---|
980 | WHERE changetime >= %s AND summary LIKE %s |
---|
981 | ORDER BY changetime DESC""" |
---|
982 | cursor.execute(sql, [lookback, summary.strip()]) |
---|
983 | |
---|
984 | for row in cursor: |
---|
985 | (matched_id,) = row |
---|
986 | |
---|
987 | self.logger.debug('Found matching ticket id: %d' % matched_id) |
---|
988 | |
---|
989 | break |
---|
990 | |
---|
991 | if matched_id: |
---|
992 | matched_id = '#%d' % matched_id |
---|
993 | return (matched_id, orig_subject) |
---|
994 | |
---|
995 | subject = orig_subject |
---|
996 | |
---|
997 | return (matched_id, subject) |
---|
998 | |
---|
999 | |
---|
1000 | def new_ticket(self, msg, subject, spam, set_fields = None): |
---|
1001 | """ |
---|
1002 | Create a new ticket |
---|
1003 | """ |
---|
1004 | self.logger.debug('function new_ticket') |
---|
1005 | |
---|
1006 | tkt = Ticket(self.env) |
---|
1007 | |
---|
1008 | self.set_reply_fields(tkt, msg) |
---|
1009 | |
---|
1010 | self.set_ticket_fields(tkt) |
---|
1011 | |
---|
1012 | ## Check the permission of the reporter |
---|
1013 | # |
---|
1014 | if self.parameters.ticket_permission_system: |
---|
1015 | if not self.check_permission(tkt, 'TICKET_CREATE'): |
---|
1016 | self.logger.info('Reporter: %s has no permission to create tickets' %self.author) |
---|
1017 | return False |
---|
1018 | |
---|
1019 | ## Old style setting for component, will be removed |
---|
1020 | # |
---|
1021 | if spam: |
---|
1022 | tkt['component'] = 'Spam' |
---|
1023 | |
---|
1024 | elif self.parameters.has_key('component'): |
---|
1025 | tkt['component'] = self.parameters['component'] |
---|
1026 | |
---|
1027 | if not msg['Subject']: |
---|
1028 | tkt['summary'] = u'(No subject)' |
---|
1029 | else: |
---|
1030 | tkt['summary'] = subject |
---|
1031 | |
---|
1032 | |
---|
1033 | if set_fields: |
---|
1034 | rest, keywords = string.split(set_fields, '?') |
---|
1035 | |
---|
1036 | if keywords: |
---|
1037 | update_fields = self.str_to_dict(keywords) |
---|
1038 | self.update_ticket_fields(tkt, update_fields) |
---|
1039 | |
---|
1040 | |
---|
1041 | message_parts = self.get_message_parts(msg) |
---|
1042 | |
---|
1043 | ## Must we update some ticket fields properties via body_text |
---|
1044 | # |
---|
1045 | if self.properties: |
---|
1046 | self.update_ticket_fields(tkt, self.properties) |
---|
1047 | |
---|
1048 | message_parts = self.unique_attachment_names(message_parts) |
---|
1049 | |
---|
1050 | ## produce e-mail like header |
---|
1051 | # |
---|
1052 | head = '' |
---|
1053 | if self.parameters.email_header: |
---|
1054 | head = self.email_header_txt(msg) |
---|
1055 | message_parts.insert(0, head) |
---|
1056 | |
---|
1057 | body_text = self.get_body_text(message_parts) |
---|
1058 | |
---|
1059 | tkt['description'] = body_text |
---|
1060 | |
---|
1061 | ## When is the change committed |
---|
1062 | # |
---|
1063 | if self.VERSION < 0.11: |
---|
1064 | when = int(time.time()) |
---|
1065 | else: |
---|
1066 | when = datetime.now(util.datefmt.utc) |
---|
1067 | |
---|
1068 | if self.parameters.dry_run: |
---|
1069 | print 'DRY_RUN: tkt.insert()' |
---|
1070 | else: |
---|
1071 | self.id = tkt.insert() |
---|
1072 | |
---|
1073 | changed = False |
---|
1074 | comment = '' |
---|
1075 | |
---|
1076 | ## some routines in trac are dependend on ticket id |
---|
1077 | # like alternate notify template |
---|
1078 | # |
---|
1079 | if self.parameters.alternate_notify_template: |
---|
1080 | tkt['id'] = self.id |
---|
1081 | changed = True |
---|
1082 | |
---|
1083 | ## Rewrite the description if we have mailto enabled |
---|
1084 | # |
---|
1085 | if self.parameters.mailto_link: |
---|
1086 | changed = True |
---|
1087 | comment = u'\nadded mailto line\n' |
---|
1088 | mailto = self.html_mailto_link( m['Subject']) |
---|
1089 | |
---|
1090 | tkt['description'] = u'%s\r\n%s%s\r\n' \ |
---|
1091 | %(head, mailto, body_text) |
---|
1092 | |
---|
1093 | ## Save the attachments to the ticket |
---|
1094 | # |
---|
1095 | error_with_attachments = self.attach_attachments(message_parts) |
---|
1096 | |
---|
1097 | if error_with_attachments: |
---|
1098 | changed = True |
---|
1099 | comment = '%s\n%s\n' %(comment, error_with_attachments) |
---|
1100 | |
---|
1101 | if changed: |
---|
1102 | if self.parameters.dry_run: |
---|
1103 | print 'DRY_RUN: tkt.save_changes(%s, comment) real reporter = %s' %( tkt['reporter'], self.author) |
---|
1104 | else: |
---|
1105 | tkt.save_changes(tkt['reporter'], comment) |
---|
1106 | #print tkt.get_changelog(self.db, when) |
---|
1107 | |
---|
1108 | if not spam: |
---|
1109 | self.notify(tkt, True) |
---|
1110 | |
---|
1111 | |
---|
1112 | def attach_attachments(self, message_parts, update=False): |
---|
1113 | ''' |
---|
1114 | save any attachments as files in the ticket's directory |
---|
1115 | ''' |
---|
1116 | self.logger.debug('function attach_attachments()') |
---|
1117 | |
---|
1118 | if self.parameters.dry_run: |
---|
1119 | print "DRY_RUN: no attachments attached to tickets" |
---|
1120 | return '' |
---|
1121 | |
---|
1122 | count = 0 |
---|
1123 | |
---|
1124 | ## Get Maxium attachment size |
---|
1125 | # |
---|
1126 | max_size = int(self.get_config('attachment', 'max_size')) |
---|
1127 | status = None |
---|
1128 | |
---|
1129 | for item in message_parts: |
---|
1130 | ## Skip body parts |
---|
1131 | # |
---|
1132 | if not isinstance(item, tuple): |
---|
1133 | continue |
---|
1134 | |
---|
1135 | (original, filename, part) = item |
---|
1136 | |
---|
1137 | ## We have to determine the size so we use this temporary solution. we must escape it |
---|
1138 | # else we get UnicodeErrors. |
---|
1139 | # |
---|
1140 | path, fd = util.create_unique_file(os.path.join(self.parameters.tmpdir, util.text.unicode_quote(filename))) |
---|
1141 | text = part.get_payload(decode=1) |
---|
1142 | if not text: |
---|
1143 | text = '(None)' |
---|
1144 | fd.write(text) |
---|
1145 | fd.close() |
---|
1146 | |
---|
1147 | ## get the file_size |
---|
1148 | # |
---|
1149 | stats = os.lstat(path) |
---|
1150 | file_size = stats[ST_SIZE] |
---|
1151 | |
---|
1152 | ## Check if the attachment size is allowed |
---|
1153 | # |
---|
1154 | if (max_size != -1) and (file_size > max_size): |
---|
1155 | status = '%s\nFile %s is larger then allowed attachment size (%d > %d)\n\n' \ |
---|
1156 | %(status, original, file_size, max_size) |
---|
1157 | |
---|
1158 | os.unlink(path) |
---|
1159 | continue |
---|
1160 | else: |
---|
1161 | count = count + 1 |
---|
1162 | |
---|
1163 | ## Insert the attachment |
---|
1164 | # |
---|
1165 | fd = open(path, 'rb') |
---|
1166 | if self.system == 'discussion': |
---|
1167 | att = attachment.Attachment(self.env, 'discussion', 'topic/%s' |
---|
1168 | % (self.id,)) |
---|
1169 | else: |
---|
1170 | self.logger.debug('Attach %s to ticket %d' %(util.text.unicode_quote(filename), self.id)) |
---|
1171 | att = attachment.Attachment(self.env, 'ticket', self.id) |
---|
1172 | |
---|
1173 | ## This will break the ticket_update system, the body_text is vaporized |
---|
1174 | # ;-( |
---|
1175 | # |
---|
1176 | if not update: |
---|
1177 | att.author = self.author |
---|
1178 | att.description = self.email_to_unicode('Added by email2trac') |
---|
1179 | |
---|
1180 | try: |
---|
1181 | self.logger.debug('Insert atachment') |
---|
1182 | att.insert(filename, fd, file_size) |
---|
1183 | except OSError, detail: |
---|
1184 | self.logger.info('%s\nFilename %s could not be saved, problem: %s' %(status, filename, detail)) |
---|
1185 | status = '%s\nFilename %s could not be saved, problem: %s' %(status, filename, detail) |
---|
1186 | |
---|
1187 | ## Remove the created temporary filename |
---|
1188 | # |
---|
1189 | fd.close() |
---|
1190 | os.unlink(path) |
---|
1191 | |
---|
1192 | ## return error |
---|
1193 | # |
---|
1194 | return status |
---|
1195 | |
---|
1196 | ########## Fullblog functions ################################################# |
---|
1197 | |
---|
1198 | def blog(self, id): |
---|
1199 | """ |
---|
1200 | The blog create/update function |
---|
1201 | """ |
---|
1202 | ## import the modules |
---|
1203 | # |
---|
1204 | from tracfullblog.core import FullBlogCore |
---|
1205 | from tracfullblog.model import BlogPost, BlogComment |
---|
1206 | from trac.test import Mock, MockPerm |
---|
1207 | |
---|
1208 | ## instantiate blog core |
---|
1209 | # |
---|
1210 | blog = FullBlogCore(self.env) |
---|
1211 | req = Mock(authname='anonymous', perm=MockPerm(), args={}) |
---|
1212 | |
---|
1213 | if id: |
---|
1214 | |
---|
1215 | ## update blog |
---|
1216 | # |
---|
1217 | comment = BlogComment(self.env, id) |
---|
1218 | comment.author = self.author |
---|
1219 | |
---|
1220 | message_parts = self.get_message_parts(m) |
---|
1221 | comment.comment = self.get_body_text(message_parts) |
---|
1222 | |
---|
1223 | blog.create_comment(req, comment) |
---|
1224 | |
---|
1225 | else: |
---|
1226 | ## create blog |
---|
1227 | # |
---|
1228 | import time |
---|
1229 | post = BlogPost(self.env, 'blog_'+time.strftime("%Y%m%d%H%M%S", time.gmtime())) |
---|
1230 | |
---|
1231 | #post = BlogPost(self.env, blog._get_default_postname(self.env)) |
---|
1232 | |
---|
1233 | post.author = self.author |
---|
1234 | post.title = self.email_to_unicode(m['Subject']) |
---|
1235 | |
---|
1236 | message_parts = self.get_message_parts(m) |
---|
1237 | post.body = self.get_body_text(message_parts) |
---|
1238 | |
---|
1239 | blog.create_post(req, post, self.author, u'Created by email2trac', False) |
---|
1240 | |
---|
1241 | |
---|
1242 | ########## Discussion functions ############################################## |
---|
1243 | |
---|
1244 | def discussion_topic(self, content, subject): |
---|
1245 | |
---|
1246 | ## Import modules. |
---|
1247 | # |
---|
1248 | from tracdiscussion.api import DiscussionApi |
---|
1249 | from trac.util.datefmt import to_timestamp, utc |
---|
1250 | |
---|
1251 | self.logger.debug('Creating a new topic in forum:', self.id) |
---|
1252 | |
---|
1253 | ## Get dissussion API component. |
---|
1254 | # |
---|
1255 | api = self.env[DiscussionApi] |
---|
1256 | context = self._create_context(content, subject) |
---|
1257 | |
---|
1258 | ## Get forum for new topic. |
---|
1259 | # |
---|
1260 | forum = api.get_forum(context, self.id) |
---|
1261 | |
---|
1262 | if not forum: |
---|
1263 | self.logger.error("ERROR: Replied forum doesn't exist") |
---|
1264 | |
---|
1265 | ## Prepare topic. |
---|
1266 | # |
---|
1267 | topic = {'forum' : forum['id'], |
---|
1268 | 'subject' : context.subject, |
---|
1269 | 'time': to_timestamp(datetime.now(utc)), |
---|
1270 | 'author' : self.author, |
---|
1271 | 'subscribers' : [self.email_addr], |
---|
1272 | 'body' : self.get_body_text(context.content_parts)} |
---|
1273 | |
---|
1274 | ## Add topic to DB and commit it. |
---|
1275 | # |
---|
1276 | self._add_topic(api, context, topic) |
---|
1277 | self.db.commit() |
---|
1278 | |
---|
1279 | def discussion_topic_reply(self, content, subject): |
---|
1280 | |
---|
1281 | ## Import modules. |
---|
1282 | # |
---|
1283 | from tracdiscussion.api import DiscussionApi |
---|
1284 | from trac.util.datefmt import to_timestamp, utc |
---|
1285 | |
---|
1286 | self.logger.debug('Replying to discussion topic', self.id) |
---|
1287 | |
---|
1288 | ## Get dissussion API component. |
---|
1289 | # |
---|
1290 | api = self.env[DiscussionApi] |
---|
1291 | context = self._create_context(content, subject) |
---|
1292 | |
---|
1293 | ## Get replied topic. |
---|
1294 | # |
---|
1295 | topic = api.get_topic(context, self.id) |
---|
1296 | |
---|
1297 | if not topic: |
---|
1298 | self.logger.error("ERROR: Replied topic doesn't exist") |
---|
1299 | |
---|
1300 | ## Prepare message. |
---|
1301 | # |
---|
1302 | message = {'forum' : topic['forum'], |
---|
1303 | 'topic' : topic['id'], |
---|
1304 | 'replyto' : -1, |
---|
1305 | 'time' : to_timestamp(datetime.now(utc)), |
---|
1306 | 'author' : self.author, |
---|
1307 | 'body' : self.get_body_text(context.content_parts)} |
---|
1308 | |
---|
1309 | ## Add message to DB and commit it. |
---|
1310 | # |
---|
1311 | self._add_message(api, context, message) |
---|
1312 | self.db.commit() |
---|
1313 | |
---|
1314 | def discussion_message_reply(self, content, subject): |
---|
1315 | |
---|
1316 | ## Import modules. |
---|
1317 | # |
---|
1318 | from tracdiscussion.api import DiscussionApi |
---|
1319 | from trac.util.datefmt import to_timestamp, utc |
---|
1320 | |
---|
1321 | self.logger.debug('Replying to discussion message', self.id) |
---|
1322 | |
---|
1323 | ## Get dissussion API component. |
---|
1324 | # |
---|
1325 | api = self.env[DiscussionApi] |
---|
1326 | context = self._create_context(content, subject) |
---|
1327 | |
---|
1328 | ## Get replied message. |
---|
1329 | # |
---|
1330 | message = api.get_message(context, self.id) |
---|
1331 | |
---|
1332 | if not message: |
---|
1333 | self.logger.error("ERROR: Replied message doesn't exist") |
---|
1334 | |
---|
1335 | ## Prepare message. |
---|
1336 | # |
---|
1337 | message = {'forum' : message['forum'], |
---|
1338 | 'topic' : message['topic'], |
---|
1339 | 'replyto' : message['id'], |
---|
1340 | 'time' : to_timestamp(datetime.now(utc)), |
---|
1341 | 'author' : self.author, |
---|
1342 | 'body' : self.get_body_text(context.content_parts)} |
---|
1343 | |
---|
1344 | ## Add message to DB and commit it. |
---|
1345 | # |
---|
1346 | self._add_message(api, context, message) |
---|
1347 | self.db.commit() |
---|
1348 | |
---|
1349 | def _create_context(self, content, subject): |
---|
1350 | |
---|
1351 | ## Import modules. |
---|
1352 | # |
---|
1353 | from trac.mimeview import Context |
---|
1354 | from trac.web.api import Request |
---|
1355 | from trac.perm import PermissionCache |
---|
1356 | |
---|
1357 | ## TODO: Read server base URL from config. |
---|
1358 | # Create request object to mockup context creation. |
---|
1359 | # |
---|
1360 | environ = {'SERVER_PORT' : 80, |
---|
1361 | 'SERVER_NAME' : 'test', |
---|
1362 | 'REQUEST_METHOD' : 'POST', |
---|
1363 | 'wsgi.url_scheme' : 'http', |
---|
1364 | 'wsgi.input' : sys.stdin} |
---|
1365 | chrome = {'links': {}, |
---|
1366 | 'scripts': [], |
---|
1367 | 'ctxtnav': [], |
---|
1368 | 'warnings': [], |
---|
1369 | 'notices': []} |
---|
1370 | |
---|
1371 | if self.env.base_url_for_redirect: |
---|
1372 | environ['trac.base_url'] = self.env.base_url |
---|
1373 | |
---|
1374 | req = Request(environ, None) |
---|
1375 | req.chrome = chrome |
---|
1376 | req.tz = 'missing' |
---|
1377 | req.authname = self.author |
---|
1378 | req.perm = PermissionCache(self.env, self.author) |
---|
1379 | req.locale = None |
---|
1380 | |
---|
1381 | ## Create and return context. |
---|
1382 | # |
---|
1383 | context = Context.from_request(req) |
---|
1384 | context.realm = 'discussion-email2trac' |
---|
1385 | context.cursor = self.db.cursor() |
---|
1386 | context.content = content |
---|
1387 | context.subject = subject |
---|
1388 | |
---|
1389 | ## Read content parts from content. |
---|
1390 | # |
---|
1391 | context.content_parts = self.get_message_parts(content) |
---|
1392 | context.content_parts = self.unique_attachment_names( |
---|
1393 | context.content_parts) |
---|
1394 | |
---|
1395 | return context |
---|
1396 | |
---|
1397 | def _add_topic(self, api, context, topic): |
---|
1398 | context.req.perm.assert_permission('DISCUSSION_APPEND') |
---|
1399 | |
---|
1400 | ## Filter topic. |
---|
1401 | # |
---|
1402 | for discussion_filter in api.discussion_filters: |
---|
1403 | accept, topic_or_error = discussion_filter.filter_topic( |
---|
1404 | context, topic) |
---|
1405 | if accept: |
---|
1406 | topic = topic_or_error |
---|
1407 | else: |
---|
1408 | raise TracError(topic_or_error) |
---|
1409 | |
---|
1410 | ## Add a new topic. |
---|
1411 | # |
---|
1412 | api.add_topic(context, topic) |
---|
1413 | |
---|
1414 | ## Get inserted topic with new ID. |
---|
1415 | # |
---|
1416 | topic = api.get_topic_by_time(context, topic['time']) |
---|
1417 | |
---|
1418 | ## Attach attachments. |
---|
1419 | # |
---|
1420 | self.id = topic['id'] |
---|
1421 | self.attach_attachments(context.content_parts, True) |
---|
1422 | |
---|
1423 | ## Notify change listeners. |
---|
1424 | # |
---|
1425 | for listener in api.topic_change_listeners: |
---|
1426 | listener.topic_created(context, topic) |
---|
1427 | |
---|
1428 | def _add_message(self, api, context, message): |
---|
1429 | context.req.perm.assert_permission('DISCUSSION_APPEND') |
---|
1430 | |
---|
1431 | ## Filter message. |
---|
1432 | # |
---|
1433 | for discussion_filter in api.discussion_filters: |
---|
1434 | accept, message_or_error = discussion_filter.filter_message( |
---|
1435 | context, message) |
---|
1436 | if accept: |
---|
1437 | message = message_or_error |
---|
1438 | else: |
---|
1439 | raise TracError(message_or_error) |
---|
1440 | |
---|
1441 | ## Add message. |
---|
1442 | # |
---|
1443 | api.add_message(context, message) |
---|
1444 | |
---|
1445 | ## Get inserted message with new ID. |
---|
1446 | # |
---|
1447 | message = api.get_message_by_time(context, message['time']) |
---|
1448 | |
---|
1449 | ## Attach attachments. |
---|
1450 | # |
---|
1451 | self.id = message['topic'] |
---|
1452 | self.attach_attachments(context.content_parts, True) |
---|
1453 | |
---|
1454 | ## Notify change listeners. |
---|
1455 | # |
---|
1456 | for listener in api.message_change_listeners: |
---|
1457 | listener.message_created(context, message) |
---|
1458 | |
---|
1459 | ########## MAIN function ###################################################### |
---|
1460 | |
---|
1461 | def parse(self, fp): |
---|
1462 | """ |
---|
1463 | """ |
---|
1464 | self.logger.debug('Main function parse') |
---|
1465 | global m |
---|
1466 | |
---|
1467 | m = email.message_from_file(fp) |
---|
1468 | |
---|
1469 | if not m: |
---|
1470 | self.logger.debug('This is not a valid email message format') |
---|
1471 | return |
---|
1472 | |
---|
1473 | ## Work around lack of header folding in Python; see http://bugs.python.org/issue4696 |
---|
1474 | # |
---|
1475 | try: |
---|
1476 | m.replace_header('Subject', m['Subject'].replace('\r', '').replace('\n', '')) |
---|
1477 | except AttributeError, detail: |
---|
1478 | pass |
---|
1479 | |
---|
1480 | if self.parameters.debug: # save the entire e-mail message text |
---|
1481 | self.save_email_for_debug(m, True) |
---|
1482 | |
---|
1483 | self.db = self.env.get_db_cnx() |
---|
1484 | self.get_sender_info(m) |
---|
1485 | |
---|
1486 | if not self.email_header_acl('white_list', self.email_addr, True): |
---|
1487 | self.logger.info('Message rejected : %s not in white list' %(self.email_addr)) |
---|
1488 | return False |
---|
1489 | |
---|
1490 | if self.email_header_acl('black_list', self.email_addr, False): |
---|
1491 | self.logger.info('Message rejected : %s in black list' %(self.email_addr)) |
---|
1492 | return False |
---|
1493 | |
---|
1494 | if not self.email_header_acl('recipient_list', self.to_email_addr, True): |
---|
1495 | self.logger.info('Message rejected : %s not in recipient list' %(self.to_email_addr)) |
---|
1496 | return False |
---|
1497 | |
---|
1498 | ## If spam drop the message |
---|
1499 | # |
---|
1500 | if self.spam(m) == 'drop': |
---|
1501 | return False |
---|
1502 | |
---|
1503 | elif self.spam(m) == 'spam': |
---|
1504 | spam_msg = True |
---|
1505 | else: |
---|
1506 | spam_msg = False |
---|
1507 | |
---|
1508 | if not m['Subject']: |
---|
1509 | subject = 'No Subject' |
---|
1510 | else: |
---|
1511 | subject = self.email_to_unicode(m['Subject']) |
---|
1512 | |
---|
1513 | self.logger.debug('subject: %s' %subject) |
---|
1514 | |
---|
1515 | ## [hic] #1529: Re: LRZ |
---|
1516 | # [hic] #1529?owner=bas,priority=medium: Re: LRZ |
---|
1517 | # |
---|
1518 | ticket_regex = r''' |
---|
1519 | (?P<new_fields>[#][?].*) |
---|
1520 | |(?P<reply>(?P<id>[#][\d]+)(?P<fields>\?.*)?:) |
---|
1521 | ''' |
---|
1522 | ## Check if FullBlogPlugin is installed |
---|
1523 | # |
---|
1524 | blog_enabled = None |
---|
1525 | blog_regex = '' |
---|
1526 | if self.get_config('components', 'tracfullblog.*') in ['enabled']: |
---|
1527 | self.logger.debug('Trac BLOG support enabled') |
---|
1528 | blog_enabled = True |
---|
1529 | blog_regex = '''|(?P<blog>blog:(?P<blog_id>\w*))''' |
---|
1530 | |
---|
1531 | |
---|
1532 | ## Check if DiscussionPlugin is installed |
---|
1533 | # |
---|
1534 | discussion_enabled = None |
---|
1535 | discussion_regex = '' |
---|
1536 | if self.get_config('components', 'tracdiscussion.api.discussionapi') in ['enabled']: |
---|
1537 | self.logger.debug('Trac Discussion support enabled') |
---|
1538 | discussion_enabled = True |
---|
1539 | discussion_regex = r''' |
---|
1540 | |(?P<forum>Forum[ ][#](?P<forum_id>\d+)[ ]-[ ]?) |
---|
1541 | |(?P<topic>Topic[ ][#](?P<topic_id>\d+)[ ]-[ ]?) |
---|
1542 | |(?P<message>Message[ ][#](?P<message_id>\d+)[ ]-[ ]?) |
---|
1543 | ''' |
---|
1544 | |
---|
1545 | |
---|
1546 | regex_str = ticket_regex + blog_regex + discussion_regex |
---|
1547 | SYSTEM_RE = re.compile(regex_str, re.VERBOSE) |
---|
1548 | |
---|
1549 | ## Find out if this is a ticket, a blog or a discussion |
---|
1550 | # |
---|
1551 | result = SYSTEM_RE.search(subject) |
---|
1552 | |
---|
1553 | if result: |
---|
1554 | ## update ticket + fields |
---|
1555 | # |
---|
1556 | if result.group('reply'): |
---|
1557 | self.system = 'ticket' |
---|
1558 | |
---|
1559 | ## Skip the last ':' character |
---|
1560 | # |
---|
1561 | if not self.ticket_update(m, result.group('reply')[:-1], spam_msg): |
---|
1562 | self.new_ticket(m, subject, spam_msg) |
---|
1563 | |
---|
1564 | ## New ticket + fields |
---|
1565 | # |
---|
1566 | elif result.group('new_fields'): |
---|
1567 | self.system = 'ticket' |
---|
1568 | self.new_ticket(m, subject[:result.start('new_fields')], spam_msg, result.group('new_fields')) |
---|
1569 | |
---|
1570 | if blog_enabled: |
---|
1571 | if result.group('blog'): |
---|
1572 | self.system = 'blog' |
---|
1573 | self.blog(result.group('blog_id')) |
---|
1574 | |
---|
1575 | if discussion_enabled: |
---|
1576 | ## New topic. |
---|
1577 | # |
---|
1578 | if result.group('forum'): |
---|
1579 | self.system = 'discussion' |
---|
1580 | self.id = int(result.group('forum_id')) |
---|
1581 | self.discussion_topic(m, subject[result.end('forum'):]) |
---|
1582 | |
---|
1583 | ## Reply to topic. |
---|
1584 | # |
---|
1585 | elif result.group('topic'): |
---|
1586 | self.system = 'discussion' |
---|
1587 | self.id = int(result.group('topic_id')) |
---|
1588 | self.discussion_topic_reply(m, subject[result.end('topic'):]) |
---|
1589 | |
---|
1590 | ## Reply to topic message. |
---|
1591 | # |
---|
1592 | elif result.group('message'): |
---|
1593 | self.system = 'discussion' |
---|
1594 | self.id = int(result.group('message_id')) |
---|
1595 | self.discussion_message_reply(m, subject[result.end('message'):]) |
---|
1596 | |
---|
1597 | else: |
---|
1598 | self.system = 'ticket' |
---|
1599 | (matched_id, subject) = self.ticket_update_by_subject(subject) |
---|
1600 | if matched_id: |
---|
1601 | if not self.ticket_update(m, matched_id, spam_msg): |
---|
1602 | self.new_ticket(m, subject, spam_msg) |
---|
1603 | else: |
---|
1604 | ## No update by subject, so just create a new ticket |
---|
1605 | # |
---|
1606 | self.new_ticket(m, subject, spam_msg) |
---|
1607 | |
---|
1608 | |
---|
1609 | ########## BODY TEXT functions ########################################################### |
---|
1610 | |
---|
1611 | def strip_signature(self, text): |
---|
1612 | """ |
---|
1613 | Strip signature from message, inspired by Mailman software |
---|
1614 | """ |
---|
1615 | self.logger.debug('function strip_signature') |
---|
1616 | |
---|
1617 | body = [] |
---|
1618 | for line in text.splitlines(): |
---|
1619 | if line == '-- ': |
---|
1620 | break |
---|
1621 | body.append(line) |
---|
1622 | |
---|
1623 | return ('\n'.join(body)) |
---|
1624 | |
---|
1625 | def reflow(self, text, delsp = 0): |
---|
1626 | """ |
---|
1627 | Reflow the message based on the format="flowed" specification (RFC 3676) |
---|
1628 | """ |
---|
1629 | flowedlines = [] |
---|
1630 | quotelevel = 0 |
---|
1631 | prevflowed = 0 |
---|
1632 | |
---|
1633 | for line in text.splitlines(): |
---|
1634 | from re import match |
---|
1635 | |
---|
1636 | ## Figure out the quote level and the content of the current line |
---|
1637 | # |
---|
1638 | m = match('(>*)( ?)(.*)', line) |
---|
1639 | linequotelevel = len(m.group(1)) |
---|
1640 | line = m.group(3) |
---|
1641 | |
---|
1642 | ## Determine whether this line is flowed |
---|
1643 | # |
---|
1644 | if line and line != '-- ' and line[-1] == ' ': |
---|
1645 | flowed = 1 |
---|
1646 | else: |
---|
1647 | flowed = 0 |
---|
1648 | |
---|
1649 | if flowed and delsp and line and line[-1] == ' ': |
---|
1650 | line = line[:-1] |
---|
1651 | |
---|
1652 | ## If the previous line is flowed, append this line to it |
---|
1653 | # |
---|
1654 | if prevflowed and line != '-- ' and linequotelevel == quotelevel: |
---|
1655 | flowedlines[-1] += line |
---|
1656 | |
---|
1657 | ## Otherwise, start a new line |
---|
1658 | # |
---|
1659 | else: |
---|
1660 | flowedlines.append('>' * linequotelevel + line) |
---|
1661 | |
---|
1662 | prevflowed = flowed |
---|
1663 | |
---|
1664 | |
---|
1665 | return '\n'.join(flowedlines) |
---|
1666 | |
---|
1667 | def strip_quotes(self, text): |
---|
1668 | """ |
---|
1669 | Strip quotes from message by Nicolas Mendoza |
---|
1670 | """ |
---|
1671 | self.logger.debug('function strip_quotes') |
---|
1672 | |
---|
1673 | body = [] |
---|
1674 | for line in text.splitlines(): |
---|
1675 | try: |
---|
1676 | |
---|
1677 | if line.startswith(self.parameters.email_quote): |
---|
1678 | continue |
---|
1679 | |
---|
1680 | except UnicodeDecodeError: |
---|
1681 | |
---|
1682 | tmp_line = self.email_to_unicode(line) |
---|
1683 | if tmp_line.startswith(self.parameters.email_quote): |
---|
1684 | continue |
---|
1685 | |
---|
1686 | body.append(line) |
---|
1687 | |
---|
1688 | return ('\n'.join(body)) |
---|
1689 | |
---|
1690 | def inline_properties(self, text): |
---|
1691 | """ |
---|
1692 | Parse text if we use inline keywords to set ticket fields |
---|
1693 | """ |
---|
1694 | self.logger.debug('function inline_properties') |
---|
1695 | |
---|
1696 | properties = dict() |
---|
1697 | body = list() |
---|
1698 | |
---|
1699 | INLINE_EXP = re.compile('\s*[@]\s*(\w+)\s*:(.*)$') |
---|
1700 | |
---|
1701 | for line in text.splitlines(): |
---|
1702 | match = INLINE_EXP.match(line) |
---|
1703 | if match: |
---|
1704 | keyword, value = match.groups() |
---|
1705 | self.properties[keyword] = value.strip() |
---|
1706 | |
---|
1707 | self.logger.debug('inline properties: %s : %s' %(keyword,value)) |
---|
1708 | |
---|
1709 | else: |
---|
1710 | body.append(line) |
---|
1711 | |
---|
1712 | return '\n'.join(body) |
---|
1713 | |
---|
1714 | |
---|
1715 | def wrap_text(self, text, replace_whitespace = False): |
---|
1716 | """ |
---|
1717 | Will break a lines longer then given length into several small |
---|
1718 | lines of size given length |
---|
1719 | """ |
---|
1720 | import textwrap |
---|
1721 | |
---|
1722 | LINESEPARATOR = '\n' |
---|
1723 | reformat = '' |
---|
1724 | |
---|
1725 | for s in text.split(LINESEPARATOR): |
---|
1726 | tmp = textwrap.fill(s, self.parameters.use_textwrap) |
---|
1727 | if tmp: |
---|
1728 | reformat = '%s\n%s' %(reformat,tmp) |
---|
1729 | else: |
---|
1730 | reformat = '%s\n' %reformat |
---|
1731 | |
---|
1732 | return reformat |
---|
1733 | |
---|
1734 | # Python2.4 and higher |
---|
1735 | # |
---|
1736 | #return LINESEPARATOR.join(textwrap.fill(s,width) for s in str.split(LINESEPARATOR)) |
---|
1737 | # |
---|
1738 | |
---|
1739 | ########## EMAIL attachements functions ########################################################### |
---|
1740 | |
---|
1741 | def inline_part(self, part): |
---|
1742 | """ |
---|
1743 | """ |
---|
1744 | self.logger.debug('function inline_part()') |
---|
1745 | |
---|
1746 | return part.get_param('inline', None, 'Content-Disposition') == '' or not part.has_key('Content-Disposition') |
---|
1747 | |
---|
1748 | def get_message_parts(self, msg): |
---|
1749 | """ |
---|
1750 | parses the email message and returns a list of body parts and attachments |
---|
1751 | body parts are returned as strings, attachments are returned as tuples of (filename, Message object) |
---|
1752 | """ |
---|
1753 | self.logger.debug('function get_message_parts()') |
---|
1754 | |
---|
1755 | message_parts = list() |
---|
1756 | |
---|
1757 | ALTERNATIVE_MULTIPART = False |
---|
1758 | |
---|
1759 | for part in msg.walk(): |
---|
1760 | content_maintype = part.get_content_maintype() |
---|
1761 | content_type = part.get_content_type() |
---|
1762 | |
---|
1763 | self.logger.debug('Message part: Main-Type: %s' % content_maintype) |
---|
1764 | self.logger.debug('Message part: Content-Type: %s' % content_type) |
---|
1765 | |
---|
1766 | ## Check content type |
---|
1767 | # |
---|
1768 | if content_type in self.STRIP_CONTENT_TYPES: |
---|
1769 | self.logger.debug("A %s attachment named '%s' was skipped" %(content_type, part.get_filename())) |
---|
1770 | continue |
---|
1771 | |
---|
1772 | ## Catch some mulitpart execptions |
---|
1773 | # |
---|
1774 | if content_type == 'multipart/alternative': |
---|
1775 | ALTERNATIVE_MULTIPART = True |
---|
1776 | continue |
---|
1777 | |
---|
1778 | ## Skip multipart containers |
---|
1779 | # |
---|
1780 | if content_maintype == 'multipart': |
---|
1781 | self.logger.debug("Skipping multipart container") |
---|
1782 | continue |
---|
1783 | |
---|
1784 | ## 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" |
---|
1785 | # |
---|
1786 | inline = self.inline_part(part) |
---|
1787 | |
---|
1788 | ## Drop HTML message |
---|
1789 | # |
---|
1790 | if ALTERNATIVE_MULTIPART and self.parameters.drop_alternative_html_version: |
---|
1791 | if content_type == 'text/html': |
---|
1792 | self.logger.debug('Skipping alternative HTML message') |
---|
1793 | ALTERNATIVE_MULTIPART = False |
---|
1794 | continue |
---|
1795 | |
---|
1796 | |
---|
1797 | ## Save all non plain text message as attachment |
---|
1798 | # |
---|
1799 | if not content_type in ['text/plain']: |
---|
1800 | |
---|
1801 | if self.parameters.debug: |
---|
1802 | s = ' Filename: %s' % part.get_filename() |
---|
1803 | self.print_unicode(s) |
---|
1804 | |
---|
1805 | ## First try to use email header function to convert filename. |
---|
1806 | # If this fails the use the plain filename |
---|
1807 | # |
---|
1808 | try: |
---|
1809 | filename = self.email_to_unicode(part.get_filename()) |
---|
1810 | except UnicodeEncodeError, detail: |
---|
1811 | filename = part.get_filename() |
---|
1812 | |
---|
1813 | message_parts.append((filename, part)) |
---|
1814 | |
---|
1815 | ## Inline text parts are where the body is |
---|
1816 | # |
---|
1817 | if (content_type in ['text/plain', 'text/html']) and inline: |
---|
1818 | self.logger.debug(' Inline body part (content_type = %s)' %(content_type)) |
---|
1819 | |
---|
1820 | ## Try to decode, if fails then do not decode |
---|
1821 | # |
---|
1822 | body_text = part.get_payload(decode=1) |
---|
1823 | if not body_text: |
---|
1824 | body_text = part.get_payload(decode=0) |
---|
1825 | |
---|
1826 | #print type(body_text) must be string |
---|
1827 | |
---|
1828 | ## Convert html message to text if a conversion command is specified |
---|
1829 | # |
---|
1830 | if content_type == 'text/html' and self.parameters.html2text_cmd: |
---|
1831 | tmp_file = tempfile.mktemp('.email2trac') |
---|
1832 | cmd = '%s %s' %(self.parameters.html2text_cmd, tmp_file) |
---|
1833 | |
---|
1834 | self.logger.debug('html2text conversion %s'%(cmd)) |
---|
1835 | |
---|
1836 | if self.parameters.dry_run: |
---|
1837 | print 'DRY_RUN: html2text conversion command: %s\n' %(cmd) |
---|
1838 | else: |
---|
1839 | f = open(tmp_file, "w+") |
---|
1840 | f.write(body_text) |
---|
1841 | f.close() |
---|
1842 | |
---|
1843 | lines = os.popen(cmd).readlines() |
---|
1844 | body_text = ''.join(lines) |
---|
1845 | |
---|
1846 | os.unlink(tmp_file) |
---|
1847 | |
---|
1848 | |
---|
1849 | else: |
---|
1850 | ## Save only as attachment. No further processing |
---|
1851 | # |
---|
1852 | continue |
---|
1853 | |
---|
1854 | format = email.Utils.collapse_rfc2231_value(part.get_param('Format', 'fixed')).lower() |
---|
1855 | delsp = email.Utils.collapse_rfc2231_value(part.get_param('DelSp', 'no')).lower() |
---|
1856 | |
---|
1857 | if self.parameters.reflow and not self.parameters.verbatim_format and format == 'flowed': |
---|
1858 | body_text = self.reflow(body_text, delsp == 'yes') |
---|
1859 | |
---|
1860 | if self.parameters.strip_signature: |
---|
1861 | body_text = self.strip_signature(body_text) |
---|
1862 | |
---|
1863 | if self.parameters.strip_quotes: |
---|
1864 | body_text = self.strip_quotes(body_text) |
---|
1865 | |
---|
1866 | if self.parameters.inline_properties: |
---|
1867 | body_text = self.inline_properties(body_text) |
---|
1868 | |
---|
1869 | if self.parameters.use_textwrap: |
---|
1870 | body_text = self.wrap_text(body_text) |
---|
1871 | |
---|
1872 | ## Get contents charset (iso-8859-15 if not defined in mail headers) |
---|
1873 | # |
---|
1874 | charset = part.get_content_charset() |
---|
1875 | if not charset: |
---|
1876 | charset = 'iso-8859-15' |
---|
1877 | |
---|
1878 | try: |
---|
1879 | ubody_text = unicode(body_text, charset) |
---|
1880 | |
---|
1881 | except UnicodeError, detail: |
---|
1882 | ubody_text = unicode(body_text, 'iso-8859-15') |
---|
1883 | |
---|
1884 | except LookupError, detail: |
---|
1885 | ubody_text = 'ERROR: Could not find charset: %s, please install' %(charset) |
---|
1886 | |
---|
1887 | if self.parameters.verbatim_format: |
---|
1888 | message_parts.append('{{{\r\n%s\r\n}}}' %ubody_text) |
---|
1889 | else: |
---|
1890 | message_parts.append('%s' %ubody_text) |
---|
1891 | |
---|
1892 | return message_parts |
---|
1893 | |
---|
1894 | def unique_attachment_names(self, message_parts): |
---|
1895 | """ |
---|
1896 | Make sure we have unique names attachments: |
---|
1897 | - check if it contains illegal characters |
---|
1898 | - Rename "None" filenames to "untitled-part" |
---|
1899 | """ |
---|
1900 | self.logger.debug('function unique_attachment_names()') |
---|
1901 | renamed_parts = [] |
---|
1902 | attachment_names = set() |
---|
1903 | |
---|
1904 | for item in message_parts: |
---|
1905 | |
---|
1906 | ## If not an attachment, leave it alone |
---|
1907 | # |
---|
1908 | if not isinstance(item, tuple): |
---|
1909 | renamed_parts.append(item) |
---|
1910 | continue |
---|
1911 | |
---|
1912 | (filename, part) = item |
---|
1913 | |
---|
1914 | ## If filename = None, use a default one |
---|
1915 | # |
---|
1916 | if filename in [ 'None']: |
---|
1917 | filename = 'untitled-part' |
---|
1918 | self.logger.info('Rename filename "None" to: %s' %filename) |
---|
1919 | |
---|
1920 | ## Guess the extension from the content type, use non strict mode |
---|
1921 | # some additional non-standard but commonly used MIME types |
---|
1922 | # are also recognized |
---|
1923 | # |
---|
1924 | ext = mimetypes.guess_extension(part.get_content_type(), False) |
---|
1925 | if not ext: |
---|
1926 | ext = '.bin' |
---|
1927 | |
---|
1928 | filename = '%s%s' % (filename, ext) |
---|
1929 | |
---|
1930 | ## Discard relative paths for windows/unix in attachment names |
---|
1931 | # |
---|
1932 | #filename = filename.replace('\\', '/').replace(':', '/') |
---|
1933 | filename = filename.replace('\\', '_') |
---|
1934 | filename = filename.replace('/', '_') |
---|
1935 | |
---|
1936 | ## remove linefeed char |
---|
1937 | # |
---|
1938 | for forbidden_char in ['\r', '\n']: |
---|
1939 | filename = filename.replace(forbidden_char,'') |
---|
1940 | |
---|
1941 | ## We try to normalize the filename to utf-8 NFC if we can. |
---|
1942 | # Files uploaded from OS X might be in NFD. |
---|
1943 | # Check python version and then try it |
---|
1944 | # |
---|
1945 | #if sys.version_info[0] > 2 or (sys.version_info[0] == 2 and sys.version_info[1] >= 3): |
---|
1946 | # try: |
---|
1947 | # filename = unicodedata.normalize('NFC', unicode(filename, 'utf-8')).encode('utf-8') |
---|
1948 | # except TypeError: |
---|
1949 | # pass |
---|
1950 | |
---|
1951 | ## Make the filename unique for this ticket |
---|
1952 | # |
---|
1953 | num = 0 |
---|
1954 | unique_filename = filename |
---|
1955 | dummy_filename, ext = os.path.splitext(filename) |
---|
1956 | |
---|
1957 | while (unique_filename in attachment_names) or self.attachment_exists(unique_filename): |
---|
1958 | num += 1 |
---|
1959 | unique_filename = "%s-%s%s" % (dummy_filename, num, ext) |
---|
1960 | |
---|
1961 | if self.parameters.debug: |
---|
1962 | s = 'Attachment with filename %s will be saved as %s' % (filename, unique_filename) |
---|
1963 | self.print_unicode(s) |
---|
1964 | |
---|
1965 | attachment_names.add(unique_filename) |
---|
1966 | |
---|
1967 | renamed_parts.append((filename, unique_filename, part)) |
---|
1968 | |
---|
1969 | return renamed_parts |
---|
1970 | |
---|
1971 | |
---|
1972 | def attachment_exists(self, filename): |
---|
1973 | |
---|
1974 | if self.parameters.debug: |
---|
1975 | s = 'attachment already exists: Id : %s, Filename : %s' %(self.id, filename) |
---|
1976 | self.print_unicode(s) |
---|
1977 | |
---|
1978 | ## We have no valid ticket id |
---|
1979 | # |
---|
1980 | if not self.id: |
---|
1981 | return False |
---|
1982 | |
---|
1983 | try: |
---|
1984 | if self.system == 'discussion': |
---|
1985 | att = attachment.Attachment(self.env, 'discussion', 'ticket/%s' |
---|
1986 | % (self.id,), filename) |
---|
1987 | else: |
---|
1988 | att = attachment.Attachment(self.env, 'ticket', self.id, |
---|
1989 | filename) |
---|
1990 | return True |
---|
1991 | except attachment.ResourceNotFound: |
---|
1992 | return False |
---|
1993 | |
---|
1994 | ########## TRAC Ticket Text ########################################################### |
---|
1995 | |
---|
1996 | def get_body_text(self, message_parts): |
---|
1997 | """ |
---|
1998 | """ |
---|
1999 | self.logger.debug('function get_body_text()') |
---|
2000 | |
---|
2001 | body_text = [] |
---|
2002 | |
---|
2003 | for part in message_parts: |
---|
2004 | |
---|
2005 | ## Plain text part, append it |
---|
2006 | # |
---|
2007 | if not isinstance(part, tuple): |
---|
2008 | body_text.extend(part.strip().splitlines()) |
---|
2009 | body_text.append("") |
---|
2010 | continue |
---|
2011 | |
---|
2012 | (original, filename, part) = part |
---|
2013 | inline = self.inline_part(part) |
---|
2014 | |
---|
2015 | ## Skip generation of attachment link if html is converted to text |
---|
2016 | # |
---|
2017 | if part.get_content_type() == 'text/html' and self.parameters.html2text_cmd and inline: |
---|
2018 | s = 'Skipping attachment link for html part: %s' %(filename) |
---|
2019 | self.print_unicode(s) |
---|
2020 | continue |
---|
2021 | |
---|
2022 | if part.get_content_maintype() == 'image' and inline: |
---|
2023 | if self.system != 'discussion': |
---|
2024 | s = 'wiki image link for: %s' %(filename) |
---|
2025 | self.print_unicode(s) |
---|
2026 | body_text.append('[[Image(%s)]]' % filename) |
---|
2027 | body_text.append("") |
---|
2028 | else: |
---|
2029 | if self.system != 'discussion': |
---|
2030 | s = 'wiki attachment link for: %s' %(filename) |
---|
2031 | self.print_unicode(s) |
---|
2032 | body_text.append('[attachment:"%s"]' % filename) |
---|
2033 | body_text.append("") |
---|
2034 | |
---|
2035 | ## Convert list body_texts to string |
---|
2036 | # |
---|
2037 | body_text = '\r\n'.join(body_text) |
---|
2038 | return body_text |
---|
2039 | |
---|
2040 | def html_mailto_link(self, subject): |
---|
2041 | """ |
---|
2042 | This function returns a HTML mailto tag with the ticket id and author email address |
---|
2043 | """ |
---|
2044 | if not self.author: |
---|
2045 | author = self.email_addr |
---|
2046 | else: |
---|
2047 | author = self.author |
---|
2048 | |
---|
2049 | if not self.parameters.mailto_cc: |
---|
2050 | self.parameters.mailto_cc = '' |
---|
2051 | |
---|
2052 | ## use urllib to escape the chars |
---|
2053 | # |
---|
2054 | s = 'mailto:%s?Subject=%s&Cc=%s' %( |
---|
2055 | urllib.quote(self.email_addr), |
---|
2056 | urllib.quote('Re: #%s: %s' %(self.id, subject)), |
---|
2057 | urllib.quote(self.parameters.mailto_cc) |
---|
2058 | ) |
---|
2059 | |
---|
2060 | 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) |
---|
2061 | return s |
---|
2062 | |
---|
2063 | ########## TRAC notify section ########################################################### |
---|
2064 | |
---|
2065 | def notify(self, tkt, new=True, modtime=0): |
---|
2066 | """ |
---|
2067 | A wrapper for the TRAC notify function. So we can use templates |
---|
2068 | """ |
---|
2069 | self.logger.debug('function notify()') |
---|
2070 | |
---|
2071 | if self.parameters.dry_run: |
---|
2072 | print 'DRY_RUN: self.notify(tkt, True) reporter = %s' %tkt['reporter'] |
---|
2073 | return |
---|
2074 | try: |
---|
2075 | |
---|
2076 | #from trac.ticket.web_ui import TicketModule |
---|
2077 | #from trac.ticket.notification import TicketNotificationSystem |
---|
2078 | #ticket_sys = TicketNotificationSystem(self.env) |
---|
2079 | #a = TicketModule(self.env) |
---|
2080 | #print a.__dict__ |
---|
2081 | #tn_sys = TicketNotificationSystem(self.env) |
---|
2082 | #print tn_sys |
---|
2083 | #print tn_sys.__dict__ |
---|
2084 | #sys.exit(0) |
---|
2085 | |
---|
2086 | ## create false {abs_}href properties, to trick Notify() |
---|
2087 | # |
---|
2088 | if not (self.VERSION in [0.11, 0.12]): |
---|
2089 | self.env.abs_href = Href(self.get_config('project', 'url')) |
---|
2090 | self.env.href = Href(self.get_config('project', 'url')) |
---|
2091 | |
---|
2092 | |
---|
2093 | tn = TicketNotifyEmail(self.env) |
---|
2094 | |
---|
2095 | if self.parameters.alternate_notify_template: |
---|
2096 | |
---|
2097 | if self.VERSION >= 0.11: |
---|
2098 | |
---|
2099 | from trac.web.chrome import Chrome |
---|
2100 | |
---|
2101 | if self.parameters.alternate_notify_template_update and not new: |
---|
2102 | tn.template_name = self.parameters.alternate_notify_template_update |
---|
2103 | else: |
---|
2104 | tn.template_name = self.parameters.alternate_notify_template |
---|
2105 | |
---|
2106 | tn.template = Chrome(tn.env).load_template(tn.template_name, method='text') |
---|
2107 | |
---|
2108 | else: |
---|
2109 | |
---|
2110 | tn.template_name = self.parameters.alternate_notify_template |
---|
2111 | |
---|
2112 | tn.notify(tkt, new, modtime) |
---|
2113 | |
---|
2114 | except Exception, e: |
---|
2115 | self.logger.error('Failure sending notification on creation of ticket #%s: %s' %(self.id, e)) |
---|
2116 | |
---|
2117 | |
---|
2118 | |
---|
2119 | ########## Parse Config File ########################################################### |
---|
2120 | |
---|
2121 | def ReadConfig(file, name): |
---|
2122 | """ |
---|
2123 | Parse the config file |
---|
2124 | """ |
---|
2125 | if not os.path.isfile(file): |
---|
2126 | print 'File %s does not exist' %file |
---|
2127 | sys.exit(1) |
---|
2128 | |
---|
2129 | config = trac_config.Configuration(file) |
---|
2130 | |
---|
2131 | parentdir = config.get('DEFAULT', 'parentdir') |
---|
2132 | sections = config.sections() |
---|
2133 | |
---|
2134 | ## use some trac internals to get the defaults |
---|
2135 | # |
---|
2136 | tmp = config.parser.defaults() |
---|
2137 | project = SaraDict() |
---|
2138 | |
---|
2139 | for option, value in tmp.items(): |
---|
2140 | try: |
---|
2141 | project[option] = int(value) |
---|
2142 | except ValueError: |
---|
2143 | project[option] = value |
---|
2144 | |
---|
2145 | if name: |
---|
2146 | if name in sections: |
---|
2147 | project = SaraDict() |
---|
2148 | for option, value in config.options(name): |
---|
2149 | try: |
---|
2150 | project[option] = int(value) |
---|
2151 | except ValueError: |
---|
2152 | project[option] = value |
---|
2153 | |
---|
2154 | elif not parentdir: |
---|
2155 | print "Not a valid project name: %s, valid names are: %s" %(name, sections) |
---|
2156 | print "or set parentdir in the [DEFAULT] section" |
---|
2157 | sys.exit(1) |
---|
2158 | |
---|
2159 | ## If parentdir the set project dir to parentdir + name |
---|
2160 | # |
---|
2161 | if not project.has_key('project'): |
---|
2162 | if not parentdir: |
---|
2163 | print "You must set project or parentdir in your configuration file" |
---|
2164 | sys.exit(1) |
---|
2165 | elif not name: |
---|
2166 | print "You must set project in your configuration file" |
---|
2167 | else: |
---|
2168 | project['project'] = os.path.join(parentdir, name) |
---|
2169 | |
---|
2170 | return project |
---|
2171 | |
---|
2172 | ########## Setup Logging ############################################################### |
---|
2173 | |
---|
2174 | def setup_log(parameters, project_name, interactive=None): |
---|
2175 | """ |
---|
2176 | Setup loging |
---|
2177 | |
---|
2178 | Note for log format the usage of `$(...)s` instead of `%(...)s` as the latter form |
---|
2179 | would be interpreted by the ConfigParser itself. |
---|
2180 | """ |
---|
2181 | logger = logging.getLogger('email2trac %s' %project_name) |
---|
2182 | |
---|
2183 | if interactive: |
---|
2184 | parameters.log_type = 'stderr' |
---|
2185 | |
---|
2186 | if not parameters.log_type: |
---|
2187 | if sys.platform in ['win32', 'cygwin']: |
---|
2188 | paramters.log_type = 'eventlog' |
---|
2189 | else: |
---|
2190 | parameters.log_type = 'syslog' |
---|
2191 | |
---|
2192 | if parameters.log_type == 'file': |
---|
2193 | |
---|
2194 | if not parameters.log_file: |
---|
2195 | parameters.log_file = 'email2trac.log' |
---|
2196 | |
---|
2197 | if not os.path.isabs(parameters.log_file): |
---|
2198 | parameters.log_file = os.path.join(tempfile.gettempdir(), parameters.log_file) |
---|
2199 | |
---|
2200 | log_handler = logging.FileHandler(parameters.log_file) |
---|
2201 | |
---|
2202 | elif parameters.log_type in ('winlog', 'eventlog', 'nteventlog'): |
---|
2203 | ## Requires win32 extensions |
---|
2204 | # |
---|
2205 | log_handler = logging.handlers.NTEventLogHandler(logid, logtype='Application') |
---|
2206 | |
---|
2207 | elif parameters.log_type in ('syslog', 'unix'): |
---|
2208 | log_handler = logging.handlers.SysLogHandler('/dev/log') |
---|
2209 | |
---|
2210 | elif parameters.log_type in ('stderr'): |
---|
2211 | log_handler = logging.StreamHandler(sys.stderr) |
---|
2212 | |
---|
2213 | else: |
---|
2214 | log_handler = logging.handlers.BufferingHandler(0) |
---|
2215 | |
---|
2216 | if parameters.log_format: |
---|
2217 | parameters.log_format = parameters.log_format.replace('$(', '%(') |
---|
2218 | else: |
---|
2219 | parameters.log_format = '%(name)s: %(message)s' |
---|
2220 | |
---|
2221 | log_formatter = logging.Formatter(parameters.log_format) |
---|
2222 | log_handler.setFormatter(log_formatter) |
---|
2223 | logger.addHandler(log_handler) |
---|
2224 | |
---|
2225 | if (parameters.log_level in ['DEBUG', 'ALL']) or (parameters.debug > 0): |
---|
2226 | logger.setLevel(logging.DEBUG) |
---|
2227 | parameters.debug = 1 |
---|
2228 | |
---|
2229 | elif parameters.log_level in ['INFO'] or parameters.verbose: |
---|
2230 | logger.setLevel(logging.INFO) |
---|
2231 | |
---|
2232 | elif parameters.log_level in ['WARNING']: |
---|
2233 | logger.setLevel(logging.WARNING) |
---|
2234 | |
---|
2235 | elif parameters.log_level in ['ERROR']: |
---|
2236 | logger.setLevel(logging.ERROR) |
---|
2237 | |
---|
2238 | elif parameters.log_level in ['CRITICAL']: |
---|
2239 | logger.setLevel(logging.CRITICAL) |
---|
2240 | |
---|
2241 | else: |
---|
2242 | logger.setLevel(logging.INFO) |
---|
2243 | |
---|
2244 | return logger |
---|
2245 | |
---|
2246 | |
---|
2247 | if __name__ == '__main__': |
---|
2248 | ## Default config file |
---|
2249 | # |
---|
2250 | configfile = '@email2trac_conf@' |
---|
2251 | project = '' |
---|
2252 | component = '' |
---|
2253 | ticket_prefix = 'default' |
---|
2254 | dry_run = None |
---|
2255 | verbose = None |
---|
2256 | debug_interactive = None |
---|
2257 | |
---|
2258 | SHORT_OPT = 'cdhf:np:t:v' |
---|
2259 | LONG_OPT = ['component=', 'debug', 'dry-run', 'help', 'file=', 'project=', 'ticket_prefix=', 'verbose'] |
---|
2260 | |
---|
2261 | try: |
---|
2262 | opts, args = getopt.getopt(sys.argv[1:], SHORT_OPT, LONG_OPT) |
---|
2263 | except getopt.error,detail: |
---|
2264 | print __doc__ |
---|
2265 | print detail |
---|
2266 | sys.exit(1) |
---|
2267 | |
---|
2268 | project_name = None |
---|
2269 | for opt,value in opts: |
---|
2270 | if opt in [ '-h', '--help']: |
---|
2271 | print __doc__ |
---|
2272 | sys.exit(0) |
---|
2273 | elif opt in ['-c', '--component']: |
---|
2274 | component = value |
---|
2275 | elif opt in ['-d', '--debug']: |
---|
2276 | debug_interactive = 1 |
---|
2277 | elif opt in ['-f', '--file']: |
---|
2278 | configfile = value |
---|
2279 | elif opt in ['-n', '--dry-run']: |
---|
2280 | dry_run = True |
---|
2281 | elif opt in ['-p', '--project']: |
---|
2282 | project_name = value |
---|
2283 | elif opt in ['-t', '--ticket_prefix']: |
---|
2284 | ticket_prefix = value |
---|
2285 | elif opt in ['-v', '--verbose']: |
---|
2286 | verbose = True |
---|
2287 | |
---|
2288 | settings = ReadConfig(configfile, project_name) |
---|
2289 | |
---|
2290 | ## The default prefix for ticket values in email2trac.conf |
---|
2291 | # |
---|
2292 | settings.ticket_prefix = ticket_prefix |
---|
2293 | settings.dry_run = dry_run |
---|
2294 | settings.verbose = verbose |
---|
2295 | |
---|
2296 | if not settings.debug and debug_interactive: |
---|
2297 | settings.debug = debug_interactive |
---|
2298 | |
---|
2299 | if not settings.project: |
---|
2300 | print __doc__ |
---|
2301 | print 'No Trac project is defined in the email2trac config file.' |
---|
2302 | sys.exit(1) |
---|
2303 | |
---|
2304 | logger = setup_log(settings, os.path.basename(settings.project), debug_interactive) |
---|
2305 | |
---|
2306 | if component: |
---|
2307 | settings['component'] = component |
---|
2308 | |
---|
2309 | ## Determine major trac version used to be in email2trac.conf |
---|
2310 | # Quick hack for 0.12 |
---|
2311 | # |
---|
2312 | version = '0.%s' %(trac_version.split('.')[1]) |
---|
2313 | if version.startswith('0.12'): |
---|
2314 | version = '0.12' |
---|
2315 | |
---|
2316 | logger.debug("Found trac version: %s" %(version)) |
---|
2317 | |
---|
2318 | try: |
---|
2319 | if version == '0.10': |
---|
2320 | from trac import attachment |
---|
2321 | from trac.env import Environment |
---|
2322 | from trac.ticket import Ticket |
---|
2323 | from trac.web.href import Href |
---|
2324 | from trac import util |
---|
2325 | from trac.ticket.web_ui import TicketModule |
---|
2326 | |
---|
2327 | # |
---|
2328 | # return util.text.to_unicode(str) |
---|
2329 | # |
---|
2330 | # see http://projects.edgewall.com/trac/changeset/2799 |
---|
2331 | from trac.ticket.notification import TicketNotifyEmail |
---|
2332 | from trac import config as trac_config |
---|
2333 | from trac.core import TracError |
---|
2334 | |
---|
2335 | elif version == '0.11': |
---|
2336 | from trac import attachment |
---|
2337 | from trac.env import Environment |
---|
2338 | from trac.ticket import Ticket |
---|
2339 | from trac.web.href import Href |
---|
2340 | from trac import config as trac_config |
---|
2341 | from trac import util |
---|
2342 | from trac.core import TracError |
---|
2343 | from trac.perm import PermissionSystem |
---|
2344 | from trac.ticket.web_ui import TicketModule |
---|
2345 | |
---|
2346 | # |
---|
2347 | # return util.text.to_unicode(str) |
---|
2348 | # |
---|
2349 | # see http://projects.edgewall.com/trac/changeset/2799 |
---|
2350 | from trac.ticket.notification import TicketNotifyEmail |
---|
2351 | |
---|
2352 | elif version == '0.12': |
---|
2353 | from trac import attachment |
---|
2354 | from trac.env import Environment |
---|
2355 | from trac.ticket import Ticket |
---|
2356 | from trac.web.href import Href |
---|
2357 | from trac import config as trac_config |
---|
2358 | from trac import util |
---|
2359 | from trac.core import TracError |
---|
2360 | from trac.perm import PermissionSystem |
---|
2361 | from trac.ticket.web_ui import TicketModule |
---|
2362 | |
---|
2363 | # |
---|
2364 | # return util.text.to_unicode(str) |
---|
2365 | # |
---|
2366 | # see http://projects.edgewall.com/trac/changeset/2799 |
---|
2367 | from trac.ticket.notification import TicketNotifyEmail |
---|
2368 | |
---|
2369 | |
---|
2370 | else: |
---|
2371 | logger.error('TRAC version %s is not supported' %version) |
---|
2372 | sys.exit(1) |
---|
2373 | |
---|
2374 | ## Must be set before environment is created |
---|
2375 | # |
---|
2376 | if settings.has_key('python_egg_cache'): |
---|
2377 | python_egg_cache = str(settings['python_egg_cache']) |
---|
2378 | os.environ['PYTHON_EGG_CACHE'] = python_egg_cache |
---|
2379 | |
---|
2380 | if settings.debug > 0: |
---|
2381 | logger.debug('Loading environment %s', settings.project) |
---|
2382 | |
---|
2383 | try: |
---|
2384 | env = Environment(settings['project'], create=0) |
---|
2385 | except IOError, detail: |
---|
2386 | print "Trac project does not exists: %s" %(settings['project']) |
---|
2387 | sys.exit(1) |
---|
2388 | |
---|
2389 | tktparser = TicketEmailParser(env, settings, logger, float(version)) |
---|
2390 | tktparser.parse(sys.stdin) |
---|
2391 | |
---|
2392 | ## Catch all errors and use the logging module |
---|
2393 | # |
---|
2394 | except Exception, error: |
---|
2395 | |
---|
2396 | etype, evalue, etb = sys.exc_info() |
---|
2397 | for e in traceback.format_exception(etype, evalue, etb): |
---|
2398 | logger.critical(e) |
---|
2399 | |
---|
2400 | if m: |
---|
2401 | tktparser.save_email_for_debug(m, True) |
---|
2402 | |
---|
2403 | sys.exit(1) |
---|
2404 | # EOB |
---|