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