3 from datetime import datetime, timedelta, date
10 from django.core.urlresolvers import reverse
11 from django.conf import settings
12 from django.http import Http404, JsonResponse
13 from django.utils.encoding import force_text
14 from django.utils.encoding import python_2_unicode_compatible
15 from django.utils.six.moves.urllib import parse as urlparse
16 from django.views.decorators.cache import cache_control
17 from django.views.generic.base import TemplateView
18 from django.views.generic.detail import DetailView
19 from django.views.decorators.csrf import csrf_exempt
20 from django.views.generic.dates import _date_from_string
21 from django.views.generic.dates import MonthArchiveView
23 from django.core.paginator import Paginator
25 from django.contrib.sites.models import Site
26 from django.contrib.syndication.views import Feed, add_domain
27 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
29 from haystack.query import SearchQuerySet
31 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
32 Schedule, Nonstop, NewsItem, NewsCategory, Focus
34 from emissions.utils import whatsonair, period_program
36 from newsletter.forms import SubscribeForm
37 from nonstop.utils import get_current_nonstop_track
38 from nonstop.models import SomaLogLine
40 from combo.data.models import Page
41 from panikombo.models import ItemTopik
47 def get_emission_context(self, emission, episode_ids=None):
50 # get all episodes, with an additional attribute to get the date of
51 # their first diffusion
52 episodes_queryset = Episode.objects.select_related()
53 if episode_ids is not None:
54 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
56 episodes_queryset = episodes_queryset.filter(emission=emission)
58 context['episodes'] = \
59 episodes_queryset.extra(select={
60 'first_diffusion': 'emissions_diffusion.datetime',
62 select_params=(False, True),
63 where=['''datetime = (SELECT MIN(datetime)
64 FROM emissions_diffusion
65 WHERE episode_id = emissions_episode.id
66 AND datetime <= CURRENT_TIMESTAMP)'''],
67 tables=['emissions_diffusion'],
68 ).order_by('-first_diffusion').distinct()
70 context['futurEpisodes'] = \
71 episodes_queryset.extra(select={
72 'first_diffusion': 'emissions_diffusion.datetime',
74 select_params=(False, True),
75 where=['''datetime = (SELECT MIN(datetime)
76 FROM emissions_diffusion
77 WHERE episode_id = emissions_episode.id
78 AND datetime > CURRENT_TIMESTAMP)'''],
79 tables=['emissions_diffusion'],
80 ).order_by('first_diffusion').distinct()
83 current_year = emission.creation_timestamp.replace(month=5, day=1)
85 current_year = datetime.now().replace(month=5, day=1).replace(year=2019)
87 context['all_episodes'] = episodes_queryset.filter(
88 creation_timestamp__gt=current_year
90 'first_diffusion': 'emissions_diffusion.datetime',
92 select_params=(False, True),
93 where=['''datetime = (SELECT MIN(datetime)
94 FROM emissions_diffusion
95 WHERE episode_id = emissions_episode.id
97 tables=['emissions_diffusion'],
98 ).order_by('first_diffusion').distinct()
100 # get all related soundfiles in a single query
102 if episode_ids is not None:
103 for episode_id in episode_ids:
104 soundfiles[episode_id] = None
106 for episode in Episode.objects.filter(emission=emission):
107 soundfiles[episode.id] = None
109 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
110 fragment=False, episode__emission=emission):
111 soundfiles[soundfile.episode_id] = soundfile
113 Episode.set_prefetched_soundfiles(soundfiles)
115 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
120 class EmissionDetailView(DetailView, EmissionMixin):
123 def get_context_data(self, **kwargs):
124 context = super(EmissionDetailView, self).get_context_data(**kwargs)
125 context['schedules'] = Schedule.objects.select_related().filter(
126 emission=self.object).order_by('rerun', 'datetime')
127 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
129 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
130 except Nonstop.DoesNotExist:
134 dates = [today - timedelta(days=x) for x in range(7)]
135 if datetime.now().time() < nonstop_object.start:
137 context['nonstop'] = nonstop_object
138 context['nonstop_dates'] = dates
139 context.update(self.get_emission_context(self.object))
141 emission = EmissionDetailView.as_view()
143 class EpisodeDetailView(DetailView, EmissionMixin):
146 def get_queryset(self, *args, **kwargs):
147 queryset = super(EpisodeDetailView, self).get_queryset(*args, **kwargs)
148 return queryset.filter(emission__slug=self.kwargs['emission_slug'])
150 def get_context_data(self, **kwargs):
151 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
152 context['diffusions'] = Diffusion.objects.select_related().filter(
153 episode=self.object.id).order_by('datetime')
155 context['emission'] = context['episode'].emission
156 except Emission.DoesNotExist:
158 if self.kwargs.get('emission_slug') != context['emission'].slug:
160 context.update(self.get_emission_context(context['emission']))
161 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
163 episode = EpisodeDetailView.as_view()
166 class NonstopPlaylistView(TemplateView):
167 template_name = 'nonstop_playlist.html'
169 def get_context_data(self, **kwargs):
170 context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
172 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
173 except Emission.DoesNotExist:
175 context['date'] = date(int(kwargs.get('year')),
176 int(kwargs.get('month')), int(kwargs.get('day')))
177 context['future'] = (context['date'] >= date.today())
179 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
181 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
182 nonstop_object.start.hour, nonstop_object.start.minute)
184 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
185 nonstop_object.end.hour, nonstop_object.end.minute)
187 end = end + timedelta(days=1)
188 context['tracks'] = SomaLogLine.objects.filter(
189 play_timestamp__gte=start,
190 play_timestamp__lte=end,
191 on_air=True).select_related()
194 nonstop_playlist = NonstopPlaylistView.as_view()
196 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
198 template_name = 'emissions/episodes.html'
200 def get_context_data(self, **kwargs):
201 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
202 context['schedules'] = Schedule.objects.select_related().filter(
203 emission=self.object).order_by('rerun', 'datetime')
205 context['search_query'] = self.request.GET.get('q')
206 if context['search_query']:
208 sqs = SearchQuerySet().models(Episode).filter(
209 emission_slug_exact=self.object.slug, text=context['search_query'])
210 episode_ids = [x.pk for x in sqs]
214 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
216 emissionEpisodes = EmissionEpisodesDetailView.as_view()
219 class SoundFileEmbedView(DetailView):
221 template_name = 'soundfiles/embed.html'
223 def get_context_data(self, **kwargs):
224 context = super(SoundFileEmbedView, self).get_context_data(**kwargs)
225 if self.kwargs.get('episode_slug') != self.object.episode.slug:
227 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
229 context['episode'] = self.object.episode
231 soundfile_embed = SoundFileEmbedView.as_view()
234 class SoundFileDialogEmbedView(DetailView):
236 template_name = 'soundfiles/dialog-embed.html'
238 def get_context_data(self, **kwargs):
239 context = super(SoundFileDialogEmbedView, self).get_context_data(**kwargs)
240 if self.kwargs.get('episode_slug') != self.object.episode.slug:
242 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
244 context['episode'] = self.object.episode
246 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
250 class ProgramView(TemplateView):
251 template_name = 'program.html'
253 def get_context_data(self, year=None, week=None, **kwargs):
254 context = super(ProgramView, self).get_context_data(**kwargs)
256 context['weekday'] = datetime.today().weekday()
258 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
259 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
260 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
261 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
265 program = ProgramView.as_view()
267 @python_2_unicode_compatible
274 def __init__(self, i, j):
279 def add_schedule(self, schedule):
280 end_time = schedule.datetime + timedelta(
281 minutes=schedule.get_duration())
282 self.time_label = '%02d:%02d-%02d:%02d' % (
283 schedule.datetime.hour,
284 schedule.datetime.minute,
287 self.schedules.append(schedule)
291 return ', '.join([x.emission.title for x in self.schedules])
295 def __eq__(self, other):
296 return (force_text(self) == force_text(other) and self.time_label == other.time_label)
299 class Grid(TemplateView):
300 template_name = 'grid.html'
302 def get_context_data(self, **kwargs):
303 context = super(Grid, self).get_context_data(**kwargs)
305 nb_lines = 2 * 24 # the cells are half hours
308 Schedule.DAY_HOUR_START = 12
310 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
311 # start grid after the night programs
312 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
315 for nonstop in Nonstop.objects.all():
316 if nonstop.start == nonstop.end:
318 if nonstop.start < nonstop.end:
319 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
320 nonstop.end.hour + nonstop.end.minute/60.,
321 nonstop.title, nonstop.slug])
324 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
326 nonstop.title, nonstop.slug])
328 nonstop.end.hour + nonstop.end.minute/60.,
329 nonstop.title, nonstop.slug])
332 for i in range(nb_lines):
335 grid[-1].append(TimeCell(i, j))
338 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
341 for time_cell in grid[-1]:
342 time_cell.nonstop = nonstop[2]
343 time_cell.nonstop_slug = nonstop[3]
345 # the one ending at 5am will be cut down, so we inscribe
346 # its duration manually
347 time_cell.time_label = '%02d:00-%02d:00' % (
348 nonstop[0], nonstop[1])
350 for schedule in Schedule.objects.filter(emission__archived=False).prefetch_related(
351 'emission__categories').select_related().order_by('datetime'):
352 row_start = schedule.datetime.hour * 2 + \
353 int(math.ceil(schedule.datetime.minute / 30))
354 day_no = schedule.get_weekday()
356 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
357 if grid[(row_start+step)%nb_lines][day_no] is None:
358 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
359 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
361 # start grid after the night programs
362 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
364 # look for the case where the same emission has different schedules for
365 # the same time cell, for example if it lasts one hour the first week,
366 # and two hours the third week.
367 for i in range(nb_lines):
368 grid[i] = [x for x in grid[i] if x is not None]
369 for j, cell in enumerate(grid[i]):
370 if grid[i][j] is None:
372 if len(grid[i][j].schedules) > 1:
373 time_cell_emissions = {}
374 for schedule in grid[i][j].schedules:
375 if not schedule.emission.id in time_cell_emissions:
376 time_cell_emissions[schedule.emission.id] = []
377 time_cell_emissions[schedule.emission.id].append(schedule)
378 for schedule_list in time_cell_emissions.values():
379 if len(schedule_list) == 1:
381 # here it is, same cell, same emission, several
383 schedule_list.sort(key=lambda x: x.get_duration())
385 schedule = schedule_list[0]
386 end_time = schedule.datetime + timedelta(
387 minutes=schedule.get_duration())
388 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
389 schedule.datetime.hour,
390 schedule.datetime.minute,
394 for schedule in schedule_list[1:]:
395 grid[i][j].schedules.remove(schedule)
396 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
397 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
398 end_time.hour, end_time.minute, schedule.weeks_string)
402 # 1st thing is to merge cells on the same line, this will mostly catch
403 # consecutive nonstop cells
404 for i in range(nb_lines):
405 for j, cell in enumerate(grid[i]):
406 if grid[i][j] is None:
410 # if the cells are identical, they are removed from the
411 # grid, and current cell width is increased
412 while grid[i][j+t] == cell:
419 # once we're done we remove empty cells
420 grid[i] = [x for x in grid[i] if x is not None]
422 # 2nd thing is to merge cells vertically, this is emissions that last
423 # for more than 30 minutes
424 for i in range(nb_lines):
425 grid[i] = [x for x in grid[i] if x is not None]
426 for j, cell in enumerate(grid[i]):
427 if grid[i][j] is None:
432 # we look if the next time cell has the same emissions
433 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
434 if x == cell and x.y == cell.y and x.w == cell.w]
436 # if the cell was identical, we remove it and
437 # increase current cell height
438 bj, same_cell_below = same_cell_below[0]
439 del grid[i+cell.h][bj]
442 # if the cell is different, we have a closer look
443 # to it, so we can remove emissions that will
444 # already be mentioned in the current cell.
447 # - 7am30, seuls contre tout, 1h30
448 # - 8am, du pied gauche & la voix de la rue, 1h
449 # should produce: (this is case A)
451 # | seuls contre tout |
452 # |---------------------|
455 # | la voix de la rue |
457 # On the other hand, if all three emissions started
458 # at 7am30, we want: (this is case B)
460 # | seuls contre tout |
462 # | la voix de la rue |
463 # that is we merge all of them, ignoring the fact
464 # that the other emissions will stop at 8am30
465 current_cell_schedules = set(grid[i][j].schedules)
466 current_cell_emissions = set([x.emission for x in current_cell_schedules])
468 while True and current_cell_schedules:
469 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
470 if not same_cell_below:
473 same_cell_below = same_cell_below[0]
474 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
476 if current_cell_emissions.issubset(same_cell_below_emissions):
477 # this handles case A (see comment above)
478 for schedule in current_cell_schedules:
479 if schedule in same_cell_below.schedules:
480 same_cell_below.schedules.remove(schedule)
481 elif same_cell_below_emissions and \
482 current_cell_emissions.issuperset(same_cell_below_emissions):
483 # this handles case B (see comment above)
484 # we set the cell time label to the longest
486 grid[i][j].time_label = same_cell_below.time_label
487 # then we sort emissions so the longest are
489 grid[i][j].schedules.sort(key=lambda x: -x.get_duration())
490 # then we add individual time labels to the
492 for schedule in current_cell_schedules:
493 if schedule not in same_cell_below.schedules:
494 end_time = schedule.datetime + timedelta(
495 minutes=schedule.get_duration())
496 schedule.time_label = '%02d:%02d-%02d:%02d' % (
497 schedule.datetime.hour,
498 schedule.datetime.minute,
502 grid[i+cursor].remove(same_cell_below)
503 elif same_cell_below_emissions and \
504 current_cell_emissions.intersection(same_cell_below_emissions):
505 same_cell_below.schedules = [x for x in
506 same_cell_below.schedules if
508 current_cell_emissions or
509 x.get_duration() < 30]
519 context['grid'] = grid
520 context['times'] = times
521 context['categories'] = Category.objects.all()
522 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
523 'Vendredi', 'Samedi', 'Dimanche']
527 grid = Grid.as_view()
530 class Home(TemplateView):
531 template_name = 'home.html'
533 def get_context_data(self, **kwargs):
534 context = super(Home, self).get_context_data(**kwargs)
535 context['emissions'] = Emission.objects.filter(archived=False).order_by('title')
536 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()
537 ).exclude(expiration_date__lt=date.today()).order_by('-date')[:3]
539 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
540 podcastable=True, fragment=False) \
541 .select_related().extra(select={
542 'first_diffusion': 'emissions_diffusion.datetime', },
543 select_params=(False, True),
544 where=['''datetime = (SELECT MIN(datetime)
545 FROM emissions_diffusion
546 WHERE episode_id = emissions_episode.id)'''],
547 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
549 context['newsletter_form'] = SubscribeForm()
550 context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
554 home = Home.as_view()
556 class NewsItemView(DetailView):
558 def get_context_data(self, **kwargs):
559 context = super(NewsItemView, self).get_context_data(**kwargs)
560 context['categories'] = NewsCategory.objects.all()
561 context['news'] = NewsItem.objects.all().order_by('-date')
562 context['topiks'] = [x.topik for x in ItemTopik.objects.filter(newsitem=self.object)]
564 newsitemview = NewsItemView.as_view()
566 class News(TemplateView):
567 template_name = 'news.html'
568 def get_context_data(self, **kwargs):
569 context = super(News, self).get_context_data(**kwargs)
570 context['focus'] = NewsItem.objects.exclude(date__gt=date.today() # publication date
571 ).exclude(expiration_date__lt=date.today() # expiration date
572 ).filter(got_focus__isnull=False
573 ).select_related('category').order_by('-date')[:10]
574 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
577 news = News.as_view()
580 class Agenda(TemplateView):
581 template_name = 'agenda.html'
582 def get_context_data(self, **kwargs):
583 context = super(Agenda, self).get_context_data(**kwargs)
584 context['agenda'] = NewsItem.objects.exclude(date__gt=date.today()).filter(
585 event_date__gte=date.today()).order_by('date')[:20]
586 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
587 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
590 agenda = Agenda.as_view()
593 class AgendaByMonth(MonthArchiveView):
594 template_name = 'agenda.html'
595 queryset = NewsItem.objects.filter(event_date__isnull=False)
597 date_field = 'event_date'
600 def get_context_data(self, **kwargs):
601 context = super(AgendaByMonth, self).get_context_data(**kwargs)
602 context['agenda'] = context['object_list']
603 context['news'] = NewsItem.objects.all().order_by('-date')
606 agenda_by_month = AgendaByMonth.as_view()
609 class Emissions(TemplateView):
610 template_name = 'emissions.html'
612 def get_context_data(self, **kwargs):
613 context = super(Emissions, self).get_context_data(**kwargs)
614 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
615 context['categories'] = Category.objects.all()
618 emissions = Emissions.as_view()
620 class EmissionsArchives(TemplateView):
621 template_name = 'emissions/archives.html'
623 def get_context_data(self, **kwargs):
624 context = super(EmissionsArchives, self).get_context_data(**kwargs)
625 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
626 context['categories'] = Category.objects.all()
628 emissionsArchives = EmissionsArchives.as_view()
631 class Listen(TemplateView):
632 template_name = 'listen.html'
634 def get_context_data(self, **kwargs):
635 context = super(Listen, self).get_context_data(**kwargs)
636 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
637 podcastable=True, got_focus__isnull=False) \
638 .select_related().extra(select={
639 'first_diffusion': 'emissions_diffusion.datetime', },
640 select_params=(False, True),
641 where=['''datetime = (SELECT MIN(datetime)
642 FROM emissions_diffusion
643 WHERE episode_id = emissions_episode.id)'''],
644 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
645 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
647 .select_related().extra(select={
648 'first_diffusion': 'emissions_diffusion.datetime', },
649 select_params=(False, True),
650 where=['''datetime = (SELECT MIN(datetime)
651 FROM emissions_diffusion
652 WHERE episode_id = emissions_episode.id)'''],
653 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct()
658 listen = Listen.as_view()
660 @cache_control(max_age=15)
663 if datetime.now() < datetime(2019, 7, 30, 17, 0):
664 class FakeNonstop(object):
665 title = 'Le festival arrive, découvrez déjà la musique !'
666 d = {'title': 'XXX', 'nonstop': FakeNonstop()}
667 #return JsonResponse({'data': {'emission': {'title': 'À partir du 31 juillet 18h', 'url': '/'}}})
668 elif date.today() >= date(2019, 8, 5):
669 return JsonResponse({'data': {'emission': {'title': "À l'année prochaine, découvrez les podcasts !", 'url': '/'}}})
674 'title': d['episode'].title,
675 'url': d['episode'].get_absolute_url()
677 if d.get('emission'):
679 if d['emission'].chat_open:
680 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
682 'title': d['emission'].title,
683 'url': d['emission'].get_absolute_url(),
688 playing_txt = os.path.join(settings.MEDIA_ROOT, 'playing.txt')
689 if os.path.exists(playing_txt):
690 track_title = open(playing_txt).read().strip()
691 if len(track_title) < 6:
695 'title': d['nonstop'].title,
698 d['track_title'] = track_title
699 elif d.get('emission') and not d.get('episode') and track_title:
700 # live emission, if there's a track playing, and no known episode,
703 'title': track_title,
704 'url': d['emission']['url'],
707 if d.get('current_slot'):
708 del d['current_slot']
709 return JsonResponse({'data': d})
712 class NewsItemDetailView(DetailView):
715 newsitem = NewsItemDetailView.as_view()
717 class RssCustomPodcastsFeed(Rss201rev2Feed):
718 def add_root_elements(self, handler):
719 super(RssCustomPodcastsFeed, self).add_root_elements(handler)
720 emission = self.feed.get('emission')
721 if emission and emission.image and emission.image.url:
722 image_url = emission.image.url
724 image_url = '/static/img/logo-panik-500.png'
725 image_url = urlparse.urljoin(self.feed['link'], image_url)
726 handler.startElement('image', {})
728 handler.addQuickElement('title', emission.title)
730 handler.addQuickElement('title', 'Radio Esperanzah!')
731 handler.addQuickElement('url', image_url)
732 handler.endElement('image')
733 handler.addQuickElement('itunes:explicit', 'no') # invidividual items will get their own value
734 handler.addQuickElement('itunes:image', None, {'href': image_url})
736 if emission.subtitle:
737 handler.addQuickElement('itunes:subtitle', emission.subtitle)
738 for category in emission.categories.all():
739 if category.itunes_category:
740 handler.addQuickElement('itunes:category', None, {'text': category.itunes_category})
742 handler.addQuickElement('itunes:author', emission.title)
743 handler.startElement('itunes:owner', {})
745 handler.addQuickElement('itunes:email', emission.email)
746 handler.addQuickElement('itunes:name', emission.title)
747 handler.endElement('itunes:owner')
749 handler.addQuickElement('itunes:author', 'Radio Esperanzah!')
750 handler.startElement('itunes:owner', {})
751 handler.addQuickElement('itunes:email', 'radio@esperanzah.be')
752 handler.addQuickElement('itunes:name', 'Radio Esperanzah!')
753 handler.endElement('itunes:owner')
755 def root_attributes(self):
756 attrs = super(RssCustomPodcastsFeed, self).root_attributes()
757 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
758 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
761 def add_item_elements(self, handler, item):
762 super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
764 for tag in item.get('tags') or []:
765 handler.addQuickElement('dc:subject', tag)
766 if tag == 'explicit':
769 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
770 handler.addQuickElement('itunes:explicit', explicit)
771 episode = item.get('episode')
772 if episode and episode.image and episode.image.url:
773 image_url = urlparse.urljoin(self.feed['link'], episode.image.url)
774 handler.addQuickElement('itunes:image', None, {'href': image_url})
775 soundfile = item.get('soundfile')
776 if soundfile.duration:
777 handler.addQuickElement('itunes:duration', '%02d:%02d:%02d' % (
778 soundfile.duration / 3600,
779 soundfile.duration % 3600 / 60,
780 soundfile.duration % 60))
783 class PodcastsFeed(Feed):
784 title = 'Radio Esperanzah! - Podcasts'
786 description_template = 'feed/soundfile.html'
787 feed_type = RssCustomPodcastsFeed
790 return SoundFile.objects.select_related().filter(
791 podcastable=True).order_by('-creation_timestamp')[:20]
793 def item_title(self, item):
795 return '%s - %s' % (item.title, item.episode.title)
796 return '%s - %s' % (item.episode.emission.title, item.episode.title)
798 def item_link(self, item):
799 return item.episode.get_absolute_url()
801 def item_enclosure_url(self, item):
802 current_site = Site.objects.get(id=settings.SITE_ID)
803 return add_domain(current_site.domain, item.get_format_url('mp3'))
805 def item_enclosure_length(self, item):
806 sound_path = item.get_format_path('mp3')
808 return os.stat(sound_path)[stat.ST_SIZE]
812 def item_enclosure_mime_type(self, item):
815 def item_pubdate(self, item):
816 return item.creation_timestamp
818 def item_extra_kwargs(self, item):
819 return {'tags': [x.name for x in item.episode.tags.all()],
821 'episode': item.episode}
823 podcasts_feed = PodcastsFeed()
826 class RssNewsFeed(Feed):
827 title = 'Radio Esperanzah!'
829 description_template = 'feed/newsitem.html'
832 return NewsItem.objects.order_by('-date')[:20]
834 rss_news_feed = RssNewsFeed()
836 class Atom1FeedWithBaseXml(Atom1Feed):
837 def root_attributes(self):
838 root_attributes = super(Atom1FeedWithBaseXml, self).root_attributes()
839 scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.feed['feed_url'])
840 root_attributes['xml:base'] = urlparse.urlunparse((scheme, netloc, '/', params, query, fragment))
841 return root_attributes
843 class AtomNewsFeed(RssNewsFeed):
844 feed_type = Atom1FeedWithBaseXml
846 atom_news_feed = AtomNewsFeed()
849 class EmissionPodcastsFeed(PodcastsFeed):
850 description_template = 'feed/soundfile.html'
851 feed_type = RssCustomPodcastsFeed
853 def __call__(self, request, *args, **kwargs):
854 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
855 return super(EmissionPodcastsFeed, self).__call__(request, *args, **kwargs)
859 return self.emission.title
863 return reverse('emission-view', kwargs={'slug': self.emission.slug})
865 def feed_extra_kwargs(self, obj):
866 return {'emission': self.emission}
869 return SoundFile.objects.select_related().filter(
871 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
873 emission_podcasts_feed = EmissionPodcastsFeed()
876 class Party(TemplateView):
877 template_name = 'party.html'
879 def get_context_data(self, **kwargs):
880 context = super(Party, self).get_context_data(**kwargs)
881 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
884 focus.newsitem = NewsItem.objects.exclude(
885 image__isnull=True).exclude(image__exact='').order_by('?')[0]
886 elif t == 'emission':
887 focus.emission = Emission.objects.exclude(
888 image__isnull=True).exclude(image__exact='').order_by('?')[0]
890 focus.episode = Episode.objects.exclude(
891 image__isnull=True).exclude(image__exact='').order_by('?')[0]
892 elif t == 'soundfile':
893 focus.soundfile = SoundFile.objects.exclude(
894 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
896 context['focus'] = focus
900 party = Party.as_view()
904 class Chat(DetailView, EmissionMixin):
906 template_name = 'chat.html'
908 chat = cache_control(max_age=15)(Chat.as_view())
912 class ArchivesView(TemplateView):
913 template_name = 'archives.html'
915 def get_context_data(self, **kwargs):
916 context = super(ArchivesView, self).get_context_data(**kwargs)
917 context['diffusions'] = Diffusion.objects.filter(episode__soundfile__isnull=False).distinct().order_by('-datetime')
920 archives = ArchivesView.as_view()