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
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')
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(emission=self.object).order_by('datetime')
85 context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
86 context.update(self.get_emission_context(self.object))
88 emission = EmissionDetailView.as_view()
90 class EpisodeDetailView(DetailView, EmissionMixin):
93 def get_context_data(self, **kwargs):
94 context = super(EpisodeDetailView, self).get_context_data(**kwargs)
95 context['sectionName'] = "Emissions"
96 context['diffusions'] = Diffusion.objects.select_related().filter(episode=self.object.id)
97 context['soundfiles'] = SoundFile.objects.select_related().filter(episode=self.object.id)
98 context['emission'] = Emission.objects.get(slug=self.kwargs.get('emission_slug'))
99 context.update(self.get_emission_context(context['emission']))
101 episode = EpisodeDetailView.as_view()
104 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
106 template_name = 'emissions/episodes.html'
108 def get_context_data(self, **kwargs):
109 context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
110 context['sectionName'] = "Emissions"
111 context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
113 context['search_query'] = self.request.GET.get('q')
114 if context['search_query']:
116 sqs = SearchQuerySet().models(Episode).filter(
117 emission_slug_exact=self.object.slug, text=context['search_query'])
118 episode_ids = [x.pk for x in sqs]
122 context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
124 emissionEpisodes = EmissionEpisodesDetailView.as_view()
126 class ProgramView(TemplateView):
127 template_name = 'program.html'
129 def get_context_data(self, year=None, week=None, **kwargs):
130 context = super(ProgramView, self).get_context_data(**kwargs)
131 context['sectionName'] = "Emissions"
133 context['weekday'] = datetime.today().weekday()
135 context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
136 context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
137 context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
138 context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
142 program = ProgramView.as_view()
150 def __init__(self, i, j):
155 def add_schedule(self, schedule):
156 end_time = schedule.datetime + timedelta(
157 minutes=schedule.get_duration())
158 self.time_label = '%02d:%02d-%02d:%02d' % (
159 schedule.datetime.hour,
160 schedule.datetime.minute,
163 self.schedules.append(schedule)
165 def __unicode__(self):
167 return ', '.join([x.emission.title for x in self.schedules])
171 def __eq__(self, other):
172 return (unicode(self) == unicode(other) and self.time_label == other.time_label)
175 class Grid(TemplateView):
176 template_name = 'grid.html'
178 def get_context_data(self, **kwargs):
179 context = super(Grid, self).get_context_data(**kwargs)
180 context['sectionName'] = "Emissions"
182 nb_lines = 2 * 24 # the cells are half hours
185 times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
186 # start grid after the night programs
187 times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
190 for nonstop in Nonstop.objects.all():
191 if nonstop.start < nonstop.end:
192 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
193 nonstop.end.hour + nonstop.end.minute/60.,
194 nonstop.title, nonstop.slug])
197 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
199 nonstop.title, nonstop.slug])
201 nonstop.end.hour + nonstop.end.minute/60.,
202 nonstop.title, nonstop.slug])
205 for i in range(nb_lines):
208 grid[-1].append(TimeCell(i, j))
210 nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
211 for time_cell in grid[-1]:
212 time_cell.nonstop = nonstop[2]
213 time_cell.nonstop_slug = nonstop[3]
215 # the one ending at 5am will be cut down, so we inscribe
216 # its duration manually
217 time_cell.time_label = '%02d:00-%02d:00' % (
218 nonstop[0], nonstop[1])
220 for schedule in Schedule.objects.prefetch_related(
221 'emission__categories').select_related().order_by('datetime'):
222 row_start = schedule.datetime.hour * 2 + \
223 int(math.ceil(schedule.datetime.minute / 30))
224 day_no = schedule.get_weekday()
226 for step in range(int(math.ceil(schedule.get_duration() / 30.))):
227 if grid[(row_start+step)%nb_lines][day_no] is None:
228 grid[(row_start+step)%nb_lines][day_no] = TimeCell()
229 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
231 # start grid after the night programs
232 grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
234 # look for the case where the same emission has different schedules for
235 # the same time cell, for example if it lasts one hour the first week,
236 # and two hours the third week.
237 for i in range(nb_lines):
238 grid[i] = [x for x in grid[i] if x is not None]
239 for j, cell in enumerate(grid[i]):
240 if grid[i][j] is None:
242 if len(grid[i][j].schedules) > 1:
243 time_cell_emissions = {}
244 for schedule in grid[i][j].schedules:
245 if not schedule.emission.id in time_cell_emissions:
246 time_cell_emissions[schedule.emission.id] = []
247 time_cell_emissions[schedule.emission.id].append(schedule)
248 for schedule_list in time_cell_emissions.values():
249 if len(schedule_list) == 1:
251 # here it is, same cell, same emission, several
253 schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
255 schedule = schedule_list[0]
256 end_time = schedule.datetime + timedelta(
257 minutes=schedule.get_duration())
258 grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
259 schedule.datetime.hour,
260 schedule.datetime.minute,
264 for schedule in schedule_list[1:]:
265 grid[i][j].schedules.remove(schedule)
266 end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
267 schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
268 end_time.hour, end_time.minute, schedule.weeks_string)
272 # 1st thing is to merge cells on the same line, this will mostly catch
273 # consecutive nonstop cells
274 for i in range(nb_lines):
275 for j, cell in enumerate(grid[i]):
276 if grid[i][j] is None:
280 # if the cells are identical, they are removed from the
281 # grid, and current cell width is increased
282 while grid[i][j+t] == cell:
289 # once we're done we remove empty cells
290 grid[i] = [x for x in grid[i] if x is not None]
292 # 2nd thing is to merge cells vertically, this is emissions that last
293 # for more than 30 minutes
294 for i in range(nb_lines):
295 grid[i] = [x for x in grid[i] if x is not None]
296 for j, cell in enumerate(grid[i]):
297 if grid[i][j] is None:
302 # we look if the next time cell has the same emissions
303 same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
304 if x == cell and x.y == cell.y and x.w == cell.w]
306 # if the cell was identical, we remove it and
307 # increase current cell height
308 bj, same_cell_below = same_cell_below[0]
309 del grid[i+cell.h][bj]
312 # if the cell is different, we have a closer look
313 # to it, so we can remove emissions that will
314 # already be mentioned in the current cell.
317 # - 7am30, seuls contre tout, 1h30
318 # - 8am, du pied gauche & la voix de la rue, 1h
319 # should produce: (this is case A)
321 # | seuls contre tout |
322 # |---------------------|
325 # | la voix de la rue |
327 # On the other hand, if all three emissions started
328 # at 7am30, we want: (this is case B)
330 # | seuls contre tout |
332 # | la voix de la rue |
333 # that is we merge all of them, ignoring the fact
334 # that the other emissions will stop at 8am30
335 current_cell_schedules = set(grid[i][j].schedules)
336 current_cell_emissions = set([x.emission for x in current_cell_schedules])
338 while True and current_cell_schedules:
339 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
340 if not same_cell_below:
343 same_cell_below = same_cell_below[0]
344 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
346 if current_cell_emissions.issubset(same_cell_below_emissions):
347 # this handles case A (see comment above)
348 for schedule in current_cell_schedules:
349 if schedule in same_cell_below.schedules:
350 same_cell_below.schedules.remove(schedule)
351 elif same_cell_below_emissions and \
352 current_cell_emissions.issuperset(same_cell_below_emissions):
353 # this handles case B (see comment above)
354 # we set the cell time label to the longest
356 grid[i][j].time_label = same_cell_below.time_label
357 # then we sort emissions so the longest are
359 grid[i][j].schedules.sort(
360 lambda x, y: -cmp(x.get_duration(), y.get_duration()))
361 # then we add individual time labels to the
363 for schedule in current_cell_schedules:
364 if schedule not in same_cell_below.schedules:
365 end_time = schedule.datetime + timedelta(
366 minutes=schedule.get_duration())
367 schedule.time_label = '%02d:%02d-%02d:%02d' % (
368 schedule.datetime.hour,
369 schedule.datetime.minute,
373 grid[i+cursor].remove(same_cell_below)
374 elif same_cell_below_emissions and \
375 current_cell_emissions.intersection(same_cell_below_emissions):
376 same_cell_below.schedules = [x for x in
377 same_cell_below.schedules if
379 current_cell_emissions or
380 x.get_duration() < 30]
390 context['grid'] = grid
391 context['times'] = times
392 context['categories'] = Category.objects.all()
393 context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
394 'Vendredi', 'Samedi', 'Dimanche']
398 grid = Grid.as_view()
401 class Home(TemplateView):
402 template_name = 'home.html'
404 def get_context_data(self, **kwargs):
405 context = super(Home, self).get_context_data(**kwargs)
406 context['sectionName'] = "Home"
407 context['focus'] = NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:5]
408 context['emissions'] = Emission.objects.filter(archived=False,
409 creation_timestamp__gte=datetime(2013, 9, 13)).order_by('title')
410 schedules = Schedule.objects.select_related().order_by('datetime')
413 days.append({'schedules': [x for x in schedules if x.is_on_weekday(day+1)],
414 'datetime': datetime(2007, 1, day+1)})
415 context['days'] = days
417 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
418 podcastable=True, fragment=False) \
419 .select_related().extra(select={
420 'first_diffusion': 'emissions_diffusion.datetime', },
421 select_params=(False, True),
422 where=['''datetime = (SELECT MIN(datetime)
423 FROM emissions_diffusion
424 WHERE episode_id = emissions_episode.id)'''],
425 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:6]
427 context['newsletter_form'] = SubscribeForm()
431 home = Home.as_view()
433 class NewsItemView(DetailView):
435 def get_context_data(self, **kwargs):
436 context = super(NewsItemView, self).get_context_data(**kwargs)
437 context['sectionName'] = "News"
438 context['focus'] = list(NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
439 context['categories'] = NewsCategory.objects.all()
441 newsitemview = NewsItemView.as_view()
443 class News(TemplateView):
444 template_name = 'news.html'
445 def get_context_data(self, **kwargs):
446 context = super(News, self).get_context_data(**kwargs)
447 context['sectionName'] = "News"
448 context['news'] = NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:14]
451 news = News.as_view()
453 class NewsArchives(TemplateView):
454 template_name = 'news/archives.html'
455 def get_context_data(self, **kwargs):
456 context = super(NewsArchives, self).get_context_data(**kwargs)
457 context['sectionName'] = "News"
458 context['search_query'] = self.request.GET.get('q')
459 sqs = SearchQuerySet().models(NewsItem)
460 if context['search_query']:
462 sqs = sqs.filter(text=context['search_query'])
464 sqs = sqs.order_by('-date')
468 context['results'] = sqs
472 newsArchives = NewsArchives.as_view()
474 class Emissions(TemplateView):
475 template_name = 'emissions.html'
477 def get_context_data(self, **kwargs):
478 context = super(Emissions, self).get_context_data(**kwargs)
479 context['sectionName'] = "Emissions"
480 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
481 context['categories'] = Category.objects.all()
484 emissions = Emissions.as_view()
486 class EmissionsArchives(TemplateView):
487 template_name = 'emissions/archives.html'
489 def get_context_data(self, **kwargs):
490 context = super(EmissionsArchives, self).get_context_data(**kwargs)
491 context['sectionName'] = "Emissions"
492 context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
493 context['categories'] = Category.objects.all()
495 emissionsArchives = EmissionsArchives.as_view()
498 class Listen(TemplateView):
499 template_name = 'listen.html'
501 def get_context_data(self, **kwargs):
502 context = super(Listen, self).get_context_data(**kwargs)
503 context['sectionName'] = "Listen"
504 context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
505 podcastable=True, fragment=False) \
506 .select_related().extra(select={
507 'first_diffusion': 'emissions_diffusion.datetime', },
508 select_params=(False, True),
509 where=['''datetime = (SELECT MIN(datetime)
510 FROM emissions_diffusion
511 WHERE episode_id = emissions_episode.id)'''],
512 tables=['emissions_diffusion'],).order_by('-first_diffusion') [:10]
514 context['categories'] = Category.objects.all()
518 listen = Listen.as_view()
520 @cache_control(max_age=25)
527 'title': d['episode'].title,
528 'url': d['episode'].get_absolute_url()
530 if d.get('emission'):
532 'title': d['emission'].title,
533 'url': d['emission'].get_absolute_url()
537 'title': d['nonstop'].title,
539 if d.get('current_slot'):
540 del d['current_slot']
544 class NewsItemDetailView(DetailView):
547 newsitem = NewsItemDetailView.as_view()
550 class PodcastsFeed(Feed):
551 title = 'Radio Panik - Podcasts'
553 description_template = 'feed/soundfile.html'
556 return SoundFile.objects.select_related().filter(
557 podcastable=True).order_by('-creation_timestamp')[:5]
559 def item_title(self, item):
561 return '%s - %s' % (item.title, item.episode.title)
562 return item.episode.title
564 def item_link(self, item):
565 return item.episode.get_absolute_url()
567 def item_enclosure_url(self, item):
568 current_site = Site.objects.get(id=settings.SITE_ID)
569 return add_domain(current_site.domain, item.get_format_url('mp3'))
571 def item_enclosure_length(self, item):
572 sound_path = item.get_format_path('mp3')
574 return os.stat(sound_path)[stat.ST_SIZE]
578 def item_enclosure_mime_type(self, item):
581 def item_pubdate(self, item):
582 return item.creation_timestamp
584 podcasts_feed = PodcastsFeed()
587 class FiberPageView(fiber.views.FiberTemplateView):
588 def get_context_data(self, **kwargs):
589 context = super(FiberPageView, self).get_context_data(**kwargs)
590 context['sectionName'] = 'About'
592 fiber_page = FiberPageView.as_view()
595 class RssNewsFeed(Feed):
596 title = 'Radio Panik'
598 description_template = 'feed/newsitem.html'
601 return NewsItem.objects.order_by('-date')[:10]
603 rss_news_feed = RssNewsFeed()
605 class AtomNewsFeed(RssNewsFeed):
606 feed_type = Atom1Feed
608 atom_news_feed = AtomNewsFeed()