]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/models.py
Use generic email confirmation object
[patchwork] / apps / patchwork / models.py
1 # Patchwork - automated patch tracking system
2 # Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
3 #
4 # This file is part of the Patchwork package.
5 #
6 # Patchwork is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # Patchwork 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 Patchwork; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 from django.db import models
21 from django.contrib.auth.models import User
22 from django.core.urlresolvers import reverse
23 from django.contrib.sites.models import Site
24 from patchwork.parser import hash_patch
25
26 import re
27 import datetime, time
28 import random
29
30 try:
31     from email.mime.nonmultipart import MIMENonMultipart
32     from email.encoders import encode_7or8bit
33     from email.parser import HeaderParser
34     import email.utils
35 except ImportError:
36     # Python 2.4 compatibility
37     from email.MIMENonMultipart import MIMENonMultipart
38     from email.Encoders import encode_7or8bit
39     from email.Parser import HeaderParser
40     import email.Utils
41     email.utils = email.Utils
42
43 class Person(models.Model):
44     email = models.CharField(max_length=255, unique = True)
45     name = models.CharField(max_length=255, null = True, blank = True)
46     user = models.ForeignKey(User, null = True, blank = True)
47
48     def __unicode__(self):
49         if self.name:
50             return u'%s <%s>' % (self.name, self.email)
51         else:
52             return self.email
53
54     def link_to_user(self, user):
55         self.name = user.get_profile().name()
56         self.user = user
57
58     class Meta:
59         verbose_name_plural = 'People'
60
61 class Project(models.Model):
62     linkname = models.CharField(max_length=255, unique=True)
63     name = models.CharField(max_length=255, unique=True)
64     listid = models.CharField(max_length=255, unique=True)
65     listemail = models.CharField(max_length=200)
66
67     def __unicode__(self):
68         return self.name
69
70     def is_editable(self, user):
71         if not user.is_authenticated():
72             return False
73         return self in user.get_profile().maintainer_projects.all()
74
75 class UserProfile(models.Model):
76     user = models.ForeignKey(User, unique = True)
77     primary_project = models.ForeignKey(Project, null = True, blank = True)
78     maintainer_projects = models.ManyToManyField(Project,
79             related_name = 'maintainer_project')
80     send_email = models.BooleanField(default = False,
81             help_text = 'Selecting this option allows patchwork to send ' +
82                 'email on your behalf')
83     patches_per_page = models.PositiveIntegerField(default = 100,
84             null = False, blank = False,
85             help_text = 'Number of patches to display per page')
86
87     def name(self):
88         if self.user.first_name or self.user.last_name:
89             names = filter(bool, [self.user.first_name, self.user.last_name])
90             return u' '.join(names)
91         return self.user.username
92
93     def contributor_projects(self):
94         submitters = Person.objects.filter(user = self.user)
95         return Project.objects.filter(id__in =
96                                         Patch.objects.filter(
97                                             submitter__in = submitters)
98                                         .values('project_id').query)
99
100
101     def sync_person(self):
102         pass
103
104     def n_todo_patches(self):
105         return self.todo_patches().count()
106
107     def todo_patches(self, project = None):
108
109         # filter on project, if necessary
110         if project:
111             qs = Patch.objects.filter(project = project)
112         else:
113             qs = Patch.objects
114
115         qs = qs.filter(archived = False) \
116              .filter(delegate = self.user) \
117              .filter(state__in =
118                      State.objects.filter(action_required = True)
119                          .values('pk').query)
120         return qs
121
122     def save(self):
123         super(UserProfile, self).save()
124         people = Person.objects.filter(email = self.user.email)
125         if not people:
126             person = Person(email = self.user.email,
127                     name = self.name(), user = self.user)
128             person.save()
129         else:
130             for person in people:
131                  person.link_to_user(self.user)
132                  person.save()
133
134     def __unicode__(self):
135         return self.name()
136
137 def _user_created_callback(sender, created, instance, **kwargs):
138     if not created:
139         return
140     profile = UserProfile(user = instance)
141     profile.save()
142
143 models.signals.post_save.connect(_user_created_callback, sender = User)
144
145 class State(models.Model):
146     name = models.CharField(max_length = 100)
147     ordering = models.IntegerField(unique = True)
148     action_required = models.BooleanField(default = True)
149
150     def __unicode__(self):
151         return self.name
152
153     class Meta:
154         ordering = ['ordering']
155
156 class HashField(models.CharField):
157     __metaclass__ = models.SubfieldBase
158
159     def __init__(self, algorithm = 'sha1', *args, **kwargs):
160         self.algorithm = algorithm
161         try:
162             import hashlib
163             def _construct(string = ''):
164                 return hashlib.new(self.algorithm, string)
165             self.construct = _construct
166             self.n_bytes = len(hashlib.new(self.algorithm).hexdigest())
167         except ImportError:
168             modules = { 'sha1': 'sha', 'md5': 'md5'}
169
170             if algorithm not in modules.keys():
171                 raise NameError("Unknown algorithm '%s'" % algorithm)
172
173             self.construct = __import__(modules[algorithm]).new
174
175         self.n_bytes = len(self.construct().hexdigest())
176
177         kwargs['max_length'] = self.n_bytes
178         super(HashField, self).__init__(*args, **kwargs)
179
180     def db_type(self):
181         return 'char(%d)' % self.n_bytes
182
183 class PatchMbox(MIMENonMultipart):
184     patch_charset = 'utf-8'
185     def __init__(self, _text):
186         MIMENonMultipart.__init__(self, 'text', 'plain',
187                         **{'charset': self.patch_charset})
188         self.set_payload(_text.encode(self.patch_charset))
189         encode_7or8bit(self)
190
191 class Patch(models.Model):
192     project = models.ForeignKey(Project)
193     msgid = models.CharField(max_length=255)
194     name = models.CharField(max_length=255)
195     date = models.DateTimeField(default=datetime.datetime.now)
196     submitter = models.ForeignKey(Person)
197     delegate = models.ForeignKey(User, blank = True, null = True)
198     state = models.ForeignKey(State)
199     archived = models.BooleanField(default = False)
200     headers = models.TextField(blank = True)
201     content = models.TextField(null = True, blank = True)
202     pull_url = models.CharField(max_length=255, null = True, blank = True)
203     commit_ref = models.CharField(max_length=255, null = True, blank = True)
204     hash = HashField(null = True, blank = True)
205
206     def __unicode__(self):
207         return self.name
208
209     def comments(self):
210         return Comment.objects.filter(patch = self)
211
212     def save(self):
213         try:
214             s = self.state
215         except:
216             self.state = State.objects.get(ordering =  0)
217
218         if self.hash is None and self.content is not None:
219             self.hash = hash_patch(self.content).hexdigest()
220
221         super(Patch, self).save()
222
223     def is_editable(self, user):
224         if not user.is_authenticated():
225             return False
226
227         if self.submitter.user == user or self.delegate == user:
228             return True
229
230         return self.project.is_editable(user)
231
232     def filename(self):
233         fname_re = re.compile('[^-_A-Za-z0-9\.]+')
234         str = fname_re.sub('-', self.name)
235         return str.strip('-') + '.patch'
236
237     def mbox(self):
238         postscript_re = re.compile('\n-{2,3} ?\n')
239
240         comment = None
241         try:
242             comment = Comment.objects.get(patch = self, msgid = self.msgid)
243         except Exception:
244             pass
245
246         body = ''
247         if comment:
248             body = comment.content.strip() + "\n"
249
250         parts = postscript_re.split(body, 1)
251         if len(parts) == 2:
252             (body, postscript) = parts
253             body = body.strip() + "\n"
254             postscript = postscript.strip() + "\n"
255         else:
256             postscript = ''
257
258         for comment in Comment.objects.filter(patch = self) \
259                 .exclude(msgid = self.msgid):
260             body += comment.patch_responses()
261
262         if body:
263             body += '\n'
264
265         if postscript:
266             body += '---\n' + postscript.strip() + '\n'
267
268         if self.content:
269             body += '\n' + self.content
270
271         mail = PatchMbox(body)
272         mail['Subject'] = self.name
273         mail['Date'] = email.utils.formatdate(
274                         time.mktime(self.date.utctimetuple()))
275         mail['From'] = unicode(self.submitter)
276         mail['X-Patchwork-Id'] = str(self.id)
277         mail['Message-Id'] = self.msgid
278         mail.set_unixfrom('From patchwork ' + self.date.ctime())
279
280
281         copied_headers = ['To', 'Cc']
282         orig_headers = HeaderParser().parsestr(str(self.headers))
283         for header in copied_headers:
284             if header in orig_headers:
285                 mail[header] = orig_headers[header]
286
287         return mail
288
289     @models.permalink
290     def get_absolute_url(self):
291         return ('patchwork.views.patch.patch', (), {'patch_id': self.id})
292
293     class Meta:
294         verbose_name_plural = 'Patches'
295         ordering = ['date']
296         unique_together = [('msgid', 'project')]
297
298 class Comment(models.Model):
299     patch = models.ForeignKey(Patch)
300     msgid = models.CharField(max_length=255)
301     submitter = models.ForeignKey(Person)
302     date = models.DateTimeField(default = datetime.datetime.now)
303     headers = models.TextField(blank = True)
304     content = models.TextField()
305
306     response_re = re.compile( \
307             '^(Tested|Reviewed|Acked|Signed-off|Nacked|Reported)-by: .*$',
308             re.M | re.I)
309
310     def patch_responses(self):
311         return ''.join([ match.group(0) + '\n' for match in
312                                 self.response_re.finditer(self.content)])
313
314     class Meta:
315         ordering = ['date']
316         unique_together = [('msgid', 'patch')]
317
318 class Bundle(models.Model):
319     owner = models.ForeignKey(User)
320     project = models.ForeignKey(Project)
321     name = models.CharField(max_length = 50, null = False, blank = False)
322     patches = models.ManyToManyField(Patch, through = 'BundlePatch')
323     public = models.BooleanField(default = False)
324
325     def n_patches(self):
326         return self.patches.all().count()
327
328     def ordered_patches(self):
329         return self.patches.order_by('bundlepatch__order')
330
331     def append_patch(self, patch):
332         # todo: use the aggregate queries in django 1.1
333         orders = BundlePatch.objects.filter(bundle = self).order_by('-order') \
334                  .values('order')
335
336         if len(orders) > 0:
337             max_order = orders[0]['order']
338         else:
339             max_order = 0
340
341         # see if the patch is already in this bundle
342         if BundlePatch.objects.filter(bundle = self, patch = patch).count():
343             raise Exception("patch is already in bundle")
344
345         bp = BundlePatch.objects.create(bundle = self, patch = patch,
346                 order = max_order + 1)
347         bp.save()
348
349     class Meta:
350         unique_together = [('owner', 'name')]
351
352     def public_url(self):
353         if not self.public:
354             return None
355         site = Site.objects.get_current()
356         return 'http://%s%s' % (site.domain,
357                 reverse('patchwork.views.bundle.public',
358                         kwargs = {
359                                 'username': self.owner.username,
360                                 'bundlename': self.name
361                         }))
362
363     def mbox(self):
364         return '\n'.join([p.mbox().as_string(True)
365                         for p in self.ordered_patches()])
366
367 class BundlePatch(models.Model):
368     patch = models.ForeignKey(Patch)
369     bundle = models.ForeignKey(Bundle)
370     order = models.IntegerField()
371
372     class Meta:
373         unique_together = [('bundle', 'patch')]
374         ordering = ['order']
375
376 class EmailConfirmation(models.Model):
377     validity = datetime.timedelta(days = 30)
378     type = models.CharField(max_length = 20, choices = [
379                                 ('userperson', 'User-Person association'),
380                             ])
381     email = models.CharField(max_length = 200)
382     user = models.ForeignKey(User, null = True)
383     key = HashField()
384     date = models.DateTimeField(default = datetime.datetime.now)
385     active = models.BooleanField(default = True)
386
387     def deactivate(self):
388         self.active = False
389         self.save()
390
391     def is_valid(self):
392         return self.date + self.validity > datetime.datetime.now()
393
394     def save(self):
395         max = 1 << 32
396         if self.key == '':
397             str = '%s%s%d' % (self.user, self.email, random.randint(0, max))
398             self.key = self._meta.get_field('key').construct(str).hexdigest()
399         super(EmailConfirmation, self).save()
400
401