1 from datetime import datetime, timedelta, date
8 from django.core.urlresolvers import reverse
9 from django.conf import settings
10 from django.http import Http404, JsonResponse
11 from django.utils.encoding import force_text
12 from django.utils.encoding import python_2_unicode_compatible
13 from django.utils.six.moves.urllib import parse as urlparse
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
31 from emissions.views import EmissionEpisodeMixin
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 panikombo.models import ItemTopik
44 def get_emission_context(self, emission, episode_ids=None):
47 # get all episodes, with an additional attribute to get the date of
48 # their first diffusion
49 episodes_queryset = Episode.objects.select_related()
50 if episode_ids is not None:
51 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
53 episodes_queryset = episodes_queryset.filter(emission=emission)
55 context['episodes'] = \
56 episodes_queryset.extra(select={
57 'first_diffusion': 'emissions_diffusion.datetime',
59 select_params=(False, True),
60 where=['''datetime = (SELECT MIN(datetime)
61 FROM emissions_diffusion
62 WHERE episode_id = emissions_episode.id
63 AND datetime <= CURRENT_TIMESTAMP)'''],
64 tables=['emissions_diffusion'],
65 ).order_by('-first_diffusion').distinct()
67 context['futurEpisodes'] = \
68 episodes_queryset.extra(select={
69 'first_diffusion': 'emissions_diffusion.datetime',
71 select_params=(False, True),
72 where=['''datetime = (SELECT MIN(datetime)
73 FROM emissions_diffusion
74 WHERE episode_id = emissions_episode.id
75 AND datetime > CURRENT_TIMESTAMP)'''],
76 tables=['emissions_diffusion'],
77 ).order_by('first_diffusion').distinct()
80 # get all related soundfiles in a single query
82 if episode_ids is not None:
83 for episode_id in episode_ids:
84 soundfiles[episode_id] = None
86 for episode in Episode.objects.filter(emission=emission):
87 soundfiles[episode.id] = None
89 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
90 fragment=False, episode__emission=emission):
91 soundfiles[soundfile.episode_id] = soundfile
93 Episode.set_prefetched_soundfiles(soundfiles)
95 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
100 class EmissionDetailView(DetailView, EmissionMixin):
103 def get_context_data(self, **kwargs):
104 context = super(EmissionDetailView, self).get_context_data(**kwargs)
105 context['schedules'] = Schedule.objects.select_related().filter(
106 emission=self.object).order_by('rerun', 'datetime')
107 context['news'] = NewsItem.objects.all(
108 ).filter(emission=self.object.id
109 ).exclude(expiration_date__lt=date.today() # expiration date
110 ).exclude(date__lt=date.today() - timedelta(days=60)
111 ).order_by('-date')[:3]
113 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
114 except Nonstop.DoesNotExist:
118 dates = [today - timedelta(days=x) for x in range(7)]
119 if datetime.now().time() < nonstop_object.start:
121 context['nonstop'] = nonstop_object
122 context['nonstop_dates'] = dates
123 context.update(self.get_emission_context(self.object))
125 emission = EmissionDetailView.as_view()
128 class EpisodeDetailView(EmissionEpisodeMixin, DetailView, EmissionMixin):
131 def get_context_data(self, **kwargs):
132 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
133 context['diffusions'] = Diffusion.objects.select_related().filter(
134 episode=self.object.id).order_by('datetime')
136 context['emission'] = context['episode'].emission
137 except Emission.DoesNotExist:
139 if self.kwargs.get('emission_slug') != context['emission'].slug:
141 context.update(self.get_emission_context(context['emission']))
142 context['topik_pages'] = [x.page for x in ItemTopik.objects.filter(episode=self.object)]
146 episode = EpisodeDetailView.as_view()
149 class NonstopPlaylistView(TemplateView):
150 template_name = 'nonstop_playlist.html'
152 def get_context_data(self, **kwargs):
153 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
155 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
156 except Emission.DoesNotExist:
158 context['date'] = date(int(kwargs.get('year')),
159 int(kwargs.get('month')), int(kwargs.get('day')))
160 context['future'] = (context['date'] >= date.today())
162 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
164 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
165 nonstop_object.start.hour, nonstop_object.start.minute)
167 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
168 nonstop_object.end.hour, nonstop_object.end.minute)
170 end = end + timedelta(days=1)
171 context['tracks'] = SomaLogLine.objects.filter(
172 play_timestamp__gte=start,
173 play_timestamp__lte=end,
174 on_air=True).select_related()
177 nonstop_playlist = NonstopPlaylistView.as_view()
179 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
181 template_name = 'emissions/episodes.html'
183 def get_context_data(self, **kwargs):
184 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
185 context['schedules'] = Schedule.objects.select_related().filter(
186 emission=self.object).order_by('rerun', 'datetime')
188 context['search_query'] = self.request.GET.get('q')
189 if context['search_query']:
191 sqs = SearchQuerySet().models(Episode).filter(
192 emission_slug_exact=self.object.slug, text=context['search_query'])
193 episode_ids = [x.pk for x in sqs]
197 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
199 emissionEpisodes = EmissionEpisodesDetailView.as_view()
202 class SoundFileEmbedView(DetailView):
204 template_name = 'soundfiles/embed.html'
206 def get_context_data(self, **kwargs):
207 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
208 if self.kwargs.get('episode_slug') != self.object.episode.slug:
210 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
212 context['episode'] = self.object.episode
214 soundfile_embed = SoundFileEmbedView.as_view()
217 class SoundFileDialogEmbedView(DetailView):
219 template_name = 'soundfiles/dialog-embed.html'
221 def get_context_data(self, **kwargs):
222 context = super(SoundFileDialogEmbedView, 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_dlg_embed = SoundFileDialogEmbedView.as_view()
233 class ProgramView(TemplateView):
234 template_name = 'program.html'
236 def get_context_data(self, year=None, week=None, **kwargs):
237 context = super(ProgramView, self).get_context_data(**kwargs)
239 context['weekday'] = datetime.today().weekday()
241 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
242 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
243 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
244 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
248 program = ProgramView.as_view()
250 @python_2_unicode_compatible
257 def __init__(self, i, j):
262 def add_schedule(self, schedule):
263 end_time = schedule.datetime + timedelta(
264 minutes=schedule.get_duration())
265 self.time_label = '%02d:%02d-%02d:%02d' % (
266 schedule.datetime.hour,
267 schedule.datetime.minute,
270 self.schedules.append(schedule)
272 def sorted_schedules(self):
273 return sorted(self.schedules, key=lambda x: x.week_sort_key())
277 return ', '.join([x.emission.title for x in self.schedules])
281 def __eq__(self, other):
282 return (force_text(self) == force_text(other) and self.time_label == other.time_label)
285 class Grid(TemplateView):
286 template_name = 'grid.html'
288 def get_context_data(self, **kwargs):
289 context = super(Grid, self).get_context_data(**kwargs)
291 nb_lines = 2 * 24 # the cells are half hours
294 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
295 # start grid after the night programs
296 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
299 for nonstop in Nonstop.objects.all():
300 if nonstop.start == nonstop.end:
302 if nonstop.start < nonstop.end:
303 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
304 nonstop.end.hour + nonstop.end.minute/60.,
305 nonstop.title, nonstop.slug, nonstop])
308 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
310 nonstop.title, nonstop.slug, nonstop])
312 nonstop.end.hour + nonstop.end.minute/60.,
313 nonstop.title, nonstop.slug, nonstop])
316 for i in range(nb_lines):
319 grid[-1].append(TimeCell(i, j))
321 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
322 for time_cell in grid[-1]:
323 time_cell.nonstop = nonstop[2]
324 time_cell.nonstop_slug = nonstop[3]
325 time_cell.redirect_path = nonstop[4].redirect_path
327 # the one ending at 5am will be cut down, so we inscribe
328 # its duration manually
329 time_cell.time_label = '%02d:00-%02d:00' % (
330 nonstop[0], nonstop[1])
332 for schedule in Schedule.objects.prefetch_related(
333 'emission__categories').select_related().order_by('datetime'):
334 row_start = schedule.datetime.hour * 2 + \
335 int(math.ceil(schedule.datetime.minute / 30))
336 day_no = schedule.get_weekday()
338 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
339 if grid[(row_start+step)%nb_lines][day_no] is None:
340 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
341 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
343 # start grid after the night programs
344 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
346 # look for the case where the same emission has different schedules for
347 # the same time cell, for example if it lasts one hour the first week,
348 # and two hours the third week.
349 for i in range(nb_lines):
350 grid[i] = [x for x in grid[i] if x is not None]
351 for j, cell in enumerate(grid[i]):
352 if grid[i][j] is None:
354 if len(grid[i][j].schedules) > 1:
355 time_cell_emissions = {}
356 for schedule in grid[i][j].schedules:
357 if not schedule.emission.id in time_cell_emissions:
358 time_cell_emissions[schedule.emission.id] = []
359 time_cell_emissions[schedule.emission.id].append(schedule)
360 for schedule_list in time_cell_emissions.values():
361 if len(schedule_list) == 1:
363 # here it is, same cell, same emission, several
365 schedule_list.sort(key=lambda x: x.get_duration())
367 schedule = schedule_list[0]
368 end_time = schedule.datetime + timedelta(
369 minutes=schedule.get_duration())
370 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
371 schedule.datetime.hour,
372 schedule.datetime.minute,
376 for schedule in schedule_list[1:]:
377 grid[i][j].schedules.remove(schedule)
378 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
379 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
380 end_time.hour, end_time.minute, schedule.weeks_string)
384 # 1st thing is to merge cells on the same line, this will mostly catch
385 # consecutive nonstop cells
386 for i in range(nb_lines):
387 for j, cell in enumerate(grid[i]):
388 if grid[i][j] is None:
392 # if the cells are identical, they are removed from the
393 # grid, and current cell width is increased
394 while grid[i][j+t] == cell:
401 # once we're done we remove empty cells
402 grid[i] = [x for x in grid[i] if x is not None]
404 # 2nd thing is to merge cells vertically, this is emissions that last
405 # for more than 30 minutes
406 for i in range(nb_lines):
407 grid[i] = [x for x in grid[i] if x is not None]
408 for j, cell in enumerate(grid[i]):
409 if grid[i][j] is None:
414 # we look if the next time cell has the same emissions
415 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
416 if x == cell and x.y == cell.y and x.w == cell.w]
418 # if the cell was identical, we remove it and
419 # increase current cell height
420 bj, same_cell_below = same_cell_below[0]
421 del grid[i+cell.h][bj]
424 # if the cell is different, we have a closer look
425 # to it, so we can remove emissions that will
426 # already be mentioned in the current cell.
429 # - 7am30, seuls contre tout, 1h30
430 # - 8am, du pied gauche & la voix de la rue, 1h
431 # should produce: (this is case A)
433 # | seuls contre tout |
434 # |---------------------|
437 # | la voix de la rue |
439 # On the other hand, if all three emissions started
440 # at 7am30, we want: (this is case B)
442 # | seuls contre tout |
444 # | la voix de la rue |
445 # that is we merge all of them, ignoring the fact
446 # that the other emissions will stop at 8am30
447 current_cell_schedules = set(grid[i][j].schedules)
448 current_cell_emissions = set([x.emission for x in current_cell_schedules])
450 while True and current_cell_schedules:
451 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
452 if not same_cell_below:
455 same_cell_below = same_cell_below[0]
456 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
458 if current_cell_emissions.issubset(same_cell_below_emissions):
459 # this handles case A (see comment above)
460 for schedule in current_cell_schedules:
461 if schedule in same_cell_below.schedules:
462 same_cell_below.schedules.remove(schedule)
463 elif same_cell_below_emissions and \
464 current_cell_emissions.issuperset(same_cell_below_emissions):
465 # this handles case B (see comment above)
466 # we set the cell time label to the longest
468 grid[i][j].time_label = same_cell_below.time_label
469 # then we sort emissions so the longest are
471 grid[i][j].schedules.sort(key=lambda x: -x.get_duration())
472 # then we add individual time labels to the
474 for schedule in current_cell_schedules:
475 if schedule not in same_cell_below.schedules:
476 end_time = schedule.datetime + timedelta(
477 minutes=schedule.get_duration())
478 schedule.time_label = '%02d:%02d-%02d:%02d' % (
479 schedule.datetime.hour,
480 schedule.datetime.minute,
484 grid[i+cursor].remove(same_cell_below)
485 elif same_cell_below_emissions and \
486 current_cell_emissions.intersection(same_cell_below_emissions):
487 same_cell_below.schedules = [x for x in
488 same_cell_below.schedules if
490 current_cell_emissions or
491 x.get_duration() < 30]
501 context['grid'] = grid
502 context['times'] = times
503 context['categories'] = Category.objects.all()
504 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
505 'Vendredi', 'Samedi', 'Dimanche']
509 grid = Grid.as_view()
512 class Home(TemplateView):
513 template_name = 'home.html'
515 def get_context_data(self, **kwargs):
516 context = super(Home, self).get_context_data(**kwargs)
517 context['emissions'] = Emission.objects.filter(archived=False).order_by('-creation_timestamp')[:3]
518 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')[:3]
520 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
521 podcastable=True, fragment=False) \
522 .select_related().extra(select={
523 'first_diffusion': 'emissions_diffusion.datetime', },
524 select_params=(False, True),
525 where=['''datetime = (SELECT MIN(datetime)
526 FROM emissions_diffusion
527 WHERE episode_id = emissions_episode.id)'''],
528 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
530 context['newsletter_form'] = SubscribeForm()
534 home = Home.as_view()
537 class NewsItemView(DetailView):
540 def get_context_data(self, **kwargs):
541 context = super(NewsItemView, self).get_context_data(**kwargs)
542 context['categories'] = NewsCategory.objects.all()
543 context['news'] = NewsItem.objects.all().order_by('-date')
544 context['topik_pages'] = [x.page for x in ItemTopik.objects.filter(newsitem=self.object)]
548 newsitemview = NewsItemView.as_view()
551 class News(TemplateView):
552 template_name = 'news.html'
553 def get_context_data(self, **kwargs):
554 context = super(News, self).get_context_data(**kwargs)
555 context['focus'] = NewsItem.objects.exclude(date__gt=date.today() # publication date
556 ).exclude(expiration_date__lt=date.today() # expiration date
557 ).filter(got_focus__isnull=False
558 ).select_related('category').order_by('-date')[:10]
559 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
562 news = News.as_view()
565 class Agenda(TemplateView):
566 template_name = 'agenda.html'
567 def get_context_data(self, **kwargs):
568 context = super(Agenda, self).get_context_data(**kwargs)
569 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
570 event_date__gte=date.today()).order_by('date')[:20]
571 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
572 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
575 agenda = Agenda.as_view()
578 class AgendaByMonth(MonthArchiveView):
579 template_name = 'agenda.html'
580 queryset = NewsItem.objects.filter(event_date__isnull=False)
582 date_field = 'event_date'
585 def get_context_data(self, **kwargs):
586 context = super(AgendaByMonth, self).get_context_data(**kwargs)
587 context['agenda'] = context['object_list']
588 context['news'] = NewsItem.objects.all().order_by('-date')
591 agenda_by_month = AgendaByMonth.as_view()
594 class Emissions(TemplateView):
595 template_name = 'emissions.html'
597 def get_context_data(self, **kwargs):
598 context = super(Emissions, self).get_context_data(**kwargs)
599 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
600 context['categories'] = Category.objects.all()
603 emissions = Emissions.as_view()
605 class EmissionsArchives(TemplateView):
606 template_name = 'emissions/archives.html'
608 def get_context_data(self, **kwargs):
609 context = super(EmissionsArchives, self).get_context_data(**kwargs)
610 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
611 context['categories'] = Category.objects.all()
613 emissionsArchives = EmissionsArchives.as_view()
616 class Listen(TemplateView):
617 template_name = 'listen.html'
619 def get_context_data(self, **kwargs):
620 context = super(Listen, self).get_context_data(**kwargs)
621 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
622 podcastable=True, got_focus__isnull=False) \
623 .select_related().extra(select={
624 'first_diffusion': 'emissions_diffusion.datetime', },
625 select_params=(False, True),
626 where=['''datetime = (SELECT MIN(datetime)
627 FROM emissions_diffusion
628 WHERE episode_id = emissions_episode.id)'''],
629 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
630 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
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('-creation_timestamp').distinct()
643 listen = Listen.as_view()
645 @cache_control(max_age=15)
651 'title': d['episode'].title,
652 'url': d['episode'].get_absolute_url()
654 if d.get('emission'):
656 if d['emission'].chat_open:
657 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
659 'title': d['emission'].title,
660 'url': d['emission'].get_absolute_url(),
664 redirect_path = d['nonstop'].redirect_path
666 'title': d['nonstop'].title,
669 d['nonstop']['url'] = redirect_path
670 d.update(get_current_nonstop_track())
671 if d.get('current_slot'):
672 del d['current_slot']
673 return JsonResponse({'data': d})
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', settings.RADIO_NAME)
695 handler.addQuickElement('url', image_url)
696 handler.endElement('image')
697 handler.addQuickElement('itunes:explicit', 'no') # invidividual items will get their own value
698 handler.addQuickElement('itunes:image', None, {'href': image_url})
700 if emission.subtitle:
701 handler.addQuickElement('itunes:subtitle', emission.subtitle)
702 for category in emission.categories.all():
703 if category.itunes_category:
704 handler.addQuickElement('itunes:category', None, {'text': category.itunes_category})
706 handler.addQuickElement('itunes:author', emission.title)
707 handler.startElement('itunes:owner', {})
709 handler.addQuickElement('itunes:email', emission.email)
710 handler.addQuickElement('itunes:name', emission.title)
711 handler.endElement('itunes:owner')
713 handler.addQuickElement('itunes:author', settings.RADIO_NAME)
714 handler.startElement('itunes:owner', {})
715 handler.addQuickElement('itunes:email', 'info@radiopanik.org')
716 handler.addQuickElement('itunes:name', settings.RADIO_NAME)
717 handler.endElement('itunes:owner')
719 def root_attributes(self):
720 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
721 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
722 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
725 def add_item_elements(self, handler, item):
726 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
728 for tag in item.get('tags') or []:
729 handler.addQuickElement('dc:subject', tag)
730 if tag == 'explicit':
733 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
734 handler.addQuickElement('itunes:explicit', explicit)
735 episode = item.get('episode')
736 if episode and episode.image and episode.image.url:
737 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
738 handler.addQuickElement('itunes:image', None, {'href': image_url})
739 soundfile = item.get('soundfile')
740 if soundfile.duration:
741 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
742 soundfile.duration / 3600,
743 soundfile.duration % 3600 / 60,
744 soundfile.duration % 60))
747 class PodcastsFeed(Feed):
748 title = '%s - Podcasts' % settings.RADIO_NAME
750 description_template = 'feed/soundfile.html'
751 feed_type = RssCustomPodcastsFeed
754 return SoundFile.objects.select_related().filter(
755 podcastable=True).order_by('-creation_timestamp')[:50]
757 def item_title(self, item):
759 return '[%s] %s - %s' % (item.episode.emission.title, item.title, item.episode.title)
760 return '[%s] %s' % (item.episode.emission.title, item.episode.title)
762 def item_link(self, item):
764 return item.episode.get_absolute_url() + '#%s' % item.id
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 = settings.RADIO_NAME
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)
823 def item_title(self, item):
825 return '%s - %s' % (item.title, item.episode.title)
826 return item.episode.title
830 return self.emission.title
833 def description(self):
834 return self.emission.subtitle
838 return reverse('emission-view', kwargs={'slug': self.emission.slug})
840 def feed_extra_kwargs(self, obj):
841 return {'emission': self.emission}
844 return SoundFile.objects.select_related().filter(
846 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:50]
848 emission_podcasts_feed = EmissionPodcastsFeed()
851 class Party(TemplateView):
852 template_name = 'party.html'
854 def get_context_data(self, **kwargs):
855 context = super(Party, self).get_context_data(**kwargs)
856 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
859 focus.newsitem = NewsItem.objects.exclude(
860 image__isnull=True).exclude(image__exact='').order_by('?')[0]
861 elif t == 'emission':
862 focus.emission = Emission.objects.exclude(
863 image__isnull=True).exclude(image__exact='').order_by('?')[0]
865 focus.episode = Episode.objects.exclude(
866 image__isnull=True).exclude(image__exact='').order_by('?')[0]
867 elif t == 'soundfile':
868 focus.soundfile = SoundFile.objects.exclude(
869 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
871 context['focus'] = focus
875 party = Party.as_view()
879 class Chat(DetailView, EmissionMixin):
881 template_name = 'chat.html'
883 chat = cache_control(max_age=15)(Chat.as_view())