Fixed login redirects
[philo.git] / contrib / penfield / models.py
1 from django.db import models
2 from django.conf import settings
3 from philo.models import Tag, Titled, Entity, MultiView, Page, register_value_model
4 from philo.exceptions import ViewCanNotProvideSubpath
5 from django.conf.urls.defaults import url, patterns, include
6 from django.core.urlresolvers import reverse
7 from django.http import Http404
8 from datetime import datetime
9 from philo.utils import paginate
10 from philo.contrib.penfield.validators import validate_pagination_count
11 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
12 from philo.contrib.penfield.utils import FeedMultiViewMixin
13
14
15 class Blog(Entity, Titled):
16         @property
17         def entry_tags(self):
18                 """ Returns a QuerySet of Tags that are used on any entries in this blog. """
19                 return Tag.objects.filter(blogentries__blog=self).distinct()
20         
21         @property
22         def entry_dates(self):
23                 dates = {'year': self.entries.dates('date', 'year', order='DESC'), 'month': self.entries.dates('date', 'month', order='DESC'), 'day': self.entries.dates('date', 'day', order='DESC')}
24                 return dates
25
26
27 register_value_model(Blog)
28
29
30 class BlogEntry(Entity, Titled):
31         blog = models.ForeignKey(Blog, related_name='entries', blank=True, null=True)
32         author = models.ForeignKey(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='blogentries')
33         date = models.DateTimeField(default=datetime.now)
34         content = models.TextField()
35         excerpt = models.TextField(blank=True, null=True)
36         tags = models.ManyToManyField(Tag, related_name='blogentries', blank=True, null=True)
37         
38         class Meta:
39                 ordering = ['-date']
40                 verbose_name_plural = "blog entries"
41
42
43 register_value_model(BlogEntry)
44
45
46 class BlogView(MultiView, FeedMultiViewMixin):
47         ENTRY_PERMALINK_STYLE_CHOICES = (
48                 ('D', 'Year, month, and day'),
49                 ('M', 'Year and month'),
50                 ('Y', 'Year'),
51                 ('B', 'Custom base'),
52                 ('N', 'No base')
53         )
54         
55         blog = models.ForeignKey(Blog, related_name='blogviews')
56         
57         index_page = models.ForeignKey(Page, related_name='blog_index_related')
58         entry_page = models.ForeignKey(Page, related_name='blog_entry_related')
59         entry_archive_page = models.ForeignKey(Page, related_name='blog_entry_archive_related', null=True, blank=True)
60         tag_page = models.ForeignKey(Page, related_name='blog_tag_related')
61         tag_archive_page = models.ForeignKey(Page, related_name='blog_tag_archive_related', null=True, blank=True)
62         entries_per_page = models.IntegerField(blank=True, validators=[validate_pagination_count], null=True)
63         
64         entry_permalink_style = models.CharField(max_length=1, choices=ENTRY_PERMALINK_STYLE_CHOICES)
65         entry_permalink_base = models.CharField(max_length=255, blank=False, default='entries')
66         tag_permalink_base = models.CharField(max_length=255, blank=False, default='tags')
67         feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
68         feeds_enabled = models.BooleanField()
69         list_var = 'entries'
70         
71         def __unicode__(self):
72                 return u'BlogView for %s' % self.blog.title
73         
74         @property
75         def per_page(self):
76                 return self.entries_per_page
77         
78         @property
79         def feed_title(self):
80                 return self.blog.title
81         
82         def get_subpath(self, obj):
83                 if isinstance(obj, BlogEntry):
84                         if obj.blog == self.blog:
85                                 kwargs = {'slug': obj.slug}
86                                 if self.entry_permalink_style in 'DMY':
87                                         kwargs.update({'year': str(obj.date.year).zfill(4)})
88                                         if self.entry_permalink_style in 'DM':
89                                                 kwargs.update({'month': str(obj.date.month).zfill(2)})
90                                                 if self.entry_permalink_style == 'D':
91                                                         kwargs.update({'day': str(obj.date.day).zfill(2)})
92                                 return reverse(self.entry_view, urlconf=self, kwargs=kwargs)
93                 elif isinstance(obj, Tag):
94                         if obj in self.blog.entry_tags:
95                                 return reverse('entries_by_tag', urlconf=self, kwargs={'tag_slugs': obj.slug})
96                 elif isinstance(obj, (str, unicode)):
97                         split_obj = obj.split(':')
98                         if len(split_obj) > 1:
99                                 kwargs = {}
100                                 try:
101                                         kwargs.update({'year': str(int(split_obj[1])).zfill(4)})
102                                         if len(split_obj) > 2:
103                                                 kwargs.update({'month': str(int(split_obj[2])).zfill(2)})
104                                                 if len(split_obj) > 3:
105                                                         kwargs.update({'day': str(int(split_obj[3])).zfill(2)})
106                                                         return reverse('entries_by_day', urlconf=self, kwargs=kwargs)
107                                                 return reverse('entries_by_month', urlconf=self, kwargs=kwargs)
108                                         return reverse('entries_by_year', urlconf=self, kwargs=kwargs)
109                                 except:
110                                         pass
111                 raise ViewCanNotProvideSubpath
112         
113         def get_context(self):
114                 return {'blog': self.blog}
115         
116         @property
117         def urlpatterns(self):
118                 urlpatterns = patterns('',
119                         url(r'^', include(self.feed_patterns(self.get_all_entries, self.index_page, 'index'))),
120                         url((r'^(?:%s)/(?P<tag_slugs>[-\w]+[-+/\w]*)/' % self.tag_permalink_base), include(self.feed_patterns(self.get_entries_by_tag, self.tag_page, 'entries_by_tag')))
121                 )
122                 if self.tag_archive_page:
123                         urlpatterns += patterns('',
124                                 url((r'^(?:%s)/?$' % self.tag_permalink_base), self.tag_archive_view)
125                         )
126                 
127                 if self.entry_archive_page:
128                         if self.entry_permalink_style in 'DMY':
129                                 urlpatterns += patterns('',
130                                         url(r'^(?P<year>\d{4})/', include(self.feed_patterns(self.get_entries_by_ymd, self.entry_archive_page, 'entries_by_year')))
131                                 )
132                                 if self.entry_permalink_style in 'DM':
133                                         urlpatterns += patterns('',
134                                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/?$', include(self.feed_patterns(self.get_entries_by_ymd, self.entry_archive_page, 'entries_by_month'))),
135                                         )
136                                         if self.entry_permalink_style == 'D':
137                                                 urlpatterns += patterns('',
138                                                         url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/?$', include(self.feed_patterns(self.get_entries_by_ymd, self.entry_archive_page, 'entries_by_day')))
139                                                 )
140                 
141                 if self.entry_permalink_style == 'D':
142                         urlpatterns += patterns('',
143                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/?$', self.entry_view)
144                         )
145                 elif self.entry_permalink_style == 'M':
146                         urlpatterns += patterns('',
147                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/?$', self.entry_view)
148                         )
149                 elif self.entry_permalink_style == 'Y':
150                         urlpatterns += patterns('',
151                                 url(r'^(?P<year>\d{4})/(?P<slug>[-\w]+)/?$', self.entry_view)
152                         )
153                 elif self.entry_permalink_style == 'B':
154                         urlpatterns += patterns('',
155                                 url((r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.entry_permalink_base), self.entry_view)
156                         )
157                 else:
158                         urlpatterns = patterns('',
159                                 url(r'^(?P<slug>[-\w]+)/?$', self.entry_view)
160                         )
161                 return urlpatterns
162         
163         def get_all_entries(self, request, node=None, extra_context=None):
164                 return self.blog.entries.all(), extra_context
165         
166         def get_entries_by_ymd(self, request, year=None, month=None, day=None, node=None, extra_context=None):
167                 if not self.entry_archive_page:
168                         raise Http404
169                 entries = self.blog.entries.all()
170                 if year:
171                         entries = entries.filter(date__year=year)
172                 if month:
173                         entries = entries.filter(date__month=month)
174                 if day:
175                         entries = entries.filter(date__day=day)
176                 
177                 context = extra_context or {}
178                 context.update({'year': year, 'month': month, 'day': day})
179                 return entries, context
180         
181         def get_entries_by_tag(self, request, node=None, extra_context=None):
182                 tags = []
183                 for tag_slug in tag_slugs.replace('+', '/').split('/'):
184                         if tag_slug: # ignore blank slugs, handles for multiple consecutive separators (+ or /)
185                                 try:
186                                         tag = self.blog.entry_tags.get(slug=tag_slug)
187                                 except:
188                                         raise Http404
189                                 tags.append(tag)
190                 if len(tags) <= 0:
191                         raise Http404
192
193                 entries = self.blog.entries.all()
194                 for tag in tags:
195                         entries = entries.filter(tags=tag)
196                 if entries.count() <= 0:
197                         raise Http404
198                 
199                 return entries, extra_context
200         
201         def get_obj_description(self, obj):
202                 return obj.excerpt
203         
204         def entry_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
205                 entries = self.blog.entries.all()
206                 if year:
207                         entries = entries.filter(date__year=year)
208                 if month:
209                         entries = entries.filter(date__month=month)
210                 if day:
211                         entries = entries.filter(date__day=day)
212                 try:
213                         entry = entries.get(slug=slug)
214                 except:
215                         raise Http404
216                 context = self.get_context()
217                 context.update(extra_context or {})
218                 context.update({'entry': entry})
219                 return self.entry_page.render_to_response(node, request, extra_context=context)
220         
221         def tag_archive_view(self, request, node=None, extra_context=None):
222                 if not self.tag_archive_page:
223                         raise Http404
224                 context = {}
225                 context.update(extra_context or {})
226                 context.update({'blog': self.blog})
227                 return self.tag_archive_page.render_to_response(node, request, extra_context=context)
228
229
230 class Newsletter(Entity, Titled):
231         pass
232
233
234 register_value_model(Newsletter)
235
236
237 class NewsletterArticle(Entity, Titled):
238         newsletter = models.ForeignKey(Newsletter, related_name='articles')
239         authors = models.ManyToManyField(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='newsletterarticles')
240         date = models.DateTimeField(default=datetime.now)
241         lede = models.TextField(null=True, blank=True)
242         full_text = models.TextField()
243         tags = models.ManyToManyField(Tag, related_name='newsletterarticles', blank=True, null=True)
244         
245         class Meta:
246                 get_latest_by = 'date'
247                 ordering = ['-date']
248                 unique_together = (('newsletter', 'slug'),)
249
250
251 register_value_model(NewsletterArticle)
252
253
254 class NewsletterIssue(Entity, Titled):
255         newsletter = models.ForeignKey(Newsletter, related_name='issues')
256         numbering = models.CharField(max_length=50, help_text='For example, 04.02 for volume 4, issue 2.')
257         articles = models.ManyToManyField(NewsletterArticle, related_name='issues')
258         
259         class Meta:
260                 ordering = ['-numbering']
261                 unique_together = (('newsletter', 'numbering'),)
262
263
264 register_value_model(NewsletterIssue)
265
266
267 class NewsletterView(MultiView, FeedMultiViewMixin):
268         ARTICLE_PERMALINK_STYLE_CHOICES = (
269                 ('D', 'Year, month, and day'),
270                 ('M', 'Year and month'),
271                 ('Y', 'Year'),
272                 ('S', 'Slug only')
273         )
274         
275         newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
276         
277         index_page = models.ForeignKey(Page, related_name='newsletter_index_related')
278         article_page = models.ForeignKey(Page, related_name='newsletter_article_related')
279         article_archive_page = models.ForeignKey(Page, related_name='newsletter_article_archive_related', null=True, blank=True)
280         issue_page = models.ForeignKey(Page, related_name='newsletter_issue_related')
281         issue_archive_page = models.ForeignKey(Page, related_name='newsletter_issue_archive_related', null=True, blank=True)
282         
283         article_permalink_style = models.CharField(max_length=1, choices=ARTICLE_PERMALINK_STYLE_CHOICES)
284         article_permalink_base = models.CharField(max_length=255, blank=False, default='articles')
285         issue_permalink_base = models.CharField(max_length=255, blank=False, default='issues')
286         
287         feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
288         feeds_enabled = models.BooleanField()
289         list_var = 'articles'
290         
291         def __unicode__(self):
292                 return self.newsletter.__unicode__()
293         
294         @property
295         def feed_title(self):
296                 return self.newsletter.title
297         
298         def get_subpath(self, obj):
299                 if isinstance(obj, NewsletterArticle):
300                         if obj.newsletter == self.newsletter:
301                                 kwargs = {'slug': obj.slug}
302                                 if self.article_permalink_style in 'DMY':
303                                         kwargs.update({'year': str(obj.date.year).zfill(4)})
304                                         if self.article_permalink_style in 'DM':
305                                                 kwargs.update({'month': str(obj.date.month).zfill(2)})
306                                                 if self.article_permalink_style == 'D':
307                                                         kwargs.update({'day': str(obj.date.day).zfill(2)})
308                                 return reverse(self.article_view, urlconf=self, kwargs=kwargs)
309                 elif isinstance(obj, NewsletterIssue):
310                         if obj.newsletter == self.newsletter:
311                                 return reverse('issue', urlconf=self, kwargs={'numbering': obj.numbering})
312                 raise ViewCanNotProvideSubpath
313         
314         @property
315         def urlpatterns(self):
316                 urlpatterns = patterns('',
317                         url(r'^', include(self.feed_patterns(self.get_all_articles, self.index_page, 'index'))),
318                         url(r'^(?:%s)/(?P<numbering>.+)/' % self.issue_permalink_base, include(self.feed_patterns(self.get_articles_by_issue, self.issue_page, 'issue')))
319                 )
320                 if self.issue_archive_page:
321                         urlpatterns += patterns('',
322                                 url(r'^(?:%s)/$' % self.issue_permalink_base, self.issue_archive_view)
323                         )
324                 if self.article_archive_page:
325                         urlpatterns += patterns('',
326                                 url(r'^(?:%s)/' % self.article_permalink_base, include(self.feed_patterns(self.get_all_articles, self.article_archive_page, 'articles')))
327                         )
328                         if self.article_permalink_style in 'DMY':
329                                 urlpatterns += patterns('',
330                                         url(r'^(?:%s)/(?P<year>\d{4})/' % self.article_permalink_base, include(self.feed_patterns(self.get_articles_by_ymd, self.article_archive_page, 'articles_by_year')))
331                                 )
332                                 if self.article_permalink_style in 'DM':
333                                         urlpatterns += patterns('',
334                                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/' % self.article_permalink_base, include(self.feed_patterns(self.get_articles_by_ymd, self.article_archive_page, 'articles_by_month')))
335                                         )
336                                         if self.article_permalink_style == 'D':
337                                                 urlpatterns += patterns('',
338                                                         url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/' % self.article_permalink_base, include(self.feed_patterns(self.get_articles_by_ymd, self.article_archive_page, 'articles_by_day')))
339                                                 )
340                 
341                 if self.article_permalink_style == 'Y':
342                         urlpatterns += patterns('',
343                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
344                         )
345                 elif self.article_permalink_style == 'M':
346                         urlpatterns += patterns('',
347                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
348                         )
349                 elif self.article_permalink_style == 'D':
350                         urlpatterns += patterns('',
351                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
352                         )
353                 else:   
354                         urlpatterns += patterns('',
355                                 url(r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base, self.article_view)
356                         )
357                 
358                 return urlpatterns
359         
360         def get_context(self):
361                 return {'newsletter': self.newsletter}
362         
363         def get_all_articles(self, request, node, extra_context=None):
364                 return self.newsletter.articles.all(), extra_context
365         
366         def get_articles_by_ymd(self, request, year, month=None, day=None, node=None, extra_context=None):
367                 articles = self.newsletter.articles.filter(dat__year=year)
368                 if month:
369                         articles = articles.filter(date__month=month)
370                 if day:
371                         articles = articles.filter(date__day=day)
372                 return articles
373         
374         def get_articles_by_issue(self, request, numbering, node=None, extra_context=None):
375                 try:
376                         issue = self.newsletter.issues.get(numbering=numbering)
377                 except:
378                         raise Http404
379                 context = extra_context or {}
380                 context.update({'issue': issue})
381                 return issue.articles.all(), context
382         
383         def article_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
384                 articles = self.newsletter.articles.all()
385                 if year:
386                         articles = articles.filter(date__year=year)
387                 if month:
388                         articles = articles.filter(date__month=month)
389                 if day:
390                         articles = articles.filter(date__day=day)
391                 try:
392                         article = articles.get(slug=slug)
393                 except:
394                         raise Http404
395                 context = self.get_context()
396                 context.update(extra_context or {})
397                 context.update({'article': article})
398                 return self.article_page.render_to_response(node, request, extra_context=context)
399         
400         def issue_archive_view(self, request, node=None, extra_context=None):
401                 if not self.issue_archive_page:
402                         raise Http404
403                 context = {}
404                 context.update(extra_context or {})
405                 context.update({'newsletter': self.newsletter})
406                 return self.issue_archive_page.render_to_response(node, request, extra_context=context)
407         
408         def get_obj_description(self, obj):
409                 return obj.lede or obj.full_text