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()
81 current_year = datetime.now().replace(month=5, day=1)
83 context['all_episodes'] = episodes_queryset.filter(
84 creation_timestamp__gt=current_year
86 'first_diffusion': 'emissions_diffusion.datetime',
88 select_params=(False, True),
89 where=['''datetime = (SELECT MIN(datetime)
90 FROM emissions_diffusion
91 WHERE episode_id = emissions_episode.id
93 tables=['emissions_diffusion'],
94 ).order_by('first_diffusion')
96 # get all related soundfiles in a single query
98 if episode_ids is not None:
99 for episode_id in episode_ids:
100 soundfiles[episode_id] = None
102 for episode in Episode.objects.filter(emission=emission):
103 soundfiles[episode.id] = None
105 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
106 fragment=False, episode__emission=emission):
107 soundfiles[soundfile.episode_id] = soundfile
109 Episode.set_prefetched_soundfiles(soundfiles)
111 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
116 class EmissionDetailView(DetailView, EmissionMixin):
119 def get_context_data(self, **kwargs):
120 context = super(EmissionDetailView, self).get_context_data(**kwargs)
121 context['schedules'] = Schedule.objects.select_related().filter(
122 emission=self.object).order_by('rerun', 'datetime')
123 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
125 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
126 except Nonstop.DoesNotExist:
130 dates = [today - timedelta(days=x) for x in range(7)]
131 if datetime.now().time() < nonstop_object.start:
133 context['nonstop'] = nonstop_object
134 context['nonstop_dates'] = dates
135 context.update(self.get_emission_context(self.object))
137 emission = EmissionDetailView.as_view()
139 class EpisodeDetailView(DetailView, EmissionMixin):
142 def get_context_data(self, **kwargs):
143 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
144 context['diffusions'] = Diffusion.objects.select_related().filter(
145 episode=self.object.id).order_by('datetime')
147 context['emission'] = context['episode'].emission
148 except Emission.DoesNotExist:
150 if self.kwargs.get('emission_slug') != context['emission'].slug:
152 context.update(self.get_emission_context(context['emission']))
153 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
155 episode = EpisodeDetailView.as_view()
158 class NonstopPlaylistView(TemplateView):
159 template_name = 'nonstop_playlist.html'
161 def get_context_data(self, **kwargs):
162 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
164 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
165 except Emission.DoesNotExist:
167 context['date'] = date(int(kwargs.get('year')),
168 int(kwargs.get('month')), int(kwargs.get('day')))
169 context['future'] = (context['date'] >= date.today())
171 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
173 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
174 nonstop_object.start.hour, nonstop_object.start.minute)
176 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
177 nonstop_object.end.hour, nonstop_object.end.minute)
179 end = end + timedelta(days=1)
180 context['tracks'] = SomaLogLine.objects.filter(
181 play_timestamp__gte=start,
182 play_timestamp__lte=end,
183 on_air=True).select_related()
186 nonstop_playlist = NonstopPlaylistView.as_view()
188 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
190 template_name = 'emissions/episodes.html'
192 def get_context_data(self, **kwargs):
193 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
194 context['schedules'] = Schedule.objects.select_related().filter(
195 emission=self.object).order_by('rerun', 'datetime')
197 context['search_query'] = self.request.GET.get('q')
198 if context['search_query']:
200 sqs = SearchQuerySet().models(Episode).filter(
201 emission_slug_exact=self.object.slug, text=context['search_query'])
202 episode_ids = [x.pk for x in sqs]
206 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
208 emissionEpisodes = EmissionEpisodesDetailView.as_view()
211 class SoundFileEmbedView(DetailView):
213 template_name = 'soundfiles/embed.html'
215 def get_context_data(self, **kwargs):
216 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
217 if self.kwargs.get('episode_slug') != self.object.episode.slug:
219 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
221 context['episode'] = self.object.episode
223 soundfile_embed = SoundFileEmbedView.as_view()
226 class SoundFileDialogEmbedView(DetailView):
228 template_name = 'soundfiles/dialog-embed.html'
230 def get_context_data(self, **kwargs):
231 context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
232 if self.kwargs.get('episode_slug') != self.object.episode.slug:
234 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
236 context['episode'] = self.object.episode
238 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
242 class ProgramView(TemplateView):
243 template_name = 'program.html'
245 def get_context_data(self, year=None, week=None, **kwargs):
246 context = super(ProgramView, self).get_context_data(**kwargs)
248 context['weekday'] = datetime.today().weekday()
250 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
251 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
252 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
253 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
257 program = ProgramView.as_view()
265 def __init__(self, i, j):
270 def add_schedule(self, schedule):
271 end_time = schedule.datetime + timedelta(
272 minutes=schedule.get_duration())
273 self.time_label = '%02d:%02d-%02d:%02d' % (
274 schedule.datetime.hour,
275 schedule.datetime.minute,
278 self.schedules.append(schedule)
280 def __unicode__(self):
282 return ', '.join([x.emission.title for x in self.schedules])
286 def __eq__(self, other):
287 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
290 class Grid(TemplateView):
291 template_name = 'grid.html'
293 def get_context_data(self, **kwargs):
294 context = super(Grid, self).get_context_data(**kwargs)
296 nb_lines = 2 * 24 # the cells are half hours
299 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
300 # start grid after the night programs
301 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
304 for nonstop in Nonstop.objects.all():
305 if nonstop.start == nonstop.end:
307 if nonstop.start < nonstop.end:
308 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
309 nonstop.end.hour + nonstop.end.minute/60.,
310 nonstop.title, nonstop.slug])
313 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
315 nonstop.title, nonstop.slug])
317 nonstop.end.hour + nonstop.end.minute/60.,
318 nonstop.title, nonstop.slug])
321 for i in range(nb_lines):
324 grid[-1].append(TimeCell(i, j))
326 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
327 for time_cell in grid[-1]:
328 time_cell.nonstop = nonstop[2]
329 time_cell.nonstop_slug = nonstop[3]
331 # the one ending at 5am will be cut down, so we inscribe
332 # its duration manually
333 time_cell.time_label = '%02d:00-%02d:00' % (
334 nonstop[0], nonstop[1])
336 for schedule in Schedule.objects.prefetch_related(
337 'emission__categories').select_related().order_by('datetime'):
338 row_start = schedule.datetime.hour * 2 + \
339 int(math.ceil(schedule.datetime.minute / 30))
340 day_no = schedule.get_weekday()
342 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
343 if grid[(row_start+step)%nb_lines][day_no] is None:
344 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
345 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
347 # start grid after the night programs
348 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
350 # look for the case where the same emission has different schedules for
351 # the same time cell, for example if it lasts one hour the first week,
352 # and two hours the third week.
353 for i in range(nb_lines):
354 grid[i] = [x for x in grid[i] if x is not None]
355 for j, cell in enumerate(grid[i]):
356 if grid[i][j] is None:
358 if len(grid[i][j].schedules) > 1:
359 time_cell_emissions = {}
360 for schedule in grid[i][j].schedules:
361 if not schedule.emission.id in time_cell_emissions:
362 time_cell_emissions[schedule.emission.id] = []
363 time_cell_emissions[schedule.emission.id].append(schedule)
364 for schedule_list in time_cell_emissions.values():
365 if len(schedule_list) == 1:
367 # here it is, same cell, same emission, several
369 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
371 schedule = schedule_list[0]
372 end_time = schedule.datetime + timedelta(
373 minutes=schedule.get_duration())
374 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
375 schedule.datetime.hour,
376 schedule.datetime.minute,
380 for schedule in schedule_list[1:]:
381 grid[i][j].schedules.remove(schedule)
382 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
383 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
384 end_time.hour, end_time.minute, schedule.weeks_string)
388 # 1st thing is to merge cells on the same line, this will mostly catch
389 # consecutive nonstop cells
390 for i in range(nb_lines):
391 for j, cell in enumerate(grid[i]):
392 if grid[i][j] is None:
396 # if the cells are identical, they are removed from the
397 # grid, and current cell width is increased
398 while grid[i][j+t] == cell:
405 # once we're done we remove empty cells
406 grid[i] = [x for x in grid[i] if x is not None]
408 # 2nd thing is to merge cells vertically, this is emissions that last
409 # for more than 30 minutes
410 for i in range(nb_lines):
411 grid[i] = [x for x in grid[i] if x is not None]
412 for j, cell in enumerate(grid[i]):
413 if grid[i][j] is None:
418 # we look if the next time cell has the same emissions
419 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
420 if x == cell and x.y == cell.y and x.w == cell.w]
422 # if the cell was identical, we remove it and
423 # increase current cell height
424 bj, same_cell_below = same_cell_below[0]
425 del grid[i+cell.h][bj]
428 # if the cell is different, we have a closer look
429 # to it, so we can remove emissions that will
430 # already be mentioned in the current cell.
433 # - 7am30, seuls contre tout, 1h30
434 # - 8am, du pied gauche & la voix de la rue, 1h
435 # should produce: (this is case A)
437 # | seuls contre tout |
438 # |---------------------|
441 # | la voix de la rue |
443 # On the other hand, if all three emissions started
444 # at 7am30, we want: (this is case B)
446 # | seuls contre tout |
448 # | la voix de la rue |
449 # that is we merge all of them, ignoring the fact
450 # that the other emissions will stop at 8am30
451 current_cell_schedules = set(grid[i][j].schedules)
452 current_cell_emissions = set([x.emission for x in current_cell_schedules])
454 while True and current_cell_schedules:
455 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
456 if not same_cell_below:
459 same_cell_below = same_cell_below[0]
460 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
462 if current_cell_emissions.issubset(same_cell_below_emissions):
463 # this handles case A (see comment above)
464 for schedule in current_cell_schedules:
465 if schedule in same_cell_below.schedules:
466 same_cell_below.schedules.remove(schedule)
467 elif same_cell_below_emissions and \
468 current_cell_emissions.issuperset(same_cell_below_emissions):
469 # this handles case B (see comment above)
470 # we set the cell time label to the longest
472 grid[i][j].time_label = same_cell_below.time_label
473 # then we sort emissions so the longest are
475 grid[i][j].schedules.sort(
476 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
477 # then we add individual time labels to the
479 for schedule in current_cell_schedules:
480 if schedule not in same_cell_below.schedules:
481 end_time = schedule.datetime + timedelta(
482 minutes=schedule.get_duration())
483 schedule.time_label = '%02d:%02d-%02d:%02d' % (
484 schedule.datetime.hour,
485 schedule.datetime.minute,
489 grid[i+cursor].remove(same_cell_below)
490 elif same_cell_below_emissions and \
491 current_cell_emissions.intersection(same_cell_below_emissions):
492 same_cell_below.schedules = [x for x in
493 same_cell_below.schedules if
495 current_cell_emissions or
496 x.get_duration() < 30]
506 context['grid'] = grid
507 context['times'] = times
508 context['categories'] = Category.objects.all()
509 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
510 'Vendredi', 'Samedi', 'Dimanche']
514 grid = Grid.as_view()
517 class Home(TemplateView):
518 template_name = 'home.html'
520 def get_context_data(self, **kwargs):
521 context = super(Home, self).get_context_data(**kwargs)
522 context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
523 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
524 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
526 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
527 podcastable=True, fragment=False) \
528 .select_related().extra(select={
529 'first_diffusion': 'emissions_diffusion.datetime', },
530 select_params=(False, True),
531 where=['''datetime = (SELECT MIN(datetime)
532 FROM emissions_diffusion
533 WHERE episode_id = emissions_episode.id)'''],
534 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
536 context['newsletter_form'] = SubscribeForm()
537 context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
541 home = Home.as_view()
543 class NewsItemView(DetailView):
545 def get_context_data(self, **kwargs):
546 context = super(NewsItemView, self).get_context_data(**kwargs)
547 context['categories'] = NewsCategory.objects.all()
548 context['news'] = NewsItem.objects.all().order_by('-date')
549 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
551 newsitemview = NewsItemView.as_view()
553 class News(TemplateView):
554 template_name = 'news.html'
555 def get_context_data(self, **kwargs):
556 context = super(News, self).get_context_data(**kwargs)
557 context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
558 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
561 news = News.as_view()
564 class Agenda(TemplateView):
565 template_name = 'agenda.html'
566 def get_context_data(self, **kwargs):
567 context = super(Agenda, self).get_context_data(**kwargs)
568 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
569 event_date__gte=date.today()).order_by('date')[:20]
570 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
571 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
574 agenda = Agenda.as_view()
577 class AgendaByMonth(MonthArchiveView):
578 template_name = 'agenda.html'
579 queryset = NewsItem.objects.filter(event_date__isnull=False)
581 date_field = 'event_date'
584 def get_context_data(self, **kwargs):
585 context = super(AgendaByMonth, self).get_context_data(**kwargs)
586 context['agenda'] = context['object_list']
587 context['news'] = NewsItem.objects.all().order_by('-date')
590 agenda_by_month = AgendaByMonth.as_view()
593 class Emissions(TemplateView):
594 template_name = 'emissions.html'
596 def get_context_data(self, **kwargs):
597 context = super(Emissions, self).get_context_data(**kwargs)
598 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
599 context['categories'] = Category.objects.all()
602 emissions = Emissions.as_view()
604 class EmissionsArchives(TemplateView):
605 template_name = 'emissions/archives.html'
607 def get_context_data(self, **kwargs):
608 context = super(EmissionsArchives, self).get_context_data(**kwargs)
609 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
610 context['categories'] = Category.objects.all()
612 emissionsArchives = EmissionsArchives.as_view()
615 class Listen(TemplateView):
616 template_name = 'listen.html'
618 def get_context_data(self, **kwargs):
619 context = super(Listen, self).get_context_data(**kwargs)
620 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
621 podcastable=True, got_focus__isnull=False) \
622 .select_related().extra(select={
623 'first_diffusion': 'emissions_diffusion.datetime', },
624 select_params=(False, True),
625 where=['''datetime = (SELECT MIN(datetime)
626 FROM emissions_diffusion
627 WHERE episode_id = emissions_episode.id)'''],
628 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
629 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
631 .select_related().extra(select={
632 'first_diffusion': 'emissions_diffusion.datetime', },
633 select_params=(False, True),
634 where=['''datetime = (SELECT MIN(datetime)
635 FROM emissions_diffusion
636 WHERE episode_id = emissions_episode.id)'''],
637 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
642 listen = Listen.as_view()
644 @cache_control(max_age=15)
648 if date.today() < date(2017, 8, 3):
649 return {'emission': {'title': 'À partir du 3 août 17h', 'url': '/'}}
650 if date.today() > date(2017, 8, 6):
651 return {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}
655 'title': d['episode'].title,
656 'url': d['episode'].get_absolute_url()
658 if d.get('emission'):
660 if d['emission'].chat_open:
661 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
663 'title': d['emission'].title,
664 'url': d['emission'].get_absolute_url(),
669 'title': d['nonstop'].title,
671 playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
672 if os.path.exists(os.path.join(playing_txt)):
673 d['track_title'] = open(playing_txt).read().strip()
674 if d.get('current_slot'):
675 del d['current_slot']
679 class NewsItemDetailView(DetailView):
682 newsitem = NewsItemDetailView.as_view()
684 class RssCustomPodcastsFeed(Rss201rev2Feed):
685 def add_root_elements(self, handler):
686 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
687 emission = self.feed.get('emission')
688 if emission and emission.image and emission.image.url:
689 image_url = emission.image.url
691 image_url = '/static/img/logo-panik-500.png'
692 image_url = urlparse.urljoin(self.feed['link'], image_url)
693 handler.startElement('image', {})
695 handler.addQuickElement('title', emission.title)
697 handler.addQuickElement('title', 'Radio Esperanzah!')
698 handler.addQuickElement('url', image_url)
699 handler.endElement('image')
700 handler.addQuickElement('itunes:image', None, {'href': image_url})
701 if emission and emission.subtitle:
702 handler.addQuickElement('itunes:subtitle', emission.subtitle)
704 def root_attributes(self):
705 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
706 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
707 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
710 def add_item_elements(self, handler, item):
711 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
713 for tag in item.get('tags') or []:
714 handler.addQuickElement('dc:subject', tag)
715 if tag == 'explicit':
718 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
719 handler.addQuickElement('itunes:explicit', explicit)
720 episode = item.get('episode')
721 if episode and episode.image and episode.image.url:
722 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
723 handler.addQuickElement('itunes:image', None, {'href': image_url})
724 soundfile = item.get('soundfile')
725 if soundfile.duration:
726 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
727 soundfile.duration / 3600,
728 soundfile.duration % 3600 / 60,
729 soundfile.duration % 60))
732 class PodcastsFeed(Feed):
733 title = 'Radio Esperanzah! - Podcasts'
735 description_template = 'feed/soundfile.html'
736 feed_type = RssCustomPodcastsFeed
739 return SoundFile.objects.select_related().filter(
740 podcastable=True).order_by('-creation_timestamp')[:20]
742 def item_title(self, item):
744 return '%s - %s' % (item.title, item.episode.title)
745 return '%s - %s' % (item.episode.emission.title, item.episode.title)
747 def item_link(self, item):
748 return item.episode.get_absolute_url()
750 def item_enclosure_url(self, item):
751 current_site = Site.objects.get(id=settings.SITE_ID)
752 return add_domain(current_site.domain, item.get_format_url('mp3'))
754 def item_enclosure_length(self, item):
755 sound_path = item.get_format_path('mp3')
757 return os.stat(sound_path)[stat.ST_SIZE]
761 def item_enclosure_mime_type(self, item):
764 def item_pubdate(self, item):
765 return item.creation_timestamp
767 def item_extra_kwargs(self, item):
768 return {'tags': [x.name for x in item.episode.tags.all()],
770 'episode': item.episode}
772 podcasts_feed = PodcastsFeed()
775 class RssNewsFeed(Feed):
776 title = 'Radio Esperanzah!'
778 description_template = 'feed/newsitem.html'
781 return NewsItem.objects.order_by('-date')[:20]
783 rss_news_feed = RssNewsFeed()
785 class Atom1FeedWithBaseXml(Atom1Feed):
786 def root_attributes(self):
787 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
788 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
789 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
790 return root_attributes
792 class AtomNewsFeed(RssNewsFeed):
793 feed_type = Atom1FeedWithBaseXml
795 atom_news_feed = AtomNewsFeed()
798 class EmissionPodcastsFeed(PodcastsFeed):
799 description_template = 'feed/soundfile.html'
800 feed_type = RssCustomPodcastsFeed
802 def __call__(self, request, *args, **kwargs):
803 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
804 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
808 return '%s - Podcasts' % self.emission.title
812 return reverse('emission-view', kwargs={'slug': self.emission.slug})
814 def feed_extra_kwargs(self, obj):
815 return {'emission': self.emission}
818 return SoundFile.objects.select_related().filter(
820 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
822 emission_podcasts_feed = EmissionPodcastsFeed()
825 class Party(TemplateView):
826 template_name = 'party.html'
828 def get_context_data(self, **kwargs):
829 context = super(Party, self).get_context_data(**kwargs)
830 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
833 focus.newsitem = NewsItem.objects.exclude(
834 image__isnull=True).exclude(image__exact='').order_by('?')[0]
835 elif t == 'emission':
836 focus.emission = Emission.objects.exclude(
837 image__isnull=True).exclude(image__exact='').order_by('?')[0]
839 focus.episode = Episode.objects.exclude(
840 image__isnull=True).exclude(image__exact='').order_by('?')[0]
841 elif t == 'soundfile':
842 focus.soundfile = SoundFile.objects.exclude(
843 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
845 context['focus'] = focus
849 party = Party.as_view()
853 class Chat(DetailView, EmissionMixin):
855 template_name = 'chat.html'
857 chat = cache_control(max_age=15)(Chat.as_view())
861 class ArchivesView(TemplateView):
862 template_name = 'archives.html'
864 def get_context_data(self, **kwargs):
865 context = super(ArchivesView, self).get_context_data(**kwargs)
866 context['diffusions'] = Diffusion.objects.all().order_by('-datetime')
869 archives = ArchivesView.as_view()