]> git.0d.be Git - panikweb.git/blob - panikweb/views.py
update focus roll style to match discussions
[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         return context
133
134 program = ProgramView.as_view()
135
136 class TimeCell:
137     nonstop = None
138     w = 1
139     h = 1
140     time_label = None
141
142     def __init__(self, i, j):
143         self.x = i
144         self.y = j
145         self.schedules = []
146
147     def add_schedule(self, schedule):
148         end_time = schedule.datetime + timedelta(
149                 minutes=schedule.get_duration())
150         self.time_label = '%02d:%02d-%02d:%02d' % (
151                 schedule.datetime.hour,
152                 schedule.datetime.minute,
153                 end_time.hour,
154                 end_time.minute)
155         self.schedules.append(schedule)
156
157     def __unicode__(self):
158         if self.schedules:
159             return ', '.join([x.emission.title for x in self.schedules])
160         else:
161             return self.nonstop
162
163     def __eq__(self, other):
164         return (unicode(self) == unicode(other) and self.time_label == other.time_label)
165
166
167 class Grid(TemplateView):
168     template_name = 'grid.html'
169
170     def get_context_data(self, **kwargs):
171         context = super(Grid, self).get_context_data(**kwargs)
172         context['sectionName'] = "Emissions"
173
174         nb_lines = 2 * 24 # the cells are half hours
175         grid = []
176
177         times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
178         # start grid after the night programs
179         times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]
180
181         nonstops = []
182         for nonstop in Nonstop.objects.all():
183             if nonstop.start < nonstop.end:
184                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
185                                  nonstop.end.hour + nonstop.end.minute/60.,
186                                  nonstop.title, nonstop.slug])
187             else:
188                 # crossing midnight
189                 nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
190                                  24,
191                                  nonstop.title, nonstop.slug])
192                 nonstops.append([0,
193                                  nonstop.end.hour + nonstop.end.minute/60.,
194                                  nonstop.title, nonstop.slug])
195         nonstops.sort()
196
197         for i in range(nb_lines):
198             grid.append([])
199             for j in range(7):
200                 grid[-1].append(TimeCell(i, j))
201
202             nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
203             for time_cell in grid[-1]:
204                 time_cell.nonstop = nonstop[2]
205                 time_cell.nonstop_slug = nonstop[3]
206                 if nonstop[1] == 5:
207                     # the one ending at 5am will be cut down, so we inscribe
208                     # its duration manually
209                     time_cell.time_label = '%02d:00-%02d:00' % (
210                             nonstop[0], nonstop[1])
211
212         for schedule in Schedule.objects.prefetch_related(
213                 'emission__categories').select_related().order_by('datetime'):
214             row_start = schedule.datetime.hour * 2 + \
215                     int(math.ceil(schedule.datetime.minute / 30))
216             day_no = schedule.get_weekday()
217
218             for step in range(int(math.ceil(schedule.get_duration() / 30.))):
219                 if grid[(row_start+step)%nb_lines][day_no] is None:
220                     grid[(row_start+step)%nb_lines][day_no] = TimeCell()
221                 grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)
222
223         # start grid after the night programs
224         grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]
225
226         # look for the case where the same emission has different schedules for
227         # the same time cell, for example if it lasts one hour the first week,
228         # and two hours the third week.
229         for i in range(nb_lines):
230             grid[i] = [x for x in grid[i] if x is not None]
231             for j, cell in enumerate(grid[i]):
232                 if grid[i][j] is None:
233                     continue
234                 if len(grid[i][j].schedules) > 1:
235                     time_cell_emissions = {}
236                     for schedule in grid[i][j].schedules:
237                         if not schedule.emission.id in time_cell_emissions:
238                             time_cell_emissions[schedule.emission.id] = []
239                         time_cell_emissions[schedule.emission.id].append(schedule)
240                     for schedule_list in time_cell_emissions.values():
241                         if len(schedule_list) == 1:
242                             continue
243                         # here it is, same cell, same emission, several
244                         # schedules
245                         schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))
246
247                         schedule = schedule_list[0]
248                         end_time = schedule.datetime + timedelta(
249                                 minutes=schedule.get_duration())
250                         grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
251                                 schedule.datetime.hour,
252                                 schedule.datetime.minute,
253                                 end_time.hour,
254                                 end_time.minute)
255
256                         for schedule in schedule_list[1:]:
257                             grid[i][j].schedules.remove(schedule)
258                             end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
259                             schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
260                                     end_time.hour, end_time.minute, schedule.weeks_string)
261
262         # merge adjacent
263
264         # 1st thing is to merge cells on the same line, this will mostly catch
265         # consecutive nonstop cells
266         for i in range(nb_lines):
267             for j, cell in enumerate(grid[i]):
268                 if grid[i][j] is None:
269                     continue
270                 t = 1
271                 try:
272                     # if the cells are identical, they are removed from the
273                     # grid, and current cell width is increased
274                     while grid[i][j+t] == cell:
275                         cell.w += 1
276                         grid[i][j+t] = None
277                         t += 1
278                 except IndexError:
279                     pass
280
281             # once we're done we remove empty cells
282             grid[i] = [x for x in grid[i] if x is not None]
283
284         # 2nd thing is to merge cells vertically, this is emissions that last
285         # for more than 30 minutes
286         for i in range(nb_lines):
287             grid[i] = [x for x in grid[i] if x is not None]
288             for j, cell in enumerate(grid[i]):
289                 if grid[i][j] is None:
290                     continue
291                 t = 1
292                 try:
293                     while True:
294                         # we look if the next time cell has the same emissions
295                         same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
296                                            if x == cell and x.y == cell.y and x.w == cell.w]
297                         if same_cell_below:
298                             # if the cell was identical, we remove it and
299                             # increase current cell height
300                             bj, same_cell_below = same_cell_below[0]
301                             del grid[i+cell.h][bj]
302                             cell.h += 1
303                         else:
304                             # if the cell is different, we have a closer look
305                             # to it, so we can remove emissions that will
306                             # already be mentioned in the current cell.
307                             #
308                             # For example:
309                             #  - 7am30, seuls contre tout, 1h30
310                             #  - 8am, du pied gauche & la voix de la rue, 1h
311                             # should produce: (this is case A)
312                             #  |      7:30-9:00      |
313                             #  |  seuls contre tout  |
314                             #  |---------------------|
315                             #  |      8:00-9:00      |
316                             #  |   du pied gauche    |
317                             #  |  la voix de la rue  |
318                             #
319                             # On the other hand, if all three emissions started
320                             # at 7am30, we want: (this is case B)
321                             #  |      7:30-9:00      |
322                             #  |  seuls contre tout  |
323                             #  |   du pied gauche    |
324                             #  |  la voix de la rue  |
325                             # that is we merge all of them, ignoring the fact
326                             # that the other emissions will stop at 8am30
327                             current_cell_schedules = set(grid[i][j].schedules)
328                             current_cell_emissions = set([x.emission for x in current_cell_schedules])
329                             cursor = 1
330                             while True and current_cell_schedules:
331                                 same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
332                                 if not same_cell_below:
333                                     cursor += 1
334                                     continue
335                                 same_cell_below = same_cell_below[0]
336                                 same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])
337
338                                 if current_cell_emissions.issubset(same_cell_below_emissions):
339                                     # this handles case A (see comment above)
340                                     for schedule in current_cell_schedules:
341                                         if schedule in same_cell_below.schedules:
342                                             same_cell_below.schedules.remove(schedule)
343                                 elif same_cell_below_emissions and \
344                                         current_cell_emissions.issuperset(same_cell_below_emissions):
345                                     # this handles case B (see comment above)
346                                     # we set the cell time label to the longest
347                                     # period
348                                     grid[i][j].time_label = same_cell_below.time_label
349                                     # then we sort emissions so the longest are
350                                     # put first
351                                     grid[i][j].schedules.sort(
352                                             lambda x, y: -cmp(x.get_duration(), y.get_duration()))
353                                     # then we add individual time labels to the
354                                     # other schedules
355                                     for schedule in current_cell_schedules:
356                                         if schedule not in same_cell_below.schedules:
357                                             end_time = schedule.datetime + timedelta(
358                                                     minutes=schedule.get_duration())
359                                             schedule.time_label = '%02d:%02d-%02d:%02d' % (
360                                                     schedule.datetime.hour,
361                                                     schedule.datetime.minute,
362                                                     end_time.hour,
363                                                     end_time.minute)
364                                     grid[i][j].h += 1
365                                     grid[i+cursor].remove(same_cell_below)
366                                 elif same_cell_below_emissions and \
367                                         current_cell_emissions.intersection(same_cell_below_emissions):
368                                     same_cell_below.schedules = [x for x in
369                                             same_cell_below.schedules if
370                                             x.emission not in
371                                             current_cell_emissions or
372                                             x.get_duration() < 30]
373                                 cursor += 1
374                             break
375                 except IndexError:
376                     pass
377
378         # cut night at 3am
379         grid = grid[:42]
380         times = times[:42]
381
382         context['grid'] = grid
383         context['times'] = times
384         context['categories'] = Category.objects.all()
385         context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
386                 'Vendredi', 'Samedi', 'Dimanche']
387
388         return context
389
390 grid = Grid.as_view()
391
392
393 class Home(TemplateView):
394     template_name = 'home.html'
395
396     def get_context_data(self, **kwargs):
397         context = super(Home, self).get_context_data(**kwargs)
398         context['sectionName'] = "Home"
399         context['focus'] = NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:5]
400         context['emissions'] = Emission.objects.filter(archived=False,
401                 creation_timestamp__gte=datetime(2013, 9, 13)).order_by('title')
402         schedules = Schedule.objects.select_related().order_by('datetime')
403         days = []
404         for day in range(7):
405             days.append({'schedules': [x for x in schedules if x.is_on_weekday(day+1)],
406                          'datetime': datetime(2007, 1, day+1)})
407         context['days'] = days
408
409         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
410                 podcastable=True, fragment=False) \
411                 .select_related().extra(select={
412                     'first_diffusion': 'emissions_diffusion.datetime', },
413                     select_params=(False, True),
414                     where=['''datetime = (SELECT MIN(datetime)
415                                             FROM emissions_diffusion
416                                         WHERE episode_id = emissions_episode.id)'''],
417                     tables=['emissions_diffusion'],).order_by('-first_diffusion') [:6]
418
419         context['newsletter_form'] = SubscribeForm()
420
421         return context
422
423 home = Home.as_view()
424
425 class NewsItemView(DetailView):
426     model = NewsItem
427     def get_context_data(self, **kwargs):
428         context = super(NewsItemView, self).get_context_data(**kwargs)
429         context['sectionName'] = "News"
430         context['focus'] = list(NewsItem.objects.select_related('category').filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
431         context['categories'] = NewsCategory.objects.all()
432         return context
433 newsitemview = NewsItemView.as_view()
434
435 class News(TemplateView):
436     template_name = 'news.html'
437     def get_context_data(self, **kwargs):
438         context = super(News, self).get_context_data(**kwargs)
439         context['sectionName'] = "News"
440         context['news'] = NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[:14]
441         return context
442
443 news = News.as_view()
444
445 class NewsArchives(TemplateView):
446     template_name = 'news/archives.html'
447     def get_context_data(self, **kwargs):
448         context = super(NewsArchives, self).get_context_data(**kwargs)
449         context['sectionName'] = "News"
450         context['search_query'] = self.request.GET.get('q')
451         sqs = SearchQuerySet().filter(django_ct='emissions.newsitem')
452         if context['search_query']:
453             # query string
454             sqs = sqs.filter(text=context['search_query'])
455         else:
456             sqs = sqs.order_by('-date')
457
458         sqs = sqs.load_all()
459
460         context['results'] = sqs
461
462         return context
463
464 newsArchives = NewsArchives.as_view()
465
466 class Emissions(TemplateView):
467     template_name = 'emissions.html'
468
469     def get_context_data(self, **kwargs):
470         context = super(Emissions, self).get_context_data(**kwargs)
471         context['sectionName'] = "Emissions"
472         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
473         context['categories'] = Category.objects.all()
474         return context
475
476 emissions = Emissions.as_view()
477
478 class EmissionsArchives(TemplateView):
479     template_name = 'emissions/archives.html'
480
481     def get_context_data(self, **kwargs):
482         context = super(EmissionsArchives, self).get_context_data(**kwargs)
483         context['sectionName'] = "Emissions"
484         context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
485         context['categories'] = Category.objects.all()
486         return context
487 emissionsArchives = EmissionsArchives.as_view()
488
489
490 class Listen(TemplateView):
491     template_name = 'listen.html'
492
493     def get_context_data(self, **kwargs):
494         context = super(Listen, self).get_context_data(**kwargs)
495         context['sectionName'] = "Listen"
496         context['soundfiles'] = SoundFile.objects.prefetch_related('episode__emission__categories').filter(
497                 podcastable=True, fragment=False) \
498                 .select_related().extra(select={
499                     'first_diffusion': 'emissions_diffusion.datetime', },
500                     select_params=(False, True),
501                     where=['''datetime = (SELECT MIN(datetime)
502                                             FROM emissions_diffusion
503                                         WHERE episode_id = emissions_episode.id)'''],
504                     tables=['emissions_diffusion'],).order_by('-first_diffusion') [:10]
505
506         context['categories'] = Category.objects.all()
507
508         return context
509
510 listen = Listen.as_view()
511
512 @cache_control(max_age=25)
513 @csrf_exempt
514 @to_json('api')
515 def onair(request):
516     d = whatsonair()
517     if d.get('episode'):
518         d['episode'] = {
519             'title': d['episode'].title,
520             'url': d['episode'].get_absolute_url()
521         }
522     if d.get('emission'):
523         d['emission'] = {
524             'title': d['emission'].title,
525             'url': d['emission'].get_absolute_url()
526         }
527     if d.get('nonstop'):
528         d['nonstop'] = {
529             'title': d['nonstop'].title,
530         }
531     if d.get('current_slot'):
532         del d['current_slot']
533     return d
534
535
536 class NewsItemDetailView(DetailView):
537     model = NewsItem
538
539 newsitem = NewsItemDetailView.as_view()
540
541
542 class PodcastsFeedView(TemplateView):
543     template_name = 'podcasts.html'
544     content_type = 'application/rss+xml'
545
546     def get_context_data(self, **kwargs):
547         context = super(PodcastsFeedView, self).get_context_data(**kwargs)
548         context['base_url'] = self.request.build_absolute_uri('/')[:-1]
549         context['soundfiles'] = SoundFile.objects.select_related().filter(
550                 podcastable=True).order_by('-creation_timestamp')
551         return context
552
553 podcasts_feed = PodcastsFeedView.as_view()
554
555
556 class FiberPageView(fiber.views.FiberTemplateView):
557     def get_context_data(self, **kwargs):
558         context = super(FiberPageView, self).get_context_data(**kwargs)
559         context['sectionName'] = 'About'
560         return context
561 fiber_page = FiberPageView.as_view()