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))
334 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
337 for time_cell in grid[-1]:
338 time_cell.nonstop = nonstop[2]
339 time_cell.nonstop_slug = nonstop[3]
341 # the one ending at 5am will be cut down, so we inscribe
342 # its duration manually
343 time_cell.time_label = '%02d:00-%02d:00' % (
344 nonstop[0], nonstop[1])
346 for schedule in Schedule.objects.filter(emission__archived=False).prefetch_related(
347 'emission__categories').select_related().order_by('datetime'):
348 row_start = schedule.datetime.hour * 2 + \
349 int(math.ceil(schedule.datetime.minute / 30))
350 day_no = schedule.get_weekday()
352 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
353 if grid[(row_start+step)%nb_lines][day_no] is None:
354 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
355 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
357 # start grid after the night programs
358 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
360 # look for the case where the same emission has different schedules for
361 # the same time cell, for example if it lasts one hour the first week,
362 # and two hours the third week.
363 for i in range(nb_lines):
364 grid[i] = [x for x in grid[i] if x is not None]
365 for j, cell in enumerate(grid[i]):
366 if grid[i][j] is None:
368 if len(grid[i][j].schedules) > 1:
369 time_cell_emissions = {}
370 for schedule in grid[i][j].schedules:
371 if not schedule.emission.id in time_cell_emissions:
372 time_cell_emissions[schedule.emission.id] = []
373 time_cell_emissions[schedule.emission.id].append(schedule)
374 for schedule_list in time_cell_emissions.values():
375 if len(schedule_list) == 1:
377 # here it is, same cell, same emission, several
379 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
381 schedule = schedule_list[0]
382 end_time = schedule.datetime + timedelta(
383 minutes=schedule.get_duration())
384 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
385 schedule.datetime.hour,
386 schedule.datetime.minute,
390 for schedule in schedule_list[1:]:
391 grid[i][j].schedules.remove(schedule)
392 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
393 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
394 end_time.hour, end_time.minute, schedule.weeks_string)
398 # 1st thing is to merge cells on the same line, this will mostly catch
399 # consecutive nonstop cells
400 for i in range(nb_lines):
401 for j, cell in enumerate(grid[i]):
402 if grid[i][j] is None:
406 # if the cells are identical, they are removed from the
407 # grid, and current cell width is increased
408 while grid[i][j+t] == cell:
415 # once we're done we remove empty cells
416 grid[i] = [x for x in grid[i] if x is not None]
418 # 2nd thing is to merge cells vertically, this is emissions that last
419 # for more than 30 minutes
420 for i in range(nb_lines):
421 grid[i] = [x for x in grid[i] if x is not None]
422 for j, cell in enumerate(grid[i]):
423 if grid[i][j] is None:
428 # we look if the next time cell has the same emissions
429 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
430 if x == cell and x.y == cell.y and x.w == cell.w]
432 # if the cell was identical, we remove it and
433 # increase current cell height
434 bj, same_cell_below = same_cell_below[0]
435 del grid[i+cell.h][bj]
438 # if the cell is different, we have a closer look
439 # to it, so we can remove emissions that will
440 # already be mentioned in the current cell.
443 # - 7am30, seuls contre tout, 1h30
444 # - 8am, du pied gauche & la voix de la rue, 1h
445 # should produce: (this is case A)
447 # | seuls contre tout |
448 # |---------------------|
451 # | la voix de la rue |
453 # On the other hand, if all three emissions started
454 # at 7am30, we want: (this is case B)
456 # | seuls contre tout |
458 # | la voix de la rue |
459 # that is we merge all of them, ignoring the fact
460 # that the other emissions will stop at 8am30
461 current_cell_schedules = set(grid[i][j].schedules)
462 current_cell_emissions = set([x.emission for x in current_cell_schedules])
464 while True and current_cell_schedules:
465 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
466 if not same_cell_below:
469 same_cell_below = same_cell_below[0]
470 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
472 if current_cell_emissions.issubset(same_cell_below_emissions):
473 # this handles case A (see comment above)
474 for schedule in current_cell_schedules:
475 if schedule in same_cell_below.schedules:
476 same_cell_below.schedules.remove(schedule)
477 elif same_cell_below_emissions and \
478 current_cell_emissions.issuperset(same_cell_below_emissions):
479 # this handles case B (see comment above)
480 # we set the cell time label to the longest
482 grid[i][j].time_label = same_cell_below.time_label
483 # then we sort emissions so the longest are
485 grid[i][j].schedules.sort(
486 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
487 # then we add individual time labels to the
489 for schedule in current_cell_schedules:
490 if schedule not in same_cell_below.schedules:
491 end_time = schedule.datetime + timedelta(
492 minutes=schedule.get_duration())
493 schedule.time_label = '%02d:%02d-%02d:%02d' % (
494 schedule.datetime.hour,
495 schedule.datetime.minute,
499 grid[i+cursor].remove(same_cell_below)
500 elif same_cell_below_emissions and \
501 current_cell_emissions.intersection(same_cell_below_emissions):
502 same_cell_below.schedules = [x for x in
503 same_cell_below.schedules if
505 current_cell_emissions or
506 x.get_duration() < 30]
516 context['grid'] = grid
517 context['times'] = times
518 context['categories'] = Category.objects.all()
519 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
520 'Vendredi', 'Samedi', 'Dimanche']
524 grid = Grid.as_view()
527 class Home(TemplateView):
528 template_name = 'home.html'
530 def get_context_data(self, **kwargs):
531 context = super(Home, self).get_context_data(**kwargs)
532 context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
533 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
534 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
536 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
537 podcastable=True, fragment=False) \
538 .select_related().extra(select={
539 'first_diffusion': 'emissions_diffusion.datetime', },
540 select_params=(False, True),
541 where=['''datetime = (SELECT MIN(datetime)
542 FROM emissions_diffusion
543 WHERE episode_id = emissions_episode.id)'''],
544 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
546 context['newsletter_form'] = SubscribeForm()
547 context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
551 home = Home.as_view()
553 class NewsItemView(DetailView):
555 def get_context_data(self, **kwargs):
556 context = super(NewsItemView, self).get_context_data(**kwargs)
557 context['categories'] = NewsCategory.objects.all()
558 context['news'] = NewsItem.objects.all().order_by('-date')
559 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
561 newsitemview = NewsItemView.as_view()
563 class News(TemplateView):
564 template_name = 'news.html'
565 def get_context_data(self, **kwargs):
566 context = super(News, self).get_context_data(**kwargs)
567 context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
568 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
571 news = News.as_view()
574 class Agenda(TemplateView):
575 template_name = 'agenda.html'
576 def get_context_data(self, **kwargs):
577 context = super(Agenda, self).get_context_data(**kwargs)
578 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
579 event_date__gte=date.today()).order_by('date')[:20]
580 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
581 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
584 agenda = Agenda.as_view()
587 class AgendaByMonth(MonthArchiveView):
588 template_name = 'agenda.html'
589 queryset = NewsItem.objects.filter(event_date__isnull=False)
591 date_field = 'event_date'
594 def get_context_data(self, **kwargs):
595 context = super(AgendaByMonth, self).get_context_data(**kwargs)
596 context['agenda'] = context['object_list']
597 context['news'] = NewsItem.objects.all().order_by('-date')
600 agenda_by_month = AgendaByMonth.as_view()
603 class Emissions(TemplateView):
604 template_name = 'emissions.html'
606 def get_context_data(self, **kwargs):
607 context = super(Emissions, self).get_context_data(**kwargs)
608 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
609 context['categories'] = Category.objects.all()
612 emissions = Emissions.as_view()
614 class EmissionsArchives(TemplateView):
615 template_name = 'emissions/archives.html'
617 def get_context_data(self, **kwargs):
618 context = super(EmissionsArchives, self).get_context_data(**kwargs)
619 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
620 context['categories'] = Category.objects.all()
622 emissionsArchives = EmissionsArchives.as_view()
625 class Listen(TemplateView):
626 template_name = 'listen.html'
628 def get_context_data(self, **kwargs):
629 context = super(Listen, self).get_context_data(**kwargs)
630 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
631 podcastable=True, got_focus__isnull=False) \
632 .select_related().extra(select={
633 'first_diffusion': 'emissions_diffusion.datetime', },
634 select_params=(False, True),
635 where=['''datetime = (SELECT MIN(datetime)
636 FROM emissions_diffusion
637 WHERE episode_id = emissions_episode.id)'''],
638 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
639 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
641 .select_related().extra(select={
642 'first_diffusion': 'emissions_diffusion.datetime', },
643 select_params=(False, True),
644 where=['''datetime = (SELECT MIN(datetime)
645 FROM emissions_diffusion
646 WHERE episode_id = emissions_episode.id)'''],
647 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
652 listen = Listen.as_view()
654 @cache_control(max_age=15)
658 if date.today() < date(2018, 7, 30):
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']
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 '%s - Podcasts' % 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()