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 combo.data.models import Page
40 from panikombo.models import ItemTopik
46 def get_emission_context(self, emission, episode_ids=None):
49 # get all episodes, with an additional attribute to get the date of
50 # their first diffusion
51 episodes_queryset = Episode.objects.select_related()
52 if episode_ids is not None:
53 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
55 episodes_queryset = episodes_queryset.filter(emission=emission)
57 context['episodes'] = \
58 episodes_queryset.extra(select={
59 'first_diffusion': 'emissions_diffusion.datetime',
61 select_params=(False, True),
62 where=['''datetime = (SELECT MIN(datetime)
63 FROM emissions_diffusion
64 WHERE episode_id = emissions_episode.id
65 AND datetime <= CURRENT_TIMESTAMP)'''],
66 tables=['emissions_diffusion'],
67 ).order_by('-first_diffusion').distinct()
69 context['futurEpisodes'] = \
70 episodes_queryset.extra(select={
71 'first_diffusion': 'emissions_diffusion.datetime',
73 select_params=(False, True),
74 where=['''datetime = (SELECT MIN(datetime)
75 FROM emissions_diffusion
76 WHERE episode_id = emissions_episode.id
77 AND datetime > CURRENT_TIMESTAMP)'''],
78 tables=['emissions_diffusion'],
79 ).order_by('first_diffusion').distinct()
82 current_year = emission.creation_timestamp.replace(month=5, day=1)
84 current_year = datetime.now().replace(month=5, day=1)
86 context['all_episodes'] = episodes_queryset.filter(
87 creation_timestamp__gt=current_year
89 'first_diffusion': 'emissions_diffusion.datetime',
91 select_params=(False, True),
92 where=['''datetime = (SELECT MIN(datetime)
93 FROM emissions_diffusion
94 WHERE episode_id = emissions_episode.id
96 tables=['emissions_diffusion'],
97 ).order_by('first_diffusion').distinct()
99 # get all related soundfiles in a single query
101 if episode_ids is not None:
102 for episode_id in episode_ids:
103 soundfiles[episode_id] = None
105 for episode in Episode.objects.filter(emission=emission):
106 soundfiles[episode.id] = None
108 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
109 fragment=False, episode__emission=emission):
110 soundfiles[soundfile.episode_id] = soundfile
112 Episode.set_prefetched_soundfiles(soundfiles)
114 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
119 class EmissionDetailView(DetailView, EmissionMixin):
122 def get_context_data(self, **kwargs):
123 context = super(EmissionDetailView, self).get_context_data(**kwargs)
124 context['schedules'] = Schedule.objects.select_related().filter(
125 emission=self.object).order_by('rerun', 'datetime')
126 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
128 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
129 except Nonstop.DoesNotExist:
133 dates = [today - timedelta(days=x) for x in range(7)]
134 if datetime.now().time() < nonstop_object.start:
136 context['nonstop'] = nonstop_object
137 context['nonstop_dates'] = dates
138 context.update(self.get_emission_context(self.object))
140 emission = EmissionDetailView.as_view()
142 class EpisodeDetailView(DetailView, EmissionMixin):
145 def get_queryset(self, *args, **kwargs):
146 queryset = super(EpisodeDetailView, self).get_queryset(*args, **kwargs)
147 return queryset.filter(emission__slug=self.kwargs['emission_slug'])
149 def get_context_data(self, **kwargs):
150 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
151 context['diffusions'] = Diffusion.objects.select_related().filter(
152 episode=self.object.id).order_by('datetime')
154 context['emission'] = context['episode'].emission
155 except Emission.DoesNotExist:
157 if self.kwargs.get('emission_slug') != context['emission'].slug:
159 context.update(self.get_emission_context(context['emission']))
160 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
162 episode = EpisodeDetailView.as_view()
165 class NonstopPlaylistView(TemplateView):
166 template_name = 'nonstop_playlist.html'
168 def get_context_data(self, **kwargs):
169 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
171 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
172 except Emission.DoesNotExist:
174 context['date'] = date(int(kwargs.get('year')),
175 int(kwargs.get('month')), int(kwargs.get('day')))
176 context['future'] = (context['date'] >= date.today())
178 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
180 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
181 nonstop_object.start.hour, nonstop_object.start.minute)
183 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
184 nonstop_object.end.hour, nonstop_object.end.minute)
186 end = end + timedelta(days=1)
187 context['tracks'] = SomaLogLine.objects.filter(
188 play_timestamp__gte=start,
189 play_timestamp__lte=end,
190 on_air=True).select_related()
193 nonstop_playlist = NonstopPlaylistView.as_view()
195 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
197 template_name = 'emissions/episodes.html'
199 def get_context_data(self, **kwargs):
200 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
201 context['schedules'] = Schedule.objects.select_related().filter(
202 emission=self.object).order_by('rerun', 'datetime')
204 context['search_query'] = self.request.GET.get('q')
205 if context['search_query']:
207 sqs = SearchQuerySet().models(Episode).filter(
208 emission_slug_exact=self.object.slug, text=context['search_query'])
209 episode_ids = [x.pk for x in sqs]
213 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
215 emissionEpisodes = EmissionEpisodesDetailView.as_view()
218 class SoundFileEmbedView(DetailView):
220 template_name = 'soundfiles/embed.html'
222 def get_context_data(self, **kwargs):
223 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
224 if self.kwargs.get('episode_slug') != self.object.episode.slug:
226 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
228 context['episode'] = self.object.episode
230 soundfile_embed = SoundFileEmbedView.as_view()
233 class SoundFileDialogEmbedView(DetailView):
235 template_name = 'soundfiles/dialog-embed.html'
237 def get_context_data(self, **kwargs):
238 context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
239 if self.kwargs.get('episode_slug') != self.object.episode.slug:
241 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
243 context['episode'] = self.object.episode
245 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
249 class ProgramView(TemplateView):
250 template_name = 'program.html'
252 def get_context_data(self, year=None, week=None, **kwargs):
253 context = super(ProgramView, self).get_context_data(**kwargs)
255 context['weekday'] = datetime.today().weekday()
257 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
258 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
259 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
260 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
264 program = ProgramView.as_view()
272 def __init__(self, i, j):
277 def add_schedule(self, schedule):
278 end_time = schedule.datetime + timedelta(
279 minutes=schedule.get_duration())
280 self.time_label = '%02d:%02d-%02d:%02d' % (
281 schedule.datetime.hour,
282 schedule.datetime.minute,
285 self.schedules.append(schedule)
287 def __unicode__(self):
289 return ', '.join([x.emission.title for x in self.schedules])
293 def __eq__(self, other):
294 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
297 class Grid(TemplateView):
298 template_name = 'grid.html'
300 def get_context_data(self, **kwargs):
301 context = super(Grid, self).get_context_data(**kwargs)
303 nb_lines = 2 * 24 # the cells are half hours
306 Schedule.DAY_HOUR_START = 12
308 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
309 # start grid after the night programs
310 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
313 for nonstop in Nonstop.objects.all():
314 if nonstop.start == nonstop.end:
316 if nonstop.start < nonstop.end:
317 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
318 nonstop.end.hour + nonstop.end.minute/60.,
319 nonstop.title, nonstop.slug])
322 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
324 nonstop.title, nonstop.slug])
326 nonstop.end.hour + nonstop.end.minute/60.,
327 nonstop.title, nonstop.slug])
330 for i in range(nb_lines):
333 grid[-1].append(TimeCell(i, j))
336 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
339 for time_cell in grid[-1]:
340 time_cell.nonstop = nonstop[2]
341 time_cell.nonstop_slug = nonstop[3]
343 # the one ending at 5am will be cut down, so we inscribe
344 # its duration manually
345 time_cell.time_label = '%02d:00-%02d:00' % (
346 nonstop[0], nonstop[1])
348 for schedule in Schedule.objects.filter(emission__archived=False).prefetch_related(
349 'emission__categories').select_related().order_by('datetime'):
350 row_start = schedule.datetime.hour * 2 + \
351 int(math.ceil(schedule.datetime.minute / 30))
352 day_no = schedule.get_weekday()
354 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
355 if grid[(row_start+step)%nb_lines][day_no] is None:
356 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
357 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
359 # start grid after the night programs
360 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
362 # look for the case where the same emission has different schedules for
363 # the same time cell, for example if it lasts one hour the first week,
364 # and two hours the third week.
365 for i in range(nb_lines):
366 grid[i] = [x for x in grid[i] if x is not None]
367 for j, cell in enumerate(grid[i]):
368 if grid[i][j] is None:
370 if len(grid[i][j].schedules) > 1:
371 time_cell_emissions = {}
372 for schedule in grid[i][j].schedules:
373 if not schedule.emission.id in time_cell_emissions:
374 time_cell_emissions[schedule.emission.id] = []
375 time_cell_emissions[schedule.emission.id].append(schedule)
376 for schedule_list in time_cell_emissions.values():
377 if len(schedule_list) == 1:
379 # here it is, same cell, same emission, several
381 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
383 schedule = schedule_list[0]
384 end_time = schedule.datetime + timedelta(
385 minutes=schedule.get_duration())
386 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
387 schedule.datetime.hour,
388 schedule.datetime.minute,
392 for schedule in schedule_list[1:]:
393 grid[i][j].schedules.remove(schedule)
394 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
395 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
396 end_time.hour, end_time.minute, schedule.weeks_string)
400 # 1st thing is to merge cells on the same line, this will mostly catch
401 # consecutive nonstop cells
402 for i in range(nb_lines):
403 for j, cell in enumerate(grid[i]):
404 if grid[i][j] is None:
408 # if the cells are identical, they are removed from the
409 # grid, and current cell width is increased
410 while grid[i][j+t] == cell:
417 # once we're done we remove empty cells
418 grid[i] = [x for x in grid[i] if x is not None]
420 # 2nd thing is to merge cells vertically, this is emissions that last
421 # for more than 30 minutes
422 for i in range(nb_lines):
423 grid[i] = [x for x in grid[i] if x is not None]
424 for j, cell in enumerate(grid[i]):
425 if grid[i][j] is None:
430 # we look if the next time cell has the same emissions
431 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
432 if x == cell and x.y == cell.y and x.w == cell.w]
434 # if the cell was identical, we remove it and
435 # increase current cell height
436 bj, same_cell_below = same_cell_below[0]
437 del grid[i+cell.h][bj]
440 # if the cell is different, we have a closer look
441 # to it, so we can remove emissions that will
442 # already be mentioned in the current cell.
445 # - 7am30, seuls contre tout, 1h30
446 # - 8am, du pied gauche & la voix de la rue, 1h
447 # should produce: (this is case A)
449 # | seuls contre tout |
450 # |---------------------|
453 # | la voix de la rue |
455 # On the other hand, if all three emissions started
456 # at 7am30, we want: (this is case B)
458 # | seuls contre tout |
460 # | la voix de la rue |
461 # that is we merge all of them, ignoring the fact
462 # that the other emissions will stop at 8am30
463 current_cell_schedules = set(grid[i][j].schedules)
464 current_cell_emissions = set([x.emission for x in current_cell_schedules])
466 while True and current_cell_schedules:
467 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
468 if not same_cell_below:
471 same_cell_below = same_cell_below[0]
472 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
474 if current_cell_emissions.issubset(same_cell_below_emissions):
475 # this handles case A (see comment above)
476 for schedule in current_cell_schedules:
477 if schedule in same_cell_below.schedules:
478 same_cell_below.schedules.remove(schedule)
479 elif same_cell_below_emissions and \
480 current_cell_emissions.issuperset(same_cell_below_emissions):
481 # this handles case B (see comment above)
482 # we set the cell time label to the longest
484 grid[i][j].time_label = same_cell_below.time_label
485 # then we sort emissions so the longest are
487 grid[i][j].schedules.sort(
488 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
489 # then we add individual time labels to the
491 for schedule in current_cell_schedules:
492 if schedule not in same_cell_below.schedules:
493 end_time = schedule.datetime + timedelta(
494 minutes=schedule.get_duration())
495 schedule.time_label = '%02d:%02d-%02d:%02d' % (
496 schedule.datetime.hour,
497 schedule.datetime.minute,
501 grid[i+cursor].remove(same_cell_below)
502 elif same_cell_below_emissions and \
503 current_cell_emissions.intersection(same_cell_below_emissions):
504 same_cell_below.schedules = [x for x in
505 same_cell_below.schedules if
507 current_cell_emissions or
508 x.get_duration() < 30]
518 context['grid'] = grid
519 context['times'] = times
520 context['categories'] = Category.objects.all()
521 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
522 'Vendredi', 'Samedi', 'Dimanche']
526 grid = Grid.as_view()
529 class Home(TemplateView):
530 template_name = 'home.html'
532 def get_context_data(self, **kwargs):
533 context = super(Home, self).get_context_data(**kwargs)
534 context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
535 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
536 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
538 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
539 podcastable=True, fragment=False) \
540 .select_related().extra(select={
541 'first_diffusion': 'emissions_diffusion.datetime', },
542 select_params=(False, True),
543 where=['''datetime = (SELECT MIN(datetime)
544 FROM emissions_diffusion
545 WHERE episode_id = emissions_episode.id)'''],
546 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
548 context['newsletter_form'] = SubscribeForm()
549 context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
553 home = Home.as_view()
555 class NewsItemView(DetailView):
557 def get_context_data(self, **kwargs):
558 context = super(NewsItemView, self).get_context_data(**kwargs)
559 context['categories'] = NewsCategory.objects.all()
560 context['news'] = NewsItem.objects.all().order_by('-date')
561 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
563 newsitemview = NewsItemView.as_view()
565 class News(TemplateView):
566 template_name = 'news.html'
567 def get_context_data(self, **kwargs):
568 context = super(News, self).get_context_data(**kwargs)
569 context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
570 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
573 news = News.as_view()
576 class Agenda(TemplateView):
577 template_name = 'agenda.html'
578 def get_context_data(self, **kwargs):
579 context = super(Agenda, self).get_context_data(**kwargs)
580 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
581 event_date__gte=date.today()).order_by('date')[:20]
582 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
583 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
586 agenda = Agenda.as_view()
589 class AgendaByMonth(MonthArchiveView):
590 template_name = 'agenda.html'
591 queryset = NewsItem.objects.filter(event_date__isnull=False)
593 date_field = 'event_date'
596 def get_context_data(self, **kwargs):
597 context = super(AgendaByMonth, self).get_context_data(**kwargs)
598 context['agenda'] = context['object_list']
599 context['news'] = NewsItem.objects.all().order_by('-date')
602 agenda_by_month = AgendaByMonth.as_view()
605 class Emissions(TemplateView):
606 template_name = 'emissions.html'
608 def get_context_data(self, **kwargs):
609 context = super(Emissions, self).get_context_data(**kwargs)
610 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
611 context['categories'] = Category.objects.all()
614 emissions = Emissions.as_view()
616 class EmissionsArchives(TemplateView):
617 template_name = 'emissions/archives.html'
619 def get_context_data(self, **kwargs):
620 context = super(EmissionsArchives, self).get_context_data(**kwargs)
621 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
622 context['categories'] = Category.objects.all()
624 emissionsArchives = EmissionsArchives.as_view()
627 class Listen(TemplateView):
628 template_name = 'listen.html'
630 def get_context_data(self, **kwargs):
631 context = super(Listen, self).get_context_data(**kwargs)
632 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
633 podcastable=True, got_focus__isnull=False) \
634 .select_related().extra(select={
635 'first_diffusion': 'emissions_diffusion.datetime', },
636 select_params=(False, True),
637 where=['''datetime = (SELECT MIN(datetime)
638 FROM emissions_diffusion
639 WHERE episode_id = emissions_episode.id)'''],
640 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
641 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
643 .select_related().extra(select={
644 'first_diffusion': 'emissions_diffusion.datetime', },
645 select_params=(False, True),
646 where=['''datetime = (SELECT MIN(datetime)
647 FROM emissions_diffusion
648 WHERE episode_id = emissions_episode.id)'''],
649 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
654 listen = Listen.as_view()
656 @cache_control(max_age=15)
660 if datetime.now() < datetime(2018, 7, 31, 18, 0):
661 return {'emission': {'title': 'À partir du 31 juillet 18h', 'url': '/'}}
662 if date.today() > date(2018, 8, 5):
663 return {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}
667 'title': d['episode'].title,
668 'url': d['episode'].get_absolute_url()
670 if d.get('emission'):
672 if d['emission'].chat_open:
673 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
675 'title': d['emission'].title,
676 'url': d['emission'].get_absolute_url(),
681 'title': d['nonstop'].title,
683 playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
684 if os.path.exists(os.path.join(playing_txt)):
685 d['track_title'] = open(playing_txt).read().strip()
686 if d.get('current_slot'):
687 del d['current_slot']
691 class NewsItemDetailView(DetailView):
694 newsitem = NewsItemDetailView.as_view()
696 class RssCustomPodcastsFeed(Rss201rev2Feed):
697 def add_root_elements(self, handler):
698 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
699 emission = self.feed.get('emission')
700 if emission and emission.image and emission.image.url:
701 image_url = emission.image.url
703 image_url = '/static/img/logo-panik-500.png'
704 image_url = urlparse.urljoin(self.feed['link'], image_url)
705 handler.startElement('image', {})
707 handler.addQuickElement('title', emission.title)
709 handler.addQuickElement('title', 'Radio Esperanzah!')
710 handler.addQuickElement('url', image_url)
711 handler.endElement('image')
712 handler.addQuickElement('itunes:image', None, {'href': image_url})
713 if emission and emission.subtitle:
714 handler.addQuickElement('itunes:subtitle', emission.subtitle)
716 def root_attributes(self):
717 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
718 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
719 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
722 def add_item_elements(self, handler, item):
723 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
725 for tag in item.get('tags') or []:
726 handler.addQuickElement('dc:subject', tag)
727 if tag == 'explicit':
730 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
731 handler.addQuickElement('itunes:explicit', explicit)
732 episode = item.get('episode')
733 if episode and episode.image and episode.image.url:
734 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
735 handler.addQuickElement('itunes:image', None, {'href': image_url})
736 soundfile = item.get('soundfile')
737 if soundfile.duration:
738 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
739 soundfile.duration / 3600,
740 soundfile.duration % 3600 / 60,
741 soundfile.duration % 60))
744 class PodcastsFeed(Feed):
745 title = 'Radio Esperanzah! - Podcasts'
747 description_template = 'feed/soundfile.html'
748 feed_type = RssCustomPodcastsFeed
751 return SoundFile.objects.select_related().filter(
752 podcastable=True).order_by('-creation_timestamp')[:20]
754 def item_title(self, item):
756 return '%s - %s' % (item.title, item.episode.title)
757 return '%s - %s' % (item.episode.emission.title, item.episode.title)
759 def item_link(self, item):
760 return item.episode.get_absolute_url()
762 def item_enclosure_url(self, item):
763 current_site = Site.objects.get(id=settings.SITE_ID)
764 return add_domain(current_site.domain, item.get_format_url('mp3'))
766 def item_enclosure_length(self, item):
767 sound_path = item.get_format_path('mp3')
769 return os.stat(sound_path)[stat.ST_SIZE]
773 def item_enclosure_mime_type(self, item):
776 def item_pubdate(self, item):
777 return item.creation_timestamp
779 def item_extra_kwargs(self, item):
780 return {'tags': [x.name for x in item.episode.tags.all()],
782 'episode': item.episode}
784 podcasts_feed = PodcastsFeed()
787 class RssNewsFeed(Feed):
788 title = 'Radio Esperanzah!'
790 description_template = 'feed/newsitem.html'
793 return NewsItem.objects.order_by('-date')[:20]
795 rss_news_feed = RssNewsFeed()
797 class Atom1FeedWithBaseXml(Atom1Feed):
798 def root_attributes(self):
799 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
800 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
801 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
802 return root_attributes
804 class AtomNewsFeed(RssNewsFeed):
805 feed_type = Atom1FeedWithBaseXml
807 atom_news_feed = AtomNewsFeed()
810 class EmissionPodcastsFeed(PodcastsFeed):
811 description_template = 'feed/soundfile.html'
812 feed_type = RssCustomPodcastsFeed
814 def __call__(self, request, *args, **kwargs):
815 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
816 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
820 return '%s - Podcasts' % self.emission.title
824 return reverse('emission-view', kwargs={'slug': self.emission.slug})
826 def feed_extra_kwargs(self, obj):
827 return {'emission': self.emission}
830 return SoundFile.objects.select_related().filter(
832 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
834 emission_podcasts_feed = EmissionPodcastsFeed()
837 class Party(TemplateView):
838 template_name = 'party.html'
840 def get_context_data(self, **kwargs):
841 context = super(Party, self).get_context_data(**kwargs)
842 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
845 focus.newsitem = NewsItem.objects.exclude(
846 image__isnull=True).exclude(image__exact='').order_by('?')[0]
847 elif t == 'emission':
848 focus.emission = Emission.objects.exclude(
849 image__isnull=True).exclude(image__exact='').order_by('?')[0]
851 focus.episode = Episode.objects.exclude(
852 image__isnull=True).exclude(image__exact='').order_by('?')[0]
853 elif t == 'soundfile':
854 focus.soundfile = SoundFile.objects.exclude(
855 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
857 context['focus'] = focus
861 party = Party.as_view()
865 class Chat(DetailView, EmissionMixin):
867 template_name = 'chat.html'
869 chat = cache_control(max_age=15)(Chat.as_view())
873 class ArchivesView(TemplateView):
874 template_name = 'archives.html'
876 def get_context_data(self, **kwargs):
877 context = super(ArchivesView, self).get_context_data(**kwargs)
878 context['diffusions'] = Diffusion.objects.filter(episode__soundfile__isnull=False).distinct().order_by('-datetime')
881 archives = ArchivesView.as_view()