]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/bin/parsemail.py
Get parsemail scripts going
[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     new_person = False
89
90     try:
91         person = Person.objects.get(email = email)
92     except Person.DoesNotExist:
93         person = Person(name = name, email = email)
94         new_person = True
95
96     return (person, new_person)
97
98 def mail_date(mail):
99     t = parsedate_tz(mail.get('Date', ''))
100     if not t:
101         print "using now()"
102         return datetime.datetime.utcnow()
103     return datetime.datetime.utcfromtimestamp(mktime_tz(t))
104
105 def mail_headers(mail):
106     return reduce(operator.__concat__,
107             ['%s: %s\n' % (k, Header(v, header_name = k, \
108                     continuation_ws = '\t').encode()) \
109                 for (k, v) in mail.items()])
110
111 def find_content(project, mail):
112     patchbuf = None
113     commentbuf = ''
114
115     for part in mail.walk():
116         if part.get_content_maintype() != 'text':
117             continue
118
119         #print "\t%s, %s" % \
120         #    (part.get_content_subtype(), part.get_content_charset())
121
122         charset = part.get_content_charset()
123         if not charset:
124             charset = mail.get_charset()
125         if not charset:
126             charset = 'utf-8'
127
128         payload = unicode(part.get_payload(decode=True), charset, "replace")
129
130         if part.get_content_subtype() == 'x-patch':
131             patchbuf = payload
132
133         if part.get_content_subtype() == 'plain':
134             if not patchbuf:
135                 (patchbuf, c) = parse_patch(payload)
136             else:
137                 c = payload
138
139             if c is not None:
140                 commentbuf += c.strip() + '\n'
141
142     patch = None
143     comment = None
144
145     if patchbuf:
146         mail_headers(mail)
147         patch = Patch(name = clean_subject(mail.get('Subject')),
148                 content = patchbuf, date = mail_date(mail),
149                 headers = mail_headers(mail))
150
151     if commentbuf:
152         if patch:
153             cpatch = patch
154         else:
155             cpatch = find_patch_for_comment(mail)
156             if not cpatch:
157                 return (None, None)
158         comment = Comment(patch = cpatch, date = mail_date(mail),
159                 content = clean_content(commentbuf),
160                 headers = mail_headers(mail))
161
162     return (patch, comment)
163
164 def find_patch_for_comment(mail):
165     # construct a list of possible reply message ids
166     refs = []
167     if 'In-Reply-To' in mail:
168         refs.append(mail.get('In-Reply-To'))
169
170     if 'References' in mail:
171         rs = mail.get('References').split()
172         rs.reverse()
173         for r in rs:
174             if r not in refs:
175                 refs.append(r)
176
177     for ref in refs:
178         patch = None
179
180         # first, check for a direct reply
181         try:
182             patch = Patch.objects.get(msgid = ref)
183             return patch
184         except Patch.DoesNotExist:
185             pass
186
187         # see if we have comments that refer to a patch
188         try:
189             comment = Comment.objects.get(msgid = ref)
190             return comment.patch
191         except Comment.DoesNotExist:
192             pass
193
194
195     return None
196
197 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
198 prefix_re = re.compile('^\[.*\]\s*')
199 whitespace_re = re.compile('\s+')
200
201 def clean_subject(subject):
202     subject = re_re.sub(' ', subject)
203     subject = prefix_re.sub('', subject)
204     subject = whitespace_re.sub(' ', subject)
205     return subject.strip()
206
207 sig_re = re.compile('^(-{2,3} ?|_+)\n.*', re.S | re.M)
208 def clean_content(str):
209     str = sig_re.sub('', str)
210     return str.strip()
211
212 def main(args):
213     mail = message_from_file(sys.stdin)
214
215     # some basic sanity checks
216     if 'From' not in mail:
217         return 0
218
219     if 'Subject' not in mail:
220         return 0
221
222     if 'Message-Id' not in mail:
223         return 0
224
225     hint = mail.get('X-Patchwork-Hint', '').lower()
226     if hint == 'ignore':
227         return 0;
228
229     project = find_project(mail)
230     if project is None:
231         print "no project found"
232         return 0
233
234     msgid = mail.get('Message-Id').strip()
235
236     (author, save_required) = find_author(mail)
237
238     (patch, comment) = find_content(project, mail)
239
240     if patch:
241         # we delay the saving until we know we have a patch.
242         if save_required:
243             author.save()
244             save_required = False
245         patch.submitter = author
246         patch.msgid = msgid
247         patch.project = project
248         try:
249             patch.save()
250         except Exception, ex:
251             print ex.message
252
253     if comment:
254         if save_required:
255             author.save()
256         # looks like the original constructor for Comment takes the pk
257         # when the Comment is created. reset it here.
258         if patch:
259             comment.patch = patch
260         comment.submitter = author
261         comment.msgid = msgid
262         try:
263             comment.save()
264         except Exception, ex:
265             print ex.message
266
267     return 0
268
269 if __name__ == '__main__':
270     sys.exit(main(sys.argv))