1 from datetime import datetime, timedelta
5 from django.views.decorators.cache import cache_control
6 from django.views.generic.base import TemplateView
7 from django.views.generic.detail import DetailView
8 from django.views.decorators.csrf import csrf_exempt
9 from django.views.generic.dates import _date_from_string
11 from django.core.paginator import Paginator
14 from haystack.query import SearchQuerySet
15 from jsonresponse import to_json
17 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
18 Schedule, Nonstop, NewsItem, NewsCategory
20 from emissions.utils import whatsonair, period_program
22 from newsletter.forms import SubscribeForm
28 def get_emission_context(self, emission, episode_ids=None):
31 # get all episodes, with an additional attribute to get the date of
32 # their first diffusion
33 episodes_queryset = Episode.objects.select_related()
34 if episode_ids is not None:
35 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
37 episodes_queryset = episodes_queryset.filter(emission=emission)
39 context['episodes'] = \
40 episodes_queryset.extra(select={
41 'first_diffusion': 'emissions_diffusion.datetime',
43 select_params=(False, True),
44 where=['''datetime = (SELECT MIN(datetime)
45 FROM emissions_diffusion
46 WHERE episode_id = emissions_episode.id)'''],
47 tables=['emissions_diffusion'],
48 ).order_by('-first_diffusion')
50 # get all related soundfiles in a single query
52 if episode_ids is not None:
53 for episode_id in episode_ids:
54 soundfiles[episode_id] = None
56 for episode in Episode.objects.filter(emission=emission):
57 soundfiles[episode.id] = None
59 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
60 fragment=False, episode__emission=emission):
61 soundfiles[soundfile.episode_id] = soundfile
63 Episode.set_prefetched_soundfiles(soundfiles)
65 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
70 class EmissionDetailView(DetailView, EmissionMixin):
73 def get_context_data(self, **kwargs):
74 context = super(EmissionDetailView, self).get_context_data(**kwargs)
75 context['sectionName'] = "Emissions"
76 context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
77 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
78 context.update(self.get_emission_context(self.object))
80 emission = EmissionDetailView.as_view()
82 class EpisodeDetailView(DetailView, EmissionMixin):
85 def get_context_data(self, **kwargs):
86 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
87 context['sectionName'] = "Emissions"
88 context['diffusions'] = Diffusion.objects.select_related().filter(episode=self.object.id)
89 context['soundfiles'] = SoundFile.objects.select_related().filter(episode=self.object.id)
90 context['emission'] = Emission.objects.get(slug=self.kwargs.get('emission_slug'))
91 context.update(self.get_emission_context(context['emission']))
93 episode = EpisodeDetailView.as_view()
96 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
98 template_name = 'emissions/episodes.html'
100 def get_context_data(self, **kwargs):
101 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
102 context['sectionName'] = "Emissions"
103 context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
105 context['search_query'] = self.request.GET.get('q')
106 if context['search_query']:
108 sqs = SearchQuerySet().filter(django_ct='emissions.episode',
109 emission_slug_exact=self.object.slug, text=context['search_query'])
110 episode_ids = [x.pk for x in sqs]
114 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
116 emissionEpisodes = EmissionEpisodesDetailView.as_view()
118 class ProgramView(TemplateView):
119 template_name = 'program.html'
121 def get_context_data(self, year=None, week=None, **kwargs):
122 context = super(ProgramView, self).get_context_data(**kwargs)
123 context['sectionName'] = "Emissions"
125 context['weekday'] = datetime.today().weekday()
127 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
128 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
129 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
130 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
132 previous_week = context['week_first_day'] - timedelta(days=7)
133 context['previous_week_no'] = previous_week.isocalendar()[1]
134 context['previous_week_year'] = previous_week.isocalendar()[0]
136 next_week = context['week_first_day'] + timedelta(days=7)
137 context['next_week_no'] = next_week.isocalendar()[1]
138 context['next_week_year'] = next_week.isocalendar()[0]
142 program = ProgramView.as_view()
150 def __init__(self, i, j):
155 def add_schedule(self, schedule):
156 end_time = schedule.datetime + timedelta(
157 minutes=schedule.get_duration())
158 self.time_label = '%02d:%02d-%02d:%02d' % (
159 schedule.datetime.hour,
160 schedule.datetime.minute,
163 self.schedules.append(schedule)
165 def __unicode__(self):
167 return ', '.join([x.emission.title for x in self.schedules])
171 def __eq__(self, other):
172 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
175 class Grid(TemplateView):
176 template_name = 'grid.html'
178 def get_context_data(self, **kwargs):
179 context = super(Grid, self).get_context_data(**kwargs)
180 context['sectionName'] = "Emissions"
182 nb_lines = 2 * 24 # the cells are half hours
185 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
186 # start grid after the night programs
187 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
190 for nonstop in Nonstop.objects.all():
191 if nonstop.start < nonstop.end:
192 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
193 nonstop.end.hour + nonstop.end.minute/60.,
194 nonstop.title, nonstop.slug])
197 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
199 nonstop.title, nonstop.slug])
201 nonstop.end.hour + nonstop.end.minute/60.,
202 nonstop.title, nonstop.slug])
205 for i in range(nb_lines):
208 grid[-1].append(TimeCell(i, j))
210 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
211 for time_cell in grid[-1]:
212 time_cell.nonstop = nonstop[2]
213 time_cell.nonstop_slug = nonstop[3]
215 # the one ending at 5am will be cut down, so we inscribe
216 # its duration manually
217 time_cell.time_label = '%02d:00-%02d:00' % (
218 nonstop[0], nonstop[1])
220 for schedule in Schedule.objects.prefetch_related(
221 'emission__categories').select_related().order_by('datetime'):
222 row_start = schedule.datetime.hour * 2 + \
223 int(math.ceil(schedule.datetime.minute / 30))
224 day_no = schedule.get_weekday()
226 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
227 if grid[(row_start+step)%nb_lines][day_no] is None:
228 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
229 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
231 # start grid after the night programs
232 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
234 # look for the case where the same emission has different schedules for
235 # the same time cell, for example if it lasts one hour the first week,
236 # and two hours the third week.
237 for i in range(nb_lines):
238 grid[i] = [x for x in grid[i] if x is not None]
239 for j, cell in enumerate(grid[i]):
240 if grid[i][j] is None:
242 if len(grid[i][j].schedules) > 1:
243 time_cell_emissions = {}
244 for schedule in grid[i][j].schedules:
245 if not schedule.emission.id in time_cell_emissions:
246 time_cell_emissions[schedule.emission.id] = []
247 time_cell_emissions[schedule.emission.id].append(schedule)
248 for schedule_list in time_cell_emissions.values():
249 if len(schedule_list) == 1:
251 # here it is, same cell, same emission, several
253 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
255 schedule = schedule_list[0]
256 end_time = schedule.datetime + timedelta(
257 minutes=schedule.get_duration())
258 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
259 schedule.datetime.hour,
260 schedule.datetime.minute,
264 for schedule in schedule_list[1:]:
265 grid[i][j].schedules.remove(schedule)
266 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
267 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
268 end_time.hour, end_time.minute, schedule.weeks_string)
272 # 1st thing is to merge cells on the same line, this will mostly catch
273 # consecutive nonstop cells
274 for i in range(nb_lines):
275 for j, cell in enumerate(grid[i]):
276 if grid[i][j] is None:
280 # if the cells are identical, they are removed from the
281 # grid, and current cell width is increased
282 while grid[i][j+t] == cell:
289 # once we're done we remove empty cells
290 grid[i] = [x for x in grid[i] if x is not None]
292 # 2nd thing is to merge cells vertically, this is emissions that last
293 # for more than 30 minutes
294 for i in range(nb_lines):
295 grid[i] = [x for x in grid[i] if x is not None]
296 for j, cell in enumerate(grid[i]):
297 if grid[i][j] is None:
302 # we look if the next time cell has the same emissions
303 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
304 if x == cell and x.y == cell.y and x.w == cell.w]
306 # if the cell was identical, we remove it and
307 # increase current cell height
308 bj, same_cell_below = same_cell_below[0]
309 del grid[i+cell.h][bj]
312 # if the cell is different, we have a closer look
313 # to it, so we can remove emissions that will
314 # already be mentioned in the current cell.
317 # - 7am30, seuls contre tout, 1h30
318 # - 8am, du pied gauche & la voix de la rue, 1h
319 # should produce: (this is case A)
321 # | seuls contre tout |
322 # |---------------------|
325 # | la voix de la rue |
327 # On the other hand, if all three emissions started
328 # at 7am30, we want: (this is case B)
330 # | seuls contre tout |
332 # | la voix de la rue |
333 # that is we merge all of them, ignoring the fact
334 # that the other emissions will stop at 8am30
335 current_cell_schedules = set(grid[i][j].schedules)
336 current_cell_emissions = set([x.emission for x in current_cell_schedules])
338 while True and current_cell_schedules:
339 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
340 if not same_cell_below:
343 same_cell_below = same_cell_below[0]
344 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
346 if current_cell_emissions.issubset(same_cell_below_emissions):
347 # this handles case A (see comment above)
348 for schedule in current_cell_schedules:
349 if schedule in same_cell_below.schedules:
350 same_cell_below.schedules.remove(schedule)
351 elif same_cell_below_emissions and \
352 current_cell_emissions.issuperset(same_cell_below_emissions):
353 # this handles case B (see comment above)
354 # we set the cell time label to the longest
356 grid[i][j].time_label = same_cell_below.time_label
357 # then we sort emissions so the longest are
359 grid[i][j].schedules.sort(
360 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
361 # then we add individual time labels to the
363 for schedule in current_cell_schedules:
364 if schedule not in same_cell_below.schedules:
365 end_time = schedule.datetime + timedelta(
366 minutes=schedule.get_duration())
367 schedule.time_label = '%02d:%02d-%02d:%02d' % (
368 schedule.datetime.hour,
369 schedule.datetime.minute,
373 grid[i+cursor].remove(same_cell_below)
374 elif same_cell_below_emissions and \
375 current_cell_emissions.intersection(same_cell_below_emissions):
376 same_cell_below.schedules = [x for x in
377 same_cell_below.schedules if
379 current_cell_emissions or
380 x.get_duration() < 30]
390 context['grid'] = grid
391 context['times'] = times
392 context['categories'] = Category.objects.all()
393 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
394 'Vendredi', 'Samedi', 'Dimanche']
398 grid = Grid.as_view()
401 class Home(TemplateView):
402 template_name = 'home.html'
404 def get_context_data(self, **kwargs):
405 context = super(Home, self).get_context_data(**kwargs)
406 context['sectionName'] = "Home"
407 context['focus'] = NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:9]
408 context['emissions'] = list(Emission.objects.filter(archived=False).order_by('title'))
409 schedules = Schedule.objects.select_related().order_by('datetime')
412 days.append({'schedules': [x for x in schedules if x.is_on_weekday(day+1)],
413 'datetime': datetime(2007, 1, day+1)})
414 context['days'] = days
416 context['episodes'] = Episode.objects.prefetch_related('emission__categories').filter(
417 soundfile__podcastable=True, soundfile__fragment=False) \
418 .select_related().extra(select={
419 'first_diffusion': 'emissions_diffusion.datetime', },
420 select_params=(False, True),
421 where=['''datetime = (SELECT MIN(datetime)
422 FROM emissions_diffusion
423 WHERE episode_id = emissions_episode.id)'''],
424 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:6]
426 # get all related soundfiles in a single query
428 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
429 fragment=False, episode__in=[x.id for x in context['episodes']]):
430 soundfiles[soundfile.episode_id] = soundfile
432 # replace dynamic property by a static attribute, to avoid database
434 for episode in context['episodes']:
435 episode.main_sound = soundfiles.get(episode.id)
437 context['newsletter_form'] = SubscribeForm()
441 home = Home.as_view()
443 class NewsItemView(DetailView):
445 def get_context_data(self, **kwargs):
446 context = super(NewsItemView, self).get_context_data(**kwargs)
447 context['sectionName'] = "News"
448 context['focus'] = list(NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
449 context['categories'] = NewsCategory.objects.all()
451 newsitemview = NewsItemView.as_view()
453 class News(TemplateView):
454 template_name = 'news.html'
455 def get_context_data(self, **kwargs):
456 context = super(News, self).get_context_data(**kwargs)
457 context['sectionName'] = "News"
458 context['focus'] = NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:9]
459 context['news'] = NewsItem.objects.all().exclude(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[3:14]
462 news = News.as_view()
464 class NewsArchives(TemplateView):
465 template_name = 'news/archives.html'
466 def get_context_data(self, **kwargs):
467 context = super(NewsArchives, self).get_context_data(**kwargs)
468 context['sectionName'] = "News"
469 context['search_query'] = self.request.GET.get('q')
470 sqs = SearchQuerySet().filter(django_ct='emissions.newsitem')
471 if context['search_query']:
473 sqs = sqs.filter(text=context['search_query'])
475 sqs = sqs.order_by('-date')
479 context['results'] = sqs
483 newsArchives = NewsArchives.as_view()
485 class Emissions(TemplateView):
486 template_name = 'emissions.html'
488 def get_context_data(self, **kwargs):
489 context = super(Emissions, self).get_context_data(**kwargs)
490 context['sectionName'] = "Emissions"
491 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
492 context['categories'] = Category.objects.all()
495 emissions = Emissions.as_view()
497 class EmissionsArchives(TemplateView):
498 template_name = 'emissions/archives.html'
500 def get_context_data(self, **kwargs):
501 context = super(EmissionsArchives, self).get_context_data(**kwargs)
502 context['sectionName'] = "Emissions"
503 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
505 emissionsArchives = EmissionsArchives.as_view()
508 class Listen(TemplateView):
509 template_name = 'listen.html'
511 def get_context_data(self, **kwargs):
512 context = super(Listen, self).get_context_data(**kwargs)
513 context['sectionName'] = "Listen"
514 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
515 podcastable=True, fragment=False) \
516 .select_related().extra(select={
517 'first_diffusion': 'emissions_diffusion.datetime', },
518 select_params=(False, True),
519 where=['''datetime = (SELECT MIN(datetime)
520 FROM emissions_diffusion
521 WHERE episode_id = emissions_episode.id)'''],
522 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:10]
524 context['categories'] = Category.objects.all()
528 listen = Listen.as_view()
530 @cache_control(max_age=25)
537 'title': d['episode'].title,
538 'url': d['episode'].get_absolute_url()
540 if d.get('emission'):
542 'title': d['emission'].title,
543 'url': d['emission'].get_absolute_url()
547 'title': d['nonstop'].title,
549 if d.get('current_slot'):
550 del d['current_slot']
554 class NewsItemDetailView(DetailView):
557 newsitem = NewsItemDetailView.as_view()
560 class PodcastsFeedView(TemplateView):
561 template_name = 'podcasts.html'
562 content_type = 'application/rss+xml'
564 def get_context_data(self, **kwargs):
565 context = super(PodcastsFeedView, self).get_context_data(**kwargs)
566 context['base_url'] = self.request.build_absolute_uri('/')[:-1]
567 context['soundfiles'] = SoundFile.objects.select_related().filter(
568 podcastable=True).order_by('-creation_timestamp')
571 podcasts_feed = PodcastsFeedView.as_view()
574 class FiberPageView(fiber.views.FiberTemplateView):
575 def get_context_data(self, **kwargs):
576 context = super(FiberPageView, self).get_context_data(**kwargs)
577 context['sectionName'] = 'About'
579 fiber_page = FiberPageView.as_view()