]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/bin/parsemail.py
Inital commit
[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 from email.header import Header
29 from email.utils import parsedate_tz, mktime_tz
30
31 from patchparser import parse_patch
32 from patchwork.models import Patch, Project, Person, Comment
33
34 list_id_headers = ['List-ID', 'X-Mailing-List']
35
36 def find_project(mail):
37     project = None
38     listid_re = re.compile('.*<([^>]+)>.*', re.S)
39
40     for header in list_id_headers:
41         if header in mail:
42             match = listid_re.match(mail.get(header))
43             if not match:
44                 continue
45
46             listid = match.group(1)
47
48             try:
49                 project = Project.objects.get(listid = listid)
50                 break
51             except:
52                 pass
53
54     return project
55
56 def find_author(mail):
57
58     from_header = mail.get('From').strip()
59     (name, email) = (None, None)
60
61     # tuple of (regex, fn)
62     #  - where fn returns a (name, email) tuple from the match groups resulting
63     #    from re.match().groups()
64     from_res = [
65         # for "Firstname Lastname" <example@example.com> style addresses
66        (re.compile('"?(.*?)"?\s*<([^>]+)>'), (lambda g: (g[0], g[1]))),
67
68        # for example@example.com (Firstname Lastname) style addresses
69        (re.compile('"?(.*?)"?\s*\(([^\)]+)\)'), (lambda g: (g[1], g[0]))),
70
71        # everything else
72        (re.compile('(.*)'), (lambda g: (None, g[0]))),
73     ]
74
75     for regex, fn in from_res:
76         match = regex.match(from_header)
77         if match:
78             (name, email) = fn(match.groups())
79             break
80
81     if email is None:
82         raise Exception("Could not parse From: header")
83
84     email = email.strip()
85     if name is not None:
86         name = name.strip()
87
88     try:
89         person = Person.objects.get(email = email)
90     except Person.DoesNotExist:
91         person = Person(name = name, email = email)
92
93     return person
94
95 def mail_date(mail):
96     t = parsedate_tz(mail.get('Date', ''))
97     if not t:
98         print "using now()"
99         return datetime.datetime.utcnow()
100     return datetime.datetime.utcfromtimestamp(mktime_tz(t))
101
102 def mail_headers(mail):
103     return reduce(operator.__concat__,
104             ['%s: %s\n' % (k, Header(v, header_name = k, \
105                     continuation_ws = '\t').encode()) \
106                 for (k, v) in mail.items()])
107
108 def find_content(project, mail):
109     patchbuf = None
110     commentbuf = ''
111
112     for part in mail.walk():
113         if part.get_content_maintype() != 'text':
114             continue
115
116         #print "\t%s, %s" % \
117         #    (part.get_content_subtype(), part.get_content_charset())
118
119         charset = part.get_content_charset()
120         if not charset:
121             charset = mail.get_charset()
122         if not charset:
123             charset = 'utf-8'
124
125         payload = unicode(part.get_payload(decode=True), charset, "replace")
126
127         if part.get_content_subtype() == 'x-patch':
128             patchbuf = payload
129
130         if part.get_content_subtype() == 'plain':
131             if not patchbuf:
132                 (patchbuf, c) = parse_patch(payload)
133             else:
134                 c = payload
135
136             if c is not None:
137                 commentbuf += c.strip() + '\n'
138
139     patch = None
140     comment = None
141
142     if patchbuf:
143         mail_headers(mail)
144         patch = Patch(name = clean_subject(mail.get('Subject')),
145                 content = patchbuf, date = mail_date(mail),
146                 headers = mail_headers(mail))
147
148     if commentbuf:
149         if patch:
150             cpatch = patch
151         else:
152             cpatch = find_patch_for_comment(mail)
153             if not cpatch:
154                 return (None, None)
155         comment = Comment(patch = cpatch, date = mail_date(mail),
156                 content = clean_content(commentbuf),
157                 headers = mail_headers(mail))
158
159     return (patch, comment)
160
161 def find_patch_for_comment(mail):
162     # construct a list of possible reply message ids
163     refs = []
164     if 'In-Reply-To' in mail:
165         refs.append(mail.get('In-Reply-To'))
166
167     if 'References' in mail:
168         rs = mail.get('References').split()
169         rs.reverse()
170         for r in rs:
171             if r not in refs:
172                 refs.append(r)
173
174     for ref in refs:
175         patch = None
176
177         # first, check for a direct reply
178         try:
179             patch = Patch.objects.get(msgid = ref)
180             return patch
181         except Patch.DoesNotExist:
182             pass
183
184         # see if we have comments that refer to a patch
185         try:
186             comment = Comment.objects.get(msgid = ref)
187             return comment.patch
188         except Comment.DoesNotExist:
189             pass
190
191
192     return None
193
194 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
195 prefix_re = re.compile('^\[.*\]\s*')
196 whitespace_re = re.compile('\s+')
197
198 def clean_subject(subject):
199     subject = re_re.sub(' ', subject)
200     subject = prefix_re.sub('', subject)
201     subject = whitespace_re.sub(' ', subject)
202     return subject.strip()
203
204 sig_re = re.compile('^(-{2,3} ?|_+)\n.*', re.S | re.M)
205 def clean_content(str):
206     str = sig_re.sub('', str)
207     return str.strip()
208
209 def main(args):
210     mail = message_from_file(sys.stdin)
211
212     # some basic sanity checks
213     if 'From' not in mail:
214         return 0
215
216     if 'Subject' not in mail:
217         return 0
218
219     if 'Message-Id' not in mail:
220         return 0
221
222     hint = mail.get('X-Patchwork-Hint', '').lower()
223     if hint == 'ignore':
224         return 0;
225
226     project = find_project(mail)
227     if project is None:
228         print "no project found"
229         return 0
230
231     msgid = mail.get('Message-Id').strip()
232
233     author = find_author(mail)
234
235     (patch, comment) = find_content(project, mail)
236
237     if patch:
238         author.save()
239         patch.submitter = author
240         patch.msgid = msgid
241         patch.project = project
242         try:
243             patch.save()
244         except Exception, ex:
245             print ex.message
246
247     if comment:
248         author.save()
249         # looks like the original constructor for Comment takes the pk
250         # when the Comment is created. reset it here.
251         if patch:
252             comment.patch = patch
253         comment.submitter = author
254         comment.msgid = msgid
255         try:
256             comment.save()
257         except Exception, ex:
258             print ex.message
259
260     return 0
261
262 if __name__ == '__main__':
263     sys.exit(main(sys.argv))