]> git.0d.be Git - panikweb.git/blob - panikweb/views.py
d22662e022d9c075511b36961659b517e60b8e2f
[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
11 from django.views.decorators.cache import cache_control
12 from django.views.generic.base import TemplateView
13 from django.views.generic.detail import DetailView
14 from django.views.decorators.csrf import csrf_exempt
15 from django.views.generic.dates import _date_from_string
16 from django.views.generic.dates import MonthArchiveView
17
18 from django.core.paginator import Paginator
19
20 from django.contrib.sites.models import Site
21 from django.contrib.syndication.views import Feed, add_domain
22 from django.utils.feedgenerator import Atom1Feed
23
24 from haystack.query import SearchQuerySet
25 from jsonresponse import to_json
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         context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
146         context['date'] = date(int(kwargs.get('year')),
147                 int(kwargs.get('month')), int(kwargs.get('day')))
148
149         nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
150         start = datetime(
151                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
152                 nonstop_object.start.hour, nonstop_object.start.minute)
153         end = datetime(
154                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
155                 nonstop_object.end.hour, nonstop_object.end.minute)
156         if end < start:
157             end = end + timedelta(days=1)
158         context['tracks'] = SomaLogLine.objects.filter(
159                 play_timestamp__gte=start,
160                 play_timestamp__lte=end,
161                 on_air=True).select_related()
162         return context
163
164 nonstop_playlist = NonstopPlaylistView.as_view()
165
166 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
167     model = Emission
168     template_name = 'emissions/episodes.html'
169
170     def get_context_data(self, **kwargs):
171         context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
172         context['schedules'] = Schedule.objects.select_related().filter(
173                 emission=self.object).order_by('rerun', 'datetime')
174
175         context['search_query'] = self.request.GET.get('q')
176         if context['search_query']:
177             # query string
178             sqs = SearchQuerySet().models(Episode).filter(
179                     emission_slug_exact=self.object.slug, text=context['search_query'])
180             episode_ids = [x.pk for x in sqs]
181         else:
182             episode_ids = None
183
184         context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
185         return context
186 emissionEpisodes = EmissionEpisodesDetailView.as_view()
187
188
189 class SoundFileEmbedView(DetailView):
190     model = SoundFile
191     template_name = 'soundfiles/embed.html'
192
193     def get_context_data(self, **kwargs):
194         context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
195         if self.kwargs.get('episode_slug') != self.object.episode.slug:
196             raise Http404()
197         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
198             raise Http404()
199         context['episode'] = self.object.episode
200         return context
201 soundfile_embed = SoundFileEmbedView.as_view()
202
203
204 class SoundFileDialogEmbedView(DetailView):
205     model = SoundFile
206     template_name = 'soundfiles/dialog-embed.html'
207
208     def get_context_data(self, **kwargs):
209         context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
210         if self.kwargs.get('episode_slug') != self.object.episode.slug:
211             raise Http404()
212         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
213             raise Http404()
214         context['episode'] = self.object.episode
215         context['site_url'] = self.request.build_absolute_uri('/').strip('/')
216         return context
217 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
218
219
220
221 class ProgramView(TemplateView):
222     template_name = 'program.html'
223
224     def get_context_data(self, year=None, week=None, **kwargs):
225         context = super(ProgramView, self).get_context_data(**kwargs)
226
227         context['weekday'] = datetime.today().weekday()
228
229         context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
230         context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
231         context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
232         context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
233
234         return context
235
236 program = ProgramView.as_view()
237
238 class TimeCell:
239     nonstop = None
240     w = 1
241     h = 1
242     time_label = None
243
244     def __init__(self, i, j):
245         self.x = i
246         self.y = j
247         self.schedules = []
248
249     def add_schedule(self, schedule):
250         end_time = schedule.datetime + timedelta(
251                 minutes=schedule.get_duration())
252         self.time_label = '%02d:%02d-%02d:%02d' % (
253                 schedule.datetime.hour,
254                 schedule.datetime.minute,
255                 end_time.hour,
256                 end_time.minute)
257         self.schedules.append(schedule)
258
259     def __unicode__(self):
260         if self.schedules:
261             return ', '.join([x.emission.title for x in self.schedules])
262         else:
263             return self.nonstop
264
265     def __eq__(self, other):
266         return (unicode(self) == unicode(other) and self.time_label == other.time_label)
267
268
269 class Grid(TemplateView):
270     template_name = 'grid.html'
271
272     def get_context_data(self, **kwargs):
273         context = super(Grid, self).get_context_data(**kwargs)
274
275         nb_lines = 2 * 24 # the cells are half hours
276         grid = []
277
278         times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
279         # start grid after the night programs
280         times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
281
282         nonstops = []
283         for nonstop in Nonstop.objects.all():
284             if nonstop.start < nonstop.end:
285                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
286                                  nonstop.end.hour + nonstop.end.minute/60.,
287                                  nonstop.title, nonstop.slug])
288             else:
289                 # crossing midnight
290                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
291                                  24,
292                                  nonstop.title, nonstop.slug])
293                 nonstops.append([0,
294                                  nonstop.end.hour + nonstop.end.minute/60.,
295                                  nonstop.title, nonstop.slug])
296         nonstops.sort()
297
298         for i in range(nb_lines):
299             grid.append([])
300             for j in range(7):
301                 grid[-1].append(TimeCell(i, j))
302
303             nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
304             for time_cell in grid[-1]:
305                 time_cell.nonstop = nonstop[2]
306                 time_cell.nonstop_slug = nonstop[3]
307                 if nonstop[1] == 5:
308                     # the one ending at 5am will be cut down, so we inscribe
309                     # its duration manually
310                     time_cell.time_label = '%02d:00-%02d:00' % (
311                             nonstop[0], nonstop[1])
312
313         for schedule in Schedule.objects.prefetch_related(
314                 'emission__categories').select_related().order_by('datetime'):
315             row_start = schedule.datetime.hour * 2 + \
316                     int(math.ceil(schedule.datetime.minute / 30))
317             day_no = schedule.get_weekday()
318
319             for step in range(int(math.ceil(schedule.get_duration() / 30.))):
320                 if grid[(row_start+step)%nb_lines][day_no] is None:
321                     grid[(row_start+step)%nb_lines][day_no] = TimeCell()
322                 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
323
324         # start grid after the night programs
325         grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
326
327         # look for the case where the same emission has different schedules for
328         # the same time cell, for example if it lasts one hour the first week,
329         # and two hours the third week.
330         for i in range(nb_lines):
331             grid[i] = [x for x in grid[i] if x is not None]
332             for j, cell in enumerate(grid[i]):
333                 if grid[i][j] is None:
334                     continue
335                 if len(grid[i][j].schedules) > 1:
336                     time_cell_emissions = {}
337                     for schedule in grid[i][j].schedules:
338                         if not schedule.emission.id in time_cell_emissions:
339                             time_cell_emissions[schedule.emission.id] = []
340                         time_cell_emissions[schedule.emission.id].append(schedule)
341                     for schedule_list in time_cell_emissions.values():
342                         if len(schedule_list) == 1:
343                             continue
344                         # here it is, same cell, same emission, several
345                         # schedules
346                         schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
347
348                         schedule = schedule_list[0]
349                         end_time = schedule.datetime + timedelta(
350                                 minutes=schedule.get_duration())
351                         grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
352                                 schedule.datetime.hour,
353                                 schedule.datetime.minute,
354                                 end_time.hour,
355                                 end_time.minute)
356
357                         for schedule in schedule_list[1:]:
358                             grid[i][j].schedules.remove(schedule)
359                             end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
360                             schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
361                                     end_time.hour, end_time.minute, schedule.weeks_string)
362
363         # merge adjacent
364
365         # 1st thing is to merge cells on the same line, this will mostly catch
366         # consecutive nonstop cells
367         for i in range(nb_lines):
368             for j, cell in enumerate(grid[i]):
369                 if grid[i][j] is None:
370                     continue
371                 t = 1
372                 try:
373                     # if the cells are identical, they are removed from the
374                     # grid, and current cell width is increased
375                     while grid[i][j+t] == cell:
376                         cell.w += 1
377                         grid[i][j+t] = None
378                         t += 1
379                 except IndexError:
380                     pass
381
382             # once we're done we remove empty cells
383             grid[i] = [x for x in grid[i] if x is not None]
384
385         # 2nd thing is to merge cells vertically, this is emissions that last
386         # for more than 30 minutes
387         for i in range(nb_lines):
388             grid[i] = [x for x in grid[i] if x is not None]
389             for j, cell in enumerate(grid[i]):
390                 if grid[i][j] is None:
391                     continue
392                 t = 1
393                 try:
394                     while True:
395                         # we look if the next time cell has the same emissions
396                         same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
397                                            if x == cell and x.y == cell.y and x.w == cell.w]
398                         if same_cell_below:
399                             # if the cell was identical, we remove it and
400                             # increase current cell height
401                             bj, same_cell_below = same_cell_below[0]
402                             del grid[i+cell.h][bj]
403                             cell.h += 1
404                         else:
405                             # if the cell is different, we have a closer look
406                             # to it, so we can remove emissions that will
407                             # already be mentioned in the current cell.
408                             #
409                             # For example:
410                             #  - 7am30, seuls contre tout, 1h30
411                             #  - 8am, du pied gauche & la voix de la rue, 1h
412                             # should produce: (this is case A)
413                             #  |      7:30-9:00      |
414                             #  |  seuls contre tout  |
415                             #  |---------------------|
416                             #  |      8:00-9:00      |
417                             #  |   du pied gauche    |
418                             #  |  la voix de la rue  |
419                             #
420                             # On the other hand, if all three emissions started
421                             # at 7am30, we want: (this is case B)
422                             #  |      7:30-9:00      |
423                             #  |  seuls contre tout  |
424                             #  |   du pied gauche    |
425                             #  |  la voix de la rue  |
426                             # that is we merge all of them, ignoring the fact
427                             # that the other emissions will stop at 8am30
428                             current_cell_schedules = set(grid[i][j].schedules)
429                             current_cell_emissions = set([x.emission for x in current_cell_schedules])
430                             cursor = 1
431                             while True and current_cell_schedules:
432                                 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
433                                 if not same_cell_below:
434                                     cursor += 1
435                                     continue
436                                 same_cell_below = same_cell_below[0]
437                                 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
438
439                                 if current_cell_emissions.issubset(same_cell_below_emissions):
440                                     # this handles case A (see comment above)
441                                     for schedule in current_cell_schedules:
442                                         if schedule in same_cell_below.schedules:
443                                             same_cell_below.schedules.remove(schedule)
444                                 elif same_cell_below_emissions and \
445                                         current_cell_emissions.issuperset(same_cell_below_emissions):
446                                     # this handles case B (see comment above)
447                                     # we set the cell time label to the longest
448                                     # period
449                                     grid[i][j].time_label = same_cell_below.time_label
450                                     # then we sort emissions so the longest are
451                                     # put first
452                                     grid[i][j].schedules.sort(
453                                             lambda x, y: -cmp(x.get_duration(), y.get_duration()))
454                                     # then we add individual time labels to the
455                                     # other schedules
456                                     for schedule in current_cell_schedules:
457                                         if schedule not in same_cell_below.schedules:
458                                             end_time = schedule.datetime + timedelta(
459                                                     minutes=schedule.get_duration())
460                                             schedule.time_label = '%02d:%02d-%02d:%02d' % (
461                                                     schedule.datetime.hour,
462                                                     schedule.datetime.minute,
463                                                     end_time.hour,
464                                                     end_time.minute)
465                                     grid[i][j].h += 1
466                                     grid[i+cursor].remove(same_cell_below)
467                                 elif same_cell_below_emissions and \
468                                         current_cell_emissions.intersection(same_cell_below_emissions):
469                                     same_cell_below.schedules = [x for x in
470                                             same_cell_below.schedules if
471                                             x.emission not in
472                                             current_cell_emissions or
473                                             x.get_duration() < 30]
474                                 cursor += 1
475                             break
476                 except IndexError:
477                     pass
478
479         # cut night at 3am
480         grid = grid[:42]
481         times = times[:42]
482
483         context['grid'] = grid
484         context['times'] = times
485         context['categories'] = Category.objects.all()
486         context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
487                 'Vendredi', 'Samedi', 'Dimanche']
488
489         return context
490
491 grid = Grid.as_view()
492
493
494 class Home(TemplateView):
495     template_name = 'home.html'
496
497     def get_context_data(self, **kwargs):
498         context = super(Home, self).get_context_data(**kwargs)
499         context['emissions'] = Emission.objects.filter(archived=False).order_by('-creation_timestamp')[:3]
500         context['newsitems'] = NewsItem.objects.order_by('-date')[:3]
501
502         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
503                 podcastable=True, fragment=False) \
504                 .select_related().extra(select={
505                     'first_diffusion': 'emissions_diffusion.datetime', },
506                     select_params=(False, True),
507                     where=['''datetime = (SELECT MIN(datetime)
508                                             FROM emissions_diffusion
509                                         WHERE episode_id = emissions_episode.id)'''],
510                     tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
511
512         context['newsletter_form'] = SubscribeForm()
513
514         return context
515
516 home = Home.as_view()
517
518 class NewsItemView(DetailView):
519     model = NewsItem
520     def get_context_data(self, **kwargs):
521         context = super(NewsItemView, self).get_context_data(**kwargs)
522         context['categories'] = NewsCategory.objects.all()
523         context['news'] = NewsItem.objects.all().order_by('-date')
524         context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
525         return context
526 newsitemview = NewsItemView.as_view()
527
528 class News(TemplateView):
529     template_name = 'news.html'
530     def get_context_data(self, **kwargs):
531         context = super(News, self).get_context_data(**kwargs)
532         context['focus'] = NewsItem.objects.filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
533         context['news'] = NewsItem.objects.all().order_by('-date')
534         return context
535
536 news = News.as_view()
537
538
539 class Agenda(TemplateView):
540     template_name = 'agenda.html'
541     def get_context_data(self, **kwargs):
542         context = super(Agenda, self).get_context_data(**kwargs)
543         context['agenda'] = NewsItem.objects.filter(
544                 event_date__gte=date.today()).order_by('date')[:20]
545         context['news'] = NewsItem.objects.all().order_by('-date')
546         context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
547         return context
548
549 agenda = Agenda.as_view()
550
551
552 class AgendaByMonth(MonthArchiveView):
553     template_name = 'agenda.html'
554     queryset = NewsItem.objects.filter(event_date__isnull=False)
555     allow_future = True
556     date_field = 'event_date'
557     month_format = '%m'
558
559     def get_context_data(self, **kwargs):
560         context = super(AgendaByMonth, self).get_context_data(**kwargs)
561         context['agenda'] = context['object_list']
562         context['news'] = NewsItem.objects.all().order_by('-date')
563         return context
564
565 agenda_by_month = AgendaByMonth.as_view()
566
567
568 class Emissions(TemplateView):
569     template_name = 'emissions.html'
570
571     def get_context_data(self, **kwargs):
572         context = super(Emissions, self).get_context_data(**kwargs)
573         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
574         context['categories'] = Category.objects.all()
575         return context
576
577 emissions = Emissions.as_view()
578
579 class EmissionsArchives(TemplateView):
580     template_name = 'emissions/archives.html'
581
582     def get_context_data(self, **kwargs):
583         context = super(EmissionsArchives, self).get_context_data(**kwargs)
584         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
585         context['categories'] = Category.objects.all()
586         return context
587 emissionsArchives = EmissionsArchives.as_view()
588
589
590 class Listen(TemplateView):
591     template_name = 'listen.html'
592
593     def get_context_data(self, **kwargs):
594         context = super(Listen, self).get_context_data(**kwargs)
595         context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
596                 podcastable=True, got_focus__isnull=False) \
597                 .select_related().extra(select={
598                     'first_diffusion': 'emissions_diffusion.datetime', },
599                     select_params=(False, True),
600                     where=['''datetime = (SELECT MIN(datetime)
601                                             FROM emissions_diffusion
602                                         WHERE episode_id = emissions_episode.id)'''],
603                     tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
604         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
605                 podcastable=True) \
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('-creation_timestamp').distinct() [:10]
613
614
615         return context
616
617 listen = Listen.as_view()
618
619 @cache_control(max_age=15)
620 @csrf_exempt
621 @to_json('api')
622 def onair(request):
623     d = whatsonair()
624     if d.get('episode'):
625         d['episode'] = {
626             'title': d['episode'].title,
627             'url': d['episode'].get_absolute_url()
628         }
629     if d.get('emission'):
630         chat_url = None
631         if d['emission'].chat_open:
632             chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
633         d['emission'] = {
634             'title': d['emission'].title,
635             'url': d['emission'].get_absolute_url(),
636             'chat': chat_url,
637         }
638     if d.get('nonstop'):
639         d['nonstop'] = {
640             'title': d['nonstop'].title,
641         }
642         d.update(get_current_nonstop_track())
643     if d.get('current_slot'):
644         del d['current_slot']
645     return d
646
647
648 class NewsItemDetailView(DetailView):
649     model = NewsItem
650
651 newsitem = NewsItemDetailView.as_view()
652
653
654 class PodcastsFeed(Feed):
655     title = 'Radio Panik - Podcasts'
656     link = '/'
657     description_template = 'feed/soundfile.html'
658
659     def items(self):
660         return SoundFile.objects.select_related().filter(
661                 podcastable=True).order_by('-creation_timestamp')[:5]
662
663     def item_title(self, item):
664         if item.fragment:
665             return '%s - %s' % (item.title, item.episode.title)
666         return item.episode.title
667
668     def item_link(self, item):
669         return item.episode.get_absolute_url()
670
671     def item_enclosure_url(self, item):
672         current_site = Site.objects.get(id=settings.SITE_ID)
673         return add_domain(current_site.domain, item.get_format_url('mp3'))
674
675     def item_enclosure_length(self, item):
676         sound_path = item.get_format_path('mp3')
677         try:
678             return os.stat(sound_path)[stat.ST_SIZE]
679         except OSError:
680             return 0
681
682     def item_enclosure_mime_type(self, item):
683         return 'audio/mpeg'
684
685     def item_pubdate(self, item):
686         return item.creation_timestamp
687
688 podcasts_feed = PodcastsFeed()
689
690
691 class RssNewsFeed(Feed):
692     title = 'Radio Panik'
693     link = '/news/'
694     description_template = 'feed/newsitem.html'
695
696     def items(self):
697         return NewsItem.objects.order_by('-date')[:10]
698
699 rss_news_feed = RssNewsFeed()
700
701 class AtomNewsFeed(RssNewsFeed):
702     feed_type = Atom1Feed
703
704 atom_news_feed = AtomNewsFeed()
705
706
707
708 class Party(TemplateView):
709     template_name = 'party.html'
710
711     def get_context_data(self, **kwargs):
712         context = super(Party, self).get_context_data(**kwargs)
713         t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
714         focus = Focus()
715         if t == 'newsitem':
716             focus.newsitem = NewsItem.objects.exclude(
717                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
718         elif t == 'emission':
719             focus.emission = Emission.objects.exclude(
720                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
721         elif t == 'episode':
722             focus.episode = Episode.objects.exclude(
723                     image__isnull=True).exclude(image__exact='').order_by('?')[0]
724         elif t == 'soundfile':
725             focus.soundfile = SoundFile.objects.exclude(
726                     episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
727
728         context['focus'] = focus
729
730         return context
731
732 party = Party.as_view()
733
734
735
736 class Chat(DetailView, EmissionMixin):
737     model = Emission
738     template_name = 'chat.html'
739
740 chat = Chat.as_view()