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