]> git.0d.be Git - panikweb.git/blobdiff - panikweb/views.py
feeds: include fragment id in guid
[panikweb.git] / panikweb / views.py
index 766be4f74433ba944d5f401b28e2c8bf5d564336..6e5209bbf0707175b5e8d167b126f9d4423fe3e0 100644 (file)
@@ -4,11 +4,13 @@ import random
 import os
 import stat
 import time
-import urlparse
 
 from django.core.urlresolvers import reverse
 from django.conf import settings
-from django.http import Http404
+from django.http import Http404, JsonResponse
+from django.utils.encoding import force_text
+from django.utils.encoding import python_2_unicode_compatible
+from django.utils.six.moves.urllib import parse as urlparse
 from django.views.decorators.cache import cache_control
 from django.views.generic.base import TemplateView
 from django.views.generic.detail import DetailView
@@ -23,7 +25,6 @@ from django.contrib.syndication.views import Feed, add_domain
 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
 
 from haystack.query import SearchQuerySet
-from jsonresponse import to_json
 
 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
         Schedule, Nonstop, NewsItem, NewsCategory, Focus
@@ -103,7 +104,11 @@ class EmissionDetailView(DetailView, EmissionMixin):
         context = super(EmissionDetailView, self).get_context_data(**kwargs)
         context['schedules'] = Schedule.objects.select_related().filter(
                 emission=self.object).order_by('rerun', 'datetime')
-        context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
+        context['news'] = NewsItem.objects.all(
+                ).filter(emission=self.object.id
+                ).exclude(expiration_date__lt=date.today()  # expiration date
+                ).exclude(date__lt=date.today() - timedelta(days=60)
+                ).order_by('-date')[:3]
         try:
             nonstop_object = Nonstop.objects.get(slug=self.object.slug)
         except Nonstop.DoesNotExist:
@@ -239,6 +244,7 @@ class ProgramView(TemplateView):
 
 program = ProgramView.as_view()
 
+@python_2_unicode_compatible
 class TimeCell:
     nonstop = None
     w = 1
@@ -260,14 +266,17 @@ class TimeCell:
                 end_time.minute)
         self.schedules.append(schedule)
 
-    def __unicode__(self):
+    def sorted_schedules(self):
+        return sorted(self.schedules, key=lambda x: x.week_sort_key())
+
+    def __str__(self):
         if self.schedules:
             return ', '.join([x.emission.title for x in self.schedules])
         else:
             return self.nonstop
 
     def __eq__(self, other):
-        return (unicode(self) == unicode(other) and self.time_label == other.time_label)
+        return (force_text(self) == force_text(other) and self.time_label == other.time_label)
 
 
 class Grid(TemplateView):
@@ -290,15 +299,15 @@ class Grid(TemplateView):
             if nonstop.start < nonstop.end:
                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
                                  nonstop.end.hour + nonstop.end.minute/60.,
-                                 nonstop.title, nonstop.slug])
+                                 nonstop.title, nonstop.slug, nonstop])
             else:
                 # crossing midnight
                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
                                  24,
-                                 nonstop.title, nonstop.slug])
+                                 nonstop.title, nonstop.slug, nonstop])
                 nonstops.append([0,
                                  nonstop.end.hour + nonstop.end.minute/60.,
-                                 nonstop.title, nonstop.slug])
+                                 nonstop.title, nonstop.slug, nonstop])
         nonstops.sort()
 
         for i in range(nb_lines):
@@ -310,6 +319,7 @@ class Grid(TemplateView):
             for time_cell in grid[-1]:
                 time_cell.nonstop = nonstop[2]
                 time_cell.nonstop_slug = nonstop[3]
+                time_cell.redirect_path = nonstop[4].redirect_path
                 if nonstop[1] == 5:
                     # the one ending at 5am will be cut down, so we inscribe
                     # its duration manually
@@ -349,7 +359,7 @@ class Grid(TemplateView):
                             continue
                         # here it is, same cell, same emission, several
                         # schedules
-                        schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
+                        schedule_list.sort(key=lambda x: x.get_duration())
 
                         schedule = schedule_list[0]
                         end_time = schedule.datetime + timedelta(
@@ -455,8 +465,7 @@ class Grid(TemplateView):
                                     grid[i][j].time_label = same_cell_below.time_label
                                     # then we sort emissions so the longest are
                                     # put first
-                                    grid[i][j].schedules.sort(
-                                            lambda x, y: -cmp(x.get_duration(), y.get_duration()))
+                                    grid[i][j].schedules.sort(key=lambda x: -x.get_duration())
                                     # then we add individual time labels to the
                                     # other schedules
                                     for schedule in current_cell_schedules:
@@ -535,7 +544,10 @@ class News(TemplateView):
     template_name = 'news.html'
     def get_context_data(self, **kwargs):
         context = super(News, self).get_context_data(**kwargs)
-        context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
+        context['focus'] = NewsItem.objects.exclude(date__gt=date.today()  # publication date
+                ).exclude(expiration_date__lt=date.today()  # expiration date
+                ).filter(got_focus__isnull=False
+                ).select_related('category').order_by('-date')[:10]
         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
         return context
 
@@ -624,7 +636,6 @@ listen = Listen.as_view()
 
 @cache_control(max_age=15)
 @csrf_exempt
-@to_json('api')
 def onair(request):
     d = whatsonair()
     if d.get('episode'):
@@ -642,13 +653,16 @@ def onair(request):
             'chat': chat_url,
         }
     if d.get('nonstop'):
+        redirect_path = d['nonstop'].redirect_path
         d['nonstop'] = {
             'title': d['nonstop'].title,
         }
+        if redirect_path:
+            d['nonstop']['url'] = redirect_path
         d.update(get_current_nonstop_track())
     if d.get('current_slot'):
         del d['current_slot']
-    return d
+    return JsonResponse({'data': d})
 
 
 class NewsItemDetailView(DetailView):
@@ -659,23 +673,71 @@ newsitem = NewsItemDetailView.as_view()
 class RssCustomPodcastsFeed(Rss201rev2Feed):
     def add_root_elements(self, handler):
         super(RssCustomPodcastsFeed, self).add_root_elements(handler)
+        emission = self.feed.get('emission')
+        if emission and emission.image and emission.image.url:
+            image_url = emission.image.url
+        else:
+            image_url = '/static/img/logo-panik-500.png'
+        image_url = urlparse.urljoin(self.feed['link'], image_url)
         handler.startElement('image', {})
-        handler.addQuickElement('title', 'Radio Panik')
-        handler.addQuickElement('url', self.feed['link'] + 'static/img/Radio_Panik_Logo_2016-01.png')
+        if emission:
+            handler.addQuickElement('title', emission.title)
+        else:
+            handler.addQuickElement('title', settings.RADIO_NAME)
+        handler.addQuickElement('url', image_url)
         handler.endElement('image')
+        handler.addQuickElement('itunes:explicit', 'no')  # invidividual items will get their own value
+        handler.addQuickElement('itunes:image', None, {'href': image_url})
+        if emission:
+            if emission.subtitle:
+                handler.addQuickElement('itunes:subtitle', emission.subtitle)
+            for category in emission.categories.all():
+                if category.itunes_category:
+                    handler.addQuickElement('itunes:category', None, {'text': category.itunes_category})
+
+            handler.addQuickElement('itunes:author', emission.title)
+            handler.startElement('itunes:owner', {})
+            if emission.email:
+                handler.addQuickElement('itunes:email', emission.email)
+            handler.addQuickElement('itunes:name', emission.title)
+            handler.endElement('itunes:owner')
+        else:
+            handler.addQuickElement('itunes:author', settings.RADIO_NAME)
+            handler.startElement('itunes:owner', {})
+            handler.addQuickElement('itunes:email', 'info@radiopanik.org')
+            handler.addQuickElement('itunes:name', settings.RADIO_NAME)
+            handler.endElement('itunes:owner')
 
     def root_attributes(self):
         attrs = super(RssCustomPodcastsFeed, self).root_attributes()
         attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
+        attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
         return attrs
 
     def add_item_elements(self, handler, item):
         super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
+        explicit = 'no'
         for tag in item.get('tags') or []:
             handler.addQuickElement('dc:subject', tag)
+            if tag == 'explicit':
+                explicit = 'yes'
+        if item.get('tags'):
+            handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
+        handler.addQuickElement('itunes:explicit', explicit)
+        episode = item.get('episode')
+        if episode and episode.image and episode.image.url:
+            image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
+            handler.addQuickElement('itunes:image', None, {'href': image_url})
+        soundfile = item.get('soundfile')
+        if soundfile.duration:
+            handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
+                soundfile.duration / 3600,
+                soundfile.duration % 3600 / 60,
+                soundfile.duration % 60))
+
 
 class PodcastsFeed(Feed):
-    title = 'Radio Panik - Podcasts'
+    title = '%s - Podcasts' % settings.RADIO_NAME
     link = '/'
     description_template = 'feed/soundfile.html'
     feed_type = RssCustomPodcastsFeed
@@ -686,11 +748,13 @@ class PodcastsFeed(Feed):
 
     def item_title(self, item):
         if item.fragment:
-            return '%s - %s' % (item.title, item.episode.title)
-        return item.episode.title
+            return '[%s] %s - %s' % (item.episode.emission.title, item.title, item.episode.title)
+        return '[%s] %s' % (item.episode.emission.title, item.episode.title)
 
     def item_link(self, item):
-        return item.episode.get_absolute_url()
+        if item.fragment:
+            return item.episode.get_absolute_url() + '#%s' % item.id
+        return item.episode.get_absolute_url() + '#%s' % item.id
 
     def item_enclosure_url(self, item):
         current_site = Site.objects.get(id=settings.SITE_ID)
@@ -710,13 +774,15 @@ class PodcastsFeed(Feed):
         return item.creation_timestamp
 
     def item_extra_kwargs(self, item):
-        return {'tags': [x.name for x in item.episode.tags.all()]}
+        return {'tags': [x.name for x in item.episode.tags.all()],
+                'soundfile': item,
+                'episode': item.episode}
 
 podcasts_feed = PodcastsFeed()
 
 
 class RssNewsFeed(Feed):
-    title = 'Radio Panik'
+    title = settings.RADIO_NAME
     link = '/news/'
     description_template = 'feed/newsitem.html'
 
@@ -738,6 +804,41 @@ class AtomNewsFeed(RssNewsFeed):
 atom_news_feed = AtomNewsFeed()
 
 
+class EmissionPodcastsFeed(PodcastsFeed):
+    description_template = 'feed/soundfile.html'
+    feed_type = RssCustomPodcastsFeed
+
+    def __call__(self, request, *args, **kwargs):
+        self.emission = Emission.objects.get(slug=kwargs.get('slug'))
+        return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
+
+    def item_title(self, item):
+        if item.fragment:
+            return '%s - %s' % (item.title, item.episode.title)
+        return item.episode.title
+
+    @property
+    def title(self):
+        return self.emission.title
+
+    @property
+    def description(self):
+        return self.emission.subtitle
+
+    @property
+    def link(self):
+        return reverse('emission-view', kwargs={'slug': self.emission.slug})
+
+    def feed_extra_kwargs(self, obj):
+        return {'emission': self.emission}
+
+    def items(self):
+        return SoundFile.objects.select_related().filter(
+                podcastable=True,
+                episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
+
+emission_podcasts_feed = EmissionPodcastsFeed()
+
 
 class Party(TemplateView):
     template_name = 'party.html'