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 context['all_episodes'] = \
82 episodes_queryset.extra(select={
83 'first_diffusion': 'emissions_diffusion.datetime',
85 select_params=(False, True),
86 where=['''datetime = (SELECT MIN(datetime)
87 FROM emissions_diffusion
88 WHERE episode_id = emissions_episode.id
90 tables=['emissions_diffusion'],
91 ).order_by('first_diffusion')
93 # get all related soundfiles in a single query
95 if episode_ids is not None:
96 for episode_id in episode_ids:
97 soundfiles[episode_id] = None
99 for episode in Episode.objects.filter(emission=emission):
100 soundfiles[episode.id] = None
102 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
103 fragment=False, episode__emission=emission):
104 soundfiles[soundfile.episode_id] = soundfile
106 Episode.set_prefetched_soundfiles(soundfiles)
108 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
113 class EmissionDetailView(DetailView, EmissionMixin):
116 def get_context_data(self, **kwargs):
117 context = super(EmissionDetailView, self).get_context_data(**kwargs)
118 context['schedules'] = Schedule.objects.select_related().filter(
119 emission=self.object).order_by('rerun', 'datetime')
120 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
122 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
123 except Nonstop.DoesNotExist:
127 dates = [today - timedelta(days=x) for x in range(7)]
128 if datetime.now().time() < nonstop_object.start:
130 context['nonstop'] = nonstop_object
131 context['nonstop_dates'] = dates
132 context.update(self.get_emission_context(self.object))
134 emission = EmissionDetailView.as_view()
136 class EpisodeDetailView(DetailView, EmissionMixin):
139 def get_context_data(self, **kwargs):
140 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
141 context['diffusions'] = Diffusion.objects.select_related().filter(
142 episode=self.object.id).order_by('datetime')
144 context['emission'] = context['episode'].emission
145 except Emission.DoesNotExist:
147 if self.kwargs.get('emission_slug') != context['emission'].slug:
149 context.update(self.get_emission_context(context['emission']))
150 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
152 episode = EpisodeDetailView.as_view()
155 class NonstopPlaylistView(TemplateView):
156 template_name = 'nonstop_playlist.html'
158 def get_context_data(self, **kwargs):
159 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
161 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
162 except Emission.DoesNotExist:
164 context['date'] = date(int(kwargs.get('year')),
165 int(kwargs.get('month')), int(kwargs.get('day')))
166 context['future'] = (context['date'] >= date.today())
168 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
170 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
171 nonstop_object.start.hour, nonstop_object.start.minute)
173 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
174 nonstop_object.end.hour, nonstop_object.end.minute)
176 end = end + timedelta(days=1)
177 context['tracks'] = SomaLogLine.objects.filter(
178 play_timestamp__gte=start,
179 play_timestamp__lte=end,
180 on_air=True).select_related()
183 nonstop_playlist = NonstopPlaylistView.as_view()
185 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
187 template_name = 'emissions/episodes.html'
189 def get_context_data(self, **kwargs):
190 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
191 context['schedules'] = Schedule.objects.select_related().filter(
192 emission=self.object).order_by('rerun', 'datetime')
194 context['search_query'] = self.request.GET.get('q')
195 if context['search_query']:
197 sqs = SearchQuerySet().models(Episode).filter(
198 emission_slug_exact=self.object.slug, text=context['search_query'])
199 episode_ids = [x.pk for x in sqs]
203 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
205 emissionEpisodes = EmissionEpisodesDetailView.as_view()
208 class SoundFileEmbedView(DetailView):
210 template_name = 'soundfiles/embed.html'
212 def get_context_data(self, **kwargs):
213 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
214 if self.kwargs.get('episode_slug') != self.object.episode.slug:
216 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
218 context['episode'] = self.object.episode
220 soundfile_embed = SoundFileEmbedView.as_view()
223 class SoundFileDialogEmbedView(DetailView):
225 template_name = 'soundfiles/dialog-embed.html'
227 def get_context_data(self, **kwargs):
228 context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
229 if self.kwargs.get('episode_slug') != self.object.episode.slug:
231 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
233 context['episode'] = self.object.episode
235 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
239 class ProgramView(TemplateView):
240 template_name = 'program.html'
242 def get_context_data(self, year=None, week=None, **kwargs):
243 context = super(ProgramView, self).get_context_data(**kwargs)
245 context['weekday'] = datetime.today().weekday()
247 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
248 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
249 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
250 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
254 program = ProgramView.as_view()
262 def __init__(self, i, j):
267 def add_schedule(self, schedule):
268 end_time = schedule.datetime + timedelta(
269 minutes=schedule.get_duration())
270 self.time_label = '%02d:%02d-%02d:%02d' % (
271 schedule.datetime.hour,
272 schedule.datetime.minute,
275 self.schedules.append(schedule)
277 def __unicode__(self):
279 return ', '.join([x.emission.title for x in self.schedules])
283 def __eq__(self, other):
284 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
287 class Grid(TemplateView):
288 template_name = 'grid.html'
290 def get_context_data(self, **kwargs):
291 context = super(Grid, self).get_context_data(**kwargs)
293 nb_lines = 2 * 24 # the cells are half hours
296 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
297 # start grid after the night programs
298 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
301 for nonstop in Nonstop.objects.all():
302 if nonstop.start == nonstop.end:
304 if nonstop.start < nonstop.end:
305 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
306 nonstop.end.hour + nonstop.end.minute/60.,
307 nonstop.title, nonstop.slug])
310 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
312 nonstop.title, nonstop.slug])
314 nonstop.end.hour + nonstop.end.minute/60.,
315 nonstop.title, nonstop.slug])
318 for i in range(nb_lines):
321 grid[-1].append(TimeCell(i, j))
323 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
324 for time_cell in grid[-1]:
325 time_cell.nonstop = nonstop[2]
326 time_cell.nonstop_slug = nonstop[3]
328 # the one ending at 5am will be cut down, so we inscribe
329 # its duration manually
330 time_cell.time_label = '%02d:00-%02d:00' % (
331 nonstop[0], nonstop[1])
333 for schedule in Schedule.objects.prefetch_related(
334 'emission__categories').select_related().order_by('datetime'):
335 row_start = schedule.datetime.hour * 2 + \
336 int(math.ceil(schedule.datetime.minute / 30))
337 day_no = schedule.get_weekday()
339 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
340 if grid[(row_start+step)%nb_lines][day_no] is None:
341 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
342 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
344 # start grid after the night programs
345 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
347 # look for the case where the same emission has different schedules for
348 # the same time cell, for example if it lasts one hour the first week,
349 # and two hours the third week.
350 for i in range(nb_lines):
351 grid[i] = [x for x in grid[i] if x is not None]
352 for j, cell in enumerate(grid[i]):
353 if grid[i][j] is None:
355 if len(grid[i][j].schedules) > 1:
356 time_cell_emissions = {}
357 for schedule in grid[i][j].schedules:
358 if not schedule.emission.id in time_cell_emissions:
359 time_cell_emissions[schedule.emission.id] = []
360 time_cell_emissions[schedule.emission.id].append(schedule)
361 for schedule_list in time_cell_emissions.values():
362 if len(schedule_list) == 1:
364 # here it is, same cell, same emission, several
366 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
368 schedule = schedule_list[0]
369 end_time = schedule.datetime + timedelta(
370 minutes=schedule.get_duration())
371 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
372 schedule.datetime.hour,
373 schedule.datetime.minute,
377 for schedule in schedule_list[1:]:
378 grid[i][j].schedules.remove(schedule)
379 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
380 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
381 end_time.hour, end_time.minute, schedule.weeks_string)
385 # 1st thing is to merge cells on the same line, this will mostly catch
386 # consecutive nonstop cells
387 for i in range(nb_lines):
388 for j, cell in enumerate(grid[i]):
389 if grid[i][j] is None:
393 # if the cells are identical, they are removed from the
394 # grid, and current cell width is increased
395 while grid[i][j+t] == cell:
402 # once we're done we remove empty cells
403 grid[i] = [x for x in grid[i] if x is not None]
405 # 2nd thing is to merge cells vertically, this is emissions that last
406 # for more than 30 minutes
407 for i in range(nb_lines):
408 grid[i] = [x for x in grid[i] if x is not None]
409 for j, cell in enumerate(grid[i]):
410 if grid[i][j] is None:
415 # we look if the next time cell has the same emissions
416 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
417 if x == cell and x.y == cell.y and x.w == cell.w]
419 # if the cell was identical, we remove it and
420 # increase current cell height
421 bj, same_cell_below = same_cell_below[0]
422 del grid[i+cell.h][bj]
425 # if the cell is different, we have a closer look
426 # to it, so we can remove emissions that will
427 # already be mentioned in the current cell.
430 # - 7am30, seuls contre tout, 1h30
431 # - 8am, du pied gauche & la voix de la rue, 1h
432 # should produce: (this is case A)
434 # | seuls contre tout |
435 # |---------------------|
438 # | la voix de la rue |
440 # On the other hand, if all three emissions started
441 # at 7am30, we want: (this is case B)
443 # | seuls contre tout |
445 # | la voix de la rue |
446 # that is we merge all of them, ignoring the fact
447 # that the other emissions will stop at 8am30
448 current_cell_schedules = set(grid[i][j].schedules)
449 current_cell_emissions = set([x.emission for x in current_cell_schedules])
451 while True and current_cell_schedules:
452 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
453 if not same_cell_below:
456 same_cell_below = same_cell_below[0]
457 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
459 if current_cell_emissions.issubset(same_cell_below_emissions):
460 # this handles case A (see comment above)
461 for schedule in current_cell_schedules:
462 if schedule in same_cell_below.schedules:
463 same_cell_below.schedules.remove(schedule)
464 elif same_cell_below_emissions and \
465 current_cell_emissions.issuperset(same_cell_below_emissions):
466 # this handles case B (see comment above)
467 # we set the cell time label to the longest
469 grid[i][j].time_label = same_cell_below.time_label
470 # then we sort emissions so the longest are
472 grid[i][j].schedules.sort(
473 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
474 # then we add individual time labels to the
476 for schedule in current_cell_schedules:
477 if schedule not in same_cell_below.schedules:
478 end_time = schedule.datetime + timedelta(
479 minutes=schedule.get_duration())
480 schedule.time_label = '%02d:%02d-%02d:%02d' % (
481 schedule.datetime.hour,
482 schedule.datetime.minute,
486 grid[i+cursor].remove(same_cell_below)
487 elif same_cell_below_emissions and \
488 current_cell_emissions.intersection(same_cell_below_emissions):
489 same_cell_below.schedules = [x for x in
490 same_cell_below.schedules if
492 current_cell_emissions or
493 x.get_duration() < 30]
503 context['grid'] = grid
504 context['times'] = times
505 context['categories'] = Category.objects.all()
506 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
507 'Vendredi', 'Samedi', 'Dimanche']
511 grid = Grid.as_view()
514 class Home(TemplateView):
515 template_name = 'home.html'
517 def get_context_data(self, **kwargs):
518 context = super(Home, self).get_context_data(**kwargs)
519 context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
520 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
521 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
523 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
524 podcastable=True, fragment=False) \
525 .select_related().extra(select={
526 'first_diffusion': 'emissions_diffusion.datetime', },
527 select_params=(False, True),
528 where=['''datetime = (SELECT MIN(datetime)
529 FROM emissions_diffusion
530 WHERE episode_id = emissions_episode.id)'''],
531 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
533 context['newsletter_form'] = SubscribeForm()
534 context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
538 home = Home.as_view()
540 class NewsItemView(DetailView):
542 def get_context_data(self, **kwargs):
543 context = super(NewsItemView, self).get_context_data(**kwargs)
544 context['categories'] = NewsCategory.objects.all()
545 context['news'] = NewsItem.objects.all().order_by('-date')
546 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
548 newsitemview = NewsItemView.as_view()
550 class News(TemplateView):
551 template_name = 'news.html'
552 def get_context_data(self, **kwargs):
553 context = super(News, self).get_context_data(**kwargs)
554 context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
555 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
558 news = News.as_view()
561 class Agenda(TemplateView):
562 template_name = 'agenda.html'
563 def get_context_data(self, **kwargs):
564 context = super(Agenda, self).get_context_data(**kwargs)
565 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
566 event_date__gte=date.today()).order_by('date')[:20]
567 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
568 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
571 agenda = Agenda.as_view()
574 class AgendaByMonth(MonthArchiveView):
575 template_name = 'agenda.html'
576 queryset = NewsItem.objects.filter(event_date__isnull=False)
578 date_field = 'event_date'
581 def get_context_data(self, **kwargs):
582 context = super(AgendaByMonth, self).get_context_data(**kwargs)
583 context['agenda'] = context['object_list']
584 context['news'] = NewsItem.objects.all().order_by('-date')
587 agenda_by_month = AgendaByMonth.as_view()
590 class Emissions(TemplateView):
591 template_name = 'emissions.html'
593 def get_context_data(self, **kwargs):
594 context = super(Emissions, self).get_context_data(**kwargs)
595 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
596 context['categories'] = Category.objects.all()
599 emissions = Emissions.as_view()
601 class EmissionsArchives(TemplateView):
602 template_name = 'emissions/archives.html'
604 def get_context_data(self, **kwargs):
605 context = super(EmissionsArchives, self).get_context_data(**kwargs)
606 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
607 context['categories'] = Category.objects.all()
609 emissionsArchives = EmissionsArchives.as_view()
612 class Listen(TemplateView):
613 template_name = 'listen.html'
615 def get_context_data(self, **kwargs):
616 context = super(Listen, self).get_context_data(**kwargs)
617 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
618 podcastable=True, got_focus__isnull=False) \
619 .select_related().extra(select={
620 'first_diffusion': 'emissions_diffusion.datetime', },
621 select_params=(False, True),
622 where=['''datetime = (SELECT MIN(datetime)
623 FROM emissions_diffusion
624 WHERE episode_id = emissions_episode.id)'''],
625 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
626 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
628 .select_related().extra(select={
629 'first_diffusion': 'emissions_diffusion.datetime', },
630 select_params=(False, True),
631 where=['''datetime = (SELECT MIN(datetime)
632 FROM emissions_diffusion
633 WHERE episode_id = emissions_episode.id)'''],
634 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
639 listen = Listen.as_view()
641 @cache_control(max_age=15)
645 if date.today() < date(2017, 8, 3):
646 return {'emission': {'title': 'À partir du 3 août 17h', 'url': '/'}}
647 if date.today() > date(2017, 8, 6):
648 return {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}
652 'title': d['episode'].title,
653 'url': d['episode'].get_absolute_url()
655 if d.get('emission'):
657 if d['emission'].chat_open:
658 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
660 'title': d['emission'].title,
661 'url': d['emission'].get_absolute_url(),
666 'title': d['nonstop'].title,
668 playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
669 if os.path.exists(os.path.join(playing_txt)):
670 d['track_title'] = open(playing_txt).read().strip()
671 if d.get('current_slot'):
672 del d['current_slot']
676 class NewsItemDetailView(DetailView):
679 newsitem = NewsItemDetailView.as_view()
681 class RssCustomPodcastsFeed(Rss201rev2Feed):
682 def add_root_elements(self, handler):
683 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
684 emission = self.feed.get('emission')
685 if emission and emission.image and emission.image.url:
686 image_url = emission.image.url
688 image_url = '/static/img/logo-panik-500.png'
689 image_url = urlparse.urljoin(self.feed['link'], image_url)
690 handler.startElement('image', {})
692 handler.addQuickElement('title', emission.title)
694 handler.addQuickElement('title', 'Radio Esperanzah!')
695 handler.addQuickElement('url', image_url)
696 handler.endElement('image')
697 handler.addQuickElement('itunes:image', None, {'href': image_url})
698 if emission and emission.subtitle:
699 handler.addQuickElement('itunes:subtitle', emission.subtitle)
701 def root_attributes(self):
702 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
703 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
704 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
707 def add_item_elements(self, handler, item):
708 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
710 for tag in item.get('tags') or []:
711 handler.addQuickElement('dc:subject', tag)
712 if tag == 'explicit':
715 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
716 handler.addQuickElement('itunes:explicit', explicit)
717 episode = item.get('episode')
718 if episode and episode.image and episode.image.url:
719 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
720 handler.addQuickElement('itunes:image', None, {'href': image_url})
721 soundfile = item.get('soundfile')
722 if soundfile.duration:
723 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
724 soundfile.duration / 3600,
725 soundfile.duration % 3600 / 60,
726 soundfile.duration % 60))
729 class PodcastsFeed(Feed):
730 title = 'Radio Esperanzah! - Podcasts'
732 description_template = 'feed/soundfile.html'
733 feed_type = RssCustomPodcastsFeed
736 return SoundFile.objects.select_related().filter(
737 podcastable=True).order_by('-creation_timestamp')[:20]
739 def item_title(self, item):
741 return '%s - %s' % (item.title, item.episode.title)
742 return '%s - %s' % (item.episode.emission.title, item.episode.title)
744 def item_link(self, item):
745 return item.episode.get_absolute_url()
747 def item_enclosure_url(self, item):
748 current_site = Site.objects.get(id=settings.SITE_ID)
749 return add_domain(current_site.domain, item.get_format_url('mp3'))
751 def item_enclosure_length(self, item):
752 sound_path = item.get_format_path('mp3')
754 return os.stat(sound_path)[stat.ST_SIZE]
758 def item_enclosure_mime_type(self, item):
761 def item_pubdate(self, item):
762 return item.creation_timestamp
764 def item_extra_kwargs(self, item):
765 return {'tags': [x.name for x in item.episode.tags.all()],
767 'episode': item.episode}
769 podcasts_feed = PodcastsFeed()
772 class RssNewsFeed(Feed):
773 title = 'Radio Esperanzah!'
775 description_template = 'feed/newsitem.html'
778 return NewsItem.objects.order_by('-date')[:20]
780 rss_news_feed = RssNewsFeed()
782 class Atom1FeedWithBaseXml(Atom1Feed):
783 def root_attributes(self):
784 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
785 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
786 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
787 return root_attributes
789 class AtomNewsFeed(RssNewsFeed):
790 feed_type = Atom1FeedWithBaseXml
792 atom_news_feed = AtomNewsFeed()
795 class EmissionPodcastsFeed(PodcastsFeed):
796 description_template = 'feed/soundfile.html'
797 feed_type = RssCustomPodcastsFeed
799 def __call__(self, request, *args, **kwargs):
800 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
801 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
805 return '%s - Podcasts' % self.emission.title
809 return reverse('emission-view', kwargs={'slug': self.emission.slug})
811 def feed_extra_kwargs(self, obj):
812 return {'emission': self.emission}
815 return SoundFile.objects.select_related().filter(
817 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
819 emission_podcasts_feed = EmissionPodcastsFeed()
822 class Party(TemplateView):
823 template_name = 'party.html'
825 def get_context_data(self, **kwargs):
826 context = super(Party, self).get_context_data(**kwargs)
827 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
830 focus.newsitem = NewsItem.objects.exclude(
831 image__isnull=True).exclude(image__exact='').order_by('?')[0]
832 elif t == 'emission':
833 focus.emission = Emission.objects.exclude(
834 image__isnull=True).exclude(image__exact='').order_by('?')[0]
836 focus.episode = Episode.objects.exclude(
837 image__isnull=True).exclude(image__exact='').order_by('?')[0]
838 elif t == 'soundfile':
839 focus.soundfile = SoundFile.objects.exclude(
840 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
842 context['focus'] = focus
846 party = Party.as_view()
850 class Chat(DetailView, EmissionMixin):
852 template_name = 'chat.html'
854 chat = cache_control(max_age=15)(Chat.as_view())