]> git.0d.be Git - panikweb.git/blob - panikweb/views.py
only include episodes of this year on emission page
[panikweb.git] / panikweb / views.py
1 # coding: utf-8
2
3 from datetime import datetime, timedelta, date
4 import math
5 import random
6 import os
7 import stat
8 import time
9 import urlparse
10
11 from django.core.urlresolvers import reverse
12 from django.conf import settings
13 from django.http import Http404
14 from django.views.decorators.cache import cache_control
15 from django.views.generic.base import TemplateView
16 from django.views.generic.detail import DetailView
17 from django.views.decorators.csrf import csrf_exempt
18 from django.views.generic.dates import _date_from_string
19 from django.views.generic.dates import MonthArchiveView
20
21 from django.core.paginator import Paginator
22
23 from django.contrib.sites.models import Site
24 from django.contrib.syndication.views import Feed, add_domain
25 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
26
27 from haystack.query import SearchQuerySet
28 from jsonresponse import to_json
29
30 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
31         Schedule, Nonstop, NewsItem, NewsCategory, Focus
32
33 from emissions.utils import whatsonair, period_program
34
35 from newsletter.forms import SubscribeForm
36 from nonstop.utils import get_current_nonstop_track
37 from nonstop.models import SomaLogLine
38
39 from combo.data.models import Page
40 from panikombo.models import ItemTopik
41
42 from . import utils
43
44
45 class EmissionMixin:
46     def get_emission_context(self, emission, episode_ids=None):
47         context = {}
48
49         # get all episodes, with an additional attribute to get the date of
50         # their first diffusion
51         episodes_queryset = Episode.objects.select_related()
52         if episode_ids is not None:
53             episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
54         else:
55             episodes_queryset = episodes_queryset.filter(emission=emission)
56
57         context['episodes'] = \
58                 episodes_queryset.extra(select={
59                         'first_diffusion': 'emissions_diffusion.datetime',
60                         },
61                         select_params=(False, True),
62                         where=['''datetime = (SELECT MIN(datetime)
63                                                 FROM emissions_diffusion
64                                                WHERE episode_id = emissions_episode.id
65                                                  AND datetime <= CURRENT_TIMESTAMP)'''],
66                         tables=['emissions_diffusion'],
67                     ).order_by('-first_diffusion').distinct()
68
69         context['futurEpisodes'] = \
70                 episodes_queryset.extra(select={
71                         'first_diffusion': 'emissions_diffusion.datetime',
72                         },
73                         select_params=(False, True),
74                         where=['''datetime = (SELECT MIN(datetime)
75                                                 FROM emissions_diffusion
76                                                WHERE episode_id = emissions_episode.id
77                                                  AND datetime > CURRENT_TIMESTAMP)'''],
78                         tables=['emissions_diffusion'],
79                     ).order_by('first_diffusion').distinct()
80
81         current_year = datetime.now().replace(month=5, day=1)
82
83         context['all_episodes'] = episodes_queryset.filter(
84                 creation_timestamp__gt=current_year
85                 ).extra(select={
86                         'first_diffusion': 'emissions_diffusion.datetime',
87                         },
88                         select_params=(False, True),
89                         where=['''datetime = (SELECT MIN(datetime)
90                                                 FROM emissions_diffusion
91                                                WHERE episode_id = emissions_episode.id
92                                              )'''],
93                         tables=['emissions_diffusion'],
94                     ).order_by('first_diffusion')
95
96         # get all related soundfiles in a single query
97         soundfiles = {}
98         if episode_ids is not None:
99             for episode_id in episode_ids:
100                 soundfiles[episode_id] = None
101         else:
102             for episode in Episode.objects.filter(emission=emission):
103                 soundfiles[episode.id] = None
104
105         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
106                 fragment=False, episode__emission=emission):
107             soundfiles[soundfile.episode_id] = soundfile
108
109         Episode.set_prefetched_soundfiles(soundfiles)
110
111         #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
112
113         return context
114
115
116 class EmissionDetailView(DetailView, EmissionMixin):
117     model = Emission
118
119     def get_context_data(self, **kwargs):
120         context = super(EmissionDetailView, self).get_context_data(**kwargs)
121         context['schedules'] = Schedule.objects.select_related().filter(
122                 emission=self.object).order_by('rerun', 'datetime')
123         context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
124         try:
125             nonstop_object = Nonstop.objects.get(slug=self.object.slug)
126         except Nonstop.DoesNotExist:
127             pass
128         else:
129             today = date.today()
130             dates = [today - timedelta(days=x) for x in range(7)]
131             if datetime.now().time() < nonstop_object.start:
132                 dates = dates[1:]
133             context['nonstop'] = nonstop_object
134             context['nonstop_dates'] = dates
135         context.update(self.get_emission_context(self.object))
136         return context
137 emission = EmissionDetailView.as_view()
138
139 class EpisodeDetailView(DetailView, EmissionMixin):
140     model = Episode
141
142     def get_context_data(self, **kwargs):
143         context = super(EpisodeDetailView, self).get_context_data(**kwargs)
144         context['diffusions'] = Diffusion.objects.select_related().filter(
145                 episode=self.object.id).order_by('datetime')
146         try:
147             context['emission'] = context['episode'].emission
148         except Emission.DoesNotExist:
149             raise Http404()
150         if self.kwargs.get('emission_slug') != context['emission'].slug:
151             raise Http404()
152         context.update(self.get_emission_context(context['emission']))
153         context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
154         return context
155 episode = EpisodeDetailView.as_view()
156
157
158 class NonstopPlaylistView(TemplateView):
159     template_name = 'nonstop_playlist.html'
160
161     def get_context_data(self, **kwargs):
162         context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
163         try:
164             context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
165         except Emission.DoesNotExist:
166             raise Http404()
167         context['date'] = date(int(kwargs.get('year')),
168                 int(kwargs.get('month')), int(kwargs.get('day')))
169         context['future'] = (context['date'] >= date.today())
170
171         nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
172         start = datetime(
173                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
174                 nonstop_object.start.hour, nonstop_object.start.minute)
175         end = datetime(
176                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
177                 nonstop_object.end.hour, nonstop_object.end.minute)
178         if end < start:
179             end = end + timedelta(days=1)
180         context['tracks'] = SomaLogLine.objects.filter(
181                 play_timestamp__gte=start,
182                 play_timestamp__lte=end,
183                 on_air=True).select_related()
184         return context
185
186 nonstop_playlist = NonstopPlaylistView.as_view()
187
188 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
189     model = Emission
190     template_name = 'emissions/episodes.html'
191
192     def get_context_data(self, **kwargs):
193         context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
194         context['schedules'] = Schedule.objects.select_related().filter(
195                 emission=self.object).order_by('rerun', 'datetime')
196
197         context['search_query'] = self.request.GET.get('q')
198         if context['search_query']:
199             # query string
200             sqs = SearchQuerySet().models(Episode).filter(
201                     emission_slug_exact=self.object.slug, text=context['search_query'])
202             episode_ids = [x.pk for x in sqs]
203         else:
204             episode_ids = None
205
206         context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
207         return context
208 emissionEpisodes = EmissionEpisodesDetailView.as_view()
209
210
211 class SoundFileEmbedView(DetailView):
212     model = SoundFile
213     template_name = 'soundfiles/embed.html'
214
215     def get_context_data(self, **kwargs):
216         context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
217         if self.kwargs.get('episode_slug') != self.object.episode.slug:
218             raise Http404()
219         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
220             raise Http404()
221         context['episode'] = self.object.episode
222         return context
223 soundfile_embed = SoundFileEmbedView.as_view()
224
225
226 class SoundFileDialogEmbedView(DetailView):
227     model = SoundFile
228     template_name = 'soundfiles/dialog-embed.html'
229
230     def get_context_data(self, **kwargs):
231         context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
232         if self.kwargs.get('episode_slug') != self.object.episode.slug:
233             raise Http404()
234         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
235             raise Http404()
236         context['episode'] = self.object.episode
237         return context
238 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
239
240
241
242 class ProgramView(TemplateView):
243     template_name = 'program.html'
244
245     def get_context_data(self, year=None, week=None, **kwargs):
246         context = super(ProgramView, self).get_context_data(**kwargs)
247
248         context['weekday'] = datetime.today().weekday()
249
250         context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
251         context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
252         context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
253         context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
254
255         return context
256
257 program = ProgramView.as_view()
258
259 class TimeCell:
260     nonstop = None
261     w = 1
262     h = 1
263     time_label = None
264
265     def __init__(self, i, j):
266         self.x = i
267         self.y = j
268         self.schedules = []
269
270     def add_schedule(self, schedule):
271         end_time = schedule.datetime + timedelta(
272                 minutes=schedule.get_duration())
273         self.time_label = '%02d:%02d-%02d:%02d' % (
274                 schedule.datetime.hour,
275                 schedule.datetime.minute,
276                 end_time.hour,
277                 end_time.minute)
278         self.schedules.append(schedule)
279
280     def __unicode__(self):
281         if self.schedules:
282             return ', '.join([x.emission.title for x in self.schedules])
283         else:
284             return self.nonstop
285
286     def __eq__(self, other):
287         return (unicode(self) == unicode(other) and self.time_label == other.time_label)
288
289
290 class Grid(TemplateView):
291     template_name = 'grid.html'
292
293     def get_context_data(self, **kwargs):
294         context = super(Grid, self).get_context_data(**kwargs)
295
296         nb_lines = 2 * 24 # the cells are half hours
297         grid = []
298
299         times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
300         # start grid after the night programs
301         times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
302
303         nonstops = []
304         for nonstop in Nonstop.objects.all():
305             if nonstop.start == nonstop.end:
306                 continue
307             if nonstop.start < nonstop.end:
308                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
309                                  nonstop.end.hour + nonstop.end.minute/60.,
310                                  nonstop.title, nonstop.slug])
311             else:
312                 # crossing midnight
313                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
314                                  24,
315                                  nonstop.title, nonstop.slug])
316                 nonstops.append([0,
317                                  nonstop.end.hour + nonstop.end.minute/60.,
318                                  nonstop.title, nonstop.slug])
319         nonstops.sort()
320
321         for i in range(nb_lines):
322             grid.append([])
323             for j in range(7):
324                 grid[-1].append(TimeCell(i, j))
325
326             nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
327             for time_cell in grid[-1]:
328                 time_cell.nonstop = nonstop[2]
329                 time_cell.nonstop_slug = nonstop[3]
330                 if nonstop[1] == 5:
331                     # the one ending at 5am will be cut down, so we inscribe
332                     # its duration manually
333                     time_cell.time_label = '%02d:00-%02d:00' % (
334                             nonstop[0], nonstop[1])
335
336         for schedule in Schedule.objects.prefetch_related(
337                 'emission__categories').select_related().order_by('datetime'):
338             row_start = schedule.datetime.hour * 2 + \
339                     int(math.ceil(schedule.datetime.minute / 30))
340             day_no = schedule.get_weekday()
341
342             for step in range(int(math.ceil(schedule.get_duration() / 30.))):
343                 if grid[(row_start+step)%nb_lines][day_no] is None:
344                     grid[(row_start+step)%nb_lines][day_no] = TimeCell()
345                 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
346
347         # start grid after the night programs
348         grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
349
350         # look for the case where the same emission has different schedules for
351         # the same time cell, for example if it lasts one hour the first week,
352         # and two hours the third week.
353         for i in range(nb_lines):
354             grid[i] = [x for x in grid[i] if x is not None]
355             for j, cell in enumerate(grid[i]):
356                 if grid[i][j] is None:
357                     continue
358                 if len(grid[i][j].schedules) > 1:
359                     time_cell_emissions = {}
360                     for schedule in grid[i][j].schedules:
361                         if not schedule.emission.id in time_cell_emissions:
362                             time_cell_emissions[schedule.emission.id] = []
363                         time_cell_emissions[schedule.emission.id].append(schedule)
364                     for schedule_list in time_cell_emissions.values():
365                         if len(schedule_list) == 1:
366                             continue
367                         # here it is, same cell, same emission, several
368                         # schedules
369                         schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
370
371                         schedule = schedule_list[0]
372                         end_time = schedule.datetime + timedelta(
373                                 minutes=schedule.get_duration())
374                         grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
375                                 schedule.datetime.hour,
376                                 schedule.datetime.minute,
377                                 end_time.hour,
378                                 end_time.minute)
379
380                         for schedule in schedule_list[1:]:
381                             grid[i][j].schedules.remove(schedule)
382                             end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
383                             schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
384                                     end_time.hour, end_time.minute, schedule.weeks_string)
385
386         # merge adjacent
387
388         # 1st thing is to merge cells on the same line, this will mostly catch
389         # consecutive nonstop cells
390         for i in range(nb_lines):
391             for j, cell in enumerate(grid[i]):
392                 if grid[i][j] is None:
393                     continue
394                 t = 1
395                 try:
396                     # if the cells are identical, they are removed from the
397                     # grid, and current cell width is increased
398                     while grid[i][j+t] == cell:
399                         cell.w += 1
400                         grid[i][j+t] = None
401                         t += 1
402                 except IndexError:
403                     pass
404
405             # once we're done we remove empty cells
406             grid[i] = [x for x in grid[i] if x is not None]
407
408         # 2nd thing is to merge cells vertically, this is emissions that last
409         # for more than 30 minutes
410         for i in range(nb_lines):
411             grid[i] = [x for x in grid[i] if x is not None]
412             for j, cell in enumerate(grid[i]):
413                 if grid[i][j] is None:
414                     continue
415                 t = 1
416                 try:
417                     while True:
418                         # we look if the next time cell has the same emissions
419                         same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
420                                            if x == cell and x.y == cell.y and x.w == cell.w]
421                         if same_cell_below:
422                             # if the cell was identical, we remove it and
423                             # increase current cell height
424                             bj, same_cell_below = same_cell_below[0]
425                             del grid[i+cell.h][bj]
426                             cell.h += 1
427                         else:
428                             # if the cell is different, we have a closer look
429                             # to it, so we can remove emissions that will
430                             # already be mentioned in the current cell.
431                             #
432                             # For example:
433                             #  - 7am30, seuls contre tout, 1h30
434                             #  - 8am, du pied gauche & la voix de la rue, 1h
435                             # should produce: (this is case A)
436                             #  |      7:30-9:00      |
437                             #  |  seuls contre tout  |
438                             #  |---------------------|
439                             #  |      8:00-9:00      |
440                             #  |   du pied gauche    |
441                             #  |  la voix de la rue  |
442                             #
443                             # On the other hand, if all three emissions started
444                             # at 7am30, we want: (this is case B)
445                             #  |      7:30-9:00      |
446                             #  |  seuls contre tout  |
447                             #  |   du pied gauche    |
448                             #  |  la voix de la rue  |
449                             # that is we merge all of them, ignoring the fact
450                             # that the other emissions will stop at 8am30
451                             current_cell_schedules = set(grid[i][j].schedules)
452                             current_cell_emissions = set([x.emission for x in current_cell_schedules])
453                             cursor = 1
454                             while True and current_cell_schedules:
455                                 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
456                                 if not same_cell_below:
457                                     cursor += 1
458                                     continue
459                                 same_cell_below = same_cell_below[0]
460                                 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
461
462                                 if current_cell_emissions.issubset(same_cell_below_emissions):
463                                     # this handles case A (see comment above)
464                                     for schedule in current_cell_schedules:
465                                         if schedule in same_cell_below.schedules:
466                                             same_cell_below.schedules.remove(schedule)
467                                 elif same_cell_below_emissions and \
468                                         current_cell_emissions.issuperset(same_cell_below_emissions):
469                                     # this handles case B (see comment above)
470                                     # we set the cell time label to the longest
471                                     # period
472                                     grid[i][j].time_label = same_cell_below.time_label
473                                     # then we sort emissions so the longest are
474                                     # put first
475                                     grid[i][j].schedules.sort(
476                                             lambda x, y: -cmp(x.get_duration(), y.get_duration()))
477                                     # then we add individual time labels to the
478                                     # other schedules
479                                     for schedule in current_cell_schedules:
480                                         if schedule not in same_cell_below.schedules:
481                                             end_time = schedule.datetime + timedelta(
482                                                     minutes=schedule.get_duration())
483                                             schedule.time_label = '%02d:%02d-%02d:%02d' % (
484                                                     schedule.datetime.hour,
485                                                     schedule.datetime.minute,
486                                                     end_time.hour,
487                                                     end_time.minute)
488                                     grid[i][j].h += 1
489                                     grid[i+cursor].remove(same_cell_below)
490                                 elif same_cell_below_emissions and \
491                                         current_cell_emissions.intersection(same_cell_below_emissions):
492                                     same_cell_below.schedules = [x for x in
493                                             same_cell_below.schedules if
494                                             x.emission not in
495                                             current_cell_emissions or
496                                             x.get_duration() < 30]
497                                 cursor += 1
498                             break
499                 except IndexError:
500                     pass
501
502         # cut night at 3am
503         grid = grid[:42]
504         times = times[:42]
505
506         context['grid'] = grid
507         context['times'] = times
508         context['categories'] = Category.objects.all()
509         context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
510                 'Vendredi', 'Samedi', 'Dimanche']
511
512         return context
513
514 grid = Grid.as_view()
515
516
517 class Home(TemplateView):
518     template_name = 'home.html'
519
520     def get_context_data(self, **kwargs):
521         context = super(Home, self).get_context_data(**kwargs)
522         context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
523         context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
524                 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
525
526         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
527                 podcastable=True, fragment=False) \
528                 .select_related().extra(select={
529                     'first_diffusion': 'emissions_diffusion.datetime', },
530                     select_params=(False, True),
531                     where=['''datetime = (SELECT MIN(datetime)
532                                             FROM emissions_diffusion
533                                         WHERE episode_id = emissions_episode.id)'''],
534                     tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
535
536         context['newsletter_form'] = SubscribeForm()
537         context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
538
539         return context
540
541 home = Home.as_view()
542
543 class NewsItemView(DetailView):
544     model = NewsItem
545     def get_context_data(self, **kwargs):
546         context = super(NewsItemView, self).get_context_data(**kwargs)
547         context['categories'] = NewsCategory.objects.all()
548         context['news'] = NewsItem.objects.all().order_by('-date')
549         context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
550         return context
551 newsitemview = NewsItemView.as_view()
552
553 class News(TemplateView):
554     template_name = 'news.html'
555     def get_context_data(self, **kwargs):
556         context = super(News, self).get_context_data(**kwargs)
557         context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
558         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
559         return context
560
561 news = News.as_view()
562
563
564 class Agenda(TemplateView):
565     template_name = 'agenda.html'
566     def get_context_data(self, **kwargs):
567         context = super(Agenda, self).get_context_data(**kwargs)
568         context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
569                 event_date__gte=date.today()).order_by('date')[:20]
570         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
571         context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
572         return context
573
574 agenda = Agenda.as_view()
575
576
577 class AgendaByMonth(MonthArchiveView):
578     template_name = 'agenda.html'
579     queryset = NewsItem.objects.filter(event_date__isnull=False)
580     allow_future = True
581     date_field = 'event_date'
582     month_format = '%m'
583
584     def get_context_data(self, **kwargs):
585         context = super(AgendaByMonth, self).get_context_data(**kwargs)
586         context['agenda'] = context['object_list']
587         context['news'] = NewsItem.objects.all().order_by('-date')
588         return context
589
590 agenda_by_month = AgendaByMonth.as_view()
591
592
593 class Emissions(TemplateView):
594     template_name = 'emissions.html'
595
596     def get_context_data(self, **kwargs):
597         context = super(Emissions, self).get_context_data(**kwargs)
598         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
599         context['categories'] = Category.objects.all()
600         return context
601
602 emissions = Emissions.as_view()
603
604 class EmissionsArchives(TemplateView):
605     template_name = 'emissions/archives.html'
606
607     def get_context_data(self, **kwargs):
608         context = super(EmissionsArchives, self).get_context_data(**kwargs)
609         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
610         context['categories'] = Category.objects.all()
611         return context
612 emissionsArchives = EmissionsArchives.as_view()
613
614
615 class Listen(TemplateView):
616     template_name = 'listen.html'
617
618     def get_context_data(self, **kwargs):
619         context = super(Listen, self).get_context_data(**kwargs)
620         context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
621                 podcastable=True, got_focus__isnull=False) \
622                 .select_related().extra(select={
623                     'first_diffusion': 'emissions_diffusion.datetime', },
624                     select_params=(False, True),
625                     where=['''datetime = (SELECT MIN(datetime)
626                                             FROM emissions_diffusion
627                                         WHERE episode_id = emissions_episode.id)'''],
628                     tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
629         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
630                 podcastable=True) \
631                 .select_related().extra(select={
632                     'first_diffusion': 'emissions_diffusion.datetime', },
633                     select_params=(False, True),
634                     where=['''datetime = (SELECT MIN(datetime)
635                                             FROM emissions_diffusion
636                                         WHERE episode_id = emissions_episode.id)'''],
637                     tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
638
639
640         return context
641
642 listen = Listen.as_view()
643
644 @cache_control(max_age=15)
645 @csrf_exempt
646 @to_json('api')
647 def onair(request):
648     if date.today() < date(2017, 8, 3):
649         return {'emission': {'title': 'À partir du 3 août 17h', 'url': '/'}}
650     if date.today() > date(2017, 8, 6):
651         return {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}
652     d = whatsonair()
653     if d.get('episode'):
654         d['episode'] = {
655             'title': d['episode'].title,
656             'url': d['episode'].get_absolute_url()
657         }
658     if d.get('emission'):
659         chat_url = None
660         if d['emission'].chat_open:
661             chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
662         d['emission'] = {
663             'title': d['emission'].title,
664             'url': d['emission'].get_absolute_url(),
665             'chat': chat_url,
666         }
667     if d.get('nonstop'):
668         d['nonstop'] = {
669             'title': d['nonstop'].title,
670         }
671         playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
672         if os.path.exists(os.path.join(playing_txt)):
673             d['track_title'] = open(playing_txt).read().strip()
674     if d.get('current_slot'):
675         del d['current_slot']
676     return d
677
678
679 class NewsItemDetailView(DetailView):
680     model = NewsItem
681
682 newsitem = NewsItemDetailView.as_view()
683
684 class RssCustomPodcastsFeed(Rss201rev2Feed):
685     def add_root_elements(self, handler):
686         super(RssCustomPodcastsFeed, self).add_root_elements(handler)
687         emission = self.feed.get('emission')
688         if emission and emission.image and emission.image.url:
689             image_url = emission.image.url
690         else:
691             image_url = '/static/img/logo-panik-500.png'
692         image_url = urlparse.urljoin(self.feed['link'], image_url)
693         handler.startElement('image', {})
694         if emission:
695             handler.addQuickElement('title', emission.title)
696         else:
697             handler.addQuickElement('title', 'Radio Esperanzah!')
698         handler.addQuickElement('url', image_url)
699         handler.endElement('image')
700         handler.addQuickElement('itunes:image', None, {'href': image_url})
701         if emission and emission.subtitle:
702             handler.addQuickElement('itunes:subtitle', emission.subtitle)
703
704     def root_attributes(self):
705         attrs = super(RssCustomPodcastsFeed, self).root_attributes()
706         attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
707         attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
708         return attrs
709
710     def add_item_elements(self, handler, item):
711         super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
712         explicit = 'no'
713         for tag in item.get('tags') or []:
714             handler.addQuickElement('dc:subject', tag)
715             if tag == 'explicit':
716                 explicit = 'yes'
717         if item.get('tags'):
718             handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
719         handler.addQuickElement('itunes:explicit', explicit)
720         episode = item.get('episode')
721         if episode and episode.image and episode.image.url:
722             image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
723             handler.addQuickElement('itunes:image', None, {'href': image_url})
724         soundfile = item.get('soundfile')
725         if soundfile.duration:
726             handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
727                 soundfile.duration / 3600,
728                 soundfile.duration % 3600 / 60,
729                 soundfile.duration % 60))
730
731
732 class PodcastsFeed(Feed):
733     title = 'Radio Esperanzah! - Podcasts'
734     link = '/'
735     description_template = 'feed/soundfile.html'
736     feed_type = RssCustomPodcastsFeed
737
738     def items(self):
739         return SoundFile.objects.select_related().filter(
740                 podcastable=True).order_by('-creation_timestamp')[:20]
741
742     def item_title(self, item):
743         if item.fragment:
744             return '%s - %s' % (item.title, item.episode.title)
745         return '%s - %s' % (item.episode.emission.title, item.episode.title)
746
747     def item_link(self, item):
748         return item.episode.get_absolute_url()
749
750     def item_enclosure_url(self, item):
751         current_site = Site.objects.get(id=settings.SITE_ID)
752         return add_domain(current_site.domain, item.get_format_url('mp3'))
753
754     def item_enclosure_length(self, item):
755         sound_path = item.get_format_path('mp3')
756         try:
757             return os.stat(sound_path)[stat.ST_SIZE]
758         except OSError:
759             return 0
760
761     def item_enclosure_mime_type(self, item):
762         return 'audio/mpeg'
763
764     def item_pubdate(self, item):
765         return item.creation_timestamp
766
767     def item_extra_kwargs(self, item):
768         return {'tags': [x.name for x in item.episode.tags.all()],
769                 'soundfile': item,
770                 'episode': item.episode}
771
772 podcasts_feed = PodcastsFeed()
773
774
775 class RssNewsFeed(Feed):
776     title = 'Radio Esperanzah!'
777     link = '/news/'
778     description_template = 'feed/newsitem.html'
779
780     def items(self):
781         return NewsItem.objects.order_by('-date')[:20]
782
783 rss_news_feed = RssNewsFeed()
784
785 class Atom1FeedWithBaseXml(Atom1Feed):
786     def root_attributes(self):
787         root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
788         scheme, netloc, path, params, query, fragment  = urlparse.urlparse(self.feed['feed_url'])
789         root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
790         return root_attributes
791
792 class AtomNewsFeed(RssNewsFeed):
793     feed_type = Atom1FeedWithBaseXml
794
795 atom_news_feed = AtomNewsFeed()
796
797
798 class EmissionPodcastsFeed(PodcastsFeed):
799     description_template = 'feed/soundfile.html'
800     feed_type = RssCustomPodcastsFeed
801
802     def __call__(self, request, *args, **kwargs):
803         self.emission = Emission.objects.get(slug=kwargs.get('slug'))
804         return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
805
806     @property
807     def title(self):
808         return '%s - Podcasts' % self.emission.title
809
810     @property
811     def link(self):
812         return reverse('emission-view', kwargs={'slug': self.emission.slug})
813
814     def feed_extra_kwargs(self, obj):
815         return {'emission': self.emission}
816
817     def items(self):
818         return SoundFile.objects.select_related().filter(
819                 podcastable=True,
820                 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
821
822 emission_podcasts_feed = EmissionPodcastsFeed()
823
824
825 class Party(TemplateView):
826     template_name = 'party.html'
827
828     def get_context_data(self, **kwargs):
829         context = super(Party, self).get_context_data(**kwargs)
830         t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
831         focus = Focus()
832         if t == 'newsitem':
833             focus.newsitem = NewsItem.objects.exclude(
834                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
835         elif t == 'emission':
836             focus.emission = Emission.objects.exclude(
837                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
838         elif t == 'episode':
839             focus.episode = Episode.objects.exclude(
840                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
841         elif t == 'soundfile':
842             focus.soundfile = SoundFile.objects.exclude(
843                     episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
844
845         context['focus'] = focus
846
847         return context
848
849 party = Party.as_view()
850
851
852
853 class Chat(DetailView, EmissionMixin):
854     model = Emission
855     template_name = 'chat.html'
856
857 chat = cache_control(max_age=15)(Chat.as_view())