1 from datetime import datetime, timedelta
7 from django.conf import settings
9 from django.views.decorators.cache import cache_control
10 from django.views.generic.base import TemplateView
11 from django.views.generic.detail import DetailView
12 from django.views.decorators.csrf import csrf_exempt
13 from django.views.generic.dates import _date_from_string
15 from django.core.paginator import Paginator
17 from django.contrib.sites.models import Site
18 from django.contrib.syndication.views import Feed, add_domain
19 from django.utils.feedgenerator import Atom1Feed
22 from haystack.query import SearchQuerySet
23 from jsonresponse import to_json
25 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
26 Schedule, Nonstop, NewsItem, NewsCategory, Focus
28 from emissions.utils import whatsonair, period_program
30 from newsletter.forms import SubscribeForm
36 def get_emission_context(self, emission, episode_ids=None):
39 # get all episodes, with an additional attribute to get the date of
40 # their first diffusion
41 episodes_queryset = Episode.objects.select_related()
42 if episode_ids is not None:
43 episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
45 episodes_queryset = episodes_queryset.filter(emission=emission)
47 context['episodes'] = \
48 episodes_queryset.extra(select={
49 'first_diffusion': 'emissions_diffusion.datetime',
51 select_params=(False, True),
52 where=['''datetime = (SELECT MIN(datetime)
53 FROM emissions_diffusion
54 WHERE episode_id = emissions_episode.id)'''],
55 tables=['emissions_diffusion'],
56 ).order_by('-first_diffusion').distinct()
58 # get all related soundfiles in a single query
60 if episode_ids is not None:
61 for episode_id in episode_ids:
62 soundfiles[episode_id] = None
64 for episode in Episode.objects.filter(emission=emission):
65 soundfiles[episode.id] = None
67 for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
68 fragment=False, episode__emission=emission):
69 soundfiles[soundfile.episode_id] = soundfile
71 Episode.set_prefetched_soundfiles(soundfiles)
73 #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
78 class EmissionDetailView(DetailView, EmissionMixin):
81 def get_context_data(self, **kwargs):
82 context = super(EmissionDetailView, self).get_context_data(**kwargs)
83 context['sectionName'] = "Emissions"
84 context['schedules'] = Schedule.objects.select_related().filter(
85 emission=self.object).order_by('rerun', 'datetime')
86 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
87 context.update(self.get_emission_context(self.object))
89 emission = EmissionDetailView.as_view()
91 class EpisodeDetailView(DetailView, EmissionMixin):
94 def get_context_data(self, **kwargs):
95 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
96 context['sectionName'] = "Emissions"
97 context['diffusions'] = Diffusion.objects.select_related().filter(episode=self.object.id)
98 context['soundfiles'] = SoundFile.objects.select_related().filter(episode=self.object.id)
99 context['emission'] = Emission.objects.get(slug=self.kwargs.get('emission_slug'))
100 context.update(self.get_emission_context(context['emission']))
102 episode = EpisodeDetailView.as_view()
105 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
107 template_name = 'emissions/episodes.html'
109 def get_context_data(self, **kwargs):
110 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
111 context['sectionName'] = "Emissions"
112 context['schedules'] = Schedule.objects.select_related().filter(
113 emission=self.object).order_by('rerun', 'datetime')
115 context['search_query'] = self.request.GET.get('q')
116 if context['search_query']:
118 sqs = SearchQuerySet().models(Episode).filter(
119 emission_slug_exact=self.object.slug, text=context['search_query'])
120 episode_ids = [x.pk for x in sqs]
124 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
126 emissionEpisodes = EmissionEpisodesDetailView.as_view()
128 class ProgramView(TemplateView):
129 template_name = 'program.html'
131 def get_context_data(self, year=None, week=None, **kwargs):
132 context = super(ProgramView, self).get_context_data(**kwargs)
133 context['sectionName'] = "Emissions"
135 context['weekday'] = datetime.today().weekday()
137 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
138 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
139 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
140 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
144 program = ProgramView.as_view()
152 def __init__(self, i, j):
157 def add_schedule(self, schedule):
158 end_time = schedule.datetime + timedelta(
159 minutes=schedule.get_duration())
160 self.time_label = '%02d:%02d-%02d:%02d' % (
161 schedule.datetime.hour,
162 schedule.datetime.minute,
165 self.schedules.append(schedule)
167 def __unicode__(self):
169 return ', '.join([x.emission.title for x in self.schedules])
173 def __eq__(self, other):
174 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
177 class Grid(TemplateView):
178 template_name = 'grid.html'
180 def get_context_data(self, **kwargs):
181 context = super(Grid, self).get_context_data(**kwargs)
182 context['sectionName'] = "Emissions"
184 nb_lines = 2 * 24 # the cells are half hours
187 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
188 # start grid after the night programs
189 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
192 for nonstop in Nonstop.objects.all():
193 if nonstop.start < nonstop.end:
194 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
195 nonstop.end.hour + nonstop.end.minute/60.,
196 nonstop.title, nonstop.slug])
199 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
201 nonstop.title, nonstop.slug])
203 nonstop.end.hour + nonstop.end.minute/60.,
204 nonstop.title, nonstop.slug])
207 for i in range(nb_lines):
210 grid[-1].append(TimeCell(i, j))
212 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
213 for time_cell in grid[-1]:
214 time_cell.nonstop = nonstop[2]
215 time_cell.nonstop_slug = nonstop[3]
217 # the one ending at 5am will be cut down, so we inscribe
218 # its duration manually
219 time_cell.time_label = '%02d:00-%02d:00' % (
220 nonstop[0], nonstop[1])
222 for schedule in Schedule.objects.prefetch_related(
223 'emission__categories').select_related().order_by('datetime'):
224 row_start = schedule.datetime.hour * 2 + \
225 int(math.ceil(schedule.datetime.minute / 30))
226 day_no = schedule.get_weekday()
228 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
229 if grid[(row_start+step)%nb_lines][day_no] is None:
230 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
231 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
233 # start grid after the night programs
234 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
236 # look for the case where the same emission has different schedules for
237 # the same time cell, for example if it lasts one hour the first week,
238 # and two hours the third week.
239 for i in range(nb_lines):
240 grid[i] = [x for x in grid[i] if x is not None]
241 for j, cell in enumerate(grid[i]):
242 if grid[i][j] is None:
244 if len(grid[i][j].schedules) > 1:
245 time_cell_emissions = {}
246 for schedule in grid[i][j].schedules:
247 if not schedule.emission.id in time_cell_emissions:
248 time_cell_emissions[schedule.emission.id] = []
249 time_cell_emissions[schedule.emission.id].append(schedule)
250 for schedule_list in time_cell_emissions.values():
251 if len(schedule_list) == 1:
253 # here it is, same cell, same emission, several
255 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
257 schedule = schedule_list[0]
258 end_time = schedule.datetime + timedelta(
259 minutes=schedule.get_duration())
260 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
261 schedule.datetime.hour,
262 schedule.datetime.minute,
266 for schedule in schedule_list[1:]:
267 grid[i][j].schedules.remove(schedule)
268 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
269 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
270 end_time.hour, end_time.minute, schedule.weeks_string)
274 # 1st thing is to merge cells on the same line, this will mostly catch
275 # consecutive nonstop cells
276 for i in range(nb_lines):
277 for j, cell in enumerate(grid[i]):
278 if grid[i][j] is None:
282 # if the cells are identical, they are removed from the
283 # grid, and current cell width is increased
284 while grid[i][j+t] == cell:
291 # once we're done we remove empty cells
292 grid[i] = [x for x in grid[i] if x is not None]
294 # 2nd thing is to merge cells vertically, this is emissions that last
295 # for more than 30 minutes
296 for i in range(nb_lines):
297 grid[i] = [x for x in grid[i] if x is not None]
298 for j, cell in enumerate(grid[i]):
299 if grid[i][j] is None:
304 # we look if the next time cell has the same emissions
305 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
306 if x == cell and x.y == cell.y and x.w == cell.w]
308 # if the cell was identical, we remove it and
309 # increase current cell height
310 bj, same_cell_below = same_cell_below[0]
311 del grid[i+cell.h][bj]
314 # if the cell is different, we have a closer look
315 # to it, so we can remove emissions that will
316 # already be mentioned in the current cell.
319 # - 7am30, seuls contre tout, 1h30
320 # - 8am, du pied gauche & la voix de la rue, 1h
321 # should produce: (this is case A)
323 # | seuls contre tout |
324 # |---------------------|
327 # | la voix de la rue |
329 # On the other hand, if all three emissions started
330 # at 7am30, we want: (this is case B)
332 # | seuls contre tout |
334 # | la voix de la rue |
335 # that is we merge all of them, ignoring the fact
336 # that the other emissions will stop at 8am30
337 current_cell_schedules = set(grid[i][j].schedules)
338 current_cell_emissions = set([x.emission for x in current_cell_schedules])
340 while True and current_cell_schedules:
341 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
342 if not same_cell_below:
345 same_cell_below = same_cell_below[0]
346 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
348 if current_cell_emissions.issubset(same_cell_below_emissions):
349 # this handles case A (see comment above)
350 for schedule in current_cell_schedules:
351 if schedule in same_cell_below.schedules:
352 same_cell_below.schedules.remove(schedule)
353 elif same_cell_below_emissions and \
354 current_cell_emissions.issuperset(same_cell_below_emissions):
355 # this handles case B (see comment above)
356 # we set the cell time label to the longest
358 grid[i][j].time_label = same_cell_below.time_label
359 # then we sort emissions so the longest are
361 grid[i][j].schedules.sort(
362 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
363 # then we add individual time labels to the
365 for schedule in current_cell_schedules:
366 if schedule not in same_cell_below.schedules:
367 end_time = schedule.datetime + timedelta(
368 minutes=schedule.get_duration())
369 schedule.time_label = '%02d:%02d-%02d:%02d' % (
370 schedule.datetime.hour,
371 schedule.datetime.minute,
375 grid[i+cursor].remove(same_cell_below)
376 elif same_cell_below_emissions and \
377 current_cell_emissions.intersection(same_cell_below_emissions):
378 same_cell_below.schedules = [x for x in
379 same_cell_below.schedules if
381 current_cell_emissions or
382 x.get_duration() < 30]
392 context['grid'] = grid
393 context['times'] = times
394 context['categories'] = Category.objects.all()
395 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
396 'Vendredi', 'Samedi', 'Dimanche']
400 grid = Grid.as_view()
403 class Home(TemplateView):
404 template_name = 'home.html'
406 def get_context_data(self, **kwargs):
407 context = super(Home, self).get_context_data(**kwargs)
408 context['sectionName'] = "Home"
409 context['focus'] = Focus.objects.select_related('emission', 'newsitem',
410 'soundfile', 'episode', 'newsitem__category').order_by('?')[:12]
411 context['emissions'] = Emission.objects.filter(archived=False,
412 creation_timestamp__gte=datetime(2013, 9, 13)).order_by('title')
414 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
415 podcastable=True, fragment=False) \
416 .select_related().extra(select={
417 'first_diffusion': 'emissions_diffusion.datetime', },
418 select_params=(False, True),
419 where=['''datetime = (SELECT MIN(datetime)
420 FROM emissions_diffusion
421 WHERE episode_id = emissions_episode.id)'''],
422 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:3]
424 context['newsletter_form'] = SubscribeForm()
428 home = Home.as_view()
430 class NewsItemView(DetailView):
432 def get_context_data(self, **kwargs):
433 context = super(NewsItemView, self).get_context_data(**kwargs)
434 context['sectionName'] = "News"
435 context['categories'] = NewsCategory.objects.all()
436 context['news'] = NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:10]
438 newsitemview = NewsItemView.as_view()
440 class News(TemplateView):
441 template_name = 'news.html'
442 def get_context_data(self, **kwargs):
443 context = super(News, self).get_context_data(**kwargs)
444 context['sectionName'] = "News"
445 newsitem_ids = [x.newsitem_id for x in Focus.objects.filter(newsitem__isnull=False)]
446 context['focus'] = NewsItem.objects.filter(id__in=newsitem_ids).select_related('category').order_by('-date')[0:9]
447 context['news'] = NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:30]
450 news = News.as_view()
453 class Emissions(TemplateView):
454 template_name = 'emissions.html'
456 def get_context_data(self, **kwargs):
457 context = super(Emissions, self).get_context_data(**kwargs)
458 context['sectionName'] = "Emissions"
459 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
460 context['categories'] = Category.objects.all()
463 emissions = Emissions.as_view()
465 class EmissionsArchives(TemplateView):
466 template_name = 'emissions/archives.html'
468 def get_context_data(self, **kwargs):
469 context = super(EmissionsArchives, self).get_context_data(**kwargs)
470 context['sectionName'] = "Emissions"
471 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
472 context['categories'] = Category.objects.all()
474 emissionsArchives = EmissionsArchives.as_view()
477 class Listen(TemplateView):
478 template_name = 'listen.html'
480 def get_context_data(self, **kwargs):
481 context = super(Listen, self).get_context_data(**kwargs)
482 context['sectionName'] = "Listen"
483 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
484 podcastable=True, fragment=False) \
485 .select_related().extra(select={
486 'first_diffusion': 'emissions_diffusion.datetime', },
487 select_params=(False, True),
488 where=['''datetime = (SELECT MIN(datetime)
489 FROM emissions_diffusion
490 WHERE episode_id = emissions_episode.id)'''],
491 tables=['emissions_diffusion'],).order_by('-first_diffusion').distinct() [:10]
493 context['categories'] = Category.objects.all()
497 listen = Listen.as_view()
499 @cache_control(max_age=25)
506 'title': d['episode'].title,
507 'url': d['episode'].get_absolute_url()
509 if d.get('emission'):
511 'title': d['emission'].title,
512 'url': d['emission'].get_absolute_url()
516 'title': d['nonstop'].title,
518 if d.get('current_slot'):
519 del d['current_slot']
523 class NewsItemDetailView(DetailView):
526 newsitem = NewsItemDetailView.as_view()
529 class PodcastsFeed(Feed):
530 title = 'Radio Panik - Podcasts'
532 description_template = 'feed/soundfile.html'
535 return SoundFile.objects.select_related().filter(
536 podcastable=True).order_by('-creation_timestamp')[:5]
538 def item_title(self, item):
540 return '%s - %s' % (item.title, item.episode.title)
541 return item.episode.title
543 def item_link(self, item):
544 return item.episode.get_absolute_url()
546 def item_enclosure_url(self, item):
547 current_site = Site.objects.get(id=settings.SITE_ID)
548 return add_domain(current_site.domain, item.get_format_url('mp3'))
550 def item_enclosure_length(self, item):
551 sound_path = item.get_format_path('mp3')
553 return os.stat(sound_path)[stat.ST_SIZE]
557 def item_enclosure_mime_type(self, item):
560 def item_pubdate(self, item):
561 return item.creation_timestamp
563 podcasts_feed = PodcastsFeed()
566 class FiberPageView(fiber.views.FiberTemplateView):
567 def get_context_data(self, **kwargs):
568 context = super(FiberPageView, self).get_context_data(**kwargs)
569 context['sectionName'] = 'About'
571 fiber_page = FiberPageView.as_view()
574 class RssNewsFeed(Feed):
575 title = 'Radio Panik'
577 description_template = 'feed/newsitem.html'
580 return NewsItem.objects.order_by('-date')[:10]
582 rss_news_feed = RssNewsFeed()
584 class AtomNewsFeed(RssNewsFeed):
585 feed_type = Atom1Feed
587 atom_news_feed = AtomNewsFeed()