]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/bin/parsemail.py
Move patchparser to patchwork.parser
[patchwork] / apps / patchwork / bin / parsemail.py
1 #!/usr/bin/python
2 #
3 # Patchwork - automated patch tracking system
4 # Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
5 #
6 # This file is part of the Patchwork package.
7 #
8 # Patchwork is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # Patchwork is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Patchwork; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21
22 import sys
23 import re
24 import datetime
25 import time
26 import operator
27 from email import message_from_file
28 try:
29     from email.header import Header
30     from email.utils import parsedate_tz, mktime_tz
31 except ImportError:
32     # Python 2.4 compatibility
33     from email.Header import Header
34     from email.Utils import parsedate_tz, mktime_tz
35
36 from patchwork.parser import parse_patch
37 from patchwork.models import Patch, Project, Person, Comment
38
39 list_id_headers = ['List-ID', 'X-Mailing-List']
40
41 def find_project(mail):
42     project = None
43     listid_re = re.compile('.*<([^>]+)>.*', re.S)
44
45     for header in list_id_headers:
46         if header in mail:
47             match = listid_re.match(mail.get(header))
48             if not match:
49                 continue
50
51             listid = match.group(1)
52
53             try:
54                 project = Project.objects.get(listid = listid)
55                 break
56             except:
57                 pass
58
59     return project
60
61 def find_author(mail):
62
63     from_header = mail.get('From').strip()
64     (name, email) = (None, None)
65
66     # tuple of (regex, fn)
67     #  - where fn returns a (name, email) tuple from the match groups resulting
68     #    from re.match().groups()
69     from_res = [
70         # for "Firstname Lastname" <example@example.com> style addresses
71        (re.compile('"?(.*?)"?\s*<([^>]+)>'), (lambda g: (g[0], g[1]))),
72
73        # for example@example.com (Firstname Lastname) style addresses
74        (re.compile('"?(.*?)"?\s*\(([^\)]+)\)'), (lambda g: (g[1], g[0]))),
75
76        # everything else
77        (re.compile('(.*)'), (lambda g: (None, g[0]))),
78     ]
79
80     for regex, fn in from_res:
81         match = regex.match(from_header)
82         if match:
83             (name, email) = fn(match.groups())
84             break
85
86     if email is None:
87         raise Exception("Could not parse From: header")
88
89     email = email.strip()
90     if name is not None:
91         name = name.strip()
92
93     new_person = False
94
95     try:
96         person = Person.objects.get(email = email)
97     except Person.DoesNotExist:
98         person = Person(name = name, email = email)
99         new_person = True
100
101     return (person, new_person)
102
103 def mail_date(mail):
104     t = parsedate_tz(mail.get('Date', ''))
105     if not t:
106         print "using now()"
107         return datetime.datetime.utcnow()
108     return datetime.datetime.utcfromtimestamp(mktime_tz(t))
109
110 def mail_headers(mail):
111     return reduce(operator.__concat__,
112             ['%s: %s\n' % (k, Header(v, header_name = k, \
113                     continuation_ws = '\t').encode()) \
114                 for (k, v) in mail.items()])
115
116 def find_content(project, mail):
117     patchbuf = None
118     commentbuf = ''
119
120     for part in mail.walk():
121         if part.get_content_maintype() != 'text':
122             continue
123
124         #print "\t%s, %s" % \
125         #    (part.get_content_subtype(), part.get_content_charset())
126
127         charset = part.get_content_charset()
128         if not charset:
129             charset = mail.get_charset()
130         if not charset:
131             charset = 'utf-8'
132
133         payload = unicode(part.get_payload(decode=True), charset, "replace")
134
135         if part.get_content_subtype() == 'x-patch':
136             patchbuf = payload
137
138         if part.get_content_subtype() == 'plain':
139             if not patchbuf:
140                 (patchbuf, c) = parse_patch(payload)
141             else:
142                 c = payload
143
144             if c is not None:
145                 commentbuf += c.strip() + '\n'
146
147     patch = None
148     comment = None
149
150     if patchbuf:
151         mail_headers(mail)
152         patch = Patch(name = clean_subject(mail.get('Subject')),
153                 content = patchbuf, date = mail_date(mail),
154                 headers = mail_headers(mail))
155
156     if commentbuf:
157         if patch:
158             cpatch = patch
159         else:
160             cpatch = find_patch_for_comment(mail)
161             if not cpatch:
162                 return (None, None)
163         comment = Comment(patch = cpatch, date = mail_date(mail),
164                 content = clean_content(commentbuf),
165                 headers = mail_headers(mail))
166
167     return (patch, comment)
168
169 def find_patch_for_comment(mail):
170     # construct a list of possible reply message ids
171     refs = []
172     if 'In-Reply-To' in mail:
173         refs.append(mail.get('In-Reply-To'))
174
175     if 'References' in mail:
176         rs = mail.get('References').split()
177         rs.reverse()
178         for r in rs:
179             if r not in refs:
180                 refs.append(r)
181
182     for ref in refs:
183         patch = None
184
185         # first, check for a direct reply
186         try:
187             patch = Patch.objects.get(msgid = ref)
188             return patch
189         except Patch.DoesNotExist:
190             pass
191
192         # see if we have comments that refer to a patch
193         try:
194             comment = Comment.objects.get(msgid = ref)
195             return comment.patch
196         except Comment.DoesNotExist:
197             pass
198
199
200     return None
201
202 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
203 prefix_re = re.compile('^\[.*\]\s*')
204 whitespace_re = re.compile('\s+')
205
206 def clean_subject(subject):
207     subject = re_re.sub(' ', subject)
208     subject = prefix_re.sub('', subject)
209     subject = whitespace_re.sub(' ', subject)
210     return subject.strip()
211
212 sig_re = re.compile('^(-{2,3} ?|_+)\n.*', re.S | re.M)
213 def clean_content(str):
214     str = sig_re.sub('', str)
215     return str.strip()
216
217 def main(args):
218     mail = message_from_file(sys.stdin)
219
220     # some basic sanity checks
221     if 'From' not in mail:
222         return 0
223
224     if 'Subject' not in mail:
225         return 0
226
227     if 'Message-Id' not in mail:
228         return 0
229
230     hint = mail.get('X-Patchwork-Hint', '').lower()
231     if hint == 'ignore':
232         return 0;
233
234     project = find_project(mail)
235     if project is None:
236         print "no project found"
237         return 0
238
239     msgid = mail.get('Message-Id').strip()
240
241     (author, save_required) = find_author(mail)
242
243     (patch, comment) = find_content(project, mail)
244
245     if patch:
246         # we delay the saving until we know we have a patch.
247         if save_required:
248             author.save()
249             save_required = False
250         patch.submitter = author
251         patch.msgid = msgid
252         patch.project = project
253         try:
254             patch.save()
255         except Exception, ex:
256             print str(ex)
257
258     if comment:
259         if save_required:
260             author.save()
261         # looks like the original constructor for Comment takes the pk
262         # when the Comment is created. reset it here.
263         if patch:
264             comment.patch = patch
265         comment.submitter = author
266         comment.msgid = msgid
267         try:
268             comment.save()
269         except Exception, ex:
270             print str(ex)
271
272     return 0
273
274 if __name__ == '__main__':
275     sys.exit(main(sys.argv))