]> git.0d.be Git - panikweb-esperanzah.git/blob - panikweb/views.py
add itunes:owner to feed
[panikweb-esperanzah.git] / panikweb / views.py
1 # coding: utf-8
2
3 from datetime import datetime, timedelta, date
4 import math
5 import random
6 import os
7 import stat
8 import time
9
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
22
23 from django.core.paginator import Paginator
24
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
28
29 from haystack.query import SearchQuerySet
30
31 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
32         Schedule, Nonstop, NewsItem, NewsCategory, Focus
33
34 from emissions.utils import whatsonair, period_program
35
36 from newsletter.forms import SubscribeForm
37 from nonstop.utils import get_current_nonstop_track
38 from nonstop.models import SomaLogLine
39
40 from combo.data.models import Page
41 from panikombo.models import ItemTopik
42
43 from . import utils
44
45
46 class EmissionMixin:
47     def get_emission_context(self, emission, episode_ids=None):
48         context = {}
49
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)
55         else:
56             episodes_queryset = episodes_queryset.filter(emission=emission)
57
58         context['episodes'] = \
59                 episodes_queryset.extra(select={
60                         'first_diffusion': 'emissions_diffusion.datetime',
61                         },
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()
69
70         context['futurEpisodes'] = \
71                 episodes_queryset.extra(select={
72                         'first_diffusion': 'emissions_diffusion.datetime',
73                         },
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()
81
82         if emission.archived:
83             current_year = emission.creation_timestamp.replace(month=5, day=1)
84         else:
85             current_year = datetime.now().replace(month=5, day=1).replace(year=2019)
86
87         context['all_episodes'] = episodes_queryset.filter(
88                 creation_timestamp__gt=current_year
89                 ).extra(select={
90                         'first_diffusion': 'emissions_diffusion.datetime',
91                         },
92                         select_params=(False, True),
93                         where=['''datetime = (SELECT MIN(datetime)
94                                                 FROM emissions_diffusion
95                                                WHERE episode_id = emissions_episode.id
96                                              )'''],
97                         tables=['emissions_diffusion'],
98                     ).order_by('first_diffusion').distinct()
99
100         # get all related soundfiles in a single query
101         soundfiles = {}
102         if episode_ids is not None:
103             for episode_id in episode_ids:
104                 soundfiles[episode_id] = None
105         else:
106             for episode in Episode.objects.filter(emission=emission):
107                 soundfiles[episode.id] = None
108
109         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
110                 fragment=False, episode__emission=emission):
111             soundfiles[soundfile.episode_id] = soundfile
112
113         Episode.set_prefetched_soundfiles(soundfiles)
114
115         #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
116
117         return context
118
119
120 class EmissionDetailView(DetailView, EmissionMixin):
121     model = Emission
122
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]
128         try:
129             nonstop_object = Nonstop.objects.get(slug=self.object.slug)
130         except Nonstop.DoesNotExist:
131             pass
132         else:
133             today = date.today()
134             dates = [today - timedelta(days=x) for x in range(7)]
135             if datetime.now().time() < nonstop_object.start:
136                 dates = dates[1:]
137             context['nonstop'] = nonstop_object
138             context['nonstop_dates'] = dates
139         context.update(self.get_emission_context(self.object))
140         return context
141 emission = EmissionDetailView.as_view()
142
143 class EpisodeDetailView(DetailView, EmissionMixin):
144     model = Episode
145
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'])
149
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')
154         try:
155             context['emission'] = context['episode'].emission
156         except Emission.DoesNotExist:
157             raise Http404()
158         if self.kwargs.get('emission_slug') != context['emission'].slug:
159             raise Http404()
160         context.update(self.get_emission_context(context['emission']))
161         context['topiks'] = [x.topik for x in ItemTopik.objects.filter(episode=self.object)]
162         return context
163 episode = EpisodeDetailView.as_view()
164
165
166 class NonstopPlaylistView(TemplateView):
167     template_name = 'nonstop_playlist.html'
168
169     def get_context_data(self, **kwargs):
170         context = super(NonstopPlaylistView, self).get_context_data(**kwargs)
171         try:
172             context['emission'] = Emission.objects.get(slug=kwargs.get('slug'))
173         except Emission.DoesNotExist:
174             raise Http404()
175         context['date'] = date(int(kwargs.get('year')),
176                 int(kwargs.get('month')), int(kwargs.get('day')))
177         context['future'] = (context['date'] >= date.today())
178
179         nonstop_object = Nonstop.objects.get(slug=kwargs.get('slug'))
180         start = datetime(
181                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
182                 nonstop_object.start.hour, nonstop_object.start.minute)
183         end = datetime(
184                 int(kwargs.get('year')), int(kwargs.get('month')), int(kwargs.get('day')),
185                 nonstop_object.end.hour, nonstop_object.end.minute)
186         if end < start:
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()
192         return context
193
194 nonstop_playlist = NonstopPlaylistView.as_view()
195
196 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
197     model = Emission
198     template_name = 'emissions/episodes.html'
199
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')
204
205         context['search_query'] = self.request.GET.get('q')
206         if context['search_query']:
207             # query string
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]
211         else:
212             episode_ids = None
213
214         context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
215         return context
216 emissionEpisodes = EmissionEpisodesDetailView.as_view()
217
218
219 class SoundFileEmbedView(DetailView):
220     model = SoundFile
221     template_name = 'soundfiles/embed.html'
222
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:
226             raise Http404()
227         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
228             raise Http404()
229         context['episode'] = self.object.episode
230         return context
231 soundfile_embed = SoundFileEmbedView.as_view()
232
233
234 class SoundFileDialogEmbedView(DetailView):
235     model = SoundFile
236     template_name = 'soundfiles/dialog-embed.html'
237
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:
241             raise Http404()
242         if self.kwargs.get('emission_slug') != self.object.episode.emission.slug:
243             raise Http404()
244         context['episode'] = self.object.episode
245         return context
246 soundfile_dlg_embed = SoundFileDialogEmbedView.as_view()
247
248
249
250 class ProgramView(TemplateView):
251     template_name = 'program.html'
252
253     def get_context_data(self, year=None, week=None, **kwargs):
254         context = super(ProgramView, self).get_context_data(**kwargs)
255
256         context['weekday'] = datetime.today().weekday()
257
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)
262
263         return context
264
265 program = ProgramView.as_view()
266
267 @python_2_unicode_compatible
268 class TimeCell:
269     nonstop = None
270     w = 1
271     h = 1
272     time_label = None
273
274     def __init__(self, i, j):
275         self.x = i
276         self.y = j
277         self.schedules = []
278
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,
285                 end_time.hour,
286                 end_time.minute)
287         self.schedules.append(schedule)
288
289     def __str__(self):
290         if self.schedules:
291             return ', '.join([x.emission.title for x in self.schedules])
292         else:
293             return self.nonstop
294
295     def __eq__(self, other):
296         return (force_text(self) == force_text(other) and self.time_label == other.time_label)
297
298
299 class Grid(TemplateView):
300     template_name = 'grid.html'
301
302     def get_context_data(self, **kwargs):
303         context = super(Grid, self).get_context_data(**kwargs)
304
305         nb_lines = 2 * 24 # the cells are half hours
306         grid = []
307
308         Schedule.DAY_HOUR_START = 12
309
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]
313
314         nonstops = []
315         for nonstop in Nonstop.objects.all():
316             if nonstop.start == nonstop.end:
317                 continue
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])
322             else:
323                 # crossing midnight
324                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
325                                  24,
326                                  nonstop.title, nonstop.slug])
327                 nonstops.append([0,
328                                  nonstop.end.hour + nonstop.end.minute/60.,
329                                  nonstop.title, nonstop.slug])
330         nonstops.sort()
331
332         for i in range(nb_lines):
333             grid.append([])
334             for j in range(7):
335                 grid[-1].append(TimeCell(i, j))
336
337             try:
338                 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
339             except IndexError:
340                 pass
341             for time_cell in grid[-1]:
342                 time_cell.nonstop = nonstop[2]
343                 time_cell.nonstop_slug = nonstop[3]
344                 if nonstop[1] == 5:
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])
349
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()
355
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)
360
361         # start grid after the night programs
362         grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
363
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:
371                     continue
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:
380                             continue
381                         # here it is, same cell, same emission, several
382                         # schedules
383                         schedule_list.sort(key=lambda x: x.get_duration())
384
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,
391                                 end_time.hour,
392                                 end_time.minute)
393
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)
399
400         # merge adjacent
401
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:
407                     continue
408                 t = 1
409                 try:
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:
413                         cell.w += 1
414                         grid[i][j+t] = None
415                         t += 1
416                 except IndexError:
417                     pass
418
419             # once we're done we remove empty cells
420             grid[i] = [x for x in grid[i] if x is not None]
421
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:
428                     continue
429                 t = 1
430                 try:
431                     while True:
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]
435                         if same_cell_below:
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]
440                             cell.h += 1
441                         else:
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.
445                             #
446                             # For example:
447                             #  - 7am30, seuls contre tout, 1h30
448                             #  - 8am, du pied gauche & la voix de la rue, 1h
449                             # should produce: (this is case A)
450                             #  |      7:30-9:00      |
451                             #  |  seuls contre tout  |
452                             #  |---------------------|
453                             #  |      8:00-9:00      |
454                             #  |   du pied gauche    |
455                             #  |  la voix de la rue  |
456                             #
457                             # On the other hand, if all three emissions started
458                             # at 7am30, we want: (this is case B)
459                             #  |      7:30-9:00      |
460                             #  |  seuls contre tout  |
461                             #  |   du pied gauche    |
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])
467                             cursor = 1
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:
471                                     cursor += 1
472                                     continue
473                                 same_cell_below = same_cell_below[0]
474                                 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
475
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
485                                     # period
486                                     grid[i][j].time_label = same_cell_below.time_label
487                                     # then we sort emissions so the longest are
488                                     # put first
489                                     grid[i][j].schedules.sort(key=lambda x: -x.get_duration())
490                                     # then we add individual time labels to the
491                                     # other schedules
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,
499                                                     end_time.hour,
500                                                     end_time.minute)
501                                     grid[i][j].h += 1
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
507                                             x.emission not in
508                                             current_cell_emissions or
509                                             x.get_duration() < 30]
510                                 cursor += 1
511                             break
512                 except IndexError:
513                     pass
514
515         # cut night
516         grid = grid[:28]
517         times = times[:28]
518
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']
524
525         return context
526
527 grid = Grid.as_view()
528
529
530 class Home(TemplateView):
531     template_name = 'home.html'
532
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]
538
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]
548
549         context['newsletter_form'] = SubscribeForm()
550         context['extra_pages'] = Page.objects.filter(exclude_from_navigation=False)
551
552         return context
553
554 home = Home.as_view()
555
556 class NewsItemView(DetailView):
557     model = NewsItem
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)]
563         return context
564 newsitemview = NewsItemView.as_view()
565
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')
575         return context
576
577 news = News.as_view()
578
579
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)
588         return context
589
590 agenda = Agenda.as_view()
591
592
593 class AgendaByMonth(MonthArchiveView):
594     template_name = 'agenda.html'
595     queryset = NewsItem.objects.filter(event_date__isnull=False)
596     allow_future = True
597     date_field = 'event_date'
598     month_format = '%m'
599
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')
604         return context
605
606 agenda_by_month = AgendaByMonth.as_view()
607
608
609 class Emissions(TemplateView):
610     template_name = 'emissions.html'
611
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()
616         return context
617
618 emissions = Emissions.as_view()
619
620 class EmissionsArchives(TemplateView):
621     template_name = 'emissions/archives.html'
622
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()
627         return context
628 emissionsArchives = EmissionsArchives.as_view()
629
630
631 class Listen(TemplateView):
632     template_name = 'listen.html'
633
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(
646                 podcastable=True) \
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()
654
655
656         return context
657
658 listen = Listen.as_view()
659
660 @cache_control(max_age=15)
661 @csrf_exempt
662 def onair(request):
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': '/'}}})
670     else:
671         d = whatsonair()
672     if d.get('episode'):
673         d['episode'] = {
674             'title': d['episode'].title,
675             'url': d['episode'].get_absolute_url()
676         }
677     if d.get('emission'):
678         chat_url = None
679         if d['emission'].chat_open:
680             chat_url = reverse('emission-chat', kwargs={'slug': d['emission'].slug})
681         d['emission'] = {
682             'title': d['emission'].title,
683             'url': d['emission'].get_absolute_url(),
684             'chat': chat_url,
685         }
686
687     track_title = None
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:
692             track_title = None
693     if d.get('nonstop'):
694         d['nonstop'] = {
695             'title': d['nonstop'].title,
696         }
697         if track_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,
701         # display it.
702         d['episode'] = {
703             'title': track_title,
704             'url': d['emission']['url'],
705         }
706
707     if d.get('current_slot'):
708         del d['current_slot']
709     return JsonResponse({'data': d})
710
711
712 class NewsItemDetailView(DetailView):
713     model = NewsItem
714
715 newsitem = NewsItemDetailView.as_view()
716
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
723         else:
724             image_url = '/static/img/logo-panik-500.png'
725         image_url = urlparse.urljoin(self.feed['link'], image_url)
726         handler.startElement('image', {})
727         if emission:
728             handler.addQuickElement('title', emission.title)
729         else:
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})
735         if emission:
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})
741
742             handler.addQuickElement('itunes:author', emission.title)
743             handler.startElement('itunes:owner', {})
744             if emission.email:
745                 handler.addQuickElement('itunes:email', emission.email)
746             handler.addQuickElement('itunes:name', emission.title)
747             handler.endElement('itunes:owner')
748         else:
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')
754
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'
759         return attrs
760
761     def add_item_elements(self, handler, item):
762         super(RssCustomPodcastsFeed, self).add_item_elements(handler, item)
763         explicit = 'no'
764         for tag in item.get('tags') or []:
765             handler.addQuickElement('dc:subject', tag)
766             if tag == 'explicit':
767                 explicit = 'yes'
768         if item.get('tags'):
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))
781
782
783 class PodcastsFeed(Feed):
784     title = 'Radio Esperanzah! - Podcasts'
785     link = '/'
786     description_template = 'feed/soundfile.html'
787     feed_type = RssCustomPodcastsFeed
788
789     def items(self):
790         return SoundFile.objects.select_related().filter(
791                 podcastable=True).order_by('-creation_timestamp')[:20]
792
793     def item_title(self, item):
794         if item.fragment:
795             return '%s - %s' % (item.title, item.episode.title)
796         return '%s - %s' % (item.episode.emission.title, item.episode.title)
797
798     def item_link(self, item):
799         return item.episode.get_absolute_url()
800
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'))
804
805     def item_enclosure_length(self, item):
806         sound_path = item.get_format_path('mp3')
807         try:
808             return os.stat(sound_path)[stat.ST_SIZE]
809         except OSError:
810             return 0
811
812     def item_enclosure_mime_type(self, item):
813         return 'audio/mpeg'
814
815     def item_pubdate(self, item):
816         return item.creation_timestamp
817
818     def item_extra_kwargs(self, item):
819         return {'tags': [x.name for x in item.episode.tags.all()],
820                 'soundfile': item,
821                 'episode': item.episode}
822
823 podcasts_feed = PodcastsFeed()
824
825
826 class RssNewsFeed(Feed):
827     title = 'Radio Esperanzah!'
828     link = '/news/'
829     description_template = 'feed/newsitem.html'
830
831     def items(self):
832         return NewsItem.objects.order_by('-date')[:20]
833
834 rss_news_feed = RssNewsFeed()
835
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
842
843 class AtomNewsFeed(RssNewsFeed):
844     feed_type = Atom1FeedWithBaseXml
845
846 atom_news_feed = AtomNewsFeed()
847
848
849 class EmissionPodcastsFeed(PodcastsFeed):
850     description_template = 'feed/soundfile.html'
851     feed_type = RssCustomPodcastsFeed
852
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)
856
857     @property
858     def title(self):
859         return self.emission.title
860
861     @property
862     def link(self):
863         return reverse('emission-view', kwargs={'slug': self.emission.slug})
864
865     def feed_extra_kwargs(self, obj):
866         return {'emission': self.emission}
867
868     def items(self):
869         return SoundFile.objects.select_related().filter(
870                 podcastable=True,
871                 episode__emission__slug=self.emission.slug).order_by('-creation_timestamp')[:20]
872
873 emission_podcasts_feed = EmissionPodcastsFeed()
874
875
876 class Party(TemplateView):
877     template_name = 'party.html'
878
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)
882         focus = Focus()
883         if t == 'newsitem':
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]
889         elif t == 'episode':
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]
895
896         context['focus'] = focus
897
898         return context
899
900 party = Party.as_view()
901
902
903
904 class Chat(DetailView, EmissionMixin):
905     model = Emission
906     template_name = 'chat.html'
907
908 chat = cache_control(max_age=15)(Chat.as_view())
909
910
911
912 class ArchivesView(TemplateView):
913     template_name = 'archives.html'
914
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')
918         return context
919
920 archives = ArchivesView.as_view()