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, JsonResponse
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
29 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
30 Schedule, Nonstop, NewsItem, NewsCategory, Focus
32 from emissions.utils import whatsonair, period_program
34 from newsletter.forms import SubscribeForm
35 from nonstop.utils import get_current_nonstop_track
36 from nonstop.models import SomaLogLine
38 from combo.data.models import Page
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()
81 current_year = emission.creation_timestamp.replace(month=5, day=1)
83 current_year = datetime.now().replace(month=5, day=1)
85 context['all_episodes'] = episodes_queryset.filter(
86 creation_timestamp__gt=current_year
88 'first_diffusion': 'emissions_diffusion.datetime',
90 select_params=(False, True),
91 where=['''datetime = (SELECT MIN(datetime)
92 FROM emissions_diffusion
93 WHERE episode_id = emissions_episode.id
95 tables=['emissions_diffusion'],
96 ).order_by('first_diffusion').distinct()
98 # get all related soundfiles in a single query
100 if episode_ids is not None:
101 for episode_id in episode_ids:
102 soundfiles[episode_id] = None
104 for episode in Episode.objects.filter(emission=emission):
105 soundfiles[episode.id] = None
107 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
108 fragment=False, episode__emission=emission):
109 soundfiles[soundfile.episode_id] = soundfile
111 Episode.set_prefetched_soundfiles(soundfiles)
113 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
118 class EmissionDetailView(DetailView, EmissionMixin):
121 def get_context_data(self, **kwargs):
122 context = super(EmissionDetailView, self).get_context_data(**kwargs)
123 context['schedules'] = Schedule.objects.select_related().filter(
124 emission=self.object).order_by('rerun', 'datetime')
125 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
127 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
128 except Nonstop.DoesNotExist:
132 dates = [today - timedelta(days=x) for x in range(7)]
133 if datetime.now().time() < nonstop_object.start:
135 context['nonstop'] = nonstop_object
136 context['nonstop_dates'] = dates
137 context.update(self.get_emission_context(self.object))
139 emission = EmissionDetailView.as_view()
141 class EpisodeDetailView(DetailView, EmissionMixin):
144 def get_queryset(self, *args, **kwargs):
145 queryset = super(EpisodeDetailView, self).get_queryset(*args, **kwargs)
146 return queryset.filter(emission__slug=self.kwargs['emission_slug'])
148 def get_context_data(self, **kwargs):
149 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
150 context['diffusions'] = Diffusion.objects.select_related().filter(
151 episode=self.object.id).order_by('datetime')
153 context['emission'] = context['episode'].emission
154 except Emission.DoesNotExist:
156 if self.kwargs.get('emission_slug') != context['emission'].slug:
158 context.update(self.get_emission_context(context['emission']))
159 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
161 episode = EpisodeDetailView.as_view()
164 class NonstopPlaylistView(TemplateView):
165 template_name = 'nonstop_playlist.html'
167 def get_context_data(self, **kwargs):
168 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
170 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
171 except Emission.DoesNotExist:
173 context['date'] = date(int(kwargs.get('year')),
174 int(kwargs.get('month')), int(kwargs.get('day')))
175 context['future'] = (context['date'] >= date.today())
177 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
179 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
180 nonstop_object.start.hour, nonstop_object.start.minute)
182 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
183 nonstop_object.end.hour, nonstop_object.end.minute)
185 end = end + timedelta(days=1)
186 context['tracks'] = SomaLogLine.objects.filter(
187 play_timestamp__gte=start,
188 play_timestamp__lte=end,
189 on_air=True).select_related()
192 nonstop_playlist = NonstopPlaylistView.as_view()
194 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
196 template_name = 'emissions/episodes.html'
198 def get_context_data(self, **kwargs):
199 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
200 context['schedules'] = Schedule.objects.select_related().filter(
201 emission=self.object).order_by('rerun', 'datetime')
203 context['search_query'] = self.request.GET.get('q')
204 if context['search_query']:
206 sqs = SearchQuerySet().models(Episode).filter(
207 emission_slug_exact=self.object.slug, text=context['search_query'])
208 episode_ids = [x.pk for x in sqs]
212 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
214 emissionEpisodes = EmissionEpisodesDetailView.as_view()
217 class SoundFileEmbedView(DetailView):
219 template_name = 'soundfiles/embed.html'
221 def get_context_data(self, **kwargs):
222 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
223 if self.kwargs.get('episode_slug') != self.object.episode.slug:
225 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
227 context['episode'] = self.object.episode
229 soundfile_embed = SoundFileEmbedView.as_view()
232 class SoundFileDialogEmbedView(DetailView):
234 template_name = 'soundfiles/dialog-embed.html'
236 def get_context_data(self, **kwargs):
237 context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
238 if self.kwargs.get('episode_slug') != self.object.episode.slug:
240 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
242 context['episode'] = self.object.episode
244 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
248 class ProgramView(TemplateView):
249 template_name = 'program.html'
251 def get_context_data(self, year=None, week=None, **kwargs):
252 context = super(ProgramView, self).get_context_data(**kwargs)
254 context['weekday'] = datetime.today().weekday()
256 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
257 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
258 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
259 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
263 program = ProgramView.as_view()
271 def __init__(self, i, j):
276 def add_schedule(self, schedule):
277 end_time = schedule.datetime + timedelta(
278 minutes=schedule.get_duration())
279 self.time_label = '%02d:%02d-%02d:%02d' % (
280 schedule.datetime.hour,
281 schedule.datetime.minute,
284 self.schedules.append(schedule)
286 def __unicode__(self):
288 return ', '.join([x.emission.title for x in self.schedules])
292 def __eq__(self, other):
293 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
296 class Grid(TemplateView):
297 template_name = 'grid.html'
299 def get_context_data(self, **kwargs):
300 context = super(Grid, self).get_context_data(**kwargs)
302 nb_lines = 2 * 24 # the cells are half hours
305 Schedule.DAY_HOUR_START = 12
307 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
308 # start grid after the night programs
309 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
312 for nonstop in Nonstop.objects.all():
313 if nonstop.start == nonstop.end:
315 if nonstop.start < nonstop.end:
316 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
317 nonstop.end.hour + nonstop.end.minute/60.,
318 nonstop.title, nonstop.slug])
321 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
323 nonstop.title, nonstop.slug])
325 nonstop.end.hour + nonstop.end.minute/60.,
326 nonstop.title, nonstop.slug])
329 for i in range(nb_lines):
332 grid[-1].append(TimeCell(i, j))
335 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
338 for time_cell in grid[-1]:
339 time_cell.nonstop = nonstop[2]
340 time_cell.nonstop_slug = nonstop[3]
342 # the one ending at 5am will be cut down, so we inscribe
343 # its duration manually
344 time_cell.time_label = '%02d:00-%02d:00' % (
345 nonstop[0], nonstop[1])
347 for schedule in Schedule.objects.filter(emission__archived=False).prefetch_related(
348 'emission__categories').select_related().order_by('datetime'):
349 row_start = schedule.datetime.hour * 2 + \
350 int(math.ceil(schedule.datetime.minute / 30))
351 day_no = schedule.get_weekday()
353 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
354 if grid[(row_start+step)%nb_lines][day_no] is None:
355 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
356 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
358 # start grid after the night programs
359 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
361 # look for the case where the same emission has different schedules for
362 # the same time cell, for example if it lasts one hour the first week,
363 # and two hours the third week.
364 for i in range(nb_lines):
365 grid[i] = [x for x in grid[i] if x is not None]
366 for j, cell in enumerate(grid[i]):
367 if grid[i][j] is None:
369 if len(grid[i][j].schedules) > 1:
370 time_cell_emissions = {}
371 for schedule in grid[i][j].schedules:
372 if not schedule.emission.id in time_cell_emissions:
373 time_cell_emissions[schedule.emission.id] = []
374 time_cell_emissions[schedule.emission.id].append(schedule)
375 for schedule_list in time_cell_emissions.values():
376 if len(schedule_list) == 1:
378 # here it is, same cell, same emission, several
380 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
382 schedule = schedule_list[0]
383 end_time = schedule.datetime + timedelta(
384 minutes=schedule.get_duration())
385 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
386 schedule.datetime.hour,
387 schedule.datetime.minute,
391 for schedule in schedule_list[1:]:
392 grid[i][j].schedules.remove(schedule)
393 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
394 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
395 end_time.hour, end_time.minute, schedule.weeks_string)
399 # 1st thing is to merge cells on the same line, this will mostly catch
400 # consecutive nonstop cells
401 for i in range(nb_lines):
402 for j, cell in enumerate(grid[i]):
403 if grid[i][j] is None:
407 # if the cells are identical, they are removed from the
408 # grid, and current cell width is increased
409 while grid[i][j+t] == cell:
416 # once we're done we remove empty cells
417 grid[i] = [x for x in grid[i] if x is not None]
419 # 2nd thing is to merge cells vertically, this is emissions that last
420 # for more than 30 minutes
421 for i in range(nb_lines):
422 grid[i] = [x for x in grid[i] if x is not None]
423 for j, cell in enumerate(grid[i]):
424 if grid[i][j] is None:
429 # we look if the next time cell has the same emissions
430 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
431 if x == cell and x.y == cell.y and x.w == cell.w]
433 # if the cell was identical, we remove it and
434 # increase current cell height
435 bj, same_cell_below = same_cell_below[0]
436 del grid[i+cell.h][bj]
439 # if the cell is different, we have a closer look
440 # to it, so we can remove emissions that will
441 # already be mentioned in the current cell.
444 # - 7am30, seuls contre tout, 1h30
445 # - 8am, du pied gauche & la voix de la rue, 1h
446 # should produce: (this is case A)
448 # | seuls contre tout |
449 # |---------------------|
452 # | la voix de la rue |
454 # On the other hand, if all three emissions started
455 # at 7am30, we want: (this is case B)
457 # | seuls contre tout |
459 # | la voix de la rue |
460 # that is we merge all of them, ignoring the fact
461 # that the other emissions will stop at 8am30
462 current_cell_schedules = set(grid[i][j].schedules)
463 current_cell_emissions = set([x.emission for x in current_cell_schedules])
465 while True and current_cell_schedules:
466 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
467 if not same_cell_below:
470 same_cell_below = same_cell_below[0]
471 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
473 if current_cell_emissions.issubset(same_cell_below_emissions):
474 # this handles case A (see comment above)
475 for schedule in current_cell_schedules:
476 if schedule in same_cell_below.schedules:
477 same_cell_below.schedules.remove(schedule)
478 elif same_cell_below_emissions and \
479 current_cell_emissions.issuperset(same_cell_below_emissions):
480 # this handles case B (see comment above)
481 # we set the cell time label to the longest
483 grid[i][j].time_label = same_cell_below.time_label
484 # then we sort emissions so the longest are
486 grid[i][j].schedules.sort(
487 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
488 # then we add individual time labels to the
490 for schedule in current_cell_schedules:
491 if schedule not in same_cell_below.schedules:
492 end_time = schedule.datetime + timedelta(
493 minutes=schedule.get_duration())
494 schedule.time_label = '%02d:%02d-%02d:%02d' % (
495 schedule.datetime.hour,
496 schedule.datetime.minute,
500 grid[i+cursor].remove(same_cell_below)
501 elif same_cell_below_emissions and \
502 current_cell_emissions.intersection(same_cell_below_emissions):
503 same_cell_below.schedules = [x for x in
504 same_cell_below.schedules if
506 current_cell_emissions or
507 x.get_duration() < 30]
517 context['grid'] = grid
518 context['times'] = times
519 context['categories'] = Category.objects.all()
520 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
521 'Vendredi', 'Samedi', 'Dimanche']
525 grid = Grid.as_view()
528 class Home(TemplateView):
529 template_name = 'home.html'
531 def get_context_data(self, **kwargs):
532 context = super(Home, self).get_context_data(**kwargs)
533 context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
534 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
535 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
537 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
538 podcastable=True, fragment=False) \
539 .select_related().extra(select={
540 'first_diffusion': 'emissions_diffusion.datetime', },
541 select_params=(False, True),
542 where=['''datetime = (SELECT MIN(datetime)
543 FROM emissions_diffusion
544 WHERE episode_id = emissions_episode.id)'''],
545 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
547 context['newsletter_form'] = SubscribeForm()
548 context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
552 home = Home.as_view()
554 class NewsItemView(DetailView):
556 def get_context_data(self, **kwargs):
557 context = super(NewsItemView, self).get_context_data(**kwargs)
558 context['categories'] = NewsCategory.objects.all()
559 context['news'] = NewsItem.objects.all().order_by('-date')
560 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
562 newsitemview = NewsItemView.as_view()
564 class News(TemplateView):
565 template_name = 'news.html'
566 def get_context_data(self, **kwargs):
567 context = super(News, self).get_context_data(**kwargs)
568 context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
569 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
572 news = News.as_view()
575 class Agenda(TemplateView):
576 template_name = 'agenda.html'
577 def get_context_data(self, **kwargs):
578 context = super(Agenda, self).get_context_data(**kwargs)
579 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
580 event_date__gte=date.today()).order_by('date')[:20]
581 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
582 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
585 agenda = Agenda.as_view()
588 class AgendaByMonth(MonthArchiveView):
589 template_name = 'agenda.html'
590 queryset = NewsItem.objects.filter(event_date__isnull=False)
592 date_field = 'event_date'
595 def get_context_data(self, **kwargs):
596 context = super(AgendaByMonth, self).get_context_data(**kwargs)
597 context['agenda'] = context['object_list']
598 context['news'] = NewsItem.objects.all().order_by('-date')
601 agenda_by_month = AgendaByMonth.as_view()
604 class Emissions(TemplateView):
605 template_name = 'emissions.html'
607 def get_context_data(self, **kwargs):
608 context = super(Emissions, self).get_context_data(**kwargs)
609 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
610 context['categories'] = Category.objects.all()
613 emissions = Emissions.as_view()
615 class EmissionsArchives(TemplateView):
616 template_name = 'emissions/archives.html'
618 def get_context_data(self, **kwargs):
619 context = super(EmissionsArchives, self).get_context_data(**kwargs)
620 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
621 context['categories'] = Category.objects.all()
623 emissionsArchives = EmissionsArchives.as_view()
626 class Listen(TemplateView):
627 template_name = 'listen.html'
629 def get_context_data(self, **kwargs):
630 context = super(Listen, self).get_context_data(**kwargs)
631 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
632 podcastable=True, got_focus__isnull=False) \
633 .select_related().extra(select={
634 'first_diffusion': 'emissions_diffusion.datetime', },
635 select_params=(False, True),
636 where=['''datetime = (SELECT MIN(datetime)
637 FROM emissions_diffusion
638 WHERE episode_id = emissions_episode.id)'''],
639 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
640 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
642 .select_related().extra(select={
643 'first_diffusion': 'emissions_diffusion.datetime', },
644 select_params=(False, True),
645 where=['''datetime = (SELECT MIN(datetime)
646 FROM emissions_diffusion
647 WHERE episode_id = emissions_episode.id)'''],
648 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
653 listen = Listen.as_view()
655 @cache_control(max_age=15)
658 if datetime.now() < datetime(2018, 7, 31, 18, 0):
659 return {'emission': {'title': 'À partir du 31 juillet 18h', 'url': '/'}}
660 if date.today() > date(2018, 8, 5):
661 return {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}
665 'title': d['episode'].title,
666 'url': d['episode'].get_absolute_url()
668 if d.get('emission'):
670 if d['emission'].chat_open:
671 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
673 'title': d['emission'].title,
674 'url': d['emission'].get_absolute_url(),
679 'title': d['nonstop'].title,
681 playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
682 if os.path.exists(os.path.join(playing_txt)):
683 d['track_title'] = open(playing_txt).read().strip()
684 if d.get('current_slot'):
685 del d['current_slot']
686 return JsonResponse(d)
689 class NewsItemDetailView(DetailView):
692 newsitem = NewsItemDetailView.as_view()
694 class RssCustomPodcastsFeed(Rss201rev2Feed):
695 def add_root_elements(self, handler):
696 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
697 emission = self.feed.get('emission')
698 if emission and emission.image and emission.image.url:
699 image_url = emission.image.url
701 image_url = '/static/img/logo-panik-500.png'
702 image_url = urlparse.urljoin(self.feed['link'], image_url)
703 handler.startElement('image', {})
705 handler.addQuickElement('title', emission.title)
707 handler.addQuickElement('title', 'Radio Esperanzah!')
708 handler.addQuickElement('url', image_url)
709 handler.endElement('image')
710 handler.addQuickElement('itunes:image', None, {'href': image_url})
711 if emission and emission.subtitle:
712 handler.addQuickElement('itunes:subtitle', emission.subtitle)
714 def root_attributes(self):
715 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
716 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
717 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
720 def add_item_elements(self, handler, item):
721 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
723 for tag in item.get('tags') or []:
724 handler.addQuickElement('dc:subject', tag)
725 if tag == 'explicit':
728 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
729 handler.addQuickElement('itunes:explicit', explicit)
730 episode = item.get('episode')
731 if episode and episode.image and episode.image.url:
732 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
733 handler.addQuickElement('itunes:image', None, {'href': image_url})
734 soundfile = item.get('soundfile')
735 if soundfile.duration:
736 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
737 soundfile.duration / 3600,
738 soundfile.duration % 3600 / 60,
739 soundfile.duration % 60))
742 class PodcastsFeed(Feed):
743 title = 'Radio Esperanzah! - Podcasts'
745 description_template = 'feed/soundfile.html'
746 feed_type = RssCustomPodcastsFeed
749 return SoundFile.objects.select_related().filter(
750 podcastable=True).order_by('-creation_timestamp')[:20]
752 def item_title(self, item):
754 return '%s - %s' % (item.title, item.episode.title)
755 return '%s - %s' % (item.episode.emission.title, item.episode.title)
757 def item_link(self, item):
758 return item.episode.get_absolute_url()
760 def item_enclosure_url(self, item):
761 current_site = Site.objects.get(id=settings.SITE_ID)
762 return add_domain(current_site.domain, item.get_format_url('mp3'))
764 def item_enclosure_length(self, item):
765 sound_path = item.get_format_path('mp3')
767 return os.stat(sound_path)[stat.ST_SIZE]
771 def item_enclosure_mime_type(self, item):
774 def item_pubdate(self, item):
775 return item.creation_timestamp
777 def item_extra_kwargs(self, item):
778 return {'tags': [x.name for x in item.episode.tags.all()],
780 'episode': item.episode}
782 podcasts_feed = PodcastsFeed()
785 class RssNewsFeed(Feed):
786 title = 'Radio Esperanzah!'
788 description_template = 'feed/newsitem.html'
791 return NewsItem.objects.order_by('-date')[:20]
793 rss_news_feed = RssNewsFeed()
795 class Atom1FeedWithBaseXml(Atom1Feed):
796 def root_attributes(self):
797 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
798 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
799 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
800 return root_attributes
802 class AtomNewsFeed(RssNewsFeed):
803 feed_type = Atom1FeedWithBaseXml
805 atom_news_feed = AtomNewsFeed()
808 class EmissionPodcastsFeed(PodcastsFeed):
809 description_template = 'feed/soundfile.html'
810 feed_type = RssCustomPodcastsFeed
812 def __call__(self, request, *args, **kwargs):
813 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
814 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
818 return self.emission.title
822 return reverse('emission-view', kwargs={'slug': self.emission.slug})
824 def feed_extra_kwargs(self, obj):
825 return {'emission': self.emission}
828 return SoundFile.objects.select_related().filter(
830 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
832 emission_podcasts_feed = EmissionPodcastsFeed()
835 class Party(TemplateView):
836 template_name = 'party.html'
838 def get_context_data(self, **kwargs):
839 context = super(Party, self).get_context_data(**kwargs)
840 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
843 focus.newsitem = NewsItem.objects.exclude(
844 image__isnull=True).exclude(image__exact='').order_by('?')[0]
845 elif t == 'emission':
846 focus.emission = Emission.objects.exclude(
847 image__isnull=True).exclude(image__exact='').order_by('?')[0]
849 focus.episode = Episode.objects.exclude(
850 image__isnull=True).exclude(image__exact='').order_by('?')[0]
851 elif t == 'soundfile':
852 focus.soundfile = SoundFile.objects.exclude(
853 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
855 context['focus'] = focus
859 party = Party.as_view()
863 class Chat(DetailView, EmissionMixin):
865 template_name = 'chat.html'
867 chat = cache_control(max_age=15)(Chat.as_view())
871 class ArchivesView(TemplateView):
872 template_name = 'archives.html'
874 def get_context_data(self, **kwargs):
875 context = super(ArchivesView, self).get_context_data(**kwargs)
876 context['diffusions'] = Diffusion.objects.filter(episode__soundfile__isnull=False).distinct().order_by('-datetime')
879 archives = ArchivesView.as_view()