]> git.0d.be Git - panikweb.git/blob - panikweb/views.py
use pages to get to topiks
[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
8 from django.core.urlresolvers import reverse
9 from django.conf import settings
10 from django.http import Http404, JsonResponse
11 from django.utils.encoding import force_text
12 from django.utils.encoding import python_2_unicode_compatible
13 from django.utils.six.moves.urllib import parse as urlparse
14 from django.views.decorators.cache import cache_control
15 from django.views.generic.base import TemplateView
16 from django.views.generic.detail import DetailView
17 from django.views.decorators.csrf import csrf_exempt
18 from django.views.generic.dates import _date_from_string
19 from django.views.generic.dates import MonthArchiveView
20
21 from django.core.paginator import Paginator
22
23 from django.contrib.sites.models import Site
24 from django.contrib.syndication.views import Feed, add_domain
25 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
26
27 from haystack.query import SearchQuerySet
28
29 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
30         Schedule, Nonstop, NewsItem, NewsCategory, Focus
31 from emissions.views import EmissionEpisodeMixin
32 from emissions.utils import whatsonair, period_program
33
34 from newsletter.forms import SubscribeForm
35 from nonstop.utils import get_current_nonstop_track
36 from nonstop.models import SomaLogLine
37
38 from panikombo.models import ItemTopik
39
40 from . import utils
41
42
43 class EmissionMixin:
44     def get_emission_context(self, emission, episode_ids=None):
45         context = {}
46
47         # get all episodes, with an additional attribute to get the date of
48         # their first diffusion
49         episodes_queryset = Episode.objects.select_related()
50         if episode_ids is not None:
51             episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
52         else:
53             episodes_queryset = episodes_queryset.filter(emission=emission)
54
55         context['episodes'] = \
56                 episodes_queryset.extra(select={
57                         'first_diffusion': 'emissions_diffusion.datetime',
58                         },
59                         select_params=(False, True),
60                         where=['''datetime = (SELECT MIN(datetime)
61                                                 FROM emissions_diffusion
62                                                WHERE episode_id = emissions_episode.id
63                                                  AND datetime <= CURRENT_TIMESTAMP)'''],
64                         tables=['emissions_diffusion'],
65                     ).order_by('-first_diffusion').distinct()
66
67         context['futurEpisodes'] = \
68                 episodes_queryset.extra(select={
69                         'first_diffusion': 'emissions_diffusion.datetime',
70                         },
71                         select_params=(False, True),
72                         where=['''datetime = (SELECT MIN(datetime)
73                                                 FROM emissions_diffusion
74                                                WHERE episode_id = emissions_episode.id
75                                                  AND datetime > CURRENT_TIMESTAMP)'''],
76                         tables=['emissions_diffusion'],
77                     ).order_by('first_diffusion').distinct()
78
79
80         # get all related soundfiles in a single query
81         soundfiles = {}
82         if episode_ids is not None:
83             for episode_id in episode_ids:
84                 soundfiles[episode_id] = None
85         else:
86             for episode in Episode.objects.filter(emission=emission):
87                 soundfiles[episode.id] = None
88
89         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
90                 fragment=False, episode__emission=emission):
91             soundfiles[soundfile.episode_id] = soundfile
92
93         Episode.set_prefetched_soundfiles(soundfiles)
94
95         #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
96
97         return context
98
99
100 class EmissionDetailView(DetailView, EmissionMixin):
101     model = Emission
102
103     def get_context_data(self, **kwargs):
104         context = super(EmissionDetailView, self).get_context_data(**kwargs)
105         context['schedules'] = Schedule.objects.select_related().filter(
106                 emission=self.object).order_by('rerun', 'datetime')
107         context['news'] = NewsItem.objects.all(
108                 ).filter(emission=self.object.id
109                 ).exclude(expiration_date__lt=date.today()  # expiration date
110                 ).exclude(date__lt=date.today() - timedelta(days=60)
111                 ).order_by('-date')[:3]
112         try:
113             nonstop_object = Nonstop.objects.get(slug=self.object.slug)
114         except Nonstop.DoesNotExist:
115             pass
116         else:
117             today = date.today()
118             dates = [today - timedelta(days=x) for x in range(7)]
119             if datetime.now().time() < nonstop_object.start:
120                 dates = dates[1:]
121             context['nonstop'] = nonstop_object
122             context['nonstop_dates'] = dates
123         context.update(self.get_emission_context(self.object))
124         return context
125 emission = EmissionDetailView.as_view()
126
127
128 class EpisodeDetailView(EmissionEpisodeMixin, DetailView, EmissionMixin):
129     model = Episode
130
131     def get_context_data(self, **kwargs):
132         context = super(EpisodeDetailView, self).get_context_data(**kwargs)
133         context['diffusions'] = Diffusion.objects.select_related().filter(
134                 episode=self.object.id).order_by('datetime')
135         try:
136             context['emission'] = context['episode'].emission
137         except Emission.DoesNotExist:
138             raise Http404()
139         if self.kwargs.get('emission_slug') != context['emission'].slug:
140             raise Http404()
141         context.update(self.get_emission_context(context['emission']))
142         context['topik_pages'] = [x.page for x in ItemTopik.objects.filter(episode=self.object)]
143         return context
144
145
146 episode = EpisodeDetailView.as_view()
147
148
149 class NonstopPlaylistView(TemplateView):
150     template_name = 'nonstop_playlist.html'
151
152     def get_context_data(self, **kwargs):
153         context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
154         try:
155             context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
156         except Emission.DoesNotExist:
157             raise Http404()
158         context['date'] = date(int(kwargs.get('year')),
159                 int(kwargs.get('month')), int(kwargs.get('day')))
160         context['future'] = (context['date'] >= date.today())
161
162         nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
163         start = datetime(
164                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
165                 nonstop_object.start.hour, nonstop_object.start.minute)
166         end = datetime(
167                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
168                 nonstop_object.end.hour, nonstop_object.end.minute)
169         if end < start:
170             end = end + timedelta(days=1)
171         context['tracks'] = SomaLogLine.objects.filter(
172                 play_timestamp__gte=start,
173                 play_timestamp__lte=end,
174                 on_air=True).select_related()
175         return context
176
177 nonstop_playlist = NonstopPlaylistView.as_view()
178
179 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
180     model = Emission
181     template_name = 'emissions/episodes.html'
182
183     def get_context_data(self, **kwargs):
184         context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
185         context['schedules'] = Schedule.objects.select_related().filter(
186                 emission=self.object).order_by('rerun', 'datetime')
187
188         context['search_query'] = self.request.GET.get('q')
189         if context['search_query']:
190             # query string
191             sqs = SearchQuerySet().models(Episode).filter(
192                     emission_slug_exact=self.object.slug, text=context['search_query'])
193             episode_ids = [x.pk for x in sqs]
194         else:
195             episode_ids = None
196
197         context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
198         return context
199 emissionEpisodes = EmissionEpisodesDetailView.as_view()
200
201
202 class SoundFileEmbedView(DetailView):
203     model = SoundFile
204     template_name = 'soundfiles/embed.html'
205
206     def get_context_data(self, **kwargs):
207         context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
208         if self.kwargs.get('episode_slug') != self.object.episode.slug:
209             raise Http404()
210         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
211             raise Http404()
212         context['episode'] = self.object.episode
213         return context
214 soundfile_embed = SoundFileEmbedView.as_view()
215
216
217 class SoundFileDialogEmbedView(DetailView):
218     model = SoundFile
219     template_name = 'soundfiles/dialog-embed.html'
220
221     def get_context_data(self, **kwargs):
222         context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
223         if self.kwargs.get('episode_slug') != self.object.episode.slug:
224             raise Http404()
225         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
226             raise Http404()
227         context['episode'] = self.object.episode
228         return context
229 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
230
231
232
233 class ProgramView(TemplateView):
234     template_name = 'program.html'
235
236     def get_context_data(self, year=None, week=None, **kwargs):
237         context = super(ProgramView, self).get_context_data(**kwargs)
238
239         context['weekday'] = datetime.today().weekday()
240
241         context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
242         context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
243         context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
244         context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
245
246         return context
247
248 program = ProgramView.as_view()
249
250 @python_2_unicode_compatible
251 class TimeCell:
252     nonstop = None
253     w = 1
254     h = 1
255     time_label = None
256
257     def __init__(self, i, j):
258         self.x = i
259         self.y = j
260         self.schedules = []
261
262     def add_schedule(self, schedule):
263         end_time = schedule.datetime + timedelta(
264                 minutes=schedule.get_duration())
265         self.time_label = '%02d:%02d-%02d:%02d' % (
266                 schedule.datetime.hour,
267                 schedule.datetime.minute,
268                 end_time.hour,
269                 end_time.minute)
270         self.schedules.append(schedule)
271
272     def sorted_schedules(self):
273         return sorted(self.schedules, key=lambda x: x.week_sort_key())
274
275     def __str__(self):
276         if self.schedules:
277             return ', '.join([x.emission.title for x in self.schedules])
278         else:
279             return self.nonstop
280
281     def __eq__(self, other):
282         return (force_text(self) == force_text(other) and self.time_label == other.time_label)
283
284
285 class Grid(TemplateView):
286     template_name = 'grid.html'
287
288     def get_context_data(self, **kwargs):
289         context = super(Grid, self).get_context_data(**kwargs)
290
291         nb_lines = 2 * 24 # the cells are half hours
292         grid = []
293
294         times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
295         # start grid after the night programs
296         times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
297
298         nonstops = []
299         for nonstop in Nonstop.objects.all():
300             if nonstop.start == nonstop.end:
301                 continue
302             if nonstop.start < nonstop.end:
303                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
304                                  nonstop.end.hour + nonstop.end.minute/60.,
305                                  nonstop.title, nonstop.slug, nonstop])
306             else:
307                 # crossing midnight
308                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
309                                  24,
310                                  nonstop.title, nonstop.slug, nonstop])
311                 nonstops.append([0,
312                                  nonstop.end.hour + nonstop.end.minute/60.,
313                                  nonstop.title, nonstop.slug, nonstop])
314         nonstops.sort()
315
316         for i in range(nb_lines):
317             grid.append([])
318             for j in range(7):
319                 grid[-1].append(TimeCell(i, j))
320
321             nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
322             for time_cell in grid[-1]:
323                 time_cell.nonstop = nonstop[2]
324                 time_cell.nonstop_slug = nonstop[3]
325                 time_cell.redirect_path = nonstop[4].redirect_path
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(key=lambda x: x.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(key=lambda x: -x.get_duration())
472                                     # then we add individual time labels to the
473                                     # other schedules
474                                     for schedule in current_cell_schedules:
475                                         if schedule not in same_cell_below.schedules:
476                                             end_time = schedule.datetime + timedelta(
477                                                     minutes=schedule.get_duration())
478                                             schedule.time_label = '%02d:%02d-%02d:%02d' % (
479                                                     schedule.datetime.hour,
480                                                     schedule.datetime.minute,
481                                                     end_time.hour,
482                                                     end_time.minute)
483                                     grid[i][j].h += 1
484                                     grid[i+cursor].remove(same_cell_below)
485                                 elif same_cell_below_emissions and \
486                                         current_cell_emissions.intersection(same_cell_below_emissions):
487                                     same_cell_below.schedules = [x for x in
488                                             same_cell_below.schedules if
489                                             x.emission not in
490                                             current_cell_emissions or
491                                             x.get_duration() < 30]
492                                 cursor += 1
493                             break
494                 except IndexError:
495                     pass
496
497         # cut night at 3am
498         grid = grid[:42]
499         times = times[:42]
500
501         context['grid'] = grid
502         context['times'] = times
503         context['categories'] = Category.objects.all()
504         context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
505                 'Vendredi', 'Samedi', 'Dimanche']
506
507         return context
508
509 grid = Grid.as_view()
510
511
512 class Home(TemplateView):
513     template_name = 'home.html'
514
515     def get_context_data(self, **kwargs):
516         context = super(Home, self).get_context_data(**kwargs)
517         context['emissions'] = Emission.objects.filter(archived=False).order_by('-creation_timestamp')[:3]
518         context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')[:3]
519
520         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
521                 podcastable=True, fragment=False) \
522                 .select_related().extra(select={
523                     'first_diffusion': 'emissions_diffusion.datetime', },
524                     select_params=(False, True),
525                     where=['''datetime = (SELECT MIN(datetime)
526                                             FROM emissions_diffusion
527                                         WHERE episode_id = emissions_episode.id)'''],
528                     tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
529
530         context['newsletter_form'] = SubscribeForm()
531
532         return context
533
534 home = Home.as_view()
535
536
537 class NewsItemView(DetailView):
538     model = NewsItem
539
540     def get_context_data(self, **kwargs):
541         context = super(NewsItemView, self).get_context_data(**kwargs)
542         context['categories'] = NewsCategory.objects.all()
543         context['news'] = NewsItem.objects.all().order_by('-date')
544         context['topik_pages'] = [x.page for x in ItemTopik.objects.filter(newsitem=self.object)]
545         return context
546
547
548 newsitemview = NewsItemView.as_view()
549
550
551 class News(TemplateView):
552     template_name = 'news.html'
553     def get_context_data(self, **kwargs):
554         context = super(News, self).get_context_data(**kwargs)
555         context['focus'] = NewsItem.objects.exclude(date__gt=date.today()  # publication date
556                 ).exclude(expiration_date__lt=date.today()  # expiration date
557                 ).filter(got_focus__isnull=False
558                 ).select_related('category').order_by('-date')[:10]
559         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
560         return context
561
562 news = News.as_view()
563
564
565 class Agenda(TemplateView):
566     template_name = 'agenda.html'
567     def get_context_data(self, **kwargs):
568         context = super(Agenda, self).get_context_data(**kwargs)
569         context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
570                 event_date__gte=date.today()).order_by('date')[:20]
571         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
572         context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
573         return context
574
575 agenda = Agenda.as_view()
576
577
578 class AgendaByMonth(MonthArchiveView):
579     template_name = 'agenda.html'
580     queryset = NewsItem.objects.filter(event_date__isnull=False)
581     allow_future = True
582     date_field = 'event_date'
583     month_format = '%m'
584
585     def get_context_data(self, **kwargs):
586         context = super(AgendaByMonth, self).get_context_data(**kwargs)
587         context['agenda'] = context['object_list']
588         context['news'] = NewsItem.objects.all().order_by('-date')
589         return context
590
591 agenda_by_month = AgendaByMonth.as_view()
592
593
594 class Emissions(TemplateView):
595     template_name = 'emissions.html'
596
597     def get_context_data(self, **kwargs):
598         context = super(Emissions, self).get_context_data(**kwargs)
599         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
600         context['categories'] = Category.objects.all()
601         return context
602
603 emissions = Emissions.as_view()
604
605 class EmissionsArchives(TemplateView):
606     template_name = 'emissions/archives.html'
607
608     def get_context_data(self, **kwargs):
609         context = super(EmissionsArchives, self).get_context_data(**kwargs)
610         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
611         context['categories'] = Category.objects.all()
612         return context
613 emissionsArchives = EmissionsArchives.as_view()
614
615
616 class Listen(TemplateView):
617     template_name = 'listen.html'
618
619     def get_context_data(self, **kwargs):
620         context = super(Listen, self).get_context_data(**kwargs)
621         context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
622                 podcastable=True, got_focus__isnull=False) \
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('-first_diffusion').distinct() [:10]
630         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
631                 podcastable=True) \
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('-creation_timestamp').distinct()
639
640
641         return context
642
643 listen = Listen.as_view()
644
645 @cache_control(max_age=15)
646 @csrf_exempt
647 def onair(request):
648     d = whatsonair()
649     if d.get('episode'):
650         d['episode'] = {
651             'title': d['episode'].title,
652             'url': d['episode'].get_absolute_url()
653         }
654     if d.get('emission'):
655         chat_url = None
656         if d['emission'].chat_open:
657             chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
658         d['emission'] = {
659             'title': d['emission'].title,
660             'url': d['emission'].get_absolute_url(),
661             'chat': chat_url,
662         }
663     if d.get('nonstop'):
664         redirect_path = d['nonstop'].redirect_path
665         d['nonstop'] = {
666             'title': d['nonstop'].title,
667         }
668         if redirect_path:
669             d['nonstop']['url'] = redirect_path
670         d.update(get_current_nonstop_track())
671     if d.get('current_slot'):
672         del d['current_slot']
673     return JsonResponse({'data': d})
674
675
676 class NewsItemDetailView(DetailView):
677     model = NewsItem
678
679 newsitem = NewsItemDetailView.as_view()
680
681 class RssCustomPodcastsFeed(Rss201rev2Feed):
682     def add_root_elements(self, handler):
683         super(RssCustomPodcastsFeed, self).add_root_elements(handler)
684         emission = self.feed.get('emission')
685         if emission and emission.image and emission.image.url:
686             image_url = emission.image.url
687         else:
688             image_url = '/static/img/logo-panik-500.png'
689         image_url = urlparse.urljoin(self.feed['link'], image_url)
690         handler.startElement('image', {})
691         if emission:
692             handler.addQuickElement('title', emission.title)
693         else:
694             handler.addQuickElement('title', settings.RADIO_NAME)
695         handler.addQuickElement('url', image_url)
696         handler.endElement('image')
697         handler.addQuickElement('itunes:explicit', 'no')  # invidividual items will get their own value
698         handler.addQuickElement('itunes:image', None, {'href': image_url})
699         if emission:
700             if emission.subtitle:
701                 handler.addQuickElement('itunes:subtitle', emission.subtitle)
702             for category in emission.categories.all():
703                 if category.itunes_category:
704                     handler.addQuickElement('itunes:category', None, {'text': category.itunes_category})
705
706             handler.addQuickElement('itunes:author', emission.title)
707             handler.startElement('itunes:owner', {})
708             if emission.email:
709                 handler.addQuickElement('itunes:email', emission.email)
710             handler.addQuickElement('itunes:name', emission.title)
711             handler.endElement('itunes:owner')
712         else:
713             handler.addQuickElement('itunes:author', settings.RADIO_NAME)
714             handler.startElement('itunes:owner', {})
715             handler.addQuickElement('itunes:email', 'info@radiopanik.org')
716             handler.addQuickElement('itunes:name', settings.RADIO_NAME)
717             handler.endElement('itunes:owner')
718
719     def root_attributes(self):
720         attrs = super(RssCustomPodcastsFeed, self).root_attributes()
721         attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
722         attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
723         return attrs
724
725     def add_item_elements(self, handler, item):
726         super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
727         explicit = 'no'
728         for tag in item.get('tags') or []:
729             handler.addQuickElement('dc:subject', tag)
730             if tag == 'explicit':
731                 explicit = 'yes'
732         if item.get('tags'):
733             handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
734         handler.addQuickElement('itunes:explicit', explicit)
735         episode = item.get('episode')
736         if episode and episode.image and episode.image.url:
737             image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
738             handler.addQuickElement('itunes:image', None, {'href': image_url})
739         soundfile = item.get('soundfile')
740         if soundfile.duration:
741             handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
742                 soundfile.duration / 3600,
743                 soundfile.duration % 3600 / 60,
744                 soundfile.duration % 60))
745
746
747 class PodcastsFeed(Feed):
748     title = '%s - Podcasts' % settings.RADIO_NAME
749     link = '/'
750     description_template = 'feed/soundfile.html'
751     feed_type = RssCustomPodcastsFeed
752
753     def items(self):
754         return SoundFile.objects.select_related().filter(
755                 podcastable=True).order_by('-creation_timestamp')[:50]
756
757     def item_title(self, item):
758         if item.fragment:
759             return '[%s] %s - %s' % (item.episode.emission.title, item.title, item.episode.title)
760         return '[%s] %s' % (item.episode.emission.title, item.episode.title)
761
762     def item_link(self, item):
763         if item.fragment:
764             return item.episode.get_absolute_url() + '#%s' % item.id
765         return item.episode.get_absolute_url()
766
767     def item_enclosure_url(self, item):
768         current_site = Site.objects.get(id=settings.SITE_ID)
769         return add_domain(current_site.domain, item.get_format_url('mp3'))
770
771     def item_enclosure_length(self, item):
772         sound_path = item.get_format_path('mp3')
773         try:
774             return os.stat(sound_path)[stat.ST_SIZE]
775         except OSError:
776             return 0
777
778     def item_enclosure_mime_type(self, item):
779         return 'audio/mpeg'
780
781     def item_pubdate(self, item):
782         return item.creation_timestamp
783
784     def item_extra_kwargs(self, item):
785         return {'tags': [x.name for x in item.episode.tags.all()],
786                 'soundfile': item,
787                 'episode': item.episode}
788
789 podcasts_feed = PodcastsFeed()
790
791
792 class RssNewsFeed(Feed):
793     title = settings.RADIO_NAME
794     link = '/news/'
795     description_template = 'feed/newsitem.html'
796
797     def items(self):
798         return NewsItem.objects.order_by('-date')[:20]
799
800 rss_news_feed = RssNewsFeed()
801
802 class Atom1FeedWithBaseXml(Atom1Feed):
803     def root_attributes(self):
804         root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
805         scheme, netloc, path, params, query, fragment  = urlparse.urlparse(self.feed['feed_url'])
806         root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
807         return root_attributes
808
809 class AtomNewsFeed(RssNewsFeed):
810     feed_type = Atom1FeedWithBaseXml
811
812 atom_news_feed = AtomNewsFeed()
813
814
815 class EmissionPodcastsFeed(PodcastsFeed):
816     description_template = 'feed/soundfile.html'
817     feed_type = RssCustomPodcastsFeed
818
819     def __call__(self, request, *args, **kwargs):
820         self.emission = Emission.objects.get(slug=kwargs.get('slug'))
821         return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
822
823     def item_title(self, item):
824         if item.fragment:
825             return '%s - %s' % (item.title, item.episode.title)
826         return item.episode.title
827
828     @property
829     def title(self):
830         return self.emission.title
831
832     @property
833     def description(self):
834         return self.emission.subtitle
835
836     @property
837     def link(self):
838         return reverse('emission-view', kwargs={'slug': self.emission.slug})
839
840     def feed_extra_kwargs(self, obj):
841         return {'emission': self.emission}
842
843     def items(self):
844         return SoundFile.objects.select_related().filter(
845                 podcastable=True,
846                 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:50]
847
848 emission_podcasts_feed = EmissionPodcastsFeed()
849
850
851 class Party(TemplateView):
852     template_name = 'party.html'
853
854     def get_context_data(self, **kwargs):
855         context = super(Party, self).get_context_data(**kwargs)
856         t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
857         focus = Focus()
858         if t == 'newsitem':
859             focus.newsitem = NewsItem.objects.exclude(
860                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
861         elif t == 'emission':
862             focus.emission = Emission.objects.exclude(
863                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
864         elif t == 'episode':
865             focus.episode = Episode.objects.exclude(
866                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
867         elif t == 'soundfile':
868             focus.soundfile = SoundFile.objects.exclude(
869                     episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
870
871         context['focus'] = focus
872
873         return context
874
875 party = Party.as_view()
876
877
878
879 class Chat(DetailView, EmissionMixin):
880     model = Emission
881     template_name = 'chat.html'
882
883 chat = cache_control(max_age=15)(Chat.as_view())