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, JsonResponse
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
29 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
30 Schedule, Nonstop, NewsItem, NewsCategory, Focus
32 from emissions.utils import whatsonair, period_program
34 from newsletter.forms import SubscribeForm
35 from nonstop.utils import get_current_nonstop_track
36 from nonstop.models import SomaLogLine
38 from combo.data.models import Page
39 from panikombo.models import ItemTopik
45 def get_emission_context(self, emission, episode_ids=None):
48 # get all episodes, with an additional attribute to get the date of
49 # their first diffusion
50 episodes_queryset = Episode.objects.select_related()
51 if episode_ids is not None:
52 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
54 episodes_queryset = episodes_queryset.filter(emission=emission)
56 context['episodes'] = \
57 episodes_queryset.extra(select={
58 'first_diffusion': 'emissions_diffusion.datetime',
60 select_params=(False, True),
61 where=['''datetime = (SELECT MIN(datetime)
62 FROM emissions_diffusion
63 WHERE episode_id = emissions_episode.id
64 AND datetime <= CURRENT_TIMESTAMP)'''],
65 tables=['emissions_diffusion'],
66 ).order_by('-first_diffusion').distinct()
68 context['futurEpisodes'] = \
69 episodes_queryset.extra(select={
70 'first_diffusion': 'emissions_diffusion.datetime',
72 select_params=(False, True),
73 where=['''datetime = (SELECT MIN(datetime)
74 FROM emissions_diffusion
75 WHERE episode_id = emissions_episode.id
76 AND datetime > CURRENT_TIMESTAMP)'''],
77 tables=['emissions_diffusion'],
78 ).order_by('first_diffusion').distinct()
81 current_year = emission.creation_timestamp.replace(month=5, day=1)
83 current_year = datetime.now().replace(month=5, day=1).replace(year=2019)
85 context['all_episodes'] = episodes_queryset.filter(
86 creation_timestamp__gt=current_year
88 'first_diffusion': 'emissions_diffusion.datetime',
90 select_params=(False, True),
91 where=['''datetime = (SELECT MIN(datetime)
92 FROM emissions_diffusion
93 WHERE episode_id = emissions_episode.id
95 tables=['emissions_diffusion'],
96 ).order_by('first_diffusion').distinct()
98 # get all related soundfiles in a single query
100 if episode_ids is not None:
101 for episode_id in episode_ids:
102 soundfiles[episode_id] = None
104 for episode in Episode.objects.filter(emission=emission):
105 soundfiles[episode.id] = None
107 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
108 fragment=False, episode__emission=emission):
109 soundfiles[soundfile.episode_id] = soundfile
111 Episode.set_prefetched_soundfiles(soundfiles)
113 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
118 class EmissionDetailView(DetailView, EmissionMixin):
121 def get_context_data(self, **kwargs):
122 context = super(EmissionDetailView, self).get_context_data(**kwargs)
123 context['schedules'] = Schedule.objects.select_related().filter(
124 emission=self.object).order_by('rerun', 'datetime')
125 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
127 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
128 except Nonstop.DoesNotExist:
132 dates = [today - timedelta(days=x) for x in range(7)]
133 if datetime.now().time() < nonstop_object.start:
135 context['nonstop'] = nonstop_object
136 context['nonstop_dates'] = dates
137 context.update(self.get_emission_context(self.object))
139 emission = EmissionDetailView.as_view()
141 class EpisodeDetailView(DetailView, EmissionMixin):
144 def get_queryset(self, *args, **kwargs):
145 queryset = super(EpisodeDetailView, self).get_queryset(*args, **kwargs)
146 return queryset.filter(emission__slug=self.kwargs['emission_slug'])
148 def get_context_data(self, **kwargs):
149 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
150 context['diffusions'] = Diffusion.objects.select_related().filter(
151 episode=self.object.id).order_by('datetime')
153 context['emission'] = context['episode'].emission
154 except Emission.DoesNotExist:
156 if self.kwargs.get('emission_slug') != context['emission'].slug:
158 context.update(self.get_emission_context(context['emission']))
159 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
161 episode = EpisodeDetailView.as_view()
164 class NonstopPlaylistView(TemplateView):
165 template_name = 'nonstop_playlist.html'
167 def get_context_data(self, **kwargs):
168 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
170 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
171 except Emission.DoesNotExist:
173 context['date'] = date(int(kwargs.get('year')),
174 int(kwargs.get('month')), int(kwargs.get('day')))
175 context['future'] = (context['date'] >= date.today())
177 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
179 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
180 nonstop_object.start.hour, nonstop_object.start.minute)
182 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
183 nonstop_object.end.hour, nonstop_object.end.minute)
185 end = end + timedelta(days=1)
186 context['tracks'] = SomaLogLine.objects.filter(
187 play_timestamp__gte=start,
188 play_timestamp__lte=end,
189 on_air=True).select_related()
192 nonstop_playlist = NonstopPlaylistView.as_view()
194 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
196 template_name = 'emissions/episodes.html'
198 def get_context_data(self, **kwargs):
199 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
200 context['schedules'] = Schedule.objects.select_related().filter(
201 emission=self.object).order_by('rerun', 'datetime')
203 context['search_query'] = self.request.GET.get('q')
204 if context['search_query']:
206 sqs = SearchQuerySet().models(Episode).filter(
207 emission_slug_exact=self.object.slug, text=context['search_query'])
208 episode_ids = [x.pk for x in sqs]
212 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
214 emissionEpisodes = EmissionEpisodesDetailView.as_view()
217 class SoundFileEmbedView(DetailView):
219 template_name = 'soundfiles/embed.html'
221 def get_context_data(self, **kwargs):
222 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
223 if self.kwargs.get('episode_slug') != self.object.episode.slug:
225 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
227 context['episode'] = self.object.episode
229 soundfile_embed = SoundFileEmbedView.as_view()
232 class SoundFileDialogEmbedView(DetailView):
234 template_name = 'soundfiles/dialog-embed.html'
236 def get_context_data(self, **kwargs):
237 context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
238 if self.kwargs.get('episode_slug') != self.object.episode.slug:
240 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
242 context['episode'] = self.object.episode
244 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
248 class ProgramView(TemplateView):
249 template_name = 'program.html'
251 def get_context_data(self, year=None, week=None, **kwargs):
252 context = super(ProgramView, self).get_context_data(**kwargs)
254 context['weekday'] = datetime.today().weekday()
256 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
257 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
258 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
259 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
263 program = ProgramView.as_view()
271 def __init__(self, i, j):
276 def add_schedule(self, schedule):
277 end_time = schedule.datetime + timedelta(
278 minutes=schedule.get_duration())
279 self.time_label = '%02d:%02d-%02d:%02d' % (
280 schedule.datetime.hour,
281 schedule.datetime.minute,
284 self.schedules.append(schedule)
286 def __unicode__(self):
288 return ', '.join([x.emission.title for x in self.schedules])
292 def __eq__(self, other):
293 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
296 class Grid(TemplateView):
297 template_name = 'grid.html'
299 def get_context_data(self, **kwargs):
300 context = super(Grid, self).get_context_data(**kwargs)
302 nb_lines = 2 * 24 # the cells are half hours
305 Schedule.DAY_HOUR_START = 12
307 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
308 # start grid after the night programs
309 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
312 for nonstop in Nonstop.objects.all():
313 if nonstop.start == nonstop.end:
315 if nonstop.start < nonstop.end:
316 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
317 nonstop.end.hour + nonstop.end.minute/60.,
318 nonstop.title, nonstop.slug])
321 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
323 nonstop.title, nonstop.slug])
325 nonstop.end.hour + nonstop.end.minute/60.,
326 nonstop.title, nonstop.slug])
329 for i in range(nb_lines):
332 grid[-1].append(TimeCell(i, j))
335 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
338 for time_cell in grid[-1]:
339 time_cell.nonstop = nonstop[2]
340 time_cell.nonstop_slug = nonstop[3]
342 # the one ending at 5am will be cut down, so we inscribe
343 # its duration manually
344 time_cell.time_label = '%02d:00-%02d:00' % (
345 nonstop[0], nonstop[1])
347 for schedule in Schedule.objects.filter(emission__archived=False).prefetch_related(
348 'emission__categories').select_related().order_by('datetime'):
349 row_start = schedule.datetime.hour * 2 + \
350 int(math.ceil(schedule.datetime.minute / 30))
351 day_no = schedule.get_weekday()
353 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
354 if grid[(row_start+step)%nb_lines][day_no] is None:
355 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
356 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
358 # start grid after the night programs
359 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
361 # look for the case where the same emission has different schedules for
362 # the same time cell, for example if it lasts one hour the first week,
363 # and two hours the third week.
364 for i in range(nb_lines):
365 grid[i] = [x for x in grid[i] if x is not None]
366 for j, cell in enumerate(grid[i]):
367 if grid[i][j] is None:
369 if len(grid[i][j].schedules) > 1:
370 time_cell_emissions = {}
371 for schedule in grid[i][j].schedules:
372 if not schedule.emission.id in time_cell_emissions:
373 time_cell_emissions[schedule.emission.id] = []
374 time_cell_emissions[schedule.emission.id].append(schedule)
375 for schedule_list in time_cell_emissions.values():
376 if len(schedule_list) == 1:
378 # here it is, same cell, same emission, several
380 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
382 schedule = schedule_list[0]
383 end_time = schedule.datetime + timedelta(
384 minutes=schedule.get_duration())
385 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
386 schedule.datetime.hour,
387 schedule.datetime.minute,
391 for schedule in schedule_list[1:]:
392 grid[i][j].schedules.remove(schedule)
393 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
394 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
395 end_time.hour, end_time.minute, schedule.weeks_string)
399 # 1st thing is to merge cells on the same line, this will mostly catch
400 # consecutive nonstop cells
401 for i in range(nb_lines):
402 for j, cell in enumerate(grid[i]):
403 if grid[i][j] is None:
407 # if the cells are identical, they are removed from the
408 # grid, and current cell width is increased
409 while grid[i][j+t] == cell:
416 # once we're done we remove empty cells
417 grid[i] = [x for x in grid[i] if x is not None]
419 # 2nd thing is to merge cells vertically, this is emissions that last
420 # for more than 30 minutes
421 for i in range(nb_lines):
422 grid[i] = [x for x in grid[i] if x is not None]
423 for j, cell in enumerate(grid[i]):
424 if grid[i][j] is None:
429 # we look if the next time cell has the same emissions
430 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
431 if x == cell and x.y == cell.y and x.w == cell.w]
433 # if the cell was identical, we remove it and
434 # increase current cell height
435 bj, same_cell_below = same_cell_below[0]
436 del grid[i+cell.h][bj]
439 # if the cell is different, we have a closer look
440 # to it, so we can remove emissions that will
441 # already be mentioned in the current cell.
444 # - 7am30, seuls contre tout, 1h30
445 # - 8am, du pied gauche & la voix de la rue, 1h
446 # should produce: (this is case A)
448 # | seuls contre tout |
449 # |---------------------|
452 # | la voix de la rue |
454 # On the other hand, if all three emissions started
455 # at 7am30, we want: (this is case B)
457 # | seuls contre tout |
459 # | la voix de la rue |
460 # that is we merge all of them, ignoring the fact
461 # that the other emissions will stop at 8am30
462 current_cell_schedules = set(grid[i][j].schedules)
463 current_cell_emissions = set([x.emission for x in current_cell_schedules])
465 while True and current_cell_schedules:
466 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
467 if not same_cell_below:
470 same_cell_below = same_cell_below[0]
471 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
473 if current_cell_emissions.issubset(same_cell_below_emissions):
474 # this handles case A (see comment above)
475 for schedule in current_cell_schedules:
476 if schedule in same_cell_below.schedules:
477 same_cell_below.schedules.remove(schedule)
478 elif same_cell_below_emissions and \
479 current_cell_emissions.issuperset(same_cell_below_emissions):
480 # this handles case B (see comment above)
481 # we set the cell time label to the longest
483 grid[i][j].time_label = same_cell_below.time_label
484 # then we sort emissions so the longest are
486 grid[i][j].schedules.sort(
487 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
488 # then we add individual time labels to the
490 for schedule in current_cell_schedules:
491 if schedule not in same_cell_below.schedules:
492 end_time = schedule.datetime + timedelta(
493 minutes=schedule.get_duration())
494 schedule.time_label = '%02d:%02d-%02d:%02d' % (
495 schedule.datetime.hour,
496 schedule.datetime.minute,
500 grid[i+cursor].remove(same_cell_below)
501 elif same_cell_below_emissions and \
502 current_cell_emissions.intersection(same_cell_below_emissions):
503 same_cell_below.schedules = [x for x in
504 same_cell_below.schedules if
506 current_cell_emissions or
507 x.get_duration() < 30]
517 context['grid'] = grid
518 context['times'] = times
519 context['categories'] = Category.objects.all()
520 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
521 'Vendredi', 'Samedi', 'Dimanche']
525 grid = Grid.as_view()
528 class Home(TemplateView):
529 template_name = 'home.html'
531 def get_context_data(self, **kwargs):
532 context = super(Home, self).get_context_data(**kwargs)
533 context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
534 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
535 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
537 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
538 podcastable=True, fragment=False) \
539 .select_related().extra(select={
540 'first_diffusion': 'emissions_diffusion.datetime', },
541 select_params=(False, True),
542 where=['''datetime = (SELECT MIN(datetime)
543 FROM emissions_diffusion
544 WHERE episode_id = emissions_episode.id)'''],
545 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
547 context['newsletter_form'] = SubscribeForm()
548 context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
552 home = Home.as_view()
554 class NewsItemView(DetailView):
556 def get_context_data(self, **kwargs):
557 context = super(NewsItemView, self).get_context_data(**kwargs)
558 context['categories'] = NewsCategory.objects.all()
559 context['news'] = NewsItem.objects.all().order_by('-date')
560 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
562 newsitemview = NewsItemView.as_view()
564 class News(TemplateView):
565 template_name = 'news.html'
566 def get_context_data(self, **kwargs):
567 context = super(News, self).get_context_data(**kwargs)
568 context['focus'] = NewsItem.objects.exclude(date__gt=date.today() # publication date
569 ).exclude(expiration_date__lt=date.today() # expiration date
570 ).filter(got_focus__isnull=False
571 ).select_related('category').order_by('-date')[:10]
572 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
575 news = News.as_view()
578 class Agenda(TemplateView):
579 template_name = 'agenda.html'
580 def get_context_data(self, **kwargs):
581 context = super(Agenda, self).get_context_data(**kwargs)
582 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
583 event_date__gte=date.today()).order_by('date')[:20]
584 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
585 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
588 agenda = Agenda.as_view()
591 class AgendaByMonth(MonthArchiveView):
592 template_name = 'agenda.html'
593 queryset = NewsItem.objects.filter(event_date__isnull=False)
595 date_field = 'event_date'
598 def get_context_data(self, **kwargs):
599 context = super(AgendaByMonth, self).get_context_data(**kwargs)
600 context['agenda'] = context['object_list']
601 context['news'] = NewsItem.objects.all().order_by('-date')
604 agenda_by_month = AgendaByMonth.as_view()
607 class Emissions(TemplateView):
608 template_name = 'emissions.html'
610 def get_context_data(self, **kwargs):
611 context = super(Emissions, self).get_context_data(**kwargs)
612 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
613 context['categories'] = Category.objects.all()
616 emissions = Emissions.as_view()
618 class EmissionsArchives(TemplateView):
619 template_name = 'emissions/archives.html'
621 def get_context_data(self, **kwargs):
622 context = super(EmissionsArchives, self).get_context_data(**kwargs)
623 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
624 context['categories'] = Category.objects.all()
626 emissionsArchives = EmissionsArchives.as_view()
629 class Listen(TemplateView):
630 template_name = 'listen.html'
632 def get_context_data(self, **kwargs):
633 context = super(Listen, self).get_context_data(**kwargs)
634 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
635 podcastable=True, got_focus__isnull=False) \
636 .select_related().extra(select={
637 'first_diffusion': 'emissions_diffusion.datetime', },
638 select_params=(False, True),
639 where=['''datetime = (SELECT MIN(datetime)
640 FROM emissions_diffusion
641 WHERE episode_id = emissions_episode.id)'''],
642 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
643 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
645 .select_related().extra(select={
646 'first_diffusion': 'emissions_diffusion.datetime', },
647 select_params=(False, True),
648 where=['''datetime = (SELECT MIN(datetime)
649 FROM emissions_diffusion
650 WHERE episode_id = emissions_episode.id)'''],
651 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
656 listen = Listen.as_view()
658 @cache_control(max_age=15)
661 if datetime.now() < datetime(2019, 7, 31, 18, 0):
662 class FakeNonstop(object):
663 title = 'Le festival arrive, découvrez déjà la musique !'
664 d = {'title': 'XXX', 'nonstop': FakeNonstop()}
665 #return JsonResponse({'data': {'emission': {'title': 'À partir du 31 juillet 18h', 'url': '/'}}})
666 elif date.today() > date(2019, 8, 5):
667 return JsonResponse({'data': {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}})
672 'title': d['episode'].title,
673 'url': d['episode'].get_absolute_url()
675 if d.get('emission'):
677 if d['emission'].chat_open:
678 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
680 'title': d['emission'].title,
681 'url': d['emission'].get_absolute_url(),
686 'title': d['nonstop'].title,
688 playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
689 if os.path.exists(os.path.join(playing_txt)):
690 d['track_title'] = open(playing_txt).read().strip()
691 if d.get('current_slot'):
692 del d['current_slot']
693 return JsonResponse({'data': d})
696 class NewsItemDetailView(DetailView):
699 newsitem = NewsItemDetailView.as_view()
701 class RssCustomPodcastsFeed(Rss201rev2Feed):
702 def add_root_elements(self, handler):
703 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
704 emission = self.feed.get('emission')
705 if emission and emission.image and emission.image.url:
706 image_url = emission.image.url
708 image_url = '/static/img/logo-panik-500.png'
709 image_url = urlparse.urljoin(self.feed['link'], image_url)
710 handler.startElement('image', {})
712 handler.addQuickElement('title', emission.title)
714 handler.addQuickElement('title', 'Radio Esperanzah!')
715 handler.addQuickElement('url', image_url)
716 handler.endElement('image')
717 handler.addQuickElement('itunes:image', None, {'href': image_url})
718 if emission and emission.subtitle:
719 handler.addQuickElement('itunes:subtitle', emission.subtitle)
721 def root_attributes(self):
722 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
723 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
724 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
727 def add_item_elements(self, handler, item):
728 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
730 for tag in item.get('tags') or []:
731 handler.addQuickElement('dc:subject', tag)
732 if tag == 'explicit':
735 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
736 handler.addQuickElement('itunes:explicit', explicit)
737 episode = item.get('episode')
738 if episode and episode.image and episode.image.url:
739 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
740 handler.addQuickElement('itunes:image', None, {'href': image_url})
741 soundfile = item.get('soundfile')
742 if soundfile.duration:
743 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
744 soundfile.duration / 3600,
745 soundfile.duration % 3600 / 60,
746 soundfile.duration % 60))
749 class PodcastsFeed(Feed):
750 title = 'Radio Esperanzah! - Podcasts'
752 description_template = 'feed/soundfile.html'
753 feed_type = RssCustomPodcastsFeed
756 return SoundFile.objects.select_related().filter(
757 podcastable=True).order_by('-creation_timestamp')[:20]
759 def item_title(self, item):
761 return '%s - %s' % (item.title, item.episode.title)
762 return '%s - %s' % (item.episode.emission.title, item.episode.title)
764 def item_link(self, item):
765 return item.episode.get_absolute_url()
767 def item_enclosure_url(self, item):
768 current_site = Site.objects.get(id=settings.SITE_ID)
769 return add_domain(current_site.domain, item.get_format_url('mp3'))
771 def item_enclosure_length(self, item):
772 sound_path = item.get_format_path('mp3')
774 return os.stat(sound_path)[stat.ST_SIZE]
778 def item_enclosure_mime_type(self, item):
781 def item_pubdate(self, item):
782 return item.creation_timestamp
784 def item_extra_kwargs(self, item):
785 return {'tags': [x.name for x in item.episode.tags.all()],
787 'episode': item.episode}
789 podcasts_feed = PodcastsFeed()
792 class RssNewsFeed(Feed):
793 title = 'Radio Esperanzah!'
795 description_template = 'feed/newsitem.html'
798 return NewsItem.objects.order_by('-date')[:20]
800 rss_news_feed = RssNewsFeed()
802 class Atom1FeedWithBaseXml(Atom1Feed):
803 def root_attributes(self):
804 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
805 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
806 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
807 return root_attributes
809 class AtomNewsFeed(RssNewsFeed):
810 feed_type = Atom1FeedWithBaseXml
812 atom_news_feed = AtomNewsFeed()
815 class EmissionPodcastsFeed(PodcastsFeed):
816 description_template = 'feed/soundfile.html'
817 feed_type = RssCustomPodcastsFeed
819 def __call__(self, request, *args, **kwargs):
820 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
821 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
825 return self.emission.title
829 return reverse('emission-view', kwargs={'slug': self.emission.slug})
831 def feed_extra_kwargs(self, obj):
832 return {'emission': self.emission}
835 return SoundFile.objects.select_related().filter(
837 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
839 emission_podcasts_feed = EmissionPodcastsFeed()
842 class Party(TemplateView):
843 template_name = 'party.html'
845 def get_context_data(self, **kwargs):
846 context = super(Party, self).get_context_data(**kwargs)
847 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
850 focus.newsitem = NewsItem.objects.exclude(
851 image__isnull=True).exclude(image__exact='').order_by('?')[0]
852 elif t == 'emission':
853 focus.emission = Emission.objects.exclude(
854 image__isnull=True).exclude(image__exact='').order_by('?')[0]
856 focus.episode = Episode.objects.exclude(
857 image__isnull=True).exclude(image__exact='').order_by('?')[0]
858 elif t == 'soundfile':
859 focus.soundfile = SoundFile.objects.exclude(
860 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
862 context['focus'] = focus
866 party = Party.as_view()
870 class Chat(DetailView, EmissionMixin):
872 template_name = 'chat.html'
874 chat = cache_control(max_age=15)(Chat.as_view())
878 class ArchivesView(TemplateView):
879 template_name = 'archives.html'
881 def get_context_data(self, **kwargs):
882 context = super(ArchivesView, self).get_context_data(**kwargs)
883 context['diffusions'] = Diffusion.objects.filter(episode__soundfile__isnull=False).distinct().order_by('-datetime')
886 archives = ArchivesView.as_view()