1 from datetime import datetime, timedelta, date
8 from django.conf import settings
9 from django.http import Http404
11 from django.views.decorators.cache import cache_control
12 from django.views.generic.base import TemplateView
13 from django.views.generic.detail import DetailView
14 from django.views.decorators.csrf import csrf_exempt
15 from django.views.generic.dates import _date_from_string
17 from django.core.paginator import Paginator
19 from django.contrib.sites.models import Site
20 from django.contrib.syndication.views import Feed, add_domain
21 from django.utils.feedgenerator import Atom1Feed
23 from haystack.query import SearchQuerySet
24 from jsonresponse import to_json
26 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
27 Schedule, Nonstop, NewsItem, NewsCategory, Focus
29 from emissions.utils import whatsonair, period_program
31 from newsletter.forms import SubscribeForm
32 from nonstop.utils import get_current_nonstop_track
38 def get_emission_context(self, emission, episode_ids=None):
41 # get all episodes, with an additional attribute to get the date of
42 # their first diffusion
43 episodes_queryset = Episode.objects.select_related()
44 if episode_ids is not None:
45 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
47 episodes_queryset = episodes_queryset.filter(emission=emission)
49 context['episodes'] = \
50 episodes_queryset.extra(select={
51 'first_diffusion': 'emissions_diffusion.datetime',
53 select_params=(False, True),
54 where=['''datetime = (SELECT MIN(datetime)
55 FROM emissions_diffusion
56 WHERE episode_id = emissions_episode.id
57 AND datetime <= CURRENT_TIMESTAMP)'''],
58 tables=['emissions_diffusion'],
59 ).order_by('-first_diffusion').distinct()
61 context['futurEpisodes'] = \
62 episodes_queryset.extra(select={
63 'first_diffusion': 'emissions_diffusion.datetime',
65 select_params=(False, True),
66 where=['''datetime = (SELECT MIN(datetime)
67 FROM emissions_diffusion
68 WHERE episode_id = emissions_episode.id
69 AND datetime > CURRENT_TIMESTAMP)'''],
70 tables=['emissions_diffusion'],
71 ).order_by('first_diffusion').distinct()
74 # get all related soundfiles in a single query
76 if episode_ids is not None:
77 for episode_id in episode_ids:
78 soundfiles[episode_id] = None
80 for episode in Episode.objects.filter(emission=emission):
81 soundfiles[episode.id] = None
83 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
84 fragment=False, episode__emission=emission):
85 soundfiles[soundfile.episode_id] = soundfile
87 Episode.set_prefetched_soundfiles(soundfiles)
89 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
94 class EmissionDetailView(DetailView, EmissionMixin):
97 def get_context_data(self, **kwargs):
98 context = super(EmissionDetailView, self).get_context_data(**kwargs)
99 context['sectionName'] = "Emissions"
100 context['schedules'] = Schedule.objects.select_related().filter(
101 emission=self.object).order_by('rerun', 'datetime')
102 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
103 context.update(self.get_emission_context(self.object))
105 emission = EmissionDetailView.as_view()
107 class EpisodeDetailView(DetailView, EmissionMixin):
110 def get_context_data(self, **kwargs):
111 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
112 context['sectionName'] = "Emissions"
113 context['diffusions'] = Diffusion.objects.select_related().filter(
114 episode=self.object.id).order_by('datetime')
116 context['emission'] = context['episode'].emission
117 except Emission.DoesNotExist:
119 if self.kwargs.get('emission_slug') != context['emission'].slug:
121 context.update(self.get_emission_context(context['emission']))
123 episode = EpisodeDetailView.as_view()
126 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
128 template_name = 'emissions/episodes.html'
130 def get_context_data(self, **kwargs):
131 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
132 context['sectionName'] = "Emissions"
133 context['schedules'] = Schedule.objects.select_related().filter(
134 emission=self.object).order_by('rerun', 'datetime')
136 context['search_query'] = self.request.GET.get('q')
137 if context['search_query']:
139 sqs = SearchQuerySet().models(Episode).filter(
140 emission_slug_exact=self.object.slug, text=context['search_query'])
141 episode_ids = [x.pk for x in sqs]
145 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
147 emissionEpisodes = EmissionEpisodesDetailView.as_view()
149 class ProgramView(TemplateView):
150 template_name = 'program.html'
152 def get_context_data(self, year=None, week=None, **kwargs):
153 context = super(ProgramView, self).get_context_data(**kwargs)
154 context['sectionName'] = "Emissions"
156 context['weekday'] = datetime.today().weekday()
158 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
159 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
160 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
161 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
165 program = ProgramView.as_view()
173 def __init__(self, i, j):
178 def add_schedule(self, schedule):
179 end_time = schedule.datetime + timedelta(
180 minutes=schedule.get_duration())
181 self.time_label = '%02d:%02d-%02d:%02d' % (
182 schedule.datetime.hour,
183 schedule.datetime.minute,
186 self.schedules.append(schedule)
188 def __unicode__(self):
190 return ', '.join([x.emission.title for x in self.schedules])
194 def __eq__(self, other):
195 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
198 class Grid(TemplateView):
199 template_name = 'grid.html'
201 def get_context_data(self, **kwargs):
202 context = super(Grid, self).get_context_data(**kwargs)
203 context['sectionName'] = "Emissions"
205 nb_lines = 2 * 24 # the cells are half hours
208 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
209 # start grid after the night programs
210 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
213 for nonstop in Nonstop.objects.all():
214 if nonstop.start < nonstop.end:
215 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
216 nonstop.end.hour + nonstop.end.minute/60.,
217 nonstop.title, nonstop.slug])
220 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
222 nonstop.title, nonstop.slug])
224 nonstop.end.hour + nonstop.end.minute/60.,
225 nonstop.title, nonstop.slug])
228 for i in range(nb_lines):
231 grid[-1].append(TimeCell(i, j))
233 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
234 for time_cell in grid[-1]:
235 time_cell.nonstop = nonstop[2]
236 time_cell.nonstop_slug = nonstop[3]
238 # the one ending at 5am will be cut down, so we inscribe
239 # its duration manually
240 time_cell.time_label = '%02d:00-%02d:00' % (
241 nonstop[0], nonstop[1])
243 for schedule in Schedule.objects.prefetch_related(
244 'emission__categories').select_related().order_by('datetime'):
245 row_start = schedule.datetime.hour * 2 + \
246 int(math.ceil(schedule.datetime.minute / 30))
247 day_no = schedule.get_weekday()
249 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
250 if grid[(row_start+step)%nb_lines][day_no] is None:
251 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
252 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
254 # start grid after the night programs
255 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
257 # look for the case where the same emission has different schedules for
258 # the same time cell, for example if it lasts one hour the first week,
259 # and two hours the third week.
260 for i in range(nb_lines):
261 grid[i] = [x for x in grid[i] if x is not None]
262 for j, cell in enumerate(grid[i]):
263 if grid[i][j] is None:
265 if len(grid[i][j].schedules) > 1:
266 time_cell_emissions = {}
267 for schedule in grid[i][j].schedules:
268 if not schedule.emission.id in time_cell_emissions:
269 time_cell_emissions[schedule.emission.id] = []
270 time_cell_emissions[schedule.emission.id].append(schedule)
271 for schedule_list in time_cell_emissions.values():
272 if len(schedule_list) == 1:
274 # here it is, same cell, same emission, several
276 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
278 schedule = schedule_list[0]
279 end_time = schedule.datetime + timedelta(
280 minutes=schedule.get_duration())
281 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
282 schedule.datetime.hour,
283 schedule.datetime.minute,
287 for schedule in schedule_list[1:]:
288 grid[i][j].schedules.remove(schedule)
289 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
290 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
291 end_time.hour, end_time.minute, schedule.weeks_string)
295 # 1st thing is to merge cells on the same line, this will mostly catch
296 # consecutive nonstop cells
297 for i in range(nb_lines):
298 for j, cell in enumerate(grid[i]):
299 if grid[i][j] is None:
303 # if the cells are identical, they are removed from the
304 # grid, and current cell width is increased
305 while grid[i][j+t] == cell:
312 # once we're done we remove empty cells
313 grid[i] = [x for x in grid[i] if x is not None]
315 # 2nd thing is to merge cells vertically, this is emissions that last
316 # for more than 30 minutes
317 for i in range(nb_lines):
318 grid[i] = [x for x in grid[i] if x is not None]
319 for j, cell in enumerate(grid[i]):
320 if grid[i][j] is None:
325 # we look if the next time cell has the same emissions
326 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
327 if x == cell and x.y == cell.y and x.w == cell.w]
329 # if the cell was identical, we remove it and
330 # increase current cell height
331 bj, same_cell_below = same_cell_below[0]
332 del grid[i+cell.h][bj]
335 # if the cell is different, we have a closer look
336 # to it, so we can remove emissions that will
337 # already be mentioned in the current cell.
340 # - 7am30, seuls contre tout, 1h30
341 # - 8am, du pied gauche & la voix de la rue, 1h
342 # should produce: (this is case A)
344 # | seuls contre tout |
345 # |---------------------|
348 # | la voix de la rue |
350 # On the other hand, if all three emissions started
351 # at 7am30, we want: (this is case B)
353 # | seuls contre tout |
355 # | la voix de la rue |
356 # that is we merge all of them, ignoring the fact
357 # that the other emissions will stop at 8am30
358 current_cell_schedules = set(grid[i][j].schedules)
359 current_cell_emissions = set([x.emission for x in current_cell_schedules])
361 while True and current_cell_schedules:
362 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
363 if not same_cell_below:
366 same_cell_below = same_cell_below[0]
367 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
369 if current_cell_emissions.issubset(same_cell_below_emissions):
370 # this handles case A (see comment above)
371 for schedule in current_cell_schedules:
372 if schedule in same_cell_below.schedules:
373 same_cell_below.schedules.remove(schedule)
374 elif same_cell_below_emissions and \
375 current_cell_emissions.issuperset(same_cell_below_emissions):
376 # this handles case B (see comment above)
377 # we set the cell time label to the longest
379 grid[i][j].time_label = same_cell_below.time_label
380 # then we sort emissions so the longest are
382 grid[i][j].schedules.sort(
383 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
384 # then we add individual time labels to the
386 for schedule in current_cell_schedules:
387 if schedule not in same_cell_below.schedules:
388 end_time = schedule.datetime + timedelta(
389 minutes=schedule.get_duration())
390 schedule.time_label = '%02d:%02d-%02d:%02d' % (
391 schedule.datetime.hour,
392 schedule.datetime.minute,
396 grid[i+cursor].remove(same_cell_below)
397 elif same_cell_below_emissions and \
398 current_cell_emissions.intersection(same_cell_below_emissions):
399 same_cell_below.schedules = [x for x in
400 same_cell_below.schedules if
402 current_cell_emissions or
403 x.get_duration() < 30]
413 context['grid'] = grid
414 context['times'] = times
415 context['categories'] = Category.objects.all()
416 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
417 'Vendredi', 'Samedi', 'Dimanche']
421 grid = Grid.as_view()
424 class Home(TemplateView):
425 template_name = 'home.html'
427 def get_context_data(self, **kwargs):
428 context = super(Home, self).get_context_data(**kwargs)
429 context['sectionName'] = "Home"
430 context['emissions'] = Emission.objects.filter(archived=False).order_by('-creation_timestamp')[:3]
431 context['newsitems'] = NewsItem.objects.order_by('-date')[:3]
433 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
434 podcastable=True, fragment=False) \
435 .select_related().extra(select={
436 'first_diffusion': 'emissions_diffusion.datetime', },
437 select_params=(False, True),
438 where=['''datetime = (SELECT MIN(datetime)
439 FROM emissions_diffusion
440 WHERE episode_id = emissions_episode.id)'''],
441 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
443 context['newsletter_form'] = SubscribeForm()
447 home = Home.as_view()
449 class NewsItemView(DetailView):
451 def get_context_data(self, **kwargs):
452 context = super(NewsItemView, self).get_context_data(**kwargs)
453 context['sectionName'] = "News"
454 context['categories'] = NewsCategory.objects.all()
455 context['news'] = NewsItem.objects.all().order_by('-date')
457 newsitemview = NewsItemView.as_view()
459 class News(TemplateView):
460 template_name = 'news.html'
461 def get_context_data(self, **kwargs):
462 context = super(News, self).get_context_data(**kwargs)
463 context['sectionName'] = "News"
464 context['focus'] = NewsItem.objects.filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
465 context['news'] = NewsItem.objects.all().order_by('-date')
468 news = News.as_view()
471 class Agenda(TemplateView):
472 template_name = 'agenda.html'
473 def get_context_data(self, **kwargs):
474 context = super(Agenda, self).get_context_data(**kwargs)
475 context['sectionName'] = "News"
476 context['agenda'] = NewsItem.objects.filter(
477 event_date__lte=date.today()).order_by('date')[:20]
478 context['news'] = NewsItem.objects.all().order_by('-date')
481 agenda = Agenda.as_view()
484 class Emissions(TemplateView):
485 template_name = 'emissions.html'
487 def get_context_data(self, **kwargs):
488 context = super(Emissions, self).get_context_data(**kwargs)
489 context['sectionName'] = "Emissions"
490 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
491 context['categories'] = Category.objects.all()
494 emissions = Emissions.as_view()
496 class EmissionsArchives(TemplateView):
497 template_name = 'emissions/archives.html'
499 def get_context_data(self, **kwargs):
500 context = super(EmissionsArchives, self).get_context_data(**kwargs)
501 context['sectionName'] = "Emissions"
502 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
503 context['categories'] = Category.objects.all()
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['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
515 podcastable=True, got_focus__isnull=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').distinct() [:10]
523 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
525 .select_related().extra(select={
526 'first_diffusion': 'emissions_diffusion.datetime', },
527 select_params=(False, True),
528 where=['''datetime = (SELECT MIN(datetime)
529 FROM emissions_diffusion
530 WHERE episode_id = emissions_episode.id)'''],
531 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:10]
536 listen = Listen.as_view()
538 @cache_control(max_age=15)
545 'title': d['episode'].title,
546 'url': d['episode'].get_absolute_url()
548 if d.get('emission'):
550 'title': d['emission'].title,
551 'url': d['emission'].get_absolute_url()
555 'title': d['nonstop'].title,
557 d.update(get_current_nonstop_track())
558 if d.get('current_slot'):
559 del d['current_slot']
563 class NewsItemDetailView(DetailView):
566 newsitem = NewsItemDetailView.as_view()
569 class PodcastsFeed(Feed):
570 title = 'Radio Panik - Podcasts'
572 description_template = 'feed/soundfile.html'
575 return SoundFile.objects.select_related().filter(
576 podcastable=True).order_by('-creation_timestamp')[:5]
578 def item_title(self, item):
580 return '%s - %s' % (item.title, item.episode.title)
581 return item.episode.title
583 def item_link(self, item):
584 return item.episode.get_absolute_url()
586 def item_enclosure_url(self, item):
587 current_site = Site.objects.get(id=settings.SITE_ID)
588 return add_domain(current_site.domain, item.get_format_url('mp3'))
590 def item_enclosure_length(self, item):
591 sound_path = item.get_format_path('mp3')
593 return os.stat(sound_path)[stat.ST_SIZE]
597 def item_enclosure_mime_type(self, item):
600 def item_pubdate(self, item):
601 return item.creation_timestamp
603 podcasts_feed = PodcastsFeed()
606 class RssNewsFeed(Feed):
607 title = 'Radio Panik'
609 description_template = 'feed/newsitem.html'
612 return NewsItem.objects.order_by('-date')[:10]
614 rss_news_feed = RssNewsFeed()
616 class AtomNewsFeed(RssNewsFeed):
617 feed_type = Atom1Feed
619 atom_news_feed = AtomNewsFeed()
623 class Party(TemplateView):
624 template_name = 'party.html'
626 def get_context_data(self, **kwargs):
627 context = super(Party, self).get_context_data(**kwargs)
628 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
631 focus.newsitem = NewsItem.objects.exclude(
632 image__isnull=True).exclude(image__exact='').order_by('?')[0]
633 elif t == 'emission':
634 focus.emission = Emission.objects.exclude(
635 image__isnull=True).exclude(image__exact='').order_by('?')[0]
637 focus.episode = Episode.objects.exclude(
638 image__isnull=True).exclude(image__exact='').order_by('?')[0]
639 elif t == 'soundfile':
640 focus.soundfile = SoundFile.objects.exclude(
641 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
643 context['focus'] = focus
647 party = Party.as_view()