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 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
307 # start grid after the night programs
308 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
311 for nonstop in Nonstop.objects.all():
312 if nonstop.start == nonstop.end:
314 if nonstop.start < nonstop.end:
315 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
316 nonstop.end.hour + nonstop.end.minute/60.,
317 nonstop.title, nonstop.slug])
320 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
322 nonstop.title, nonstop.slug])
324 nonstop.end.hour + nonstop.end.minute/60.,
325 nonstop.title, nonstop.slug])
328 for i in range(nb_lines):
331 grid[-1].append(TimeCell(i, j))
333 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
334 for time_cell in grid[-1]:
335 time_cell.nonstop = nonstop[2]
336 time_cell.nonstop_slug = nonstop[3]
338 # the one ending at 5am will be cut down, so we inscribe
339 # its duration manually
340 time_cell.time_label = '%02d:00-%02d:00' % (
341 nonstop[0], nonstop[1])
343 for schedule in Schedule.objects.prefetch_related(
344 'emission__categories').select_related().order_by('datetime'):
345 row_start = schedule.datetime.hour * 2 + \
346 int(math.ceil(schedule.datetime.minute / 30))
347 day_no = schedule.get_weekday()
349 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
350 if grid[(row_start+step)%nb_lines][day_no] is None:
351 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
352 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
354 # start grid after the night programs
355 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
357 # look for the case where the same emission has different schedules for
358 # the same time cell, for example if it lasts one hour the first week,
359 # and two hours the third week.
360 for i in range(nb_lines):
361 grid[i] = [x for x in grid[i] if x is not None]
362 for j, cell in enumerate(grid[i]):
363 if grid[i][j] is None:
365 if len(grid[i][j].schedules) > 1:
366 time_cell_emissions = {}
367 for schedule in grid[i][j].schedules:
368 if not schedule.emission.id in time_cell_emissions:
369 time_cell_emissions[schedule.emission.id] = []
370 time_cell_emissions[schedule.emission.id].append(schedule)
371 for schedule_list in time_cell_emissions.values():
372 if len(schedule_list) == 1:
374 # here it is, same cell, same emission, several
376 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
378 schedule = schedule_list[0]
379 end_time = schedule.datetime + timedelta(
380 minutes=schedule.get_duration())
381 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
382 schedule.datetime.hour,
383 schedule.datetime.minute,
387 for schedule in schedule_list[1:]:
388 grid[i][j].schedules.remove(schedule)
389 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
390 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
391 end_time.hour, end_time.minute, schedule.weeks_string)
395 # 1st thing is to merge cells on the same line, this will mostly catch
396 # consecutive nonstop cells
397 for i in range(nb_lines):
398 for j, cell in enumerate(grid[i]):
399 if grid[i][j] is None:
403 # if the cells are identical, they are removed from the
404 # grid, and current cell width is increased
405 while grid[i][j+t] == cell:
412 # once we're done we remove empty cells
413 grid[i] = [x for x in grid[i] if x is not None]
415 # 2nd thing is to merge cells vertically, this is emissions that last
416 # for more than 30 minutes
417 for i in range(nb_lines):
418 grid[i] = [x for x in grid[i] if x is not None]
419 for j, cell in enumerate(grid[i]):
420 if grid[i][j] is None:
425 # we look if the next time cell has the same emissions
426 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
427 if x == cell and x.y == cell.y and x.w == cell.w]
429 # if the cell was identical, we remove it and
430 # increase current cell height
431 bj, same_cell_below = same_cell_below[0]
432 del grid[i+cell.h][bj]
435 # if the cell is different, we have a closer look
436 # to it, so we can remove emissions that will
437 # already be mentioned in the current cell.
440 # - 7am30, seuls contre tout, 1h30
441 # - 8am, du pied gauche & la voix de la rue, 1h
442 # should produce: (this is case A)
444 # | seuls contre tout |
445 # |---------------------|
448 # | la voix de la rue |
450 # On the other hand, if all three emissions started
451 # at 7am30, we want: (this is case B)
453 # | seuls contre tout |
455 # | la voix de la rue |
456 # that is we merge all of them, ignoring the fact
457 # that the other emissions will stop at 8am30
458 current_cell_schedules = set(grid[i][j].schedules)
459 current_cell_emissions = set([x.emission for x in current_cell_schedules])
461 while True and current_cell_schedules:
462 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
463 if not same_cell_below:
466 same_cell_below = same_cell_below[0]
467 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
469 if current_cell_emissions.issubset(same_cell_below_emissions):
470 # this handles case A (see comment above)
471 for schedule in current_cell_schedules:
472 if schedule in same_cell_below.schedules:
473 same_cell_below.schedules.remove(schedule)
474 elif same_cell_below_emissions and \
475 current_cell_emissions.issuperset(same_cell_below_emissions):
476 # this handles case B (see comment above)
477 # we set the cell time label to the longest
479 grid[i][j].time_label = same_cell_below.time_label
480 # then we sort emissions so the longest are
482 grid[i][j].schedules.sort(
483 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
484 # then we add individual time labels to the
486 for schedule in current_cell_schedules:
487 if schedule not in same_cell_below.schedules:
488 end_time = schedule.datetime + timedelta(
489 minutes=schedule.get_duration())
490 schedule.time_label = '%02d:%02d-%02d:%02d' % (
491 schedule.datetime.hour,
492 schedule.datetime.minute,
496 grid[i+cursor].remove(same_cell_below)
497 elif same_cell_below_emissions and \
498 current_cell_emissions.intersection(same_cell_below_emissions):
499 same_cell_below.schedules = [x for x in
500 same_cell_below.schedules if
502 current_cell_emissions or
503 x.get_duration() < 30]
513 context['grid'] = grid
514 context['times'] = times
515 context['categories'] = Category.objects.all()
516 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
517 'Vendredi', 'Samedi', 'Dimanche']
521 grid = Grid.as_view()
524 class Home(TemplateView):
525 template_name = 'home.html'
527 def get_context_data(self, **kwargs):
528 context = super(Home, self).get_context_data(**kwargs)
529 context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
530 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
531 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
533 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
534 podcastable=True, fragment=False) \
535 .select_related().extra(select={
536 'first_diffusion': 'emissions_diffusion.datetime', },
537 select_params=(False, True),
538 where=['''datetime = (SELECT MIN(datetime)
539 FROM emissions_diffusion
540 WHERE episode_id = emissions_episode.id)'''],
541 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
543 context['newsletter_form'] = SubscribeForm()
544 context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
548 home = Home.as_view()
550 class NewsItemView(DetailView):
552 def get_context_data(self, **kwargs):
553 context = super(NewsItemView, self).get_context_data(**kwargs)
554 context['categories'] = NewsCategory.objects.all()
555 context['news'] = NewsItem.objects.all().order_by('-date')
556 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
558 newsitemview = NewsItemView.as_view()
560 class News(TemplateView):
561 template_name = 'news.html'
562 def get_context_data(self, **kwargs):
563 context = super(News, self).get_context_data(**kwargs)
564 context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
565 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
568 news = News.as_view()
571 class Agenda(TemplateView):
572 template_name = 'agenda.html'
573 def get_context_data(self, **kwargs):
574 context = super(Agenda, self).get_context_data(**kwargs)
575 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
576 event_date__gte=date.today()).order_by('date')[:20]
577 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
578 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
581 agenda = Agenda.as_view()
584 class AgendaByMonth(MonthArchiveView):
585 template_name = 'agenda.html'
586 queryset = NewsItem.objects.filter(event_date__isnull=False)
588 date_field = 'event_date'
591 def get_context_data(self, **kwargs):
592 context = super(AgendaByMonth, self).get_context_data(**kwargs)
593 context['agenda'] = context['object_list']
594 context['news'] = NewsItem.objects.all().order_by('-date')
597 agenda_by_month = AgendaByMonth.as_view()
600 class Emissions(TemplateView):
601 template_name = 'emissions.html'
603 def get_context_data(self, **kwargs):
604 context = super(Emissions, self).get_context_data(**kwargs)
605 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
606 context['categories'] = Category.objects.all()
609 emissions = Emissions.as_view()
611 class EmissionsArchives(TemplateView):
612 template_name = 'emissions/archives.html'
614 def get_context_data(self, **kwargs):
615 context = super(EmissionsArchives, self).get_context_data(**kwargs)
616 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
617 context['categories'] = Category.objects.all()
619 emissionsArchives = EmissionsArchives.as_view()
622 class Listen(TemplateView):
623 template_name = 'listen.html'
625 def get_context_data(self, **kwargs):
626 context = super(Listen, self).get_context_data(**kwargs)
627 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
628 podcastable=True, got_focus__isnull=False) \
629 .select_related().extra(select={
630 'first_diffusion': 'emissions_diffusion.datetime', },
631 select_params=(False, True),
632 where=['''datetime = (SELECT MIN(datetime)
633 FROM emissions_diffusion
634 WHERE episode_id = emissions_episode.id)'''],
635 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
636 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
638 .select_related().extra(select={
639 'first_diffusion': 'emissions_diffusion.datetime', },
640 select_params=(False, True),
641 where=['''datetime = (SELECT MIN(datetime)
642 FROM emissions_diffusion
643 WHERE episode_id = emissions_episode.id)'''],
644 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
649 listen = Listen.as_view()
651 @cache_control(max_age=15)
655 if date.today() < date(2018, 7, 30):
656 return {'emission': {'title': 'À partir du 31 juillet 18h', 'url': '/'}}
657 if date.today() > date(2018, 8, 5):
658 return {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}
662 'title': d['episode'].title,
663 'url': d['episode'].get_absolute_url()
665 if d.get('emission'):
667 if d['emission'].chat_open:
668 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
670 'title': d['emission'].title,
671 'url': d['emission'].get_absolute_url(),
676 'title': d['nonstop'].title,
678 playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
679 if os.path.exists(os.path.join(playing_txt)):
680 d['track_title'] = open(playing_txt).read().strip()
681 if d.get('current_slot'):
682 del d['current_slot']
686 class NewsItemDetailView(DetailView):
689 newsitem = NewsItemDetailView.as_view()
691 class RssCustomPodcastsFeed(Rss201rev2Feed):
692 def add_root_elements(self, handler):
693 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
694 emission = self.feed.get('emission')
695 if emission and emission.image and emission.image.url:
696 image_url = emission.image.url
698 image_url = '/static/img/logo-panik-500.png'
699 image_url = urlparse.urljoin(self.feed['link'], image_url)
700 handler.startElement('image', {})
702 handler.addQuickElement('title', emission.title)
704 handler.addQuickElement('title', 'Radio Esperanzah!')
705 handler.addQuickElement('url', image_url)
706 handler.endElement('image')
707 handler.addQuickElement('itunes:image', None, {'href': image_url})
708 if emission and emission.subtitle:
709 handler.addQuickElement('itunes:subtitle', emission.subtitle)
711 def root_attributes(self):
712 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
713 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
714 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
717 def add_item_elements(self, handler, item):
718 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
720 for tag in item.get('tags') or []:
721 handler.addQuickElement('dc:subject', tag)
722 if tag == 'explicit':
725 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
726 handler.addQuickElement('itunes:explicit', explicit)
727 episode = item.get('episode')
728 if episode and episode.image and episode.image.url:
729 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
730 handler.addQuickElement('itunes:image', None, {'href': image_url})
731 soundfile = item.get('soundfile')
732 if soundfile.duration:
733 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
734 soundfile.duration / 3600,
735 soundfile.duration % 3600 / 60,
736 soundfile.duration % 60))
739 class PodcastsFeed(Feed):
740 title = 'Radio Esperanzah! - Podcasts'
742 description_template = 'feed/soundfile.html'
743 feed_type = RssCustomPodcastsFeed
746 return SoundFile.objects.select_related().filter(
747 podcastable=True).order_by('-creation_timestamp')[:20]
749 def item_title(self, item):
751 return '%s - %s' % (item.title, item.episode.title)
752 return '%s - %s' % (item.episode.emission.title, item.episode.title)
754 def item_link(self, item):
755 return item.episode.get_absolute_url()
757 def item_enclosure_url(self, item):
758 current_site = Site.objects.get(id=settings.SITE_ID)
759 return add_domain(current_site.domain, item.get_format_url('mp3'))
761 def item_enclosure_length(self, item):
762 sound_path = item.get_format_path('mp3')
764 return os.stat(sound_path)[stat.ST_SIZE]
768 def item_enclosure_mime_type(self, item):
771 def item_pubdate(self, item):
772 return item.creation_timestamp
774 def item_extra_kwargs(self, item):
775 return {'tags': [x.name for x in item.episode.tags.all()],
777 'episode': item.episode}
779 podcasts_feed = PodcastsFeed()
782 class RssNewsFeed(Feed):
783 title = 'Radio Esperanzah!'
785 description_template = 'feed/newsitem.html'
788 return NewsItem.objects.order_by('-date')[:20]
790 rss_news_feed = RssNewsFeed()
792 class Atom1FeedWithBaseXml(Atom1Feed):
793 def root_attributes(self):
794 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
795 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
796 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
797 return root_attributes
799 class AtomNewsFeed(RssNewsFeed):
800 feed_type = Atom1FeedWithBaseXml
802 atom_news_feed = AtomNewsFeed()
805 class EmissionPodcastsFeed(PodcastsFeed):
806 description_template = 'feed/soundfile.html'
807 feed_type = RssCustomPodcastsFeed
809 def __call__(self, request, *args, **kwargs):
810 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
811 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
815 return '%s - Podcasts' % self.emission.title
819 return reverse('emission-view', kwargs={'slug': self.emission.slug})
821 def feed_extra_kwargs(self, obj):
822 return {'emission': self.emission}
825 return SoundFile.objects.select_related().filter(
827 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
829 emission_podcasts_feed = EmissionPodcastsFeed()
832 class Party(TemplateView):
833 template_name = 'party.html'
835 def get_context_data(self, **kwargs):
836 context = super(Party, self).get_context_data(**kwargs)
837 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
840 focus.newsitem = NewsItem.objects.exclude(
841 image__isnull=True).exclude(image__exact='').order_by('?')[0]
842 elif t == 'emission':
843 focus.emission = Emission.objects.exclude(
844 image__isnull=True).exclude(image__exact='').order_by('?')[0]
846 focus.episode = Episode.objects.exclude(
847 image__isnull=True).exclude(image__exact='').order_by('?')[0]
848 elif t == 'soundfile':
849 focus.soundfile = SoundFile.objects.exclude(
850 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
852 context['focus'] = focus
856 party = Party.as_view()
860 class Chat(DetailView, EmissionMixin):
862 template_name = 'chat.html'
864 chat = cache_control(max_age=15)(Chat.as_view())
868 class ArchivesView(TemplateView):
869 template_name = 'archives.html'
871 def get_context_data(self, **kwargs):
872 context = super(ArchivesView, self).get_context_data(**kwargs)
873 context['diffusions'] = Diffusion.objects.filter(episode__soundfile__isnull=False).select_related().order_by('-datetime')
876 archives = ArchivesView.as_view()