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