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