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
26 def get_emission_context(self, emission, episode_ids=None):
29 # get all episodes, with an additional attribute to get the date of
30 # their first diffusion
31 episodes_queryset = Episode.objects.select_related()
32 if episode_ids is not None:
33 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
35 episodes_queryset = episodes_queryset.filter(emission=emission)
37 context['episodes'] = \
38 episodes_queryset.extra(select={
39 'first_diffusion': 'emissions_diffusion.datetime',
41 select_params=(False, True),
42 where=['''datetime = (SELECT MIN(datetime)
43 FROM emissions_diffusion
44 WHERE episode_id = emissions_episode.id)'''],
45 tables=['emissions_diffusion'],
46 ).order_by('-first_diffusion')
48 # get all related soundfiles in a single query
50 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
51 fragment=False, episode__emission=emission):
52 soundfiles[soundfile.episode_id] = soundfile
54 # replace dynamic property by a static attribute, to avoid database
56 for episode in context['episodes']:
57 episode.main_sound = soundfiles.get(episode.id)
59 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
64 class EmissionDetailView(DetailView, EmissionMixin):
67 def get_context_data(self, **kwargs):
68 context = super(EmissionDetailView, self).get_context_data(**kwargs)
69 context['sectionName'] = "Emissions"
70 context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
71 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
72 context.update(self.get_emission_context(self.object))
74 emission = EmissionDetailView.as_view()
76 class EpisodeDetailView(DetailView, EmissionMixin):
79 def get_context_data(self, **kwargs):
80 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
81 context['sectionName'] = "Emissions"
82 context['diffusions'] = Diffusion.objects.select_related().filter(episode=self.object.id)
83 context['soundfiles'] = SoundFile.objects.select_related().filter(episode=self.object.id)
84 context['emission'] = Emission.objects.get(slug=self.kwargs.get('emission_slug'))
85 context.update(self.get_emission_context(context['emission']))
87 episode = EpisodeDetailView.as_view()
90 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
92 template_name = 'emissions/episodes.html'
94 def get_context_data(self, **kwargs):
95 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
96 context['sectionName'] = "Emissions"
97 context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
99 context['search_query'] = self.request.GET.get('q')
100 if context['search_query']:
102 sqs = SearchQuerySet().filter(django_ct='emissions.episode',
103 emission_slug_exact=self.object.slug, text=context['search_query'])
104 episode_ids = [x.pk for x in sqs]
108 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
110 emissionEpisodes = EmissionEpisodesDetailView.as_view()
112 class ProgramView(TemplateView):
113 template_name = 'program.html'
115 def get_context_data(self, year=None, week=None, **kwargs):
116 context = super(ProgramView, self).get_context_data(**kwargs)
117 context['sectionName'] = "Emissions"
119 context['weekday'] = datetime.today().weekday()
121 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
122 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
123 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
124 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
126 previous_week = context['week_first_day'] - timedelta(days=7)
127 context['previous_week_no'] = previous_week.isocalendar()[1]
128 context['previous_week_year'] = previous_week.isocalendar()[0]
130 next_week = context['week_first_day'] + timedelta(days=7)
131 context['next_week_no'] = next_week.isocalendar()[1]
132 context['next_week_year'] = next_week.isocalendar()[0]
136 program = ProgramView.as_view()
144 def __init__(self, i, j):
149 def add_schedule(self, schedule):
150 end_time = schedule.datetime + timedelta(
151 minutes=schedule.get_duration())
152 self.time_label = '%02d:%02d-%02d:%02d' % (
153 schedule.datetime.hour,
154 schedule.datetime.minute,
157 self.schedules.append(schedule)
159 def __unicode__(self):
161 return ', '.join([x.emission.title for x in self.schedules])
165 def __eq__(self, other):
166 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
169 class Grid(TemplateView):
170 template_name = 'grid.html'
172 def get_context_data(self, **kwargs):
173 context = super(Grid, self).get_context_data(**kwargs)
174 context['sectionName'] = "Emissions"
176 nb_lines = 2 * 24 # the cells are half hours
179 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
180 # start grid after the night programs
181 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
184 for nonstop in Nonstop.objects.all():
185 if nonstop.start < nonstop.end:
186 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
187 nonstop.end.hour + nonstop.end.minute/60.,
188 nonstop.title, nonstop.slug])
191 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
193 nonstop.title, nonstop.slug])
195 nonstop.end.hour + nonstop.end.minute/60.,
196 nonstop.title, nonstop.slug])
199 for i in range(nb_lines):
202 grid[-1].append(TimeCell(i, j))
204 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
205 for time_cell in grid[-1]:
206 time_cell.nonstop = nonstop[2]
207 time_cell.nonstop_slug = nonstop[3]
209 # the one ending at 5am will be cut down, so we inscribe
210 # its duration manually
211 time_cell.time_label = '%02d:00-%02d:00' % (
212 nonstop[0], nonstop[1])
214 for schedule in Schedule.objects.prefetch_related(
215 'emission__categories').select_related().order_by('datetime'):
216 row_start = schedule.datetime.hour * 2 + \
217 int(math.ceil(schedule.datetime.minute / 30))
218 day_no = schedule.get_weekday()
220 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
221 if grid[(row_start+step)%nb_lines][day_no] is None:
222 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
223 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
225 # start grid after the night programs
226 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
228 # look for the case where the same emission has different schedules for
229 # the same time cell, for example if it lasts one hour the first week,
230 # and two hours the third week.
231 for i in range(nb_lines):
232 grid[i] = [x for x in grid[i] if x is not None]
233 for j, cell in enumerate(grid[i]):
234 if grid[i][j] is None:
236 if len(grid[i][j].schedules) > 1:
237 time_cell_emissions = {}
238 for schedule in grid[i][j].schedules:
239 if not schedule.emission.id in time_cell_emissions:
240 time_cell_emissions[schedule.emission.id] = []
241 time_cell_emissions[schedule.emission.id].append(schedule)
242 for schedule_list in time_cell_emissions.values():
243 if len(schedule_list) == 1:
245 # here it is, same cell, same emission, several
247 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
249 schedule = schedule_list[0]
250 end_time = schedule.datetime + timedelta(
251 minutes=schedule.get_duration())
252 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
253 schedule.datetime.hour,
254 schedule.datetime.minute,
258 for schedule in schedule_list[1:]:
259 grid[i][j].schedules.remove(schedule)
260 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
261 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
262 end_time.hour, end_time.minute, schedule.weeks_string)
266 # 1st thing is to merge cells on the same line, this will mostly catch
267 # consecutive nonstop cells
268 for i in range(nb_lines):
269 for j, cell in enumerate(grid[i]):
270 if grid[i][j] is None:
274 # if the cells are identical, they are removed from the
275 # grid, and current cell width is increased
276 while grid[i][j+t] == cell:
283 # once we're done we remove empty cells
284 grid[i] = [x for x in grid[i] if x is not None]
286 # 2nd thing is to merge cells vertically, this is emissions that last
287 # for more than 30 minutes
288 for i in range(nb_lines):
289 grid[i] = [x for x in grid[i] if x is not None]
290 for j, cell in enumerate(grid[i]):
291 if grid[i][j] is None:
296 # we look if the next time cell has the same emissions
297 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
298 if x == cell and x.y == cell.y and x.w == cell.w]
300 # if the cell was identical, we remove it and
301 # increase current cell height
302 bj, same_cell_below = same_cell_below[0]
303 del grid[i+cell.h][bj]
306 # if the cell is different, we have a closer look
307 # to it, so we can remove emissions that will
308 # already be mentioned in the current cell.
311 # - 7am30, seuls contre tout, 1h30
312 # - 8am, du pied gauche & la voix de la rue, 1h
313 # should produce: (this is case A)
315 # | seuls contre tout |
316 # |---------------------|
319 # | la voix de la rue |
321 # On the other hand, if all three emissions started
322 # at 7am30, we want: (this is case B)
324 # | seuls contre tout |
326 # | la voix de la rue |
327 # that is we merge all of them, ignoring the fact
328 # that the other emissions will stop at 8am30
329 current_cell_schedules = set(grid[i][j].schedules)
330 current_cell_emissions = set([x.emission for x in current_cell_schedules])
332 while True and current_cell_schedules:
333 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
334 if not same_cell_below:
337 same_cell_below = same_cell_below[0]
338 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
340 if current_cell_emissions.issubset(same_cell_below_emissions):
341 # this handles case A (see comment above)
342 for schedule in current_cell_schedules:
343 if schedule in same_cell_below.schedules:
344 same_cell_below.schedules.remove(schedule)
345 elif same_cell_below_emissions and \
346 current_cell_emissions.issuperset(same_cell_below_emissions):
347 # this handles case B (see comment above)
348 # we set the cell time label to the longest
350 grid[i][j].time_label = same_cell_below.time_label
351 # then we sort emissions so the longest are
353 grid[i][j].schedules.sort(
354 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
355 # then we add individual time labels to the
357 for schedule in current_cell_schedules:
358 if schedule not in same_cell_below.schedules:
359 end_time = schedule.datetime + timedelta(
360 minutes=schedule.get_duration())
361 schedule.time_label = '%02d:%02d-%02d:%02d' % (
362 schedule.datetime.hour,
363 schedule.datetime.minute,
367 grid[i+cursor].remove(same_cell_below)
368 elif same_cell_below_emissions and \
369 current_cell_emissions.intersection(same_cell_below_emissions):
370 same_cell_below.schedules = [x for x in
371 same_cell_below.schedules if
373 current_cell_emissions or
374 x.get_duration() < 30]
384 context['grid'] = grid
385 context['times'] = times
386 context['categories'] = Category.objects.all()
387 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
388 'Vendredi', 'Samedi', 'Dimanche']
392 grid = Grid.as_view()
395 class Home(TemplateView):
396 template_name = 'home.html'
398 def get_context_data(self, **kwargs):
399 context = super(Home, self).get_context_data(**kwargs)
400 context['sectionName'] = "Home"
401 context['focus'] = list(NewsItem.objects.all().filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:5])
402 context['emissions'] = list(Emission.objects.filter(archived=False).order_by('title'))
403 schedules = Schedule.objects.select_related().order_by('datetime')
406 days.append({'schedules': [x for x in schedules if x.is_on_weekday(day+1)],
407 'datetime': datetime(2007, 1, day+1)})
408 context['days'] = days
410 context['episodes'] = Episode.objects.prefetch_related('emission__categories').filter(
411 soundfile__podcastable=True, soundfile__fragment=False) \
412 .select_related().extra(select={
413 'first_diffusion': 'emissions_diffusion.datetime', },
414 select_params=(False, True),
415 where=['''datetime = (SELECT MIN(datetime)
416 FROM emissions_diffusion
417 WHERE episode_id = emissions_episode.id)'''],
418 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:6]
420 # get all related soundfiles in a single query
422 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
423 fragment=False, episode__in=[x.id for x in context['episodes']]):
424 soundfiles[soundfile.episode_id] = soundfile
426 # replace dynamic property by a static attribute, to avoid database
428 for episode in context['episodes']:
429 episode.main_sound = soundfiles.get(episode.id)
433 home = Home.as_view()
435 class NewsItemView(DetailView):
437 def get_context_data(self, **kwargs):
438 context = super(NewsItemView, self).get_context_data(**kwargs)
439 context['sectionName'] = "News"
440 context['focus'] = list(NewsItem.objects.all().filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
441 context['categories'] = NewsCategory.objects.all()
443 newsitemview = NewsItemView.as_view()
445 class News(TemplateView):
446 template_name = 'news.html'
447 def get_context_data(self, **kwargs):
448 context = super(News, self).get_context_data(**kwargs)
449 context['sectionName'] = "News"
450 context['focus'] = list(NewsItem.objects.all().filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
451 context['news'] = list(NewsItem.objects.all().exclude(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[3:14])
452 context['categories'] = NewsCategory.objects.all()
455 news = News.as_view()
457 class NewsArchives(TemplateView):
458 template_name = 'news/archives.html'
459 def get_context_data(self, **kwargs):
460 context = super(NewsArchives, self).get_context_data(**kwargs)
461 context['sectionName'] = "News"
462 context['search_query'] = self.request.GET.get('q')
463 sqs = SearchQuerySet().filter(django_ct='emissions.newsitem')
464 if context['search_query']:
466 sqs = sqs.filter(text=context['search_query'])
470 context['results'] = sqs
474 newsArchives = NewsArchives.as_view()
476 class Emissions(TemplateView):
477 template_name = 'emissions.html'
479 def get_context_data(self, **kwargs):
480 context = super(Emissions, self).get_context_data(**kwargs)
481 context['sectionName'] = "Emissions"
482 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
483 context['categories'] = Category.objects.all()
486 emissions = Emissions.as_view()
488 class EmissionsArchives(TemplateView):
489 template_name = 'emissions/archives.html'
491 def get_context_data(self, **kwargs):
492 context = super(EmissionsArchives, self).get_context_data(**kwargs)
493 context['sectionName'] = "Emissions"
494 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
496 emissionsArchives = EmissionsArchives.as_view()
499 class Get(TemplateView):
500 template_name = 'get.html'
501 def get_context_data(self, **kwargs):
502 context = super(Get, self).get_context_data(**kwargs)
503 context['emissions'] = Emission.objects.all().order_by('title')
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['episodes'] = Episode.objects.prefetch_related('emission__categories').filter(
515 soundfile__podcastable=True, soundfile__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') [:60]
524 # get all related soundfiles in a single query
526 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
527 fragment=False, episode__in=[x.id for x in context['episodes']]):
528 soundfiles[soundfile.episode_id] = soundfile
530 # replace dynamic property by a static attribute, to avoid database
532 for episode in context['episodes']:
533 episode.main_sound = soundfiles.get(episode.id)
534 context['categories'] = Category.objects.all()
538 listen = Listen.as_view()
540 class ListenArchives(TemplateView):
541 template_name = 'listen/archives.html'
542 def get_context_data(self, **kwargs):
544 context = super(ListenArchives, self).get_context_data(**kwargs)
545 context['sectionName'] = "Listen"
546 context['episodes'] = Episode.objects.filter(
547 soundfile__podcastable=True, soundfile__fragment=False) \
548 .select_related().extra(select={
549 'first_diffusion': 'emissions_diffusion.datetime', },
550 select_params=(False, True),
551 where=['''datetime = (SELECT MIN(datetime)
552 FROM emissions_diffusion
553 WHERE episode_id = emissions_episode.id)'''],
554 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:60]
556 # get all related soundfiles in a single query
558 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
559 fragment=False, episode__in=[x.id for x in context['episodes']]):
560 soundfiles[soundfile.episode_id] = soundfile
562 # replace dynamic property by a static attribute, to avoid database
564 for episode in context['episodes']:
565 episode.main_sound = soundfiles.get(episode.id)
566 context['categories'] = Category.objects.all()
570 listenArchives = ListenArchives.as_view()
572 @cache_control(max_age=25)
579 'title': d['episode'].title,
580 'url': d['episode'].get_absolute_url()
582 if d.get('emission'):
584 'title': d['emission'].title,
585 'url': d['emission'].get_absolute_url()
589 'title': d['nonstop'].title,
591 if d.get('current_slot'):
592 del d['current_slot']
596 class NewsItemDetailView(DetailView):
599 newsitem = NewsItemDetailView.as_view()
602 class PodcastsFeedView(TemplateView):
603 template_name = 'podcasts.html'
604 content_type = 'application/rss+xml'
606 def get_context_data(self, **kwargs):
607 context = super(PodcastsFeedView, self).get_context_data(**kwargs)
608 context['base_url'] = self.request.build_absolute_uri('/')[:-1]
609 context['soundfiles'] = SoundFile.objects.select_related().filter(
610 podcastable=True).order_by('-creation_timestamp')
613 podcasts_feed = PodcastsFeedView.as_view()
616 class FiberPageView(fiber.views.FiberTemplateView):
617 def get_context_data(self, **kwargs):
618 context = super(FiberPageView, self).get_context_data(**kwargs)
619 context['sectionName'] = 'About'
621 fiber_page = FiberPageView.as_view()