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