]> git.0d.be Git - panikweb.git/blob - panikweb/views.py
update for django 1.11
[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)
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()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
569         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
570         return context
571
572 news = News.as_view()
573
574
575 class Agenda(TemplateView):
576     template_name = 'agenda.html'
577     def get_context_data(self, **kwargs):
578         context = super(Agenda, self).get_context_data(**kwargs)
579         context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
580                 event_date__gte=date.today()).order_by('date')[:20]
581         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
582         context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
583         return context
584
585 agenda = Agenda.as_view()
586
587
588 class AgendaByMonth(MonthArchiveView):
589     template_name = 'agenda.html'
590     queryset = NewsItem.objects.filter(event_date__isnull=False)
591     allow_future = True
592     date_field = 'event_date'
593     month_format = '%m'
594
595     def get_context_data(self, **kwargs):
596         context = super(AgendaByMonth, self).get_context_data(**kwargs)
597         context['agenda'] = context['object_list']
598         context['news'] = NewsItem.objects.all().order_by('-date')
599         return context
600
601 agenda_by_month = AgendaByMonth.as_view()
602
603
604 class Emissions(TemplateView):
605     template_name = 'emissions.html'
606
607     def get_context_data(self, **kwargs):
608         context = super(Emissions, self).get_context_data(**kwargs)
609         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
610         context['categories'] = Category.objects.all()
611         return context
612
613 emissions = Emissions.as_view()
614
615 class EmissionsArchives(TemplateView):
616     template_name = 'emissions/archives.html'
617
618     def get_context_data(self, **kwargs):
619         context = super(EmissionsArchives, self).get_context_data(**kwargs)
620         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
621         context['categories'] = Category.objects.all()
622         return context
623 emissionsArchives = EmissionsArchives.as_view()
624
625
626 class Listen(TemplateView):
627     template_name = 'listen.html'
628
629     def get_context_data(self, **kwargs):
630         context = super(Listen, self).get_context_data(**kwargs)
631         context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
632                 podcastable=True, got_focus__isnull=False) \
633                 .select_related().extra(select={
634                     'first_diffusion': 'emissions_diffusion.datetime', },
635                     select_params=(False, True),
636                     where=['''datetime = (SELECT MIN(datetime)
637                                             FROM emissions_diffusion
638                                         WHERE episode_id = emissions_episode.id)'''],
639                     tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
640         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
641                 podcastable=True) \
642                 .select_related().extra(select={
643                     'first_diffusion': 'emissions_diffusion.datetime', },
644                     select_params=(False, True),
645                     where=['''datetime = (SELECT MIN(datetime)
646                                             FROM emissions_diffusion
647                                         WHERE episode_id = emissions_episode.id)'''],
648                     tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
649
650
651         return context
652
653 listen = Listen.as_view()
654
655 @cache_control(max_age=15)
656 @csrf_exempt
657 def onair(request):
658     if datetime.now() < datetime(2018, 7, 31, 18, 0):
659         return {'emission': {'title': 'À partir du 31 juillet 18h', 'url': '/'}}
660     if date.today() > date(2018, 8, 5):
661         return {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}
662     d = whatsonair()
663     if d.get('episode'):
664         d['episode'] = {
665             'title': d['episode'].title,
666             'url': d['episode'].get_absolute_url()
667         }
668     if d.get('emission'):
669         chat_url = None
670         if d['emission'].chat_open:
671             chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
672         d['emission'] = {
673             'title': d['emission'].title,
674             'url': d['emission'].get_absolute_url(),
675             'chat': chat_url,
676         }
677     if d.get('nonstop'):
678         d['nonstop'] = {
679             'title': d['nonstop'].title,
680         }
681         playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
682         if os.path.exists(os.path.join(playing_txt)):
683             d['track_title'] = open(playing_txt).read().strip()
684     if d.get('current_slot'):
685         del d['current_slot']
686     return JsonResponse(d)
687
688
689 class NewsItemDetailView(DetailView):
690     model = NewsItem
691
692 newsitem = NewsItemDetailView.as_view()
693
694 class RssCustomPodcastsFeed(Rss201rev2Feed):
695     def add_root_elements(self, handler):
696         super(RssCustomPodcastsFeed, self).add_root_elements(handler)
697         emission = self.feed.get('emission')
698         if emission and emission.image and emission.image.url:
699             image_url = emission.image.url
700         else:
701             image_url = '/static/img/logo-panik-500.png'
702         image_url = urlparse.urljoin(self.feed['link'], image_url)
703         handler.startElement('image', {})
704         if emission:
705             handler.addQuickElement('title', emission.title)
706         else:
707             handler.addQuickElement('title', 'Radio Esperanzah!')
708         handler.addQuickElement('url', image_url)
709         handler.endElement('image')
710         handler.addQuickElement('itunes:image', None, {'href': image_url})
711         if emission and emission.subtitle:
712             handler.addQuickElement('itunes:subtitle', emission.subtitle)
713
714     def root_attributes(self):
715         attrs = super(RssCustomPodcastsFeed, self).root_attributes()
716         attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
717         attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
718         return attrs
719
720     def add_item_elements(self, handler, item):
721         super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
722         explicit = 'no'
723         for tag in item.get('tags') or []:
724             handler.addQuickElement('dc:subject', tag)
725             if tag == 'explicit':
726                 explicit = 'yes'
727         if item.get('tags'):
728             handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
729         handler.addQuickElement('itunes:explicit', explicit)
730         episode = item.get('episode')
731         if episode and episode.image and episode.image.url:
732             image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
733             handler.addQuickElement('itunes:image', None, {'href': image_url})
734         soundfile = item.get('soundfile')
735         if soundfile.duration:
736             handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
737                 soundfile.duration / 3600,
738                 soundfile.duration % 3600 / 60,
739                 soundfile.duration % 60))
740
741
742 class PodcastsFeed(Feed):
743     title = 'Radio Esperanzah! - Podcasts'
744     link = '/'
745     description_template = 'feed/soundfile.html'
746     feed_type = RssCustomPodcastsFeed
747
748     def items(self):
749         return SoundFile.objects.select_related().filter(
750                 podcastable=True).order_by('-creation_timestamp')[:20]
751
752     def item_title(self, item):
753         if item.fragment:
754             return '%s - %s' % (item.title, item.episode.title)
755         return '%s - %s' % (item.episode.emission.title, item.episode.title)
756
757     def item_link(self, item):
758         return item.episode.get_absolute_url()
759
760     def item_enclosure_url(self, item):
761         current_site = Site.objects.get(id=settings.SITE_ID)
762         return add_domain(current_site.domain, item.get_format_url('mp3'))
763
764     def item_enclosure_length(self, item):
765         sound_path = item.get_format_path('mp3')
766         try:
767             return os.stat(sound_path)[stat.ST_SIZE]
768         except OSError:
769             return 0
770
771     def item_enclosure_mime_type(self, item):
772         return 'audio/mpeg'
773
774     def item_pubdate(self, item):
775         return item.creation_timestamp
776
777     def item_extra_kwargs(self, item):
778         return {'tags': [x.name for x in item.episode.tags.all()],
779                 'soundfile': item,
780                 'episode': item.episode}
781
782 podcasts_feed = PodcastsFeed()
783
784
785 class RssNewsFeed(Feed):
786     title = 'Radio Esperanzah!'
787     link = '/news/'
788     description_template = 'feed/newsitem.html'
789
790     def items(self):
791         return NewsItem.objects.order_by('-date')[:20]
792
793 rss_news_feed = RssNewsFeed()
794
795 class Atom1FeedWithBaseXml(Atom1Feed):
796     def root_attributes(self):
797         root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
798         scheme, netloc, path, params, query, fragment  = urlparse.urlparse(self.feed['feed_url'])
799         root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
800         return root_attributes
801
802 class AtomNewsFeed(RssNewsFeed):
803     feed_type = Atom1FeedWithBaseXml
804
805 atom_news_feed = AtomNewsFeed()
806
807
808 class EmissionPodcastsFeed(PodcastsFeed):
809     description_template = 'feed/soundfile.html'
810     feed_type = RssCustomPodcastsFeed
811
812     def __call__(self, request, *args, **kwargs):
813         self.emission = Emission.objects.get(slug=kwargs.get('slug'))
814         return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
815
816     @property
817     def title(self):
818         return self.emission.title
819
820     @property
821     def link(self):
822         return reverse('emission-view', kwargs={'slug': self.emission.slug})
823
824     def feed_extra_kwargs(self, obj):
825         return {'emission': self.emission}
826
827     def items(self):
828         return SoundFile.objects.select_related().filter(
829                 podcastable=True,
830                 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
831
832 emission_podcasts_feed = EmissionPodcastsFeed()
833
834
835 class Party(TemplateView):
836     template_name = 'party.html'
837
838     def get_context_data(self, **kwargs):
839         context = super(Party, self).get_context_data(**kwargs)
840         t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
841         focus = Focus()
842         if t == 'newsitem':
843             focus.newsitem = NewsItem.objects.exclude(
844                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
845         elif t == 'emission':
846             focus.emission = Emission.objects.exclude(
847                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
848         elif t == 'episode':
849             focus.episode = Episode.objects.exclude(
850                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
851         elif t == 'soundfile':
852             focus.soundfile = SoundFile.objects.exclude(
853                     episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
854
855         context['focus'] = focus
856
857         return context
858
859 party = Party.as_view()
860
861
862
863 class Chat(DetailView, EmissionMixin):
864     model = Emission
865     template_name = 'chat.html'
866
867 chat = cache_control(max_age=15)(Chat.as_view())
868
869
870
871 class ArchivesView(TemplateView):
872     template_name = 'archives.html'
873
874     def get_context_data(self, **kwargs):
875         context = super(ArchivesView, self).get_context_data(**kwargs)
876         context['diffusions'] = Diffusion.objects.filter(episode__soundfile__isnull=False).distinct().order_by('-datetime')
877         return context
878
879 archives = ArchivesView.as_view()