]> git.0d.be Git - panikweb.git/blob - panikweb/views.py
listen archives page
[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         if episode_ids is not None:
53             for episode_id in episode_ids:
54                 soundfiles[episode_id] = None
55         else:
56             for episode in Episode.objects.filter(emission=emission):
57                 soundfiles[episode.id] = None
58
59         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
60                 fragment=False, episode__emission=emission):
61             soundfiles[soundfile.episode_id] = soundfile
62
63         Episode.set_prefetched_soundfiles(soundfiles)
64
65         #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]
66
67         return context
68
69
70 class EmissionDetailView(DetailView, EmissionMixin):
71     model = Emission
72
73     def get_context_data(self, **kwargs):
74         context = super(EmissionDetailView, self).get_context_data(**kwargs)
75         context['sectionName'] = "Emissions"
76         context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
77         context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
78         context.update(self.get_emission_context(self.object))
79         return context
80 emission = EmissionDetailView.as_view()
81
82 class EpisodeDetailView(DetailView, EmissionMixin):
83     model = Episode
84
85     def get_context_data(self, **kwargs):
86         context = super(EpisodeDetailView, self).get_context_data(**kwargs)
87         context['sectionName'] = "Emissions"
88         context['diffusions'] = Diffusion.objects.select_related().filter(episode=self.object.id)
89         context['soundfiles'] = SoundFile.objects.select_related().filter(episode=self.object.id)
90         context['emission'] = Emission.objects.get(slug=self.kwargs.get('emission_slug'))
91         context.update(self.get_emission_context(context['emission']))
92         return context
93 episode = EpisodeDetailView.as_view()
94
95
96 class EmissionEpisodesDetailView(DetailView, EmissionMixin):
97     model = Emission
98     template_name = 'emissions/episodes.html'
99
100     def get_context_data(self, **kwargs):
101         context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
102         context['sectionName'] = "Emissions"
103         context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
104
105         context['search_query'] = self.request.GET.get('q')
106         if context['search_query']:
107             # query string
108             sqs = SearchQuerySet().filter(django_ct='emissions.episode',
109                     emission_slug_exact=self.object.slug, text=context['search_query'])
110             episode_ids = [x.pk for x in sqs]
111         else:
112             episode_ids = None
113
114         context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
115         return context
116 emissionEpisodes = EmissionEpisodesDetailView.as_view()
117
118 class ProgramView(TemplateView):
119     template_name = 'program.html'
120
121     def get_context_data(self, year=None, week=None, **kwargs):
122         context = super(ProgramView, self).get_context_data(**kwargs)
123         context['sectionName'] = "Emissions"
124
125         context['weekday'] = datetime.today().weekday()
126
127         context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
128         context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
129         context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
130         context['week_last_day'] = context['week_first_day'] + timedelta(days=6)
131
132         previous_week = context['week_first_day'] - timedelta(days=7)
133         context['previous_week_no'] = previous_week.isocalendar()[1]
134         context['previous_week_year'] = previous_week.isocalendar()[0]
135
136         next_week = context['week_first_day'] + timedelta(days=7)
137         context['next_week_no'] = next_week.isocalendar()[1]
138         context['next_week_year'] = next_week.isocalendar()[0]
139
140         return context
141
142 program = ProgramView.as_view()
143
144 class TimeCell:
145     nonstop = None
146     w = 1
147     h = 1
148     time_label = None
149
150     def __init__(self, i, j):
151         self.x = i
152         self.y = j
153         self.schedules = []
154
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,
161                 end_time.hour,
162                 end_time.minute)
163         self.schedules.append(schedule)
164
165     def __unicode__(self):
166         if self.schedules:
167             return ', '.join([x.emission.title for x in self.schedules])
168         else:
169             return self.nonstop
170
171     def __eq__(self, other):
172         return (unicode(self) == unicode(other) and self.time_label == other.time_label)
173
174
175 class Grid(TemplateView):
176     template_name = 'grid.html'
177
178     def get_context_data(self, **kwargs):
179         context = super(Grid, self).get_context_data(**kwargs)
180         context['sectionName'] = "Emissions"
181
182         nb_lines = 2 * 24 # the cells are half hours
183         grid = []
184
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]
188
189         nonstops = []
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])
195             else:
196                 # crossing midnight
197                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
198                                  24,
199                                  nonstop.title, nonstop.slug])
200                 nonstops.append([0,
201                                  nonstop.end.hour + nonstop.end.minute/60.,
202                                  nonstop.title, nonstop.slug])
203         nonstops.sort()
204
205         for i in range(nb_lines):
206             grid.append([])
207             for j in range(7):
208                 grid[-1].append(TimeCell(i, j))
209
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]
214                 if nonstop[1] == 5:
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])
219
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()
225
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)
230
231         # start grid after the night programs
232         grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
233
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:
241                     continue
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:
250                             continue
251                         # here it is, same cell, same emission, several
252                         # schedules
253                         schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
254
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,
261                                 end_time.hour,
262                                 end_time.minute)
263
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)
269
270         # merge adjacent
271
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:
277                     continue
278                 t = 1
279                 try:
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:
283                         cell.w += 1
284                         grid[i][j+t] = None
285                         t += 1
286                 except IndexError:
287                     pass
288
289             # once we're done we remove empty cells
290             grid[i] = [x for x in grid[i] if x is not None]
291
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:
298                     continue
299                 t = 1
300                 try:
301                     while True:
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]
305                         if same_cell_below:
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]
310                             cell.h += 1
311                         else:
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.
315                             #
316                             # For example:
317                             #  - 7am30, seuls contre tout, 1h30
318                             #  - 8am, du pied gauche & la voix de la rue, 1h
319                             # should produce: (this is case A)
320                             #  |      7:30-9:00      |
321                             #  |  seuls contre tout  |
322                             #  |---------------------|
323                             #  |      8:00-9:00      |
324                             #  |   du pied gauche    |
325                             #  |  la voix de la rue  |
326                             #
327                             # On the other hand, if all three emissions started
328                             # at 7am30, we want: (this is case B)
329                             #  |      7:30-9:00      |
330                             #  |  seuls contre tout  |
331                             #  |   du pied gauche    |
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])
337                             cursor = 1
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:
341                                     cursor += 1
342                                     continue
343                                 same_cell_below = same_cell_below[0]
344                                 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
345
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
355                                     # period
356                                     grid[i][j].time_label = same_cell_below.time_label
357                                     # then we sort emissions so the longest are
358                                     # put first
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
362                                     # other schedules
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,
370                                                     end_time.hour,
371                                                     end_time.minute)
372                                     grid[i][j].h += 1
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
378                                             x.emission not in
379                                             current_cell_emissions or
380                                             x.get_duration() < 30]
381                                 cursor += 1
382                             break
383                 except IndexError:
384                     pass
385
386         # cut night at 3am
387         grid = grid[:42]
388         times = times[:42]
389
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']
395
396         return context
397
398 grid = Grid.as_view()
399
400
401 class Home(TemplateView):
402     template_name = 'home.html'
403
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')[:9]
408         context['emissions'] = list(Emission.objects.filter(archived=False).order_by('title'))
409         schedules = Schedule.objects.select_related().order_by('datetime')
410         days = []
411         for day in range(7):
412             days.append({'schedules': [x for x in schedules if x.is_on_weekday(day+1)],
413                          'datetime': datetime(2007, 1, day+1)})
414         context['days'] = days
415
416         context['episodes'] = Episode.objects.prefetch_related('emission__categories').filter(
417                 soundfile__podcastable=True, soundfile__fragment=False) \
418                 .select_related().extra(select={
419                     'first_diffusion': 'emissions_diffusion.datetime', },
420                     select_params=(False, True),
421                     where=['''datetime = (SELECT MIN(datetime)
422                                             FROM emissions_diffusion
423                                         WHERE episode_id = emissions_episode.id)'''],
424                     tables=['emissions_diffusion'],).order_by('-first_diffusion') [:6]
425
426         # get all related soundfiles in a single query
427         soundfiles = {}
428         for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
429                 fragment=False, episode__in=[x.id for x in context['episodes']]):
430             soundfiles[soundfile.episode_id] = soundfile
431
432         # replace dynamic property by a static attribute, to avoid database
433         # lookups
434         for episode in context['episodes']:
435             episode.main_sound = soundfiles.get(episode.id)
436
437         context['newsletter_form'] = SubscribeForm()
438
439         return context
440
441 home = Home.as_view()
442
443 class NewsItemView(DetailView):
444     model = NewsItem
445     def get_context_data(self, **kwargs):
446         context = super(NewsItemView, self).get_context_data(**kwargs)
447         context['sectionName'] = "News"
448         context['focus'] = list(NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
449         context['categories'] = NewsCategory.objects.all()
450         return context
451 newsitemview = NewsItemView.as_view()
452
453 class News(TemplateView):
454     template_name = 'news.html'
455     def get_context_data(self, **kwargs):
456         context = super(News, self).get_context_data(**kwargs)
457         context['sectionName'] = "News"
458         context['focus'] = NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:9]
459         context['news'] = NewsItem.objects.all().exclude(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[3:14]
460         return context
461
462 news = News.as_view()
463
464 class NewsArchives(TemplateView):
465     template_name = 'news/archives.html'
466     def get_context_data(self, **kwargs):
467         context = super(NewsArchives, self).get_context_data(**kwargs)
468         context['sectionName'] = "News"
469         context['search_query'] = self.request.GET.get('q')
470         sqs = SearchQuerySet().filter(django_ct='emissions.newsitem')
471         if context['search_query']:
472             # query string
473             sqs = sqs.filter(text=context['search_query'])
474         else:
475             sqs = sqs.order_by('-date')
476
477         sqs = sqs.load_all()
478
479         context['results'] = sqs
480
481         return context
482
483 newsArchives = NewsArchives.as_view()
484
485 class Emissions(TemplateView):
486     template_name = 'emissions.html'
487
488     def get_context_data(self, **kwargs):
489         context = super(Emissions, self).get_context_data(**kwargs)
490         context['sectionName'] = "Emissions"
491         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
492         context['categories'] = Category.objects.all()
493         return context
494
495 emissions = Emissions.as_view()
496
497 class EmissionsArchives(TemplateView):
498     template_name = 'emissions/archives.html'
499
500     def get_context_data(self, **kwargs):
501         context = super(EmissionsArchives, self).get_context_data(**kwargs)
502         context['sectionName'] = "Emissions"
503         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
504         return context
505 emissionsArchives = EmissionsArchives.as_view()
506
507
508 class Listen(TemplateView):
509     template_name = 'listen.html'
510
511     def get_context_data(self, **kwargs):
512         context = super(Listen, self).get_context_data(**kwargs)
513         context['sectionName'] = "Listen"
514         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
515                 podcastable=True, fragment=False) \
516                 .select_related().extra(select={
517                     'first_diffusion': 'emissions_diffusion.datetime', },
518                     select_params=(False, True),
519                     where=['''datetime = (SELECT MIN(datetime)
520                                             FROM emissions_diffusion
521                                         WHERE episode_id = emissions_episode.id)'''],
522                     tables=['emissions_diffusion'],).order_by('-first_diffusion') [:10]
523
524         context['categories'] = Category.objects.all()
525
526         return context
527
528 listen = Listen.as_view()
529
530 @cache_control(max_age=25)
531 @csrf_exempt
532 @to_json('api')
533 def onair(request):
534     d = whatsonair()
535     if d.get('episode'):
536         d['episode'] = {
537             'title': d['episode'].title,
538             'url': d['episode'].get_absolute_url()
539         }
540     if d.get('emission'):
541         d['emission'] = {
542             'title': d['emission'].title,
543             'url': d['emission'].get_absolute_url()
544         }
545     if d.get('nonstop'):
546         d['nonstop'] = {
547             'title': d['nonstop'].title,
548         }
549     if d.get('current_slot'):
550         del d['current_slot']
551     return d
552
553
554 class NewsItemDetailView(DetailView):
555     model = NewsItem
556
557 newsitem = NewsItemDetailView.as_view()
558
559
560 class PodcastsFeedView(TemplateView):
561     template_name = 'podcasts.html'
562     content_type = 'application/rss+xml'
563
564     def get_context_data(self, **kwargs):
565         context = super(PodcastsFeedView, self).get_context_data(**kwargs)
566         context['base_url'] = self.request.build_absolute_uri('/')[:-1]
567         context['soundfiles'] = SoundFile.objects.select_related().filter(
568                 podcastable=True).order_by('-creation_timestamp')
569         return context
570
571 podcasts_feed = PodcastsFeedView.as_view()
572
573
574 class FiberPageView(fiber.views.FiberTemplateView):
575     def get_context_data(self, **kwargs):
576         context = super(FiberPageView, self).get_context_data(**kwargs)
577         context['sectionName'] = 'About'
578         return context
579 fiber_page = FiberPageView.as_view()