]> git.0d.be Git - panikweb.git/blobdiff - panikweb/views.py
templates: strip label of embed dialog
[panikweb.git] / panikweb / views.py
index a37aa11cdc09bad5608acbf7f21a19649f85be88..f918932890c383817649aeb3513441ffb830cf8e 100644 (file)
@@ -1,14 +1,18 @@
+# coding: utf-8
+
 from datetime import datetime, timedelta, date
 import math
 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 +27,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
@@ -34,6 +37,7 @@ from newsletter.forms import SubscribeForm
 from nonstop.utils import get_current_nonstop_track
 from nonstop.models import SomaLogLine
 
+from combo.data.models import Page
 from panikombo.models import ItemTopik
 
 from . import utils
@@ -75,6 +79,23 @@ class EmissionMixin:
                         tables=['emissions_diffusion'],
                     ).order_by('first_diffusion').distinct()
 
+        if emission.archived:
+            current_year = emission.creation_timestamp.replace(month=5, day=1)
+        else:
+            current_year = datetime.now().replace(month=5, day=1).replace(year=2019)
+
+        context['all_episodes'] = episodes_queryset.filter(
+                creation_timestamp__gt=current_year
+                ).extra(select={
+                        'first_diffusion': 'emissions_diffusion.datetime',
+                        },
+                        select_params=(False, True),
+                        where=['''datetime = (SELECT MIN(datetime)
+                                                FROM emissions_diffusion
+                                               WHERE episode_id = emissions_episode.id
+                                             )'''],
+                        tables=['emissions_diffusion'],
+                    ).order_by('first_diffusion').distinct()
 
         # get all related soundfiles in a single query
         soundfiles = {}
@@ -122,6 +143,10 @@ emission = EmissionDetailView.as_view()
 class EpisodeDetailView(DetailView, EmissionMixin):
     model = Episode
 
+    def get_queryset(self, *args, **kwargs):
+        queryset = super(EpisodeDetailView, self).get_queryset(*args, **kwargs)
+        return queryset.filter(emission__slug=self.kwargs['emission_slug'])
+
     def get_context_data(self, **kwargs):
         context = super(EpisodeDetailView, self).get_context_data(**kwargs)
         context['diffusions'] = Diffusion.objects.select_related().filter(
@@ -239,6 +264,7 @@ class ProgramView(TemplateView):
 
 program = ProgramView.as_view()
 
+@python_2_unicode_compatible
 class TimeCell:
     nonstop = None
     w = 1
@@ -260,14 +286,14 @@ class TimeCell:
                 end_time.minute)
         self.schedules.append(schedule)
 
-    def __unicode__(self):
+    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):
@@ -279,6 +305,8 @@ class Grid(TemplateView):
         nb_lines = 2 * 24 # the cells are half hours
         grid = []
 
+        Schedule.DAY_HOUR_START = 12
+
         times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
         # start grid after the night programs
         times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
@@ -306,7 +334,10 @@ class Grid(TemplateView):
             for j in range(7):
                 grid[-1].append(TimeCell(i, j))
 
-            nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
+            try:
+                nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
+            except IndexError:
+                pass
             for time_cell in grid[-1]:
                 time_cell.nonstop = nonstop[2]
                 time_cell.nonstop_slug = nonstop[3]
@@ -316,7 +347,7 @@ class Grid(TemplateView):
                     time_cell.time_label = '%02d:00-%02d:00' % (
                             nonstop[0], nonstop[1])
 
-        for schedule in Schedule.objects.prefetch_related(
+        for schedule in Schedule.objects.filter(emission__archived=False).prefetch_related(
                 'emission__categories').select_related().order_by('datetime'):
             row_start = schedule.datetime.hour * 2 + \
                     int(math.ceil(schedule.datetime.minute / 30))
@@ -349,7 +380,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 +486,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:
@@ -482,9 +512,9 @@ class Grid(TemplateView):
                 except IndexError:
                     pass
 
-        # cut night at 3am
-        grid = grid[:42]
-        times = times[:42]
+        # cut night
+        grid = grid[:28]
+        times = times[:28]
 
         context['grid'] = grid
         context['times'] = times
@@ -502,8 +532,9 @@ class Home(TemplateView):
 
     def get_context_data(self, **kwargs):
         context = super(Home, self).get_context_data(**kwargs)
-        context['emissions'] = Emission.objects.filter(archived=False).order_by('-creation_timestamp')[:3]
-        context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')[:3]
+        context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
+        context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
+                ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
 
         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
                 podcastable=True, fragment=False) \
@@ -516,6 +547,7 @@ class Home(TemplateView):
                     tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
 
         context['newsletter_form'] = SubscribeForm()
+        context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
 
         return context
 
@@ -535,7 +567,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,9 +659,16 @@ listen = Listen.as_view()
 
 @cache_control(max_age=15)
 @csrf_exempt
-@to_json('api')
 def onair(request):
-    d = whatsonair()
+    if datetime.now() < datetime(2019, 7, 30, 17, 0):
+        class FakeNonstop(object):
+            title = 'Le festival arrive, découvrez déjà la musique !'
+        d = {'title': 'XXX', 'nonstop': FakeNonstop()}
+        #return JsonResponse({'data': {'emission': {'title': 'À partir du 31 juillet 18h', 'url': '/'}}})
+    elif date.today() >= date(2019, 8, 5):
+        return JsonResponse({'data': {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}})
+    else:
+        d = whatsonair()
     if d.get('episode'):
         d['episode'] = {
             'title': d['episode'].title,
@@ -641,14 +683,30 @@ def onair(request):
             'url': d['emission'].get_absolute_url(),
             'chat': chat_url,
         }
+
+    track_title = None
+    playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
+    if os.path.exists(playing_txt):
+        track_title = open(playing_txt).read().strip()
+        if len(track_title) < 6:
+            track_title = None
     if d.get('nonstop'):
         d['nonstop'] = {
             'title': d['nonstop'].title,
         }
-        d.update(get_current_nonstop_track())
+        if track_title:
+            d['track_title'] = track_title
+    elif d.get('emission') and not d.get('episode') and track_title:
+        # live emission, if there's a track playing, and no known episode,
+        # display it.
+        d['episode'] = {
+            'title': track_title,
+            'url': d['emission']['url'],
+        }
+
     if d.get('current_slot'):
         del d['current_slot']
-    return d
+    return JsonResponse({'data': d})
 
 
 class NewsItemDetailView(DetailView):
@@ -660,29 +718,70 @@ 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', {})
         if emission:
             handler.addQuickElement('title', emission.title)
         else:
-            handler.addQuickElement('title', 'Radio Panik')
-        if emission and emission.image and emission.image.url:
-            handler.addQuickElement('url', urlparse.urljoin(self.feed['link'], emission.image.url))
-        else:
-            handler.addQuickElement('url', urlparse.urljoin(self.feed['link'], '/static/img/logo-panik-500.png'))
+            handler.addQuickElement('title', 'Radio Esperanzah!')
+        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', 'Radio Esperanzah!')
+            handler.startElement('itunes:owner', {})
+            handler.addQuickElement('itunes:email', 'radio@esperanzah.be')
+            handler.addQuickElement('itunes:name', 'Radio Esperanzah!')
+            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 = 'Radio Esperanzah! - Podcasts'
     link = '/'
     description_template = 'feed/soundfile.html'
     feed_type = RssCustomPodcastsFeed
@@ -694,7 +793,7 @@ 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' % (item.episode.emission.title, item.episode.title)
 
     def item_link(self, item):
         return item.episode.get_absolute_url()
@@ -717,13 +816,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 = 'Radio Esperanzah!'
     link = '/news/'
     description_template = 'feed/newsitem.html'
 
@@ -745,7 +846,7 @@ class AtomNewsFeed(RssNewsFeed):
 atom_news_feed = AtomNewsFeed()
 
 
-class EmissionPodcastsFeed(Feed):
+class EmissionPodcastsFeed(PodcastsFeed):
     description_template = 'feed/soundfile.html'
     feed_type = RssCustomPodcastsFeed
 
@@ -755,7 +856,7 @@ class EmissionPodcastsFeed(Feed):
 
     @property
     def title(self):
-        return '%s - Podcasts' % self.emission.title
+        return self.emission.title
 
     @property
     def link(self):
@@ -769,34 +870,6 @@ class EmissionPodcastsFeed(Feed):
                 podcastable=True,
                 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
 
-    def item_title(self, item):
-        if item.fragment:
-            return '%s - %s' % (item.title, item.episode.title)
-        return item.episode.title
-
-    def item_link(self, item):
-        return item.episode.get_absolute_url()
-
-    def item_enclosure_url(self, item):
-        current_site = Site.objects.get(id=settings.SITE_ID)
-        return add_domain(current_site.domain, item.get_format_url('mp3'))
-
-    def item_enclosure_length(self, item):
-        sound_path = item.get_format_path('mp3')
-        try:
-            return os.stat(sound_path)[stat.ST_SIZE]
-        except OSError:
-            return 0
-
-    def item_enclosure_mime_type(self, item):
-        return 'audio/mpeg'
-
-    def item_pubdate(self, item):
-        return item.creation_timestamp
-
-    def item_extra_kwargs(self, item):
-        return {'tags': [x.name for x in item.episode.tags.all()]}
-
 emission_podcasts_feed = EmissionPodcastsFeed()
 
 
@@ -833,3 +906,15 @@ class Chat(DetailView, EmissionMixin):
     template_name = 'chat.html'
 
 chat = cache_control(max_age=15)(Chat.as_view())
+
+
+
+class ArchivesView(TemplateView):
+    template_name = 'archives.html'
+
+    def get_context_data(self, **kwargs):
+        context = super(ArchivesView, self).get_context_data(**kwargs)
+        context['diffusions'] = Diffusion.objects.filter(episode__soundfile__isnull=False).distinct().order_by('-datetime')
+        return context
+
+archives = ArchivesView.as_view()