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
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
26 from jsonresponse import to_json
28 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
29 Schedule, Nonstop, NewsItem, NewsCategory, Focus
31 from emissions.utils import whatsonair, period_program
33 from newsletter.forms import SubscribeForm
34 from nonstop.utils import get_current_nonstop_track
35 from nonstop.models import SomaLogLine
37 from panikombo.models import ItemTopik
43 def get_emission_context(self, emission, episode_ids=None):
46 # get all episodes, with an additional attribute to get the date of
47 # their first diffusion
48 episodes_queryset = Episode.objects.select_related()
49 if episode_ids is not None:
50 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
52 episodes_queryset = episodes_queryset.filter(emission=emission)
54 context['episodes'] = \
55 episodes_queryset.extra(select={
56 'first_diffusion': 'emissions_diffusion.datetime',
58 select_params=(False, True),
59 where=['''datetime = (SELECT MIN(datetime)
60 FROM emissions_diffusion
61 WHERE episode_id = emissions_episode.id
62 AND datetime <= CURRENT_TIMESTAMP)'''],
63 tables=['emissions_diffusion'],
64 ).order_by('-first_diffusion').distinct()
66 context['futurEpisodes'] = \
67 episodes_queryset.extra(select={
68 'first_diffusion': 'emissions_diffusion.datetime',
70 select_params=(False, True),
71 where=['''datetime = (SELECT MIN(datetime)
72 FROM emissions_diffusion
73 WHERE episode_id = emissions_episode.id
74 AND datetime > CURRENT_TIMESTAMP)'''],
75 tables=['emissions_diffusion'],
76 ).order_by('first_diffusion').distinct()
78 context['all_episodes'] = \
79 episodes_queryset.extra(select={
80 'first_diffusion': 'emissions_diffusion.datetime',
82 select_params=(False, True),
83 where=['''datetime = (SELECT MIN(datetime)
84 FROM emissions_diffusion
85 WHERE episode_id = emissions_episode.id
87 tables=['emissions_diffusion'],
88 ).order_by('first_diffusion')
90 # get all related soundfiles in a single query
92 if episode_ids is not None:
93 for episode_id in episode_ids:
94 soundfiles[episode_id] = None
96 for episode in Episode.objects.filter(emission=emission):
97 soundfiles[episode.id] = None
99 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
100 fragment=False, episode__emission=emission):
101 soundfiles[soundfile.episode_id] = soundfile
103 Episode.set_prefetched_soundfiles(soundfiles)
105 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
110 class EmissionDetailView(DetailView, EmissionMixin):
113 def get_context_data(self, **kwargs):
114 context = super(EmissionDetailView, self).get_context_data(**kwargs)
115 context['schedules'] = Schedule.objects.select_related().filter(
116 emission=self.object).order_by('rerun', 'datetime')
117 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
119 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
120 except Nonstop.DoesNotExist:
124 dates = [today - timedelta(days=x) for x in range(7)]
125 if datetime.now().time() < nonstop_object.start:
127 context['nonstop'] = nonstop_object
128 context['nonstop_dates'] = dates
129 context.update(self.get_emission_context(self.object))
131 emission = EmissionDetailView.as_view()
133 class EpisodeDetailView(DetailView, EmissionMixin):
136 def get_context_data(self, **kwargs):
137 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
138 context['diffusions'] = Diffusion.objects.select_related().filter(
139 episode=self.object.id).order_by('datetime')
141 context['emission'] = context['episode'].emission
142 except Emission.DoesNotExist:
144 if self.kwargs.get('emission_slug') != context['emission'].slug:
146 context.update(self.get_emission_context(context['emission']))
147 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
149 episode = EpisodeDetailView.as_view()
152 class NonstopPlaylistView(TemplateView):
153 template_name = 'nonstop_playlist.html'
155 def get_context_data(self, **kwargs):
156 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
158 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
159 except Emission.DoesNotExist:
161 context['date'] = date(int(kwargs.get('year')),
162 int(kwargs.get('month')), int(kwargs.get('day')))
163 context['future'] = (context['date'] >= date.today())
165 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
167 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
168 nonstop_object.start.hour, nonstop_object.start.minute)
170 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
171 nonstop_object.end.hour, nonstop_object.end.minute)
173 end = end + timedelta(days=1)
174 context['tracks'] = SomaLogLine.objects.filter(
175 play_timestamp__gte=start,
176 play_timestamp__lte=end,
177 on_air=True).select_related()
180 nonstop_playlist = NonstopPlaylistView.as_view()
182 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
184 template_name = 'emissions/episodes.html'
186 def get_context_data(self, **kwargs):
187 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
188 context['schedules'] = Schedule.objects.select_related().filter(
189 emission=self.object).order_by('rerun', 'datetime')
191 context['search_query'] = self.request.GET.get('q')
192 if context['search_query']:
194 sqs = SearchQuerySet().models(Episode).filter(
195 emission_slug_exact=self.object.slug, text=context['search_query'])
196 episode_ids = [x.pk for x in sqs]
200 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
202 emissionEpisodes = EmissionEpisodesDetailView.as_view()
205 class SoundFileEmbedView(DetailView):
207 template_name = 'soundfiles/embed.html'
209 def get_context_data(self, **kwargs):
210 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
211 if self.kwargs.get('episode_slug') != self.object.episode.slug:
213 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
215 context['episode'] = self.object.episode
217 soundfile_embed = SoundFileEmbedView.as_view()
220 class SoundFileDialogEmbedView(DetailView):
222 template_name = 'soundfiles/dialog-embed.html'
224 def get_context_data(self, **kwargs):
225 context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
226 if self.kwargs.get('episode_slug') != self.object.episode.slug:
228 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
230 context['episode'] = self.object.episode
232 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
236 class ProgramView(TemplateView):
237 template_name = 'program.html'
239 def get_context_data(self, year=None, week=None, **kwargs):
240 context = super(ProgramView, self).get_context_data(**kwargs)
242 context['weekday'] = datetime.today().weekday()
244 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
245 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
246 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
247 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
251 program = ProgramView.as_view()
259 def __init__(self, i, j):
264 def add_schedule(self, schedule):
265 end_time = schedule.datetime + timedelta(
266 minutes=schedule.get_duration())
267 self.time_label = '%02d:%02d-%02d:%02d' % (
268 schedule.datetime.hour,
269 schedule.datetime.minute,
272 self.schedules.append(schedule)
274 def __unicode__(self):
276 return ', '.join([x.emission.title for x in self.schedules])
280 def __eq__(self, other):
281 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
284 class Grid(TemplateView):
285 template_name = 'grid.html'
287 def get_context_data(self, **kwargs):
288 context = super(Grid, self).get_context_data(**kwargs)
290 nb_lines = 2 * 24 # the cells are half hours
293 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
294 # start grid after the night programs
295 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
298 for nonstop in Nonstop.objects.all():
299 if nonstop.start == nonstop.end:
301 if nonstop.start < nonstop.end:
302 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
303 nonstop.end.hour + nonstop.end.minute/60.,
304 nonstop.title, nonstop.slug])
307 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
309 nonstop.title, nonstop.slug])
311 nonstop.end.hour + nonstop.end.minute/60.,
312 nonstop.title, nonstop.slug])
315 for i in range(nb_lines):
318 grid[-1].append(TimeCell(i, j))
320 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
321 for time_cell in grid[-1]:
322 time_cell.nonstop = nonstop[2]
323 time_cell.nonstop_slug = nonstop[3]
325 # the one ending at 5am will be cut down, so we inscribe
326 # its duration manually
327 time_cell.time_label = '%02d:00-%02d:00' % (
328 nonstop[0], nonstop[1])
330 for schedule in Schedule.objects.prefetch_related(
331 'emission__categories').select_related().order_by('datetime'):
332 row_start = schedule.datetime.hour * 2 + \
333 int(math.ceil(schedule.datetime.minute / 30))
334 day_no = schedule.get_weekday()
336 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
337 if grid[(row_start+step)%nb_lines][day_no] is None:
338 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
339 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
341 # start grid after the night programs
342 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
344 # look for the case where the same emission has different schedules for
345 # the same time cell, for example if it lasts one hour the first week,
346 # and two hours the third week.
347 for i in range(nb_lines):
348 grid[i] = [x for x in grid[i] if x is not None]
349 for j, cell in enumerate(grid[i]):
350 if grid[i][j] is None:
352 if len(grid[i][j].schedules) > 1:
353 time_cell_emissions = {}
354 for schedule in grid[i][j].schedules:
355 if not schedule.emission.id in time_cell_emissions:
356 time_cell_emissions[schedule.emission.id] = []
357 time_cell_emissions[schedule.emission.id].append(schedule)
358 for schedule_list in time_cell_emissions.values():
359 if len(schedule_list) == 1:
361 # here it is, same cell, same emission, several
363 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
365 schedule = schedule_list[0]
366 end_time = schedule.datetime + timedelta(
367 minutes=schedule.get_duration())
368 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
369 schedule.datetime.hour,
370 schedule.datetime.minute,
374 for schedule in schedule_list[1:]:
375 grid[i][j].schedules.remove(schedule)
376 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
377 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
378 end_time.hour, end_time.minute, schedule.weeks_string)
382 # 1st thing is to merge cells on the same line, this will mostly catch
383 # consecutive nonstop cells
384 for i in range(nb_lines):
385 for j, cell in enumerate(grid[i]):
386 if grid[i][j] is None:
390 # if the cells are identical, they are removed from the
391 # grid, and current cell width is increased
392 while grid[i][j+t] == cell:
399 # once we're done we remove empty cells
400 grid[i] = [x for x in grid[i] if x is not None]
402 # 2nd thing is to merge cells vertically, this is emissions that last
403 # for more than 30 minutes
404 for i in range(nb_lines):
405 grid[i] = [x for x in grid[i] if x is not None]
406 for j, cell in enumerate(grid[i]):
407 if grid[i][j] is None:
412 # we look if the next time cell has the same emissions
413 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
414 if x == cell and x.y == cell.y and x.w == cell.w]
416 # if the cell was identical, we remove it and
417 # increase current cell height
418 bj, same_cell_below = same_cell_below[0]
419 del grid[i+cell.h][bj]
422 # if the cell is different, we have a closer look
423 # to it, so we can remove emissions that will
424 # already be mentioned in the current cell.
427 # - 7am30, seuls contre tout, 1h30
428 # - 8am, du pied gauche & la voix de la rue, 1h
429 # should produce: (this is case A)
431 # | seuls contre tout |
432 # |---------------------|
435 # | la voix de la rue |
437 # On the other hand, if all three emissions started
438 # at 7am30, we want: (this is case B)
440 # | seuls contre tout |
442 # | la voix de la rue |
443 # that is we merge all of them, ignoring the fact
444 # that the other emissions will stop at 8am30
445 current_cell_schedules = set(grid[i][j].schedules)
446 current_cell_emissions = set([x.emission for x in current_cell_schedules])
448 while True and current_cell_schedules:
449 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
450 if not same_cell_below:
453 same_cell_below = same_cell_below[0]
454 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
456 if current_cell_emissions.issubset(same_cell_below_emissions):
457 # this handles case A (see comment above)
458 for schedule in current_cell_schedules:
459 if schedule in same_cell_below.schedules:
460 same_cell_below.schedules.remove(schedule)
461 elif same_cell_below_emissions and \
462 current_cell_emissions.issuperset(same_cell_below_emissions):
463 # this handles case B (see comment above)
464 # we set the cell time label to the longest
466 grid[i][j].time_label = same_cell_below.time_label
467 # then we sort emissions so the longest are
469 grid[i][j].schedules.sort(
470 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
471 # then we add individual time labels to the
473 for schedule in current_cell_schedules:
474 if schedule not in same_cell_below.schedules:
475 end_time = schedule.datetime + timedelta(
476 minutes=schedule.get_duration())
477 schedule.time_label = '%02d:%02d-%02d:%02d' % (
478 schedule.datetime.hour,
479 schedule.datetime.minute,
483 grid[i+cursor].remove(same_cell_below)
484 elif same_cell_below_emissions and \
485 current_cell_emissions.intersection(same_cell_below_emissions):
486 same_cell_below.schedules = [x for x in
487 same_cell_below.schedules if
489 current_cell_emissions or
490 x.get_duration() < 30]
500 context['grid'] = grid
501 context['times'] = times
502 context['categories'] = Category.objects.all()
503 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
504 'Vendredi', 'Samedi', 'Dimanche']
508 grid = Grid.as_view()
511 class Home(TemplateView):
512 template_name = 'home.html'
514 def get_context_data(self, **kwargs):
515 context = super(Home, self).get_context_data(**kwargs)
516 context['emissions'] = Emission.objects.filter(archived=False).order_by('?') #-creation_timestamp')[:3]
517 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')[:3]
519 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
520 podcastable=True, fragment=False) \
521 .select_related().extra(select={
522 'first_diffusion': 'emissions_diffusion.datetime', },
523 select_params=(False, True),
524 where=['''datetime = (SELECT MIN(datetime)
525 FROM emissions_diffusion
526 WHERE episode_id = emissions_episode.id)'''],
527 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
529 context['newsletter_form'] = SubscribeForm()
533 home = Home.as_view()
535 class NewsItemView(DetailView):
537 def get_context_data(self, **kwargs):
538 context = super(NewsItemView, self).get_context_data(**kwargs)
539 context['categories'] = NewsCategory.objects.all()
540 context['news'] = NewsItem.objects.all().order_by('-date')
541 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
543 newsitemview = NewsItemView.as_view()
545 class News(TemplateView):
546 template_name = 'news.html'
547 def get_context_data(self, **kwargs):
548 context = super(News, self).get_context_data(**kwargs)
549 context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
550 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
553 news = News.as_view()
556 class Agenda(TemplateView):
557 template_name = 'agenda.html'
558 def get_context_data(self, **kwargs):
559 context = super(Agenda, self).get_context_data(**kwargs)
560 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
561 event_date__gte=date.today()).order_by('date')[:20]
562 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
563 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
566 agenda = Agenda.as_view()
569 class AgendaByMonth(MonthArchiveView):
570 template_name = 'agenda.html'
571 queryset = NewsItem.objects.filter(event_date__isnull=False)
573 date_field = 'event_date'
576 def get_context_data(self, **kwargs):
577 context = super(AgendaByMonth, self).get_context_data(**kwargs)
578 context['agenda'] = context['object_list']
579 context['news'] = NewsItem.objects.all().order_by('-date')
582 agenda_by_month = AgendaByMonth.as_view()
585 class Emissions(TemplateView):
586 template_name = 'emissions.html'
588 def get_context_data(self, **kwargs):
589 context = super(Emissions, self).get_context_data(**kwargs)
590 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
591 context['categories'] = Category.objects.all()
594 emissions = Emissions.as_view()
596 class EmissionsArchives(TemplateView):
597 template_name = 'emissions/archives.html'
599 def get_context_data(self, **kwargs):
600 context = super(EmissionsArchives, self).get_context_data(**kwargs)
601 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
602 context['categories'] = Category.objects.all()
604 emissionsArchives = EmissionsArchives.as_view()
607 class Listen(TemplateView):
608 template_name = 'listen.html'
610 def get_context_data(self, **kwargs):
611 context = super(Listen, self).get_context_data(**kwargs)
612 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
613 podcastable=True, got_focus__isnull=False) \
614 .select_related().extra(select={
615 'first_diffusion': 'emissions_diffusion.datetime', },
616 select_params=(False, True),
617 where=['''datetime = (SELECT MIN(datetime)
618 FROM emissions_diffusion
619 WHERE episode_id = emissions_episode.id)'''],
620 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
621 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
623 .select_related().extra(select={
624 'first_diffusion': 'emissions_diffusion.datetime', },
625 select_params=(False, True),
626 where=['''datetime = (SELECT MIN(datetime)
627 FROM emissions_diffusion
628 WHERE episode_id = emissions_episode.id)'''],
629 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
634 listen = Listen.as_view()
636 @cache_control(max_age=15)
643 'title': d['episode'].title,
644 'url': d['episode'].get_absolute_url()
646 if d.get('emission'):
648 if d['emission'].chat_open:
649 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
651 'title': d['emission'].title,
652 'url': d['emission'].get_absolute_url(),
657 'title': d['nonstop'].title,
659 d.update(get_current_nonstop_track())
660 if d.get('current_slot'):
661 del d['current_slot']
665 class NewsItemDetailView(DetailView):
668 newsitem = NewsItemDetailView.as_view()
670 class RssCustomPodcastsFeed(Rss201rev2Feed):
671 def add_root_elements(self, handler):
672 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
673 emission = self.feed.get('emission')
674 if emission and emission.image and emission.image.url:
675 image_url = emission.image.url
677 image_url = '/static/img/logo-panik-500.png'
678 image_url = urlparse.urljoin(self.feed['link'], image_url)
679 handler.startElement('image', {})
681 handler.addQuickElement('title', emission.title)
683 handler.addQuickElement('title', 'Radio Esperanzah!')
684 handler.addQuickElement('url', image_url)
685 handler.endElement('image')
686 handler.addQuickElement('itunes:image', None, {'href': image_url})
687 if emission and emission.subtitle:
688 handler.addQuickElement('itunes:subtitle', emission.subtitle)
690 def root_attributes(self):
691 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
692 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
693 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
696 def add_item_elements(self, handler, item):
697 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
699 for tag in item.get('tags') or []:
700 handler.addQuickElement('dc:subject', tag)
701 if tag == 'explicit':
704 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
705 handler.addQuickElement('itunes:explicit', explicit)
706 episode = item.get('episode')
707 if episode and episode.image and episode.image.url:
708 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
709 handler.addQuickElement('itunes:image', None, {'href': image_url})
710 soundfile = item.get('soundfile')
711 if soundfile.duration:
712 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
713 soundfile.duration / 3600,
714 soundfile.duration % 3600 / 60,
715 soundfile.duration % 60))
718 class PodcastsFeed(Feed):
719 title = 'Radio Esperanzah! - Podcasts'
721 description_template = 'feed/soundfile.html'
722 feed_type = RssCustomPodcastsFeed
725 return SoundFile.objects.select_related().filter(
726 podcastable=True).order_by('-creation_timestamp')[:20]
728 def item_title(self, item):
730 return '%s - %s' % (item.title, item.episode.title)
731 return '%s - %s' % (item.episode.emission.title, item.episode.title)
733 def item_link(self, item):
734 return item.episode.get_absolute_url()
736 def item_enclosure_url(self, item):
737 current_site = Site.objects.get(id=settings.SITE_ID)
738 return add_domain(current_site.domain, item.get_format_url('mp3'))
740 def item_enclosure_length(self, item):
741 sound_path = item.get_format_path('mp3')
743 return os.stat(sound_path)[stat.ST_SIZE]
747 def item_enclosure_mime_type(self, item):
750 def item_pubdate(self, item):
751 return item.creation_timestamp
753 def item_extra_kwargs(self, item):
754 return {'tags': [x.name for x in item.episode.tags.all()],
756 'episode': item.episode}
758 podcasts_feed = PodcastsFeed()
761 class RssNewsFeed(Feed):
762 title = 'Radio Esperanzah!'
764 description_template = 'feed/newsitem.html'
767 return NewsItem.objects.order_by('-date')[:20]
769 rss_news_feed = RssNewsFeed()
771 class Atom1FeedWithBaseXml(Atom1Feed):
772 def root_attributes(self):
773 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
774 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
775 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
776 return root_attributes
778 class AtomNewsFeed(RssNewsFeed):
779 feed_type = Atom1FeedWithBaseXml
781 atom_news_feed = AtomNewsFeed()
784 class EmissionPodcastsFeed(PodcastsFeed):
785 description_template = 'feed/soundfile.html'
786 feed_type = RssCustomPodcastsFeed
788 def __call__(self, request, *args, **kwargs):
789 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
790 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
794 return '%s - Podcasts' % self.emission.title
798 return reverse('emission-view', kwargs={'slug': self.emission.slug})
800 def feed_extra_kwargs(self, obj):
801 return {'emission': self.emission}
804 return SoundFile.objects.select_related().filter(
806 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
808 emission_podcasts_feed = EmissionPodcastsFeed()
811 class Party(TemplateView):
812 template_name = 'party.html'
814 def get_context_data(self, **kwargs):
815 context = super(Party, self).get_context_data(**kwargs)
816 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
819 focus.newsitem = NewsItem.objects.exclude(
820 image__isnull=True).exclude(image__exact='').order_by('?')[0]
821 elif t == 'emission':
822 focus.emission = Emission.objects.exclude(
823 image__isnull=True).exclude(image__exact='').order_by('?')[0]
825 focus.episode = Episode.objects.exclude(
826 image__isnull=True).exclude(image__exact='').order_by('?')[0]
827 elif t == 'soundfile':
828 focus.soundfile = SoundFile.objects.exclude(
829 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
831 context['focus'] = focus
835 party = Party.as_view()
839 class Chat(DetailView, EmissionMixin):
841 template_name = 'chat.html'
843 chat = cache_control(max_age=15)(Chat.as_view())