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