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