3 from datetime import datetime, timedelta, date
11 from django.core.urlresolvers import reverse
12 from django.conf import settings
13 from django.http import Http404
14 from django.views.decorators.cache import cache_control
15 from django.views.generic.base import TemplateView
16 from django.views.generic.detail import DetailView
17 from django.views.decorators.csrf import csrf_exempt
18 from django.views.generic.dates import _date_from_string
19 from django.views.generic.dates import MonthArchiveView
21 from django.core.paginator import Paginator
23 from django.contrib.sites.models import Site
24 from django.contrib.syndication.views import Feed, add_domain
25 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
27 from haystack.query import SearchQuerySet
28 from jsonresponse import to_json
30 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
31 Schedule, Nonstop, NewsItem, NewsCategory, Focus
33 from emissions.utils import whatsonair, period_program
35 from newsletter.forms import SubscribeForm
36 from nonstop.utils import get_current_nonstop_track
37 from nonstop.models import SomaLogLine
39 from panikombo.models import ItemTopik
45 def get_emission_context(self, emission, episode_ids=None):
48 # get all episodes, with an additional attribute to get the date of
49 # their first diffusion
50 episodes_queryset = Episode.objects.select_related()
51 if episode_ids is not None:
52 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
54 episodes_queryset = episodes_queryset.filter(emission=emission)
56 context['episodes'] = \
57 episodes_queryset.extra(select={
58 'first_diffusion': 'emissions_diffusion.datetime',
60 select_params=(False, True),
61 where=['''datetime = (SELECT MIN(datetime)
62 FROM emissions_diffusion
63 WHERE episode_id = emissions_episode.id
64 AND datetime <= CURRENT_TIMESTAMP)'''],
65 tables=['emissions_diffusion'],
66 ).order_by('-first_diffusion').distinct()
68 context['futurEpisodes'] = \
69 episodes_queryset.extra(select={
70 'first_diffusion': 'emissions_diffusion.datetime',
72 select_params=(False, True),
73 where=['''datetime = (SELECT MIN(datetime)
74 FROM emissions_diffusion
75 WHERE episode_id = emissions_episode.id
76 AND datetime > CURRENT_TIMESTAMP)'''],
77 tables=['emissions_diffusion'],
78 ).order_by('first_diffusion').distinct()
80 context['all_episodes'] = \
81 episodes_queryset.extra(select={
82 'first_diffusion': 'emissions_diffusion.datetime',
84 select_params=(False, True),
85 where=['''datetime = (SELECT MIN(datetime)
86 FROM emissions_diffusion
87 WHERE episode_id = emissions_episode.id
89 tables=['emissions_diffusion'],
90 ).order_by('first_diffusion')
92 # get all related soundfiles in a single query
94 if episode_ids is not None:
95 for episode_id in episode_ids:
96 soundfiles[episode_id] = None
98 for episode in Episode.objects.filter(emission=emission):
99 soundfiles[episode.id] = None
101 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
102 fragment=False, episode__emission=emission):
103 soundfiles[soundfile.episode_id] = soundfile
105 Episode.set_prefetched_soundfiles(soundfiles)
107 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
112 class EmissionDetailView(DetailView, EmissionMixin):
115 def get_context_data(self, **kwargs):
116 context = super(EmissionDetailView, self).get_context_data(**kwargs)
117 context['schedules'] = Schedule.objects.select_related().filter(
118 emission=self.object).order_by('rerun', 'datetime')
119 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
121 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
122 except Nonstop.DoesNotExist:
126 dates = [today - timedelta(days=x) for x in range(7)]
127 if datetime.now().time() < nonstop_object.start:
129 context['nonstop'] = nonstop_object
130 context['nonstop_dates'] = dates
131 context.update(self.get_emission_context(self.object))
133 emission = EmissionDetailView.as_view()
135 class EpisodeDetailView(DetailView, EmissionMixin):
138 def get_context_data(self, **kwargs):
139 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
140 context['diffusions'] = Diffusion.objects.select_related().filter(
141 episode=self.object.id).order_by('datetime')
143 context['emission'] = context['episode'].emission
144 except Emission.DoesNotExist:
146 if self.kwargs.get('emission_slug') != context['emission'].slug:
148 context.update(self.get_emission_context(context['emission']))
149 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
151 episode = EpisodeDetailView.as_view()
154 class NonstopPlaylistView(TemplateView):
155 template_name = 'nonstop_playlist.html'
157 def get_context_data(self, **kwargs):
158 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
160 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
161 except Emission.DoesNotExist:
163 context['date'] = date(int(kwargs.get('year')),
164 int(kwargs.get('month')), int(kwargs.get('day')))
165 context['future'] = (context['date'] >= date.today())
167 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
169 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
170 nonstop_object.start.hour, nonstop_object.start.minute)
172 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
173 nonstop_object.end.hour, nonstop_object.end.minute)
175 end = end + timedelta(days=1)
176 context['tracks'] = SomaLogLine.objects.filter(
177 play_timestamp__gte=start,
178 play_timestamp__lte=end,
179 on_air=True).select_related()
182 nonstop_playlist = NonstopPlaylistView.as_view()
184 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
186 template_name = 'emissions/episodes.html'
188 def get_context_data(self, **kwargs):
189 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
190 context['schedules'] = Schedule.objects.select_related().filter(
191 emission=self.object).order_by('rerun', 'datetime')
193 context['search_query'] = self.request.GET.get('q')
194 if context['search_query']:
196 sqs = SearchQuerySet().models(Episode).filter(
197 emission_slug_exact=self.object.slug, text=context['search_query'])
198 episode_ids = [x.pk for x in sqs]
202 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
204 emissionEpisodes = EmissionEpisodesDetailView.as_view()
207 class SoundFileEmbedView(DetailView):
209 template_name = 'soundfiles/embed.html'
211 def get_context_data(self, **kwargs):
212 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
213 if self.kwargs.get('episode_slug') != self.object.episode.slug:
215 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
217 context['episode'] = self.object.episode
219 soundfile_embed = SoundFileEmbedView.as_view()
222 class SoundFileDialogEmbedView(DetailView):
224 template_name = 'soundfiles/dialog-embed.html'
226 def get_context_data(self, **kwargs):
227 context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
228 if self.kwargs.get('episode_slug') != self.object.episode.slug:
230 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
232 context['episode'] = self.object.episode
234 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
238 class ProgramView(TemplateView):
239 template_name = 'program.html'
241 def get_context_data(self, year=None, week=None, **kwargs):
242 context = super(ProgramView, self).get_context_data(**kwargs)
244 context['weekday'] = datetime.today().weekday()
246 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
247 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
248 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
249 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
253 program = ProgramView.as_view()
261 def __init__(self, i, j):
266 def add_schedule(self, schedule):
267 end_time = schedule.datetime + timedelta(
268 minutes=schedule.get_duration())
269 self.time_label = '%02d:%02d-%02d:%02d' % (
270 schedule.datetime.hour,
271 schedule.datetime.minute,
274 self.schedules.append(schedule)
276 def __unicode__(self):
278 return ', '.join([x.emission.title for x in self.schedules])
282 def __eq__(self, other):
283 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
286 class Grid(TemplateView):
287 template_name = 'grid.html'
289 def get_context_data(self, **kwargs):
290 context = super(Grid, self).get_context_data(**kwargs)
292 nb_lines = 2 * 24 # the cells are half hours
295 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
296 # start grid after the night programs
297 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
300 for nonstop in Nonstop.objects.all():
301 if nonstop.start == nonstop.end:
303 if nonstop.start < nonstop.end:
304 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
305 nonstop.end.hour + nonstop.end.minute/60.,
306 nonstop.title, nonstop.slug])
309 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
311 nonstop.title, nonstop.slug])
313 nonstop.end.hour + nonstop.end.minute/60.,
314 nonstop.title, nonstop.slug])
317 for i in range(nb_lines):
320 grid[-1].append(TimeCell(i, j))
322 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
323 for time_cell in grid[-1]:
324 time_cell.nonstop = nonstop[2]
325 time_cell.nonstop_slug = nonstop[3]
327 # the one ending at 5am will be cut down, so we inscribe
328 # its duration manually
329 time_cell.time_label = '%02d:00-%02d:00' % (
330 nonstop[0], nonstop[1])
332 for schedule in Schedule.objects.prefetch_related(
333 'emission__categories').select_related().order_by('datetime'):
334 row_start = schedule.datetime.hour * 2 + \
335 int(math.ceil(schedule.datetime.minute / 30))
336 day_no = schedule.get_weekday()
338 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
339 if grid[(row_start+step)%nb_lines][day_no] is None:
340 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
341 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
343 # start grid after the night programs
344 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
346 # look for the case where the same emission has different schedules for
347 # the same time cell, for example if it lasts one hour the first week,
348 # and two hours the third week.
349 for i in range(nb_lines):
350 grid[i] = [x for x in grid[i] if x is not None]
351 for j, cell in enumerate(grid[i]):
352 if grid[i][j] is None:
354 if len(grid[i][j].schedules) > 1:
355 time_cell_emissions = {}
356 for schedule in grid[i][j].schedules:
357 if not schedule.emission.id in time_cell_emissions:
358 time_cell_emissions[schedule.emission.id] = []
359 time_cell_emissions[schedule.emission.id].append(schedule)
360 for schedule_list in time_cell_emissions.values():
361 if len(schedule_list) == 1:
363 # here it is, same cell, same emission, several
365 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
367 schedule = schedule_list[0]
368 end_time = schedule.datetime + timedelta(
369 minutes=schedule.get_duration())
370 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
371 schedule.datetime.hour,
372 schedule.datetime.minute,
376 for schedule in schedule_list[1:]:
377 grid[i][j].schedules.remove(schedule)
378 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
379 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
380 end_time.hour, end_time.minute, schedule.weeks_string)
384 # 1st thing is to merge cells on the same line, this will mostly catch
385 # consecutive nonstop cells
386 for i in range(nb_lines):
387 for j, cell in enumerate(grid[i]):
388 if grid[i][j] is None:
392 # if the cells are identical, they are removed from the
393 # grid, and current cell width is increased
394 while grid[i][j+t] == cell:
401 # once we're done we remove empty cells
402 grid[i] = [x for x in grid[i] if x is not None]
404 # 2nd thing is to merge cells vertically, this is emissions that last
405 # for more than 30 minutes
406 for i in range(nb_lines):
407 grid[i] = [x for x in grid[i] if x is not None]
408 for j, cell in enumerate(grid[i]):
409 if grid[i][j] is None:
414 # we look if the next time cell has the same emissions
415 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
416 if x == cell and x.y == cell.y and x.w == cell.w]
418 # if the cell was identical, we remove it and
419 # increase current cell height
420 bj, same_cell_below = same_cell_below[0]
421 del grid[i+cell.h][bj]
424 # if the cell is different, we have a closer look
425 # to it, so we can remove emissions that will
426 # already be mentioned in the current cell.
429 # - 7am30, seuls contre tout, 1h30
430 # - 8am, du pied gauche & la voix de la rue, 1h
431 # should produce: (this is case A)
433 # | seuls contre tout |
434 # |---------------------|
437 # | la voix de la rue |
439 # On the other hand, if all three emissions started
440 # at 7am30, we want: (this is case B)
442 # | seuls contre tout |
444 # | la voix de la rue |
445 # that is we merge all of them, ignoring the fact
446 # that the other emissions will stop at 8am30
447 current_cell_schedules = set(grid[i][j].schedules)
448 current_cell_emissions = set([x.emission for x in current_cell_schedules])
450 while True and current_cell_schedules:
451 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
452 if not same_cell_below:
455 same_cell_below = same_cell_below[0]
456 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
458 if current_cell_emissions.issubset(same_cell_below_emissions):
459 # this handles case A (see comment above)
460 for schedule in current_cell_schedules:
461 if schedule in same_cell_below.schedules:
462 same_cell_below.schedules.remove(schedule)
463 elif same_cell_below_emissions and \
464 current_cell_emissions.issuperset(same_cell_below_emissions):
465 # this handles case B (see comment above)
466 # we set the cell time label to the longest
468 grid[i][j].time_label = same_cell_below.time_label
469 # then we sort emissions so the longest are
471 grid[i][j].schedules.sort(
472 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
473 # then we add individual time labels to the
475 for schedule in current_cell_schedules:
476 if schedule not in same_cell_below.schedules:
477 end_time = schedule.datetime + timedelta(
478 minutes=schedule.get_duration())
479 schedule.time_label = '%02d:%02d-%02d:%02d' % (
480 schedule.datetime.hour,
481 schedule.datetime.minute,
485 grid[i+cursor].remove(same_cell_below)
486 elif same_cell_below_emissions and \
487 current_cell_emissions.intersection(same_cell_below_emissions):
488 same_cell_below.schedules = [x for x in
489 same_cell_below.schedules if
491 current_cell_emissions or
492 x.get_duration() < 30]
502 context['grid'] = grid
503 context['times'] = times
504 context['categories'] = Category.objects.all()
505 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
506 'Vendredi', 'Samedi', 'Dimanche']
510 grid = Grid.as_view()
513 class Home(TemplateView):
514 template_name = 'home.html'
516 def get_context_data(self, **kwargs):
517 context = super(Home, self).get_context_data(**kwargs)
518 context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
519 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')[:3]
521 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
522 podcastable=True, fragment=False) \
523 .select_related().extra(select={
524 'first_diffusion': 'emissions_diffusion.datetime', },
525 select_params=(False, True),
526 where=['''datetime = (SELECT MIN(datetime)
527 FROM emissions_diffusion
528 WHERE episode_id = emissions_episode.id)'''],
529 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
531 context['newsletter_form'] = SubscribeForm()
535 home = Home.as_view()
537 class NewsItemView(DetailView):
539 def get_context_data(self, **kwargs):
540 context = super(NewsItemView, self).get_context_data(**kwargs)
541 context['categories'] = NewsCategory.objects.all()
542 context['news'] = NewsItem.objects.all().order_by('-date')
543 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
545 newsitemview = NewsItemView.as_view()
547 class News(TemplateView):
548 template_name = 'news.html'
549 def get_context_data(self, **kwargs):
550 context = super(News, self).get_context_data(**kwargs)
551 context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
552 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
555 news = News.as_view()
558 class Agenda(TemplateView):
559 template_name = 'agenda.html'
560 def get_context_data(self, **kwargs):
561 context = super(Agenda, self).get_context_data(**kwargs)
562 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
563 event_date__gte=date.today()).order_by('date')[:20]
564 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
565 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
568 agenda = Agenda.as_view()
571 class AgendaByMonth(MonthArchiveView):
572 template_name = 'agenda.html'
573 queryset = NewsItem.objects.filter(event_date__isnull=False)
575 date_field = 'event_date'
578 def get_context_data(self, **kwargs):
579 context = super(AgendaByMonth, self).get_context_data(**kwargs)
580 context['agenda'] = context['object_list']
581 context['news'] = NewsItem.objects.all().order_by('-date')
584 agenda_by_month = AgendaByMonth.as_view()
587 class Emissions(TemplateView):
588 template_name = 'emissions.html'
590 def get_context_data(self, **kwargs):
591 context = super(Emissions, self).get_context_data(**kwargs)
592 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
593 context['categories'] = Category.objects.all()
596 emissions = Emissions.as_view()
598 class EmissionsArchives(TemplateView):
599 template_name = 'emissions/archives.html'
601 def get_context_data(self, **kwargs):
602 context = super(EmissionsArchives, self).get_context_data(**kwargs)
603 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
604 context['categories'] = Category.objects.all()
606 emissionsArchives = EmissionsArchives.as_view()
609 class Listen(TemplateView):
610 template_name = 'listen.html'
612 def get_context_data(self, **kwargs):
613 context = super(Listen, self).get_context_data(**kwargs)
614 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
615 podcastable=True, got_focus__isnull=False) \
616 .select_related().extra(select={
617 'first_diffusion': 'emissions_diffusion.datetime', },
618 select_params=(False, True),
619 where=['''datetime = (SELECT MIN(datetime)
620 FROM emissions_diffusion
621 WHERE episode_id = emissions_episode.id)'''],
622 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
623 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
625 .select_related().extra(select={
626 'first_diffusion': 'emissions_diffusion.datetime', },
627 select_params=(False, True),
628 where=['''datetime = (SELECT MIN(datetime)
629 FROM emissions_diffusion
630 WHERE episode_id = emissions_episode.id)'''],
631 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
636 listen = Listen.as_view()
638 @cache_control(max_age=15)
642 if date.today() < date(2017, 8, 3):
643 return {'emission': {'title': 'À partir du 3 août 17h', 'url': '/'}}
647 'title': d['episode'].title,
648 'url': d['episode'].get_absolute_url()
650 if d.get('emission'):
652 if d['emission'].chat_open:
653 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
655 'title': d['emission'].title,
656 'url': d['emission'].get_absolute_url(),
661 'title': d['nonstop'].title,
663 d.update(get_current_nonstop_track())
664 if d.get('current_slot'):
665 del d['current_slot']
669 class NewsItemDetailView(DetailView):
672 newsitem = NewsItemDetailView.as_view()
674 class RssCustomPodcastsFeed(Rss201rev2Feed):
675 def add_root_elements(self, handler):
676 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
677 emission = self.feed.get('emission')
678 if emission and emission.image and emission.image.url:
679 image_url = emission.image.url
681 image_url = '/static/img/logo-panik-500.png'
682 image_url = urlparse.urljoin(self.feed['link'], image_url)
683 handler.startElement('image', {})
685 handler.addQuickElement('title', emission.title)
687 handler.addQuickElement('title', 'Radio Esperanzah!')
688 handler.addQuickElement('url', image_url)
689 handler.endElement('image')
690 handler.addQuickElement('itunes:image', None, {'href': image_url})
691 if emission and emission.subtitle:
692 handler.addQuickElement('itunes:subtitle', emission.subtitle)
694 def root_attributes(self):
695 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
696 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
697 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
700 def add_item_elements(self, handler, item):
701 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
703 for tag in item.get('tags') or []:
704 handler.addQuickElement('dc:subject', tag)
705 if tag == 'explicit':
708 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
709 handler.addQuickElement('itunes:explicit', explicit)
710 episode = item.get('episode')
711 if episode and episode.image and episode.image.url:
712 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
713 handler.addQuickElement('itunes:image', None, {'href': image_url})
714 soundfile = item.get('soundfile')
715 if soundfile.duration:
716 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
717 soundfile.duration / 3600,
718 soundfile.duration % 3600 / 60,
719 soundfile.duration % 60))
722 class PodcastsFeed(Feed):
723 title = 'Radio Esperanzah! - Podcasts'
725 description_template = 'feed/soundfile.html'
726 feed_type = RssCustomPodcastsFeed
729 return SoundFile.objects.select_related().filter(
730 podcastable=True).order_by('-creation_timestamp')[:20]
732 def item_title(self, item):
734 return '%s - %s' % (item.title, item.episode.title)
735 return '%s - %s' % (item.episode.emission.title, item.episode.title)
737 def item_link(self, item):
738 return item.episode.get_absolute_url()
740 def item_enclosure_url(self, item):
741 current_site = Site.objects.get(id=settings.SITE_ID)
742 return add_domain(current_site.domain, item.get_format_url('mp3'))
744 def item_enclosure_length(self, item):
745 sound_path = item.get_format_path('mp3')
747 return os.stat(sound_path)[stat.ST_SIZE]
751 def item_enclosure_mime_type(self, item):
754 def item_pubdate(self, item):
755 return item.creation_timestamp
757 def item_extra_kwargs(self, item):
758 return {'tags': [x.name for x in item.episode.tags.all()],
760 'episode': item.episode}
762 podcasts_feed = PodcastsFeed()
765 class RssNewsFeed(Feed):
766 title = 'Radio Esperanzah!'
768 description_template = 'feed/newsitem.html'
771 return NewsItem.objects.order_by('-date')[:20]
773 rss_news_feed = RssNewsFeed()
775 class Atom1FeedWithBaseXml(Atom1Feed):
776 def root_attributes(self):
777 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
778 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
779 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
780 return root_attributes
782 class AtomNewsFeed(RssNewsFeed):
783 feed_type = Atom1FeedWithBaseXml
785 atom_news_feed = AtomNewsFeed()
788 class EmissionPodcastsFeed(PodcastsFeed):
789 description_template = 'feed/soundfile.html'
790 feed_type = RssCustomPodcastsFeed
792 def __call__(self, request, *args, **kwargs):
793 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
794 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
798 return '%s - Podcasts' % self.emission.title
802 return reverse('emission-view', kwargs={'slug': self.emission.slug})
804 def feed_extra_kwargs(self, obj):
805 return {'emission': self.emission}
808 return SoundFile.objects.select_related().filter(
810 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
812 emission_podcasts_feed = EmissionPodcastsFeed()
815 class Party(TemplateView):
816 template_name = 'party.html'
818 def get_context_data(self, **kwargs):
819 context = super(Party, self).get_context_data(**kwargs)
820 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
823 focus.newsitem = NewsItem.objects.exclude(
824 image__isnull=True).exclude(image__exact='').order_by('?')[0]
825 elif t == 'emission':
826 focus.emission = Emission.objects.exclude(
827 image__isnull=True).exclude(image__exact='').order_by('?')[0]
829 focus.episode = Episode.objects.exclude(
830 image__isnull=True).exclude(image__exact='').order_by('?')[0]
831 elif t == 'soundfile':
832 focus.soundfile = SoundFile.objects.exclude(
833 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
835 context['focus'] = focus
839 party = Party.as_view()
843 class Chat(DetailView, EmissionMixin):
845 template_name = 'chat.html'
847 chat = cache_control(max_age=15)(Chat.as_view())