7 from datetime import date, datetime, timedelta
9 from django.conf import settings
10 from django.contrib.sites.models import Site
11 from django.contrib.syndication.views import Feed, add_domain
12 from django.core.paginator import Paginator
13 from django.http import Http404, JsonResponse
14 from django.urls import reverse
15 from django.utils.encoding import force_text, python_2_unicode_compatible
16 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
17 from django.views.decorators.cache import cache_control
18 from django.views.decorators.csrf import csrf_exempt
19 from django.views.generic import RedirectView
20 from django.views.generic.base import TemplateView
21 from django.views.generic.dates import MonthArchiveView, _date_from_string
22 from django.views.generic.detail import DetailView
23 from emissions.models import (
35 from emissions.utils import period_program, whatsonair
36 from emissions.views import EmissionEpisodeMixin
37 from haystack.query import SearchQuerySet
38 from newsletter.forms import SubscribeForm
39 from nonstop.models import SomaLogLine
40 from nonstop.utils import get_current_nonstop_track
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 if settings.USE_AGENDA_ONLY_FIELD:
59 episodes_queryset = episodes_queryset.exclude(agenda_only=True)
61 context['episodes'] = (
62 episodes_queryset.extra(
64 'first_diffusion': 'emissions_diffusion.datetime',
66 select_params=(False, True),
68 '''datetime = (SELECT MIN(datetime)
69 FROM emissions_diffusion
70 WHERE episode_id = emissions_episode.id
71 AND datetime <= CURRENT_TIMESTAMP)'''
73 tables=['emissions_diffusion'],
75 .order_by('-first_diffusion')
79 context['all_episodes'] = (
80 episodes_queryset.extra(
82 'first_diffusion': 'emissions_diffusion.datetime',
84 select_params=(False, True),
86 '''datetime = (SELECT MIN(datetime)
87 FROM emissions_diffusion
88 WHERE episode_id = emissions_episode.id)'''
90 tables=['emissions_diffusion'],
92 .order_by('-first_diffusion')
96 context['futurEpisodes'] = (
97 episodes_queryset.extra(
99 'first_diffusion': 'emissions_diffusion.datetime',
101 select_params=(False, True),
103 '''datetime = (SELECT MIN(datetime)
104 FROM emissions_diffusion
105 WHERE episode_id = emissions_episode.id
106 AND datetime > CURRENT_TIMESTAMP)'''
108 tables=['emissions_diffusion'],
110 .order_by('first_diffusion')
114 # get all related soundfiles in a single query
116 if episode_ids is not None:
117 for episode_id in episode_ids:
118 soundfiles[episode_id] = None
120 for episode in Episode.objects.filter(emission=emission):
121 soundfiles[episode.id] = None
123 for soundfile in SoundFile.objects.select_related().filter(
124 podcastable=True, fragment=False, episode__emission=emission
126 soundfiles[soundfile.episode_id] = soundfile
128 Episode.set_prefetched_soundfiles(soundfiles)
130 # context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
135 class EmissionDetailView(DetailView, EmissionMixin):
138 def get_context_data(self, **kwargs):
139 context = super().get_context_data(**kwargs)
140 context['schedules'] = (
141 Schedule.objects.select_related().filter(emission=self.object).order_by('rerun', 'datetime')
144 NewsItem.objects.all()
145 .filter(emission=self.object.id)
146 .exclude(expiration_date__lt=date.today()) # expiration date
147 .exclude(date__lt=date.today() - timedelta(days=60))
148 .order_by('-date')[:3]
151 nonstop_object = Nonstop.objects.get(slug=self.object.slug)
152 except Nonstop.DoesNotExist:
156 dates = [today - timedelta(days=x) for x in range(7)]
157 if datetime.now().time() < nonstop_object.start:
159 context['nonstop'] = nonstop_object
160 context['nonstop_dates'] = dates
161 context.update(self.get_emission_context(self.object))
165 emission = EmissionDetailView.as_view()
168 class EpisodeDetailView(EmissionEpisodeMixin, DetailView, EmissionMixin):
171 def get_context_data(self, **kwargs):
172 context = super().get_context_data(**kwargs)
173 context['diffusions'] = (
174 Diffusion.objects.select_related().filter(episode=self.object.id).order_by('datetime')
177 context['emission'] = context['episode'].emission
178 except Emission.DoesNotExist:
180 if self.kwargs.get('emission_slug') != context['emission'].slug:
182 context.update(self.get_emission_context(context['emission']))
183 context['topik_pages'] = [x.page for x in ItemTopik.objects.filter(episode=self.object)]
187 episode = EpisodeDetailView.as_view()
190 class NonstopPlaylistView(TemplateView):
191 template_name = 'nonstop_playlist.html'
193 def get_context_data(self, **kwargs):
194 context = super().get_context_data(**kwargs)
196 context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
197 except Emission.DoesNotExist:
200 context['date'] = date(int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')))
203 context['future'] = context['date'] >= date.today()
205 nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
207 int(kwargs.get('year')),
208 int(kwargs.get('month')),
209 int(kwargs.get('day')),
210 nonstop_object.start.hour,
211 nonstop_object.start.minute,
214 int(kwargs.get('year')),
215 int(kwargs.get('month')),
216 int(kwargs.get('day')),
217 nonstop_object.end.hour,
218 nonstop_object.end.minute,
221 end = end + timedelta(days=1)
222 context['tracks'] = SomaLogLine.objects.filter(
223 play_timestamp__gte=start, play_timestamp__lte=end, on_air=True
228 nonstop_playlist = NonstopPlaylistView.as_view()
231 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
233 template_name = 'emissions/episodes.html'
235 def get_context_data(self, **kwargs):
236 context = super().get_context_data(**kwargs)
237 context['schedules'] = (
238 Schedule.objects.select_related().filter(emission=self.object).order_by('rerun', 'datetime')
241 for schedule in context['schedules']:
244 count_per_month += bin(schedule.weeks).count('1')
246 context['count_per_month'] = count_per_month
248 context['search_query'] = self.request.GET.get('q')
249 if context['search_query']:
254 .filter(emission_slug_exact=self.object.slug, text=context['search_query'])
256 episode_ids = [x.pk for x in sqs]
260 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
264 emissionEpisodes = EmissionEpisodesDetailView.as_view()
267 class SoundFileEmbedView(DetailView):
269 template_name = 'soundfiles/embed.html'
271 def get_context_data(self, **kwargs):
272 context = super().get_context_data(**kwargs)
273 if self.kwargs.get('episode_slug') != self.object.episode.slug:
275 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
277 context['episode'] = self.object.episode
281 soundfile_embed = SoundFileEmbedView.as_view()
284 class EpisodeEmbedRedirect(RedirectView):
285 def get_redirect_url(self, **kwargs):
287 soundfile = SoundFile.objects.get(
288 episode__slug=kwargs['episode_slug'],
289 episode__emission__slug=kwargs['emission_slug'],
292 except SoundFile.DoesNotExist:
294 kwargs['pk'] = soundfile.id
295 return reverse('soundfile-embed-view', kwargs=kwargs)
298 episode_embed_redirect = EpisodeEmbedRedirect.as_view()
301 class SoundFileDialogEmbedView(DetailView):
303 template_name = 'soundfiles/dialog-embed.html'
305 def get_context_data(self, **kwargs):
306 context = super().get_context_data(**kwargs)
307 if self.kwargs.get('episode_slug') != self.object.episode.slug:
309 if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
311 context['episode'] = self.object.episode
315 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
318 class ProgramView(TemplateView):
319 template_name = 'program.html'
321 def get_context_data(self, year=None, week=None, **kwargs):
322 context = super().get_context_data(**kwargs)
324 context['weekday'] = datetime.today().weekday()
326 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
327 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
328 if context['week'] > 53:
330 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
331 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
336 program = ProgramView.as_view()
339 @python_2_unicode_compatible
346 def __init__(self, i, j):
351 def add_schedule(self, schedule):
352 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
353 self.time_label = '%02d:%02d-%02d:%02d' % (
354 schedule.datetime.hour,
355 schedule.datetime.minute,
359 self.schedules.append(schedule)
361 def sorted_schedules(self):
362 return sorted(self.schedules, key=lambda x: x.week_sort_key())
366 return ', '.join([x.emission.title for x in self.schedules])
370 def __eq__(self, other):
371 return force_text(self) == force_text(other) and self.time_label == other.time_label
374 class Grid(TemplateView):
375 template_name = 'grid.html'
377 def get_context_data(self, **kwargs):
378 context = super().get_context_data(**kwargs)
380 nb_lines = 2 * 24 # the cells are half hours
383 times = ['%02d:%02d' % (x / 2, x % 2 * 30) for x in range(nb_lines)]
384 # start grid after the night programs
386 times[2 * Schedule.DAY_HOUR_START + (1 if Schedule.DAY_MINUTE_START else 0) :]
387 + times[: 2 * Schedule.DAY_HOUR_START + (1 if Schedule.DAY_MINUTE_START else 0)]
391 for nonstop in Nonstop.objects.all():
392 if nonstop.start == nonstop.end:
394 if nonstop.start < nonstop.end:
397 nonstop.start.hour + nonstop.start.minute / 60.0,
398 nonstop.end.hour + nonstop.end.minute / 60.0,
399 nonstop.get_public_label(),
408 nonstop.start.hour + nonstop.start.minute / 60.0,
410 nonstop.get_public_label(),
418 nonstop.end.hour + nonstop.end.minute / 60.0,
419 nonstop.get_public_label(),
426 for i in range(nb_lines):
429 grid[-1].append(TimeCell(i, j))
432 nonstop = [x for x in nonstops if i >= x[0] * 2 and i < x[1] * 2][0]
434 nonstop = [0, 24, '', '', None]
435 for time_cell in grid[-1]:
436 time_cell.nonstop = nonstop[2]
437 time_cell.nonstop_slug = nonstop[3]
438 time_cell.redirect_path = nonstop[4].redirect_path if nonstop[4] else None
439 if nonstop[1] == Schedule.DAY_HOUR_START + Schedule.DAY_MINUTE_START / 60:
440 # the one ending at 4:30am will be cut down, so we inscribe
441 # its duration manually
442 time_cell.time_label = '%02d:00-%02d:%02d' % (
445 Schedule.DAY_MINUTE_START,
449 Schedule.objects.prefetch_related('emission__categories').select_related().order_by('datetime')
451 row_start = schedule.datetime.hour * 2 + int(math.ceil(schedule.datetime.minute / 30))
452 if schedule.get_duration() < 30:
453 # special case for an emission during 12:45-13:00
454 row_start = schedule.datetime.hour * 2 + int(math.floor(schedule.datetime.minute / 30))
455 day_no = schedule.get_weekday()
457 for step in range(int(math.ceil(schedule.get_duration() / 30.0))):
458 if grid[(row_start + step) % nb_lines][day_no] is None:
459 grid[(row_start + step) % nb_lines][day_no] = TimeCell()
460 grid[(row_start + step) % nb_lines][day_no].add_schedule(schedule)
462 # start grid after the night programs
464 grid[2 * Schedule.DAY_HOUR_START + (1 if Schedule.DAY_MINUTE_START else 0) :]
465 + grid[: 2 * Schedule.DAY_HOUR_START + (1 if Schedule.DAY_MINUTE_START else 0)]
468 # look for the case where the same emission has different schedules for
469 # the same time cell, for example if it lasts one hour the first week,
470 # and two hours the third week.
471 for i in range(nb_lines):
472 grid[i] = [x for x in grid[i] if x is not None]
473 for j, cell in enumerate(grid[i]):
474 if grid[i][j] is None:
476 if len(grid[i][j].schedules) > 1:
477 time_cell_emissions = {}
478 for schedule in grid[i][j].schedules:
479 if not schedule.emission.id in time_cell_emissions:
480 time_cell_emissions[schedule.emission.id] = []
481 time_cell_emissions[schedule.emission.id].append(schedule)
482 for schedule_list in time_cell_emissions.values():
483 if len(schedule_list) == 1:
485 # here it is, same cell, same emission, several
487 schedule_list.sort(key=lambda x: x.get_duration())
489 schedule = schedule_list[0]
490 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
491 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
492 schedule.datetime.hour,
493 schedule.datetime.minute,
498 schedule_list.sort(key=lambda x: x.weeks)
499 for schedule in schedule_list[1:]:
500 grid[i][j].schedules.remove(schedule)
501 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
502 if schedule_list[0].get_duration() == schedule.get_duration():
503 # same duration, append week info
504 schedule_list[0].time_label_extra = ', %s' % (schedule.weeks_string,)
506 # different durations, also append other
508 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
511 schedule.weeks_string,
517 # 1st thing is to merge cells on the same line, this will mostly catch
518 # consecutive nonstop cells
519 for i in range(nb_lines):
520 for j, cell in enumerate(grid[i]):
521 if grid[i][j] is None:
525 # if the cells are identical, they are removed from the
526 # grid, and current cell width is increased
527 while grid[i][j + t] == cell:
529 grid[i][j + t] = None
534 # once we're done we remove empty cells
535 grid[i] = [x for x in grid[i] if x is not None]
537 # 2nd thing is to merge cells vertically, this is emissions that last
538 # for more than 30 minutes
539 for i in range(nb_lines):
540 grid[i] = [x for x in grid[i] if x is not None]
541 for j, cell in enumerate(grid[i]):
542 if grid[i][j] is None:
547 # we look if the next time cell has the same emissions
550 for bj, x in enumerate(grid[i + cell.h])
551 if x == cell and x.y == cell.y and x.w == cell.w
554 # if the cell was identical, we remove it and
555 # increase current cell height
556 bj, same_cell_below = same_cell_below[0]
557 del grid[i + cell.h][bj]
560 # if the cell is different, we have a closer look
561 # to it, so we can remove emissions that will
562 # already be mentioned in the current cell.
565 # - 7am30, seuls contre tout, 1h30
566 # - 8am, du pied gauche & la voix de la rue, 1h
567 # should produce: (this is case A)
569 # | seuls contre tout |
570 # |---------------------|
573 # | la voix de la rue |
575 # On the other hand, if all three emissions started
576 # at 7am30, we want: (this is case B)
578 # | seuls contre tout |
580 # | la voix de la rue |
581 # that is we merge all of them, ignoring the fact
582 # that the other emissions will stop at 8am30
583 current_cell_schedules = set(grid[i][j].schedules)
584 current_cell_emissions = {x.emission for x in current_cell_schedules}
586 while True and current_cell_schedules:
587 same_cell_below = [x for x in grid[i + cursor] if x.y == grid[i][j].y]
588 if not same_cell_below:
591 same_cell_below = same_cell_below[0]
592 same_cell_below_emissions = {x.emission for x in same_cell_below.schedules}
594 if current_cell_emissions.issubset(same_cell_below_emissions):
595 # this handles case A (see comment above)
596 for schedule in current_cell_schedules:
597 if schedule in same_cell_below.schedules:
598 same_cell_below.schedules.remove(schedule)
599 elif same_cell_below_emissions and current_cell_emissions.issuperset(
600 same_cell_below_emissions
602 # this handles case B (see comment above)
603 # we set the cell time label to the longest
605 grid[i][j].time_label = same_cell_below.time_label
606 # then we sort emissions so the longest are
608 grid[i][j].schedules.sort(key=lambda x: -x.get_duration())
609 # then we add individual time labels to the
611 for schedule in current_cell_schedules:
612 if schedule not in same_cell_below.schedules:
613 end_time = schedule.datetime + timedelta(
614 minutes=schedule.get_duration()
616 schedule.time_label = '%02d:%02d-%02d:%02d' % (
617 schedule.datetime.hour,
618 schedule.datetime.minute,
623 grid[i + cursor].remove(same_cell_below)
624 elif same_cell_below_emissions and current_cell_emissions.intersection(
625 same_cell_below_emissions
627 same_cell_below.schedules = [
629 for x in same_cell_below.schedules
630 if x.emission not in current_cell_emissions or x.get_duration() < 30
637 # cut late night hours
641 context['grid'] = grid
642 context['times'] = times
643 context['categories'] = Category.objects.all()
644 # dates from Monday to Sunday
645 context['weekdays'] = [date(2018, 1, x) for x in range(1, 8)]
650 grid = Grid.as_view()
653 class Home(TemplateView):
654 template_name = 'home.html'
656 def get_context_data(self, **kwargs):
657 context = super().get_context_data(**kwargs)
658 context['emissions'] = Emission.objects.filter(archived=False).order_by('-creation_timestamp')[
659 : settings.HOME_EMISSIONS_COUNT
661 context['newsitems'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')[
662 : settings.HOME_NEWSITEMS_COUNT
665 context['soundfiles'] = (
666 SoundFile.objects.prefetch_related('episode__emission__categories')
667 .filter(podcastable=True, fragment=False)
671 'first_diffusion': 'emissions_diffusion.datetime',
673 select_params=(False, True),
675 '''datetime = (SELECT MIN(datetime)
676 FROM emissions_diffusion
677 WHERE episode_id = emissions_episode.id)'''
679 tables=['emissions_diffusion'],
681 .order_by('-creation_timestamp')
682 .distinct()[: settings.HOME_PODCASTS_COUNT]
685 context['newsletter_form'] = SubscribeForm()
690 home = Home.as_view()
693 class NewsItemView(DetailView):
696 def get_context_data(self, **kwargs):
697 context = super().get_context_data(**kwargs)
698 context['categories'] = NewsCategory.objects.all()
699 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
700 context['topik_pages'] = [x.page for x in ItemTopik.objects.filter(newsitem=self.object)]
704 newsitemview = NewsItemView.as_view()
707 class News(TemplateView):
708 template_name = 'news.html'
710 def get_context_data(self, **kwargs):
711 context = super().get_context_data(**kwargs)
713 NewsItem.objects.exclude(date__gt=date.today()) # publication date
714 .exclude(expiration_date__lt=date.today()) # expiration date
715 .filter(got_focus__isnull=False)
716 .select_related('category')
717 .order_by('-date')[:10]
719 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
720 context['news_not_expired'] = (
721 NewsItem.objects.exclude(date__gt=date.today())
722 .exclude(expiration_date__lt=date.today())
728 news = News.as_view()
731 class Agenda(TemplateView):
732 template_name = 'agenda.html'
734 def get_context_data(self, **kwargs):
735 context = super().get_context_data(**kwargs)
736 context['agenda'] = (
737 NewsItem.objects.exclude(date__gt=date.today())
738 .filter(event_date__gte=date.today())
739 .order_by('event_date')[:20]
741 context['news'] = NewsItem.objects.exclude(date__gt=date.today()).order_by('-date')
742 context['previous_month'] = datetime.today().replace(day=1) - timedelta(days=2)
746 agenda = Agenda.as_view()
749 class AgendaByMonth(MonthArchiveView):
750 template_name = 'agenda.html'
751 queryset = NewsItem.objects.filter(event_date__isnull=False)
753 date_field = 'event_date'
756 def get_context_data(self, **kwargs):
757 context = super().get_context_data(**kwargs)
758 context['agenda'] = context['object_list']
759 context['news'] = NewsItem.objects.all().order_by('-date')
763 agenda_by_month = AgendaByMonth.as_view()
766 class Emissions(TemplateView):
767 template_name = 'emissions.html'
769 def get_queryset(self):
770 return Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
772 def get_context_data(self, **kwargs):
773 context = super().get_context_data(**kwargs)
774 context['emissions'] = self.get_queryset()
775 context['categories'] = Category.objects.all()
779 emissions = Emissions.as_view()
782 class EmissionsArchives(TemplateView):
783 template_name = 'emissions/archives.html'
785 def get_context_data(self, **kwargs):
786 context = super().get_context_data(**kwargs)
787 context['emissions'] = (
788 Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
790 context['categories'] = Category.objects.all()
794 emissionsArchives = EmissionsArchives.as_view()
797 class Listen(TemplateView):
798 template_name = 'listen.html'
800 def get_context_data(self, **kwargs):
801 context = super().get_context_data(**kwargs)
803 SoundFile.objects.prefetch_related('episode__emission__categories')
804 .filter(podcastable=True, got_focus__isnull=False)
808 'first_diffusion': 'emissions_diffusion.datetime',
810 select_params=(False, True),
812 '''datetime = (SELECT MIN(datetime)
813 FROM emissions_diffusion
814 WHERE episode_id = emissions_episode.id)'''
816 tables=['emissions_diffusion'],
818 .order_by('-first_diffusion')
821 context['soundfiles'] = (
822 SoundFile.objects.prefetch_related('episode__emission__categories')
823 .filter(podcastable=True)
827 'first_diffusion': 'emissions_diffusion.datetime',
829 select_params=(False, True),
831 '''datetime = (SELECT MIN(datetime)
832 FROM emissions_diffusion
833 WHERE episode_id = emissions_episode.id)'''
835 tables=['emissions_diffusion'],
837 .order_by('-creation_timestamp')
844 listen = Listen.as_view()
847 @cache_control(max_age=15)
852 d['episode'] = {'title': d['episode'].title, 'url': d['episode'].get_absolute_url()}
853 if d.get('emission'):
855 if d['emission'].chat_open:
856 chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
858 'title': d['emission'].title,
859 'slug': d['emission'].slug,
860 'url': d['emission'].get_absolute_url(),
864 redirect_path = d['nonstop'].redirect_path
866 'title': d['nonstop'].get_public_label(),
867 'slug': d['current_slot'].slug,
870 d['nonstop']['url'] = redirect_path
871 today = datetime.today()
872 d['nonstop']['playlist_url'] = reverse(
876 'month': today.month,
878 'slug': d['current_slot'].slug,
881 d.update(get_current_nonstop_track())
882 if d.get('current_slot'):
883 del d['current_slot']
884 return JsonResponse({'data': d})
887 class NewsItemDetailView(DetailView):
891 newsitem = NewsItemDetailView.as_view()
894 class RssCustomPodcastsFeed(Rss201rev2Feed):
895 def add_root_elements(self, handler):
896 super().add_root_elements(handler)
897 emission = self.feed.get('emission')
898 if emission and emission.image and emission.image.url:
899 image_url = emission.image.url
901 image_url = settings.PODCASTS_DEFAULT_IMAGE_PATH
902 image_url = urllib.parse.urljoin(self.feed['link'], image_url)
903 handler.startElement('image', {})
905 handler.addQuickElement('title', emission.title)
907 handler.addQuickElement('title', settings.RADIO_NAME)
908 handler.addQuickElement('url', image_url)
909 handler.endElement('image')
910 handler.addQuickElement('itunes:explicit', 'no') # invidividual items will get their own value
911 handler.addQuickElement('itunes:image', None, {'href': image_url})
913 if emission.subtitle:
914 handler.addQuickElement('itunes:subtitle', emission.subtitle)
915 for category in emission.categories.all():
916 if category.itunes_category:
917 handler.addQuickElement('itunes:category', None, {'text': category.itunes_category})
919 handler.addQuickElement('itunes:author', settings.RADIO_NAME)
920 handler.startElement('itunes:owner', {})
921 if emission and emission.email:
922 handler.addQuickElement('itunes:email', emission.email)
924 handler.addQuickElement('itunes:email', settings.DEFAULT_FROM_EMAIL)
925 handler.addQuickElement('itunes:name', settings.RADIO_NAME)
926 handler.endElement('itunes:owner')
928 def root_attributes(self):
929 attrs = super().root_attributes()
930 attrs['xmlns:dc'] = 'http://purl.org/dc/elements/1.1/'
931 attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
934 def add_item_elements(self, handler, item):
935 super().add_item_elements(handler, item)
937 for tag in item.get('tags') or []:
938 handler.addQuickElement('dc:subject', tag)
939 if tag == 'explicit':
942 handler.addQuickElement('itunes:keywords', ','.join(item.get('tags')))
943 handler.addQuickElement('itunes:explicit', explicit)
944 episode = item.get('episode')
945 if episode and episode.image and episode.image.url:
946 image_url = urllib.parse.urljoin(self.feed['link'], episode.image.url)
947 handler.addQuickElement('itunes:image', None, {'href': image_url})
948 soundfile = item.get('soundfile')
949 if soundfile.duration:
950 handler.addQuickElement(
953 % (soundfile.duration / 3600, soundfile.duration % 3600 / 60, soundfile.duration % 60),
957 class PodcastsFeed(Feed):
958 title = '%s - Podcasts' % settings.RADIO_NAME
960 description_template = 'feed/soundfile.html'
961 feed_type = RssCustomPodcastsFeed
963 def get_feed(self, obj, request):
964 self.request = request
965 return super().get_feed(obj, request)
968 def description(self):
969 return settings.RADIO_META_DESCRIPTION
973 SoundFile.objects.select_related()
974 .filter(podcastable=True)
975 .exclude(file__isnull=True)
977 .order_by('-creation_timestamp')[:50]
980 def item_title(self, item):
982 return '[%s] %s - %s' % (item.episode.emission.title, item.title, item.episode.title)
983 return '[%s] %s' % (item.episode.emission.title, item.episode.title)
985 def item_link(self, item):
987 return item.episode.get_absolute_url() + '#%s' % item.id
988 return item.episode.get_absolute_url()
990 def item_enclosure_url(self, item):
991 current_site = Site.objects.get(id=settings.SITE_ID)
992 return add_domain(current_site.domain, item.get_format_url('mp3'), self.request.is_secure())
994 def item_enclosure_length(self, item):
995 sound_path = item.get_format_path('mp3')
997 return os.stat(sound_path)[stat.ST_SIZE]
1001 def item_enclosure_mime_type(self, item):
1004 def item_pubdate(self, item):
1005 return item.creation_timestamp
1007 def item_extra_kwargs(self, item):
1008 return {'tags': [x.name for x in item.episode.tags.all()], 'soundfile': item, 'episode': item.episode}
1011 podcasts_feed = PodcastsFeed()
1014 class RssNewsFeed(Feed):
1015 title = settings.RADIO_NAME
1017 description_template = 'feed/newsitem.html'
1020 return NewsItem.objects.order_by('-date')[:20]
1023 rss_news_feed = RssNewsFeed()
1026 class Atom1FeedWithBaseXml(Atom1Feed):
1027 def root_attributes(self):
1028 root_attributes = super().root_attributes()
1029 scheme, netloc, path, params, query, fragment = urllib.parse.urlparse(self.feed['feed_url'])
1030 root_attributes['xml:base'] = urllib.parse.urlunparse((scheme, netloc, '/', params, query, fragment))
1031 return root_attributes
1034 class AtomNewsFeed(RssNewsFeed):
1035 feed_type = Atom1FeedWithBaseXml
1038 atom_news_feed = AtomNewsFeed()
1041 class EmissionPodcastsFeed(PodcastsFeed):
1042 description_template = 'feed/soundfile.html'
1043 feed_type = RssCustomPodcastsFeed
1045 def __call__(self, request, *args, **kwargs):
1046 self.emission = Emission.objects.get(slug=kwargs.get('slug'))
1047 return super().__call__(request, *args, **kwargs)
1049 def item_title(self, item):
1051 return '%s - %s' % (item.title, item.episode.title)
1052 return item.episode.title
1056 return self.emission.title
1059 def description(self):
1060 return self.emission.subtitle
1064 return reverse('emission-view', kwargs={'slug': self.emission.slug})
1066 def feed_extra_kwargs(self, obj):
1067 return {'emission': self.emission}
1071 SoundFile.objects.select_related()
1072 .filter(podcastable=True, episode__emission__slug=self.emission.slug)
1073 .order_by('-creation_timestamp')[:50]
1077 emission_podcasts_feed = EmissionPodcastsFeed()
1080 class Party(TemplateView):
1081 template_name = 'party.html'
1083 def get_context_data(self, **kwargs):
1084 context = super().get_context_data(**kwargs)
1085 t = random.choice(['newsitem'] * 2 + ['emission'] * 3 + ['soundfile'] * 1 + ['episode'] * 2)
1089 NewsItem.objects.exclude(image__isnull=True).exclude(image__exact='').order_by('?')[0]
1091 elif t == 'emission':
1093 Emission.objects.exclude(image__isnull=True).exclude(image__exact='').order_by('?')[0]
1095 elif t == 'episode':
1097 Episode.objects.exclude(image__isnull=True).exclude(image__exact='').order_by('?')[0]
1099 elif t == 'soundfile':
1101 SoundFile.objects.exclude(episode__image__isnull=True)
1102 .exclude(episode__image__exact='')
1106 context['focus'] = focus
1111 party = Party.as_view()
1114 class Chat(DetailView, EmissionMixin):
1116 template_name = 'chat.html'
1119 chat = cache_control(max_age=15)(Chat.as_view())