models.py 12.9 KB
Newer Older
Jeremy Kerr's avatar
Jeremy Kerr committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# Patchwork - automated patch tracking system
# Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
#
# This file is part of the Patchwork package.
#
# Patchwork is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Patchwork is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Patchwork; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
24
from django.conf import settings
Jeremy Kerr's avatar
Jeremy Kerr committed
25
from patchwork.parser import hash_patch
Jeremy Kerr's avatar
Jeremy Kerr committed
26 27 28 29

import re
import datetime, time
import random
30

Jeremy Kerr's avatar
Jeremy Kerr committed
31 32
class Person(models.Model):
    email = models.CharField(max_length=255, unique = True)
33
    name = models.CharField(max_length=255, null = True, blank = True)
34 35
    user = models.ForeignKey(User, null = True, blank = True,
            on_delete = models.SET_NULL)
Jeremy Kerr's avatar
Jeremy Kerr committed
36

37
    def __unicode__(self):
Jeremy Kerr's avatar
Jeremy Kerr committed
38
        if self.name:
39
            return u'%s <%s>' % (self.name, self.email)
Jeremy Kerr's avatar
Jeremy Kerr committed
40 41 42 43
        else:
            return self.email

    def link_to_user(self, user):
44
        self.name = user.profile.name()
Jeremy Kerr's avatar
Jeremy Kerr committed
45 46 47 48 49 50 51 52 53 54
        self.user = user

    class Meta:
        verbose_name_plural = 'People'

class Project(models.Model):
    linkname = models.CharField(max_length=255, unique=True)
    name = models.CharField(max_length=255, unique=True)
    listid = models.CharField(max_length=255, unique=True)
    listemail = models.CharField(max_length=200)
Simo Sorce's avatar
Simo Sorce committed
55 56 57
    web_url = models.CharField(max_length=2000, blank=True)
    scm_url = models.CharField(max_length=2000, blank=True)
    webscm_url = models.CharField(max_length=2000, blank=True)
Jeremy Kerr's avatar
Jeremy Kerr committed
58
    send_notifications = models.BooleanField(default=False)
Jeremy Kerr's avatar
Jeremy Kerr committed
59

60
    def __unicode__(self):
Jeremy Kerr's avatar
Jeremy Kerr committed
61 62
        return self.name

63 64 65
    def is_editable(self, user):
        if not user.is_authenticated():
            return False
66
        return self in user.profile.maintainer_projects.all()
67

68 69 70 71
    class Meta:
        ordering = ['linkname']


Jeremy Kerr's avatar
Jeremy Kerr committed
72
class UserProfile(models.Model):
73
    user = models.OneToOneField(User, unique = True, related_name='profile')
74
    primary_project = models.ForeignKey(Project, null = True, blank = True)
Jeremy Kerr's avatar
Jeremy Kerr committed
75 76 77 78 79 80 81 82 83 84 85
    maintainer_projects = models.ManyToManyField(Project,
            related_name = 'maintainer_project')
    send_email = models.BooleanField(default = False,
            help_text = 'Selecting this option allows patchwork to send ' +
                'email on your behalf')
    patches_per_page = models.PositiveIntegerField(default = 100,
            null = False, blank = False,
            help_text = 'Number of patches to display per page')

    def name(self):
        if self.user.first_name or self.user.last_name:
86
            names = filter(bool, [self.user.first_name, self.user.last_name])
87
            return u' '.join(names)
Jeremy Kerr's avatar
Jeremy Kerr committed
88 89 90 91
        return self.user.username

    def contributor_projects(self):
        submitters = Person.objects.filter(user = self.user)
92 93 94 95
        return Project.objects.filter(id__in =
                                        Patch.objects.filter(
                                            submitter__in = submitters)
                                        .values('project_id').query)
Jeremy Kerr's avatar
Jeremy Kerr committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

    def sync_person(self):
        pass

    def n_todo_patches(self):
        return self.todo_patches().count()

    def todo_patches(self, project = None):

        # filter on project, if necessary
        if project:
            qs = Patch.objects.filter(project = project)
        else:
            qs = Patch.objects

        qs = qs.filter(archived = False) \
             .filter(delegate = self.user) \
113 114
             .filter(state__in =
                     State.objects.filter(action_required = True)
Jeremy Kerr's avatar
Jeremy Kerr committed
115 116 117
                         .values('pk').query)
        return qs

118
    def __unicode__(self):
Jeremy Kerr's avatar
Jeremy Kerr committed
119 120
        return self.name()

121 122
def _user_saved_callback(sender, created, instance, **kwargs):
    try:
123
        profile = instance.profile
124 125
    except UserProfile.DoesNotExist:
        profile = UserProfile(user = instance)
126 127
    profile.save()

128
models.signals.post_save.connect(_user_saved_callback, sender = User)
129

Jeremy Kerr's avatar
Jeremy Kerr committed
130 131 132 133 134
class State(models.Model):
    name = models.CharField(max_length = 100)
    ordering = models.IntegerField(unique = True)
    action_required = models.BooleanField(default = True)

135
    def __unicode__(self):
Jeremy Kerr's avatar
Jeremy Kerr committed
136 137 138 139 140
        return self.name

    class Meta:
        ordering = ['ordering']

Jeremy Kerr's avatar
Jeremy Kerr committed
141
class HashField(models.CharField):
Jeremy Kerr's avatar
Jeremy Kerr committed
142 143 144 145
    __metaclass__ = models.SubfieldBase

    def __init__(self, algorithm = 'sha1', *args, **kwargs):
        self.algorithm = algorithm
Nate Case's avatar
Nate Case committed
146 147
        try:
            import hashlib
Jeremy Kerr's avatar
Jeremy Kerr committed
148 149 150
            def _construct(string = ''):
                return hashlib.new(self.algorithm, string)
            self.construct = _construct
151
            self.n_bytes = len(hashlib.new(self.algorithm).hexdigest())
Nate Case's avatar
Nate Case committed
152
        except ImportError:
Jeremy Kerr's avatar
Jeremy Kerr committed
153 154 155
            modules = { 'sha1': 'sha', 'md5': 'md5'}

            if algorithm not in modules.keys():
Nate Case's avatar
Nate Case committed
156
                raise NameError("Unknown algorithm '%s'" % algorithm)
Jeremy Kerr's avatar
Jeremy Kerr committed
157 158 159 160

            self.construct = __import__(modules[algorithm]).new

        self.n_bytes = len(self.construct().hexdigest())
Jeremy Kerr's avatar
Jeremy Kerr committed
161

162
        kwargs['max_length'] = self.n_bytes
Jeremy Kerr's avatar
Jeremy Kerr committed
163 164
        super(HashField, self).__init__(*args, **kwargs)

165
    def db_type(self, connection=None):
166
        return 'char(%d)' % self.n_bytes
Jeremy Kerr's avatar
Jeremy Kerr committed
167

168 169 170
def get_default_initial_patch_state():
    return State.objects.get(ordering=0)

Jeremy Kerr's avatar
Jeremy Kerr committed
171 172
class Patch(models.Model):
    project = models.ForeignKey(Project)
173
    msgid = models.CharField(max_length=255)
Jeremy Kerr's avatar
Jeremy Kerr committed
174 175 176 177
    name = models.CharField(max_length=255)
    date = models.DateTimeField(default=datetime.datetime.now)
    submitter = models.ForeignKey(Person)
    delegate = models.ForeignKey(User, blank = True, null = True)
178
    state = models.ForeignKey(State, default=get_default_initial_patch_state)
Jeremy Kerr's avatar
Jeremy Kerr committed
179 180
    archived = models.BooleanField(default = False)
    headers = models.TextField(blank = True)
181 182
    content = models.TextField(null = True, blank = True)
    pull_url = models.CharField(max_length=255, null = True, blank = True)
Jeremy Kerr's avatar
Jeremy Kerr committed
183
    commit_ref = models.CharField(max_length=255, null = True, blank = True)
184
    hash = HashField(null = True, blank = True)
Jeremy Kerr's avatar
Jeremy Kerr committed
185

186
    def __unicode__(self):
Jeremy Kerr's avatar
Jeremy Kerr committed
187 188 189
        return self.name

    def comments(self):
190
        return Comment.objects.filter(patch = self)
Jeremy Kerr's avatar
Jeremy Kerr committed
191 192

    def save(self):
193
        try:
Jeremy Kerr's avatar
Jeremy Kerr committed
194 195 196
            s = self.state
        except:
            self.state = State.objects.get(ordering =  0)
Jeremy Kerr's avatar
Jeremy Kerr committed
197

198
        if self.hash is None and self.content is not None:
Jeremy Kerr's avatar
Jeremy Kerr committed
199
            self.hash = hash_patch(self.content).hexdigest()
Jeremy Kerr's avatar
Jeremy Kerr committed
200

Jeremy Kerr's avatar
Jeremy Kerr committed
201 202 203 204 205 206 207 208 209
        super(Patch, self).save()

    def is_editable(self, user):
        if not user.is_authenticated():
            return False

        if self.submitter.user == user or self.delegate == user:
            return True

210
        return self.project.is_editable(user)
Jeremy Kerr's avatar
Jeremy Kerr committed
211 212 213 214 215 216 217 218 219 220 221 222 223

    def filename(self):
        fname_re = re.compile('[^-_A-Za-z0-9\.]+')
        str = fname_re.sub('-', self.name)
        return str.strip('-') + '.patch'

    @models.permalink
    def get_absolute_url(self):
        return ('patchwork.views.patch.patch', (), {'patch_id': self.id})

    class Meta:
        verbose_name_plural = 'Patches'
        ordering = ['date']
224
        unique_together = [('msgid', 'project')]
Jeremy Kerr's avatar
Jeremy Kerr committed
225 226 227

class Comment(models.Model):
    patch = models.ForeignKey(Patch)
228
    msgid = models.CharField(max_length=255)
Jeremy Kerr's avatar
Jeremy Kerr committed
229 230 231 232 233
    submitter = models.ForeignKey(Person)
    date = models.DateTimeField(default = datetime.datetime.now)
    headers = models.TextField(blank = True)
    content = models.TextField()

234 235 236
    response_re = re.compile( \
            '^(Tested|Reviewed|Acked|Signed-off|Nacked|Reported)-by: .*$',
            re.M | re.I)
237 238

    def patch_responses(self):
239
        return ''.join([ match.group(0) + '\n' for match in
240 241
                                self.response_re.finditer(self.content)])

Jeremy Kerr's avatar
Jeremy Kerr committed
242 243
    class Meta:
        ordering = ['date']
244
        unique_together = [('msgid', 'patch')]
Jeremy Kerr's avatar
Jeremy Kerr committed
245 246 247 248 249

class Bundle(models.Model):
    owner = models.ForeignKey(User)
    project = models.ForeignKey(Project)
    name = models.CharField(max_length = 50, null = False, blank = False)
250
    patches = models.ManyToManyField(Patch, through = 'BundlePatch')
Jeremy Kerr's avatar
Jeremy Kerr committed
251 252 253 254 255
    public = models.BooleanField(default = False)

    def n_patches(self):
        return self.patches.all().count()

Jeremy Kerr's avatar
Jeremy Kerr committed
256
    def ordered_patches(self):
Guilherme Salgado's avatar
Guilherme Salgado committed
257
        return self.patches.order_by('bundlepatch__order')
Jeremy Kerr's avatar
Jeremy Kerr committed
258

259 260
    def append_patch(self, patch):
        # todo: use the aggregate queries in django 1.1
Jeremy Kerr's avatar
Jeremy Kerr committed
261 262 263 264 265 266 267 268 269 270 271
        orders = BundlePatch.objects.filter(bundle = self).order_by('-order') \
                 .values('order')

        if len(orders) > 0:
            max_order = orders[0]['order']
        else:
            max_order = 0

        # see if the patch is already in this bundle
        if BundlePatch.objects.filter(bundle = self, patch = patch).count():
            raise Exception("patch is already in bundle")
272

Jeremy Kerr's avatar
Jeremy Kerr committed
273 274
        bp = BundlePatch.objects.create(bundle = self, patch = patch,
                order = max_order + 1)
275 276
        bp.save()

Jeremy Kerr's avatar
Jeremy Kerr committed
277 278 279 280 281 282 283 284
    class Meta:
        unique_together = [('owner', 'name')]

    def public_url(self):
        if not self.public:
            return None
        site = Site.objects.get_current()
        return 'http://%s%s' % (site.domain,
285
                reverse('patchwork.views.bundle.bundle',
Jeremy Kerr's avatar
Jeremy Kerr committed
286 287 288 289 290
                        kwargs = {
                                'username': self.owner.username,
                                'bundlename': self.name
                        }))

291 292 293 294 295 296 297
    @models.permalink
    def get_absolute_url(self):
        return ('patchwork.views.bundle.bundle', (), {
                                'username': self.owner.username,
                                'bundlename': self.name,
                            })

298 299 300 301 302 303
class BundlePatch(models.Model):
    patch = models.ForeignKey(Patch)
    bundle = models.ForeignKey(Bundle)
    order = models.IntegerField()

    class Meta:
Jeremy Kerr's avatar
Jeremy Kerr committed
304 305
        unique_together = [('bundle', 'patch')]
        ordering = ['order']
306

307
class EmailConfirmation(models.Model):
308
    validity = datetime.timedelta(days = settings.CONFIRMATION_VALIDITY_DAYS)
309 310
    type = models.CharField(max_length = 20, choices = [
                                ('userperson', 'User-Person association'),
311
                                ('registration', 'Registration'),
Jeremy Kerr's avatar
Jeremy Kerr committed
312
                                ('optout', 'Email opt-out'),
313
                            ])
314
    email = models.CharField(max_length = 200)
315
    user = models.ForeignKey(User, null = True)
316
    key = HashField()
317
    date = models.DateTimeField(default = datetime.datetime.now)
318 319
    active = models.BooleanField(default = True)

320
    def deactivate(self):
321
        self.active = False
322
        self.save()
323

324 325 326
    def is_valid(self):
        return self.date + self.validity > datetime.datetime.now()

327 328 329 330 331
    def save(self):
        max = 1 << 32
        if self.key == '':
            str = '%s%s%d' % (self.user, self.email, random.randint(0, max))
            self.key = self._meta.get_field('key').construct(str).hexdigest()
332
        super(EmailConfirmation, self).save()
333

Jeremy Kerr's avatar
Jeremy Kerr committed
334 335
class EmailOptout(models.Model):
    email = models.CharField(max_length = 200, primary_key = True)
336

Jeremy Kerr's avatar
Jeremy Kerr committed
337 338
    def __unicode__(self):
        return self.email
339

Jeremy Kerr's avatar
Jeremy Kerr committed
340 341 342 343 344
    @classmethod
    def is_optout(cls, email):
        email = email.lower().strip()
        return cls.objects.filter(email = email).count() > 0

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
class PatchChangeNotification(models.Model):
    patch = models.ForeignKey(Patch, primary_key = True)
    last_modified = models.DateTimeField(default = datetime.datetime.now)
    orig_state = models.ForeignKey(State)

def _patch_change_callback(sender, instance, **kwargs):
    # we only want notification of modified patches
    if instance.pk is None:
        return

    if instance.project is None or not instance.project.send_notifications:
        return

    try:
        orig_patch = Patch.objects.get(pk = instance.pk)
    except Patch.DoesNotExist:
        return

    # If there's no interesting changes, abort without creating the
    # notification
    if orig_patch.state == instance.state:
        return

    notification = None
    try:
        notification = PatchChangeNotification.objects.get(patch = instance)
    except PatchChangeNotification.DoesNotExist:
        pass

    if notification is None:
        notification = PatchChangeNotification(patch = instance,
                                               orig_state = orig_patch.state)

    elif notification.orig_state == instance.state:
        # If we're back at the original state, there is no need to notify
        notification.delete()
        return

    notification.last_modified = datetime.datetime.now()
    notification.save()

models.signals.pre_save.connect(_patch_change_callback, sender = Patch)