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