]> git.0d.be Git - panikweb.git/blob - panikweb/views.py
work around a bug in grid
[panikweb.git] / panikweb / views.py
1 # coding: utf-8
2
3 from datetime import datetime, timedelta, date
4 import math
5 import random
6 import os
7 import stat
8 import time
9 import urlparse
10
11 from django.core.urlresolvers import reverse
12 from django.conf import settings
13 from django.http import Http404
14 from django.views.decorators.cache import cache_control
15 from django.views.generic.base import TemplateView
16 from django.views.generic.detail import DetailView
17 from django.views.decorators.csrf import csrf_exempt
18 from django.views.generic.dates import _date_from_string
19 from django.views.generic.dates import MonthArchiveView
20
21 from django.core.paginator import Paginator
22
23 from django.contrib.sites.models import Site
24 from django.contrib.syndication.views import Feed, add_domain
25 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
26
27 from haystack.query import SearchQuerySet
28 from jsonresponse import to_json
29
30 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
31         Schedule, Nonstop, NewsItem, NewsCategory, Focus
32
33 from emissions.utils import whatsonair, period_program
34
35 from newsletter.forms import SubscribeForm
36 from nonstop.utils import get_current_nonstop_track
37 from nonstop.models import SomaLogLine
38
39 from combo.data.models import Page
40 from panikombo.models import ItemTopik
41
42 from . import utils
43
44
45 class EmissionMixin:
46     def get_emission_context(self, emission, episode_ids=None):
47         context = {}
48
49         # get all episodes, with an additional attribute to get the date of
50         # their first diffusion
51         episodes_queryset = Episode.objects.select_related()
52         if episode_ids is not None:
53             episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
54         else:
55             episodes_queryset = episodes_queryset.filter(emission=emission)
56
57         context['episodes'] = \
58                 episodes_queryset.extra(select={
59                         'first_diffusion': 'emissions_diffusion.datetime',
60                         },
61                         select_params=(False, True),
62                         where=['''datetime = (SELECT MIN(datetime)
63                                                 FROM emissions_diffusion
64                                                WHERE episode_id = emissions_episode.id
65                                                  AND datetime <= CURRENT_TIMESTAMP)'''],
66                         tables=['emissions_diffusion'],
67                     ).order_by('-first_diffusion').distinct()
68
69         context['futurEpisodes'] = \
70                 episodes_queryset.extra(select={
71                         'first_diffusion': 'emissions_diffusion.datetime',
72                         },
73                         select_params=(False, True),
74                         where=['''datetime = (SELECT MIN(datetime)
75                                                 FROM emissions_diffusion
76                                                WHERE episode_id = emissions_episode.id
77                                                  AND datetime > CURRENT_TIMESTAMP)'''],
78                         tables=['emissions_diffusion'],
79                     ).order_by('first_diffusion').distinct()
80
81         if emission.archived:
82             current_year = emission.creation_timestamp.replace(month=5, day=1)
83         else:
84             current_year = datetime.now().replace(month=5, day=1)
85
86         context['all_episodes'] = episodes_queryset.filter(
87                 creation_timestamp__gt=current_year
88                 ).extra(select={
89                         'first_diffusion': 'emissions_diffusion.datetime',
90                         },
91                         select_params=(False, True),
92                         where=['''datetime = (SELECT MIN(datetime)
93                                                 FROM emissions_diffusion
94                                                WHERE episode_id = emissions_episode.id
95                                              )'''],
96                         tables=['emissions_diffusion'],
97                     ).order_by('first_diffusion').distinct()
98
99         # get all related soundfiles in a single query
100         soundfiles = {}
101         if episode_ids is not None:
102             for episode_id in episode_ids:
103                 soundfiles[episode_id] = None
104         else:
105             for episode in Episode.objects.filter(emission=emission):
106                 soundfiles[episode.id] = None
107
108         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
109                 fragment=False, episode__emission=emission):
110             soundfiles[soundfile.episode_id] = soundfile
111
112         Episode.set_prefetched_soundfiles(soundfiles)
113
114         #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
115
116         return context
117
118
119 class EmissionDetailView(DetailView, EmissionMixin):
120     model = Emission
121
122     def get_context_data(self, **kwargs):
123         context = super(EmissionDetailView, self).get_context_data(**kwargs)
124         context['schedules'] = Schedule.objects.select_related().filter(
125                 emission=self.object).order_by('rerun', 'datetime')
126         context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
127         try:
128             nonstop_object = Nonstop.objects.get(slug=self.object.slug)
129         except Nonstop.DoesNotExist:
130             pass
131         else:
132             today = date.today()
133             dates = [today - timedelta(days=x) for x in range(7)]
134             if datetime.now().time() < nonstop_object.start:
135                 dates = dates[1:]
136             context['nonstop'] = nonstop_object
137             context['nonstop_dates'] = dates
138         context.update(self.get_emission_context(self.object))
139         return context
140 emission = EmissionDetailView.as_view()
141
142 class EpisodeDetailView(DetailView, EmissionMixin):
143     model = Episode
144
145     def get_queryset(self, *args, **kwargs):
146         queryset = super(EpisodeDetailView, self).get_queryset(*args, **kwargs)
147         return queryset.filter(emission__slug=self.kwargs['emission_slug'])
148
149     def get_context_data(self, **kwargs):
150         context = super(EpisodeDetailView, self).get_context_data(**kwargs)
151         context['diffusions'] = Diffusion.objects.select_related().filter(
152                 episode=self.object.id).order_by('datetime')
153         try:
154             context['emission'] = context['episode'].emission
155         except Emission.DoesNotExist:
156             raise Http404()
157         if self.kwargs.get('emission_slug') != context['emission'].slug:
158             raise Http404()
159         context.update(self.get_emission_context(context['emission']))
160         context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
161         return context
162 episode = EpisodeDetailView.as_view()
163
164
165 class NonstopPlaylistView(TemplateView):
166     template_name = 'nonstop_playlist.html'
167
168     def get_context_data(self, **kwargs):
169         context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
170         try:
171             context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
172         except Emission.DoesNotExist:
173             raise Http404()
174         context['date'] = date(int(kwargs.get('year')),
175                 int(kwargs.get('month')), int(kwargs.get('day')))
176         context['future'] = (context['date'] >= date.today())
177
178         nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
179         start = datetime(
180                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
181                 nonstop_object.start.hour, nonstop_object.start.minute)
182         end = datetime(
183                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
184                 nonstop_object.end.hour, nonstop_object.end.minute)
185         if end < start:
186             end = end + timedelta(days=1)
187         context['tracks'] = SomaLogLine.objects.filter(
188                 play_timestamp__gte=start,
189                 play_timestamp__lte=end,
190                 on_air=True).select_related()
191         return context
192
193 nonstop_playlist = NonstopPlaylistView.as_view()
194
195 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
196     model = Emission
197     template_name = 'emissions/episodes.html'
198
199     def get_context_data(self, **kwargs):
200         context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
201         context['schedules'] = Schedule.objects.select_related().filter(
202                 emission=self.object).order_by('rerun', 'datetime')
203
204         context['search_query'] = self.request.GET.get('q')
205         if context['search_query']:
206             # query string
207             sqs = SearchQuerySet().models(Episode).filter(
208                     emission_slug_exact=self.object.slug, text=context['search_query'])
209             episode_ids = [x.pk for x in sqs]
210         else:
211             episode_ids = None
212
213         context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
214         return context
215 emissionEpisodes = EmissionEpisodesDetailView.as_view()
216
217
218 class SoundFileEmbedView(DetailView):
219     model = SoundFile
220     template_name = 'soundfiles/embed.html'
221
222     def get_context_data(self, **kwargs):
223         context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
224         if self.kwargs.get('episode_slug') != self.object.episode.slug:
225             raise Http404()
226         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
227             raise Http404()
228         context['episode'] = self.object.episode
229         return context
230 soundfile_embed = SoundFileEmbedView.as_view()
231
232
233 class SoundFileDialogEmbedView(DetailView):
234     model = SoundFile
235     template_name = 'soundfiles/dialog-embed.html'
236
237     def get_context_data(self, **kwargs):
238         context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
239         if self.kwargs.get('episode_slug') != self.object.episode.slug:
240             raise Http404()
241         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
242             raise Http404()
243         context['episode'] = self.object.episode
244         return context
245 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
246
247
248
249 class ProgramView(TemplateView):
250     template_name = 'program.html'
251
252     def get_context_data(self, year=None, week=None, **kwargs):
253         context = super(ProgramView, self).get_context_data(**kwargs)
254
255         context['weekday'] = datetime.today().weekday()
256
257         context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
258         context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
259         context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
260         context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
261
262         return context
263
264 program = ProgramView.as_view()
265
266 class TimeCell:
267     nonstop = None
268     w = 1
269     h = 1
270     time_label = None
271
272     def __init__(self, i, j):
273         self.x = i
274         self.y = j
275         self.schedules = []
276
277     def add_schedule(self, schedule):
278         end_time = schedule.datetime + timedelta(
279                 minutes=schedule.get_duration())
280         self.time_label = '%02d:%02d-%02d:%02d' % (
281                 schedule.datetime.hour,
282                 schedule.datetime.minute,
283                 end_time.hour,
284                 end_time.minute)
285         self.schedules.append(schedule)
286
287     def __unicode__(self):
288         if self.schedules:
289             return ', '.join([x.emission.title for x in self.schedules])
290         else:
291             return self.nonstop
292
293     def __eq__(self, other):
294         return (unicode(self) == unicode(other) and self.time_label == other.time_label)
295
296
297 class Grid(TemplateView):
298     template_name = 'grid.html'
299
300     def get_context_data(self, **kwargs):
301         context = super(Grid, self).get_context_data(**kwargs)
302
303         nb_lines = 2 * 24 # the cells are half hours
304         grid = []
305
306         times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
307         # start grid after the night programs
308         times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
309
310         nonstops = []
311         for nonstop in Nonstop.objects.all():
312             if nonstop.start == nonstop.end:
313                 continue
314             if nonstop.start < nonstop.end:
315                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
316                                  nonstop.end.hour + nonstop.end.minute/60.,
317                                  nonstop.title, nonstop.slug])
318             else:
319                 # crossing midnight
320                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
321                                  24,
322                                  nonstop.title, nonstop.slug])
323                 nonstops.append([0,
324                                  nonstop.end.hour + nonstop.end.minute/60.,
325                                  nonstop.title, nonstop.slug])
326         nonstops.sort()
327
328         for i in range(nb_lines):
329             grid.append([])
330             for j in range(7):
331                 grid[-1].append(TimeCell(i, j))
332
333             try:
334                 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
335             except IndexError:
336                 pass
337             for time_cell in grid[-1]:
338                 time_cell.nonstop = nonstop[2]
339                 time_cell.nonstop_slug = nonstop[3]
340                 if nonstop[1] == 5:
341                     # the one ending at 5am will be cut down, so we inscribe
342                     # its duration manually
343                     time_cell.time_label = '%02d:00-%02d:00' % (
344                             nonstop[0], nonstop[1])
345
346         for schedule in Schedule.objects.filter(emission__archived=False).prefetch_related(
347                 'emission__categories').select_related().order_by('datetime'):
348             row_start = schedule.datetime.hour * 2 + \
349                     int(math.ceil(schedule.datetime.minute / 30))
350             day_no = schedule.get_weekday()
351
352             for step in range(int(math.ceil(schedule.get_duration() / 30.))):
353                 if grid[(row_start+step)%nb_lines][day_no] is None:
354                     grid[(row_start+step)%nb_lines][day_no] = TimeCell()
355                 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
356
357         # start grid after the night programs
358         grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
359
360         # look for the case where the same emission has different schedules for
361         # the same time cell, for example if it lasts one hour the first week,
362         # and two hours the third week.
363         for i in range(nb_lines):
364             grid[i] = [x for x in grid[i] if x is not None]
365             for j, cell in enumerate(grid[i]):
366                 if grid[i][j] is None:
367                     continue
368                 if len(grid[i][j].schedules) > 1:
369                     time_cell_emissions = {}
370                     for schedule in grid[i][j].schedules:
371                         if not schedule.emission.id in time_cell_emissions:
372                             time_cell_emissions[schedule.emission.id] = []
373                         time_cell_emissions[schedule.emission.id].append(schedule)
374                     for schedule_list in time_cell_emissions.values():
375                         if len(schedule_list) == 1:
376                             continue
377                         # here it is, same cell, same emission, several
378                         # schedules
379                         schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
380
381                         schedule = schedule_list[0]
382                         end_time = schedule.datetime + timedelta(
383                                 minutes=schedule.get_duration())
384                         grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
385                                 schedule.datetime.hour,
386                                 schedule.datetime.minute,
387                                 end_time.hour,
388                                 end_time.minute)
389
390                         for schedule in schedule_list[1:]:
391                             grid[i][j].schedules.remove(schedule)
392                             end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
393                             schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
394                                     end_time.hour, end_time.minute, schedule.weeks_string)
395
396         # merge adjacent
397
398         # 1st thing is to merge cells on the same line, this will mostly catch
399         # consecutive nonstop cells
400         for i in range(nb_lines):
401             for j, cell in enumerate(grid[i]):
402                 if grid[i][j] is None:
403                     continue
404                 t = 1
405                 try:
406                     # if the cells are identical, they are removed from the
407                     # grid, and current cell width is increased
408                     while grid[i][j+t] == cell:
409                         cell.w += 1
410                         grid[i][j+t] = None
411                         t += 1
412                 except IndexError:
413                     pass
414
415             # once we're done we remove empty cells
416             grid[i] = [x for x in grid[i] if x is not None]
417
418         # 2nd thing is to merge cells vertically, this is emissions that last
419         # for more than 30 minutes
420         for i in range(nb_lines):
421             grid[i] = [x for x in grid[i] if x is not None]
422             for j, cell in enumerate(grid[i]):
423                 if grid[i][j] is None:
424                     continue
425                 t = 1
426                 try:
427                     while True:
428                         # we look if the next time cell has the same emissions
429                         same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
430                                            if x == cell and x.y == cell.y and x.w == cell.w]
431                         if same_cell_below:
432                             # if the cell was identical, we remove it and
433                             # increase current cell height
434                             bj, same_cell_below = same_cell_below[0]
435                             del grid[i+cell.h][bj]
436                             cell.h += 1
437                         else:
438                             # if the cell is different, we have a closer look
439                             # to it, so we can remove emissions that will
440                             # already be mentioned in the current cell.
441                             #
442                             # For example:
443                             #  - 7am30, seuls contre tout, 1h30
444                             #  - 8am, du pied gauche & la voix de la rue, 1h
445                             # should produce: (this is case A)
446                             #  |      7:30-9:00      |
447                             #  |  seuls contre tout  |
448                             #  |---------------------|
449                             #  |      8:00-9:00      |
450                             #  |   du pied gauche    |
451                             #  |  la voix de la rue  |
452                             #
453                             # On the other hand, if all three emissions started
454                             # at 7am30, we want: (this is case B)
455                             #  |      7:30-9:00      |
456                             #  |  seuls contre tout  |
457                             #  |   du pied gauche    |
458                             #  |  la voix de la rue  |
459                             # that is we merge all of them, ignoring the fact
460                             # that the other emissions will stop at 8am30
461                             current_cell_schedules = set(grid[i][j].schedules)
462                             current_cell_emissions = set([x.emission for x in current_cell_schedules])
463                             cursor = 1
464                             while True and current_cell_schedules:
465                                 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
466                                 if not same_cell_below:
467                                     cursor += 1
468                                     continue
469                                 same_cell_below = same_cell_below[0]
470                                 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
471
472                                 if current_cell_emissions.issubset(same_cell_below_emissions):
473                                     # this handles case A (see comment above)
474                                     for schedule in current_cell_schedules:
475                                         if schedule in same_cell_below.schedules:
476                                             same_cell_below.schedules.remove(schedule)
477                                 elif same_cell_below_emissions and \
478                                         current_cell_emissions.issuperset(same_cell_below_emissions):
479                                     # this handles case B (see comment above)
480                                     # we set the cell time label to the longest
481                                     # period
482                                     grid[i][j].time_label = same_cell_below.time_label
483                                     # then we sort emissions so the longest are
484                                     # put first
485                                     grid[i][j].schedules.sort(
486                                             lambda x, y: -cmp(x.get_duration(), y.get_duration()))
487                                     # then we add individual time labels to the
488                                     # other schedules
489                                     for schedule in current_cell_schedules:
490                                         if schedule not in same_cell_below.schedules:
491                                             end_time = schedule.datetime + timedelta(
492                                                     minutes=schedule.get_duration())
493                                             schedule.time_label = '%02d:%02d-%02d:%02d' % (
494                                                     schedule.datetime.hour,
495                                                     schedule.datetime.minute,
496                                                     end_time.hour,
497                                                     end_time.minute)
498                                     grid[i][j].h += 1
499                                     grid[i+cursor].remove(same_cell_below)
500                                 elif same_cell_below_emissions and \
501                                         current_cell_emissions.intersection(same_cell_below_emissions):
502                                     same_cell_below.schedules = [x for x in
503                                             same_cell_below.schedules if
504                                             x.emission not in
505                                             current_cell_emissions or
506                                             x.get_duration() < 30]
507                                 cursor += 1
508                             break
509                 except IndexError:
510                     pass
511
512         # cut night at 3am
513         grid = grid[:42]
514         times = times[:42]
515
516         context['grid'] = grid
517         context['times'] = times
518         context['categories'] = Category.objects.all()
519         context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
520                 'Vendredi', 'Samedi', 'Dimanche']
521
522         return context
523
524 grid = Grid.as_view()
525
526
527 class Home(TemplateView):
528     template_name = 'home.html'
529
530     def get_context_data(self, **kwargs):
531         context = super(Home, self).get_context_data(**kwargs)
532         context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
533         context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
534                 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
535
536         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
537                 podcastable=True, fragment=False) \
538                 .select_related().extra(select={
539                     'first_diffusion': 'emissions_diffusion.datetime', },
540                     select_params=(False, True),
541                     where=['''datetime = (SELECT MIN(datetime)
542                                             FROM emissions_diffusion
543                                         WHERE episode_id = emissions_episode.id)'''],
544                     tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
545
546         context['newsletter_form'] = SubscribeForm()
547         context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
548
549         return context
550
551 home = Home.as_view()
552
553 class NewsItemView(DetailView):
554     model = NewsItem
555     def get_context_data(self, **kwargs):
556         context = super(NewsItemView, self).get_context_data(**kwargs)
557         context['categories'] = NewsCategory.objects.all()
558         context['news'] = NewsItem.objects.all().order_by('-date')
559         context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
560         return context
561 newsitemview = NewsItemView.as_view()
562
563 class News(TemplateView):
564     template_name = 'news.html'
565     def get_context_data(self, **kwargs):
566         context = super(News, self).get_context_data(**kwargs)
567         context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
568         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
569         return context
570
571 news = News.as_view()
572
573
574 class Agenda(TemplateView):
575     template_name = 'agenda.html'
576     def get_context_data(self, **kwargs):
577         context = super(Agenda, self).get_context_data(**kwargs)
578         context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
579                 event_date__gte=date.today()).order_by('date')[:20]
580         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
581         context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
582         return context
583
584 agenda = Agenda.as_view()
585
586
587 class AgendaByMonth(MonthArchiveView):
588     template_name = 'agenda.html'
589     queryset = NewsItem.objects.filter(event_date__isnull=False)
590     allow_future = True
591     date_field = 'event_date'
592     month_format = '%m'
593
594     def get_context_data(self, **kwargs):
595         context = super(AgendaByMonth, self).get_context_data(**kwargs)
596         context['agenda'] = context['object_list']
597         context['news'] = NewsItem.objects.all().order_by('-date')
598         return context
599
600 agenda_by_month = AgendaByMonth.as_view()
601
602
603 class Emissions(TemplateView):
604     template_name = 'emissions.html'
605
606     def get_context_data(self, **kwargs):
607         context = super(Emissions, self).get_context_data(**kwargs)
608         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
609         context['categories'] = Category.objects.all()
610         return context
611
612 emissions = Emissions.as_view()
613
614 class EmissionsArchives(TemplateView):
615     template_name = 'emissions/archives.html'
616
617     def get_context_data(self, **kwargs):
618         context = super(EmissionsArchives, self).get_context_data(**kwargs)
619         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
620         context['categories'] = Category.objects.all()
621         return context
622 emissionsArchives = EmissionsArchives.as_view()
623
624
625 class Listen(TemplateView):
626     template_name = 'listen.html'
627
628     def get_context_data(self, **kwargs):
629         context = super(Listen, self).get_context_data(**kwargs)
630         context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
631                 podcastable=True, got_focus__isnull=False) \
632                 .select_related().extra(select={
633                     'first_diffusion': 'emissions_diffusion.datetime', },
634                     select_params=(False, True),
635                     where=['''datetime = (SELECT MIN(datetime)
636                                             FROM emissions_diffusion
637                                         WHERE episode_id = emissions_episode.id)'''],
638                     tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
639         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
640                 podcastable=True) \
641                 .select_related().extra(select={
642                     'first_diffusion': 'emissions_diffusion.datetime', },
643                     select_params=(False, True),
644                     where=['''datetime = (SELECT MIN(datetime)
645                                             FROM emissions_diffusion
646                                         WHERE episode_id = emissions_episode.id)'''],
647                     tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
648
649
650         return context
651
652 listen = Listen.as_view()
653
654 @cache_control(max_age=15)
655 @csrf_exempt
656 @to_json('api')
657 def onair(request):
658     if date.today() < date(2018, 7, 30):
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 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 '%s - Podcasts' % 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()