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)
134 program = ProgramView.as_view()
142 def __init__(self, i, j):
147 def add_schedule(self, schedule):
148 end_time = schedule.datetime + timedelta(
149 minutes=schedule.get_duration())
150 self.time_label = '%02d:%02d-%02d:%02d' % (
151 schedule.datetime.hour,
152 schedule.datetime.minute,
155 self.schedules.append(schedule)
157 def __unicode__(self):
159 return ', '.join([x.emission.title for x in self.schedules])
163 def __eq__(self, other):
164 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
167 class Grid(TemplateView):
168 template_name = 'grid.html'
170 def get_context_data(self, **kwargs):
171 context = super(Grid, self).get_context_data(**kwargs)
172 context['sectionName'] = "Emissions"
174 nb_lines = 2 * 24 # the cells are half hours
177 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
178 # start grid after the night programs
179 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
182 for nonstop in Nonstop.objects.all():
183 if nonstop.start < nonstop.end:
184 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
185 nonstop.end.hour + nonstop.end.minute/60.,
186 nonstop.title, nonstop.slug])
189 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
191 nonstop.title, nonstop.slug])
193 nonstop.end.hour + nonstop.end.minute/60.,
194 nonstop.title, nonstop.slug])
197 for i in range(nb_lines):
200 grid[-1].append(TimeCell(i, j))
202 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
203 for time_cell in grid[-1]:
204 time_cell.nonstop = nonstop[2]
205 time_cell.nonstop_slug = nonstop[3]
207 # the one ending at 5am will be cut down, so we inscribe
208 # its duration manually
209 time_cell.time_label = '%02d:00-%02d:00' % (
210 nonstop[0], nonstop[1])
212 for schedule in Schedule.objects.prefetch_related(
213 'emission__categories').select_related().order_by('datetime'):
214 row_start = schedule.datetime.hour * 2 + \
215 int(math.ceil(schedule.datetime.minute / 30))
216 day_no = schedule.get_weekday()
218 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
219 if grid[(row_start+step)%nb_lines][day_no] is None:
220 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
221 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
223 # start grid after the night programs
224 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
226 # look for the case where the same emission has different schedules for
227 # the same time cell, for example if it lasts one hour the first week,
228 # and two hours the third week.
229 for i in range(nb_lines):
230 grid[i] = [x for x in grid[i] if x is not None]
231 for j, cell in enumerate(grid[i]):
232 if grid[i][j] is None:
234 if len(grid[i][j].schedules) > 1:
235 time_cell_emissions = {}
236 for schedule in grid[i][j].schedules:
237 if not schedule.emission.id in time_cell_emissions:
238 time_cell_emissions[schedule.emission.id] = []
239 time_cell_emissions[schedule.emission.id].append(schedule)
240 for schedule_list in time_cell_emissions.values():
241 if len(schedule_list) == 1:
243 # here it is, same cell, same emission, several
245 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
247 schedule = schedule_list[0]
248 end_time = schedule.datetime + timedelta(
249 minutes=schedule.get_duration())
250 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
251 schedule.datetime.hour,
252 schedule.datetime.minute,
256 for schedule in schedule_list[1:]:
257 grid[i][j].schedules.remove(schedule)
258 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
259 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
260 end_time.hour, end_time.minute, schedule.weeks_string)
264 # 1st thing is to merge cells on the same line, this will mostly catch
265 # consecutive nonstop cells
266 for i in range(nb_lines):
267 for j, cell in enumerate(grid[i]):
268 if grid[i][j] is None:
272 # if the cells are identical, they are removed from the
273 # grid, and current cell width is increased
274 while grid[i][j+t] == cell:
281 # once we're done we remove empty cells
282 grid[i] = [x for x in grid[i] if x is not None]
284 # 2nd thing is to merge cells vertically, this is emissions that last
285 # for more than 30 minutes
286 for i in range(nb_lines):
287 grid[i] = [x for x in grid[i] if x is not None]
288 for j, cell in enumerate(grid[i]):
289 if grid[i][j] is None:
294 # we look if the next time cell has the same emissions
295 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
296 if x == cell and x.y == cell.y and x.w == cell.w]
298 # if the cell was identical, we remove it and
299 # increase current cell height
300 bj, same_cell_below = same_cell_below[0]
301 del grid[i+cell.h][bj]
304 # if the cell is different, we have a closer look
305 # to it, so we can remove emissions that will
306 # already be mentioned in the current cell.
309 # - 7am30, seuls contre tout, 1h30
310 # - 8am, du pied gauche & la voix de la rue, 1h
311 # should produce: (this is case A)
313 # | seuls contre tout |
314 # |---------------------|
317 # | la voix de la rue |
319 # On the other hand, if all three emissions started
320 # at 7am30, we want: (this is case B)
322 # | seuls contre tout |
324 # | la voix de la rue |
325 # that is we merge all of them, ignoring the fact
326 # that the other emissions will stop at 8am30
327 current_cell_schedules = set(grid[i][j].schedules)
328 current_cell_emissions = set([x.emission for x in current_cell_schedules])
330 while True and current_cell_schedules:
331 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
332 if not same_cell_below:
335 same_cell_below = same_cell_below[0]
336 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
338 if current_cell_emissions.issubset(same_cell_below_emissions):
339 # this handles case A (see comment above)
340 for schedule in current_cell_schedules:
341 if schedule in same_cell_below.schedules:
342 same_cell_below.schedules.remove(schedule)
343 elif same_cell_below_emissions and \
344 current_cell_emissions.issuperset(same_cell_below_emissions):
345 # this handles case B (see comment above)
346 # we set the cell time label to the longest
348 grid[i][j].time_label = same_cell_below.time_label
349 # then we sort emissions so the longest are
351 grid[i][j].schedules.sort(
352 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
353 # then we add individual time labels to the
355 for schedule in current_cell_schedules:
356 if schedule not in same_cell_below.schedules:
357 end_time = schedule.datetime + timedelta(
358 minutes=schedule.get_duration())
359 schedule.time_label = '%02d:%02d-%02d:%02d' % (
360 schedule.datetime.hour,
361 schedule.datetime.minute,
365 grid[i+cursor].remove(same_cell_below)
366 elif same_cell_below_emissions and \
367 current_cell_emissions.intersection(same_cell_below_emissions):
368 same_cell_below.schedules = [x for x in
369 same_cell_below.schedules if
371 current_cell_emissions or
372 x.get_duration() < 30]
382 context['grid'] = grid
383 context['times'] = times
384 context['categories'] = Category.objects.all()
385 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
386 'Vendredi', 'Samedi', 'Dimanche']
390 grid = Grid.as_view()
393 class Home(TemplateView):
394 template_name = 'home.html'
396 def get_context_data(self, **kwargs):
397 context = super(Home, self).get_context_data(**kwargs)
398 context['sectionName'] = "Home"
399 context['focus'] = NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:5]
400 context['emissions'] = Emission.objects.filter(archived=False,
401 creation_timestamp__gte=datetime(2013, 9, 13)).order_by('title')
402 schedules = Schedule.objects.select_related().order_by('datetime')
405 days.append({'schedules': [x for x in schedules if x.is_on_weekday(day+1)],
406 'datetime': datetime(2007, 1, day+1)})
407 context['days'] = days
409 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
410 podcastable=True, fragment=False) \
411 .select_related().extra(select={
412 'first_diffusion': 'emissions_diffusion.datetime', },
413 select_params=(False, True),
414 where=['''datetime = (SELECT MIN(datetime)
415 FROM emissions_diffusion
416 WHERE episode_id = emissions_episode.id)'''],
417 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:6]
419 context['newsletter_form'] = SubscribeForm()
423 home = Home.as_view()
425 class NewsItemView(DetailView):
427 def get_context_data(self, **kwargs):
428 context = super(NewsItemView, self).get_context_data(**kwargs)
429 context['sectionName'] = "News"
430 context['focus'] = list(NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
431 context['categories'] = NewsCategory.objects.all()
433 newsitemview = NewsItemView.as_view()
435 class News(TemplateView):
436 template_name = 'news.html'
437 def get_context_data(self, **kwargs):
438 context = super(News, self).get_context_data(**kwargs)
439 context['sectionName'] = "News"
440 context['news'] = NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:14]
443 news = News.as_view()
445 class NewsArchives(TemplateView):
446 template_name = 'news/archives.html'
447 def get_context_data(self, **kwargs):
448 context = super(NewsArchives, self).get_context_data(**kwargs)
449 context['sectionName'] = "News"
450 context['search_query'] = self.request.GET.get('q')
451 sqs = SearchQuerySet().filter(django_ct='emissions.newsitem')
452 if context['search_query']:
454 sqs = sqs.filter(text=context['search_query'])
456 sqs = sqs.order_by('-date')
460 context['results'] = sqs
464 newsArchives = NewsArchives.as_view()
466 class Emissions(TemplateView):
467 template_name = 'emissions.html'
469 def get_context_data(self, **kwargs):
470 context = super(Emissions, self).get_context_data(**kwargs)
471 context['sectionName'] = "Emissions"
472 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
473 context['categories'] = Category.objects.all()
476 emissions = Emissions.as_view()
478 class EmissionsArchives(TemplateView):
479 template_name = 'emissions/archives.html'
481 def get_context_data(self, **kwargs):
482 context = super(EmissionsArchives, self).get_context_data(**kwargs)
483 context['sectionName'] = "Emissions"
484 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
485 context['categories'] = Category.objects.all()
487 emissionsArchives = EmissionsArchives.as_view()
490 class Listen(TemplateView):
491 template_name = 'listen.html'
493 def get_context_data(self, **kwargs):
494 context = super(Listen, self).get_context_data(**kwargs)
495 context['sectionName'] = "Listen"
496 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
497 podcastable=True, fragment=False) \
498 .select_related().extra(select={
499 'first_diffusion': 'emissions_diffusion.datetime', },
500 select_params=(False, True),
501 where=['''datetime = (SELECT MIN(datetime)
502 FROM emissions_diffusion
503 WHERE episode_id = emissions_episode.id)'''],
504 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:10]
506 context['categories'] = Category.objects.all()
510 listen = Listen.as_view()
512 @cache_control(max_age=25)
519 'title': d['episode'].title,
520 'url': d['episode'].get_absolute_url()
522 if d.get('emission'):
524 'title': d['emission'].title,
525 'url': d['emission'].get_absolute_url()
529 'title': d['nonstop'].title,
531 if d.get('current_slot'):
532 del d['current_slot']
536 class NewsItemDetailView(DetailView):
539 newsitem = NewsItemDetailView.as_view()
542 class PodcastsFeedView(TemplateView):
543 template_name = 'podcasts.html'
544 content_type = 'application/rss+xml'
546 def get_context_data(self, **kwargs):
547 context = super(PodcastsFeedView, self).get_context_data(**kwargs)
548 context['base_url'] = self.request.build_absolute_uri('/')[:-1]
549 context['soundfiles'] = SoundFile.objects.select_related().filter(
550 podcastable=True).order_by('-creation_timestamp')
553 podcasts_feed = PodcastsFeedView.as_view()
556 class FiberPageView(fiber.views.FiberTemplateView):
557 def get_context_data(self, **kwargs):
558 context = super(FiberPageView, self).get_context_data(**kwargs)
559 context['sectionName'] = 'About'
561 fiber_page = FiberPageView.as_view()