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