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