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 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
53 fragment=False, episode__emission=emission):
54 soundfiles[soundfile.episode_id] = soundfile
56 # replace dynamic property by a static attribute, to avoid database
58 for episode in context['episodes']:
59 episode.main_sound = soundfiles.get(episode.id)
61 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
66 class EmissionDetailView(DetailView, EmissionMixin):
69 def get_context_data(self, **kwargs):
70 context = super(EmissionDetailView, self).get_context_data(**kwargs)
71 context['sectionName'] = "Emissions"
72 context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
73 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
74 context.update(self.get_emission_context(self.object))
76 emission = EmissionDetailView.as_view()
78 class EpisodeDetailView(DetailView, EmissionMixin):
81 def get_context_data(self, **kwargs):
82 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
83 context['sectionName'] = "Emissions"
84 context['diffusions'] = Diffusion.objects.select_related().filter(episode=self.object.id)
85 context['soundfiles'] = SoundFile.objects.select_related().filter(episode=self.object.id)
86 context['emission'] = Emission.objects.get(slug=self.kwargs.get('emission_slug'))
87 context.update(self.get_emission_context(context['emission']))
89 episode = EpisodeDetailView.as_view()
92 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
94 template_name = 'emissions/episodes.html'
96 def get_context_data(self, **kwargs):
97 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
98 context['sectionName'] = "Emissions"
99 context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
101 context['search_query'] = self.request.GET.get('q')
102 if context['search_query']:
104 sqs = SearchQuerySet().filter(django_ct='emissions.episode',
105 emission_slug_exact=self.object.slug, text=context['search_query'])
106 episode_ids = [x.pk for x in sqs]
110 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
112 emissionEpisodes = EmissionEpisodesDetailView.as_view()
114 class ProgramView(TemplateView):
115 template_name = 'program.html'
117 def get_context_data(self, year=None, week=None, **kwargs):
118 context = super(ProgramView, self).get_context_data(**kwargs)
119 context['sectionName'] = "Emissions"
121 context['weekday'] = datetime.today().weekday()
123 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
124 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
125 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
126 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
128 previous_week = context['week_first_day'] - timedelta(days=7)
129 context['previous_week_no'] = previous_week.isocalendar()[1]
130 context['previous_week_year'] = previous_week.isocalendar()[0]
132 next_week = context['week_first_day'] + timedelta(days=7)
133 context['next_week_no'] = next_week.isocalendar()[1]
134 context['next_week_year'] = next_week.isocalendar()[0]
138 program = ProgramView.as_view()
146 def __init__(self, i, j):
151 def add_schedule(self, schedule):
152 end_time = schedule.datetime + timedelta(
153 minutes=schedule.get_duration())
154 self.time_label = '%02d:%02d-%02d:%02d' % (
155 schedule.datetime.hour,
156 schedule.datetime.minute,
159 self.schedules.append(schedule)
161 def __unicode__(self):
163 return ', '.join([x.emission.title for x in self.schedules])
167 def __eq__(self, other):
168 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
171 class Grid(TemplateView):
172 template_name = 'grid.html'
174 def get_context_data(self, **kwargs):
175 context = super(Grid, self).get_context_data(**kwargs)
176 context['sectionName'] = "Emissions"
178 nb_lines = 2 * 24 # the cells are half hours
181 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
182 # start grid after the night programs
183 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
186 for nonstop in Nonstop.objects.all():
187 if nonstop.start < nonstop.end:
188 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
189 nonstop.end.hour + nonstop.end.minute/60.,
190 nonstop.title, nonstop.slug])
193 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
195 nonstop.title, nonstop.slug])
197 nonstop.end.hour + nonstop.end.minute/60.,
198 nonstop.title, nonstop.slug])
201 for i in range(nb_lines):
204 grid[-1].append(TimeCell(i, j))
206 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
207 for time_cell in grid[-1]:
208 time_cell.nonstop = nonstop[2]
209 time_cell.nonstop_slug = nonstop[3]
211 # the one ending at 5am will be cut down, so we inscribe
212 # its duration manually
213 time_cell.time_label = '%02d:00-%02d:00' % (
214 nonstop[0], nonstop[1])
216 for schedule in Schedule.objects.prefetch_related(
217 'emission__categories').select_related().order_by('datetime'):
218 row_start = schedule.datetime.hour * 2 + \
219 int(math.ceil(schedule.datetime.minute / 30))
220 day_no = schedule.get_weekday()
222 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
223 if grid[(row_start+step)%nb_lines][day_no] is None:
224 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
225 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
227 # start grid after the night programs
228 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
230 # look for the case where the same emission has different schedules for
231 # the same time cell, for example if it lasts one hour the first week,
232 # and two hours the third week.
233 for i in range(nb_lines):
234 grid[i] = [x for x in grid[i] if x is not None]
235 for j, cell in enumerate(grid[i]):
236 if grid[i][j] is None:
238 if len(grid[i][j].schedules) > 1:
239 time_cell_emissions = {}
240 for schedule in grid[i][j].schedules:
241 if not schedule.emission.id in time_cell_emissions:
242 time_cell_emissions[schedule.emission.id] = []
243 time_cell_emissions[schedule.emission.id].append(schedule)
244 for schedule_list in time_cell_emissions.values():
245 if len(schedule_list) == 1:
247 # here it is, same cell, same emission, several
249 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
251 schedule = schedule_list[0]
252 end_time = schedule.datetime + timedelta(
253 minutes=schedule.get_duration())
254 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
255 schedule.datetime.hour,
256 schedule.datetime.minute,
260 for schedule in schedule_list[1:]:
261 grid[i][j].schedules.remove(schedule)
262 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
263 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
264 end_time.hour, end_time.minute, schedule.weeks_string)
268 # 1st thing is to merge cells on the same line, this will mostly catch
269 # consecutive nonstop cells
270 for i in range(nb_lines):
271 for j, cell in enumerate(grid[i]):
272 if grid[i][j] is None:
276 # if the cells are identical, they are removed from the
277 # grid, and current cell width is increased
278 while grid[i][j+t] == cell:
285 # once we're done we remove empty cells
286 grid[i] = [x for x in grid[i] if x is not None]
288 # 2nd thing is to merge cells vertically, this is emissions that last
289 # for more than 30 minutes
290 for i in range(nb_lines):
291 grid[i] = [x for x in grid[i] if x is not None]
292 for j, cell in enumerate(grid[i]):
293 if grid[i][j] is None:
298 # we look if the next time cell has the same emissions
299 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
300 if x == cell and x.y == cell.y and x.w == cell.w]
302 # if the cell was identical, we remove it and
303 # increase current cell height
304 bj, same_cell_below = same_cell_below[0]
305 del grid[i+cell.h][bj]
308 # if the cell is different, we have a closer look
309 # to it, so we can remove emissions that will
310 # already be mentioned in the current cell.
313 # - 7am30, seuls contre tout, 1h30
314 # - 8am, du pied gauche & la voix de la rue, 1h
315 # should produce: (this is case A)
317 # | seuls contre tout |
318 # |---------------------|
321 # | la voix de la rue |
323 # On the other hand, if all three emissions started
324 # at 7am30, we want: (this is case B)
326 # | seuls contre tout |
328 # | la voix de la rue |
329 # that is we merge all of them, ignoring the fact
330 # that the other emissions will stop at 8am30
331 current_cell_schedules = set(grid[i][j].schedules)
332 current_cell_emissions = set([x.emission for x in current_cell_schedules])
334 while True and current_cell_schedules:
335 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
336 if not same_cell_below:
339 same_cell_below = same_cell_below[0]
340 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
342 if current_cell_emissions.issubset(same_cell_below_emissions):
343 # this handles case A (see comment above)
344 for schedule in current_cell_schedules:
345 if schedule in same_cell_below.schedules:
346 same_cell_below.schedules.remove(schedule)
347 elif same_cell_below_emissions and \
348 current_cell_emissions.issuperset(same_cell_below_emissions):
349 # this handles case B (see comment above)
350 # we set the cell time label to the longest
352 grid[i][j].time_label = same_cell_below.time_label
353 # then we sort emissions so the longest are
355 grid[i][j].schedules.sort(
356 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
357 # then we add individual time labels to the
359 for schedule in current_cell_schedules:
360 if schedule not in same_cell_below.schedules:
361 end_time = schedule.datetime + timedelta(
362 minutes=schedule.get_duration())
363 schedule.time_label = '%02d:%02d-%02d:%02d' % (
364 schedule.datetime.hour,
365 schedule.datetime.minute,
369 grid[i+cursor].remove(same_cell_below)
370 elif same_cell_below_emissions and \
371 current_cell_emissions.intersection(same_cell_below_emissions):
372 same_cell_below.schedules = [x for x in
373 same_cell_below.schedules if
375 current_cell_emissions or
376 x.get_duration() < 30]
386 context['grid'] = grid
387 context['times'] = times
388 context['categories'] = Category.objects.all()
389 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
390 'Vendredi', 'Samedi', 'Dimanche']
394 grid = Grid.as_view()
397 class Home(TemplateView):
398 template_name = 'home.html'
400 def get_context_data(self, **kwargs):
401 context = super(Home, self).get_context_data(**kwargs)
402 context['sectionName'] = "Home"
403 context['focus'] = NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:9]
404 context['emissions'] = list(Emission.objects.filter(archived=False).order_by('title'))
405 schedules = Schedule.objects.select_related().order_by('datetime')
408 days.append({'schedules': [x for x in schedules if x.is_on_weekday(day+1)],
409 'datetime': datetime(2007, 1, day+1)})
410 context['days'] = days
412 context['episodes'] = Episode.objects.prefetch_related('emission__categories').filter(
413 soundfile__podcastable=True, soundfile__fragment=False) \
414 .select_related().extra(select={
415 'first_diffusion': 'emissions_diffusion.datetime', },
416 select_params=(False, True),
417 where=['''datetime = (SELECT MIN(datetime)
418 FROM emissions_diffusion
419 WHERE episode_id = emissions_episode.id)'''],
420 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:6]
422 # get all related soundfiles in a single query
424 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
425 fragment=False, episode__in=[x.id for x in context['episodes']]):
426 soundfiles[soundfile.episode_id] = soundfile
428 # replace dynamic property by a static attribute, to avoid database
430 for episode in context['episodes']:
431 episode.main_sound = soundfiles.get(episode.id)
433 context['newsletter_form'] = SubscribeForm()
437 home = Home.as_view()
439 class NewsItemView(DetailView):
441 def get_context_data(self, **kwargs):
442 context = super(NewsItemView, self).get_context_data(**kwargs)
443 context['sectionName'] = "News"
444 context['focus'] = list(NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
445 context['categories'] = NewsCategory.objects.all()
447 newsitemview = NewsItemView.as_view()
449 class News(TemplateView):
450 template_name = 'news.html'
451 def get_context_data(self, **kwargs):
452 context = super(News, self).get_context_data(**kwargs)
453 context['sectionName'] = "News"
454 context['focus'] = NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:9]
455 context['news'] = NewsItem.objects.all().exclude(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[3:14]
458 news = News.as_view()
460 class NewsArchives(TemplateView):
461 template_name = 'news/archives.html'
462 def get_context_data(self, **kwargs):
463 context = super(NewsArchives, self).get_context_data(**kwargs)
464 context['sectionName'] = "News"
465 context['search_query'] = self.request.GET.get('q')
466 sqs = SearchQuerySet().filter(django_ct='emissions.newsitem')
467 if context['search_query']:
469 sqs = sqs.filter(text=context['search_query'])
471 sqs = sqs.order_by('-date')
475 context['results'] = sqs
479 newsArchives = NewsArchives.as_view()
481 class Emissions(TemplateView):
482 template_name = 'emissions.html'
484 def get_context_data(self, **kwargs):
485 context = super(Emissions, self).get_context_data(**kwargs)
486 context['sectionName'] = "Emissions"
487 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
488 context['categories'] = Category.objects.all()
491 emissions = Emissions.as_view()
493 class EmissionsArchives(TemplateView):
494 template_name = 'emissions/archives.html'
496 def get_context_data(self, **kwargs):
497 context = super(EmissionsArchives, self).get_context_data(**kwargs)
498 context['sectionName'] = "Emissions"
499 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
501 emissionsArchives = EmissionsArchives.as_view()
504 class Get(TemplateView):
505 template_name = 'get.html'
506 def get_context_data(self, **kwargs):
507 context = super(Get, self).get_context_data(**kwargs)
508 context['emissions'] = Emission.objects.all().order_by('title')
513 class Listen(TemplateView):
514 template_name = 'listen.html'
516 def get_context_data(self, **kwargs):
517 context = super(Listen, self).get_context_data(**kwargs)
518 context['sectionName'] = "Listen"
519 context['episodes'] = Episode.objects.prefetch_related('emission__categories').filter(
520 soundfile__podcastable=True, soundfile__fragment=False) \
521 .select_related().extra(select={
522 'first_diffusion': 'emissions_diffusion.datetime', },
523 select_params=(False, True),
524 where=['''datetime = (SELECT MIN(datetime)
525 FROM emissions_diffusion
526 WHERE episode_id = emissions_episode.id)'''],
527 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:60]
529 # get all related soundfiles in a single query
531 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
532 fragment=False, episode__in=[x.id for x in context['episodes']]):
533 soundfiles[soundfile.episode_id] = soundfile
535 # replace dynamic property by a static attribute, to avoid database
537 for episode in context['episodes']:
538 episode.main_sound = soundfiles.get(episode.id)
539 context['categories'] = Category.objects.all()
543 listen = Listen.as_view()
545 class ListenArchives(TemplateView):
546 template_name = 'listen/archives.html'
547 def get_context_data(self, **kwargs):
549 context = super(ListenArchives, self).get_context_data(**kwargs)
550 context['sectionName'] = "Listen"
551 context['episodes'] = Episode.objects.filter(
552 soundfile__podcastable=True, soundfile__fragment=False) \
553 .select_related().extra(select={
554 'first_diffusion': 'emissions_diffusion.datetime', },
555 select_params=(False, True),
556 where=['''datetime = (SELECT MIN(datetime)
557 FROM emissions_diffusion
558 WHERE episode_id = emissions_episode.id)'''],
559 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:60]
561 # get all related soundfiles in a single query
563 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
564 fragment=False, episode__in=[x.id for x in context['episodes']]):
565 soundfiles[soundfile.episode_id] = soundfile
567 # replace dynamic property by a static attribute, to avoid database
569 for episode in context['episodes']:
570 episode.main_sound = soundfiles.get(episode.id)
571 context['categories'] = Category.objects.all()
575 listenArchives = ListenArchives.as_view()
577 @cache_control(max_age=25)
584 'title': d['episode'].title,
585 'url': d['episode'].get_absolute_url()
587 if d.get('emission'):
589 'title': d['emission'].title,
590 'url': d['emission'].get_absolute_url()
594 'title': d['nonstop'].title,
596 if d.get('current_slot'):
597 del d['current_slot']
601 class NewsItemDetailView(DetailView):
604 newsitem = NewsItemDetailView.as_view()
607 class PodcastsFeedView(TemplateView):
608 template_name = 'podcasts.html'
609 content_type = 'application/rss+xml'
611 def get_context_data(self, **kwargs):
612 context = super(PodcastsFeedView, self).get_context_data(**kwargs)
613 context['base_url'] = self.request.build_absolute_uri('/')[:-1]
614 context['soundfiles'] = SoundFile.objects.select_related().filter(
615 podcastable=True).order_by('-creation_timestamp')
618 podcasts_feed = PodcastsFeedView.as_view()
621 class FiberPageView(fiber.views.FiberTemplateView):
622 def get_context_data(self, **kwargs):
623 context = super(FiberPageView, self).get_context_data(**kwargs)
624 context['sectionName'] = 'About'
626 fiber_page = FiberPageView.as_view()