1 from datetime import datetime, timedelta
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
24 from haystack.query import SearchQuerySet
25 from jsonresponse import to_json
27 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
28 Schedule, Nonstop, NewsItem, NewsCategory, Focus
30 from emissions.utils import whatsonair, period_program
32 from newsletter.forms import SubscribeForm
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'] = Emission.objects.get(slug=self.kwargs.get('emission_slug'))
117 except Emission.DoesNotExist:
119 context.update(self.get_emission_context(context['emission']))
121 episode = EpisodeDetailView.as_view()
124 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
126 template_name = 'emissions/episodes.html'
128 def get_context_data(self, **kwargs):
129 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
130 context['sectionName'] = "Emissions"
131 context['schedules'] = Schedule.objects.select_related().filter(
132 emission=self.object).order_by('rerun', 'datetime')
134 context['search_query'] = self.request.GET.get('q')
135 if context['search_query']:
137 sqs = SearchQuerySet().models(Episode).filter(
138 emission_slug_exact=self.object.slug, text=context['search_query'])
139 episode_ids = [x.pk for x in sqs]
143 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
145 emissionEpisodes = EmissionEpisodesDetailView.as_view()
147 class ProgramView(TemplateView):
148 template_name = 'program.html'
150 def get_context_data(self, year=None, week=None, **kwargs):
151 context = super(ProgramView, self).get_context_data(**kwargs)
152 context['sectionName'] = "Emissions"
154 context['weekday'] = datetime.today().weekday()
156 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
157 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
158 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
159 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
163 program = ProgramView.as_view()
171 def __init__(self, i, j):
176 def add_schedule(self, schedule):
177 end_time = schedule.datetime + timedelta(
178 minutes=schedule.get_duration())
179 self.time_label = '%02d:%02d-%02d:%02d' % (
180 schedule.datetime.hour,
181 schedule.datetime.minute,
184 self.schedules.append(schedule)
186 def __unicode__(self):
188 return ', '.join([x.emission.title for x in self.schedules])
192 def __eq__(self, other):
193 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
196 class Grid(TemplateView):
197 template_name = 'grid.html'
199 def get_context_data(self, **kwargs):
200 context = super(Grid, self).get_context_data(**kwargs)
201 context['sectionName'] = "Emissions"
203 nb_lines = 2 * 24 # the cells are half hours
206 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
207 # start grid after the night programs
208 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
211 for nonstop in Nonstop.objects.all():
212 if nonstop.start < nonstop.end:
213 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
214 nonstop.end.hour + nonstop.end.minute/60.,
215 nonstop.title, nonstop.slug])
218 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
220 nonstop.title, nonstop.slug])
222 nonstop.end.hour + nonstop.end.minute/60.,
223 nonstop.title, nonstop.slug])
226 for i in range(nb_lines):
229 grid[-1].append(TimeCell(i, j))
231 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
232 for time_cell in grid[-1]:
233 time_cell.nonstop = nonstop[2]
234 time_cell.nonstop_slug = nonstop[3]
236 # the one ending at 5am will be cut down, so we inscribe
237 # its duration manually
238 time_cell.time_label = '%02d:00-%02d:00' % (
239 nonstop[0], nonstop[1])
241 for schedule in Schedule.objects.prefetch_related(
242 'emission__categories').select_related().order_by('datetime'):
243 row_start = schedule.datetime.hour * 2 + \
244 int(math.ceil(schedule.datetime.minute / 30))
245 day_no = schedule.get_weekday()
247 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
248 if grid[(row_start+step)%nb_lines][day_no] is None:
249 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
250 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
252 # start grid after the night programs
253 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
255 # look for the case where the same emission has different schedules for
256 # the same time cell, for example if it lasts one hour the first week,
257 # and two hours the third week.
258 for i in range(nb_lines):
259 grid[i] = [x for x in grid[i] if x is not None]
260 for j, cell in enumerate(grid[i]):
261 if grid[i][j] is None:
263 if len(grid[i][j].schedules) > 1:
264 time_cell_emissions = {}
265 for schedule in grid[i][j].schedules:
266 if not schedule.emission.id in time_cell_emissions:
267 time_cell_emissions[schedule.emission.id] = []
268 time_cell_emissions[schedule.emission.id].append(schedule)
269 for schedule_list in time_cell_emissions.values():
270 if len(schedule_list) == 1:
272 # here it is, same cell, same emission, several
274 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
276 schedule = schedule_list[0]
277 end_time = schedule.datetime + timedelta(
278 minutes=schedule.get_duration())
279 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
280 schedule.datetime.hour,
281 schedule.datetime.minute,
285 for schedule in schedule_list[1:]:
286 grid[i][j].schedules.remove(schedule)
287 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
288 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
289 end_time.hour, end_time.minute, schedule.weeks_string)
293 # 1st thing is to merge cells on the same line, this will mostly catch
294 # consecutive nonstop cells
295 for i in range(nb_lines):
296 for j, cell in enumerate(grid[i]):
297 if grid[i][j] is None:
301 # if the cells are identical, they are removed from the
302 # grid, and current cell width is increased
303 while grid[i][j+t] == cell:
310 # once we're done we remove empty cells
311 grid[i] = [x for x in grid[i] if x is not None]
313 # 2nd thing is to merge cells vertically, this is emissions that last
314 # for more than 30 minutes
315 for i in range(nb_lines):
316 grid[i] = [x for x in grid[i] if x is not None]
317 for j, cell in enumerate(grid[i]):
318 if grid[i][j] is None:
323 # we look if the next time cell has the same emissions
324 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
325 if x == cell and x.y == cell.y and x.w == cell.w]
327 # if the cell was identical, we remove it and
328 # increase current cell height
329 bj, same_cell_below = same_cell_below[0]
330 del grid[i+cell.h][bj]
333 # if the cell is different, we have a closer look
334 # to it, so we can remove emissions that will
335 # already be mentioned in the current cell.
338 # - 7am30, seuls contre tout, 1h30
339 # - 8am, du pied gauche & la voix de la rue, 1h
340 # should produce: (this is case A)
342 # | seuls contre tout |
343 # |---------------------|
346 # | la voix de la rue |
348 # On the other hand, if all three emissions started
349 # at 7am30, we want: (this is case B)
351 # | seuls contre tout |
353 # | la voix de la rue |
354 # that is we merge all of them, ignoring the fact
355 # that the other emissions will stop at 8am30
356 current_cell_schedules = set(grid[i][j].schedules)
357 current_cell_emissions = set([x.emission for x in current_cell_schedules])
359 while True and current_cell_schedules:
360 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
361 if not same_cell_below:
364 same_cell_below = same_cell_below[0]
365 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
367 if current_cell_emissions.issubset(same_cell_below_emissions):
368 # this handles case A (see comment above)
369 for schedule in current_cell_schedules:
370 if schedule in same_cell_below.schedules:
371 same_cell_below.schedules.remove(schedule)
372 elif same_cell_below_emissions and \
373 current_cell_emissions.issuperset(same_cell_below_emissions):
374 # this handles case B (see comment above)
375 # we set the cell time label to the longest
377 grid[i][j].time_label = same_cell_below.time_label
378 # then we sort emissions so the longest are
380 grid[i][j].schedules.sort(
381 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
382 # then we add individual time labels to the
384 for schedule in current_cell_schedules:
385 if schedule not in same_cell_below.schedules:
386 end_time = schedule.datetime + timedelta(
387 minutes=schedule.get_duration())
388 schedule.time_label = '%02d:%02d-%02d:%02d' % (
389 schedule.datetime.hour,
390 schedule.datetime.minute,
394 grid[i+cursor].remove(same_cell_below)
395 elif same_cell_below_emissions and \
396 current_cell_emissions.intersection(same_cell_below_emissions):
397 same_cell_below.schedules = [x for x in
398 same_cell_below.schedules if
400 current_cell_emissions or
401 x.get_duration() < 30]
411 context['grid'] = grid
412 context['times'] = times
413 context['categories'] = Category.objects.all()
414 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
415 'Vendredi', 'Samedi', 'Dimanche']
419 grid = Grid.as_view()
422 class Home(TemplateView):
423 template_name = 'home.html'
425 def get_context_data(self, **kwargs):
426 context = super(Home, self).get_context_data(**kwargs)
427 context['sectionName'] = "Home"
428 context['emissions'] = Emission.objects.filter(archived=False).order_by('-creation_timestamp')[:3]
429 context['newsitems'] = NewsItem.objects.order_by('-date')[:3]
431 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
432 podcastable=True, fragment=False) \
433 .select_related().extra(select={
434 'first_diffusion': 'emissions_diffusion.datetime', },
435 select_params=(False, True),
436 where=['''datetime = (SELECT MIN(datetime)
437 FROM emissions_diffusion
438 WHERE episode_id = emissions_episode.id)'''],
439 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:3]
441 context['newsletter_form'] = SubscribeForm()
445 home = Home.as_view()
447 class NewsItemView(DetailView):
449 def get_context_data(self, **kwargs):
450 context = super(NewsItemView, self).get_context_data(**kwargs)
451 context['sectionName'] = "News"
452 context['categories'] = NewsCategory.objects.all()
453 context['news'] = NewsItem.objects.all().order_by('-date')
455 newsitemview = NewsItemView.as_view()
457 class News(TemplateView):
458 template_name = 'news.html'
459 def get_context_data(self, **kwargs):
460 context = super(News, self).get_context_data(**kwargs)
461 context['sectionName'] = "News"
462 context['focus'] = NewsItem.objects.filter(got_focus__isnull=False).select_related('category').order_by('-date')[:10]
463 context['news'] = NewsItem.objects.all().order_by('-date')
466 news = News.as_view()
469 class Emissions(TemplateView):
470 template_name = 'emissions.html'
472 def get_context_data(self, **kwargs):
473 context = super(Emissions, self).get_context_data(**kwargs)
474 context['sectionName'] = "Emissions"
475 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
476 context['categories'] = Category.objects.all()
479 emissions = Emissions.as_view()
481 class EmissionsArchives(TemplateView):
482 template_name = 'emissions/archives.html'
484 def get_context_data(self, **kwargs):
485 context = super(EmissionsArchives, self).get_context_data(**kwargs)
486 context['sectionName'] = "Emissions"
487 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
488 context['categories'] = Category.objects.all()
490 emissionsArchives = EmissionsArchives.as_view()
493 class Listen(TemplateView):
494 template_name = 'listen.html'
496 def get_context_data(self, **kwargs):
497 context = super(Listen, self).get_context_data(**kwargs)
498 context['sectionName'] = "Listen"
499 context['focus'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
500 podcastable=True, got_focus__isnull=False) \
501 .select_related().extra(select={
502 'first_diffusion': 'emissions_diffusion.datetime', },
503 select_params=(False, True),
504 where=['''datetime = (SELECT MIN(datetime)
505 FROM emissions_diffusion
506 WHERE episode_id = emissions_episode.id)'''],
507 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
508 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
510 .select_related().extra(select={
511 'first_diffusion': 'emissions_diffusion.datetime', },
512 select_params=(False, True),
513 where=['''datetime = (SELECT MIN(datetime)
514 FROM emissions_diffusion
515 WHERE episode_id = emissions_episode.id)'''],
516 tables=['emissions_diffusion'],).order_by('-creation_timestamp').distinct() [:10]
521 listen = Listen.as_view()
523 @cache_control(max_age=25)
530 'title': d['episode'].title,
531 'url': d['episode'].get_absolute_url()
533 if d.get('emission'):
535 'title': d['emission'].title,
536 'url': d['emission'].get_absolute_url()
540 'title': d['nonstop'].title,
542 if d.get('current_slot'):
543 del d['current_slot']
547 class NewsItemDetailView(DetailView):
550 newsitem = NewsItemDetailView.as_view()
553 class PodcastsFeed(Feed):
554 title = 'Radio Panik - Podcasts'
556 description_template = 'feed/soundfile.html'
559 return SoundFile.objects.select_related().filter(
560 podcastable=True).order_by('-creation_timestamp')[:5]
562 def item_title(self, item):
564 return '%s - %s' % (item.title, item.episode.title)
565 return item.episode.title
567 def item_link(self, item):
568 return item.episode.get_absolute_url()
570 def item_enclosure_url(self, item):
571 current_site = Site.objects.get(id=settings.SITE_ID)
572 return add_domain(current_site.domain, item.get_format_url('mp3'))
574 def item_enclosure_length(self, item):
575 sound_path = item.get_format_path('mp3')
577 return os.stat(sound_path)[stat.ST_SIZE]
581 def item_enclosure_mime_type(self, item):
584 def item_pubdate(self, item):
585 return item.creation_timestamp
587 podcasts_feed = PodcastsFeed()
590 class FiberPageView(fiber.views.FiberTemplateView):
591 def get_context_data(self, **kwargs):
592 context = super(FiberPageView, self).get_context_data(**kwargs)
593 context['sectionName'] = 'About'
595 fiber_page = FiberPageView.as_view()
598 class RssNewsFeed(Feed):
599 title = 'Radio Panik'
601 description_template = 'feed/newsitem.html'
604 return NewsItem.objects.order_by('-date')[:10]
606 rss_news_feed = RssNewsFeed()
608 class AtomNewsFeed(RssNewsFeed):
609 feed_type = Atom1Feed
611 atom_news_feed = AtomNewsFeed()
615 class Party(TemplateView):
616 template_name = 'party.html'
618 def get_context_data(self, **kwargs):
619 context = super(Party, self).get_context_data(**kwargs)
620 t = random.choice(['newsitem']*2 + ['emission']*3 + ['soundfile']*1 + ['episode']*2)
623 focus.newsitem = NewsItem.objects.exclude(
624 image__isnull=True).exclude(image__exact='').order_by('?')[0]
625 elif t == 'emission':
626 focus.emission = Emission.objects.exclude(
627 image__isnull=True).exclude(image__exact='').order_by('?')[0]
629 focus.episode = Episode.objects.exclude(
630 image__isnull=True).exclude(image__exact='').order_by('?')[0]
631 elif t == 'soundfile':
632 focus.soundfile = SoundFile.objects.exclude(
633 episode__image__isnull=True).exclude(episode__image__exact='').order_by('?')[0]
635 context['focus'] = focus
639 party = Party.as_view()