]> git.0d.be Git - panikweb.git/blob - panikweb/views.py
4b7a0e6f1f0ef73a6c59ba001b81d0c03a5795de
[panikweb.git] / panikweb / views.py
1 from datetime import datetime, timedelta
2 import time
3 import math
4
5 from django.views.decorators.cache import cache_control
6 from django.views.generic.base import TemplateView
7 from django.views.generic.detail import DetailView
8 from django.views.decorators.csrf import csrf_exempt
9 from django.views.generic.dates import _date_from_string
10
11 from django.core.paginator import Paginator
12
13 import fiber.views
14 from haystack.query import SearchQuerySet
15 from jsonresponse import to_json
16
17 from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
18         Schedule, Nonstop, NewsItem, NewsCategory
19
20 from emissions.utils import whatsonair, period_program
21
22 from newsletter.forms import SubscribeForm
23
24 from . import utils
25
26
27 class EmissionMixin:
28     def get_emission_context(self, emission, episode_ids=None):
29         context = {}
30
31         # get all episodes, with an additional attribute to get the date of
32         # their first diffusion
33         episodes_queryset = Episode.objects.select_related()
34         if episode_ids is not None:
35             episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
36         else:
37             episodes_queryset = episodes_queryset.filter(emission=emission)
38
39         context['episodes'] = \
40                 episodes_queryset.extra(select={
41                         'first_diffusion': 'emissions_diffusion.datetime',
42                         },
43                         select_params=(False, True),
44                         where=['''datetime = (SELECT MIN(datetime)
45                                                 FROM emissions_diffusion
46                                                WHERE episode_id = emissions_episode.id)'''],
47                         tables=['emissions_diffusion'],
48                     ).order_by('-first_diffusion')
49
50         # get all related soundfiles in a single query
51         soundfiles = {}
52         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
53                 fragment=False, episode__emission=emission):
54             soundfiles[soundfile.episode_id] = soundfile
55
56         # replace dynamic property by a static attribute, to avoid database
57         # lookups
58         for episode in context['episodes']:
59             episode.main_sound = soundfiles.get(episode.id)
60
61         #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
62
63         return context
64
65
66 class EmissionDetailView(DetailView, EmissionMixin):
67     model = Emission
68
69     def get_context_data(self, **kwargs):
70         context = super(EmissionDetailView, self).get_context_data(**kwargs)
71         context['sectionName'] = "Emissions"
72         context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
73         context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
74         context.update(self.get_emission_context(self.object))
75         return context
76 emission = EmissionDetailView.as_view()
77
78 class EpisodeDetailView(DetailView, EmissionMixin):
79     model = Episode
80
81     def get_context_data(self, **kwargs):
82         context = super(EpisodeDetailView, self).get_context_data(**kwargs)
83         context['sectionName'] = "Emissions"
84         context['diffusions'] = Diffusion.objects.select_related().filter(episode=self.object.id)
85         context['soundfiles'] = SoundFile.objects.select_related().filter(episode=self.object.id)
86         context['emission'] = Emission.objects.get(slug=self.kwargs.get('emission_slug'))
87         context.update(self.get_emission_context(context['emission']))
88         return context
89 episode = EpisodeDetailView.as_view()
90
91
92 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
93     model = Emission
94     template_name = 'emissions/episodes.html'
95
96     def get_context_data(self, **kwargs):
97         context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
98         context['sectionName'] = "Emissions"
99         context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
100
101         context['search_query'] = self.request.GET.get('q')
102         if context['search_query']:
103             # query string
104             sqs = SearchQuerySet().filter(django_ct='emissions.episode',
105                     emission_slug_exact=self.object.slug, text=context['search_query'])
106             episode_ids = [x.pk for x in sqs]
107         else:
108             episode_ids = None
109
110         context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
111         return context
112 emissionEpisodes = EmissionEpisodesDetailView.as_view()
113
114 class ProgramView(TemplateView):
115     template_name = 'program.html'
116
117     def get_context_data(self, year=None, week=None, **kwargs):
118         context = super(ProgramView, self).get_context_data(**kwargs)
119         context['sectionName'] = "Emissions"
120
121         context['weekday'] = datetime.today().weekday()
122
123         context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
124         context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
125         context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
126         context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
127
128         previous_week = context['week_first_day'] - timedelta(days=7)
129         context['previous_week_no'] = previous_week.isocalendar()[1]
130         context['previous_week_year'] = previous_week.isocalendar()[0]
131
132         next_week = context['week_first_day'] + timedelta(days=7)
133         context['next_week_no'] = next_week.isocalendar()[1]
134         context['next_week_year'] = next_week.isocalendar()[0]
135
136         return context
137
138 program = ProgramView.as_view()
139
140 class TimeCell:
141     nonstop = None
142     w = 1
143     h = 1
144     time_label = None
145
146     def __init__(self, i, j):
147         self.x = i
148         self.y = j
149         self.schedules = []
150
151     def add_schedule(self, schedule):
152         end_time = schedule.datetime + timedelta(
153                 minutes=schedule.get_duration())
154         self.time_label = '%02d:%02d-%02d:%02d' % (
155                 schedule.datetime.hour,
156                 schedule.datetime.minute,
157                 end_time.hour,
158                 end_time.minute)
159         self.schedules.append(schedule)
160
161     def __unicode__(self):
162         if self.schedules:
163             return ', '.join([x.emission.title for x in self.schedules])
164         else:
165             return self.nonstop
166
167     def __eq__(self, other):
168         return (unicode(self) == unicode(other) and self.time_label == other.time_label)
169
170
171 class Grid(TemplateView):
172     template_name = 'grid.html'
173
174     def get_context_data(self, **kwargs):
175         context = super(Grid, self).get_context_data(**kwargs)
176         context['sectionName'] = "Emissions"
177
178         nb_lines = 2 * 24 # the cells are half hours
179         grid = []
180
181         times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
182         # start grid after the night programs
183         times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
184
185         nonstops = []
186         for nonstop in Nonstop.objects.all():
187             if nonstop.start < nonstop.end:
188                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
189                                  nonstop.end.hour + nonstop.end.minute/60.,
190                                  nonstop.title, nonstop.slug])
191             else:
192                 # crossing midnight
193                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
194                                  24,
195                                  nonstop.title, nonstop.slug])
196                 nonstops.append([0,
197                                  nonstop.end.hour + nonstop.end.minute/60.,
198                                  nonstop.title, nonstop.slug])
199         nonstops.sort()
200
201         for i in range(nb_lines):
202             grid.append([])
203             for j in range(7):
204                 grid[-1].append(TimeCell(i, j))
205
206             nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
207             for time_cell in grid[-1]:
208                 time_cell.nonstop = nonstop[2]
209                 time_cell.nonstop_slug = nonstop[3]
210                 if nonstop[1] == 5:
211                     # the one ending at 5am will be cut down, so we inscribe
212                     # its duration manually
213                     time_cell.time_label = '%02d:00-%02d:00' % (
214                             nonstop[0], nonstop[1])
215
216         for schedule in Schedule.objects.prefetch_related(
217                 'emission__categories').select_related().order_by('datetime'):
218             row_start = schedule.datetime.hour * 2 + \
219                     int(math.ceil(schedule.datetime.minute / 30))
220             day_no = schedule.get_weekday()
221
222             for step in range(int(math.ceil(schedule.get_duration() / 30.))):
223                 if grid[(row_start+step)%nb_lines][day_no] is None:
224                     grid[(row_start+step)%nb_lines][day_no] = TimeCell()
225                 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
226
227         # start grid after the night programs
228         grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
229
230         # look for the case where the same emission has different schedules for
231         # the same time cell, for example if it lasts one hour the first week,
232         # and two hours the third week.
233         for i in range(nb_lines):
234             grid[i] = [x for x in grid[i] if x is not None]
235             for j, cell in enumerate(grid[i]):
236                 if grid[i][j] is None:
237                     continue
238                 if len(grid[i][j].schedules) > 1:
239                     time_cell_emissions = {}
240                     for schedule in grid[i][j].schedules:
241                         if not schedule.emission.id in time_cell_emissions:
242                             time_cell_emissions[schedule.emission.id] = []
243                         time_cell_emissions[schedule.emission.id].append(schedule)
244                     for schedule_list in time_cell_emissions.values():
245                         if len(schedule_list) == 1:
246                             continue
247                         # here it is, same cell, same emission, several
248                         # schedules
249                         schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
250
251                         schedule = schedule_list[0]
252                         end_time = schedule.datetime + timedelta(
253                                 minutes=schedule.get_duration())
254                         grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
255                                 schedule.datetime.hour,
256                                 schedule.datetime.minute,
257                                 end_time.hour,
258                                 end_time.minute)
259
260                         for schedule in schedule_list[1:]:
261                             grid[i][j].schedules.remove(schedule)
262                             end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
263                             schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
264                                     end_time.hour, end_time.minute, schedule.weeks_string)
265
266         # merge adjacent
267
268         # 1st thing is to merge cells on the same line, this will mostly catch
269         # consecutive nonstop cells
270         for i in range(nb_lines):
271             for j, cell in enumerate(grid[i]):
272                 if grid[i][j] is None:
273                     continue
274                 t = 1
275                 try:
276                     # if the cells are identical, they are removed from the
277                     # grid, and current cell width is increased
278                     while grid[i][j+t] == cell:
279                         cell.w += 1
280                         grid[i][j+t] = None
281                         t += 1
282                 except IndexError:
283                     pass
284
285             # once we're done we remove empty cells
286             grid[i] = [x for x in grid[i] if x is not None]
287
288         # 2nd thing is to merge cells vertically, this is emissions that last
289         # for more than 30 minutes
290         for i in range(nb_lines):
291             grid[i] = [x for x in grid[i] if x is not None]
292             for j, cell in enumerate(grid[i]):
293                 if grid[i][j] is None:
294                     continue
295                 t = 1
296                 try:
297                     while True:
298                         # we look if the next time cell has the same emissions
299                         same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
300                                            if x == cell and x.y == cell.y and x.w == cell.w]
301                         if same_cell_below:
302                             # if the cell was identical, we remove it and
303                             # increase current cell height
304                             bj, same_cell_below = same_cell_below[0]
305                             del grid[i+cell.h][bj]
306                             cell.h += 1
307                         else:
308                             # if the cell is different, we have a closer look
309                             # to it, so we can remove emissions that will
310                             # already be mentioned in the current cell.
311                             #
312                             # For example:
313                             #  - 7am30, seuls contre tout, 1h30
314                             #  - 8am, du pied gauche & la voix de la rue, 1h
315                             # should produce: (this is case A)
316                             #  |      7:30-9:00      |
317                             #  |  seuls contre tout  |
318                             #  |---------------------|
319                             #  |      8:00-9:00      |
320                             #  |   du pied gauche    |
321                             #  |  la voix de la rue  |
322                             #
323                             # On the other hand, if all three emissions started
324                             # at 7am30, we want: (this is case B)
325                             #  |      7:30-9:00      |
326                             #  |  seuls contre tout  |
327                             #  |   du pied gauche    |
328                             #  |  la voix de la rue  |
329                             # that is we merge all of them, ignoring the fact
330                             # that the other emissions will stop at 8am30
331                             current_cell_schedules = set(grid[i][j].schedules)
332                             current_cell_emissions = set([x.emission for x in current_cell_schedules])
333                             cursor = 1
334                             while True and current_cell_schedules:
335                                 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
336                                 if not same_cell_below:
337                                     cursor += 1
338                                     continue
339                                 same_cell_below = same_cell_below[0]
340                                 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
341
342                                 if current_cell_emissions.issubset(same_cell_below_emissions):
343                                     # this handles case A (see comment above)
344                                     for schedule in current_cell_schedules:
345                                         if schedule in same_cell_below.schedules:
346                                             same_cell_below.schedules.remove(schedule)
347                                 elif same_cell_below_emissions and \
348                                         current_cell_emissions.issuperset(same_cell_below_emissions):
349                                     # this handles case B (see comment above)
350                                     # we set the cell time label to the longest
351                                     # period
352                                     grid[i][j].time_label = same_cell_below.time_label
353                                     # then we sort emissions so the longest are
354                                     # put first
355                                     grid[i][j].schedules.sort(
356                                             lambda x, y: -cmp(x.get_duration(), y.get_duration()))
357                                     # then we add individual time labels to the
358                                     # other schedules
359                                     for schedule in current_cell_schedules:
360                                         if schedule not in same_cell_below.schedules:
361                                             end_time = schedule.datetime + timedelta(
362                                                     minutes=schedule.get_duration())
363                                             schedule.time_label = '%02d:%02d-%02d:%02d' % (
364                                                     schedule.datetime.hour,
365                                                     schedule.datetime.minute,
366                                                     end_time.hour,
367                                                     end_time.minute)
368                                     grid[i][j].h += 1
369                                     grid[i+cursor].remove(same_cell_below)
370                                 elif same_cell_below_emissions and \
371                                         current_cell_emissions.intersection(same_cell_below_emissions):
372                                     same_cell_below.schedules = [x for x in
373                                             same_cell_below.schedules if
374                                             x.emission not in
375                                             current_cell_emissions or
376                                             x.get_duration() < 30]
377                                 cursor += 1
378                             break
379                 except IndexError:
380                     pass
381
382         # cut night at 3am
383         grid = grid[:42]
384         times = times[:42]
385
386         context['grid'] = grid
387         context['times'] = times
388         context['categories'] = Category.objects.all()
389         context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
390                 'Vendredi', 'Samedi', 'Dimanche']
391
392         return context
393
394 grid = Grid.as_view()
395
396
397 class Home(TemplateView):
398     template_name = 'home.html'
399
400     def get_context_data(self, **kwargs):
401         context = super(Home, self).get_context_data(**kwargs)
402         context['sectionName'] = "Home"
403         context['focus'] = NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:9]
404         context['emissions'] = list(Emission.objects.filter(archived=False).order_by('title'))
405         schedules = Schedule.objects.select_related().order_by('datetime')
406         days = []
407         for day in range(7):
408             days.append({'schedules': [x for x in schedules if x.is_on_weekday(day+1)],
409                          'datetime': datetime(2007, 1, day+1)})
410         context['days'] = days
411
412         context['episodes'] = Episode.objects.prefetch_related('emission__categories').filter(
413                 soundfile__podcastable=True, soundfile__fragment=False) \
414                 .select_related().extra(select={
415                     'first_diffusion': 'emissions_diffusion.datetime', },
416                     select_params=(False, True),
417                     where=['''datetime = (SELECT MIN(datetime)
418                                             FROM emissions_diffusion
419                                         WHERE episode_id = emissions_episode.id)'''],
420                     tables=['emissions_diffusion'],).order_by('-first_diffusion') [:6]
421
422         # get all related soundfiles in a single query
423         soundfiles = {}
424         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
425                 fragment=False, episode__in=[x.id for x in context['episodes']]):
426             soundfiles[soundfile.episode_id] = soundfile
427
428         # replace dynamic property by a static attribute, to avoid database
429         # lookups
430         for episode in context['episodes']:
431             episode.main_sound = soundfiles.get(episode.id)
432
433         context['newsletter_form'] = SubscribeForm()
434
435         return context
436
437 home = Home.as_view()
438
439 class NewsItemView(DetailView):
440     model = NewsItem
441     def get_context_data(self, **kwargs):
442         context = super(NewsItemView, self).get_context_data(**kwargs)
443         context['sectionName'] = "News"
444         context['focus'] = list(NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
445         context['categories'] = NewsCategory.objects.all()
446         return context
447 newsitemview = NewsItemView.as_view()
448
449 class News(TemplateView):
450     template_name = 'news.html'
451     def get_context_data(self, **kwargs):
452         context = super(News, self).get_context_data(**kwargs)
453         context['sectionName'] = "News"
454         context['focus'] = NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:9]
455         context['news'] = NewsItem.objects.all().exclude(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[3:14]
456         return context
457
458 news = News.as_view()
459
460 class NewsArchives(TemplateView):
461     template_name = 'news/archives.html'
462     def get_context_data(self, **kwargs):
463         context = super(NewsArchives, self).get_context_data(**kwargs)
464         context['sectionName'] = "News"
465         context['search_query'] = self.request.GET.get('q')
466         sqs = SearchQuerySet().filter(django_ct='emissions.newsitem')
467         if context['search_query']:
468             # query string
469             sqs = sqs.filter(text=context['search_query'])
470         else:
471             sqs = sqs.order_by('-date')
472
473         sqs = sqs.load_all()
474
475         context['results'] = sqs
476
477         return context
478
479 newsArchives = NewsArchives.as_view()
480
481 class Emissions(TemplateView):
482     template_name = 'emissions.html'
483
484     def get_context_data(self, **kwargs):
485         context = super(Emissions, self).get_context_data(**kwargs)
486         context['sectionName'] = "Emissions"
487         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
488         context['categories'] = Category.objects.all()
489         return context
490
491 emissions = Emissions.as_view()
492
493 class EmissionsArchives(TemplateView):
494     template_name = 'emissions/archives.html'
495
496     def get_context_data(self, **kwargs):
497         context = super(EmissionsArchives, self).get_context_data(**kwargs)
498         context['sectionName'] = "Emissions"
499         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
500         return context
501 emissionsArchives = EmissionsArchives.as_view()
502
503
504 class Get(TemplateView):
505     template_name = 'get.html'
506     def get_context_data(self, **kwargs):
507         context = super(Get, self).get_context_data(**kwargs)
508         context['emissions'] = Emission.objects.all().order_by('title')
509         return context
510
511 get = Get.as_view()
512
513 class Listen(TemplateView):
514     template_name = 'listen.html'
515
516     def get_context_data(self, **kwargs):
517         context = super(Listen, self).get_context_data(**kwargs)
518         context['sectionName'] = "Listen"
519         context['episodes'] = Episode.objects.prefetch_related('emission__categories').filter(
520                 soundfile__podcastable=True, soundfile__fragment=False) \
521                 .select_related().extra(select={
522                     'first_diffusion': 'emissions_diffusion.datetime', },
523                     select_params=(False, True),
524                     where=['''datetime = (SELECT MIN(datetime)
525                                             FROM emissions_diffusion
526                                         WHERE episode_id = emissions_episode.id)'''],
527                     tables=['emissions_diffusion'],).order_by('-first_diffusion') [:60]
528
529         # get all related soundfiles in a single query
530         soundfiles = {}
531         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
532                 fragment=False, episode__in=[x.id for x in context['episodes']]):
533             soundfiles[soundfile.episode_id] = soundfile
534
535         # replace dynamic property by a static attribute, to avoid database
536         # lookups
537         for episode in context['episodes']:
538             episode.main_sound = soundfiles.get(episode.id)
539         context['categories'] = Category.objects.all()
540
541         return context
542
543 listen = Listen.as_view()
544
545 class ListenArchives(TemplateView):
546     template_name = 'listen/archives.html'
547     def get_context_data(self, **kwargs):
548
549         context = super(ListenArchives, self).get_context_data(**kwargs)
550         context['sectionName'] = "Listen"
551         context['episodes'] = Episode.objects.filter(
552                 soundfile__podcastable=True, soundfile__fragment=False) \
553                 .select_related().extra(select={
554                     'first_diffusion': 'emissions_diffusion.datetime', },
555                     select_params=(False, True),
556                     where=['''datetime = (SELECT MIN(datetime)
557                                             FROM emissions_diffusion
558                                         WHERE episode_id = emissions_episode.id)'''],
559                     tables=['emissions_diffusion'],).order_by('-first_diffusion') [:60]
560
561         # get all related soundfiles in a single query
562         soundfiles = {}
563         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
564                 fragment=False, episode__in=[x.id for x in context['episodes']]):
565             soundfiles[soundfile.episode_id] = soundfile
566
567         # replace dynamic property by a static attribute, to avoid database
568         # lookups
569         for episode in context['episodes']:
570             episode.main_sound = soundfiles.get(episode.id)
571         context['categories'] = Category.objects.all()
572
573         return context
574
575 listenArchives = ListenArchives.as_view()
576
577 @cache_control(max_age=25)
578 @csrf_exempt
579 @to_json('api')
580 def onair(request):
581     d = whatsonair()
582     if d.get('episode'):
583         d['episode'] = {
584             'title': d['episode'].title,
585             'url': d['episode'].get_absolute_url()
586         }
587     if d.get('emission'):
588         d['emission'] = {
589             'title': d['emission'].title,
590             'url': d['emission'].get_absolute_url()
591         }
592     if d.get('nonstop'):
593         d['nonstop'] = {
594             'title': d['nonstop'].title,
595         }
596     if d.get('current_slot'):
597         del d['current_slot']
598     return d
599
600
601 class NewsItemDetailView(DetailView):
602     model = NewsItem
603
604 newsitem = NewsItemDetailView.as_view()
605
606
607 class PodcastsFeedView(TemplateView):
608     template_name = 'podcasts.html'
609     content_type = 'application/rss+xml'
610
611     def get_context_data(self, **kwargs):
612         context = super(PodcastsFeedView, self).get_context_data(**kwargs)
613         context['base_url'] = self.request.build_absolute_uri('/')[:-1]
614         context['soundfiles'] = SoundFile.objects.select_related().filter(
615                 podcastable=True).order_by('-creation_timestamp')
616         return context
617
618 podcasts_feed = PodcastsFeedView.as_view()
619
620
621 class FiberPageView(fiber.views.FiberTemplateView):
622     def get_context_data(self, **kwargs):
623         context = super(FiberPageView, self).get_context_data(**kwargs)
624         context['sectionName'] = 'About'
625         return context
626 fiber_page = FiberPageView.as_view()