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