]> git.0d.be Git - panikweb.git/blob - panikweb/views.py
topiks: use a flat list for pages
[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
79         # get all related soundfiles in a single query
80         soundfiles = {}
81         if episode_ids is not None:
82             for episode_id in episode_ids:
83                 soundfiles[episode_id] = None
84         else:
85             for episode in Episode.objects.filter(emission=emission):
86                 soundfiles[episode.id] = None
87
88         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
89                 fragment=False, episode__emission=emission):
90             soundfiles[soundfile.episode_id] = soundfile
91
92         Episode.set_prefetched_soundfiles(soundfiles)
93
94         #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
95
96         return context
97
98
99 class EmissionDetailView(DetailView, EmissionMixin):
100     model = Emission
101
102     def get_context_data(self, **kwargs):
103         context = super(EmissionDetailView, self).get_context_data(**kwargs)
104         context['schedules'] = Schedule.objects.select_related().filter(
105                 emission=self.object).order_by('rerun', 'datetime')
106         context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
107         try:
108             nonstop_object = Nonstop.objects.get(slug=self.object.slug)
109         except Nonstop.DoesNotExist:
110             pass
111         else:
112             today = date.today()
113             dates = [today - timedelta(days=x) for x in range(7)]
114             if datetime.now().time() < nonstop_object.start:
115                 dates = dates[1:]
116             context['nonstop'] = nonstop_object
117             context['nonstop_dates'] = dates
118         context.update(self.get_emission_context(self.object))
119         return context
120 emission = EmissionDetailView.as_view()
121
122 class EpisodeDetailView(DetailView, EmissionMixin):
123     model = Episode
124
125     def get_context_data(self, **kwargs):
126         context = super(EpisodeDetailView, self).get_context_data(**kwargs)
127         context['diffusions'] = Diffusion.objects.select_related().filter(
128                 episode=self.object.id).order_by('datetime')
129         try:
130             context['emission'] = context['episode'].emission
131         except Emission.DoesNotExist:
132             raise Http404()
133         if self.kwargs.get('emission_slug') != context['emission'].slug:
134             raise Http404()
135         context.update(self.get_emission_context(context['emission']))
136         context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
137         return context
138 episode = EpisodeDetailView.as_view()
139
140
141 class NonstopPlaylistView(TemplateView):
142     template_name = 'nonstop_playlist.html'
143
144     def get_context_data(self, **kwargs):
145         context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
146         try:
147             context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
148         except Emission.DoesNotExist:
149             raise Http404()
150         context['date'] = date(int(kwargs.get('year')),
151                 int(kwargs.get('month')), int(kwargs.get('day')))
152         context['future'] = (context['date'] >= date.today())
153
154         nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
155         start = datetime(
156                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
157                 nonstop_object.start.hour, nonstop_object.start.minute)
158         end = datetime(
159                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
160                 nonstop_object.end.hour, nonstop_object.end.minute)
161         if end < start:
162             end = end + timedelta(days=1)
163         context['tracks'] = SomaLogLine.objects.filter(
164                 play_timestamp__gte=start,
165                 play_timestamp__lte=end,
166                 on_air=True).select_related()
167         return context
168
169 nonstop_playlist = NonstopPlaylistView.as_view()
170
171 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
172     model = Emission
173     template_name = 'emissions/episodes.html'
174
175     def get_context_data(self, **kwargs):
176         context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
177         context['schedules'] = Schedule.objects.select_related().filter(
178                 emission=self.object).order_by('rerun', 'datetime')
179
180         context['search_query'] = self.request.GET.get('q')
181         if context['search_query']:
182             # query string
183             sqs = SearchQuerySet().models(Episode).filter(
184                     emission_slug_exact=self.object.slug, text=context['search_query'])
185             episode_ids = [x.pk for x in sqs]
186         else:
187             episode_ids = None
188
189         context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
190         return context
191 emissionEpisodes = EmissionEpisodesDetailView.as_view()
192
193
194 class SoundFileEmbedView(DetailView):
195     model = SoundFile
196     template_name = 'soundfiles/embed.html'
197
198     def get_context_data(self, **kwargs):
199         context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
200         if self.kwargs.get('episode_slug') != self.object.episode.slug:
201             raise Http404()
202         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
203             raise Http404()
204         context['episode'] = self.object.episode
205         return context
206 soundfile_embed = SoundFileEmbedView.as_view()
207
208
209 class SoundFileDialogEmbedView(DetailView):
210     model = SoundFile
211     template_name = 'soundfiles/dialog-embed.html'
212
213     def get_context_data(self, **kwargs):
214         context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
215         if self.kwargs.get('episode_slug') != self.object.episode.slug:
216             raise Http404()
217         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
218             raise Http404()
219         context['episode'] = self.object.episode
220         return context
221 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
222
223
224
225 class ProgramView(TemplateView):
226     template_name = 'program.html'
227
228     def get_context_data(self, year=None, week=None, **kwargs):
229         context = super(ProgramView, self).get_context_data(**kwargs)
230
231         context['weekday'] = datetime.today().weekday()
232
233         context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
234         context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
235         context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
236         context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
237
238         return context
239
240 program = ProgramView.as_view()
241
242 class TimeCell:
243     nonstop = None
244     w = 1
245     h = 1
246     time_label = None
247
248     def __init__(self, i, j):
249         self.x = i
250         self.y = j
251         self.schedules = []
252
253     def add_schedule(self, schedule):
254         end_time = schedule.datetime + timedelta(
255                 minutes=schedule.get_duration())
256         self.time_label = '%02d:%02d-%02d:%02d' % (
257                 schedule.datetime.hour,
258                 schedule.datetime.minute,
259                 end_time.hour,
260                 end_time.minute)
261         self.schedules.append(schedule)
262
263     def __unicode__(self):
264         if self.schedules:
265             return ', '.join([x.emission.title for x in self.schedules])
266         else:
267             return self.nonstop
268
269     def __eq__(self, other):
270         return (unicode(self) == unicode(other) and self.time_label == other.time_label)
271
272
273 class Grid(TemplateView):
274     template_name = 'grid.html'
275
276     def get_context_data(self, **kwargs):
277         context = super(Grid, self).get_context_data(**kwargs)
278
279         nb_lines = 2 * 24 # the cells are half hours
280         grid = []
281
282         times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
283         # start grid after the night programs
284         times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
285
286         nonstops = []
287         for nonstop in Nonstop.objects.all():
288             if nonstop.start == nonstop.end:
289                 continue
290             if nonstop.start < nonstop.end:
291                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
292                                  nonstop.end.hour + nonstop.end.minute/60.,
293                                  nonstop.title, nonstop.slug])
294             else:
295                 # crossing midnight
296                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
297                                  24,
298                                  nonstop.title, nonstop.slug])
299                 nonstops.append([0,
300                                  nonstop.end.hour + nonstop.end.minute/60.,
301                                  nonstop.title, nonstop.slug])
302         nonstops.sort()
303
304         for i in range(nb_lines):
305             grid.append([])
306             for j in range(7):
307                 grid[-1].append(TimeCell(i, j))
308
309             nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
310             for time_cell in grid[-1]:
311                 time_cell.nonstop = nonstop[2]
312                 time_cell.nonstop_slug = nonstop[3]
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()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
539         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
540         return context
541
542 news = News.as_view()
543
544
545 class Agenda(TemplateView):
546     template_name = 'agenda.html'
547     def get_context_data(self, **kwargs):
548         context = super(Agenda, self).get_context_data(**kwargs)
549         context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
550                 event_date__gte=date.today()).order_by('date')[:20]
551         context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
552         context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
553         return context
554
555 agenda = Agenda.as_view()
556
557
558 class AgendaByMonth(MonthArchiveView):
559     template_name = 'agenda.html'
560     queryset = NewsItem.objects.filter(event_date__isnull=False)
561     allow_future = True
562     date_field = 'event_date'
563     month_format = '%m'
564
565     def get_context_data(self, **kwargs):
566         context = super(AgendaByMonth, self).get_context_data(**kwargs)
567         context['agenda'] = context['object_list']
568         context['news'] = NewsItem.objects.all().order_by('-date')
569         return context
570
571 agenda_by_month = AgendaByMonth.as_view()
572
573
574 class Emissions(TemplateView):
575     template_name = 'emissions.html'
576
577     def get_context_data(self, **kwargs):
578         context = super(Emissions, self).get_context_data(**kwargs)
579         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
580         context['categories'] = Category.objects.all()
581         return context
582
583 emissions = Emissions.as_view()
584
585 class EmissionsArchives(TemplateView):
586     template_name = 'emissions/archives.html'
587
588     def get_context_data(self, **kwargs):
589         context = super(EmissionsArchives, self).get_context_data(**kwargs)
590         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
591         context['categories'] = Category.objects.all()
592         return context
593 emissionsArchives = EmissionsArchives.as_view()
594
595
596 class Listen(TemplateView):
597     template_name = 'listen.html'
598
599     def get_context_data(self, **kwargs):
600         context = super(Listen, self).get_context_data(**kwargs)
601         context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
602                 podcastable=True, got_focus__isnull=False) \
603                 .select_related().extra(select={
604                     'first_diffusion': 'emissions_diffusion.datetime', },
605                     select_params=(False, True),
606                     where=['''datetime = (SELECT MIN(datetime)
607                                             FROM emissions_diffusion
608                                         WHERE episode_id = emissions_episode.id)'''],
609                     tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
610         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
611                 podcastable=True) \
612                 .select_related().extra(select={
613                     'first_diffusion': 'emissions_diffusion.datetime', },
614                     select_params=(False, True),
615                     where=['''datetime = (SELECT MIN(datetime)
616                                             FROM emissions_diffusion
617                                         WHERE episode_id = emissions_episode.id)'''],
618                     tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
619
620
621         return context
622
623 listen = Listen.as_view()
624
625 @cache_control(max_age=15)
626 @csrf_exempt
627 @to_json('api')
628 def onair(request):
629     d = whatsonair()
630     if d.get('episode'):
631         d['episode'] = {
632             'title': d['episode'].title,
633             'url': d['episode'].get_absolute_url()
634         }
635     if d.get('emission'):
636         chat_url = None
637         if d['emission'].chat_open:
638             chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
639         d['emission'] = {
640             'title': d['emission'].title,
641             'url': d['emission'].get_absolute_url(),
642             'chat': chat_url,
643         }
644     if d.get('nonstop'):
645         d['nonstop'] = {
646             'title': d['nonstop'].title,
647         }
648         d.update(get_current_nonstop_track())
649     if d.get('current_slot'):
650         del d['current_slot']
651     return d
652
653
654 class NewsItemDetailView(DetailView):
655     model = NewsItem
656
657 newsitem = NewsItemDetailView.as_view()
658
659 class RssCustomPodcastsFeed(Rss201rev2Feed):
660     def root_attributes(self):
661         attrs = super(RssCustomPodcastsFeed, self).root_attributes()
662         attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
663         return attrs
664
665     def add_item_elements(self, handler, item):
666         super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
667         for tag in item.get('tags') or []:
668             handler.addQuickElement('dc:subject', tag)
669
670 class PodcastsFeed(Feed):
671     title = 'Radio Panik - Podcasts'
672     link = '/'
673     description_template = 'feed/soundfile.html'
674     feed_type = RssCustomPodcastsFeed
675
676     def items(self):
677         return SoundFile.objects.select_related().filter(
678                 podcastable=True).order_by('-creation_timestamp')[:20]
679
680     def item_title(self, item):
681         if item.fragment:
682             return '%s - %s' % (item.title, item.episode.title)
683         return item.episode.title
684
685     def item_link(self, item):
686         return item.episode.get_absolute_url()
687
688     def item_enclosure_url(self, item):
689         current_site = Site.objects.get(id=settings.SITE_ID)
690         return add_domain(current_site.domain, item.get_format_url('mp3'))
691
692     def item_enclosure_length(self, item):
693         sound_path = item.get_format_path('mp3')
694         try:
695             return os.stat(sound_path)[stat.ST_SIZE]
696         except OSError:
697             return 0
698
699     def item_enclosure_mime_type(self, item):
700         return 'audio/mpeg'
701
702     def item_pubdate(self, item):
703         return item.creation_timestamp
704
705     def item_extra_kwargs(self, item):
706         return {'tags': [x.name for x in item.episode.tags.all()]}
707
708 podcasts_feed = PodcastsFeed()
709
710
711 class RssNewsFeed(Feed):
712     title = 'Radio Panik'
713     link = '/news/'
714     description_template = 'feed/newsitem.html'
715
716     def items(self):
717         return NewsItem.objects.order_by('-date')[:20]
718
719 rss_news_feed = RssNewsFeed()
720
721 class Atom1FeedWithBaseXml(Atom1Feed):
722     def root_attributes(self):
723         root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
724         scheme, netloc, path, params, query, fragment  = urlparse.urlparse(self.feed['feed_url'])
725         root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
726         return root_attributes
727
728 class AtomNewsFeed(RssNewsFeed):
729     feed_type = Atom1FeedWithBaseXml
730
731 atom_news_feed = AtomNewsFeed()
732
733
734
735 class Party(TemplateView):
736     template_name = 'party.html'
737
738     def get_context_data(self, **kwargs):
739         context = super(Party, self).get_context_data(**kwargs)
740         t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
741         focus = Focus()
742         if t == 'newsitem':
743             focus.newsitem = NewsItem.objects.exclude(
744                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
745         elif t == 'emission':
746             focus.emission = Emission.objects.exclude(
747                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
748         elif t == 'episode':
749             focus.episode = Episode.objects.exclude(
750                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
751         elif t == 'soundfile':
752             focus.soundfile = SoundFile.objects.exclude(
753                     episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
754
755         context['focus'] = focus
756
757         return context
758
759 party = Party.as_view()
760
761
762
763 class Chat(DetailView, EmissionMixin):
764     model = Emission
765     template_name = 'chat.html'
766
767 chat = cache_control(max_age=15)(Chat.as_view())