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