1 from datetime import datetime, timedelta
8 from django.conf import settings
10 from django.views.decorators.cache import cache_control
11 from django.views.generic.base import TemplateView
12 from django.views.generic.detail import DetailView
13 from django.views.decorators.csrf import csrf_exempt
14 from django.views.generic.dates import _date_from_string
16 from django.core.paginator import Paginator
18 from django.contrib.sites.models import Site
19 from django.contrib.syndication.views import Feed, add_domain
20 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
37 def get_emission_context(self, emission, episode_ids=None):
40 # get all episodes, with an additional attribute to get the date of
41 # their first diffusion
42 episodes_queryset = Episode.objects.select_related()
43 if episode_ids is not None:
44 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
46 episodes_queryset = episodes_queryset.filter(emission=emission)
48 context['episodes'] = \
49 episodes_queryset.extra(select={
50 'first_diffusion': 'emissions_diffusion.datetime',
52 select_params=(False, True),
53 where=['''datetime = (SELECT MIN(datetime)
54 FROM emissions_diffusion
55 WHERE episode_id = emissions_episode.id
56 AND datetime <= CURRENT_TIMESTAMP)'''],
57 tables=['emissions_diffusion'],
58 ).order_by('-first_diffusion').distinct()
60 context['futurEpisodes'] = \
61 episodes_queryset.extra(select={
62 'first_diffusion': 'emissions_diffusion.datetime',
64 select_params=(False, True),
65 where=['''datetime = (SELECT MIN(datetime)
66 FROM emissions_diffusion
67 WHERE episode_id = emissions_episode.id
68 AND datetime > CURRENT_TIMESTAMP)'''],
69 tables=['emissions_diffusion'],
70 ).order_by('first_diffusion').distinct()
73 # get all related soundfiles in a single query
75 if episode_ids is not None:
76 for episode_id in episode_ids:
77 soundfiles[episode_id] = None
79 for episode in Episode.objects.filter(emission=emission):
80 soundfiles[episode.id] = None
82 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
83 fragment=False, episode__emission=emission):
84 soundfiles[soundfile.episode_id] = soundfile
86 Episode.set_prefetched_soundfiles(soundfiles)
88 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
93 class EmissionDetailView(DetailView, EmissionMixin):
96 def get_context_data(self, **kwargs):
97 context = super(EmissionDetailView, self).get_context_data(**kwargs)
98 context['sectionName'] = "Emissions"
99 context['schedules'] = Schedule.objects.select_related().filter(
100 emission=self.object).order_by('rerun', 'datetime')
101 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
102 context.update(self.get_emission_context(self.object))
104 emission = EmissionDetailView.as_view()
106 class EpisodeDetailView(DetailView, EmissionMixin):
109 def get_context_data(self, **kwargs):
110 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
111 context['sectionName'] = "Emissions"
112 context['diffusions'] = Diffusion.objects.select_related().filter(episode=self.object.id)
113 context['emission'] = Emission.objects.get(slug=self.kwargs.get('emission_slug'))
114 context.update(self.get_emission_context(context['emission']))
116 episode = EpisodeDetailView.as_view()
119 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
121 template_name = 'emissions/episodes.html'
123 def get_context_data(self, **kwargs):
124 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
125 context['sectionName'] = "Emissions"
126 context['schedules'] = Schedule.objects.select_related().filter(
127 emission=self.object).order_by('rerun', 'datetime')
129 context['search_query'] = self.request.GET.get('q')
130 if context['search_query']:
132 sqs = SearchQuerySet().models(Episode).filter(
133 emission_slug_exact=self.object.slug, text=context['search_query'])
134 episode_ids = [x.pk for x in sqs]
138 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
140 emissionEpisodes = EmissionEpisodesDetailView.as_view()
142 class ProgramView(TemplateView):
143 template_name = 'program.html'
145 def get_context_data(self, year=None, week=None, **kwargs):
146 context = super(ProgramView, self).get_context_data(**kwargs)
147 context['sectionName'] = "Emissions"
149 context['weekday'] = datetime.today().weekday()
151 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
152 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
153 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
154 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
158 program = ProgramView.as_view()
166 def __init__(self, i, j):
171 def add_schedule(self, schedule):
172 end_time = schedule.datetime + timedelta(
173 minutes=schedule.get_duration())
174 self.time_label = '%02d:%02d-%02d:%02d' % (
175 schedule.datetime.hour,
176 schedule.datetime.minute,
179 self.schedules.append(schedule)
181 def __unicode__(self):
183 return ', '.join([x.emission.title for x in self.schedules])
187 def __eq__(self, other):
188 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
191 class Grid(TemplateView):
192 template_name = 'grid.html'
194 def get_context_data(self, **kwargs):
195 context = super(Grid, self).get_context_data(**kwargs)
196 context['sectionName'] = "Emissions"
198 nb_lines = 2 * 24 # the cells are half hours
201 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
202 # start grid after the night programs
203 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
206 for nonstop in Nonstop.objects.all():
207 if nonstop.start < nonstop.end:
208 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
209 nonstop.end.hour + nonstop.end.minute/60.,
210 nonstop.title, nonstop.slug])
213 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
215 nonstop.title, nonstop.slug])
217 nonstop.end.hour + nonstop.end.minute/60.,
218 nonstop.title, nonstop.slug])
221 for i in range(nb_lines):
224 grid[-1].append(TimeCell(i, j))
226 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
227 for time_cell in grid[-1]:
228 time_cell.nonstop = nonstop[2]
229 time_cell.nonstop_slug = nonstop[3]
231 # the one ending at 5am will be cut down, so we inscribe
232 # its duration manually
233 time_cell.time_label = '%02d:00-%02d:00' % (
234 nonstop[0], nonstop[1])
236 for schedule in Schedule.objects.prefetch_related(
237 'emission__categories').select_related().order_by('datetime'):
238 row_start = schedule.datetime.hour * 2 + \
239 int(math.ceil(schedule.datetime.minute / 30))
240 day_no = schedule.get_weekday()
242 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
243 if grid[(row_start+step)%nb_lines][day_no] is None:
244 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
245 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
247 # start grid after the night programs
248 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
250 # look for the case where the same emission has different schedules for
251 # the same time cell, for example if it lasts one hour the first week,
252 # and two hours the third week.
253 for i in range(nb_lines):
254 grid[i] = [x for x in grid[i] if x is not None]
255 for j, cell in enumerate(grid[i]):
256 if grid[i][j] is None:
258 if len(grid[i][j].schedules) > 1:
259 time_cell_emissions = {}
260 for schedule in grid[i][j].schedules:
261 if not schedule.emission.id in time_cell_emissions:
262 time_cell_emissions[schedule.emission.id] = []
263 time_cell_emissions[schedule.emission.id].append(schedule)
264 for schedule_list in time_cell_emissions.values():
265 if len(schedule_list) == 1:
267 # here it is, same cell, same emission, several
269 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
271 schedule = schedule_list[0]
272 end_time = schedule.datetime + timedelta(
273 minutes=schedule.get_duration())
274 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
275 schedule.datetime.hour,
276 schedule.datetime.minute,
280 for schedule in schedule_list[1:]:
281 grid[i][j].schedules.remove(schedule)
282 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
283 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
284 end_time.hour, end_time.minute, schedule.weeks_string)
288 # 1st thing is to merge cells on the same line, this will mostly catch
289 # consecutive nonstop cells
290 for i in range(nb_lines):
291 for j, cell in enumerate(grid[i]):
292 if grid[i][j] is None:
296 # if the cells are identical, they are removed from the
297 # grid, and current cell width is increased
298 while grid[i][j+t] == cell:
305 # once we're done we remove empty cells
306 grid[i] = [x for x in grid[i] if x is not None]
308 # 2nd thing is to merge cells vertically, this is emissions that last
309 # for more than 30 minutes
310 for i in range(nb_lines):
311 grid[i] = [x for x in grid[i] if x is not None]
312 for j, cell in enumerate(grid[i]):
313 if grid[i][j] is None:
318 # we look if the next time cell has the same emissions
319 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
320 if x == cell and x.y == cell.y and x.w == cell.w]
322 # if the cell was identical, we remove it and
323 # increase current cell height
324 bj, same_cell_below = same_cell_below[0]
325 del grid[i+cell.h][bj]
328 # if the cell is different, we have a closer look
329 # to it, so we can remove emissions that will
330 # already be mentioned in the current cell.
333 # - 7am30, seuls contre tout, 1h30
334 # - 8am, du pied gauche & la voix de la rue, 1h
335 # should produce: (this is case A)
337 # | seuls contre tout |
338 # |---------------------|
341 # | la voix de la rue |
343 # On the other hand, if all three emissions started
344 # at 7am30, we want: (this is case B)
346 # | seuls contre tout |
348 # | la voix de la rue |
349 # that is we merge all of them, ignoring the fact
350 # that the other emissions will stop at 8am30
351 current_cell_schedules = set(grid[i][j].schedules)
352 current_cell_emissions = set([x.emission for x in current_cell_schedules])
354 while True and current_cell_schedules:
355 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
356 if not same_cell_below:
359 same_cell_below = same_cell_below[0]
360 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
362 if current_cell_emissions.issubset(same_cell_below_emissions):
363 # this handles case A (see comment above)
364 for schedule in current_cell_schedules:
365 if schedule in same_cell_below.schedules:
366 same_cell_below.schedules.remove(schedule)
367 elif same_cell_below_emissions and \
368 current_cell_emissions.issuperset(same_cell_below_emissions):
369 # this handles case B (see comment above)
370 # we set the cell time label to the longest
372 grid[i][j].time_label = same_cell_below.time_label
373 # then we sort emissions so the longest are
375 grid[i][j].schedules.sort(
376 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
377 # then we add individual time labels to the
379 for schedule in current_cell_schedules:
380 if schedule not in same_cell_below.schedules:
381 end_time = schedule.datetime + timedelta(
382 minutes=schedule.get_duration())
383 schedule.time_label = '%02d:%02d-%02d:%02d' % (
384 schedule.datetime.hour,
385 schedule.datetime.minute,
389 grid[i+cursor].remove(same_cell_below)
390 elif same_cell_below_emissions and \
391 current_cell_emissions.intersection(same_cell_below_emissions):
392 same_cell_below.schedules = [x for x in
393 same_cell_below.schedules if
395 current_cell_emissions or
396 x.get_duration() < 30]
406 context['grid'] = grid
407 context['times'] = times
408 context['categories'] = Category.objects.all()
409 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
410 'Vendredi', 'Samedi', 'Dimanche']
414 grid = Grid.as_view()
417 class Home(TemplateView):
418 template_name = 'home.html'
420 def get_context_data(self, **kwargs):
421 context = super(Home, self).get_context_data(**kwargs)
422 context['sectionName'] = "Home"
423 context['emissions'] = Emission.objects.filter(archived=False).order_by('-creation_timestamp')[:3]
424 context['newsitems'] = NewsItem.objects.order_by('-date')[:3]
426 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
427 podcastable=True, fragment=False) \
428 .select_related().extra(select={
429 'first_diffusion': 'emissions_diffusion.datetime', },
430 select_params=(False, True),
431 where=['''datetime = (SELECT MIN(datetime)
432 FROM emissions_diffusion
433 WHERE episode_id = emissions_episode.id)'''],
434 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:3]
436 context['newsletter_form'] = SubscribeForm()
440 home = Home.as_view()
442 class NewsItemView(DetailView):
444 def get_context_data(self, **kwargs):
445 context = super(NewsItemView, self).get_context_data(**kwargs)
446 context['sectionName'] = "News"
447 context['categories'] = NewsCategory.objects.all()
448 context['news'] = NewsItem.objects.all().order_by('-date')
450 newsitemview = NewsItemView.as_view()
452 class News(TemplateView):
453 template_name = 'news.html'
454 def get_context_data(self, **kwargs):
455 context = super(News, self).get_context_data(**kwargs)
456 context['sectionName'] = "News"
457 context['focus'] = NewsItem.objects.filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
458 context['news'] = NewsItem.objects.all().order_by('-date')
461 news = News.as_view()
464 class Emissions(TemplateView):
465 template_name = 'emissions.html'
467 def get_context_data(self, **kwargs):
468 context = super(Emissions, self).get_context_data(**kwargs)
469 context['sectionName'] = "Emissions"
470 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
471 context['categories'] = Category.objects.all()
474 emissions = Emissions.as_view()
476 class EmissionsArchives(TemplateView):
477 template_name = 'emissions/archives.html'
479 def get_context_data(self, **kwargs):
480 context = super(EmissionsArchives, self).get_context_data(**kwargs)
481 context['sectionName'] = "Emissions"
482 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
483 context['categories'] = Category.objects.all()
485 emissionsArchives = EmissionsArchives.as_view()
488 class Listen(TemplateView):
489 template_name = 'listen.html'
491 def get_context_data(self, **kwargs):
492 context = super(Listen, self).get_context_data(**kwargs)
493 context['sectionName'] = "Listen"
494 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
495 podcastable=True, got_focus__isnull=False) \
496 .select_related().extra(select={
497 'first_diffusion': 'emissions_diffusion.datetime', },
498 select_params=(False, True),
499 where=['''datetime = (SELECT MIN(datetime)
500 FROM emissions_diffusion
501 WHERE episode_id = emissions_episode.id)'''],
502 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
503 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
505 .select_related().extra(select={
506 'first_diffusion': 'emissions_diffusion.datetime', },
507 select_params=(False, True),
508 where=['''datetime = (SELECT MIN(datetime)
509 FROM emissions_diffusion
510 WHERE episode_id = emissions_episode.id)'''],
511 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:10]
516 listen = Listen.as_view()
518 @cache_control(max_age=25)
525 'title': d['episode'].title,
526 'url': d['episode'].get_absolute_url()
528 if d.get('emission'):
530 'title': d['emission'].title,
531 'url': d['emission'].get_absolute_url()
535 'title': d['nonstop'].title,
537 if d.get('current_slot'):
538 del d['current_slot']
542 class NewsItemDetailView(DetailView):
545 newsitem = NewsItemDetailView.as_view()
548 class PodcastsFeed(Feed):
549 title = 'Radio Panik - Podcasts'
551 description_template = 'feed/soundfile.html'
554 return SoundFile.objects.select_related().filter(
555 podcastable=True).order_by('-creation_timestamp')[:5]
557 def item_title(self, item):
559 return '%s - %s' % (item.title, item.episode.title)
560 return item.episode.title
562 def item_link(self, item):
563 return item.episode.get_absolute_url()
565 def item_enclosure_url(self, item):
566 current_site = Site.objects.get(id=settings.SITE_ID)
567 return add_domain(current_site.domain, item.get_format_url('mp3'))
569 def item_enclosure_length(self, item):
570 sound_path = item.get_format_path('mp3')
572 return os.stat(sound_path)[stat.ST_SIZE]
576 def item_enclosure_mime_type(self, item):
579 def item_pubdate(self, item):
580 return item.creation_timestamp
582 podcasts_feed = PodcastsFeed()
585 class FiberPageView(fiber.views.FiberTemplateView):
586 def get_context_data(self, **kwargs):
587 context = super(FiberPageView, self).get_context_data(**kwargs)
588 context['sectionName'] = 'About'
590 fiber_page = FiberPageView.as_view()
593 class RssNewsFeed(Feed):
594 title = 'Radio Panik'
596 description_template = 'feed/newsitem.html'
599 return NewsItem.objects.order_by('-date')[:10]
601 rss_news_feed = RssNewsFeed()
603 class AtomNewsFeed(RssNewsFeed):
604 feed_type = Atom1Feed
606 atom_news_feed = AtomNewsFeed()
610 class Party(TemplateView):
611 template_name = 'party.html'
613 def get_context_data(self, **kwargs):
614 context = super(Party, self).get_context_data(**kwargs)
615 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
618 focus.newsitem = NewsItem.objects.exclude(
619 image__isnull=True).exclude(image__exact='').order_by('?')[0]
620 elif t == 'emission':
621 focus.emission = Emission.objects.exclude(
622 image__isnull=True).exclude(image__exact='').order_by('?')[0]
624 focus.episode = Episode.objects.exclude(
625 image__isnull=True).exclude(image__exact='').order_by('?')[0]
626 elif t == 'soundfile':
627 focus.soundfile = SoundFile.objects.exclude(
628 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
630 context['focus'] = focus
634 party = Party.as_view()