Source

xmppforum / snapboard / models.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
import logging
from datetime import datetime
import time

from django.conf import settings
from django.contrib.auth.models import User, AnonymousUser
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.db import models, connection
from django.db.models import signals, Q
from django.dispatch import dispatcher
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache

from treebeard import mp_tree

# Monkey-patching no-copying way:
def get_rly_annotated_list(self):
    return super(mp_tree.MP_Node, self).get_annotated_list(self)

def get_adv_annotated_list(self):
    """
    Gets an annotated list from a tree branch, adding some advanced info
    along the way.
    """
    result, info = [], {}
    start_depth, prev_depth, ddepth, rdepth = (None, -1, None, None)
    prev_siblings = []  # list of possible previous (or last) siblings

    for node in self.get_tree(self):
        depth = node.get_depth()
        if start_depth is None:
            start_depth = depth
        ddepth = depth - prev_depth  # depth difference (step)
        rdepth = depth - start_depth  # relative depth.
        open = (ddepth > 0)  # (depth > prev_depth)
        if open:
            # Ensure we have elements up to necessary depth.
            if len(prev_siblings) < rdepth + 1:
                prev_siblings.append(None)
        # shouldn't be needed, but can:
        #prev_siblings += [None] * (rdepth - len(prev_siblings) + 1)
        
        if prev_siblings[rdepth] == None:  # it's first here.
            prev_siblings[rdepth] = node
        else:  # ... that one wasn't last.
            prev_siblings[rdepth].next_sibling = node
            prev_siblings[rdepth] = node

        # Slightly inappropriate, but might be better than to use info.
        node.next_sibling = None  # might be reassigned later.
        
        if ddepth < 0:  # depth < prev_depth:
            info['close'] = range(0, -ddepth)
            # previous *deeper* nodes are not possible siblings.
            for v in range(prev_depth - start_depth, rdepth, -1):
                prev_siblings[v] = None
        # `is_last_sibling = not next_sibling`

        info = {'open': open, 'close': [], 'level': rdepth}
        result.append((node, info,))
        prev_depth = depth
    if start_depth > 0:
        info['close'] = range(0, prev_depth - start_depth + 1)
    return result

def get_flathelper_list(self):
    """ Adds few more information to annotated list (retreived from
    specified node) to display "straight" branches as flat """
    # ! branched from revision 250:310d63a10571 (tag 'flatpost'), minimized.
    annotated = get_adv_annotated_list(self)
    prev_node, prev_info = annotated[0]
    def is_alone(n, i):
        """ "node is the only direct child" (no siblings). depends on the
        data computed with later nodes in get_adv_anno... """
        return (getattr(n, "next_sibling", False) is None and i.get('open'))
    # Expecting to change mutable node and info in the list.
    for node, info in annotated[1:]:  # don't process the root node.
        if is_alone(node, info):
            node.is_flat = True
    return annotated

# Provide many various additions.
mp_tree.MP_Node.get_annotated_list = get_rly_annotated_list
mp_tree.MP_Node.get_adv_annotated_list = get_adv_annotated_list
mp_tree.MP_Node.get_flathelper_list = get_flathelper_list


from snapboard import managers
from snapboard.middleware import threadlocals

__all__ = [
    'SNAP_PREFIX', 'SNAP_MEDIA_PREFIX', 'SNAP_POST_FILTER',
    'NOBODY', 'ALL', 'USERS', 'CUSTOM', 'PERM_CHOICES', 'PERM_CHOICES_RESTRICTED',
    'PermissionError', 'is_user_banned', 'is_ip_banned',
    'Category', 'Invitation', 'Group', 'Thread', 'Post', 'Moderator',
    'WatchList', 'AbuseReport', 'UserSettings', 'IPBan', 'UserBan',
    'XMPPContact',
    ]

_log = logging.getLogger('snapboard.models')

SNAP_PREFIX = getattr(settings, 'SNAP_PREFIX', '/snapboard')
SNAP_MEDIA_PREFIX = getattr(settings, 'SNAP_MEDIA_PREFIX',
        getattr(settings, 'MEDIA_URL', '') + '/snapboard')
SNAP_POST_FILTER = getattr(settings, 'SNAP_POST_FILTER', 'markdown').lower()

NOBODY = 0
ALL = 1
USERS = 2
CUSTOM = 3

PERM_CHOICES = (
    (NOBODY, _('Nobody')),
    (ALL, _('All')),
    (USERS, _('Users')),
    (CUSTOM, _('Custom')),
)

PERM_CHOICES_RESTRICTED = (
    (NOBODY, _('Nobody')),
    (ALL, _('All')),
    (USERS, _('Users')),
    (CUSTOM, _('Custom')),
)


class PermissionError(PermissionDenied):
    '''
    Raised when a user tries to perform a forbidden operation, as per the
    permissions defined by Category objects.
    '''
    pass


def is_user_banned(user):
    return user.id in settings.SNAP_BANNED_USERS


def is_ip_banned(ip):
    return ip in settings.SNAP_BANNED_IPS


class Group(models.Model):
    '''
    User-administerable group, be used to assign permissions to possibly
    several users.

    Administrators of the group need to be explicitely added to the users
    list to be considered members.
    '''

    name = models.CharField(_('name'), max_length=36)
    users = models.ManyToManyField(User, verbose_name=_('users'), related_name='sb_member_of_group_set')
    admins = models.ManyToManyField(User, verbose_name=_('admins'), related_name='sb_admin_of_group_set')

    class Meta:
        verbose_name = _('group')
        verbose_name_plural = _('groups')

    def __unicode__(self):
        return _('Group "%s"') % self.name

    def has_user(self, user):
        return self.users.filter(pk=user.pk).count() != 0

    def has_admin(self, user):
        return self.admins.filter(pk=user.pk).count() != 0


class Invitation(models.Model):
    '''
    Group admins create invitations for users to join their group.

    Staff with site admin access can assign users to groups without
    restriction.
    '''

    group = models.ForeignKey(Group, verbose_name=_('group'), related_name='sb_invitation_set')
    sent_by = models.ForeignKey(User, verbose_name=_('sent by'), related_name='sb_sent_invitation_set')
    sent_to = models.ForeignKey(User, verbose_name=_('sent to'), related_name='sb_received_invitation_set')
    sent_date = models.DateTimeField(_('sent date'), auto_now_add=True)
    response_date = models.DateTimeField(_('response date'), blank=True, null=True)
    accepted = models.NullBooleanField(_('accepted'), blank=True, null=True)

    class Meta:
        verbose_name = _('invitation')
        verbose_name_plural = _('invitations')

    def __unicode__(self):
        return _('Invitation for "%(group)s" sent by %(sent_by)s to %(sent_to)s.') % {
                'group': self.group.name,
                'sent_by': self.sent_by,
                'sent_to': self.sent_to }

    def notify_received(instance, **kwargs):
        '''
        Notifies of new invitations.
        '''
        if instance.accepted is None:
            send_notifications(
                [instance.sent_to],
                'group_invitation_received',
                {'invitation': instance})
    notify_received = staticmethod(notify_received)

    def notify_cancelled(instance, **kwargs):
        '''
        Notifies of cancelled invitations.
        '''
        if instance.accepted is None:
            send_notifications(
                [instance.sent_to],
                'group_invitation_cancelled',
                {'invitation': instance})
    notify_cancelled = staticmethod(notify_cancelled)

signals.post_save.connect(Invitation.notify_received, sender=Invitation)
signals.pre_delete.connect(Invitation.notify_cancelled, sender=Invitation)


class Category(models.Model):

    label = models.CharField(max_length=32, verbose_name=_('label'))

    view_perms = models.PositiveSmallIntegerField(_('view permission'),
        choices=PERM_CHOICES, default=ALL,
        help_text=_('Limits the category\'s visibility.'))
    read_perms = models.PositiveSmallIntegerField(_('read permission'),
        choices=PERM_CHOICES, help_text=_('Limits the ability to read the '\
        'category\'s contents.'), default=ALL)
    post_perms = models.PositiveSmallIntegerField(_('post permission'),
        choices=PERM_CHOICES_RESTRICTED, help_text=_('Limits the ability to '\
        'post in the category.'), default=USERS)
    new_thread_perms = models.PositiveSmallIntegerField(
        _('create thread permission'), choices=PERM_CHOICES_RESTRICTED,
        help_text=_('Limits the ability to create new threads in the '\
        'category. Only users with permission to post can create new threads,'\
        'unless a group is specified.'), default=USERS)

    view_group = models.ForeignKey(Group, verbose_name=_('view group'),
        blank=True, null=True, related_name='can_view_category_set')
    read_group = models.ForeignKey(Group, verbose_name=_('read group'),
        blank=True, null=True, related_name='can_read_category_set')
    post_group = models.ForeignKey(Group, verbose_name=_('post group'),
        blank=True, null=True, related_name='can_post_category_set')
    new_thread_group = models.ForeignKey(Group, verbose_name=_('create thread group'),
        blank=True, null=True, related_name='can_create_thread_category_set')

    objects = managers.CategoryManager()    # adds thread_count

    def __unicode__(self):
        return self.label

    def moderators(self):
        mods = Moderator.objects.filter(category=self.id)
        if mods.count() > 0:
            return ', '.join([m.user.username for m in mods])
        else:
            return None

    def can_view(self, user):
        flag = False
        if self.view_perms == ALL:
            flag = True
        elif self.view_perms == USERS:
            flag = user.is_authenticated()
        elif self.view_perms == CUSTOM:
            flag = user.is_superuser or (user.is_authenticated() and self.view_group.has_user(user))
        return flag

    def can_read(self, user):
        flag = False
        if self.read_perms == ALL:
            flag = True
        elif self.read_perms == USERS:
            flag = user.is_authenticated()
        elif self.read_perms == CUSTOM:
            flag = user.is_superuser or (user.is_authenticated() and self.read_group.has_user(user))
        return flag

    def can_post(self, user):
        flag = False
        if self.post_perms == ALL:
            flag = True # Anonymous supported.
        elif self.post_perms == USERS:
            flag = user.is_authenticated() and not getattr(user, "really_anonymous", False)
        elif self.post_perms == CUSTOM:
            flag = user.is_superuser or (user.is_authenticated() and self.post_group.has_user(user))
        return flag

    def can_create_thread(self, user):
        flag = False
        if self.new_thread_perms == ALL:
            flag = True # Anonymous supported.
        if self.new_thread_perms == USERS:
            flag = user.is_authenticated() and not getattr(user, "really_anonymous", False)
        elif self.new_thread_perms == CUSTOM:
            flag = user.is_superuser or (user.is_authenticated() and self.new_thread_group.has_user(user))
        return flag

    class Meta:
        verbose_name = _('category')
        verbose_name_plural = _('categories')


class Moderator(models.Model):
    category = models.ForeignKey(Category, verbose_name=_('category'))
    user = models.ForeignKey(User, verbose_name=_('user'), related_name='sb_moderator_set')

    def __unicode__(self):
        return u'%s' % (self.user.username,)

    class Meta:
        verbose_name = _('moderator')
        verbose_name_plural = _('moderators')


class Thread(models.Model):
    subject = models.CharField(max_length=160, verbose_name=_('subject'))
    category = models.ForeignKey(Category, verbose_name=_('category'))

    closed = models.BooleanField(default=False, verbose_name=_('closed'))

    # Category sticky - will show up at the top of category listings.
    csticky = models.BooleanField(default=False, verbose_name=_('category sticky'))

    # Global sticky - will show up at the top of home listing.
    gsticky = models.BooleanField(default=False, verbose_name=_('global sticky'))

    objects = models.Manager()  # needs to be explicit due to below
    view_manager = managers.ThreadManager()

    def __unicode__(self):
        return self.subject

    def get_url(self):
        return reverse('snapboard_thread', args=(self.id,))

    class Meta:
        verbose_name = _('thread')
        verbose_name_plural = _('threads')

    def count_posts(self, user, before=None):
        '''
        Returns the number of visible posts in the thread or, if ``before`` is
        a Post object, the number of visible posts in the thread that are
        older.
        '''
        # This partly does what Thread.objects.get_query_set() does, except
        # it takes into account the user and therefore knows what posts
        # are visible to him
        qs = self.post_set.filter(revision=None)
        if user.is_authenticated():
            qs = qs.filter(Q(user=user) | Q(is_private=False) | Q(private__exact=user))
        if not getattr(user, 'is_staff', False):
            qs = qs.exclude(censor=True)
        if before:
            qs.filter(date__lt=before.date)
        return qs.count()


class Post(mp_tree.MP_Node):
    """
    Post objects store information about revisions.

    Both forward and backward revisions are stored as ForeignKeys.
    """
    # blank=True to get admin to work when the user field is missing
    user = models.ForeignKey(User, editable=False, blank=True, default=None,
            verbose_name=_('user'), related_name='sb_created_posts_set')

    thread = models.ForeignKey(Thread, verbose_name=_('thread'))
    text = models.TextField(verbose_name=_('text'))
    date = models.DateTimeField(editable=False, auto_now_add=True, verbose_name=_('date'))
    ip = models.IPAddressField(verbose_name=_('ip address'), blank=True, null=True)

    private = models.ManyToManyField(User,
            related_name="sb_private_posts_set", null=True, verbose_name=_('private recipients'))
    # The 'private message' status is denormalized by the ``is_private`` flag.
    # It's currently quite hard to do the denormalization automatically
    # If ManyRelatedManager._add_items() fired some signal on update, it would help.
    # Right now it's up to the code that changes the 'private' many-to-many field to
    # change ``is_private``.
    is_private = models.BooleanField(_('private'), default=False, editable=False)

    # (null or ID of post - most recent revision is always a diff of previous)
    odate = models.DateTimeField(editable=False, null=True)
    revision = models.ForeignKey("self", related_name="rev",
            editable=False, null=True, blank=True)
    previous = models.ForeignKey("self", related_name="prev",
            editable=False, null=True, blank=True)

    # (boolean set by mod.; true if abuse report deemed false)
    censor = models.BooleanField(default=False, verbose_name=_('censored'))  # moderator level access
    freespeech = models.BooleanField(default=False, verbose_name=_('protected'))  # superuser level access

    #objects = models.Manager()  # needs to be explicit due to below
    #view_manager = managers.PostManager()
    
    # ! Tree
    # ! Incompatible with date.auto_now_add=True
    #node_order_by = ['date']
    
    # ! get_descendants_group_count could be useful.
    
    # IDs. id_form_X <-> from_id_X
    #      (  String <-> Post  )
    def id_form_a(self):
        # Simple post number.
        return str(self.id)
    
    @classmethod
    def from_id_a(cls, ida):
        # throws ValueError if int() fails.
        # also, it might not exist.
        return cls.objects.get(id=int(ida))

    def id_form_b(self):
        chunks = lambda l, n: [l[i:i+n] for i in xrange(0, len(l), n)]
        #pad = lambda x: '%s%s' % ('0' * (Post.steplen - len(x)), x)
        l_str2int = lambda x: self._str2int(x)
        c = chunks(self.path, self.steplen)
        return "%s/%s(%d)" % (l_str2int(c[0]),
          ".".join([str(l_str2int(i)) for i in c[1:]]), len(c)-1)
        # ! ? better:
        #c = chunks(self.path[self.steplen:], self.steplen)
        #return "%s/%s(%d)" % (self.thread_id,
        #  ".".join([str(l_str2int(i)) for i in c]), len(c))

    @classmethod
    def from_id_b(cls, idb):
        # No format checking. Catch stuff.
        l_int2str = lambda x: cls._int2str(x).rjust(cls.steplen, '0')
        # disregard `(n)` part of id if it's there.
        idb2 = idb.split('(', 1)[0]
        threadid, npath = idb2.split('/', 1)
        # ! ? better:
        # thread_path = Post.objects.get(thread=threadid, depth=1).path
        anpath = [threadid] + npath.split(".")
        tpath = "".join([l_int2str(int(i)) for i in anpath])
        return cls.objects.get(path=tpath)

    # ! consider setting `steplen = 3` - for better maxwidth/maxdepth ratio.
    steplen = 3  # better maxwidth/maxdepth ratio

    def save(self, force_insert=False, force_update=False):
        _log.debug('user = %s, ip = %s' % (threadlocals.get_current_ip(),
            threadlocals.get_current_user()))

        # hack to disallow admin setting arbitrary users to posts
        if getattr(self, 'user_id', None) is None:
            self.user_id = threadlocals.get_current_user().id

        # disregard any modifications to ip address
        self.ip = threadlocals.get_current_ip()

        if self.previous is not None:
            self.odate = self.previous.odate
        elif not self.id:
            # only do the following on creation, not modification
            self.odate = datetime.now()
        super(Post, self).save(force_insert, force_update)

    def management_save(self):
        if self.previous is not None:
            self.odate = self.previous.odate
        elif not self.id:
            # only do the following on creation, not modification
            self.odate = datetime.now()
        super(Post, self).save(False, False)

    def notify(self, **kwargs):
        if not self.previous:
            all_recipients = set()
            # ! Likely, `private` should be moved to the thread-level.
            #if self.is_private:
            #    recipients = set(self.private.all())
            #    if recipients:
            #        send_notifications(
            #            recipients,
            #            'private_post_received',
            #            {'post': self}
            #        )
            #        all_recipients = all_recipients.union(recipients)
            posttree = self.get_ancestors()
            #recipients = set((wl.user for wl in WatchList.objects.filter(thread=self.thread) if wl.user not in all_recipients))
            recipients = []
            resources = {}  # Special feature, ha.
            for wl in WatchList.objects.select_related(depth=2).filter(
             post__in=posttree).order_by("snapboard_post.depth"):
                # Sorting is required to override resource requirement with
                # the one of the deepest post.
                if wl.user not in all_recipients:
                    # ! Actually, check post.user != wl.user.  Probably.
                    recipients.append(wl.user)
                if wl.xmppresource:
                    resources[wl.user] = wl.xmppresource
                else:
                    # we're sending it to a bare jid. Allow simple
                    # resourcification without specifying post.
                    cache.set('nt_%s'%wl.user.username, [self.id,
                      time.time()])
            recipients = set(recipients)
            if recipients:
                send_notifications(
                    recipients,
                    'new_post_in_watched_thread',
                    extra_context={'post': self},
                    xmppresources=resources
                )
                all_recipients = all_recipients.union(recipients)

    def get_absolute_url(self):
        return reverse('snapboard_locate_post', args=(self.id,))

    def get_edit_form(self):
        from forms import PostForm
        return PostForm(initial={'post':self.text})

    def __unicode__(self):
        return u''.join( (u'#', unicode(self.id), u': ', unicode(self.user), u' @ ',
         unicode(self.date)) )

    class Meta:
        verbose_name = _('post')
        verbose_name_plural = _('posts')

# Signals make it hard to handle the notification of private recipients
#if notification:
#    signals.post_save.connect(Post.notify, sender=Post)


class AbuseReport(models.Model):
    '''
    When an abuse report is filed by a registered User, the post is listed
    in this table.

    If the abuse report is rejected as false, the post.freespeech flag can be
    set to disallow further abuse reports on said thread.
    '''
    post = models.ForeignKey(Post, verbose_name=_('post'), related_name='sb_abusereport_set')
    submitter = models.ForeignKey(User, verbose_name=_('submitter'), related_name='sb_abusereport_set')

    class Meta:
        verbose_name = _('abuse report')
        verbose_name_plural = _('abuse reports')
        unique_together = (('post', 'submitter'),)


class WatchList(models.Model):
    """
    Keep track of who is watching what post tree.  Notify on change (sidebar).
    Note thet this can be implemented as many_to_many field on post (looks
    like it's what it actally is anyway), plus (probably) a
    notification-level abstract XMPP resource distinction.
    """
    user = models.ForeignKey(User, verbose_name=_('user'),
      related_name='sb_watchlist')
    post = models.ForeignKey(Post, verbose_name=_('post'),
      related_name='sb_watchinglist')
    # This can be implemented for all notification types, though:
    xmppresource = models.CharField(max_length=80, null=True, blank=True,
      verbose_name=_('xmpp resource'))

    class Meta:
        verbose_name = _('Watched post')
        verbose_name_plural = _('Watched posts')

    def __unicode__(self):
        return _('%s\'s watch of post %s') % (self.user, self.post.id)


class UserSettings(models.Model):
    '''
    User data tied to user accounts from the auth module.

    Real name, email, and date joined information are stored in the built-in
    auth module.

    After logging in, save these values in a session variable.
    '''
    user = models.OneToOneField(User, unique=True,
            verbose_name=_('user'), related_name='sb_usersettings')
    ppp = models.IntegerField(
            choices = ((5, '5'), (10, '10'), (20, '20'), (50, '50')),
            default = 4,
            help_text = _('Posts per page'), verbose_name=_('posts per page'))
    tpp = models.IntegerField(
            choices = ((5, '5'), (10, '10'), (20, '20'), (50, '50')),
            default = 20,
            help_text = _('Threads per page'), verbose_name=_('threads per page'))
    jid = models.EmailField(
            unique = True, blank = True, null = True,
            help_text = _('Jabber ID'), verbose_name=_('jid'))
    disable_xmpp_xhtml = models.BooleanField(
            default = False,
            help_text = _('Do not send XHTML subpart (formatted message)'),
            verbose_name = _("disable xhtml formatting"))
    #skip_xmpp_body = models.BooleanField(
    #        default = False,
    #        help_text = _('Do not send non-XHTML body '\
    #        '(fallback/unformatted). Do not set this with previous '\
    #        'setting together'),
    #        verbose_name = _("disable non-xhtml body"))
    disable_xmpp_images = models.BooleanField(
            default = True,  # Not much clients support them properly
            help_text = _("Do not send XHTML img tags."),
            verbose_name = _("disable xhtml images"))
#    notify_email = models.BooleanField(default=False, blank=True,
#            help_text = "Email notifications for watched discussions.", verbose_name=_('notify'))
    reverse_posts = models.BooleanField(
            default=False,
            help_text = _('Display newest posts first.'), verbose_name=_('new posts first'))
    frontpage_filters = models.ManyToManyField(Category,
            null=True, blank=True,
            help_text = _('Filter the list of all topics on these categories.'), verbose_name=_('front page categories'))

    class Meta:
        verbose_name = _('User settings')
        verbose_name_plural = _('User settings')

    def __unicode__(self):
        return _('%s\'s preferences') % self.user

User.really_anonymous = False
AnonymousUser.really_anonymous = False
DEFAULT_USER_SETTINGS  = UserSettings()
def get_user_settings(user):
    if not user.is_authenticated():
        return DEFAULT_USER_SETTINGS
    try:
        return user.sb_usersettings
    except UserSettings.DoesNotExist:
        return DEFAULT_USER_SETTINGS
User.get_user_settings = get_user_settings
AnonymousUser.get_user_settings = get_user_settings
   
class UserBan(models.Model):
    '''
    This bans the user from posting messages on the forum. He can still log in.
    '''
    user = models.ForeignKey(User, unique=True, verbose_name=_('user'), db_index=True,
            related_name='sb_userban_set',
            help_text=_('The user may still browse the forums anonymously. '
            'Other functions may also still be available to him if he is logged in.'))
    reason = models.CharField(max_length=255, verbose_name=_('reason'),
        help_text=_('This may be displayed to the banned user.'))

    class Meta:
        verbose_name = _('banned user')
        verbose_name_plural = _('banned users')

    def __unicode__(self):
        return _('Banned user: %s') % self.user

    @classmethod
    def update_cache(cls, **kwargs):
        c = connection.cursor()
        c.execute('SELECT user_id FROM %s;' % cls._meta.db_table)
        settings.SNAP_BANNED_USERS = set((x for (x,) in c.fetchall()))

signals.post_save.connect(UserBan.update_cache, sender=UserBan)
signals.post_delete.connect(UserBan.update_cache, sender=UserBan)


class IPBan(models.Model):
    '''
    IPs in the list are not allowed to use the boards.
    Only IPv4 addresses are supported, one per record. (patch with IPv6 and/or address range support welcome)
    '''
    address = models.IPAddressField(unique=True, verbose_name=_('IP address'),
            help_text=_('A person\'s IP address may change and an IP address may be '
            'used by more than one person, or by different people over time. '
            'Be careful when using this.'), db_index=True)
    reason = models.CharField(max_length=255, verbose_name=_('reason'),
        help_text=_('This may be displayed to the people concerned by the ban.'))

    class Meta:
        verbose_name = _('banned IP address')
        verbose_name_plural = _('banned IP addresses')
   
    def __unicode__(self):
        return _('Banned IP: %s') % self.address

    @classmethod
    def update_cache(cls, **kwargs):
        c = connection.cursor()
        c.execute('SELECT address FROM %s;' % cls._meta.db_table)
        settings.SNAP_BANNED_IPS = set((x for (x,) in c.fetchall()))


class XMPPContact(models.Model):
    '''
    Contains authentication status and contact's status for all known XMPP
    contacts.
    '''
    # Length is increased to reduce chance of problems with *very* long JIDs.
    remote = models.EmailField(max_length=100,
      verbose_name=_('remote jid'))
    local = models.EmailField(max_length=85, 
      verbose_name=_('local jid'))
    # Determines if bot has subsctiption to this contact.
    auth_to = models.BooleanField(default=False, 
      verbose_name=_('subscribed to'))
    # ...and if the contact is subscribed to bot's (local) jid.
    # ? In which case it can really be 'false', actually?
    auth_from = models.BooleanField(default=False,
      verbose_name=_('subscribed from'))
    # Status type: online / chat / away / xa / dnd / unavail.
    # It is preferrable to keep such volatile data in keyvalue storage.
    #status_type = models.CharField(max_length=10,
    #  verbose_name=_('current status'), blank=True)

    # last known vCard photo (hexdigest of SHA1 checksum, actually. should
    # always be of length 40 itself). It should be user-specific, not
    # contact-specific, but there's no more appropriate place for it (can
    # possibly store in the added avatar's filename/object, though).
    photosum = models.CharField(max_length=42, 
      verbose_name=_('photo checksum'), blank=True)
    # ? Need any other fields?

    def __unicode__(self):
        return '%s - %s' % (self.remote, self.local)

    class Meta:
        verbose_name = _('xmpp contact')
        verbose_name_plural = _('xmpp contacts')
        unique_together = ("remote", "local")


from types import FunctionType
def cachefetch(key, default=None, timeout=0):
    '''
    Slightly advanced cache.get() that can use result of a function and an
    additional timout parameter in case of cache miss.
    '''
    data = cache.get(key)
    if data is None:
        if default is not None:
            if isinstance(f, FunctionType):
                data = default()
            else:
                data = default
            cache.set(key, data, timeout)
    # no data, no default - return actual None.
    return data


signals.post_save.connect(IPBan.update_cache, sender=IPBan)
signals.post_delete.connect(IPBan.update_cache, sender=IPBan)

from xmppstuff import send_notifications

# vim: ai ts=4 sts=4 et sw=4