1 from datetime import datetime, timedelta, date
9 from django.core.urlresolvers import reverse
10 from django.conf import settings
11 from django.http import Http404, JsonResponse
12 from django.views.decorators.cache import cache_control
13 from django.views.generic.base import TemplateView
14 from django.views.generic.detail import DetailView
15 from django.views.decorators.csrf import csrf_exempt
16 from django.views.generic.dates import _date_from_string
17 from django.views.generic.dates import MonthArchiveView
19 from django.core.paginator import Paginator
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
25 from haystack.query import SearchQuerySet
27 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
28 Schedule, Nonstop, NewsItem, NewsCategory, Focus
30 from emissions.utils import whatsonair, period_program
32 from newsletter.forms import SubscribeForm
33 from nonstop.utils import get_current_nonstop_track
34 from nonstop.models import SomaLogLine
36 from panikombo.models import ItemTopik
42 def get_emission_context(self, emission, episode_ids=None):
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)
51 episodes_queryset = episodes_queryset.filter(emission=emission)
53 context['episodes'] = \
54 episodes_queryset.extra(select={
55 'first_diffusion': 'emissions_diffusion.datetime',
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()
65 context['futurEpisodes'] = \
66 episodes_queryset.extra(select={
67 'first_diffusion': 'emissions_diffusion.datetime',
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()
78 # get all related soundfiles in a single query
80 if episode_ids is not None:
81 for episode_id in episode_ids:
82 soundfiles[episode_id] = None
84 for episode in Episode.objects.filter(emission=emission):
85 soundfiles[episode.id] = None
87 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
88 fragment=False, episode__emission=emission):
89 soundfiles[soundfile.episode_id] = soundfile
91 Episode.set_prefetched_soundfiles(soundfiles)
93 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
98 class EmissionDetailView(DetailView, EmissionMixin):
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]
107 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
108 except Nonstop.DoesNotExist:
112 dates = [today - timedelta(days=x) for x in range(7)]
113 if datetime.now().time() < nonstop_object.start:
115 context['nonstop'] = nonstop_object
116 context['nonstop_dates'] = dates
117 context.update(self.get_emission_context(self.object))
119 emission = EmissionDetailView.as_view()
121 class EpisodeDetailView(DetailView, EmissionMixin):
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')
129 context['emission'] = context['episode'].emission
130 except Emission.DoesNotExist:
132 if self.kwargs.get('emission_slug') != context['emission'].slug:
134 context.update(self.get_emission_context(context['emission']))
135 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
137 episode = EpisodeDetailView.as_view()
140 class NonstopPlaylistView(TemplateView):
141 template_name = 'nonstop_playlist.html'
143 def get_context_data(self, **kwargs):
144 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
146 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
147 except Emission.DoesNotExist:
149 context['date'] = date(int(kwargs.get('year')),
150 int(kwargs.get('month')), int(kwargs.get('day')))
151 context['future'] = (context['date'] >= date.today())
153 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
155 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
156 nonstop_object.start.hour, nonstop_object.start.minute)
158 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
159 nonstop_object.end.hour, nonstop_object.end.minute)
161 end = end + timedelta(days=1)
162 context['tracks'] = SomaLogLine.objects.filter(
163 play_timestamp__gte=start,
164 play_timestamp__lte=end,
165 on_air=True).select_related()
168 nonstop_playlist = NonstopPlaylistView.as_view()
170 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
172 template_name = 'emissions/episodes.html'
174 def get_context_data(self, **kwargs):
175 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
176 context['schedules'] = Schedule.objects.select_related().filter(
177 emission=self.object).order_by('rerun', 'datetime')
179 context['search_query'] = self.request.GET.get('q')
180 if context['search_query']:
182 sqs = SearchQuerySet().models(Episode).filter(
183 emission_slug_exact=self.object.slug, text=context['search_query'])
184 episode_ids = [x.pk for x in sqs]
188 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
190 emissionEpisodes = EmissionEpisodesDetailView.as_view()
193 class SoundFileEmbedView(DetailView):
195 template_name = 'soundfiles/embed.html'
197 def get_context_data(self, **kwargs):
198 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
199 if self.kwargs.get('episode_slug') != self.object.episode.slug:
201 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
203 context['episode'] = self.object.episode
205 soundfile_embed = SoundFileEmbedView.as_view()
208 class SoundFileDialogEmbedView(DetailView):
210 template_name = 'soundfiles/dialog-embed.html'
212 def get_context_data(self, **kwargs):
213 context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
214 if self.kwargs.get('episode_slug') != self.object.episode.slug:
216 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
218 context['episode'] = self.object.episode
220 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
224 class ProgramView(TemplateView):
225 template_name = 'program.html'
227 def get_context_data(self, year=None, week=None, **kwargs):
228 context = super(ProgramView, self).get_context_data(**kwargs)
230 context['weekday'] = datetime.today().weekday()
232 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
233 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
234 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
235 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
239 program = ProgramView.as_view()
247 def __init__(self, i, j):
252 def add_schedule(self, schedule):
253 end_time = schedule.datetime + timedelta(
254 minutes=schedule.get_duration())
255 self.time_label = '%02d:%02d-%02d:%02d' % (
256 schedule.datetime.hour,
257 schedule.datetime.minute,
260 self.schedules.append(schedule)
262 def __unicode__(self):
264 return ', '.join([x.emission.title for x in self.schedules])
268 def __eq__(self, other):
269 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
272 class Grid(TemplateView):
273 template_name = 'grid.html'
275 def get_context_data(self, **kwargs):
276 context = super(Grid, self).get_context_data(**kwargs)
278 nb_lines = 2 * 24 # the cells are half hours
281 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
282 # start grid after the night programs
283 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
286 for nonstop in Nonstop.objects.all():
287 if nonstop.start == nonstop.end:
289 if nonstop.start < nonstop.end:
290 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
291 nonstop.end.hour + nonstop.end.minute/60.,
292 nonstop.title, nonstop.slug, nonstop])
295 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
297 nonstop.title, nonstop.slug, nonstop])
299 nonstop.end.hour + nonstop.end.minute/60.,
300 nonstop.title, nonstop.slug, nonstop])
303 for i in range(nb_lines):
306 grid[-1].append(TimeCell(i, j))
308 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
309 for time_cell in grid[-1]:
310 time_cell.nonstop = nonstop[2]
311 time_cell.nonstop_slug = nonstop[3]
312 time_cell.redirect_path = nonstop[4].redirect_path
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])
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()
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)
330 # start grid after the night programs
331 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
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:
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:
350 # here it is, same cell, same emission, several
352 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
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,
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)
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:
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:
388 # once we're done we remove empty cells
389 grid[i] = [x for x in grid[i] if x is not None]
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:
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]
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]
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.
416 # - 7am30, seuls contre tout, 1h30
417 # - 8am, du pied gauche & la voix de la rue, 1h
418 # should produce: (this is case A)
420 # | seuls contre tout |
421 # |---------------------|
424 # | la voix de la rue |
426 # On the other hand, if all three emissions started
427 # at 7am30, we want: (this is case B)
429 # | seuls contre tout |
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])
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:
442 same_cell_below = same_cell_below[0]
443 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
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
455 grid[i][j].time_label = same_cell_below.time_label
456 # then we sort emissions so the longest are
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
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,
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
478 current_cell_emissions or
479 x.get_duration() < 30]
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']
497 grid = Grid.as_view()
500 class Home(TemplateView):
501 template_name = 'home.html'
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]
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]
518 context['newsletter_form'] = SubscribeForm()
522 home = Home.as_view()
524 class NewsItemView(DetailView):
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)]
532 newsitemview = NewsItemView.as_view()
534 class News(TemplateView):
535 template_name = 'news.html'
536 def get_context_data(self, **kwargs):
537 context = super(News, self).get_context_data(**kwargs)
538 context['focus'] = NewsItem.objects.exclude(date__gt=date.today() # publication date
539 ).exclude(expiration_date__lt=date.today() # expiration date
540 ).filter(got_focus__isnull=False
541 ).select_related('category').order_by('-date')[:10]
542 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
545 news = News.as_view()
548 class Agenda(TemplateView):
549 template_name = 'agenda.html'
550 def get_context_data(self, **kwargs):
551 context = super(Agenda, self).get_context_data(**kwargs)
552 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
553 event_date__gte=date.today()).order_by('date')[:20]
554 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
555 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
558 agenda = Agenda.as_view()
561 class AgendaByMonth(MonthArchiveView):
562 template_name = 'agenda.html'
563 queryset = NewsItem.objects.filter(event_date__isnull=False)
565 date_field = 'event_date'
568 def get_context_data(self, **kwargs):
569 context = super(AgendaByMonth, self).get_context_data(**kwargs)
570 context['agenda'] = context['object_list']
571 context['news'] = NewsItem.objects.all().order_by('-date')
574 agenda_by_month = AgendaByMonth.as_view()
577 class Emissions(TemplateView):
578 template_name = 'emissions.html'
580 def get_context_data(self, **kwargs):
581 context = super(Emissions, self).get_context_data(**kwargs)
582 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
583 context['categories'] = Category.objects.all()
586 emissions = Emissions.as_view()
588 class EmissionsArchives(TemplateView):
589 template_name = 'emissions/archives.html'
591 def get_context_data(self, **kwargs):
592 context = super(EmissionsArchives, self).get_context_data(**kwargs)
593 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
594 context['categories'] = Category.objects.all()
596 emissionsArchives = EmissionsArchives.as_view()
599 class Listen(TemplateView):
600 template_name = 'listen.html'
602 def get_context_data(self, **kwargs):
603 context = super(Listen, self).get_context_data(**kwargs)
604 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
605 podcastable=True, got_focus__isnull=False) \
606 .select_related().extra(select={
607 'first_diffusion': 'emissions_diffusion.datetime', },
608 select_params=(False, True),
609 where=['''datetime = (SELECT MIN(datetime)
610 FROM emissions_diffusion
611 WHERE episode_id = emissions_episode.id)'''],
612 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
613 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
615 .select_related().extra(select={
616 'first_diffusion': 'emissions_diffusion.datetime', },
617 select_params=(False, True),
618 where=['''datetime = (SELECT MIN(datetime)
619 FROM emissions_diffusion
620 WHERE episode_id = emissions_episode.id)'''],
621 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
626 listen = Listen.as_view()
628 @cache_control(max_age=15)
634 'title': d['episode'].title,
635 'url': d['episode'].get_absolute_url()
637 if d.get('emission'):
639 if d['emission'].chat_open:
640 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
642 'title': d['emission'].title,
643 'url': d['emission'].get_absolute_url(),
647 redirect_path = d['nonstop'].redirect_path
649 'title': d['nonstop'].title,
652 d['nonstop']['url'] = redirect_path
653 d.update(get_current_nonstop_track())
654 if d.get('current_slot'):
655 del d['current_slot']
656 return JsonResponse({'data': d})
659 class NewsItemDetailView(DetailView):
662 newsitem = NewsItemDetailView.as_view()
664 class RssCustomPodcastsFeed(Rss201rev2Feed):
665 def add_root_elements(self, handler):
666 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
667 emission = self.feed.get('emission')
668 if emission and emission.image and emission.image.url:
669 image_url = emission.image.url
671 image_url = '/static/img/logo-panik-500.png'
672 image_url = urlparse.urljoin(self.feed['link'], image_url)
673 handler.startElement('image', {})
675 handler.addQuickElement('title', emission.title)
677 handler.addQuickElement('title', 'Radio Panik')
678 handler.addQuickElement('url', image_url)
679 handler.endElement('image')
680 handler.addQuickElement('itunes:image', None, {'href': image_url})
681 if emission and emission.subtitle:
682 handler.addQuickElement('itunes:subtitle', emission.subtitle)
684 def root_attributes(self):
685 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
686 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
687 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
690 def add_item_elements(self, handler, item):
691 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
693 for tag in item.get('tags') or []:
694 handler.addQuickElement('dc:subject', tag)
695 if tag == 'explicit':
698 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
699 handler.addQuickElement('itunes:explicit', explicit)
700 episode = item.get('episode')
701 if episode and episode.image and episode.image.url:
702 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
703 handler.addQuickElement('itunes:image', None, {'href': image_url})
704 soundfile = item.get('soundfile')
705 if soundfile.duration:
706 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
707 soundfile.duration / 3600,
708 soundfile.duration % 3600 / 60,
709 soundfile.duration % 60))
712 class PodcastsFeed(Feed):
713 title = 'Radio Panik - Podcasts'
715 description_template = 'feed/soundfile.html'
716 feed_type = RssCustomPodcastsFeed
719 return SoundFile.objects.select_related().filter(
720 podcastable=True).order_by('-creation_timestamp')[:20]
722 def item_title(self, item):
724 return '%s - %s' % (item.title, item.episode.title)
725 return item.episode.title
727 def item_link(self, item):
728 return item.episode.get_absolute_url()
730 def item_enclosure_url(self, item):
731 current_site = Site.objects.get(id=settings.SITE_ID)
732 return add_domain(current_site.domain, item.get_format_url('mp3'))
734 def item_enclosure_length(self, item):
735 sound_path = item.get_format_path('mp3')
737 return os.stat(sound_path)[stat.ST_SIZE]
741 def item_enclosure_mime_type(self, item):
744 def item_pubdate(self, item):
745 return item.creation_timestamp
747 def item_extra_kwargs(self, item):
748 return {'tags': [x.name for x in item.episode.tags.all()],
750 'episode': item.episode}
752 podcasts_feed = PodcastsFeed()
755 class RssNewsFeed(Feed):
756 title = 'Radio Panik'
758 description_template = 'feed/newsitem.html'
761 return NewsItem.objects.order_by('-date')[:20]
763 rss_news_feed = RssNewsFeed()
765 class Atom1FeedWithBaseXml(Atom1Feed):
766 def root_attributes(self):
767 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
768 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
769 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
770 return root_attributes
772 class AtomNewsFeed(RssNewsFeed):
773 feed_type = Atom1FeedWithBaseXml
775 atom_news_feed = AtomNewsFeed()
778 class EmissionPodcastsFeed(PodcastsFeed):
779 description_template = 'feed/soundfile.html'
780 feed_type = RssCustomPodcastsFeed
782 def __call__(self, request, *args, **kwargs):
783 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
784 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
788 return self.emission.title
792 return reverse('emission-view', kwargs={'slug': self.emission.slug})
794 def feed_extra_kwargs(self, obj):
795 return {'emission': self.emission}
798 return SoundFile.objects.select_related().filter(
800 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
802 emission_podcasts_feed = EmissionPodcastsFeed()
805 class Party(TemplateView):
806 template_name = 'party.html'
808 def get_context_data(self, **kwargs):
809 context = super(Party, self).get_context_data(**kwargs)
810 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
813 focus.newsitem = NewsItem.objects.exclude(
814 image__isnull=True).exclude(image__exact='').order_by('?')[0]
815 elif t == 'emission':
816 focus.emission = Emission.objects.exclude(
817 image__isnull=True).exclude(image__exact='').order_by('?')[0]
819 focus.episode = Episode.objects.exclude(
820 image__isnull=True).exclude(image__exact='').order_by('?')[0]
821 elif t == 'soundfile':
822 focus.soundfile = SoundFile.objects.exclude(
823 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
825 context['focus'] = focus
829 party = Party.as_view()
833 class Chat(DetailView, EmissionMixin):
835 template_name = 'chat.html'
837 chat = cache_control(max_age=15)(Chat.as_view())