views.py 26.7 KB
Newer Older
Simon Daron's avatar
Simon Daron committed
1
from datetime import datetime, timedelta
Simon Daron's avatar
Simon Daron committed
2
import time
3
import math
Simon Daron's avatar
Simon Daron committed
4

5
from django.views.decorators.cache import cache_control
Simon Daron's avatar
Simon Daron committed
6
7
8
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from django.views.decorators.csrf import csrf_exempt
fred's avatar
fred committed
9
from django.views.generic.dates import _date_from_string
Simon Daron's avatar
Simon Daron committed
10

Simon Daron's avatar
Simon Daron committed
11
12
from django.core.paginator import Paginator

fred's avatar
fred committed
13
import fiber.views
fred's avatar
fred committed
14
from haystack.query import SearchQuerySet
Simon Daron's avatar
Simon Daron committed
15
16
from jsonresponse import to_json

Simon Daron's avatar
Simon Daron committed
17
from emissions.models import Category, Emission, Episode, Diffusion, SoundFile, \
Simon Daron's avatar
Simon Daron committed
18
19
        Schedule, Nonstop, NewsItem, NewsCategory

fred's avatar
fred committed
20
from emissions.utils import whatsonair, period_program
Simon Daron's avatar
Simon Daron committed
21

fred's avatar
fred committed
22
23
from . import utils

Simon Daron's avatar
Simon Daron committed
24

25
class EmissionMixin:
fred's avatar
fred committed
26
    def get_emission_context(self, emission, episode_ids=None):
27
        context = {}
28
29
30

        # get all episodes, with an additional attribute to get the date of
        # their first diffusion
fred's avatar
fred committed
31
32
33
34
35
36
        episodes_queryset = Episode.objects.select_related()
        if episode_ids is not None:
            episodes_queryset = episodes_queryset.filter(id__in=episode_ids)
        else:
            episodes_queryset = episodes_queryset.filter(emission=emission)

37
        context['episodes'] = \
fred's avatar
fred committed
38
                episodes_queryset.extra(select={
39
40
41
42
43
44
45
46
47
48
49
                        'first_diffusion': 'emissions_diffusion.datetime',
                        },
                        select_params=(False, True),
                        where=['''datetime = (SELECT MIN(datetime)
                                                FROM emissions_diffusion
                                               WHERE episode_id = emissions_episode.id)'''],
                        tables=['emissions_diffusion'],
                    ).order_by('-first_diffusion')

        # get all related soundfiles in a single query
        soundfiles = {}
fred's avatar
fred committed
50
        for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
51
                fragment=False, episode__emission=emission):
52
53
54
55
56
57
58
            soundfiles[soundfile.episode_id] = soundfile

        # replace dynamic property by a static attribute, to avoid database
        # lookups
        for episode in context['episodes']:
            episode.main_sound = soundfiles.get(episode.id)

Simon Daron's avatar
Simon Daron committed
59
60
        #context['futurEpisodes'] = context['episodes'].filter(first_diffusion='2013')[0:3]

61
        return context
62
63
64
65
66
67
68
69
70


class EmissionDetailView(DetailView, EmissionMixin):
    model = Emission

    def get_context_data(self, **kwargs):
        context = super(EmissionDetailView, self).get_context_data(**kwargs)
        context['sectionName'] = "Emissions"
        context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
71
        context['news'] = NewsItem.objects.all().filter(emission=self.object.id).order_by('-date')[:3]
72
73
        context.update(self.get_emission_context(self.object))
        return context
74
75
emission = EmissionDetailView.as_view()

76
class EpisodeDetailView(DetailView, EmissionMixin):
77
78
79
80
    model = Episode

    def get_context_data(self, **kwargs):
        context = super(EpisodeDetailView, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
81
        context['sectionName'] = "Emissions"
82
83
        context['diffusions'] = Diffusion.objects.select_related().filter(episode=self.object.id)
        context['soundfiles'] = SoundFile.objects.select_related().filter(episode=self.object.id)
84
        context['emission'] = Emission.objects.get(slug=self.kwargs.get('emission_slug'))
85
        context.update(self.get_emission_context(context['emission']))
86
87
88
        return context
episode = EpisodeDetailView.as_view()

Simon Daron's avatar
Simon Daron committed
89

90
91
92
93
94
95
96
97
class EmissionEpisodesDetailView(DetailView, EmissionMixin):
    model = Emission
    template_name = 'emissions/episodes.html'

    def get_context_data(self, **kwargs):
        context = super(EmissionEpisodesDetailView, self).get_context_data(**kwargs)
        context['sectionName'] = "Emissions"
        context['schedules'] = Schedule.objects.select_related().filter(emission=self.object).order_by('datetime')
fred's avatar
fred committed
98
99
100
101
102
103
104
105
106
107

        context['search_query'] = self.request.GET.get('q')
        if context['search_query']:
            # query string
            sqs = SearchQuerySet().filter(emission_slug_exact=self.object.slug, text=context['search_query'])
            episode_ids = [x.pk for x in sqs]
        else:
            episode_ids = None

        context.update(self.get_emission_context(self.object, episode_ids=episode_ids))
108
109
110
        return context
emissionEpisodes = EmissionEpisodesDetailView.as_view()

Simon Daron's avatar
Simon Daron committed
111
112
113
class ProgramView(TemplateView):
    template_name = 'program.html'

Simon Daron's avatar
Simon Daron committed
114
    def get_context_data(self, year=None, week=None, **kwargs):
Simon Daron's avatar
Simon Daron committed
115
        context = super(ProgramView, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
116
        context['sectionName'] = "Emissions"
fred's avatar
fred committed
117

Simon Daron's avatar
Simon Daron committed
118
        context['weekday'] = datetime.today().weekday()
fred's avatar
fred committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132

        context['week'] = week = int(week) if week is not None else datetime.today().isocalendar()[1]
        context['year'] = year = int(year) if year is not None else datetime.today().isocalendar()[0]
        context['week_first_day'] = utils.tofirstdayinisoweek(year, week)
        context['week_last_day'] = context['week_first_day'] + timedelta(days=6)

        previous_week = context['week_first_day'] - timedelta(days=7)
        context['previous_week_no'] = previous_week.isocalendar()[1]
        context['previous_week_year'] = previous_week.isocalendar()[0]

        next_week = context['week_first_day'] + timedelta(days=7)
        context['next_week_no'] = next_week.isocalendar()[1]
        context['next_week_year'] = next_week.isocalendar()[0]

Simon Daron's avatar
Simon Daron committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        return context

program = ProgramView.as_view()

class TimeCell:
    nonstop = None
    w = 1
    h = 1
    time_label = None

    def __init__(self, i, j):
        self.x = i
        self.y = j
        self.schedules = []

    def add_schedule(self, schedule):
        end_time = schedule.datetime + timedelta(
                minutes=schedule.get_duration())
        self.time_label = '%02d:%02d-%02d:%02d' % (
                schedule.datetime.hour,
                schedule.datetime.minute,
                end_time.hour,
                end_time.minute)
        self.schedules.append(schedule)

    def __unicode__(self):
        if self.schedules:
            return ', '.join([x.emission.title for x in self.schedules])
        else:
            return self.nonstop

    def __eq__(self, other):
        return (unicode(self) == unicode(other) and self.time_label == other.time_label)


class Grid(TemplateView):
    template_name = 'grid.html'

    def get_context_data(self, **kwargs):
        context = super(Grid, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
173
        context['sectionName'] = "Emissions"
Simon Daron's avatar
Simon Daron committed
174
175
176
177
178
179
180
181
182
183
184
185
186

        nb_lines = 2 * 24 # the cells are half hours
        grid = []

        times = ['%02d:%02d' % (x/2, x%2*30) for x in range(nb_lines)]
        # start grid after the night programs
        times = times[2*Schedule.DAY_HOUR_START:] + times[:2*Schedule.DAY_HOUR_START]

        nonstops = []
        for nonstop in Nonstop.objects.all():
            if nonstop.start < nonstop.end:
                nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
                                 nonstop.end.hour + nonstop.end.minute/60.,
fred's avatar
fred committed
187
                                 nonstop.title, nonstop.slug])
Simon Daron's avatar
Simon Daron committed
188
189
190
191
            else:
                # crossing midnight
                nonstops.append([nonstop.start.hour + nonstop.start.minute/60.,
                                 24,
fred's avatar
fred committed
192
                                 nonstop.title, nonstop.slug])
Simon Daron's avatar
Simon Daron committed
193
194
                nonstops.append([0,
                                 nonstop.end.hour + nonstop.end.minute/60.,
fred's avatar
fred committed
195
                                 nonstop.title, nonstop.slug])
Simon Daron's avatar
Simon Daron committed
196
197
198
199
200
201
202
203
204
205
        nonstops.sort()

        for i in range(nb_lines):
            grid.append([])
            for j in range(7):
                grid[-1].append(TimeCell(i, j))

            nonstop = [x for x in nonstops if i>=x[0]*2 and i<x[1]*2][0]
            for time_cell in grid[-1]:
                time_cell.nonstop = nonstop[2]
fred's avatar
fred committed
206
                time_cell.nonstop_slug = nonstop[3]
Simon Daron's avatar
Simon Daron committed
207
208
209
210
211
212
                if nonstop[1] == 5:
                    # the one ending at 5am will be cut down, so we inscribe
                    # its duration manually
                    time_cell.time_label = '%02d:00-%02d:00' % (
                            nonstop[0], nonstop[1])

213
        for schedule in Schedule.objects.select_related().order_by('datetime'):
Simon Daron's avatar
Simon Daron committed
214
215
216
217
218
219
220
221
222
223
224
225
            row_start = schedule.datetime.hour * 2 + \
                    int(math.ceil(schedule.datetime.minute / 30))
            day_no = schedule.get_weekday()

            for step in range(int(math.ceil(schedule.get_duration() / 30.))):
                if grid[(row_start+step)%nb_lines][day_no] is None:
                    grid[(row_start+step)%nb_lines][day_no] = TimeCell()
                grid[(row_start+step)%nb_lines][day_no].add_schedule(schedule)

        # start grid after the night programs
        grid = grid[2*Schedule.DAY_HOUR_START:] + grid[:2*Schedule.DAY_HOUR_START]

226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
        # look for the case where the same emission has different schedules for
        # the same time cell, for example if it lasts one hour the first week,
        # and two hours the third week.
        for i in range(nb_lines):
            grid[i] = [x for x in grid[i] if x is not None]
            for j, cell in enumerate(grid[i]):
                if grid[i][j] is None:
                    continue
                if len(grid[i][j].schedules) > 1:
                    time_cell_emissions = {}
                    for schedule in grid[i][j].schedules:
                        if not schedule.emission.id in time_cell_emissions:
                            time_cell_emissions[schedule.emission.id] = []
                        time_cell_emissions[schedule.emission.id].append(schedule)
                    for schedule_list in time_cell_emissions.values():
                        if len(schedule_list) == 1:
                            continue
                        # here it is, same cell, same emission, several
                        # schedules
245
246
247
248
249
250
251
252
253
254
255
                        schedule_list.sort(lambda x,y: cmp(x.get_duration(), y.get_duration()))

                        schedule = schedule_list[0]
                        end_time = schedule.datetime + timedelta(
                                minutes=schedule.get_duration())
                        grid[i][j].time_label = '%02d:%02d-%02d:%02d' % (
                                schedule.datetime.hour,
                                schedule.datetime.minute,
                                end_time.hour,
                                end_time.minute)

256
257
258
259
260
261
262
                        for schedule in schedule_list[1:]:
                            grid[i][j].schedules.remove(schedule)
                            end_time = schedule.datetime + timedelta(minutes=schedule.get_duration())
                            schedule_list[0].time_label_extra = ', -%02d:%02d %s' % (
                                    end_time.hour, end_time.minute, schedule.weeks_string)

        # merge adjacent
fred's avatar
fred committed
263
264
265

        # 1st thing is to merge cells on the same line, this will mostly catch
        # consecutive nonstop cells
Simon Daron's avatar
Simon Daron committed
266
267
268
269
270
271
        for i in range(nb_lines):
            for j, cell in enumerate(grid[i]):
                if grid[i][j] is None:
                    continue
                t = 1
                try:
fred's avatar
fred committed
272
273
                    # if the cells are identical, they are removed from the
                    # grid, and current cell width is increased
Simon Daron's avatar
Simon Daron committed
274
275
276
277
278
279
                    while grid[i][j+t] == cell:
                        cell.w += 1
                        grid[i][j+t] = None
                        t += 1
                except IndexError:
                    pass
fred's avatar
fred committed
280
281

            # once we're done we remove empty cells
Simon Daron's avatar
Simon Daron committed
282
283
            grid[i] = [x for x in grid[i] if x is not None]

fred's avatar
fred committed
284
285
        # 2nd thing is to merge cells vertically, this is emissions that last
        # for more than 30 minutes
Simon Daron's avatar
Simon Daron committed
286
287
288
289
290
291
292
293
        for i in range(nb_lines):
            grid[i] = [x for x in grid[i] if x is not None]
            for j, cell in enumerate(grid[i]):
                if grid[i][j] is None:
                    continue
                t = 1
                try:
                    while True:
fred's avatar
fred committed
294
                        # we look if the next time cell has the same emissions
Simon Daron's avatar
Simon Daron committed
295
296
                        same_cell_below = [(bj, x) for bj, x in enumerate(grid[i+cell.h])
                                           if x == cell and x.y == cell.y and x.w == cell.w]
fred's avatar
fred committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
                        if same_cell_below:
                            # if the cell was identical, we remove it and
                            # increase current cell height
                            bj, same_cell_below = same_cell_below[0]
                            del grid[i+cell.h][bj]
                            cell.h += 1
                        else:
                            # if the cell is different, we have a closer look
                            # to it, so we can remove emissions that will
                            # already be mentioned in the current cell.
                            #
                            # For example:
                            #  - 7am30, seuls contre tout, 1h30
                            #  - 8am, du pied gauche & la voix de la rue, 1h
                            # should produce: (this is case A)
                            #  |      7:30-9:00      |
                            #  |  seuls contre tout  |
                            #  |---------------------|
                            #  |      8:00-9:00      |
                            #  |   du pied gauche    |
                            #  |  la voix de la rue  |
                            #
                            # On the other hand, if all three emissions started
                            # at 7am30, we want: (this is case B)
                            #  |      7:30-9:00      |
                            #  |  seuls contre tout  |
                            #  |   du pied gauche    |
                            #  |  la voix de la rue  |
                            # that is we merge all of them, ignoring the fact
                            # that the other emissions will stop at 8am30
                            current_cell_schedules = set(grid[i][j].schedules)
328
                            current_cell_emissions = set([x.emission for x in current_cell_schedules])
fred's avatar
fred committed
329
330
331
332
333
334
335
                            cursor = 1
                            while True and current_cell_schedules:
                                same_cell_below = [x for x in grid[i+cursor] if x.y == grid[i][j].y]
                                if not same_cell_below:
                                    cursor += 1
                                    continue
                                same_cell_below = same_cell_below[0]
336
337
338
                                same_cell_below_emissions = set([x.emission for x in same_cell_below.schedules])

                                if current_cell_emissions.issubset(same_cell_below_emissions):
fred's avatar
fred committed
339
340
341
342
                                    # this handles case A (see comment above)
                                    for schedule in current_cell_schedules:
                                        if schedule in same_cell_below.schedules:
                                            same_cell_below.schedules.remove(schedule)
343
344
                                elif same_cell_below_emissions and \
                                        current_cell_emissions.issuperset(same_cell_below_emissions):
fred's avatar
fred committed
345
                                    # this handles case B (see comment above)
346
347
                                    # we set the cell time label to the longest
                                    # period
fred's avatar
fred committed
348
                                    grid[i][j].time_label = same_cell_below.time_label
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
                                    # then we sort emissions so the longest are
                                    # put first
                                    grid[i][j].schedules.sort(
                                            lambda x, y: -cmp(x.get_duration(), y.get_duration()))
                                    # then we add individual time labels to the
                                    # other schedules
                                    for schedule in current_cell_schedules:
                                        if schedule not in same_cell_below.schedules:
                                            end_time = schedule.datetime + timedelta(
                                                    minutes=schedule.get_duration())
                                            schedule.time_label = '%02d:%02d-%02d:%02d' % (
                                                    schedule.datetime.hour,
                                                    schedule.datetime.minute,
                                                    end_time.hour,
                                                    end_time.minute)
fred's avatar
fred committed
364
365
                                    grid[i][j].h += 1
                                    grid[i+cursor].remove(same_cell_below)
366
367
368
369
370
371
372
                                elif same_cell_below_emissions and \
                                        current_cell_emissions.intersection(same_cell_below_emissions):
                                    same_cell_below.schedules = [x for x in
                                            same_cell_below.schedules if
                                            x.emission not in
                                            current_cell_emissions or
                                            x.get_duration() < 30]
fred's avatar
fred committed
373
                                cursor += 1
Simon Daron's avatar
Simon Daron committed
374
375
376
377
378
379
380
381
382
383
                            break
                except IndexError:
                    pass

        # cut night at 3am
        grid = grid[:42]
        times = times[:42]

        context['grid'] = grid
        context['times'] = times
Simon Daron's avatar
Simon Daron committed
384
        context['categories'] = Category.objects.all()
Simon Daron's avatar
Simon Daron committed
385
386
387
388
389
390
391
392
393
394
395
396
397
        context['weekdays'] = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi',
                'Vendredi', 'Samedi', 'Dimanche']

        return context

grid = Grid.as_view()


class Home(TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super(Home, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
398
        context['sectionName'] = "Home"
399
        context['focus'] = list(NewsItem.objects.all().filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:5])
400
        context['emissions'] = list(Emission.objects.filter(archived=False).order_by('title'))
Simon Daron's avatar
Simon Daron committed
401
402
403
404
405
406
        schedules = Schedule.objects.select_related().order_by('datetime')
        days = []
        for day in range(7):
            days.append({'schedules': [x for x in schedules if x.is_on_weekday(day+1)],
                         'datetime': datetime(2007, 1, day+1)})
        context['days'] = days
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

        context['episodes'] = Episode.objects.filter(
                soundfile__podcastable=True, soundfile__fragment=False) \
                .select_related().extra(select={
                    'first_diffusion': 'emissions_diffusion.datetime', },
                    select_params=(False, True),
                    where=['''datetime = (SELECT MIN(datetime)
                                            FROM emissions_diffusion
                                        WHERE episode_id = emissions_episode.id)'''],
                    tables=['emissions_diffusion'],).order_by('-first_diffusion') [:6]

        # get all related soundfiles in a single query
        soundfiles = {}
        for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
                fragment=False, episode__in=[x.id for x in context['episodes']]):
            soundfiles[soundfile.episode_id] = soundfile

        # replace dynamic property by a static attribute, to avoid database
        # lookups
        for episode in context['episodes']:
            episode.main_sound = soundfiles.get(episode.id)

Simon Daron's avatar
Simon Daron committed
429
430
431
432
        return context

home = Home.as_view()

Simon Daron's avatar
Simon Daron committed
433
class NewsItemView(DetailView):
Simon Daron's avatar
Simon Daron committed
434
435
    model = NewsItem
    def get_context_data(self, **kwargs):
Simon Daron's avatar
Simon Daron committed
436
        context = super(NewsItemView, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
437
        context['sectionName'] = "News"
438
        context['focus'] = list(NewsItem.objects.all().filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
Simon Daron's avatar
Simon Daron committed
439
        context['categories'] = NewsCategory.objects.all()
Simon Daron's avatar
Simon Daron committed
440
        return context
Simon Daron's avatar
Simon Daron committed
441
newsitemview = NewsItemView.as_view()
Simon Daron's avatar
Simon Daron committed
442

Simon Daron's avatar
Simon Daron committed
443
444
445
446
class News(TemplateView):
    template_name = 'news.html'
    def get_context_data(self, **kwargs):
        context = super(News, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
447
        context['sectionName'] = "News"
448
        context['focus'] = list(NewsItem.objects.all().filter(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:9])
449
        context['news'] = list(NewsItem.objects.all().exclude(focus=True).exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[3:14])
Simon Daron's avatar
Simon Daron committed
450
        context['categories'] = NewsCategory.objects.all()
Simon Daron's avatar
Simon Daron committed
451
452
453
454
        return context

news = News.as_view()

455
456
457
458
459
class NewsArchives(TemplateView):
    template_name = 'news/archives.html'
    def get_context_data(self, **kwargs):
        context = super(NewsArchives, self).get_context_data(**kwargs)
        context['sectionName'] = "News"
460
461
        context['focus'] = list(NewsItem.objects.all().exclude(image__isnull=True).exclude(image__exact='').order_by('-date')[0:6])
        context['news'] = list(NewsItem.objects.all().order_by('-date')[0:600])
462
463
464
465
466
        context['categories'] = NewsCategory.objects.all()
        return context

newsArchives = NewsArchives.as_view()

Simon Daron's avatar
Simon Daron committed
467
468
469
470
471
class Emissions(TemplateView):
    template_name = 'emissions.html'

    def get_context_data(self, **kwargs):
        context = super(Emissions, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
472
        context['sectionName'] = "Emissions"
473
        context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=False).order_by('title')
Simon Daron's avatar
Simon Daron committed
474
        context['categories'] = Category.objects.all()
Simon Daron's avatar
Simon Daron committed
475
476
477
478
        return context

emissions = Emissions.as_view()

479
class EmissionsArchives(TemplateView):
480
    template_name = 'emissions/archives.html'
481

Simon Daron's avatar
Simon Daron committed
482
    def get_context_data(self, **kwargs):
483
        context = super(EmissionsArchives, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
484
        context['sectionName'] = "Emissions"
fred's avatar
fred committed
485
        context['emissions'] = Emission.objects.prefetch_related('categories').filter(archived=True).order_by('title')
Simon Daron's avatar
Simon Daron committed
486
        return context
487
488
emissionsArchives = EmissionsArchives.as_view()

Simon Daron's avatar
Simon Daron committed
489

Simon Daron's avatar
Simon Daron committed
490
491
492
493
494
495
496
497
498
499
500
501
502
503
class Get(TemplateView):
    template_name = 'get.html'
    def get_context_data(self, **kwargs):
        context = super(Get, self).get_context_data(**kwargs)
        context['emissions'] = Emission.objects.all().order_by('title')
        return context

get = Get.as_view()

class Listen(TemplateView):
    template_name = 'listen.html'

    def get_context_data(self, **kwargs):
        context = super(Listen, self).get_context_data(**kwargs)
Simon Daron's avatar
Simon Daron committed
504
        context['sectionName'] = "Listen"
505
        context['episodes'] = Episode.objects.prefetch_related('emission__categories').filter(
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
                soundfile__podcastable=True, soundfile__fragment=False) \
                .select_related().extra(select={
                    'first_diffusion': 'emissions_diffusion.datetime', },
                    select_params=(False, True),
                    where=['''datetime = (SELECT MIN(datetime)
                                            FROM emissions_diffusion
                                        WHERE episode_id = emissions_episode.id)'''],
                    tables=['emissions_diffusion'],).order_by('-first_diffusion') [:60]

        # get all related soundfiles in a single query
        soundfiles = {}
        for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
                fragment=False, episode__in=[x.id for x in context['episodes']]):
            soundfiles[soundfile.episode_id] = soundfile

        # replace dynamic property by a static attribute, to avoid database
        # lookups
        for episode in context['episodes']:
            episode.main_sound = soundfiles.get(episode.id)
Simon Daron's avatar
Simon Daron committed
525
        context['categories'] = Category.objects.all()
fred's avatar
fred committed
526

Simon Daron's avatar
Simon Daron committed
527
528
529
530
        return context

listen = Listen.as_view()

Simon Daron's avatar
Simon Daron committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
class ListenArchives(TemplateView):
    template_name = 'listen/archives.html'
    def get_context_data(self, **kwargs):

        context = super(ListenArchives, self).get_context_data(**kwargs)
        context['sectionName'] = "Listen"
        context['episodes'] = Episode.objects.filter(
                soundfile__podcastable=True, soundfile__fragment=False) \
                .select_related().extra(select={
                    'first_diffusion': 'emissions_diffusion.datetime', },
                    select_params=(False, True),
                    where=['''datetime = (SELECT MIN(datetime)
                                            FROM emissions_diffusion
                                        WHERE episode_id = emissions_episode.id)'''],
                    tables=['emissions_diffusion'],).order_by('-first_diffusion') [:60]

        # get all related soundfiles in a single query
        soundfiles = {}
        for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
                fragment=False, episode__in=[x.id for x in context['episodes']]):
            soundfiles[soundfile.episode_id] = soundfile

        # replace dynamic property by a static attribute, to avoid database
        # lookups
        for episode in context['episodes']:
            episode.main_sound = soundfiles.get(episode.id)
        context['categories'] = Category.objects.all()

        return context

listenArchives = ListenArchives.as_view()
Simon Daron's avatar
Simon Daron committed
562

563
@cache_control(max_age=25)
Simon Daron's avatar
Simon Daron committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
@csrf_exempt
@to_json('api')
def onair(request):
    d = whatsonair()
    if d.get('episode'):
        d['episode'] = {
            'title': d['episode'].title,
            'url': d['episode'].get_absolute_url()
        }
    if d.get('emission'):
        d['emission'] = {
            'title': d['emission'].title,
            'url': d['emission'].get_absolute_url()
        }
fred's avatar
fred committed
578
579
580
581
582
    if d.get('nonstop'):
        d['nonstop'] = {
            'title': d['nonstop'].title,
        }
    if d.get('current_slot'):
fred's avatar
fred committed
583
        del d['current_slot']
Simon Daron's avatar
Simon Daron committed
584
585
586
587
588
589
590
    return d


class NewsItemDetailView(DetailView):
    model = NewsItem

newsitem = NewsItemDetailView.as_view()
fred's avatar
fred committed
591
592
593
594
595
596
597
598
599
600
601
602
603
604


class PodcastsFeedView(TemplateView):
    template_name = 'podcasts.html'
    content_type = 'application/rss+xml'

    def get_context_data(self, **kwargs):
        context = super(PodcastsFeedView, self).get_context_data(**kwargs)
        context['base_url'] = self.request.build_absolute_uri('/')[:-1]
        context['soundfiles'] = SoundFile.objects.select_related().filter(
                podcastable=True).order_by('-creation_timestamp')
        return context

podcasts_feed = PodcastsFeedView.as_view()
fred's avatar
fred committed
605
606
607
608
609
610
611
612


class FiberPageView(fiber.views.FiberTemplateView):
    def get_context_data(self, **kwargs):
        context = super(FiberPageView, self).get_context_data(**kwargs)
        context['sectionName'] = 'About'
        return context
fiber_page = FiberPageView.as_view()