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