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_context_data(self, **kwargs):
146 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
147 context['diffusions'] = Diffusion.objects.select_related().filter(
148 episode=self.object.id).order_by('datetime')
150 context['emission'] = context['episode'].emission
151 except Emission.DoesNotExist:
153 if self.kwargs.get('emission_slug') != context['emission'].slug:
155 context.update(self.get_emission_context(context['emission']))
156 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
158 episode = EpisodeDetailView.as_view()
161 class NonstopPlaylistView(TemplateView):
162 template_name = 'nonstop_playlist.html'
164 def get_context_data(self, **kwargs):
165 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
167 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
168 except Emission.DoesNotExist:
170 context['date'] = date(int(kwargs.get('year')),
171 int(kwargs.get('month')), int(kwargs.get('day')))
172 context['future'] = (context['date'] >= date.today())
174 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
176 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
177 nonstop_object.start.hour, nonstop_object.start.minute)
179 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
180 nonstop_object.end.hour, nonstop_object.end.minute)
182 end = end + timedelta(days=1)
183 context['tracks'] = SomaLogLine.objects.filter(
184 play_timestamp__gte=start,
185 play_timestamp__lte=end,
186 on_air=True).select_related()
189 nonstop_playlist = NonstopPlaylistView.as_view()
191 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
193 template_name = 'emissions/episodes.html'
195 def get_context_data(self, **kwargs):
196 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
197 context['schedules'] = Schedule.objects.select_related().filter(
198 emission=self.object).order_by('rerun', 'datetime')
200 context['search_query'] = self.request.GET.get('q')
201 if context['search_query']:
203 sqs = SearchQuerySet().models(Episode).filter(
204 emission_slug_exact=self.object.slug, text=context['search_query'])
205 episode_ids = [x.pk for x in sqs]
209 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
211 emissionEpisodes = EmissionEpisodesDetailView.as_view()
214 class SoundFileEmbedView(DetailView):
216 template_name = 'soundfiles/embed.html'
218 def get_context_data(self, **kwargs):
219 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
220 if self.kwargs.get('episode_slug') != self.object.episode.slug:
222 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
224 context['episode'] = self.object.episode
226 soundfile_embed = SoundFileEmbedView.as_view()
229 class SoundFileDialogEmbedView(DetailView):
231 template_name = 'soundfiles/dialog-embed.html'
233 def get_context_data(self, **kwargs):
234 context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
235 if self.kwargs.get('episode_slug') != self.object.episode.slug:
237 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
239 context['episode'] = self.object.episode
241 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
245 class ProgramView(TemplateView):
246 template_name = 'program.html'
248 def get_context_data(self, year=None, week=None, **kwargs):
249 context = super(ProgramView, self).get_context_data(**kwargs)
251 context['weekday'] = datetime.today().weekday()
253 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
254 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
255 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
256 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
260 program = ProgramView.as_view()
268 def __init__(self, i, j):
273 def add_schedule(self, schedule):
274 end_time = schedule.datetime + timedelta(
275 minutes=schedule.get_duration())
276 self.time_label = '%02d:%02d-%02d:%02d' % (
277 schedule.datetime.hour,
278 schedule.datetime.minute,
281 self.schedules.append(schedule)
283 def __unicode__(self):
285 return ', '.join([x.emission.title for x in self.schedules])
289 def __eq__(self, other):
290 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
293 class Grid(TemplateView):
294 template_name = 'grid.html'
296 def get_context_data(self, **kwargs):
297 context = super(Grid, self).get_context_data(**kwargs)
299 nb_lines = 2 * 24 # the cells are half hours
302 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
303 # start grid after the night programs
304 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
307 for nonstop in Nonstop.objects.all():
308 if nonstop.start == nonstop.end:
310 if nonstop.start < nonstop.end:
311 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
312 nonstop.end.hour + nonstop.end.minute/60.,
313 nonstop.title, nonstop.slug])
316 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
318 nonstop.title, nonstop.slug])
320 nonstop.end.hour + nonstop.end.minute/60.,
321 nonstop.title, nonstop.slug])
324 for i in range(nb_lines):
327 grid[-1].append(TimeCell(i, j))
329 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
330 for time_cell in grid[-1]:
331 time_cell.nonstop = nonstop[2]
332 time_cell.nonstop_slug = nonstop[3]
334 # the one ending at 5am will be cut down, so we inscribe
335 # its duration manually
336 time_cell.time_label = '%02d:00-%02d:00' % (
337 nonstop[0], nonstop[1])
339 for schedule in Schedule.objects.prefetch_related(
340 'emission__categories').select_related().order_by('datetime'):
341 row_start = schedule.datetime.hour * 2 + \
342 int(math.ceil(schedule.datetime.minute / 30))
343 day_no = schedule.get_weekday()
345 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
346 if grid[(row_start+step)%nb_lines][day_no] is None:
347 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
348 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
350 # start grid after the night programs
351 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
353 # look for the case where the same emission has different schedules for
354 # the same time cell, for example if it lasts one hour the first week,
355 # and two hours the third week.
356 for i in range(nb_lines):
357 grid[i] = [x for x in grid[i] if x is not None]
358 for j, cell in enumerate(grid[i]):
359 if grid[i][j] is None:
361 if len(grid[i][j].schedules) > 1:
362 time_cell_emissions = {}
363 for schedule in grid[i][j].schedules:
364 if not schedule.emission.id in time_cell_emissions:
365 time_cell_emissions[schedule.emission.id] = []
366 time_cell_emissions[schedule.emission.id].append(schedule)
367 for schedule_list in time_cell_emissions.values():
368 if len(schedule_list) == 1:
370 # here it is, same cell, same emission, several
372 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
374 schedule = schedule_list[0]
375 end_time = schedule.datetime + timedelta(
376 minutes=schedule.get_duration())
377 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
378 schedule.datetime.hour,
379 schedule.datetime.minute,
383 for schedule in schedule_list[1:]:
384 grid[i][j].schedules.remove(schedule)
385 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
386 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
387 end_time.hour, end_time.minute, schedule.weeks_string)
391 # 1st thing is to merge cells on the same line, this will mostly catch
392 # consecutive nonstop cells
393 for i in range(nb_lines):
394 for j, cell in enumerate(grid[i]):
395 if grid[i][j] is None:
399 # if the cells are identical, they are removed from the
400 # grid, and current cell width is increased
401 while grid[i][j+t] == cell:
408 # once we're done we remove empty cells
409 grid[i] = [x for x in grid[i] if x is not None]
411 # 2nd thing is to merge cells vertically, this is emissions that last
412 # for more than 30 minutes
413 for i in range(nb_lines):
414 grid[i] = [x for x in grid[i] if x is not None]
415 for j, cell in enumerate(grid[i]):
416 if grid[i][j] is None:
421 # we look if the next time cell has the same emissions
422 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
423 if x == cell and x.y == cell.y and x.w == cell.w]
425 # if the cell was identical, we remove it and
426 # increase current cell height
427 bj, same_cell_below = same_cell_below[0]
428 del grid[i+cell.h][bj]
431 # if the cell is different, we have a closer look
432 # to it, so we can remove emissions that will
433 # already be mentioned in the current cell.
436 # - 7am30, seuls contre tout, 1h30
437 # - 8am, du pied gauche & la voix de la rue, 1h
438 # should produce: (this is case A)
440 # | seuls contre tout |
441 # |---------------------|
444 # | la voix de la rue |
446 # On the other hand, if all three emissions started
447 # at 7am30, we want: (this is case B)
449 # | seuls contre tout |
451 # | la voix de la rue |
452 # that is we merge all of them, ignoring the fact
453 # that the other emissions will stop at 8am30
454 current_cell_schedules = set(grid[i][j].schedules)
455 current_cell_emissions = set([x.emission for x in current_cell_schedules])
457 while True and current_cell_schedules:
458 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
459 if not same_cell_below:
462 same_cell_below = same_cell_below[0]
463 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
465 if current_cell_emissions.issubset(same_cell_below_emissions):
466 # this handles case A (see comment above)
467 for schedule in current_cell_schedules:
468 if schedule in same_cell_below.schedules:
469 same_cell_below.schedules.remove(schedule)
470 elif same_cell_below_emissions and \
471 current_cell_emissions.issuperset(same_cell_below_emissions):
472 # this handles case B (see comment above)
473 # we set the cell time label to the longest
475 grid[i][j].time_label = same_cell_below.time_label
476 # then we sort emissions so the longest are
478 grid[i][j].schedules.sort(
479 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
480 # then we add individual time labels to the
482 for schedule in current_cell_schedules:
483 if schedule not in same_cell_below.schedules:
484 end_time = schedule.datetime + timedelta(
485 minutes=schedule.get_duration())
486 schedule.time_label = '%02d:%02d-%02d:%02d' % (
487 schedule.datetime.hour,
488 schedule.datetime.minute,
492 grid[i+cursor].remove(same_cell_below)
493 elif same_cell_below_emissions and \
494 current_cell_emissions.intersection(same_cell_below_emissions):
495 same_cell_below.schedules = [x for x in
496 same_cell_below.schedules if
498 current_cell_emissions or
499 x.get_duration() < 30]
509 context['grid'] = grid
510 context['times'] = times
511 context['categories'] = Category.objects.all()
512 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
513 'Vendredi', 'Samedi', 'Dimanche']
517 grid = Grid.as_view()
520 class Home(TemplateView):
521 template_name = 'home.html'
523 def get_context_data(self, **kwargs):
524 context = super(Home, self).get_context_data(**kwargs)
525 context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
526 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
527 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
529 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
530 podcastable=True, fragment=False) \
531 .select_related().extra(select={
532 'first_diffusion': 'emissions_diffusion.datetime', },
533 select_params=(False, True),
534 where=['''datetime = (SELECT MIN(datetime)
535 FROM emissions_diffusion
536 WHERE episode_id = emissions_episode.id)'''],
537 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
539 context['newsletter_form'] = SubscribeForm()
540 context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
544 home = Home.as_view()
546 class NewsItemView(DetailView):
548 def get_context_data(self, **kwargs):
549 context = super(NewsItemView, self).get_context_data(**kwargs)
550 context['categories'] = NewsCategory.objects.all()
551 context['news'] = NewsItem.objects.all().order_by('-date')
552 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
554 newsitemview = NewsItemView.as_view()
556 class News(TemplateView):
557 template_name = 'news.html'
558 def get_context_data(self, **kwargs):
559 context = super(News, self).get_context_data(**kwargs)
560 context['focus'] = NewsItem.objects.exclude(date__gt=date.today()).filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
561 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
564 news = News.as_view()
567 class Agenda(TemplateView):
568 template_name = 'agenda.html'
569 def get_context_data(self, **kwargs):
570 context = super(Agenda, self).get_context_data(**kwargs)
571 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
572 event_date__gte=date.today()).order_by('date')[:20]
573 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
574 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
577 agenda = Agenda.as_view()
580 class AgendaByMonth(MonthArchiveView):
581 template_name = 'agenda.html'
582 queryset = NewsItem.objects.filter(event_date__isnull=False)
584 date_field = 'event_date'
587 def get_context_data(self, **kwargs):
588 context = super(AgendaByMonth, self).get_context_data(**kwargs)
589 context['agenda'] = context['object_list']
590 context['news'] = NewsItem.objects.all().order_by('-date')
593 agenda_by_month = AgendaByMonth.as_view()
596 class Emissions(TemplateView):
597 template_name = 'emissions.html'
599 def get_context_data(self, **kwargs):
600 context = super(Emissions, self).get_context_data(**kwargs)
601 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
602 context['categories'] = Category.objects.all()
605 emissions = Emissions.as_view()
607 class EmissionsArchives(TemplateView):
608 template_name = 'emissions/archives.html'
610 def get_context_data(self, **kwargs):
611 context = super(EmissionsArchives, self).get_context_data(**kwargs)
612 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
613 context['categories'] = Category.objects.all()
615 emissionsArchives = EmissionsArchives.as_view()
618 class Listen(TemplateView):
619 template_name = 'listen.html'
621 def get_context_data(self, **kwargs):
622 context = super(Listen, self).get_context_data(**kwargs)
623 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
624 podcastable=True, got_focus__isnull=False) \
625 .select_related().extra(select={
626 'first_diffusion': 'emissions_diffusion.datetime', },
627 select_params=(False, True),
628 where=['''datetime = (SELECT MIN(datetime)
629 FROM emissions_diffusion
630 WHERE episode_id = emissions_episode.id)'''],
631 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
632 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
634 .select_related().extra(select={
635 'first_diffusion': 'emissions_diffusion.datetime', },
636 select_params=(False, True),
637 where=['''datetime = (SELECT MIN(datetime)
638 FROM emissions_diffusion
639 WHERE episode_id = emissions_episode.id)'''],
640 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
645 listen = Listen.as_view()
647 @cache_control(max_age=15)
651 if date.today() < date(2018, 7, 30):
652 return {'emission': {'title': 'À partir du 31 juillet 18h', 'url': '/'}}
653 if date.today() > date(2018, 8, 5):
654 return {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}
658 'title': d['episode'].title,
659 'url': d['episode'].get_absolute_url()
661 if d.get('emission'):
663 if d['emission'].chat_open:
664 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
666 'title': d['emission'].title,
667 'url': d['emission'].get_absolute_url(),
672 'title': d['nonstop'].title,
674 playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
675 if os.path.exists(os.path.join(playing_txt)):
676 d['track_title'] = open(playing_txt).read().strip()
677 if d.get('current_slot'):
678 del d['current_slot']
682 class NewsItemDetailView(DetailView):
685 newsitem = NewsItemDetailView.as_view()
687 class RssCustomPodcastsFeed(Rss201rev2Feed):
688 def add_root_elements(self, handler):
689 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
690 emission = self.feed.get('emission')
691 if emission and emission.image and emission.image.url:
692 image_url = emission.image.url
694 image_url = '/static/img/logo-panik-500.png'
695 image_url = urlparse.urljoin(self.feed['link'], image_url)
696 handler.startElement('image', {})
698 handler.addQuickElement('title', emission.title)
700 handler.addQuickElement('title', 'Radio Esperanzah!')
701 handler.addQuickElement('url', image_url)
702 handler.endElement('image')
703 handler.addQuickElement('itunes:image', None, {'href': image_url})
704 if emission and emission.subtitle:
705 handler.addQuickElement('itunes:subtitle', emission.subtitle)
707 def root_attributes(self):
708 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
709 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
710 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
713 def add_item_elements(self, handler, item):
714 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
716 for tag in item.get('tags') or []:
717 handler.addQuickElement('dc:subject', tag)
718 if tag == 'explicit':
721 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
722 handler.addQuickElement('itunes:explicit', explicit)
723 episode = item.get('episode')
724 if episode and episode.image and episode.image.url:
725 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
726 handler.addQuickElement('itunes:image', None, {'href': image_url})
727 soundfile = item.get('soundfile')
728 if soundfile.duration:
729 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
730 soundfile.duration / 3600,
731 soundfile.duration % 3600 / 60,
732 soundfile.duration % 60))
735 class PodcastsFeed(Feed):
736 title = 'Radio Esperanzah! - Podcasts'
738 description_template = 'feed/soundfile.html'
739 feed_type = RssCustomPodcastsFeed
742 return SoundFile.objects.select_related().filter(
743 podcastable=True).order_by('-creation_timestamp')[:20]
745 def item_title(self, item):
747 return '%s - %s' % (item.title, item.episode.title)
748 return '%s - %s' % (item.episode.emission.title, item.episode.title)
750 def item_link(self, item):
751 return item.episode.get_absolute_url()
753 def item_enclosure_url(self, item):
754 current_site = Site.objects.get(id=settings.SITE_ID)
755 return add_domain(current_site.domain, item.get_format_url('mp3'))
757 def item_enclosure_length(self, item):
758 sound_path = item.get_format_path('mp3')
760 return os.stat(sound_path)[stat.ST_SIZE]
764 def item_enclosure_mime_type(self, item):
767 def item_pubdate(self, item):
768 return item.creation_timestamp
770 def item_extra_kwargs(self, item):
771 return {'tags': [x.name for x in item.episode.tags.all()],
773 'episode': item.episode}
775 podcasts_feed = PodcastsFeed()
778 class RssNewsFeed(Feed):
779 title = 'Radio Esperanzah!'
781 description_template = 'feed/newsitem.html'
784 return NewsItem.objects.order_by('-date')[:20]
786 rss_news_feed = RssNewsFeed()
788 class Atom1FeedWithBaseXml(Atom1Feed):
789 def root_attributes(self):
790 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
791 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
792 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
793 return root_attributes
795 class AtomNewsFeed(RssNewsFeed):
796 feed_type = Atom1FeedWithBaseXml
798 atom_news_feed = AtomNewsFeed()
801 class EmissionPodcastsFeed(PodcastsFeed):
802 description_template = 'feed/soundfile.html'
803 feed_type = RssCustomPodcastsFeed
805 def __call__(self, request, *args, **kwargs):
806 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
807 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
811 return '%s - Podcasts' % self.emission.title
815 return reverse('emission-view', kwargs={'slug': self.emission.slug})
817 def feed_extra_kwargs(self, obj):
818 return {'emission': self.emission}
821 return SoundFile.objects.select_related().filter(
823 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
825 emission_podcasts_feed = EmissionPodcastsFeed()
828 class Party(TemplateView):
829 template_name = 'party.html'
831 def get_context_data(self, **kwargs):
832 context = super(Party, self).get_context_data(**kwargs)
833 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
836 focus.newsitem = NewsItem.objects.exclude(
837 image__isnull=True).exclude(image__exact='').order_by('?')[0]
838 elif t == 'emission':
839 focus.emission = Emission.objects.exclude(
840 image__isnull=True).exclude(image__exact='').order_by('?')[0]
842 focus.episode = Episode.objects.exclude(
843 image__isnull=True).exclude(image__exact='').order_by('?')[0]
844 elif t == 'soundfile':
845 focus.soundfile = SoundFile.objects.exclude(
846 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
848 context['focus'] = focus
852 party = Party.as_view()
856 class Chat(DetailView, EmissionMixin):
858 template_name = 'chat.html'
860 chat = cache_control(max_age=15)(Chat.as_view())
864 class ArchivesView(TemplateView):
865 template_name = 'archives.html'
867 def get_context_data(self, **kwargs):
868 context = super(ArchivesView, self).get_context_data(**kwargs)
869 context['diffusions'] = Diffusion.objects.all().order_by('-datetime')
872 archives = ArchivesView.as_view()