Source

milton / models.py

Full commit
  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
### IMPORTS ###

try:
    import markdown
except:
    markdown = None

try:
    import textile
except:
    textile = None

import datetime
import logging
import urlparse
import os

from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.conf import settings
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.managers import CurrentSiteManager
from django.db import models
from django.db.models import Q
from django.utils.safestring import mark_safe
from tagging.fields import TagField

from milton.middleware.RequestMiddleware import RequestMiddleware

log = logging.getLogger(__name__)

### CONSTANTS ###

COMMENTS_DISABLED = 0
COMMENTS_CLOSED = 1
COMMENTS_ENABLED =2

COMMENT_STATES = (
    (COMMENTS_DISABLED, 'Disabled'),
    (COMMENTS_CLOSED, 'Closed'),
    (COMMENTS_ENABLED, 'Enabled'),
)


ENTRY_STATUS_DRAFT = 0
ENTRY_STATUS_PUBLISHED = 1

ENTRY_STATUSES = (
    (ENTRY_STATUS_DRAFT, "Draft"),
    (ENTRY_STATUS_PUBLISHED, "Published"),
)


CONTENT_FORMAT_NONE = 0
CONTENT_FORMAT_TEXTILE = 1
CONTENT_FORMAT_MARKDOWN = 2

CONTENT_FORMATTERS = (
    (CONTENT_FORMAT_NONE, "None"),
    (CONTENT_FORMAT_TEXTILE, "Textile"),
    (CONTENT_FORMAT_MARKDOWN, "Markdown"),
)


### GLOBAL FUNCTIONS ###

def format_text(text_format, text):
    output = text
    if text_format == CONTENT_FORMAT_TEXTILE:
        if textile != None:
            output = textile.textile(text)
        else:
            print "No Textile support found."
    elif text_format == CONTENT_FORMAT_MARKDOWN:
        if markdown != None:
            output = markdown.markdown(text)
        else:
            print "No Markdown support found."
    return mark_safe(output)


### MANAGERS ###

class PublishedManager (models.Manager):
    def get_query_set(self):
        return super(PublishedManager,self).get_query_set().filter(
            Q(date_published=None) | Q(date_published__lte=datetime.datetime.now),
            Q(date_hidden=None) | Q(date_hidden__gt =datetime.datetime.now),
            status = 1,
            site=MiltonSite.objects.get_current()
        )

class MiltonSiteManager (models.Manager):
    def get_current(self):
        site = None
        request = RequestMiddleware.current_request()
        
        if request:
            site = self.get_site_for_URL(request.build_absolute_uri())
            
        if not site:
            site = self.get_query_set().get(pk=1)
            
        return site

    def get_site_for_URL(self, url):
        '''
    Input: http://bob.blogs.public.example.com/blogs/bob/ted/sam/index.html?count=1&path=/some/data&interesting
    Hostname: bob.blogs.public.example.com
    Path: /blogs/bob/ted/sam
    Result: ['bob.blogs.public.example.com/blogs/bob/ted/sam',
             'bob.blogs.public.example.com/blogs/bob/ted',
             'blogs.public.example.com/blogs/bob/ted/sam',
             'bob.blogs.public.example.com/blogs/bob',
             'blogs.public.example.com/blogs/bob/ted',
             'public.example.com/blogs/bob/ted/sam',
             'bob.blogs.public.example.com/blogs',
             'blogs.public.example.com/blogs/bob',
             'public.example.com/blogs/bob/ted',
             'blogs.public.example.com/blogs',
             'example.com/blogs/bob/ted/sam',
             'bob.blogs.public.example.com',
             'public.example.com/blogs/bob',
             'example.com/blogs/bob/ted',
             'blogs.public.example.com',
             'public.example.com/blogs',
             'example.com/blogs/bob',
             'public.example.com',
             'example.com/blogs',
             'example.com']
        '''
        parts = urlparse.urlparse(url)
        hostname = parts.hostname
        path = os.path.dirname(parts.path)

        if not (len(hostname) and len(path)):
            return None

        # Generate all valid permutations of the hostname and path.
        permutations = ['']
        hostnames = []
        paths = []

        hostname_parts = hostname.split(".") # ["bob", "example", "com"]
        path_parts = path.split("/") # ["blogs", "bob"]

        while len(hostname_parts) > 0:
            hostnames.append(".".join(hostname_parts))
            hostname_parts.pop(0)
        while len(path_parts) > 0:
            paths.append("/".join(path_parts))
            path_parts.pop(-1)

        for hostname in hostnames:
            for path in paths:
                permutations.append(hostname + path)

        permutations.sort(key=len, reverse=True)

        # Find the best matching site.
        query = self.get_query_set().filter(base_url__in=permutations)
        best_choice = None
        for site in query:
            if not best_choice:
                best_choice = site
                continue
            
            if len(site.base_url) > len(best_choice.base_url):
                best_choice = site
        
        return best_choice


class MiltonCurrentSiteManager (CurrentSiteManager):
    def get_query_set(self):
        if not self.__is_validated:
            self._validate_field_name()
        return super(MiltonCurrentSiteManager, self).get_query_set().filter(**{self.__field_name + '__id__exact': MiltonSite.objects.get_current().id})


### SPObject ###

class SPObject (models.Model):
    date_created = models.DateTimeField("Date Created", editable=False)
    date_modified = models.DateTimeField("Date Modified", editable=False)
    
    class Meta:
        abstract = True
    
    def __init__(self, *args, **kwargs):
        super(SPObject, self).__init__(*args, **kwargs)
        self._original_state = self._as_dict()
    
    def _as_dict(self):
        '''
        Returns the values of non-relationship model objects in a dictionary.
        '''
        return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel])
    
    def get_changed_fields(self):
        '''
        Returns a dictionary where the key is the field that changed and the value is the original value.
        '''
        new_state = self._as_dict()
        return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])
    
    def is_dirty_field(self, field):
        ''' Returns True if a field has been changed since the object was last saved. '''
        try:
            return self.__dict__.get(field, None) != self._original_state[field]
        except KeyError:
            return True
    
    def save(self, *args, **kwargs):
        if not self.date_created:
            self.date_created = datetime.datetime.now()
        
        ''' If the modification date was either not set or not manually changed since we were made, update it. '''
        if not self.date_modified or not self.is_dirty_field('date_modified'):
            self.date_modified = datetime.datetime.now()
                
        super(SPObject, self).save(*args, **kwargs)
        
        self._original_state = self._as_dict()


### Model Objects ###

class MiltonSite(SPObject):
    '''
    The Base URL is special.  It works similar to Drupal's concept of sites in that several variations are generated, all are searched against, and the longest match wins (so that we can have one DB query).
    http://mysite.bob.example.com/blog/bob/ will look for:
        mysite.bob.example.com/blog/bob
        mysite.bob.example.com/blog
        bob.example.com/blog/bob
        mysite.bob.example.com
        example.com/blog/bob
        bob.example.com
        example.com
        [empty]
    Yes, an empty string is valid as a default site or a single-site installation with multiple domain names. Note that paths are not searched alone and the domain is always included.
    '''
    base_url = models.CharField("Base URL", max_length=255, blank=True, unique=True, help_text="An installation-wide unique value that will match against the request URL and uniquely identifies this site (eg. http://example.com/bob or http://bob.example.com). This value is also used to compose permalinks. See documentation for full details.") #TODO: documentation...
    alias_for = models.ForeignKey('MiltonSite', null=True, blank=True, help_text="When this site is matched, use the site indicated here instead. Site aliases will never show their own content.")
    
    name = models.CharField("Site Name", max_length=255, blank=True, help_text="The human-readable, publicly-displayed name of the site.")
    slogan = models.CharField("Slogan", max_length=255, blank=True, help_text="A short description or slogan for the site; a subhead.")
    description_html = models.TextField("Description HTML", blank=True, help_text="This will be passed to templates as-is.")
    footer_html = models.TextField("Footer HTML", blank=True, help_text="This will be passed to templates as-is.")
    
    objects = MiltonSiteManager()
    
    class Meta:
        verbose_name = "site"

    def __unicode__(self):
        return self.name


class Section(SPObject):
    # TODO: Create admin class that auto-gens the slug
    site = models.ForeignKey(MiltonSite, null=True, blank=True, help_text='The site(s) this item is accessible at. Set to no value to use on all sites.')
    name = models.CharField("Section Name", max_length=255)
    slug = models.SlugField("Section Slug", max_length=255)
    # page = models.ForeignKey(Page, null=True, blank=True, help_text="A page to display instead of a section index.") # TODO: Would love this...
    
    class Meta:
        verbose_name = "section"
        verbose_name_plural = "sections"
    
    def __unicode__(self):
        return self.name
    
    @models.permalink
    def get_absolute_url(self):
        return ('story-archive',(), {'section':self.slug})


class Resource(SPObject):
    # Properties
    site = models.ForeignKey(MiltonSite, null=True, blank=True, help_text='The site this item is accessible at. Set to no value to use on all sites (eg. a privacy policy or TOS).')
    title = models.CharField("Title", max_length=255, null=False, blank=False)
    
    teaser = models.TextField(null=True, blank=True)
    teaser_format = models.PositiveIntegerField("Teaser Format", choices=CONTENT_FORMATTERS, default=CONTENT_FORMAT_TEXTILE, help_text="The formatter the teaser should be run through when rendering.")
    content = models.TextField("Content", null=True, blank=True, help_text='The content to display on the page.')
    content_format = models.PositiveIntegerField("Content Format", choices=CONTENT_FORMATTERS, default=CONTENT_FORMAT_TEXTILE, help_text="The formatter the content should be run through when rendering.")
    
    # Publishing status
    status = models.IntegerField("Status", choices=ENTRY_STATUSES, default=ENTRY_STATUS_PUBLISHED, help_text="Only published items will be visible on the site.")
    date_published = models.DateTimeField("Date Published", default=datetime.datetime.now, help_text="Item will become visible after this date.  Future posting is supported.")
    date_hidden = models.DateTimeField("Date Hidden", null=True, blank=True, help_text="Item will be hidden past this date.  No value indicates a perpetual item (most common).")
        
    # Object managers
    objects = models.Manager()
    published = PublishedManager()
    
    class Meta:
        abstract = True
        get_latest_by = 'date_published'
    
    def __init__(self, *args, **kwargs):
        super(Resource, self).__init__(*args, **kwargs)
        if self.id != None:
            self._original_url = self.get_absolute_url()
        else:
            self._original_url = ""
    
    def __unicode__(self):
        return self.title
    
    @property
    def visible(self):
        return (self.status == ENTRY_STATUS_PUBLISHED and self.date_published < datetime.datetime.now())
    
    @property
    def modified_since_publication(self):
        # Allow for some immediate changes for formatting, etc.
        forgiveness = datetime.timedelta(minutes=1)
        
        return (self.date_modified > (self.date_published + forgiveness))
    
    @property
    def formatted_teaser(self):
        return format_text(self.teaser_format, self.teaser)
    
    @property
    def formatted_content(self):
        return format_text(self.content_format, self.content)
    
    @property
    def previous(self):
        query = Story.published.order_by('-date_published', 'id').filter(date_published__lt=self.date_published)[0:1]
        if len(query):
            return query[0]
        else:
            return None
    
    @property
    def next(self):
        query = Story.published.order_by('date_published', 'id').filter(date_published__gt=self.date_published)[0:1]
        if len(query):
            return query[0]
        else:
            return None
    
    def save(self, *args, **kwargs):
        update_teaser_history = (self.teaser and self.is_dirty_field("teaser"))
        update_content_history = (self.content and self.is_dirty_field("content"))
        
        super(Resource, self).save(*args, **kwargs)
        
        '''
        Create a redirect with the current URL if the path has changed.
        We use the current URL so that if this object is ever deleted or hidden, we can display a 410/Gone message.
        Since we create these from the start of life for the object, all previous URLs will be recorded EXCEPT
        for the case when two objects will have shared the same URL at some point, at which case the original
        object wins (in the automated fashion; admins can always update the Redirect object manually).
        '''
        if self._original_url != self.get_absolute_url():
            (r, c) = Redirect.objects.get_or_create(
                original = self.get_absolute_url(),
                defaults = {
                    'target_object': self,
                    'permanent': True
                }
            )
            if c: r.save()
            self._original_url = self.get_absolute_url()
        
        if update_teaser_history:
            ch = ContentHistory(owner=self, field_name="teaser", content=self.teaser)
            ch.save()
        
        if update_content_history:
            ch = ContentHistory(owner=self, field_name="content", content=self.content)
            ch.save()


class Page(Resource):
    url = models.CharField("URL", max_length=255, db_index=True, help_text="The URL for this page. Ensure it begins and ends with a slash.")
    template_name = models.CharField("Template", max_length=255, blank=True, help_text="If specified, this template will be used instead of 'page.html'")

    class Meta:
        ordering = ('url',)
        verbose_name = "page"
        verbose_name_plural = "pages"
        get_latest_by = 'date_published'
    
    def __unicode__(self):
        return "%s; %s" % (self.url, self.title)

    def get_absolute_url(self):
        return self.url


class Story(Resource):
    slug = models.SlugField("URL Slug", max_length=255, null=False, blank=False)
    user = models.ForeignKey(User, null=False, blank=False)
    tags = TagField()
    section = models.ForeignKey(Section, null=True, blank=True, help_text="The section of the site this story will reside in.")
    show_metadata = models.BooleanField("Show Metadata", default=True, help_text="Toggles the display of author and date information.")
    allow_comments = models.IntegerField("Comments", choices=COMMENT_STATES, default=COMMENTS_ENABLED, help_text="If comments are disabled then existing comments will be hidden.  Choose 'Closed' to display existing comments and prevent new comments from being added.")
    
    class Meta:
        verbose_name = "story"
        verbose_name_plural = "stories"
        get_latest_by = 'date_published'
        ordering = ['-date_published','-date_modified']
    
    def show_comments(self):
        return self.allow_comments != COMMENTS_DISABLED
    
    def allow_commenting(self):
        return self.allow_comments == COMMENTS_ENABLED
    
    def get_all_urls(self):
        urls = [];
        
        if self.section:
            section = self.section.slug
        else:
            section = None
        
        kwargs = {
            'section': section,
            'year':    self.date_published.year,
            'month':   "%02d"%self.date_published.month,
            'day':     "%02d"%self.date_published.day,
            'slug':    self.slug,
        }
        
        urls.append(reverse('story-detail', kwargs = kwargs))
        
        del kwargs['slug']
        urls.append(reverse('story-archive', kwargs = kwargs))

        del kwargs['day']
        urls.append(reverse('story-archive', kwargs = kwargs))
        
        del kwargs['month']
        urls.append(reverse('story-archive', kwargs = kwargs))
        
        del kwargs['year']
        urls.append(reverse('story-archive', kwargs = kwargs))
        
        urls.append('/')
        
        return urls
        
    @models.permalink
    def get_absolute_url(self):
        kwargs = {
            'year':    self.date_published.year,
            'month':   "%02d"%self.date_published.month,
            'day':     "%02d"%self.date_published.day,
            'slug':    self.slug,
        }
        
        if self.section and len(self.section.slug):
            kwargs['section'] = self.section.slug
        
        return ('story-detail', (), kwargs)

### REDIRECTION ###

class Redirect(SPObject):
    site = models.ForeignKey(MiltonSite, null=True, blank=True, help_text='The site this redirect is active for. Set to no value to use on all sites.')
    original = models.CharField("Original path", max_length=255, db_index=True,
        help_text='The original path for this resource.  This must be an absolute path starting from the root of the site.')
    current = models.CharField("Current path", max_length=255, null=True, blank=True,
        help_text='The current path to this resource, if it is not an object.')
    
    content_type = models.ForeignKey(ContentType, null=True, blank=True, help_text='If this redirect is to an object, select an object type.')
    object_id = models.PositiveIntegerField("Object ID", null=True, blank=True, help_text='The ID of the object this redirect will point to.')
    target_object = generic.GenericForeignKey()
    
    permanent = models.BooleanField(default=True, help_text='Is this redirect permanent (301)?')
    
    class Meta:
        verbose_name = "redirect"
        verbose_name_plural = "redirects"
        ordering = ['-date_created']
        unique_together = ("site", "original")
    
    def __unicode__(self):
        return "%s to (%s, %s)" % (self.original, self.current, self.target_object)
    
    def destination(self):
        destination = None
        if self.current and len(self.current):
            destination = self.current
        elif self.target_object != None:
            try:
                destination = self.target_object.get_absolute_url()
            except Exception, e:
                pass
        return destination


### HISTORY ###

class ContentHistory(SPObject):
    content_type = models.ForeignKey(ContentType, null=True, blank=True)
    object_id = models.PositiveIntegerField(null=True, blank=True)
    owner = generic.GenericForeignKey()
    field_name = models.CharField(max_length=255)
    content = models.TextField("Content", null=True, blank=True)
    
    class Meta:
        verbose_name = "content history"
        verbose_name_plural = "content histories"
        ordering = ['-date_created', 'content_type', 'object_id']
    
    def __unicode__(self):
        return u"%s: %s" % (self.owner, self.field_name)
    
    @classmethod
    def history(owner, field):
        #FIXME: owner won't work here, need to search by ID and PK
        return ContentHistory.objects.filter(owner=owner, field_name=field).order_by('-date_created')